stacker.news/lib/toc.js
Edward Kung 4998041d73
Automatically generate table of contents in text (#2213)
* automatic toc generation in markdown

* don't open hash links in new tab

* only process toc for top level items

---------

Co-authored-by: ekzyis <ek@stacker.news>
2025-08-26 09:42:01 -05:00

24 lines
579 B
JavaScript

import { fromMarkdown } from 'mdast-util-from-markdown'
import { visit } from 'unist-util-visit'
import { toString } from 'mdast-util-to-string'
import { slug } from 'github-slugger'
export function extractHeadings (markdownOrTree) {
const tree = typeof markdownOrTree === 'string'
? fromMarkdown(markdownOrTree)
: markdownOrTree
const headings = []
visit(tree, 'heading', node => {
const str = toString(node)
headings.push({
heading: str,
slug: slug(str.replace(/[^\w\-\s]+/gi, '')),
depth: node.depth
})
})
return headings
}