'use client' import { useEffect, useMemo, useState } from 'react' import Link from 'next/link' import clsx from 'clsx' import { type Section, type Subsection } from '@/lib/sections' function getSectionIds(tableOfContents: Array
) { return tableOfContents.flatMap((section) => [ section.id, ...section.children.map((child) => child.id), ]) } export function TableOfContents({ tableOfContents, }: { tableOfContents: Array
}) { let sectionIds = useMemo( () => getSectionIds(tableOfContents), [tableOfContents], ) let [currentSection, setCurrentSection] = useState(sectionIds[0]) useEffect(() => { if (sectionIds.length === 0) { return } let headings = sectionIds .map((id) => document.getElementById(id)) .filter((heading): heading is HTMLElement => heading !== null) if (headings.length === 0) { return } let frameId = 0 function updateCurrentSection() { frameId = 0 let current = headings[0].id let viewportTop = window.innerHeight * 0.25 for (let heading of headings) { if (heading.getBoundingClientRect().top <= viewportTop) { current = heading.id } else { break } } setCurrentSection(current) } function scheduleUpdate() { if (frameId === 0) { frameId = window.requestAnimationFrame(updateCurrentSection) } } let observer = new IntersectionObserver(scheduleUpdate, { rootMargin: '-25% 0px -70% 0px', }) for (let heading of headings) { observer.observe(heading) } window.addEventListener('scroll', scheduleUpdate, { passive: true }) window.addEventListener('resize', scheduleUpdate) updateCurrentSection() return () => { observer.disconnect() window.removeEventListener('scroll', scheduleUpdate) window.removeEventListener('resize', scheduleUpdate) if (frameId !== 0) { window.cancelAnimationFrame(frameId) } } }, [sectionIds]) function isActive(section: Section | Subsection) { if (section.id === currentSection) { return true } if (!section.children) { return false } return section.children.findIndex(isActive) > -1 } return (
) }