forked from denoland/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sidebar.client.ts
83 lines (75 loc) · 2.54 KB
/
sidebar.client.ts
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
for (const el of document.querySelectorAll("[data-accordion-trigger]")) {
el.addEventListener("click", (e) => {
e.preventDefault();
const parent = el.parentElement!;
const content = parent.querySelector("[data-accordion-content]");
const hidden = content!.classList.toggle("hidden");
el.querySelector("svg")!.style.transform = hidden
? "rotate(90deg)"
: "rotate(180deg)";
for (const el of document.querySelectorAll("[data-accordion-content]")) {
if (el !== content) {
el.classList.add("hidden");
el.parentElement!.querySelector("svg")!.style.transform =
"rotate(90deg)";
}
}
});
}
const sidebar = document.getElementById("sidebar");
if (sidebar) {
const sidebarNav = sidebar.querySelector("nav")!;
const sidebarOpen = document.getElementById("sidebar-open");
const sidebarClose = document.getElementById("sidebar-close");
const sidebarCover = document.getElementById("sidebar-cover")!;
sidebarOpen?.addEventListener("click", () => {
sidebar.dataset.open = "true";
sidebarCover.dataset.open = "true";
});
sidebarClose?.addEventListener("click", () => {
sidebar.dataset.open = "false";
sidebarCover.dataset.open = "false";
});
sidebarCover?.addEventListener("click", () => {
sidebar.dataset.open = "false";
sidebarCover.dataset.open = "false";
});
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
sidebar.dataset.open = "false";
sidebarCover.dataset.open = "false";
}
});
const top = sessionStorage.getItem("sidebar-scroll");
if (top !== null) {
sidebarNav.scrollTop = parseInt(top, 10);
}
globalThis.addEventListener("beforeunload", () => {
sessionStorage.setItem("sidebar-scroll", sidebarNav.scrollTop.toString());
});
}
const toc = document.getElementById("toc");
if (toc !== null) {
const headings = document.querySelectorAll(
".markdown-body :where(h2, h3, h4, h5, h6)",
);
const ACTIVE_CSS = "sidebar__current-item";
let activeId = "";
const observer = new IntersectionObserver(
(entries) => {
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
if (entry.isIntersecting) {
const id = entry.target.id;
toc
.querySelector(`a[href="#${activeId}"]`)
?.classList.remove(ACTIVE_CSS);
toc.querySelector(`a[href="#${id}"]`)?.classList.add(ACTIVE_CSS);
activeId = id;
}
}
},
{ rootMargin: "0% 0% -70% 0%" },
);
headings.forEach((el) => observer.observe(el));
}