feat: add table of contents with scroll spy
This commit is contained in:
68
components/blog/TableOfContents.tsx
Normal file
68
components/blog/TableOfContents.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState, useRef } from "react";
|
||||
|
||||
interface TOCItem {
|
||||
id: string;
|
||||
text: string;
|
||||
level: number;
|
||||
}
|
||||
|
||||
export function TableOfContents() {
|
||||
const [headings, setHeadings] = useState<TOCItem[]>([]);
|
||||
const [activeId, setActiveId] = useState("");
|
||||
const observerRef = useRef<IntersectionObserver | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const elements = Array.from(
|
||||
document.querySelectorAll("article h2, article h3")
|
||||
) as HTMLElement[];
|
||||
|
||||
const parsed = elements.map((el) => ({
|
||||
id: el.id,
|
||||
text: el.textContent ?? "",
|
||||
level: el.tagName === "H2" ? 2 : 3,
|
||||
}));
|
||||
|
||||
setHeadings(parsed);
|
||||
|
||||
observerRef.current = new IntersectionObserver(
|
||||
(entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (entry.isIntersecting) {
|
||||
setActiveId(entry.target.id);
|
||||
}
|
||||
});
|
||||
},
|
||||
{ rootMargin: "-20% 0px -70% 0px", threshold: 0 }
|
||||
);
|
||||
|
||||
elements.forEach((el) => observerRef.current?.observe(el));
|
||||
|
||||
return () => observerRef.current?.disconnect();
|
||||
}, []);
|
||||
|
||||
if (headings.length === 0) return null;
|
||||
|
||||
return (
|
||||
<nav className="lg:sticky lg:top-8">
|
||||
<h4 className="font-sans text-xs font-semibold uppercase tracking-wider text-ink-soft mb-3">
|
||||
On this page
|
||||
</h4>
|
||||
<ul className="space-y-1">
|
||||
{headings.map((heading) => (
|
||||
<li key={heading.id}>
|
||||
<a
|
||||
href={`#${heading.id}`}
|
||||
className={`block text-sm transition-colors ${
|
||||
heading.level === 3 ? "pl-3 text-ink-soft" : "text-ink"
|
||||
} ${activeId === heading.id ? "font-semibold text-accent" : ""}`}
|
||||
>
|
||||
{heading.text}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user