-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathremarkCodeTabs.js
121 lines (97 loc) · 2.47 KB
/
remarkCodeTabs.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
const remarkCodeTabs = function remarkCodeTabs() {
function renderTabs(tabs, nodes) {
const tabNodes = [];
tabNodes.push({
type: 'jsx',
value: '<Tabs className="code-tabs" defaultIndex={0}>'
});
tabNodes.push({
type: 'jsx',
value: '<TabList className="code-tabs-tabs">'
});
tabs.forEach(tab => {
tabNodes.push({
type: 'jsx',
value: `<Tab className="code-tabs-tab">${nodes[tab.start].children[0].value}</Tab>`
});
});
tabNodes.push({
type: 'jsx',
value: '</TabList>'
});
tabNodes.push({
type: 'jsx',
value: '<TabPanels className="code-tabs-panels">'
});
tabs.forEach(tab => {
tabNodes.push({
type: 'jsx',
value: '<TabPanel className="code-tabs-panel">'
});
tabNodes.push(...nodes.slice(tab.start + 1, tab.end));
tabNodes.push({
type: 'jsx',
value: '</TabPanel>'
});
});
tabNodes.push({
type: 'jsx',
value: '</TabPanels>'
});
tabNodes.push({
type: 'jsx',
value: '</Tabs>'
});
return tabNodes;
}
function findTabs(node, index, parent) {
const tabs = [];
let depth;
let tab;
const { children } = parent;
while(++index < children.length) {
const child = children[index];
if(child.type === 'heading') {
if(depth === null || depth === undefined) {
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') {
tab.end = index;
break;
}
}
return tabs;
}
return tree => {
const { children } = tree;
let index = -1;
while(++index < children.length) {
const child = children[index];
if(child.type === 'comment' && child.value.trim() === 'tabs') {
const tabs = findTabs(child, index, tree);
const { start } = tabs[0];
const { end } = tabs[tabs.length - 1];
if(tabs.length > 0) {
const nodes = renderTabs(tabs, children);
children.splice(start, end - start, ...nodes);
index += nodes.length;
}
}
}
};
};
export default remarkCodeTabs;