generated from markedjs/marked-extension-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
59 lines (53 loc) · 1.6 KB
/
index.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
import GithubSlugger from 'github-slugger';
let slugger = new GithubSlugger();
let headings = [];
// unescape from marked helpers
const unescapeTest = /&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;
/* istanbul ignore next */
export function unescape(html) {
// explicitly match decimal, hex, and named HTML entities
return html.replace(unescapeTest, (_, n) => {
n = n.toLowerCase();
if (n === 'colon') return ':';
if (n.charAt(0) === '#') {
return n.charAt(1) === 'x'
? String.fromCharCode(parseInt(n.substring(2), 16))
: String.fromCharCode(+n.substring(1));
}
return '';
});
}
export function gfmHeadingId({ prefix = '', globalSlugs = false } = {}) {
return {
headerIds: false, // prevent deprecation warning; remove this once headerIds option is removed
hooks: {
preprocess(src) {
if (!globalSlugs) {
resetHeadings();
}
return src;
},
},
useNewRenderer: true,
renderer: {
heading({ tokens, depth }) {
const text = this.parser.parseInline(tokens);
const raw = unescape(this.parser.parseInline(tokens, this.parser.textRenderer))
.trim()
.replace(/<[!\/a-z].*?>/gi, '');
const level = depth;
const id = `${prefix}${slugger.slug(raw.toLowerCase())}`;
const heading = { level, text, id, raw };
headings.push(heading);
return `<h${level} id="${id}">${text}</h${level}>\n`;
},
},
};
}
export function getHeadingList() {
return headings;
}
export function resetHeadings() {
headings = [];
slugger = new GithubSlugger();
}