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

nativeReviewDiffSurface.test.tsx

445 lines14.6 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: () => jumpStarted.current,
217 setJumpStarted: (started) => {
218 jumpStarted.current = started;
219 },
220 loadMore: () => {},
221 onDebug: bridge.onDebug,
222 });
223 return (
224 <NativeDiff
225 {...bridge}
226 {...pullRequestDiffInitialPosition(targetFileId, -1)}
227 nativeViewRef={nativeView}
228 appearanceScheme="light"
229 rowHeight={20}
230 contentWidth={300}
231 onDebug={onDebug}
232 />
233 );
234 }
235 if (!integrated) {
236 act(() =>
237 root.render(
238 <NativeDiff
239 rowsJson="[]"
240 tokensPatchJson='{"tokensByRowId":{}}'
241 appearanceScheme="light"
242 themeJson="{}"
243 rowHeight={20}
244 contentWidth={300}
245 />,
246 ),
247 );
248 }
249 return {
250 container,
251 async mountPullRequest(targetFileId?: string) {
252 await act(async () => root.render(<PullRequestDiff targetFileId={targetFileId} />));
253 },
254 async collapseFiles(fileIds: ReadonlyArray<string>) {
255 collapsedFileIds = fileIds;
256 await act(async () => root.render(<PullRequestDiff />));
257 },
258 async updateComment() {
259 data = {
260 ...data,
261 rows: data.rows.map((row) =>
262 row.kind === "comment" ? { ...row, commentText: "Updated comment" } : row,
263 ),
264 };
265 await act(async () => root.render(<PullRequestDiff />));
266 },
267 get tokenRows() {
268 return container.querySelector("[data-token-rows]")?.getAttribute("data-token-rows");
269 },
270 async jump(firstRowIndex: number, totalRows = 1000) {
271 await act(async () => {
272 mocks.onDebug?.({
273 nativeEvent: {
274 message: "visible-range",
275 firstRowIndex,
276 lastRowIndex: firstRowIndex + 40,
277 totalRows,
278 },
279 } as unknown as Parameters<NonNullable<NativeReviewDiffViewProps["onDebug"]>>[0]);
280 await vi.runOnlyPendingTimersAsync();
281 });
282 },
283 async deliverPayloads() {
284 const callbacks = [...frames.values()];
285 frames.clear();
286 await act(async () => {
287 for (const callback of callbacks) callback(0);
288 await vi.runOnlyPendingTimersAsync();
289 });
290 },
291 retry() {
292 const button = container.querySelector("button");
293 expect(button?.textContent).toBe("Retry diff");
294 act(() => button!.click());
295 },
296 decodeFailure() {
297 act(() =>
298 mocks.onDebug?.({
299 nativeEvent: { message: "rows-decode-failed", error: "Decode failed" },
300 } as unknown as Parameters<NonNullable<NativeReviewDiffViewProps["onDebug"]>>[0]),
301 );
302 },
303 [Symbol.dispose]() {
304 act(() => root.unmount());
305 requestFrame.mockRestore();
306 cancelFrame.mockRestore();
307 errors.mockRestore();
308 vi.useRealTimers();
309 if (expo) Object.defineProperty(globalThis, "expo", expo);
310 else Reflect.deleteProperty(globalThis, "expo");
311 },
312 };
314​
315it("retries transient native registration without replacing the diff with an error", async () => {
316 using screen = setup();
317 mocks.registrationFailures = 1;
318 await screen.deliverPayloads();
319 expect(screen.container.textContent).toBe("Blank native surface");
320 await screen.deliverPayloads();
321 expect(screen.container.textContent).toBe("Rendered diff");
322});
323​
324it.each([false, undefined])(
325 "keeps colors queued until native accepts them and recovers rejected patches (%s)",
326 async (rejected) => {
327 using screen = setup(true);
328 await screen.mountPullRequest();
329 let accept!: (accepted: boolean) => void;
330 mocks.tokenCompletion = new Promise((resolve) => {
331 accept = resolve;
332 });
333 mocks.tokens.mockClear();
334 await screen.jump(0);
335 await screen.deliverPayloads();
336 await screen.jump(400);
337 await screen.deliverPayloads();
338 expect(
339 mocks.tokens.mock.calls.map(([json]) => Object.keys(JSON.parse(json).tokensByRowId)),
340 ).toEqual([["r0"]]);
341 await act(async () => accept(true));
342​
343 mocks.tokenCompletion = null;
344 mocks.tokenAccepted = rejected;
345 await screen.deliverPayloads();
346 expect(screen.tokenRows).toBe("r0");
347​
348 mocks.tokenAccepted = true;
349 await screen.jump(800);
350 await screen.deliverPayloads();
351 expect(screen.tokenRows).toBe("r0,r800");
352 await screen.jump(400);
353 await screen.deliverPayloads();
354 expect(screen.tokenRows).toBe("r0,r800,r400");
355 },
356);
357​
358it.each(["retry", "comment update"])(
359 "re-highlights accepted rows after a native row failure, PR %s, and viewport revisit",
360 async (recovery) => {
361 using screen = setup(true);
362 await screen.mountPullRequest();
363 mocks.tokens.mockClear();
364 await screen.jump(0);
365 await screen.deliverPayloads();
366 await screen.jump(400);
367 await screen.deliverPayloads();
368 expect(screen.tokenRows).toBe("r0,r400");
369​
370 screen.decodeFailure();
371 expect(screen.container.textContent).toContain("Could not display diff");
372 if (recovery === "retry") await act(async () => screen.retry());
373 else await screen.updateComment();
374 await screen.deliverPayloads();
375 expect(screen.container.textContent).toBe("Rendered diff");
376 await screen.jump(800);
377 await screen.deliverPayloads();
378 await screen.jump(400);
379 await screen.deliverPayloads();
380 expect(screen.tokenRows?.split(",")).toContain("r400");
381 },
382);
383​
384it("delivers the selected file first with a warm highlighter and no startup command", async () => {
385 using screen = setup(true);
386 mocks.autoViewport = true;
387 await screen.mountPullRequest("last-file");
388 await screen.deliverPayloads();
389 await screen.deliverPayloads();
390 expect(screen.tokenRows).toBe("r900");
391});
392​
393it("recognizes registration races for the installed native view name", async () => {
394 const { isPendingNativeViewRegistration } = await import("./nativeReviewDiffSurface");
395​
396 expect(
397 isPendingNativeViewRegistration(
398 new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag"),
399 ),
400 ).toBe(true);
401 expect(
402 isPendingNativeViewRegistration(
403 new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),
404 ),
405 ).toBe(false);
406 expect(
407 isPendingNativeViewRegistration(
408 new Error(
409 "Unable to find the class expo.modules.t3reviewdiff.T3ReviewDiffView view with tag 1150",
410 ),
411 ),
412 ).toBe(true);
413});
414​
415it("cancels stale collapse work and highlights expansion without resetting accepted tokens", async () => {
416 using screen = setup(true);
417 await screen.mountPullRequest();
418 await screen.jump(0);
419 await screen.deliverPayloads();
420 expect(screen.tokenRows).toBe("r0");
421​
422 const response = Promise.withResolvers<void>();
423 const highlight = mocks.highlight.getMockImplementation()!;
424 mocks.highlight.mockImplementation(async (input: HighlightNativeReviewDiffVisibleRowsInput) => {
425 if (input.firstRowIndex === 400) {
426 await response.promise;
427 if (input.collapsedFileIds?.has("last-file")) {
428 return { tokensByRowId: {}, rowCount: 0, retryableRowIds: [], durationMs: 0 };
429 }
430 }
431 return highlight(input);
432 });
433 await screen.jump(400);
434 await screen.collapseFiles(["last-file"]);
435 await act(async () => response.resolve());
436 await screen.deliverPayloads();
437 expect(screen.tokenRows).toBe("r0");
438​
439 await screen.collapseFiles([]);
440 await screen.deliverPayloads();
441 expect(screen.tokenRows).toBe("r0,r400");
442 await screen.jump(0);
443 await screen.deliverPayloads();
444 expect(screen.tokenRows).toBe("r0,r400");
445});