diff --git a/src/components/widget/TOC.astro b/src/components/widget/TOC.astro index 1488f94de..8ac3e5aff 100644 --- a/src/components/widget/TOC.astro +++ b/src/components/widget/TOC.astro @@ -75,7 +75,7 @@ class TableOfContents extends HTMLElement { this.observer = new IntersectionObserver( this.markVisibleSection, { threshold: 0 } ); - } + }; markVisibleSection = (entries: IntersectionObserverEntry[]) => { entries.forEach((entry) => { @@ -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)) @@ -152,7 +152,7 @@ class TableOfContents extends HTMLElement { this.scrollToActiveHeading(); // }); }); - } + }; fallback = () => { if (!this.sections.length) return; @@ -172,7 +172,7 @@ class TableOfContents extends HTMLElement { markActiveHeading = (idx: number)=> { this.active[idx] = true; - } + }; handleAnchorClick = (event: Event) => { const anchor = event @@ -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 @@ -204,7 +204,7 @@ class TableOfContents extends HTMLElement { } else { console.warn('Animation element not found'); } - } + }; init() { this.tocEl = document.getElementById( @@ -223,6 +223,8 @@ class TableOfContents extends HTMLElement { document.querySelectorAll("#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++) { @@ -243,7 +245,7 @@ class TableOfContents extends HTMLElement { this.fallback(); this.update(); - } + }; disconnectedCallback() { this.sections.forEach((section) => @@ -251,7 +253,7 @@ class TableOfContents extends HTMLElement { ); this.observer.disconnect(); this.tocEl?.removeEventListener("click", this.handleAnchorClick); - } + }; } customElements.define("table-of-contents", TableOfContents);