-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
89 lines (78 loc) · 2.2 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { toc } from "mdast-util-toc";
import { map } from "unist-util-map";
import pluck from "remark-pluck";
// WHAT THIS DOES:
// make a table of contents.
// map the table of contents replacing
// each of the elements with an MDX alternative
// so they can be replaced in the normal MDX component mapping.
export const remarkMdxToc = (options = {}) => {
const transformToMdx = (node) => {
if (node.type === "list") {
return {
...node,
type: "mdxJsxFlowElement",
name: "TableOfContents.List",
};
}
if (node.type === "listItem") {
return {
...node,
type: "mdxJsxFlowElement",
name: "TableOfContents.Item",
};
}
if (node.type === "link") {
return {
...node,
type: "mdxJsxFlowElement",
name: "TableOfContents.Link",
attributes: [
{
type: "mdxJsxAttribute",
name: "href",
value: node.url,
},
],
};
}
return node;
};
return (tree) => {
const table = toc(tree, options).map;
const mdxTable = {
type: "mdxJsxFlowElement",
name: "TableOfContents.Container",
attributes: [
{
type: "mdxJsxAttribute",
name: "className",
value: "remark-plugin page-outline",
},
],
children: table ? [map(table, transformToMdx)] : [],
};
const content = {
type: "mdxJsxFlowElement",
name: "div",
attributes: [
{
type: "mdxJsxAttribute",
name: "className",
value: "remark-plugin page-content",
},
],
children: tree.children,
};
// // I have no need for the p tags.
// // this was crucial in understanding this part https://unifiedjs.com/learn/recipe/remove-node/
// // I should turn this into a util find-and-pluck or something to remove a node but keep the children.
// visit(mdxTable, { type: "paragraph" }, (node, index, ancestor) => {
// ancestor.children.splice(index, 1, ...node.children);
// return [SKIP, index];
// });
pluck(mdxTable, { type: "paragraph" });
tree.children = [mdxTable, content];
};
};
export default remarkMdxToc;