-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathTableOfContents.tsx
106 lines (92 loc) · 3.25 KB
/
TableOfContents.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
"use client";
import useActualPathname from "@/hooks/useActualPathname";
import { FC, useEffect, useRef, useState } from "react";
const selector = ":is(h1, h2, h3, h4, h5, h6)[id]";
export default function TableOfContents({
as,
}: {
as?: keyof JSX.IntrinsicElements | FC;
}) {
const [headings, setHeadings] = useState<
{
id: string;
title: string;
}[]
>([]);
const observer = useRef<IntersectionObserver>();
const [activeId, setActiveId] = useState("");
const Root = as ?? "div";
const pathname = useActualPathname();
useEffect(() => {
const headingElements = Array.from(
document.querySelectorAll(selector) as Iterable<HTMLElement>,
);
if (
headingElements.length > 1 &&
headingElements[0]?.tagName === "H1"
) {
headingElements.shift();
}
const headings = headingElements.map(element => ({
title: element.innerText.replaceAll("&", "&"),
id: element.id,
}));
setHeadings(headings);
setActiveId(headings[0].id);
}, [pathname]);
useEffect(() => {
observer.current = new IntersectionObserver(
entries => {
for (const entry of entries) {
if (entry?.isIntersecting) {
setActiveId(entry.target.id);
}
}
},
{
rootMargin: "-30% 0% -30% 0%",
},
);
const elements = document.querySelectorAll(selector);
elements.forEach(element => observer.current?.observe(element));
return () => {
observer.current?.disconnect();
setActiveId("");
};
}, [pathname]);
const onlyOne = headings.length === 1;
return (
<Root>
<h4 className="pl-[15px] mb-3 mt-4 uppercase font-bold tracking-wider text-[15px]">
On this page
</h4>
<ul className="list-none pr-2.5">
{headings.map(heading => (
<li key={heading.id}>
<a
className={`my-2 block pl-[15px] ${
activeId === heading.id || onlyOne
? "text-blue-500 after:[content:'●'] after:ml-2 after:inline-block after:text-blue-500"
: "hover:text-blue-500"
}`}
href={`#${heading.id}`}
onClick={event => {
event.preventDefault();
const element = document.getElementById(
heading.id,
);
element?.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "center",
});
}}
>
{heading.title}
</a>
</li>
))}
</ul>
</Root>
);
}