Open History to see the last commit
1import { useEffect, useState } from "react";
2import type { RefObject } from "react";
3
4import { anchorAt, measureAnchors } from "@/lib/scroll-anchor";
5
6/**
7 * Id of the `[data-scroll-anchor]` element the reader is looking at in a
8 * scroll container: the one crossing a line `lineRatio` of the way down the
9 * view (or the last one, once scrolled to the end). `null` above the first.
10 */
11export function useAnchorInView(
12 containerRef: RefObject<HTMLElement | null>,
13 lineRatio = 0.3,
14): string | null {
15 const [anchorId, setAnchorId] = useState<string | null>(null);
16
17 useEffect(() => {
18 const container = containerRef.current;
19 if (!container) return;
20
21 let frame = 0;
22 const update = () => {
23 frame = 0;
24 const atEnd =
25 container.scrollTop > 0 &&
26 container.scrollTop >= container.scrollHeight - container.clientHeight - 1;
27 const line = atEnd ? container.clientHeight : container.clientHeight * lineRatio;
28 setAnchorId(anchorAt(measureAnchors(container), line)?.id ?? null);
29 };
30 const scheduleUpdate = () => {
31 if (!frame) frame = requestAnimationFrame(update);
32 };
33
34 update();
35 container.addEventListener("scroll", scheduleUpdate, { passive: true });
36 const resizeObserver = new ResizeObserver(scheduleUpdate);
37 resizeObserver.observe(container);
38 return () => {
39 cancelAnimationFrame(frame);
40 container.removeEventListener("scroll", scheduleUpdate);
41 resizeObserver.disconnect();
42 };
43 }, [containerRef, lineRatio]);
44
45 return anchorId;
46}