Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

useTocHighlight.js

76 lines2.2 KB

1import React from 'react';
2​
3/**
4 * Sets up Table of Contents highlighting. It requires that
5 */
6export function useTocHighlight(linkClassName, linkActiveClassName, topOffset, getHeaderAnchors, getHeaderDataFromAnchor, getAnchorHeaderIdentifier) {
7 const [lastActiveLink, setLastActiveLink] = React.useState(undefined);
8 const [headings, setHeadings] = React.useState([]);
9 React.useEffect(() => {
10 setHeadings(getHeaderAnchors().map(getHeaderDataFromAnchor));
11 }, [setHeadings]);
12 React.useEffect(() => {
13 let headersAnchors = [];
14 let links = [];
15​
16 function setActiveLink() {
17 function getActiveHeaderAnchor() {
18 let index = 0;
19 let activeHeaderAnchor = null;
20 headersAnchors = getHeaderAnchors();
21​
22 while (index < headersAnchors.length && !activeHeaderAnchor) {
23 const headerAnchor = headersAnchors[index];
24 const {
25 top
26 } = headerAnchor.getBoundingClientRect();
27​
28 if (top >= 0 && top <= topOffset) {
29 activeHeaderAnchor = headerAnchor;
30 }
31​
32 index += 1;
33 }
34​
35 return activeHeaderAnchor;
36 }
37​
38 const activeHeaderAnchor = getActiveHeaderAnchor();
39​
40 if (activeHeaderAnchor) {
41 let index = 0;
42 let itemHighlighted = false;
43 links = document.getElementsByClassName(linkClassName);
44​
45 while (index < links.length && !itemHighlighted) {
46 const link = links[index];
47 const {
48 href
49 } = link;
50 const anchorValue = decodeURIComponent(href.substring(href.indexOf('#') + 1));
51​
52 if (getAnchorHeaderIdentifier(activeHeaderAnchor) === anchorValue) {
53 if (lastActiveLink) {
54 lastActiveLink.classList.remove(linkActiveClassName);
55 }
56​
57 link.classList.add(linkActiveClassName);
58 setLastActiveLink(link);
59 itemHighlighted = true;
60 }
61​
62 index += 1;
63 }
64 }
65 }
66​
67 document.addEventListener('scroll', setActiveLink);
68 document.addEventListener('resize', setActiveLink);
69 setActiveLink();
70 return () => {
71 document.removeEventListener('scroll', setActiveLink);
72 document.removeEventListener('resize', setActiveLink);
73 };
74 });
75 return headings;