'use client' import { useEffect, useRef, useState } from 'react' type TocItem = { text: string; id: string; level: number } const indentByLevel: Record = { 2: 'pl-0', 3: 'pl-4', } export function TableOfContents({ items }: { items: TocItem[] }) { const [activeId, setActiveId] = useState(null) const observer = useRef(null) useEffect(() => { if (items.length === 0) return const headingElements = items .map((item) => document.getElementById(item.id)) .filter((el): el is HTMLElement => el !== null) observer.current = new IntersectionObserver( (entries) => { const visible = entries.filter((entry) => entry.isIntersecting) if (visible.length > 0) { setActiveId(visible[0].target.id) } }, { rootMargin: '0px 0px -70% 0px', threshold: 1.0 }, ) headingElements.forEach((el) => observer.current?.observe(el)) return () => observer.current?.disconnect() }, [items]) if (items.length === 0) return null return ( ) }