-
Notifications
You must be signed in to change notification settings - Fork 0
/
remark-plugins.mjs
52 lines (45 loc) · 1.39 KB
/
remark-plugins.mjs
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
51
52
import { findAfter } from "unist-util-find-after";
import { visit } from "unist-util-visit";
export function remarkSectionize() {
return (tree) => {
const MAX_HEADING_DEPTH = 6;
for (let depth = MAX_HEADING_DEPTH; depth > 0; depth--) {
visit(
tree,
(node) => node.type === "heading" && node.depth === depth,
(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 textNode = node.children.at(-1);
const text = textNode.value
.trimEnd()
.toLowerCase()
.split(" ")
.join("-");
const section = {
type: "div",
depth: depth,
children: between,
data: {
hName: "div",
hProperties: {
id: text,
},
},
};
parent.children.splice(startIndex, section.children.length, section);
}
);
}
};
}