MCPcopy Create free account
hub / github.com/arktypeio/arktype / useScrollspy

Function useScrollspy

ark/docs/components/shell/scrollspy.ts:22–45  ·  view source on GitHub ↗
(ids: readonly string[])

Source from the content-addressed store, hash-verified

20
21/** tracks which of the elements with these ids is being read */
22export const useScrollspy = (ids: readonly string[]): number => {
23 const [active, setActive] = useState(0)
24
25 useEffect(() => {
26 const headings = ids.map(id => document.getElementById(id))
27 if (!headings.some(Boolean)) return
28 let frame = 0
29 const update = () => {
30 cancelAnimationFrame(frame)
31 frame = requestAnimationFrame(() => setActive(activeIndexOf(headings)))
32 }
33 update()
34 addEventListener("scroll", update, { passive: true })
35 addEventListener("resize", update)
36 void document.fonts.ready.then(update)
37 return () => {
38 cancelAnimationFrame(frame)
39 removeEventListener("scroll", update)
40 removeEventListener("resize", update)
41 }
42 }, [ids])
43
44 return active
45}

Callers 1

useActiveEntryFunction · 0.90

Calls 2

updateFunction · 0.70
mapMethod · 0.65

Tested by

no test coverage detected