Skip to content

Commit

Permalink
add early return in init for no entry in TOC
Browse files Browse the repository at this point in the history
  • Loading branch information
foxton9 committed Dec 8, 2024
1 parent 99f813b commit 61b8c26
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions src/components/widget/TOC.astro
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class TableOfContents extends HTMLElement {
this.observer = new IntersectionObserver(
this.markVisibleSection, { threshold: 0 }
);
}
};

markVisibleSection = (entries: IntersectionObserverEntry[]) => {
entries.forEach((entry) => {
Expand All @@ -85,7 +85,7 @@ class TableOfContents extends HTMLElement {
this.active[idx] = entry.isIntersecting;

if (entry.isIntersecting && this.anchorNavTarget == entry.target.firstChild)
this.anchorNavTarget = null;
this.anchorNavTarget = null;
});

if (!this.active.includes(true))
Expand Down Expand Up @@ -152,7 +152,7 @@ class TableOfContents extends HTMLElement {
this.scrollToActiveHeading();
// });
});
}
};

fallback = () => {
if (!this.sections.length) return;
Expand All @@ -172,7 +172,7 @@ class TableOfContents extends HTMLElement {

markActiveHeading = (idx: number)=> {
this.active[idx] = true;
}
};

handleAnchorClick = (event: Event) => {
const anchor = event
Expand All @@ -192,7 +192,7 @@ class TableOfContents extends HTMLElement {

isInRange(value: number, min: number, max: number) {
return min < value && value < max;
}
};

connectedCallback() {
// wait for the onload animation to finish, which makes the `getBoundingClientRect` return correct values
Expand All @@ -204,7 +204,7 @@ class TableOfContents extends HTMLElement {
} else {
console.warn('Animation element not found');
}
}
};

init() {
this.tocEl = document.getElementById(
Expand All @@ -223,6 +223,8 @@ class TableOfContents extends HTMLElement {
document.querySelectorAll<HTMLAnchorElement>("#toc a[href^='#']")
);

if (this.tocEntries.length === 0) return;

this.sections = new Array(this.tocEntries.length);
this.headings = new Array(this.tocEntries.length);
for (let i = 0; i < this.tocEntries.length; i++) {
Expand All @@ -243,15 +245,15 @@ class TableOfContents extends HTMLElement {

this.fallback();
this.update();
}
};

disconnectedCallback() {
this.sections.forEach((section) =>
this.observer.unobserve(section)
);
this.observer.disconnect();
this.tocEl?.removeEventListener("click", this.handleAnchorClick);
}
};
}

customElements.define("table-of-contents", TableOfContents);
Expand Down

0 comments on commit 61b8c26

Please sign in to comment.