import type { Section, Subsection } from "@/libs/sections"; import { createSignal, createEffect, For } from "solid-js"; import { Link } from "@/components/Link"; import clsx from "clsx"; type TableOfContentsProps = { tableOfContents: Array
; }; export function TableOfContents(props: TableOfContentsProps) { const [currentSection, setCurrentSection] = createSignal( props.tableOfContents[0]?.id, ); const getHeadings = (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 = Number.parseFloat(style.scrollMarginTop); const top = window.scrollY + el.getBoundingClientRect().top - scrollMt; return { id, top }; }) .filter((x): x is { id: string; top: number } => x !== null); }; createEffect(() => { if (props.tableOfContents.length === 0) return; const headings = getHeadings(props.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, props.tableOfContents]); function isActive(section: Section | Subsection) { if (section.id === currentSection()) return true; if (!section.children) return false; return section.children.findIndex(isActive) > -1; } return ( ); }