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

useTocHighlight.js

83 lines2.2 KB

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