Open History to see the last commit
1import type { HighlightScheme } from "../../lib/highlights";
2
3import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
4import { AsyncResult } from "effect/reactivity";
5import { useCallback, useEffect, useRef, useState } from "react";
6
7import {
8 highlightNativeReviewDiffVisibleRows,
9 type NativeReviewDiffHighlightChunk,
10} from "../diffs/nativeReviewDiffHighlighter";
11import type { NativeReviewDiffRow } from "../diffs/nativeReviewDiffSurface";
12import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
13import { diffHighlightTraceId, traceDiffHighlight } from "../diffs/nativeReviewDiffTrace";
14
15import {
16 createReviewDiffHighlightScheduler,
17 type NativeReviewVisibleRange,
18} from "./reviewDiffHighlightScheduler";
19
20function createEmptyTokenPatch(resetKey: string): string {
21 return JSON.stringify({ resetKey, tokensByRowId: {} });
22}
23
24export function useNativeReviewDiffHighlighting(input: {
25 readonly files: ReadonlyArray<NativeReviewDiffFile>;
26 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
27 readonly scheme: HighlightScheme;
28 readonly collapsedFileIds: ReadonlySet<string>;
29 readonly resetKey: string;
30 readonly enabled: boolean;
31}) {
32 const { collapsedFileIds, enabled, files, resetKey, rows, scheme } = input;
33 const highlightedRowIdsRef = useRef<Set<string>>(new Set());
34 const viewportScope = `${enabled}:${resetKey}:${rows.length}`;
35 const [viewport, setViewport] = useState<{
36 scope: string;
37 range: NativeReviewVisibleRange | null;
38 }>(() => ({ scope: viewportScope, range: null }));
39 const visibleChunkIndexRef = useRef(0);
40 // Keep undelivered chunks, rather than repeatedly serializing every highlighted row.
41 const pendingPatchesRef = useRef<
42 Array<{ resetKey: string; chunkIndex: number; json: string; rowIds: string[] }>
43 >([]);
44 const [tokensPatchJson, setTokensPatchJson] = useState(() => createEmptyTokenPatch(resetKey));
45 const [scheduler] = useState(() =>
46 createReviewDiffHighlightScheduler((range) =>
47 setViewport((current) => ({ ...current, range })),
48 ),
49 );
50
51 useEffect(() => {
52 traceDiffHighlight("viewport-reset", {
53 reset: diffHighlightTraceId(resetKey),
54 enabled,
55 rows: rows.length,
56 });
57 const previousRange = scheduler.reset();
58 highlightedRowIdsRef.current = new Set();
59 pendingPatchesRef.current = [];
60 setViewport({ scope: viewportScope, range: null });
61 setTokensPatchJson(createEmptyTokenPatch(resetKey));
62 // A token reset need not produce another native range event. Reuse only an
63 // observed viewport, with the same coalescing that lets a new jump replace it.
64 if (previousRange) scheduler.update(previousRange);
65 return () => scheduler.cancel();
66 }, [enabled, resetKey, rows.length, scheduler, viewportScope]);
67
68 useEffect(() => {
69 if (!enabled || rows.length === 0 || !viewport.range || viewport.scope !== viewportScope) {
70 return;
71 }
72
73 const abortController = new AbortController();
74 const requestRange = viewport.range;
75 const generation = diffHighlightTraceId(abortController);
76 const reset = diffHighlightTraceId(resetKey);
77 traceDiffHighlight("viewport-start", {
78 generation,
79 reset,
80 first: requestRange.firstRowIndex,
81 last: requestRange.lastRowIndex,
82 pending: pendingPatchesRef.current.length,
83 });
84
85 const enqueueChunk = (result: NativeReviewDiffHighlightChunk) => {
86 if (abortController.signal.aborted || result.rowCount === 0) return;
87 const retryableRowIds = new Set(result.retryableRowIds);
88 const rowIds = Object.keys(result.tokensByRowId);
89 for (const rowId of rowIds) {
90 if (!retryableRowIds.has(rowId)) highlightedRowIdsRef.current.add(rowId);
91 }
92 const chunkIndex = visibleChunkIndexRef.current++;
93 const json = JSON.stringify({
94 resetKey,
95 chunkIndex,
96 fileId: "visible",
97 filePath: "visible rows",
98 language: "diff",
99 lineCount: result.rowCount,
100 durationMs: result.durationMs,
101 tokensByRowId: result.tokensByRowId,
102 });
103 pendingPatchesRef.current.push({ resetKey, chunkIndex, json, rowIds });
104 traceDiffHighlight("patch-queued", {
105 generation,
106 reset,
107 chunk: chunkIndex,
108 rows: rowIds.length,
109 pending: pendingPatchesRef.current.length,
110 });
111 if (pendingPatchesRef.current.length === 1) setTokensPatchJson(json);
112 };
113
114 void (async () => {
115 // Deliver viewport tokens before offscreen source fetches can delay them.
116 let retryableViewportRowIds: ReadonlyArray<string> = [];
117 for (const overscanRows of [0, undefined]) {
118 const deliveredRowIds = new Set<string>();
119 const settled = await settlePromise(() =>
120 highlightNativeReviewDiffVisibleRows({
121 files,
122 rows,
123 scheme,
124 collapsedFileIds,
125 firstRowIndex: requestRange.firstRowIndex,
126 lastRowIndex: requestRange.lastRowIndex,
127 overscanRows,
128 alreadyHighlightedRowIds:
129 retryableViewportRowIds.length > 0
130 ? new Set([...highlightedRowIdsRef.current, ...retryableViewportRowIds])
131 : highlightedRowIdsRef.current,
132 signal: abortController.signal,
133 onChunk: (chunk) => {
134 for (const rowId of Object.keys(chunk.tokensByRowId)) deliveredRowIds.add(rowId);
135 enqueueChunk(chunk);
136 },
137 }),
138 );
139 if (abortController.signal.aborted) return;
140 if (AsyncResult.isFailure(settled)) {
141 console.warn("[review-sheet] native visible highlight failed", {
142 error: squashAtomCommandFailure(settled),
143 resetKey,
144 scheme,
145 collapsedFileIds,
146 firstRowIndex: requestRange.firstRowIndex,
147 lastRowIndex: requestRange.lastRowIndex,
148 });
149 return;
150 }
151 const result = settled.value;
152 traceDiffHighlight("viewport-result", {
153 generation,
154 reset,
155 overscan: overscanRows ?? 160,
156 rows: result.rowCount,
157 retryable: result.retryableRowIds.length,
158 });
159 if (result.rowCount === 0) continue;
160 retryableViewportRowIds = result.retryableRowIds;
161
162 const remaining = Object.fromEntries(
163 Object.entries(result.tokensByRowId).filter(([rowId]) => !deliveredRowIds.has(rowId)),
164 );
165 enqueueChunk({
166 ...result,
167 tokensByRowId: remaining,
168 rowCount: Object.keys(remaining).length,
169 });
170 }
171 })();
172
173 return () => {
174 traceDiffHighlight("viewport-abort", { generation, reset });
175 abortController.abort();
176 };
177 }, [collapsedFileIds, enabled, files, resetKey, rows, scheme, viewport, viewportScope]);
178
179 const acknowledgeTokenPatch = useCallback((payload: Readonly<Record<string, unknown>>) => {
180 const pending = pendingPatchesRef.current;
181 const head = pending[0];
182 traceDiffHighlight("patch-ack", {
183 reset: diffHighlightTraceId(payload.resetKey),
184 chunk: typeof payload.chunkIndex === "number" ? payload.chunkIndex : -1,
185 matches:
186 !!head && payload.resetKey === head.resetKey && payload.chunkIndex === head.chunkIndex,
187 pending: pending.length,
188 });
189 if (!head || payload.resetKey !== head.resetKey || payload.chunkIndex !== head.chunkIndex)
190 return;
191 pending.shift();
192 setTokensPatchJson(pending[0]?.json ?? createEmptyTokenPatch(head.resetKey));
193 }, []);
194
195 const rejectTokenPatch = useCallback(
196 (payload: Readonly<Record<string, unknown>>) => {
197 const head = pendingPatchesRef.current[0];
198 traceDiffHighlight("patch-rejected", {
199 reset: diffHighlightTraceId(payload.resetKey),
200 chunk: typeof payload.chunkIndex === "number" ? payload.chunkIndex : -1,
201 matches:
202 !!head && payload.resetKey === head.resetKey && payload.chunkIndex === head.chunkIndex,
203 });
204 if (!head || payload.resetKey !== head.resetKey || payload.chunkIndex !== head.chunkIndex)
205 return;
206 for (const rowId of head.rowIds) highlightedRowIdsRef.current.delete(rowId);
207 // Retry these rows only on a later viewport request, not in a failure loop.
208 acknowledgeTokenPatch(payload);
209 },
210 [acknowledgeTokenPatch],
211 );
212
213 return {
214 rejectTokenPatch,
215 acknowledgeTokenPatch,
216 tokensPatchJson,
217 updateVisibleRange: scheduler.update,
218 };
219}