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

useLiveRefresh.ts

143 lines4.7 KB

1import { useEffect, useEffectEvent, useId } 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;
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 );
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 );
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 };
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 // An effect event 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 runRefresh = useEffectEvent((viewId: string, now: number) => {
89 if (refresh === null) return;
90 lastRefreshedAtByView.set(viewId, now);
91 refresh();
92 });
93 const fallbackViewId = useId();
94 const viewId = key ?? fallbackViewId;
95​
96 useEffect(() => {
97 if (!enabled) return;
98 const read = (now: number) => runRefresh(viewId, now);
99 const visible = () => document.visibilityState === "visible";
100 const onArrival = () => {
101 const now = Date.now();
102 if (now - lastInteractedAt >= LIVE_REFRESH_IDLE_AFTER_MS) return;
103 const lastRefreshedAt = lastRefreshedAtByView.get(viewId);
104 if (lastRefreshedAt === undefined) {
105 lastRefreshedAtByView.set(viewId, now);
106 return;
107 }
108 if (shouldRefreshOnArrival({ visible: visible(), now, lastRefreshedAt })) read(now);
109 };
110 const onInterval = () => {
111 const now = Date.now();
112 const lastRefreshedAt = lastRefreshedAtByView.get(viewId) ?? now;
113 if (shouldRefreshOnInterval({ visible: visible(), now, lastRefreshedAt, lastInteractedAt })) {
114 read(now);
115 }
116 };
117​
118 let timer: ReturnType<typeof setInterval> | undefined;
119 const syncTimer = () => {
120 clearInterval(timer);
121 timer = visible() ? setInterval(onInterval, intervalMs) : undefined;
122 };
123 const onVisibilityChange = () => {
124 onArrival();
125 syncTimer();
126 };
127​
128 const stopWatchingInteraction = watchInteraction(() => {
129 onArrival();
130 syncTimer();
131 });
132 onArrival();
133 syncTimer();
134 window.addEventListener("focus", onArrival);
135 document.addEventListener("visibilitychange", onVisibilityChange);
136 return () => {
137 clearInterval(timer);
138 window.removeEventListener("focus", onArrival);
139 document.removeEventListener("visibilitychange", onVisibilityChange);
140 stopWatchingInteraction();
141 };
142 }, [enabled, viewId, intervalMs]);