-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
123 lines (97 loc) · 2.46 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
const toString = require("mdast-util-to-string");
const visit = require("unist-util-visit");
function renderTabs(tabs, nodes) {
let tabNodes = [];
tabNodes.push({
type: "jsx",
value: `<Tabs>`,
});
tabs.forEach((tab, id) => {
const node = nodes[tab.start];
const label = toString(node);
tabNodes.push({
type: "jsx",
value: `<TabItem label="${label}" value="tab${id + 1}">`,
});
tabNodes.push(...nodes.slice(tab.start + 1, tab.end));
tabNodes.push({
type: "jsx",
value: `</TabItem>`,
});
});
tabNodes.push({
type: "jsx",
value: `</Tabs>`,
});
return tabNodes;
}
function findTabs(node, index, parent) {
const tabs = [];
let depth = null;
let tab;
const { children } = parent;
while (++index < children.length) {
const child = children[index];
if (child.type === "heading") {
if (depth == null) {
depth = child.depth;
}
if (child.depth < depth) {
tab.end = index;
break;
}
if (child.depth === depth) {
if (tab) {
tab.end = index;
}
tab = {};
tab.start = index;
tab.end = children.length;
tabs.push(tab);
}
}
if (child.type === "comment" && child.value.trim() === "/tabs") {
if (tab) {
tab.end = index;
}
break;
}
}
return tabs;
}
function tabs() {
return (root) => {
let foundTabs = false;
let alreadyImported = false;
visit(root, (node, index, parent) => {
if (node.type === "import") {
if (node.value.includes("@theme/Tabs")) {
alreadyImported = true;
}
} else if (node.type === "comment") {
if (node.value.trim() === "tabs") {
const tabs = findTabs(node, index, parent);
if (tabs.length > 0) {
const start = tabs[0].start;
const end = tabs[tabs.length - 1].end;
foundTabs = true;
const newChildren = renderTabs(tabs, parent.children);
parent.children.splice(start, end - start, ...newChildren);
return index + newChildren.length;
}
}
}
});
if (foundTabs && !alreadyImported) {
root.children.unshift({
type: "import",
value: "import TabItem from '@theme/TabItem';",
});
root.children.unshift({
type: "import",
value: "import Tabs from '@theme/Tabs';",
});
}
};
}
module.exports = tabs;