import React, { useCallback, useEffect, useState } from "react"; import { Link } from "@/components/common/Link"; import clsx from "clsx"; import { type Section, type Subsection } from "@/lib/sections"; export function TableOfContents({ tableOfContents }: { tableOfContents: Array
}) { const [currentSection, setCurrentSection] = useState(tableOfContents[0]?.id); const getHeadings = useCallback((tableOfContents: Array
) => { return tableOfContents .flatMap((node) => [node.id, ...node.children.map((child) => child.id)]) .map((id) => { const el = document.getElementById(id); if (!el) return null; const style = window.getComputedStyle(el); const scrollMt = parseFloat(style.scrollMarginTop); const top = window.scrollY + el.getBoundingClientRect().top - scrollMt; return { id, top }; }) .filter((x): x is { id: string; top: number } => x !== null); }, []); useEffect(() => { if (tableOfContents.length === 0) return; const headings = getHeadings(tableOfContents); function onScroll() { const top = window.scrollY; let current = headings[0]?.id; for (const heading of headings) { if (top < heading.top - 10) break; current = heading.id; } setCurrentSection(current); } window.addEventListener("scroll", onScroll, { passive: true }); onScroll(); return () => { window.removeEventListener("scroll", onScroll); }; }, [getHeadings, tableOfContents]); function isActive(section: Section | Subsection) { if (section.id === currentSection) return true; if (!section.children) return false; return section.children.findIndex(isActive) > -1; } return (
); }