summaryrefslogtreecommitdiff
path: root/packages/markdown-support/src/rehype-collect-headers.ts
blob: 78774e494aa764ec9106b7e41af5b4175aed7208 (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
import { visit } from 'unist-util-visit';
import slugger from 'github-slugger';

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

  const visitor = (node: any) => {
    if (node.type !== 'element') return;
    const { tagName, children } = node;
    if (tagName[0] !== 'h') return;
    let [_, depth] = tagName.match(/h([0-6])/) ?? [];
    if (!depth) return;
    depth = Number.parseInt(depth);

    let text = '';

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

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

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

    return node;
  };

  return { headers, rehypeCollectHeaders: () => (tree: any) => visit(tree, visitor) };
}