'use client'; import { useState, useEffect } from 'react'; export interface TOCItem { id: string; label: string; subItems?: TOCItem[]; } interface TableOfContentsProps { items: TOCItem[]; } // Get all IDs from items and their subitems (pure function, no dependencies) const getAllIds = (items: TOCItem[]): string[] => { return items.reduce((acc, item) => { acc.push(item.id); if (item.subItems && item.subItems.length > 0) { acc = [...acc, ...getAllIds(item.subItems)]; } return acc; }, []); }; export default function TableOfContents({ items }: TableOfContentsProps) { const [activeId, setActiveId] = useState(null); // Update active section based on scroll position useEffect(() => { const observer = new IntersectionObserver( (entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { setActiveId(entry.target.id); } }); }, { rootMargin: '-10% 0% -80% 0%', threshold: 0 }, ); // Observe all section elements that correspond to TOC items const itemIds = getAllIds(items); itemIds.forEach((id) => { const element = document.getElementById(id); if (element) { observer.observe(element); } }); return () => { itemIds.forEach((id) => { const element = document.getElementById(id); if (element) { observer.unobserve(element); } }); }; }, [items]); // Handle smooth scrolling when clicking a TOC item const scrollToSection = (id: string) => { const element = document.getElementById(id); if (element) { setActiveId(id); element.scrollIntoView({ behavior: 'smooth' }); } }; // Recursive rendering of TOC items const renderTOCItems = (items: TOCItem[], level = 0) => { return ( ); }; return ( ); }