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';
5import { NOTION_ANCHOR_CLASSNAME } from './blog/Heading';
6const TOP_OFFSET = 100;
7β
8const getHeadingDataFromAnchor = el => {
9 return {
10 text: el.getAttribute('data-heading-text'),
11 depth: Number(el.getAttribute('data-heading-depth')),
12 url: el.getAttribute('href')
13 };
14};
15β
16export function getHeaderNotionAnchors() {
17 /**
18 * .filter() does not exist on HTMLCollectionOf<Element>
19 * (the return type of document.getElementByClassName()),
20 * so we use this as a workaround.
21 */
22 return Array.prototype.filter.call(document.getElementsByClassName(NOTION_ANCHOR_CLASSNAME), function (testElement) {
23 return testElement.firstElementChild?.nodeName === 'H2' || testElement.firstElementChild?.nodeName === 'H3';
24 });
25}
26export const TocNotion = () => {
27 const headings = useTocHighlight(styles.contents__link, styles['contents__link--active'], TOP_OFFSET, getHeaderNotionAnchors, getHeadingDataFromAnchor, el => el?.id);
28 return <>
29 <h4 className="text-gray-700 font-semibold mb-3">Table of Contents</h4>
30 <ul className="space-y-3">
31 {headings && headings.length > 0 && headings.map((h, i) => h.url ? <li key={`heading-${h.url}-${i}`} className={cx('text-base ', {
32 ['pl-2']: h?.depth === 3,
33 ['hidden']: h.depth && h.depth > 3
34 })}>
35 <a className={styles.contents__link} href={h.url}>
36 {h.text}
37 </a>
38 </li> : null)}
39 </ul>
40 </>;
41};