-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
micromark-collect-headers.ts
35 lines (34 loc) · 1.06 KB
/
micromark-collect-headers.ts
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
import slugger from 'github-slugger';
// NOTE: micromark has terrible TS types. Instead of fighting with the
// limited/broken TS types that they ship, we just reach for our good friend, "any".
export function createMarkdownHeadersCollector() {
const headers: any[] = [];
let currentHeader: any;
return {
headers,
headersExtension: {
enter: {
atxHeading(node: any) {
currentHeader = {};
headers.push(currentHeader);
this.buffer();
},
atxHeadingSequence(node: any) {
currentHeader.depth = this.sliceSerialize(node).length;
},
atxHeadingText(node: any) {
currentHeader.text = this.sliceSerialize(node);
},
} as any,
exit: {
atxHeading(node: any) {
currentHeader.slug = slugger.slug(currentHeader.text);
this.resume();
this.tag(`<h${currentHeader.depth} id="${currentHeader.slug}">`);
this.raw(currentHeader.text);
this.tag(`</h${currentHeader.depth}>`);
},
} as any,
} as any,
};
}