blob: 5c6851462fff4ceaa9a3140458e671c78b91214f (
plain) (
blame)
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
|
import type { FunctionalComponent } from 'preact';
import { useState, useEffect, useRef } from 'preact/hooks';
import type { MarkdownHeading } from 'astro';
type ItemOffsets = {
id: string;
topOffset: number;
};
const TableOfContents: FunctionalComponent<{ headings: MarkdownHeading[] }> = ({
headings = [],
}) => {
const itemOffsets = useRef<ItemOffsets[]>([]);
// FIXME: Not sure what this state is doing. It was never set to anything truthy.
const [activeId] = useState<string>('');
useEffect(() => {
const getItemOffsets = () => {
const titles = document.querySelectorAll('article :is(h1, h2, h3, h4)');
itemOffsets.current = Array.from(titles).map((title) => ({
id: title.id,
topOffset: title.getBoundingClientRect().top + window.scrollY,
}));
};
getItemOffsets();
window.addEventListener('resize', getItemOffsets);
return () => {
window.removeEventListener('resize', getItemOffsets);
};
}, []);
return (
<>
<h2 className="heading">On this page</h2>
<ul>
<li className={`heading-link depth-2 ${activeId === 'overview' ? 'active' : ''}`.trim()}>
<a href="#overview">Overview</a>
</li>
{headings
.filter(({ depth }) => depth > 1 && depth < 4)
.map((heading) => (
<li
className={`heading-link depth-${heading.depth} ${
activeId === heading.slug ? 'active' : ''
}`.trim()}
>
<a href={`#${heading.slug}`}>{heading.text}</a>
</li>
))}
</ul>
</>
);
};
export default TableOfContents;
|