-
Notifications
You must be signed in to change notification settings - Fork 478
Expand file tree
/
Copy pathtoc.tsx
More file actions
54 lines (47 loc) · 1.36 KB
/
toc.tsx
File metadata and controls
54 lines (47 loc) · 1.36 KB
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
'use client'
import { useEffect, useState } from 'react'
interface TocHeading {
id: string
text: string
level: number
}
export function TableOfContents() {
const [headings, setHeadings] = useState<TocHeading[]>([])
const [activeId, setActiveId] = useState<string>('')
useEffect(() => {
const elements = Array.from(document.querySelectorAll('h2, h3'))
const headingData = elements.map((element) => ({
id: element.id,
text: element.textContent || '',
level: Number(element.tagName.charAt(1)),
}))
setHeadings(headingData)
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setActiveId(entry.target.id)
}
})
},
{ rootMargin: '0% 0% -80% 0%' }
)
elements.forEach((element) => observer.observe(element))
return () => observer.disconnect()
}, [])
return (
<nav className="space-y-1">
{headings.map((heading) => (
<a
key={heading.id}
href={`#${heading.id}`}
className={`block text-sm hover:text-accent-foreground transition-colors ${
heading.level === 3 ? 'pl-4' : ''
} ${activeId === heading.id ? 'text-accent-foreground' : 'text-muted-foreground'}`}
>
{heading.text}
</a>
))}
</nav>
)
}