forked from imcuttle/remark-heading-id
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (43 loc) · 1.58 KB
/
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* The remark plugin for supporting custom id and default id
* @author imcuttle
*/
const visit = require('unist-util-visit')
const { setNodeId, getDefaultId } = require('./lib')
module.exports = { remarkHeadingId }
function remarkHeadingId(options = { defaults: false, uniqueDefaults: true }) {
return function(root) {
const uniqueDefaultIdsCounters = {}
visit(root, 'heading', node => {
let lastChild = node.children[node.children.length - 1]
if (lastChild && lastChild.type === 'text') {
let string = lastChild.value.replace(/ +$/, '')
let matched = string.match(/ \(#([^]+?)\)$/)
if (matched) {
let id = matched[1]
if (!!id.length) {
setNodeId(node, id)
string = string.substring(0, matched.index)
lastChild.value = string
return
}
}
}
if (options.defaults) {
// If no custom id was found, use default instead
let defaultIdCandidate = getDefaultId(node.children)
if (options.uniqueDefaults) {
if (uniqueDefaultIdsCounters[defaultIdCandidate] === undefined) {
// First time this default id is used: initialize counter
uniqueDefaultIdsCounters[defaultIdCandidate] = 0
} else {
// Id already used: increment counter and append it to defaultIdCandidate
uniqueDefaultIdsCounters[defaultIdCandidate]++
defaultIdCandidate += '-' + uniqueDefaultIdsCounters[defaultIdCandidate]
}
}
setNodeId(node, defaultIdCandidate)
}
})
}
}