-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpage-toc.js
More file actions
89 lines (76 loc) · 2.52 KB
/
page-toc.js
File metadata and controls
89 lines (76 loc) · 2.52 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
(function () {
var main = document.querySelector(".content main");
if (
!main ||
main.querySelector(".landing-hero") ||
main.querySelector(".page-404")
)
return;
var headings = main.querySelectorAll("h2[id], h3[id]");
if (headings.length < 2) return;
// Build TOC
var nav = document.createElement("nav");
nav.className = "page-toc";
nav.setAttribute("aria-label", "On this page");
var title = document.createElement("div");
title.className = "page-toc-title";
title.textContent = "On this page";
nav.appendChild(title);
var list = document.createElement("ul");
headings.forEach(function (h) {
var li = document.createElement("li");
if (h.tagName === "H3") li.className = "toc-indent";
var a = document.createElement("a");
a.href = "#" + h.id;
var headerLink = h.querySelector("a.header");
a.textContent = (headerLink || h).textContent.trim();
li.appendChild(a);
list.appendChild(li);
});
nav.appendChild(list);
document.querySelector(".page-wrapper").appendChild(nav);
// Scroll spy
var links = list.querySelectorAll("a");
var headingArr = Array.prototype.slice.call(headings);
var ticking = false;
function updateActive() {
var scrollPos = window.scrollY + 120;
var current = null;
for (var i = 0; i < headingArr.length; i++) {
if (headingArr[i].offsetTop <= scrollPos) {
current = headingArr[i];
}
}
links.forEach(function (l) {
l.classList.remove("active");
});
if (current) {
var link = list.querySelector('a[href="#' + current.id + '"]');
if (link) link.classList.add("active");
}
ticking = false;
}
window.addEventListener(
"scroll",
function () {
if (!ticking) {
requestAnimationFrame(updateActive);
ticking = true;
}
},
{ passive: true },
);
updateActive();
})();
// Close search modal when clicking the backdrop
(function () {
var wrapper = document.getElementById("mdbook-search-wrapper");
if (!wrapper) return;
wrapper.addEventListener("click", function (e) {
if (e.target === wrapper) {
wrapper.classList.add("hidden");
var icon = document.getElementById("mdbook-search-toggle");
if (icon) icon.setAttribute("aria-expanded", "false");
}
});
})();