summaryrefslogtreecommitdiff
path: root/packages/markdown-support/src/rehype-collect-headers.ts
blob: 211b7177c4ed6304846e35326f2bfa53ac4b221d (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
39
import { visit } from 'unist-util-visit';
import type { Root, Properties } from 'hast';
import slugger from 'github-slugger';

/**  */
export default function createCollectHeaders() {
  const headers: any[] = [];

  function rehypeCollectHeaders() {
    return function (tree: Root) {
      visit(tree, (node) => {
        if (node.type !== 'element') return;
        const { tagName } = node;
        if (tagName[0] !== 'h') return;
        const [_, level] = tagName.match(/h([0-6])/) ?? [];
        if (!level) return;
        const depth = Number.parseInt(level);

        let text = '';

        visit(node, 'text', (child) => {
          text += child.value;
        });

        let slug = node?.data?.id || slugger.slug(text);

        node.data = node.data || {};
        node.data.properties = node.data.properties || {};
        node.data.properties = { ...(node.data.properties as Properties), slug };
        headers.push({ depth, slug, text });
      });
    };
  }

  return {
    headers,
    rehypeCollectHeaders,
  };
}