返回 CodeWhale
toc.tsx
1 "use client";
2
3 import { useEffect, useRef, useState } from "react";
4
5 export function DocsPreviewToc({ label, headings }: { label: string; headings: readonly { id: string; depth: number; title: string }[] }) {
6 const [current, setCurrent] = useState(headings[0]?.id ?? "");
7 const rail = useRef<HTMLElement>(null);
8 const active = headings.some((heading) => heading.id === current) ? current : (headings[0]?.id ?? "");
9
10 useEffect(() => {
11 const targets = headings.map((heading) => document.getElementById(heading.id)).filter((element): element is HTMLElement => element !== null);
12 if (!targets.length) return;
13 const observer = new IntersectionObserver(
14 (entries) => {
15 const visible = entries.filter((entry) => entry.isIntersecting).sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top)[0];
16 if (visible) setCurrent(visible.target.id);
17 },
18 { rootMargin: "-88px 0px -70% 0px" },
19 );
20 for (const target of targets) observer.observe(target);
21 return () => observer.disconnect();
22 }, [headings]);
23
24 useEffect(() => {
25 rail.current?.querySelector("[aria-current]")?.scrollIntoView({ block: "nearest" });
26 }, [active]);
27
28 if (headings.length < 2) return null;
29 return (
30 <nav ref={rail} className="dp-toc" aria-label={label}>
31 <p className="dp-toc-label">{label}</p>
32 <ol>
33 {headings.map((heading) => (
34 <li key={heading.id} data-depth={heading.depth}>
35 <a href={`#${heading.id}`} aria-current={heading.id === active ? "location" : undefined}>{heading.title}</a>
36 </li>
37 ))}
38 </ol>
39 </nav>
40 );
41 }
42
42 lines Plain Text