-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
46 lines (37 loc) · 1009 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
35
36
37
38
39
40
41
42
43
44
45
46
import { findAfter } from 'unist-util-find-after';
import { visit } from 'unist-util-visit';
const MAX_HEADING_DEPTH = 6
function plugin () {
return transform
}
function transform (tree) {
for (let depth = MAX_HEADING_DEPTH; depth > 0; depth--) {
visit(
tree,
node => node.type === 'heading' && node.depth === depth,
sectionize
)
}
}
function sectionize (node, index, parent) {
const start = node
const startIndex = index
const depth = start.depth
const isEnd = node => node.type === 'heading' && node.depth <= depth || node.type === 'export'
const end = findAfter(parent, start, isEnd)
const endIndex = parent.children.indexOf(end)
const between = parent.children.slice(
startIndex,
endIndex > 0 ? endIndex : undefined
)
const section = {
type: 'section',
depth: depth,
children: between,
data: {
hName: 'section'
}
}
parent.children.splice(startIndex, section.children.length, section)
}
export default plugin