feat: highlight active heading in sidebar table of contents

This commit is contained in:
Your Name
2026-02-19 21:36:59 +02:00
parent 969aff1e25
commit 88964ec842

View File

@@ -343,6 +343,7 @@ function App() {
const [selectionRects, setSelectionRects] = useState<{ left: number; top: number; width: number; height: number }[]>([]);
const [tabFocusIndex, setTabFocusIndex] = useState(0);
const [sidebarFocusIndex, setSidebarFocusIndex] = useState(0);
const [activeHeadingText, setActiveHeadingText] = useState<string | null>(null);
const contentRef = useRef<HTMLDivElement>(null);
const sidebarRef = useRef<HTMLDivElement>(null);
@@ -1033,6 +1034,35 @@ function App() {
}
}, [tabs.length, tabFocusIndex]);
// Active heading tracking via IntersectionObserver
useEffect(() => {
if (!activeTab || headings.length === 0) {
setActiveHeadingText(null);
return;
}
const allHeadings = document.querySelectorAll(
'.markdown-content h1, .markdown-content h2, .markdown-content h3, .markdown-content h4, .markdown-content h5, .markdown-content h6'
);
if (allHeadings.length === 0) return;
const observer = new IntersectionObserver(
(entries) => {
for (const entry of entries) {
if (entry.isIntersecting) {
setActiveHeadingText(entry.target.textContent?.trim() || null);
break;
}
}
},
{ rootMargin: '0px 0px -70% 0px', threshold: 0.1 }
);
allHeadings.forEach(h => observer.observe(h));
return () => observer.disconnect();
}, [activeTab, headings, highlightedHtml]);
// Reset sidebar focus index when headings change
useEffect(() => {
setSidebarFocusIndex(0);
@@ -1156,7 +1186,7 @@ function App() {
<button
key={h.id}
ref={(el) => { sidebarItemRefs.current[index] = el; }}
className={`sidebar-item h${h.level}`}
className={`sidebar-item h${h.level}${h.text === activeHeadingText ? ' active' : ''}`}
tabIndex={index === sidebarFocusIndex ? 0 : -1}
onClick={() => { setSidebarFocusIndex(index); scrollToHeading(h.text); }}
>