-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
34 lines (28 loc) · 808 Bytes
/
index.js
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
/**
* @typedef {import('mdast').Root} Root
* @typedef {import('hast').Properties} Properties
*/
import {toString} from 'mdast-util-to-string'
import {visit} from 'unist-util-visit'
import BananaSlug from 'github-slugger'
const slugs = new BananaSlug()
/**
* Plugin to add anchors headings using GitHub’s algorithm.
*
* @type {import('unified').Plugin<void[], Root>}
*/
export default function remarkSlug() {
return (tree) => {
slugs.reset()
visit(tree, 'heading', (node) => {
const data = node.data || (node.data = {})
const props = /** @type {Properties} */ (
data.hProperties || (data.hProperties = {})
)
let id = props.id
id = id ? slugs.slug(String(id), true) : slugs.slug(toString(node))
data.id = id
props.id = id
})
}
}