diff options
Diffstat (limited to 'src/compiler/markdown/micromark-collect-headers.ts')
-rw-r--r-- | src/compiler/markdown/micromark-collect-headers.ts | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/src/compiler/markdown/micromark-collect-headers.ts b/src/compiler/markdown/micromark-collect-headers.ts new file mode 100644 index 000000000..69781231a --- /dev/null +++ b/src/compiler/markdown/micromark-collect-headers.ts @@ -0,0 +1,38 @@ +import slugger from 'github-slugger'; + +/** + * Create Markdown Headers Collector + * 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, + }; +} |