Fix TOC showing headings from previous article

The TOC was displaying sections from previously viewed articles when
navigating between posts. This happened because the DOM query for
headings ran before Next.js finished updating the page content.

Changes to components/post-toc.tsx:
- Clear items and activeId immediately when pathname changes
- Add 50ms delay before querying DOM for new headings
- Properly handle IntersectionObserver cleanup with timeout

This ensures the TOC always shows the correct headings for the
current article, not the previous one.

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-20 23:29:17 +08:00
parent 5d226a2969
commit e2f9c9d556

View File

@@ -19,39 +19,53 @@ export function PostToc({ onLinkClick }: { onLinkClick?: () => void }) {
const pathname = usePathname();
useEffect(() => {
const headings = Array.from(
document.querySelectorAll<HTMLElement>('article h2, article h3')
);
const mapped = headings
.filter((el) => el.id)
.map((el) => ({
id: el.id,
text: el.innerText,
depth: el.tagName === 'H3' ? 3 : 2
}));
setItems(mapped);
// Clear items immediately when pathname changes
setItems([]);
setActiveId(null);
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const id = (entry.target as HTMLElement).id;
if (id) {
setActiveId(id);
let observer: IntersectionObserver | null = null;
// Small delay to ensure DOM has been updated with new article content
const timeoutId = setTimeout(() => {
const headings = Array.from(
document.querySelectorAll<HTMLElement>('article h2, article h3')
);
const mapped = headings
.filter((el) => el.id)
.map((el) => ({
id: el.id,
text: el.innerText,
depth: el.tagName === 'H3' ? 3 : 2
}));
setItems(mapped);
observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const id = (entry.target as HTMLElement).id;
if (id) {
setActiveId(id);
}
}
}
});
},
{
// Trigger when heading is in upper 40% of viewport
rootMargin: '0px 0px -60% 0px',
threshold: 0.1
});
},
{
// Trigger when heading is in upper 40% of viewport
rootMargin: '0px 0px -60% 0px',
threshold: 0.1
}
);
headings.forEach((el) => observer?.observe(el));
}, 50); // 50ms delay to ensure DOM is updated
return () => {
clearTimeout(timeoutId);
if (observer) {
observer.disconnect();
}
);
headings.forEach((el) => observer.observe(el));
return () => observer.disconnect();
};
}, [pathname]);
useEffect(() => {