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

use-follow-active-section.ts

92 lines3.8 KB

1import { useEffect, useRef } from "react";
2import type { RefObject } from "react";
3​
4import { useMediaQuery } from "@/hooks/use-media-query";
5​
6import { useActiveSection } from "./guide-store";
7​
8/** After the reader scrolls the guide, leave it alone for this long. */
9export const READER_SCROLL_COOLDOWN_MS = 2000;
10​
11const SCROLL_KEYS = new Set(["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "]);
12​
13/**
14 * Whether enough of a section is on screen that the reader can already see
15 * it light up: at least 30% of the section, or of the view if the section is
16 * taller than that.
17 */
18export function isSectionInView(
19 section: { top: number; bottom: number },
20 view: { top: number; bottom: number },
21): boolean {
22 const visible = Math.min(section.bottom, view.bottom) - Math.max(section.top, view.top);
23 const needed = Math.min(section.bottom - section.top, view.bottom - view.top) * 0.3;
24 return visible > 0 && visible >= needed;
26​
27/**
28 * Scrolls the guide to the highlighted section, without fighting the reader:
29 * not while they're scrolling (or just were), and not when the section is
30 * already on screen.
31 *
32 * While `paused` (on phones: the app sheet is open over the guide) the
33 * highlight changes but nothing scrolls; once it's unpaused, the guide
34 * scrolls to the section if the highlight moved in the meantime.
35 */
36export function useFollowActiveSection(scrollRef: RefObject<HTMLElement | null>, paused = false) {
37 const activeSectionId = useActiveSection();
38 const reduceMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
39 const readerScrolledAt = useRef(Number.NEGATIVE_INFINITY);
40 // The highlight we last acted on (scrolled to, or chose not to).
41 const followedId = useRef<string | null>(null);
42 const wasPaused = useRef(paused);
43​
44 useEffect(() => {
45 const container = scrollRef.current;
46 if (!container) return;
47 const markScrolling = () => {
48 readerScrolledAt.current = performance.now();
49 };
50 const onKeyDown = (event: KeyboardEvent) => {
51 if (SCROLL_KEYS.has(event.key)) markScrolling();
52 };
53 // A press on the container itself (not its content) is a press on its scrollbar.
54 const onPointerDown = (event: PointerEvent) => {
55 if (event.target === container) markScrolling();
56 };
57 container.addEventListener("wheel", markScrolling, { passive: true });
58 container.addEventListener("touchmove", markScrolling, { passive: true });
59 container.addEventListener("keydown", onKeyDown);
60 container.addEventListener("pointerdown", onPointerDown);
61 return () => {
62 container.removeEventListener("wheel", markScrolling);
63 container.removeEventListener("touchmove", markScrolling);
64 container.removeEventListener("keydown", onKeyDown);
65 container.removeEventListener("pointerdown", onPointerDown);
66 };
67 }, [scrollRef]);
68​
69 useEffect(() => {
70 const justUnpaused = wasPaused.current && !paused;
71 wasPaused.current = paused;
72 if (paused || !activeSectionId || activeSectionId === followedId.current) return;
73 followedId.current = activeSectionId;
74​
75 const follow = () => {
76 const container = scrollRef.current;
77 const section = document.getElementById(activeSectionId);
78 if (!container || !section || !container.contains(section)) return;
79 if (performance.now() - readerScrolledAt.current < READER_SCROLL_COOLDOWN_MS) return;
80 if (isSectionInView(section.getBoundingClientRect(), container.getBoundingClientRect())) {
81 return;
82 }
83 section.scrollIntoView({ behavior: reduceMotion ? "auto" : "smooth", block: "start" });
84 };
85​
86 // Coming back from the sheet: let the guide settle where it was first, so
87 // the reader sees it move to the section.
88 if (!justUnpaused) return follow();
89 const timer = window.setTimeout(follow, 350);
90 return () => window.clearTimeout(timer);
91 }, [activeSectionId, paused, reduceMotion, scrollRef]);