summaryrefslogtreecommitdiff
path: root/packages/markdown/remark/src/rehype-collect-headers.ts
blob: 45138f624b977fbe2983e982be3fd00c56f9ca90 (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 { 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?.properties?.id || slugger.slug(text);

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

	return {
		headers,
		rehypeCollectHeaders,
	};
}