import { useEffect, useRef, useState } from "preact/hooks"; import type { MarkdownHeading } from "../utils/markdown.ts"; export interface TableOfContentsProps { headings: MarkdownHeading[]; } function setActiveLink( container: HTMLElement, marker: HTMLElement, id: string, ) { container.querySelectorAll(`a`).forEach((link) => link.classList.remove("active") ); const tocLink = container.querySelector( `a[href="#${id}"]`, ) as HTMLElement; if (tocLink === null) return; tocLink.classList.add("active"); const rect = tocLink .getBoundingClientRect(); const markerRect = marker.getBoundingClientRect(); const top = tocLink.offsetTop + (rect.height / 2) - (markerRect.height / 2); marker.style.cssText = `transform: translate3d(0, ${top}px, 0); opacity: 1`; } export function TableOfContents({ headings }: TableOfContentsProps) { const ref = useRef(null); const refMarker = useRef(null); const [isOpen, setIsOpen] = useState(false); useEffect(() => { if (!ref.current) return; const container = ref.current; const activeList = new Array(headings.length).fill(false); const visibleList = new Array(headings.length).fill(false); const marker = refMarker.current!; const observer = new IntersectionObserver((entries) => { for (let i = 0; i < entries.length; i++) { const entry = entries[i]; const target = entry.target; for (let j = 0; j < headings.length; j++) { const heading = headings[j]; if (heading.id === target.id) { const active = entry.isIntersecting || entry.boundingClientRect.top < 0; activeList[j] = active; visibleList[j] = entry.isIntersecting; } } } // Reset links for (let i = 0; i < headings.length; i++) { const id = headings[i].id; const tocLink = container.querySelector( `a[href="#${id}"]`, ); if (tocLink !== null) { tocLink.classList.remove("active"); } } let activeIdx = visibleList.indexOf(true); if (activeIdx < 0) { activeIdx = activeList.lastIndexOf(true); } if (activeIdx > -1) { const id = headings[activeIdx].id; setActiveLink(container, marker, id); } else { marker.style.cssText = `transform: translate3d(0, 0, 0); opacity: 0`; } }); document.querySelectorAll( ".markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6", ).forEach((elem) => { observer.observe(elem); }); return () => { observer.disconnect(); }; }, [headings]); return (
{headings.length > 0 && ( <>
{isOpen && (
)}
); }