-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
49 lines (42 loc) · 1.55 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
/**
* The remark plugin for supporting custom id and default id
* @author imcuttle
*/
const visit = require('unist-util-visit')
const { setNodeId, getDefaultId } = require('./util')
module.exports = function(options = { defaults: false, uniqueDefaults: true }) {
return function(node) {
const uniqueDefaultIdsCounters = {}
visit(node, '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);
}
})
}
}