Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

use-reading-position.ts

35 lines1.2 KB

1import { useLayoutEffect } from "react";
2import type { RefObject } from "react";
3​
4import { captureScrollAnchor, restoreScrollAnchor } from "@/lib/scroll-anchor";
5import type { ScrollAnchor } from "@/lib/scroll-anchor";
6​
7/**
8 * Where the reader is in the guide, kept across layouts. The split layout and
9 * the small-screen layout each have their own guide scroll container; when
10 * the window crosses the breakpoint the new one opens at the same section,
11 * the same distance from the top.
12 */
13let readingPosition: ScrollAnchor | null = null;
14​
15export function useReadingPosition(scrollRef: RefObject<HTMLElement | null>) {
16 useLayoutEffect(() => {
17 const container = scrollRef.current;
18 if (!container) return;
19 if (readingPosition) restoreScrollAnchor(container, readingPosition);
20​
21 let frame = 0;
22 const save = () => {
23 frame = 0;
24 readingPosition = captureScrollAnchor(container);
25 };
26 const onScroll = () => {
27 if (!frame) frame = requestAnimationFrame(save);
28 };
29 container.addEventListener("scroll", onScroll, { passive: true });
30 return () => {
31 container.removeEventListener("scroll", onScroll);
32 cancelAnimationFrame(frame);
33 };
34 }, [scrollRef]);