diff options
Diffstat (limited to 'packages/markdown-support/src/rehype-collect-headers.ts')
-rw-r--r-- | packages/markdown-support/src/rehype-collect-headers.ts | 30 |
1 files changed, 30 insertions, 0 deletions
diff --git a/packages/markdown-support/src/rehype-collect-headers.ts b/packages/markdown-support/src/rehype-collect-headers.ts new file mode 100644 index 000000000..edfcd29bc --- /dev/null +++ b/packages/markdown-support/src/rehype-collect-headers.ts @@ -0,0 +1,30 @@ +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.value; + }); + + let slug = 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) }; +} |