-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoc.js
More file actions
119 lines (97 loc) · 2.55 KB
/
toc.js
File metadata and controls
119 lines (97 loc) · 2.55 KB
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
function makeTOC() {
let prev_level = 1;
let root = {
href: null,
parent: null,
children: []
};
let parent = root;
let last = null;
// Источник вдохновения:
// https://github.com/isaacs/github/issues/215#issuecomment-456598835
// Оттуда, в частности, взят querySelectorAll.
document
.querySelectorAll('h1 > a, h2 > a, h3 > a, h4 > a, h5 > a')
.forEach((a) =>
{
const h = a.parentNode.tagName;
const target = a.hash;
const text = a.parentNode.innerHTML.toString().trim()
.replace(/<a [^>]*>/g, "")
.replace(/<\/a>/g, "");
const level = 1 * h.substr(1);
const href = `<a href="${target}">${text}</a>`;
if (! target) {
return;
}
while (level > prev_level) {
if (! last) {
last = {
href: parent.href,
parent: parent,
children: [],
};
parent.children.push(last);
}
parent = last;
last = null;
++prev_level;
}
while (level < prev_level) {
last = parent;
parent = last.parent;
--prev_level;
}
const node = {
href: href,
parent: parent,
children: [],
};
parent.children.push(node);
last = node;
});
while (root.href == null && root.children.length == 1) {
root = root.children[0];
}
if (root.children.length == 0) {
return;
}
let fixup_href = (tree) => {
if (! tree.href) {
tree.href = fixup_href(tree.children[0]);
}
return tree.href;
};
fixup_href(root);
let makelist = (children) => {
children = children.map((tree) => (
`<li>${tree.href}<br>${makelist(tree.children)}</li>`
)).join('');
if (children) {
children = `<ul>${children}</ul>`;
}
return children;
};
const list = makelist(root.children);
document.getElementById("toc").innerHTML = `
<p>
<b>${makeTOC.localizedHeader}</b>
<a id="showHideTOC" href="#">[${makeTOC.localizedShow}]</a>
</p>
<div id="tocGenerated" hidden=false>${list}</div>`;
const showHideTOC = document.getElementById("showHideTOC");
showHideTOC.onclick = () => {
const toc = document.getElementById("tocGenerated");
if (toc.hidden) {
toc.hidden = false;
showHideTOC.innerText = `[${makeTOC.localizedHide}]`;
} else {
toc.hidden = true;
showHideTOC.innerText = `[${makeTOC.localizedShow}]`;
}
};
}
makeTOC.localizedHeader = "Table of Contents";
makeTOC.localizedShow = "Show";
makeTOC.localizedHide = "Hide";
document.body.onload = makeTOC;