Skip to content

Commit a8d0a57

Browse files
authored
docs: make table of contents sticky on desktop (#16506)
* docs: make toc sticky on desktop * docs: fix bug * docs: fix CSS style * docs: fix scrollbar style for dark mode
1 parent 9432b67 commit a8d0a57

2 files changed

Lines changed: 64 additions & 1 deletion

File tree

docs/src/assets/js/main.js

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,42 @@
1+
(function () {
2+
// for sticky table of contents
3+
const tocBody = document.querySelector(".docs-aside #js-toc-panel");
4+
const options = {
5+
root: null,
6+
rootMargin: `0px 0px -90% 0px`,
7+
threshold: 1.0,
8+
};
9+
const activeClassName = "active";
10+
const observer = new IntersectionObserver((entries) => {
11+
entries.forEach((entry) => {
12+
if (entry.isIntersecting) {
13+
const activeAnchor = tocBody.querySelector(
14+
`a.${activeClassName}`
15+
);
16+
if (activeAnchor) {
17+
activeAnchor.parentNode.classList.remove(activeClassName);
18+
activeAnchor.classList.remove(activeClassName);
19+
}
20+
21+
const nextActiveAnchor = tocBody.querySelector(
22+
`a[href="#${entry.target.id}"]`
23+
);
24+
if (nextActiveAnchor) {
25+
nextActiveAnchor.parentNode.classList.add(activeClassName);
26+
nextActiveAnchor.classList.add(activeClassName);
27+
}
28+
}
29+
});
30+
}, options);
31+
if (window.matchMedia("(min-width: 1400px)").matches) {
32+
document
33+
.querySelectorAll(
34+
"#main > div > h2[id], #main > div > h3[id], #main > div > h4[id]" // only h2, h3, h4 are shown in toc
35+
)
36+
.forEach((el) => observer.observe(el));
37+
}
38+
})();
39+
140
(function() {
241
var toc_trigger = document.getElementById("js-toc-label"),
342
toc = document.getElementById("js-toc-panel"),
@@ -279,4 +318,4 @@ if (index) {
279318

280319
document.addEventListener("DOMContentLoaded", () => {
281320
anchors.add(".docs-content h2:not(.c-toc__label), .docs-content h3, .docs-content h4");
282-
});
321+
});

docs/src/assets/scss/components/toc.scss

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,30 @@
1818
}
1919
}
2020

21+
.docs-aside {
22+
// for sticky table of contents in sidebar
23+
.docs-toc.c-toc {
24+
background-color: var(--body-background-color);
25+
@media all and (min-width: 1400px) {
26+
position: sticky;
27+
top: 20px;
28+
overflow-y: auto; // show scrollbar when toc is higher than viewport
29+
padding-right: 5px; // push scrollbar away from content
30+
max-height: calc(100vh - 32px); // minus element's margin-top
31+
a.active {
32+
color: var(--link-color);
33+
font-weight: 500;
34+
}
35+
}
36+
}
37+
38+
.c-toc ol li.active::before {
39+
@media all and (min-width: 1400px) {
40+
color: var(--link-color);
41+
}
42+
}
43+
}
44+
2145
.c-toc {
2246
ol {
2347
margin: 0;

0 commit comments

Comments
 (0)