Open History to see the last commit
1import * as React from 'react'
2import cx from 'classnames'
3import { useTocHighlight } from './useTocHighlight'
4import styles from './Toc.module.css'
5const TOP_OFFSET = 100
6β
7function getHeaderAnchors() {
8 return [
9 ...document.getElementsByTagName('H1'),
10 ...[...document.getElementsByClassName('anchor')].filter(
11 el => el.parentNode.nodeName === 'H2' || el.parentNode.nodeName === 'H3'
12 ),
13 ].filter(Boolean)
14}
15β
16function getHeaderDataFromAnchors(el) {
17 return {
18 url: el.getAttribute('href'),
19 text: el.parentElement?.innerText,
20 depth: Number(el.parentElement?.nodeName.replace('H', '')),
21 }
22}
23β
24export const Toc = ({ title }) => {
25 const headings = useTocHighlight(
26 styles.contents__link,
27 styles['contents__link--active'],
28 TOP_OFFSET,
29 getHeaderAnchors,
30 getHeaderDataFromAnchors,
31 el => el?.parentElement?.id
32 )
33β
34 return (
35 <ul className="space-y-3">
36 <li className="text-sm">
37 <a className={styles.contents__link} href="#_top">
38 {title}
39 </a>
40 </li>
41 {headings &&
42 headings.length > 0 &&
43 headings.map((h, i) =>
44 h.url ? (
45 <li
46 key={`heading-${h.url}-${i}`}
47 className={cx('text-sm ', {
48 'pl-2': h?.depth === 3,
49 hidden: h.depth && h.depth > 3,
50 })}
51 >
52 <a className={styles.contents__link} href={h.url}>
53 {h.text}
54 </a>
55 </li>
56 ) : null
57 )}
58 </ul>
59 )
60}