blob: 3587d78b8e3654236976e6f4e6da887846cb4639 (
plain)
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
|
let scrollTimeout;
const listenActive = () => {
const elems = document.querySelector(".pagetoc").children;
[...elems].forEach(el => {
el.addEventListener("click", (event) => {
clearTimeout(scrollTimeout);
[...elems].forEach(el => el.classList.remove("active"));
el.classList.add("active");
// Prevent scroll updates for a short period
scrollTimeout = setTimeout(() => {
scrollTimeout = null;
}, 100); // Adjust timing as needed
});
});
};
const getPagetoc = () => document.querySelector(".pagetoc") || autoCreatePagetoc();
const autoCreatePagetoc = () => {
const main = document.querySelector("#content > main");
const content = Object.assign(document.createElement("div"), {
className: "content-wrap"
});
content.append(...main.childNodes);
main.prepend(content);
main.insertAdjacentHTML("afterbegin", '<div class="sidetoc"><nav class="pagetoc"></nav></div>');
return document.querySelector(".pagetoc");
};
const updateFunction = () => {
if (scrollTimeout) return; // Skip updates if within the cooldown period from a click
const headers = [...document.getElementsByClassName("header")];
const scrolledY = window.scrollY;
let lastHeader = null;
// Find the last header that is above the current scroll position
for (let i = headers.length - 1; i >= 0; i--) {
if (scrolledY >= headers[i].offsetTop) {
lastHeader = headers[i];
break;
}
}
const pagetocLinks = [...document.querySelector(".pagetoc").children];
pagetocLinks.forEach(link => link.classList.remove("active"));
if (lastHeader) {
const activeLink = pagetocLinks.find(link => lastHeader.href === link.href);
if (activeLink) activeLink.classList.add("active");
}
};
window.addEventListener('load', () => {
const pagetoc = getPagetoc();
const headers = [...document.getElementsByClassName("header")];
headers.forEach(header => {
const parent = header.parentElement
if (!parent.classList.contains("toc-ignore")) {
const link = Object.assign(document.createElement("a"), {
textContent: [...parent.childNodes].map(({ textContent }) => textContent).join(''),
href: header.href,
className: `pagetoc-${parent.tagName}`
});
pagetoc.appendChild(link);
}
});
updateFunction();
listenActive();
window.addEventListener("scroll", updateFunction);
});
|