Fix TOC showing wrong headings across navigation

The TOC component was only extracting headings once at mount, causing it to show stale headings when navigating between posts via client-side routing. Now it re-extracts headings whenever the pathname changes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-20 20:29:30 +08:00
parent af40ebc5e6
commit 45cfc6acc4

View File

@@ -1,6 +1,7 @@
'use client'; 'use client';
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { usePathname } from 'next/navigation';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faListUl } from '@fortawesome/free-solid-svg-icons'; import { faListUl } from '@fortawesome/free-solid-svg-icons';
@@ -16,6 +17,7 @@ export function PostToc({ onLinkClick }: { onLinkClick?: () => void }) {
const listRef = useRef<HTMLDivElement | null>(null); const listRef = useRef<HTMLDivElement | null>(null);
const itemRefs = useRef<Record<string, HTMLDivElement | null>>({}); const itemRefs = useRef<Record<string, HTMLDivElement | null>>({});
const [indicator, setIndicator] = useState({ top: 0, opacity: 0 }); const [indicator, setIndicator] = useState({ top: 0, opacity: 0 });
const pathname = usePathname();
useEffect(() => { useEffect(() => {
const headings = Array.from( const headings = Array.from(
@@ -51,7 +53,7 @@ export function PostToc({ onLinkClick }: { onLinkClick?: () => void }) {
headings.forEach((el) => observer.observe(el)); headings.forEach((el) => observer.observe(el));
return () => observer.disconnect(); return () => observer.disconnect();
}, []); }, [pathname]);
useEffect(() => { useEffect(() => {
if (!activeId || !listRef.current) { if (!activeId || !listRef.current) {