* 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>
24 lines
579 B
JavaScript
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
|
|
}
|