forked from toml-lang/toml.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformatter.js
75 lines (59 loc) · 2.03 KB
/
formatter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// * Adds HTML attributes to header tags
// * Adds HTML attributes to <code> tags
// * Auto-links any URLs that aren't already linked in Markdown
const striptags = require("striptags");
const Entities = require("html-entities").XmlEntities;
const entities = new Entities();
const TABLE_OF_CONTENTS_POSITION = 2;
module.exports = class Formatter {
static textFromHeader(text) {
const html = entities.decode(text);
const headerText = striptags(html);
return headerText;
}
static format(text, { locale, version }) {
return this.addTextLink(this.style(this.anchor(this.stripTableOfContents(text))), locale, version);
}
static stripTableOfContents(text) {
let headerCount = 0,
removed = false,
removing = false,
output = [];
text.split("\n").forEach(line => {
if (removed) return output.push(line);
if (line.match(/<h2/)) {
headerCount++;
}
if (headerCount === TABLE_OF_CONTENTS_POSITION) {
removing = true;
} else if (headerCount > TABLE_OF_CONTENTS_POSITION) {
removing = false;
removed = true;
}
if (removing) {
return;
} else {
output.push(line);
}
});
return output.join("\n");
}
static anchor(text) {
return text.replace(/<h2.*?id="(.*?)".*?>(.*?)<\/h2>/g,(_, $1, $2) => {
const headerText = this.textFromHeader($2);
return `<h2 id="${$1}" data-target="nav.header">
<a href="#${$1}">${headerText}</a>
</h2>`;
});
}
static style(text) {
return this.styleCode(text);
}
static styleCode(text) {
let output = text.replace(/<pre><code>/g, `<pre><code class="language-toml">`);
return output.replace(/<pre><code /g, `<pre><code data-controller="snippet" `);
}
static addTextLink(html, locale, version) {
return html.replace(/<h1/, `<a class="block text-left md:text-right mt-16 md:mt-0" href="https://raw.githubusercontent.com/toml-lang/toml.io/main/specs/${locale}/${version}.md" class="text-link text-sm">Text Version</a>\n<h1`)
}
};