Skip to content
Source
Sign inSign up
samwillis/hackernews-realtime
Open History to see the last commit

use-live-list.ts

280 lines9.0 KB

1"use client";
2import { useEffect, useLayoutEffect, useRef, useState } from "react";
3import { markTransitionVisible, rectVisible } from "./timeline-visibility";
4import {
5 rowChanges,
6 HIGHLIGHT_MS,
7 type IdentifiedRow,
8 type RowChange,
9} from "@/lib/changes";
10type Position = {
11 top: number;
12 height: number;
13 padding: string;
14 visible: boolean;
15};
16export function useLiveList<T extends IdentifiedRow>(
17 initialRows: readonly T[],
18 incoming: readonly T[],
19 sort: (rows: readonly T[]) => T[],
20 fields: readonly (keyof T & string)[],
21 paused: boolean,
22 highlight: boolean,
23 initialNow: number,
24) {
25 const [state, setState] = useState(() => ({
26 rows: sort(initialRows),
27 changes: new Map<number, RowChange>(),
28 appliedAt: initialNow,
29 }));
30 const prior = useRef(state.rows);
31 const changes = useRef(state.changes);
32 const nodes = useRef(new Map<number, HTMLElement>());
33 const layoutAnimations = useRef(new Set<Animation>());
34 const colorAnimations = useRef(new Set<Animation>());
35 const lastColor = useRef(new Map<number, number>());
36 const wasPaused = useRef(false);
37 const pending = useRef<{
38 before: Map<number, Position>;
39 entering: Set<number>;
40 animate: boolean;
41 } | null>(null);
42 const cancelLayout = () => {
43 layoutAnimations.current.forEach((animation) => animation.cancel());
44 layoutAnimations.current.clear();
45 };
46 useEffect(() => {
47 if (paused) {
48 wasPaused.current = true;
49 cancelLayout();
50 colorAnimations.current.forEach((animation) => animation.cancel());
51 colorAnimations.current.clear();
52 changes.current = new Map();
53 setState((current) => ({ ...current, changes: new Map() }));
54 return;
55 }
56 const rows = sort(incoming);
57 const resuming = wasPaused.current;
58 wasPaused.current = false;
59 const animate = highlight && !resuming;
60 if (!animate) {
61 colorAnimations.current.forEach((animation) => animation.cancel());
62 colorAnimations.current.clear();
63 }
64 const before = new Map<number, Position>();
65 for (const [id, node] of nodes.current)
66 if (node.getClientRects().length) {
67 const rect = node.getBoundingClientRect();
68 before.set(id, {
69 top: rect.top + window.scrollY,
70 height: rect.height,
71 padding: getComputedStyle(node).paddingBottom,
72 visible: rectVisible(rect),
73 });
74 }
75 cancelLayout();
76 const nextIndex = new Map(rows.map((row, index) => [row.item_id, index]));
77 markTransitionVisible(
78 prior.current
79 .filter((row, index) => {
80 return (
81 nextIndex.get(row.item_id) !== index &&
82 before.get(row.item_id)?.visible
83 );
84 })
85 .map((row) => row.item_id),
86 );
87 const now = Date.now();
88 const updated = animate
89 ? rowChanges(prior.current, rows, fields, changes.current, now)
90 : new Map<number, RowChange>();
91 const oldIds = new Set(prior.current.map((row) => row.item_id));
92 pending.current = {
93 before,
94 animate,
95 entering: new Set(
96 rows
97 .filter((row) => !oldIds.has(row.item_id))
98 .map((row) => row.item_id),
99 ),
100 };
101 if (process.env.NEXT_PUBLIC_MEASURE_REALTIME === "1" && !resuming) {
102 const old = new Map(prior.current.map((row) => [row.item_id, row]));
103 for (const row of rows) {
104 const oldRow = old.get(row.item_id) as
105 | (T & { committed_at?: string })
106 | undefined;
107 const current = row as T & { committed_at?: string };
108 if (
109 oldRow &&
110 current.committed_at &&
111 oldRow.committed_at !== current.committed_at
112 )
113 console.debug(
114 "hn_realtime_applied",
115 JSON.stringify({
116 id: row.item_id,
117 committedAt: current.committed_at,
118 appliedAt: now,
119 latencyMs: now - Date.parse(current.committed_at),
120 }),
121 );
122 }
123 }
124 prior.current = rows;
125 changes.current = updated;
126 setState({ rows, changes: updated, appliedAt: now });
127 }, [incoming, paused, highlight, sort, fields]);
128 useEffect(() => {
129 if (!state.changes.size) return;
130 const stamps = [...state.changes.values()].flatMap((change) =>
131 [change.entered, change.moved, ...Object.values(change.fields)].filter(
132 (stamp): stamp is number => stamp !== undefined,
133 ),
134 );
135 const timeout = setTimeout(
136 () => {
137 setState((current) => {
138 const remaining = rowChanges(
139 current.rows,
140 current.rows,
141 [],
142 current.changes,
143 Date.now(),
144 );
145 changes.current = remaining;
146 return { ...current, changes: remaining };
147 });
148 },
149 Math.max(1, Math.min(...stamps) + HIGHLIGHT_MS - Date.now()),
150 );
151 return () => clearTimeout(timeout);
152 }, [state.changes]);
153 useLayoutEffect(() => {
154 const update = pending.current;
155 pending.current = null;
156 if (update) {
157 const crossing: number[] = [];
158 for (const [id, node] of nodes.current) {
159 const full = node.getBoundingClientRect();
160 const old = update.before.get(id);
161 if (
162 update.entering.has(id) ||
163 (old &&
164 (Math.abs(old.top - window.scrollY - full.top) > 0.5 ||
165 Math.abs(old.height - full.height) > 0.5))
166 ) {
167 const top = Math.min(
168 full.top,
169 old ? old.top - window.scrollY : full.top,
170 );
171 const bottom = Math.max(
172 full.bottom,
173 old ? old.top - window.scrollY + old.height : full.bottom,
174 );
175 if (rectVisible({ top, bottom, left: full.left, right: full.right }))
176 crossing.push(id);
177 }
178 }
179 markTransitionVisible(crossing);
180 }
181 if (
182 !update?.animate ||
183 window.matchMedia("(prefers-reduced-motion: reduce)").matches
184 )
185 return;
186 const animate = (node: HTMLElement, frames: Keyframe[]) => {
187 const animation = node.animate(frames, {
188 duration: 320,
189 easing: "cubic-bezier(.2,.7,.2,1)",
190 fill: "both",
191 });
192 animation.currentTime = 0;
193 layoutAnimations.current.add(animation);
194 void animation.finished.then(
195 () => {
196 animation.cancel();
197 layoutAnimations.current.delete(animation);
198 },
199 () => {},
200 );
201 };
202 // Collapse entering rows before measuring destinations. Their expansion then
203 // moves neighbours naturally; FLIP only accounts for the remaining reorder.
204 for (const [id, node] of nodes.current)
205 if (node.getClientRects().length) {
206 const full = node.getBoundingClientRect();
207 const old = update.before.get(id);
208 if (
209 update.entering.has(id) ||
210 (old && Math.abs(old.height - full.height) > 0.5)
211 )
212 animate(node, [
213 {
214 height: `${old?.height ?? 0}px`,
215 paddingBottom: old?.padding ?? "0px",
216 opacity: old ? 1 : 0,
217 overflow: "hidden",
218 },
219 {
220 height: `${full.height}px`,
221 paddingBottom: getComputedStyle(node).paddingBottom,
222 opacity: 1,
223 overflow: "hidden",
224 },
225 ]);
226 }
227 for (const [id, node] of nodes.current)
228 if (node.getClientRects().length) {
229 const old = update.before.get(id);
230 if (!old) continue;
231 const delta =
232 old.top - (node.getBoundingClientRect().top + window.scrollY);
233 if (Math.abs(delta) > 0.5)
234 animate(node, [
235 { transform: `translateY(${delta}px)` },
236 { transform: "translateY(0)" },
237 ]);
238 }
239 }, [state.rows]);
240 useLayoutEffect(() => {
241 if (!highlight) {
242 colorAnimations.current.forEach((animation) => animation.cancel());
243 colorAnimations.current.clear();
244 return;
245 }
246 for (const [id, change] of state.changes) {
247 const stamp = Math.max(change.entered ?? 0, change.moved ?? 0);
248 const node = nodes.current.get(id);
249 if (!stamp || !node || lastColor.current.get(id) === stamp) continue;
250 lastColor.current.set(id, stamp);
251 if (window.matchMedia("(prefers-reduced-motion: reduce)").matches)
252 continue;
253 const animation = node.animate(
254 [{ backgroundColor: "#ffe6b3" }, { backgroundColor: "transparent" }],
255 { duration: HIGHLIGHT_MS },
256 );
257 colorAnimations.current.add(animation);
258 void animation.finished.then(
259 () => colorAnimations.current.delete(animation),
260 () => {},
261 );
262 }
263 for (const id of lastColor.current.keys())
264 if (!nodes.current.has(id)) lastColor.current.delete(id);
265 }, [state.changes, highlight]);
266 useEffect(
267 () => () => {
268 layoutAnimations.current.forEach((animation) => animation.cancel());
269 colorAnimations.current.forEach((animation) => animation.cancel());
270 },
271 [],
272 );
273 return {
274 ...state,
275 register: (id: number, node: HTMLElement | null) => {
276 if (node) nodes.current.set(id, node);
277 else nodes.current.delete(id);
278 },
279 };