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 Array.prototype.filter.call(
9 document.getElementsByClassName('anchor'),
10 function (testElement) {
11 return (
12 testElement.parentNode.nodeName === 'H2' ||
13 testElement.parentNode.nodeName === 'H3'
14 )
15 }
16 )
17}
18β
19function getHeaderDataFromAnchors(el) {
20 return {
21 url: el.getAttribute('href'),
22 text: el.parentElement?.innerText,
23 depth: Number(el.parentElement?.nodeName.replace('H', '')),
24 }
25}
26β
27export const Toc = () => {
28 const headings = useTocHighlight(
29 styles.contents__link,
30 styles['contents__link--active'],
31 TOP_OFFSET,
32 getHeaderAnchors,
33 getHeaderDataFromAnchors,
34 el => el?.parentElement?.id
35 )
36β
37 return (
38 <ul className="space-y-3">
39 {headings &&
40 headings.length > 0 &&
41 headings.map((h, i) =>
42 h.url ? (
43 <li
44 key={`heading-${h.url}-${i}`}
45 className={cx('text-sm ', {
46 'pl-2': h?.depth === 3,
47 hidden: h.depth && h.depth > 3,
48 })}
49 >
50 <a className={styles.contents__link} href={h.url}>
51 {h.text}
52 </a>
53 </li>
54 ) : null
55 )}
56 </ul>
57 )
58}