Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/blog/table-of-contents.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,36 @@ function initializeTableOfContents() {
const currentLink = tocContainer.querySelector(`a[href="#${id}"]`);
if (currentLink) {
currentLink.classList.add("active");
scrollActiveLinkIntoView(currentLink);
}
}

function scrollActiveLinkIntoView(link) {
const scroller = getScrollParent(link);
if (!scroller) return; // no scrollable ancestor → nothing to do
const pad = 8;
const linkRect = link.getBoundingClientRect();
const boxRect = scroller.getBoundingClientRect();

if (linkRect.top < boxRect.top + pad) {
scroller.scrollTop -= (boxRect.top + pad) - linkRect.top;
} else if (linkRect.bottom > boxRect.bottom - pad) {
scroller.scrollTop += linkRect.bottom - (boxRect.bottom - pad);
}
}

function getScrollParent(el) {
let node = el.parentElement;
while (node && node !== document.body) {
const oy = getComputedStyle(node).overflowY;
if ((oy === "auto" || oy === "scroll") && node.scrollHeight > node.clientHeight) {
return node;
}
node = node.parentElement;
}
return null;
}

if (headers.length > 0) {
tocComponent.style.display = "block";
}
Expand Down
Loading