File size: 3,504 Bytes
b4afabc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import { useLayoutEffect, useRef, useState } from "react";

/** Whether this element's content should be showing.
 *
 * Once revealed it stays revealed: a section that fades in again every time it
 * passes the viewport is a page that will not sit still to be read.
 *
 * Three states, and the order of them is the point:
 *
 *   idle    - the first render, and the only one that happens without
 *             JavaScript having had a say. It is VISIBLE. Content that starts
 *             hidden and waits for a callback is content that renders blank
 *             when the callback never comes, and the rail's five steps did
 *             exactly that in a scrolled capture.
 *   hidden  - armed. Set in a layout effect, which runs after the DOM is
 *             built and before the browser paints, so the idle state is never
 *             seen and there is no flash.
 *   shown   - revealed, with the transition the caller wrote.
 *
 * Reveals immediately, with no animation at all, when the reader has asked
 * for less motion.
 *
 * The plain geometry check beside the observer is not redundant: an observer
 * that never delivers its first callback would leave the section hidden for
 * ever. A rect against the viewport cannot fail to answer, so it is what
 * actually decides; the observer only means the answer usually arrives
 * without waiting for a scroll event.
 */
export function useInView<T extends HTMLElement>(margin = 0.12) {
  const ref = useRef<T | null>(null);
  const [phase, setPhase] = useState<"idle" | "hidden" | "shown">("idle");

  useLayoutEffect(() => {
    const node = ref.current;
    const still =
      typeof matchMedia === "function" &&
      matchMedia("(prefers-reduced-motion: reduce)").matches;

    if (!node || still) {
      setPhase("shown");
      return;
    }

    let settled = false;
    const finish = () => {
      if (settled) return;
      settled = true;
      setPhase("shown");
      observer?.disconnect();
      removeEventListener("scroll", check);
      removeEventListener("resize", check);
    };

    const check = () => {
      const box = node.getBoundingClientRect();
      if (box.top < innerHeight * (1 - margin) && box.bottom > 0) finish();
    };

    const observer =
      typeof IntersectionObserver === "undefined"
        ? null
        : new IntersectionObserver(
            (entries) => {
              if (entries.some((e) => e.isIntersecting)) finish();
            },
            { rootMargin: `${-margin * 100}% 0px` },
          );

    setPhase("hidden");
    observer?.observe(node);
    addEventListener("scroll", check, { passive: true });
    addEventListener("resize", check);
    check();

    /* Nothing on this page may stay invisible because a callback did not
       arrive. Six seconds is far longer than a reader takes to scroll to the
       next section, so in practice this never fires; when it does, the worst
       outcome is a section that was already visible when it was reached. */
    const safety = setTimeout(finish, 6000);

    return () => {
      clearTimeout(safety);
      observer?.disconnect();
      removeEventListener("scroll", check);
      removeEventListener("resize", check);
    };
  }, [margin]);

  /* `open` is what the caller shows or hides. `arrived` is true only for the
     revealed state, so the caller can play the entrance keyframe then and not
     on a first render that was already visible. */
  return [ref, phase !== "hidden", phase === "shown"] as const;
}