Skip to content

Commit

Permalink
fix: handle headerLinkElements safely
Browse files Browse the repository at this point in the history
  • Loading branch information
HEIGE-PCloud committed Jun 11, 2024
1 parent 90c35b5 commit 2543464
Showing 1 changed file with 17 additions and 15 deletions.
32 changes: 17 additions & 15 deletions assets/js/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,7 @@ function initToc() {
const toc = document.getElementById("toc-auto");
const tocLinkElements = tocCore.querySelectorAll("a:first-child");
const tocLiElements = tocCore.getElementsByTagName("li");
const headerLinkElements = document.getElementsByClassName("headerLink");
const headerLinkElements = document.getElementsByClassName("headerLink") as HTMLCollectionOf<HTMLHeadingElement>;
const headerIsFixed =
document.body.getAttribute("header-desktop") !== "normal";
const headerHeight = document.getElementById("header-desktop").offsetHeight;
Expand Down Expand Up @@ -579,20 +579,22 @@ function initToc() {
const INDEX_SPACING = TOP_SPACING + window.newScrollTop;
// If the INDEX_SPACING is below the last header link
// activate the last element
if (
headerLinkElements[headerLinkElements.length - 1].offsetTop <
INDEX_SPACING
) {
activeTocIndex = headerLinkElements.length - 1;
} else {
// Otherwise activate the element that is in between
// Use offsetTop instead of getBoundingClientRect().top for better performance
for (let i = 0; i < headerLinkElements.length - 1; i++) {
const thisTop = headerLinkElements[i].offsetTop;
const nextTop = headerLinkElements[i + 1].offsetTop;
if (thisTop <= INDEX_SPACING && nextTop > INDEX_SPACING) {
activeTocIndex = i;
break;
if (headerLinkElements.length > 0) {
if (
headerLinkElements[headerLinkElements.length - 1].offsetTop <
INDEX_SPACING
) {
activeTocIndex = headerLinkElements.length - 1;
} else {
// Otherwise activate the element that is in between
// Use offsetTop instead of getBoundingClientRect().top for better performance
for (let i = 0; i < headerLinkElements.length - 1; i++) {
const thisTop = headerLinkElements[i].offsetTop;
const nextTop = headerLinkElements[i + 1].offsetTop;
if (thisTop <= INDEX_SPACING && nextTop > INDEX_SPACING) {
activeTocIndex = i;
break;
}
}
}
}
Expand Down

0 comments on commit 2543464

Please sign in to comment.