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

nativeReviewDiffSurface.test.tsx

442 lines14.5 KB

1import {
2 act,
3 useLayoutEffect,
4 useImperativeHandle,
5 useRef,
6 useState,
7 type Ref,
8 type ReactNode,
9} from "react";
10import { createRoot } from "react-dom/client";
11import { expect, it, vi } from "vite-plus/test";
12import { AsyncResult } from "effect/reactivity";
13import * as Cause from "effect/Cause";
14import type { HighlightNativeReviewDiffVisibleRowsInput } from "./nativeReviewDiffHighlighter";
15import type { NativeReviewDiffViewProps } from "./nativeReviewDiffSurface";
16import type { NativeReviewDiffData } from "../review/nativeReviewDiffAdapter";
17​
18const mocks = vi.hoisted(() => ({
19 registrationFailures: 0,
20 tokenAccepted: true as boolean | undefined,
21 tokenCompletion: null as Promise<boolean> | null,
22 onDebug: undefined as NativeReviewDiffViewProps["onDebug"],
23 autoViewport: false,
24 rows: vi.fn(),
25 tokens: vi.fn(),
26 highlight: vi.fn(),
27}));
28​
29function RawView({
30 ref: nativeRef,
31 onDebug,
32 initialFileId,
33 contentResetKey,
34}: NativeReviewDiffViewProps & { ref: Ref<unknown> }) {
35 const [content, setContent] = useState({ resetKey: contentResetKey, rows: "" });
36 const rows = content.resetKey === contentResetKey ? content.rows : "";
37 const [tokenRowIds, setTokenRowIds] = useState<string[]>([]);
38 useLayoutEffect(() => {
39 mocks.onDebug = onDebug;
40 });
41 useImperativeHandle(nativeRef, () => ({
42 async setRowsJson(value: string) {
43 mocks.rows(value);
44 if (mocks.registrationFailures > 0) {
45 mocks.registrationFailures -= 1;
46 throw new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag");
47 }
48 setContent({ resetKey: contentResetKey, rows: value });
49 if (mocks.autoViewport) {
50 const decoded = JSON.parse(value) as NativeReviewDiffData["rows"];
51 onDebug?.({
52 nativeEvent: { message: "rows-decoded", rows: decoded.length },
53 } as unknown as Parameters<NonNullable<typeof onDebug>>[0]);
54 const index = decoded.findIndex(
55 (row) => row.kind === "file" && row.fileId === initialFileId,
56 );
57 onDebug?.({
58 nativeEvent: {
59 message: "visible-range",
60 firstRowIndex: Math.max(0, index),
61 lastRowIndex: Math.max(0, index) + 40,
62 totalRows: decoded.length,
63 },
64 } as unknown as Parameters<NonNullable<typeof onDebug>>[0]);
65 }
66 },
67 async scrollToFile() {},
68 async setTokensPatchJson(value: string) {
69 mocks.tokens(value);
70 const accepted = mocks.tokenCompletion ? await mocks.tokenCompletion : mocks.tokenAccepted;
71 if (accepted === true) {
72 const patch = JSON.parse(value);
73 setTokenRowIds((current) => [
74 ...new Set([...current, ...Object.keys(patch.tokensByRowId)]),
75 ]);
76 }
77 return accepted;
78 },
79 }));
80 return (
81 <div data-token-rows={tokenRowIds.join(",")}>
82 {rows ? "Rendered diff" : "Blank native surface"}
83 </div>
84 );
86​
87vi.mock("expo", () => ({ requireNativeView: () => RawView }));
88vi.mock("react-native", () => ({
89 View: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
90}));
91vi.mock("../../components/ui/EmptyState", () => ({
92 EmptyState: ({
93 title,
94 actionLabel,
95 onAction,
96 }: {
97 title: string;
98 actionLabel: string;
99 onAction: () => void;
100 }) => (
101 <div>
102 {title}
103 <button onClick={onAction}>{actionLabel}</button>
104 </div>
105 ),
106}));
107vi.mock("./nativeReviewDiffHighlighter", () => ({
108 highlightNativeReviewDiffVisibleRows: mocks.highlight,
109}));
110vi.mock("@t3tools/client-runtime/state/runtime", () => ({
111 settlePromise: async (execute: () => Promise<unknown>) => {
112 try {
113 return AsyncResult.success(await execute());
114 } catch (error) {
115 return AsyncResult.failure(Cause.die(error));
116 }
117 },
118 squashAtomCommandFailure: () => "tokenization failed",
119}));
120vi.mock("../review/nativeReviewDiffAdapter", () => ({ createNativeReviewDiffTheme: () => ({}) }));
121vi.mock("../settings/appearance/useAppearanceCodeSurface", () => ({
122 useAppearanceCodeSurface: () => ({ nativeReviewDiffStyle: {} }),
123}));
124vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
125 useAppearancePreferences: () => ({ themeAppearance: "light", themeId: "test" }),
126}));
127vi.mock("../../lib/useUniwindTheme", () => ({ useUniwindTheme: () => ({}) }));
128​
129import { resolveNativeReviewDiffView } from "./nativeReviewDiffSurface";
130import { useNativeReviewDiffBridge } from "../review/useNativeReviewDiffBridge";
131import {
132 handlePullRequestDiffDebugEvent,
133 pullRequestDiffInitialPosition,
134} from "../pull-requests/pullRequestDiffDebug";
135​
136function setup(integrated = false) {
137 vi.useFakeTimers();
138 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
139 mocks.registrationFailures = 0;
140 mocks.tokenAccepted = true;
141 mocks.tokenCompletion = null;
142 mocks.onDebug = undefined;
143 mocks.autoViewport = false;
144 mocks.rows.mockClear();
145 mocks.tokens.mockClear();
146 mocks.highlight
147 .mockReset()
148 .mockImplementation(async (input: HighlightNativeReviewDiffVisibleRowsInput) => {
149 const rowId = `r${input.firstRowIndex}`;
150 const tokensByRowId = input.alreadyHighlightedRowIds?.has(rowId)
151 ? {}
152 : { [rowId]: [{ content: "const", color: "#ff0000", fontStyle: null }] };
153 return {
154 rowCount: Object.keys(tokensByRowId).length,
155 durationMs: 0,
156 retryableRowIds: [],
157 tokensByRowId,
158 };
159 });
160 const frames = new Map<number, FrameRequestCallback>();
161 let nextFrame = 0;
162 const requestFrame = vi
163 .spyOn(globalThis, "requestAnimationFrame")
164 .mockImplementation((callback) => {
165 frames.set(++nextFrame, callback);
166 return nextFrame;
167 });
168 const cancelFrame = vi.spyOn(globalThis, "cancelAnimationFrame").mockImplementation((id) => {
169 if (id != null) frames.delete(id);
170 });
171 const errors = vi.spyOn(console, "error").mockImplementation(() => {});
172 const expo = Object.getOwnPropertyDescriptor(globalThis, "expo");
173 Object.defineProperty(globalThis, "expo", {
174 configurable: true,
175 value: { getViewConfig: () => ({}) },
176 });
177 const NativeDiff = resolveNativeReviewDiffView()!;
178 const container = document.createElement("div");
179 const root = createRoot(container);
180 let data: NativeReviewDiffData = {
181 rows: Array.from({ length: 1000 }, (_, index) =>
182 index === 999
183 ? { kind: "comment", id: `r${index}`, commentText: "Original comment" }
184 : index === 900
185 ? { kind: "file", id: `r${index}`, fileId: "last-file" }
186 : { kind: "line", id: `r${index}` },
187 ),
188 files: [],
189 additions: 0,
190 deletions: 0,
191 commentTargetsByRowId: new Map(),
192 rowIdByCommentLineId: new Map(),
193 };
194 const ids: string[] = [];
195 let collapsedFileIds: ReadonlyArray<string> = ids;
196 function PullRequestDiff({ targetFileId }: { targetFileId?: string }) {
197 const bridge = useNativeReviewDiffBridge({
198 threadKey: null,
199 sectionId: "pull-request:test:1:all",
200 diff: "test diff",
201 data,
202 collapsedFileIds,
203 viewedFileIds: ids,
204 selectedRowIds: ids,
205 canHighlight: true,
206 });
207 const nativeView = useRef(null);
208 const jumpStarted = useRef(true);
209 const onDebug: NonNullable<NativeReviewDiffViewProps["onDebug"]> = (event) =>
210 handlePullRequestDiffDebugEvent(event, {
211 rowCount: data.rows.length,
212 targetFileId,
213 focusIndex: -1,
214 isIos: true,
215 nativeView,
216 jumpStarted,
217 loadMore: () => {},
218 onDebug: bridge.onDebug,
219 });
220 return (
221 <NativeDiff
222 {...bridge}
223 {...pullRequestDiffInitialPosition(targetFileId, -1)}
224 nativeViewRef={nativeView}
225 appearanceScheme="light"
226 rowHeight={20}
227 contentWidth={300}
228 onDebug={onDebug}
229 />
230 );
231 }
232 if (!integrated) {
233 act(() =>
234 root.render(
235 <NativeDiff
236 rowsJson="[]"
237 tokensPatchJson='{"tokensByRowId":{}}'
238 appearanceScheme="light"
239 themeJson="{}"
240 rowHeight={20}
241 contentWidth={300}
242 />,
243 ),
244 );
245 }
246 return {
247 container,
248 async mountPullRequest(targetFileId?: string) {
249 await act(async () => root.render(<PullRequestDiff targetFileId={targetFileId} />));
250 },
251 async collapseFiles(fileIds: ReadonlyArray<string>) {
252 collapsedFileIds = fileIds;
253 await act(async () => root.render(<PullRequestDiff />));
254 },
255 async updateComment() {
256 data = {
257 ...data,
258 rows: data.rows.map((row) =>
259 row.kind === "comment" ? { ...row, commentText: "Updated comment" } : row,
260 ),
261 };
262 await act(async () => root.render(<PullRequestDiff />));
263 },
264 get tokenRows() {
265 return container.querySelector("[data-token-rows]")?.getAttribute("data-token-rows");
266 },
267 async jump(firstRowIndex: number, totalRows = 1000) {
268 await act(async () => {
269 mocks.onDebug?.({
270 nativeEvent: {
271 message: "visible-range",
272 firstRowIndex,
273 lastRowIndex: firstRowIndex + 40,
274 totalRows,
275 },
276 } as unknown as Parameters<NonNullable<NativeReviewDiffViewProps["onDebug"]>>[0]);
277 await vi.runOnlyPendingTimersAsync();
278 });
279 },
280 async deliverPayloads() {
281 const callbacks = [...frames.values()];
282 frames.clear();
283 await act(async () => {
284 for (const callback of callbacks) callback(0);
285 await vi.runOnlyPendingTimersAsync();
286 });
287 },
288 retry() {
289 const button = container.querySelector("button");
290 expect(button?.textContent).toBe("Retry diff");
291 act(() => button!.click());
292 },
293 decodeFailure() {
294 act(() =>
295 mocks.onDebug?.({
296 nativeEvent: { message: "rows-decode-failed", error: "Decode failed" },
297 } as unknown as Parameters<NonNullable<NativeReviewDiffViewProps["onDebug"]>>[0]),
298 );
299 },
300 [Symbol.dispose]() {
301 act(() => root.unmount());
302 requestFrame.mockRestore();
303 cancelFrame.mockRestore();
304 errors.mockRestore();
305 vi.useRealTimers();
306 if (expo) Object.defineProperty(globalThis, "expo", expo);
307 else Reflect.deleteProperty(globalThis, "expo");
308 },
309 };
311​
312it("retries transient native registration without replacing the diff with an error", async () => {
313 using screen = setup();
314 mocks.registrationFailures = 1;
315 await screen.deliverPayloads();
316 expect(screen.container.textContent).toBe("Blank native surface");
317 await screen.deliverPayloads();
318 expect(screen.container.textContent).toBe("Rendered diff");
319});
320​
321it.each([false, undefined])(
322 "keeps colors queued until native accepts them and recovers rejected patches (%s)",
323 async (rejected) => {
324 using screen = setup(true);
325 await screen.mountPullRequest();
326 let accept!: (accepted: boolean) => void;
327 mocks.tokenCompletion = new Promise((resolve) => {
328 accept = resolve;
329 });
330 mocks.tokens.mockClear();
331 await screen.jump(0);
332 await screen.deliverPayloads();
333 await screen.jump(400);
334 await screen.deliverPayloads();
335 expect(
336 mocks.tokens.mock.calls.map(([json]) => Object.keys(JSON.parse(json).tokensByRowId)),
337 ).toEqual([["r0"]]);
338 await act(async () => accept(true));
339​
340 mocks.tokenCompletion = null;
341 mocks.tokenAccepted = rejected;
342 await screen.deliverPayloads();
343 expect(screen.tokenRows).toBe("r0");
344​
345 mocks.tokenAccepted = true;
346 await screen.jump(800);
347 await screen.deliverPayloads();
348 expect(screen.tokenRows).toBe("r0,r800");
349 await screen.jump(400);
350 await screen.deliverPayloads();
351 expect(screen.tokenRows).toBe("r0,r800,r400");
352 },
353);
354​
355it.each(["retry", "comment update"])(
356 "re-highlights accepted rows after a native row failure, PR %s, and viewport revisit",
357 async (recovery) => {
358 using screen = setup(true);
359 await screen.mountPullRequest();
360 mocks.tokens.mockClear();
361 await screen.jump(0);
362 await screen.deliverPayloads();
363 await screen.jump(400);
364 await screen.deliverPayloads();
365 expect(screen.tokenRows).toBe("r0,r400");
366​
367 screen.decodeFailure();
368 expect(screen.container.textContent).toContain("Could not display diff");
369 if (recovery === "retry") await act(async () => screen.retry());
370 else await screen.updateComment();
371 await screen.deliverPayloads();
372 expect(screen.container.textContent).toBe("Rendered diff");
373 await screen.jump(800);
374 await screen.deliverPayloads();
375 await screen.jump(400);
376 await screen.deliverPayloads();
377 expect(screen.tokenRows?.split(",")).toContain("r400");
378 },
379);
380​
381it("delivers the selected file first with a warm highlighter and no startup command", async () => {
382 using screen = setup(true);
383 mocks.autoViewport = true;
384 await screen.mountPullRequest("last-file");
385 await screen.deliverPayloads();
386 await screen.deliverPayloads();
387 expect(screen.tokenRows).toBe("r900");
388});
389​
390it("recognizes registration races for the installed native view name", async () => {
391 const { isPendingNativeViewRegistration } = await import("./nativeReviewDiffSurface");
392​
393 expect(
394 isPendingNativeViewRegistration(
395 new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag"),
396 ),
397 ).toBe(true);
398 expect(
399 isPendingNativeViewRegistration(
400 new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),
401 ),
402 ).toBe(false);
403 expect(
404 isPendingNativeViewRegistration(
405 new Error(
406 "Unable to find the class expo.modules.t3reviewdiff.T3ReviewDiffView view with tag 1150",
407 ),
408 ),
409 ).toBe(true);
410});
411​
412it("cancels stale collapse work and highlights expansion without resetting accepted tokens", async () => {
413 using screen = setup(true);
414 await screen.mountPullRequest();
415 await screen.jump(0);
416 await screen.deliverPayloads();
417 expect(screen.tokenRows).toBe("r0");
418​
419 const response = Promise.withResolvers<void>();
420 const highlight = mocks.highlight.getMockImplementation()!;
421 mocks.highlight.mockImplementation(async (input: HighlightNativeReviewDiffVisibleRowsInput) => {
422 if (input.firstRowIndex === 400) {
423 await response.promise;
424 if (input.collapsedFileIds?.has("last-file")) {
425 return { tokensByRowId: {}, rowCount: 0, retryableRowIds: [], durationMs: 0 };
426 }
427 }
428 return highlight(input);
429 });
430 await screen.jump(400);
431 await screen.collapseFiles(["last-file"]);
432 await act(async () => response.resolve());
433 await screen.deliverPayloads();
434 expect(screen.tokenRows).toBe("r0");
435​
436 await screen.collapseFiles([]);
437 await screen.deliverPayloads();
438 expect(screen.tokenRows).toBe("r0,r400");
439 await screen.jump(0);
440 await screen.deliverPayloads();
441 expect(screen.tokenRows).toBe("r0,r400");
442});