Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useLiveRefresh.ts

182 lines7.6 KB

1/**
2 * Keeping what a reader is looking at true, whichever way they arrived at it.
3 *
4 * A pull request changes while nobody is looking at it — a push lands, a check finishes, somebody
5 * approves — and a view that only reads on mount shows yesterday's answer for as long as the tab
6 * stays open. Three moments deserve a read: arriving at the view, coming back to the window, and
7 * simply sitting on it while it is open. All three are the same policy, so they live in one hook
8 * rather than three; every one of them is bounded by the same minimum interval, so the moments
9 * arriving together still cost one read.
10 *
11 * Every read here shells out to a host's API from the server, so the policy is written to spend as
12 * little as it can get away with: the very first arrival at a view spends nothing, because the
13 * view's own first read is already on its way, and the interval stops as soon as the reader stops
14 * reading.
15 */
16import { useEffect, useId, useRef } from "react";
17​
18/** Long enough that alt-tabbing through windows does not become a request per tab stop. */
19export const LIVE_REFRESH_MIN_INTERVAL_MS = 10_000;
20​
21/** Slow enough to be cheap on the host, quick enough that a reader is not reading last minute. */
22export const LIVE_REFRESH_INTERVAL_MS = 60_000;
23​
24/**
25 * How long a showing window goes untouched before it stops reading. A window left open on a
26 * monitor nobody is sitting at is showing in every sense the browser knows about, and polling it
27 * until morning spends a night of somebody's rate limit on an answer nobody read. Their next
28 * click, key or scroll starts the interval up again.
29 */
30export const LIVE_REFRESH_IDLE_AFTER_MS = 5 * 60_000;
31​
32/**
33 * Whether a view should read again now. Separate from the hook because the rule is the whole of
34 * it: only while the window is actually showing, and not again straight away — a reader passing
35 * through three windows, or returning to a tab that missed an hour of ticks, is asking for one
36 * read, not one per thing that happened while they were away.
37 */
38export function shouldLiveRefresh(input: {
39 readonly visible: boolean;
40 readonly now: number;
41 readonly lastRefreshedAt: number;
42}): boolean {
43 return input.visible && input.now - input.lastRefreshedAt >= LIVE_REFRESH_MIN_INTERVAL_MS;
45​
46/**
47 * Whether arriving at a view should read it. A view nobody has read this session is left alone:
48 * mounting it starts its own read, and refreshing on top of that cancels the request in flight
49 * and pays for the same answer twice. Every later arrival is an ordinary refresh.
50 */
51export function shouldRefreshOnArrival(input: {
52 readonly visible: boolean;
53 readonly now: number;
54 readonly lastRefreshedAt: number | undefined;
55}): boolean {
56 return (
57 input.lastRefreshedAt !== undefined &&
58 shouldLiveRefresh({ ...input, lastRefreshedAt: input.lastRefreshedAt })
59 );
61​
62/**
63 * Whether the interval should read again. The same rule as any other read, plus the reader having
64 * been here recently enough for the answer to be for somebody.
65 */
66export function shouldRefreshOnInterval(input: {
67 readonly visible: boolean;
68 readonly now: number;
69 readonly lastRefreshedAt: number;
70 readonly lastInteractedAt: number;
71}): boolean {
72 return (
73 input.now - input.lastInteractedAt < LIVE_REFRESH_IDLE_AFTER_MS && shouldLiveRefresh(input)
74 );
76​
77/**
78 * When each view last read, kept outside React because a mount is exactly what it has to outlive:
79 * a reader who navigates away and straight back mounts a fresh hook, and a timestamp that started
80 * at zero would call that first read due. Keyed by whatever the caller calls the view, because two
81 * views on screen at once each owe their own reader an answer. Entries are one number and never
82 * pruned; there is one per view the session ever read.
83 */
84const lastRefreshedAtByView = new Map<string, number>();
85​
86/**
87 * When the reader last did anything. Shared rather than per view: a person is present in the
88 * window, not in one component of it. Only tracked while a live view is mounted, and the handler
89 * writes a number and nothing else, so a mousemove costs what a mousemove costs.
90 */
91let lastInteractedAt = 0;
92let interactionWatchers = 0;
93const INTERACTION_EVENTS = ["pointerdown", "pointermove", "keydown", "wheel"] as const;
94const noteInteraction = () => {
95 lastInteractedAt = Date.now();
96};
97​
98function watchInteraction(): () => void {
99 if (interactionWatchers === 0) {
100 // Arriving is itself the reader doing something, and it is what makes the first interval tick
101 // after a mount count.
102 lastInteractedAt = Date.now();
103 for (const event of INTERACTION_EVENTS) {
104 document.addEventListener(event, noteInteraction, { passive: true });
105 }
106 }
107 interactionWatchers += 1;
108 return () => {
109 interactionWatchers -= 1;
110 if (interactionWatchers > 0) return;
111 for (const event of INTERACTION_EVENTS) {
112 document.removeEventListener(event, noteInteraction);
113 }
114 };
116​
117export function useLiveRefresh(
118 refresh: (() => void) | null,
119 options: { readonly enabled?: boolean; readonly key?: string } = {},
120): void {
121 const { enabled = true, key } = options;
122 // Held in a ref so a caller can pass a fresh closure every render without re-arming the
123 // listeners, which would otherwise refresh on every render that changed anything at all.
124 const latest = useRef(refresh);
125 latest.current = refresh;
126 // A caller that shows a different thing in the same place — one panel, a pull request at a time —
127 // says which thing it is showing, so the reads it owes follow the thing rather than the slot.
128 // Anything else is one view per place it appears, which is what the tree position already means.
129 const fallbackViewId = useId();
130 const viewId = key ?? fallbackViewId;
131​
132 useEffect(() => {
133 if (!enabled) return;
134 const read = (now: number) => {
135 lastRefreshedAtByView.set(viewId, now);
136 latest.current?.();
137 };
138 const visible = () => document.visibilityState === "visible";
139 const onArrival = () => {
140 const now = Date.now();
141 const lastRefreshedAt = lastRefreshedAtByView.get(viewId);
142 if (lastRefreshedAt === undefined) {
143 // Nothing read yet, so nothing to refresh: the mount's own read is what fills this in.
144 lastRefreshedAtByView.set(viewId, now);
145 return;
146 }
147 if (shouldRefreshOnArrival({ visible: visible(), now, lastRefreshedAt })) read(now);
148 };
149 const onInterval = () => {
150 const now = Date.now();
151 const lastRefreshedAt = lastRefreshedAtByView.get(viewId) ?? now;
152 if (shouldRefreshOnInterval({ visible: visible(), now, lastRefreshedAt, lastInteractedAt })) {
153 read(now);
154 }
155 };
156​
157 let timer: ReturnType<typeof setInterval> | undefined;
158 // The timer exists only while the window is showing: a tab sitting behind another one should
159 // cost the host nothing, and the reads it missed collapse into the single one it makes on the
160 // way back. Nothing else moves the window between showing and hidden, so nothing else re-arms.
161 const syncTimer = () => {
162 clearInterval(timer);
163 timer = visible() ? setInterval(onInterval, LIVE_REFRESH_INTERVAL_MS) : undefined;
164 };
165 const onVisibilityChange = () => {
166 onArrival();
167 syncTimer();
168 };
169​
170 const stopWatchingInteraction = watchInteraction();
171 onArrival();
172 syncTimer();
173 window.addEventListener("focus", onArrival);
174 document.addEventListener("visibilitychange", onVisibilityChange);
175 return () => {
176 clearInterval(timer);
177 window.removeEventListener("focus", onArrival);
178 document.removeEventListener("visibilitychange", onVisibilityChange);
179 stopWatchingInteraction();
180 };
181 }, [enabled, viewId]);