Open History to see the last commit
1import { useEffect, useId, useRef } from "react";
2
3export const LIVE_REFRESH_MIN_INTERVAL_MS = 10_000;
4
5export const LIVE_REFRESH_INTERVAL_MS = 5 * 60_000;
6
7export const LIVE_REFRESH_IDLE_AFTER_MS = 6 * 60_000;
8
9export function shouldLiveRefresh(input: {
10 readonly visible: boolean;
11 readonly now: number;
12 readonly lastRefreshedAt: number;
13}): boolean {
14 return input.visible && input.now - input.lastRefreshedAt >= LIVE_REFRESH_MIN_INTERVAL_MS;
15}
16
17/**
18 * A view nobody has read this session is left alone: mounting it starts its own read, and
19 * refreshing on top of that cancels the request in flight and pays for the same answer twice.
20 */
21export function shouldRefreshOnArrival(input: {
22 readonly visible: boolean;
23 readonly now: number;
24 readonly lastRefreshedAt: number | undefined;
25}): boolean {
26 return (
27 input.lastRefreshedAt !== undefined &&
28 shouldLiveRefresh({ ...input, lastRefreshedAt: input.lastRefreshedAt })
29 );
30}
31
32export function shouldRefreshOnInterval(input: {
33 readonly visible: boolean;
34 readonly now: number;
35 readonly lastRefreshedAt: number;
36 readonly lastInteractedAt: number;
37}): boolean {
38 return (
39 input.now - input.lastInteractedAt < LIVE_REFRESH_IDLE_AFTER_MS && shouldLiveRefresh(input)
40 );
41}
42
43/**
44 * When each view last read, kept outside React because a mount is exactly what it has to outlive:
45 * a reader who navigates away and straight back mounts a fresh hook, and a timestamp that started
46 * at zero would call that first read due.
47 */
48const lastRefreshedAtByView = new Map<string, number>();
49
50let lastInteractedAt = 0;
51const interactionWatchers = new Set<() => void>();
52const INTERACTION_EVENTS = ["pointerdown", "pointermove", "keydown", "wheel"] as const;
53const noteInteraction = () => {
54 const now = Date.now();
55 const wasIdle = now - lastInteractedAt >= LIVE_REFRESH_IDLE_AFTER_MS;
56 lastInteractedAt = now;
57 if (wasIdle) for (const resume of interactionWatchers) resume();
58};
59
60function watchInteraction(resume: () => void): () => void {
61 if (interactionWatchers.size === 0) {
62 lastInteractedAt = Date.now();
63 for (const event of INTERACTION_EVENTS) {
64 document.addEventListener(event, noteInteraction, { passive: true });
65 }
66 }
67 interactionWatchers.add(resume);
68 return () => {
69 interactionWatchers.delete(resume);
70 if (interactionWatchers.size > 0) return;
71 for (const event of INTERACTION_EVENTS) {
72 document.removeEventListener(event, noteInteraction);
73 }
74 };
75}
76
77export function useLiveRefresh(
78 refresh: (() => void) | null,
79 options: {
80 readonly enabled?: boolean;
81 readonly key?: string;
82 readonly intervalMs?: number;
83 } = {},
84): void {
85 const { enabled = true, key, intervalMs = LIVE_REFRESH_INTERVAL_MS } = options;
86 // Held in a ref so a caller can pass a fresh closure every render without re-arming the
87 // listeners, which would otherwise refresh on every render that changed anything at all.
88 const latest = useRef(refresh);
89 latest.current = refresh;
90 const fallbackViewId = useId();
91 const viewId = key ?? fallbackViewId;
92
93 useEffect(() => {
94 if (!enabled) return;
95 const read = (now: number) => {
96 if (latest.current === null) return;
97 lastRefreshedAtByView.set(viewId, now);
98 latest.current();
99 };
100 const visible = () => document.visibilityState === "visible";
101 const onArrival = () => {
102 const now = Date.now();
103 if (now - lastInteractedAt >= LIVE_REFRESH_IDLE_AFTER_MS) return;
104 const lastRefreshedAt = lastRefreshedAtByView.get(viewId);
105 if (lastRefreshedAt === undefined) {
106 lastRefreshedAtByView.set(viewId, now);
107 return;
108 }
109 if (shouldRefreshOnArrival({ visible: visible(), now, lastRefreshedAt })) read(now);
110 };
111 const onInterval = () => {
112 const now = Date.now();
113 const lastRefreshedAt = lastRefreshedAtByView.get(viewId) ?? now;
114 if (shouldRefreshOnInterval({ visible: visible(), now, lastRefreshedAt, lastInteractedAt })) {
115 read(now);
116 }
117 };
118
119 let timer: ReturnType<typeof setInterval> | undefined;
120 const syncTimer = () => {
121 clearInterval(timer);
122 timer = visible() ? setInterval(onInterval, intervalMs) : undefined;
123 };
124 const onVisibilityChange = () => {
125 onArrival();
126 syncTimer();
127 };
128
129 const stopWatchingInteraction = watchInteraction(() => {
130 onArrival();
131 syncTimer();
132 });
133 onArrival();
134 syncTimer();
135 window.addEventListener("focus", onArrival);
136 document.addEventListener("visibilitychange", onVisibilityChange);
137 return () => {
138 clearInterval(timer);
139 window.removeEventListener("focus", onArrival);
140 document.removeEventListener("visibilitychange", onVisibilityChange);
141 stopWatchingInteraction();
142 };
143 }, [enabled, viewId, intervalMs]);
144}