summaryrefslogtreecommitdiff
path: root/src/compiler/markdown/micromark-collect-headers.ts
blob: 69781231a99dfdf7ec040ee1b386fe9b09093203 (plain) (blame)
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
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,
  };
}