Open History to see the last commit
1import { useEffect, useEffectEvent, useId } from "react";
2
3export const LIVE_REFRESH_MIN_INTERVAL_MS = 10_000;
4
5const LIVE_REFRESH_INTERVAL_MS = 5 * 60_000;
6
7const LIVE_REFRESH_IDLE_AFTER_MS = 6 * 60_000;
8
9function 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 */
21function 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
32function 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// Survive remounts so returning to a view does not make fresh reads look overdue.
44const lastRefreshedAtByView = new Map<string, number>();
45
46let lastInteractedAt = 0;
47const interactionWatchers = new Set<() => void>();
48const INTERACTION_EVENTS = ["pointerdown", "pointermove", "keydown", "wheel"] as const;
49const noteInteraction = () => {
50 const now = Date.now();
51 const wasIdle = now - lastInteractedAt >= LIVE_REFRESH_IDLE_AFTER_MS;
52 lastInteractedAt = now;
53 if (wasIdle) for (const resume of interactionWatchers) resume();
54};
55
56function watchInteraction(resume: () => void): () => void {
57 if (interactionWatchers.size === 0) {
58 lastInteractedAt = Date.now();
59 for (const event of INTERACTION_EVENTS) {
60 document.addEventListener(event, noteInteraction, { passive: true });
61 }
62 }
63 interactionWatchers.add(resume);
64 return () => {
65 interactionWatchers.delete(resume);
66 if (interactionWatchers.size > 0) return;
67 for (const event of INTERACTION_EVENTS) {
68 document.removeEventListener(event, noteInteraction);
69 }
70 };
71}
72
73export function useLiveRefresh(
74 /** Returns `false` when it skipped the read, so the skip starts no cooldown. */
75 refresh: (() => boolean | void) | null,
76 options: {
77 readonly enabled?: boolean;
78 readonly key?: string;
79 /** `null` turns off the periodic refresh, for a read too costly to repeat unasked. */
80 readonly intervalMs?: number | null;
81 /**
82 * Refresh every time the view is enabled unless it read within the floor, skipping the
83 * first-read rule: for a view that stays mounted while hidden, so its mount-time read can be
84 * long stale when shown.
85 */
86 readonly refreshOnShow?: boolean;
87 } = {},
88): void {
89 const {
90 enabled = true,
91 key,
92 intervalMs = LIVE_REFRESH_INTERVAL_MS,
93 refreshOnShow = false,
94 } = options;
95 const runRefresh = useEffectEvent((viewId: string, now: number) => {
96 if (refresh !== null && refresh() !== false) lastRefreshedAtByView.set(viewId, now);
97 });
98 const fallbackViewId = useId();
99 const viewId = key ?? fallbackViewId;
100
101 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refresh interval tied to page visibility and user interaction listeners
102 useEffect(() => {
103 if (!enabled) return;
104 const read = (now: number) => runRefresh(viewId, now);
105 const visible = () => document.visibilityState === "visible";
106 const onArrival = () => {
107 const now = Date.now();
108 if (now - lastInteractedAt >= LIVE_REFRESH_IDLE_AFTER_MS) return;
109 const lastRefreshedAt = lastRefreshedAtByView.get(viewId);
110 if (lastRefreshedAt === undefined) {
111 // A refreshOnShow view's first read may have been skipped; seeding here would fake one.
112 if (refreshOnShow) {
113 if (visible()) read(now);
114 } else lastRefreshedAtByView.set(viewId, now);
115 return;
116 }
117 if (shouldRefreshOnArrival({ visible: visible(), now, lastRefreshedAt })) read(now);
118 };
119 const onInterval = () => {
120 const now = Date.now();
121 const lastRefreshedAt = lastRefreshedAtByView.get(viewId) ?? now;
122 if (shouldRefreshOnInterval({ visible: visible(), now, lastRefreshedAt, lastInteractedAt })) {
123 read(now);
124 }
125 };
126
127 let timer: ReturnType<typeof setInterval> | undefined;
128 const syncTimer = () => {
129 clearInterval(timer);
130 timer = visible() && intervalMs !== null ? setInterval(onInterval, intervalMs) : undefined;
131 };
132 const onVisibilityChange = () => {
133 onArrival();
134 syncTimer();
135 };
136
137 const stopWatchingInteraction = watchInteraction(() => {
138 onArrival();
139 syncTimer();
140 });
141 if (refreshOnShow) {
142 const now = Date.now();
143 const lastRefreshedAt = lastRefreshedAtByView.get(viewId);
144 if (lastRefreshedAt === undefined || now - lastRefreshedAt >= LIVE_REFRESH_MIN_INTERVAL_MS) {
145 read(now);
146 }
147 } else onArrival();
148 syncTimer();
149 window.addEventListener("focus", onArrival);
150 document.addEventListener("visibilitychange", onVisibilityChange);
151 return () => {
152 clearInterval(timer);
153 window.removeEventListener("focus", onArrival);
154 document.removeEventListener("visibilitychange", onVisibilityChange);
155 stopWatchingInteraction();
156 };
157 }, [enabled, viewId, intervalMs, refreshOnShow]);
158}