(ids: readonly string[])
| 20 | |
| 21 | /** tracks which of the elements with these ids is being read */ |
| 22 | export 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 | } |
no test coverage detected