-
-
Notifications
You must be signed in to change notification settings - Fork 307
/
Copy pathremark-table-of-contents.js
65 lines (51 loc) · 1.73 KB
/
remark-table-of-contents.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { visit } from "unist-util-visit";
import { list, listItem } from "mdast-builder";
import { toString as nodeToString } from "mdast-util-to-string";
const defaultOptions = {
heading: "Table of Contents",
startDepth: 1,
skip: []
};
const remarkTableOfContents = (options) => (tree, file) => {
options = { ...defaultOptions, ...options };
options.skip.push(options.heading);
options.skip = new RegExp(`^(${options.skip.join("|")})$`, "u");
let insertTableOfContents;
const tableOfContents = list("unordered");
let currentList = tableOfContents;
const listStack = [currentList];
let currentDepth = options.startDepth;
visit(tree, "heading", (headingNode, index, parent) => {
const headingText = nodeToString(headingNode);
if (headingText === options.heading) {
insertTableOfContents = () => {
parent.children.splice(index + 1, 0, tableOfContents);
};
}
if (headingNode.depth < options.startDepth) {
return;
}
while (headingNode.depth > currentDepth) {
const newList = list("unordered");
listStack.push(newList);
currentList.children.push(newList);
currentList = newList;
currentDepth++;
}
while (headingNode.depth < currentDepth) {
listStack.pop();
currentList = listStack[listStack.length - 1];
currentDepth--;
}
if (options.skip.test(headingText)) {
return;
}
currentList.children.push(listItem(headingNode.children));
});
if (insertTableOfContents) {
insertTableOfContents();
} else {
file.message(`Table of Contents not added. Add a heading with the text "${options.heading}" or set the 'heading' option to use a different heading.`);
}
};
export default remarkTableOfContents;