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 // Effect on purpose: the native highlighter's token stream and the scheduler's timers must
52 // reset with the diff the view shows, and be cancelled when it unmounts.
53 useEffect(() => {
54 traceDiffHighlight("viewport-reset", {
55 reset: diffHighlightTraceId(resetKey),
56 enabled,
57 rows: rows.length,
58 });
59 const previousRange = scheduler.reset();
60 highlightedRowIdsRef.current = new Set();
61 pendingPatchesRef.current = [];
62 // oxlint-disable-next-line react/set-state-in-effect -- Resetting the native highlighter clears the viewport and token-patch snapshots together.
63 setViewport({ scope: viewportScope, range: null });
64 setTokensPatchJson(createEmptyTokenPatch(resetKey));
65 // A token reset need not produce another native range event. Reuse only an
66 // observed viewport, with the same coalescing that lets a new jump replace it.
67 if (previousRange) scheduler.update(previousRange);
68 return () => scheduler.cancel();
69 }, [enabled, resetKey, rows.length, scheduler, viewportScope]);
70
71 // Effect on purpose: abortable async highlighting tied to the visible range's lifetime.
72 useEffect(() => {
73 if (!enabled || rows.length === 0 || !viewport.range || viewport.scope !== viewportScope) {
74 return;
75 }
76
77 const abortController = new AbortController();
78 const requestRange = viewport.range;
79 const generation = diffHighlightTraceId(abortController);
80 const reset = diffHighlightTraceId(resetKey);
81 traceDiffHighlight("viewport-start", {
82 generation,
83 reset,
84 first: requestRange.firstRowIndex,
85 last: requestRange.lastRowIndex,
86 pending: pendingPatchesRef.current.length,
87 });
88
89 const enqueueChunk = (result: NativeReviewDiffHighlightChunk) => {
90 if (abortController.signal.aborted || result.rowCount === 0) return;
91 const retryableRowIds = new Set(result.retryableRowIds);
92 const rowIds = Object.keys(result.tokensByRowId);
93 for (const rowId of rowIds) {
94 if (!retryableRowIds.has(rowId)) highlightedRowIdsRef.current.add(rowId);
95 }
96 const chunkIndex = visibleChunkIndexRef.current++;
97 const json = JSON.stringify({
98 resetKey,
99 chunkIndex,
100 fileId: "visible",
101 filePath: "visible rows",
102 language: "diff",
103 lineCount: result.rowCount,
104 durationMs: result.durationMs,
105 tokensByRowId: result.tokensByRowId,
106 });
107 pendingPatchesRef.current.push({ resetKey, chunkIndex, json, rowIds });
108 traceDiffHighlight("patch-queued", {
109 generation,
110 reset,
111 chunk: chunkIndex,
112 rows: rowIds.length,
113 pending: pendingPatchesRef.current.length,
114 });
115 if (pendingPatchesRef.current.length === 1) setTokensPatchJson(json);
116 };
117
118 void (async () => {
119 // Deliver viewport tokens before offscreen source fetches can delay them.
120 let retryableViewportRowIds: ReadonlyArray<string> = [];
121 for (const overscanRows of [0, undefined]) {
122 const deliveredRowIds = new Set<string>();
123 const settled = await settlePromise(() =>
124 highlightNativeReviewDiffVisibleRows({
125 files,
126 rows,
127 scheme,
128 collapsedFileIds,
129 firstRowIndex: requestRange.firstRowIndex,
130 lastRowIndex: requestRange.lastRowIndex,
131 overscanRows,
132 alreadyHighlightedRowIds:
133 retryableViewportRowIds.length > 0
134 ? new Set([...highlightedRowIdsRef.current, ...retryableViewportRowIds])
135 : highlightedRowIdsRef.current,
136 signal: abortController.signal,
137 onChunk: (chunk) => {
138 for (const rowId of Object.keys(chunk.tokensByRowId)) deliveredRowIds.add(rowId);
139 enqueueChunk(chunk);
140 },
141 }),
142 );
143 if (abortController.signal.aborted) return;
144 if (AsyncResult.isFailure(settled)) {
145 console.warn("[review-sheet] native visible highlight failed", {
146 error: squashAtomCommandFailure(settled),
147 resetKey,
148 scheme,
149 collapsedFileIds,
150 firstRowIndex: requestRange.firstRowIndex,
151 lastRowIndex: requestRange.lastRowIndex,
152 });
153 return;
154 }
155 const result = settled.value;
156 traceDiffHighlight("viewport-result", {
157 generation,
158 reset,
159 overscan: overscanRows ?? 160,
160 rows: result.rowCount,
161 retryable: result.retryableRowIds.length,
162 });
163 if (result.rowCount === 0) continue;
164 retryableViewportRowIds = result.retryableRowIds;
165
166 const remaining = Object.fromEntries(
167 Object.entries(result.tokensByRowId).filter(([rowId]) => !deliveredRowIds.has(rowId)),
168 );
169 enqueueChunk({
170 ...result,
171 tokensByRowId: remaining,
172 rowCount: Object.keys(remaining).length,
173 });
174 }
175 })();
176
177 return () => {
178 traceDiffHighlight("viewport-abort", { generation, reset });
179 abortController.abort();
180 };
181 }, [collapsedFileIds, enabled, files, resetKey, rows, scheme, viewport, viewportScope]);
182
183 const acknowledgeTokenPatch = useCallback((payload: Readonly<Record<string, unknown>>) => {
184 const pending = pendingPatchesRef.current;
185 const head = pending[0];
186 traceDiffHighlight("patch-ack", {
187 reset: diffHighlightTraceId(payload.resetKey),
188 chunk: typeof payload.chunkIndex === "number" ? payload.chunkIndex : -1,
189 matches:
190 !!head && payload.resetKey === head.resetKey && payload.chunkIndex === head.chunkIndex,
191 pending: pending.length,
192 });
193 if (!head || payload.resetKey !== head.resetKey || payload.chunkIndex !== head.chunkIndex)
194 return;
195 pending.shift();
196 setTokensPatchJson(pending[0]?.json ?? createEmptyTokenPatch(head.resetKey));
197 }, []);
198
199 const rejectTokenPatch = useCallback(
200 (payload: Readonly<Record<string, unknown>>) => {
201 const head = pendingPatchesRef.current[0];
202 traceDiffHighlight("patch-rejected", {
203 reset: diffHighlightTraceId(payload.resetKey),
204 chunk: typeof payload.chunkIndex === "number" ? payload.chunkIndex : -1,
205 matches:
206 !!head && payload.resetKey === head.resetKey && payload.chunkIndex === head.chunkIndex,
207 });
208 if (!head || payload.resetKey !== head.resetKey || payload.chunkIndex !== head.chunkIndex)
209 return;
210 for (const rowId of head.rowIds) highlightedRowIdsRef.current.delete(rowId);
211 // Retry these rows only on a later viewport request, not in a failure loop.
212 acknowledgeTokenPatch(payload);
213 },
214 [acknowledgeTokenPatch],
215 );
216
217 return {
218 rejectTokenPatch,
219 acknowledgeTokenPatch,
220 tokensPatchJson,
221 updateVisibleRange: scheduler.update,
222 };
223}