import { useEffect, useRef, useState } from "react"; /** Which of a list's items is the one the reader is currently at. * * Whichever item's middle is nearest the middle of the viewport. Measured * rather than observed: a threshold-based observer answers "is it on screen", * and with five tall steps several are on screen at once, so the question it * answers is not the question being asked. * * Reads are throttled to one animation frame, so a fast scroll costs one * measurement per painted frame rather than one per scroll event. * * Defaults to the first item and stays there when nothing can be measured, * which is the correct answer rather than a broken one: the panel shows step * one, which is where a reader arriving at the section is anyway. */ export function useActiveStep(count: number) { const ref = useRef(null); const [active, setActive] = useState(0); useEffect(() => { const list = ref.current; if (!list || count === 0) return; let queued = 0; const measure = () => { queued = 0; const items = list.children; const middle = innerHeight / 2; let best = 0; let nearest = Infinity; for (let i = 0; i < items.length; i++) { const box = items[i].getBoundingClientRect(); const gap = Math.abs(box.top + box.height / 2 - middle); if (gap < nearest) { nearest = gap; best = i; } } setActive(best); }; const onScroll = () => { if (queued) return; queued = requestAnimationFrame(measure); }; addEventListener("scroll", onScroll, { passive: true }); addEventListener("resize", onScroll); measure(); return () => { if (queued) cancelAnimationFrame(queued); removeEventListener("scroll", onScroll); removeEventListener("resize", onScroll); }; }, [count]); return [ref, active] as const; }