diff options
Diffstat (limited to 'packages/markdown-support/src/rehype-collect-headers.ts')
-rw-r--r-- | packages/markdown-support/src/rehype-collect-headers.ts | 53 |
1 files changed, 30 insertions, 23 deletions
diff --git a/packages/markdown-support/src/rehype-collect-headers.ts b/packages/markdown-support/src/rehype-collect-headers.ts index 78774e494..211b7177c 100644 --- a/packages/markdown-support/src/rehype-collect-headers.ts +++ b/packages/markdown-support/src/rehype-collect-headers.ts @@ -1,32 +1,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[] = []; - 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; + 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, }; - - return { headers, rehypeCollectHeaders: () => (tree: any) => visit(tree, visitor) }; } |