Open History to see the last commit
1import { RegistryContext } from "@effect/atom-react";
2import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3import { PullRequestOperationError, type PullRequestDiffResult } from "@t3tools/contracts";
4import * as Effect from "effect/Effect";
5import { Atom, AtomRegistry } from "effect/reactivity";
6import { act, useLayoutEffect, useState } from "react";
7import { createRoot } from "react-dom/client";
8import { expect, it, vi } from "vite-plus/test";
9
10const mocks = vi.hoisted(() => ({ diff: vi.fn() }));
11vi.mock("../../state/pull-requests", () => ({ composerPullRequests: { diff: mocks.diff } }));
12
13import {
14 pullRequestParams,
15 usePullRequestDiff,
16 usePullRequestDiffEntry,
17} from "./usePullRequestDiff";
18import * as reviewModel from "../review/reviewModel";
19import { getCachedNativeReviewDiffData } from "../review/nativeReviewDiffAdapter";
20
21function patch(
22 path: string,
23 nextCursor: string | null = null,
24 added = "new",
25): PullRequestDiffResult {
26 return {
27 patch: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-old\n+${added}\n`,
28 truncated: false,
29 nextCursor,
30 };
31}
32
33function setup() {
34 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
35 const registry = AtomRegistry.make();
36 const requests: {
37 cursor: string | null;
38 resolve: (value: PullRequestDiffResult) => void;
39 reject: (error: Error) => void;
40 }[] = [];
41 const queries = Atom.family((cursor: string | null) =>
42 Atom.make(
43 Effect.tryPromise({
44 try: () =>
45 new Promise<PullRequestDiffResult>((resolve, reject) => {
46 requests.push({ cursor, resolve, reject });
47 }),
48 catch: (cause) =>
49 new PullRequestOperationError({ operation: "diff", detail: "Connection lost", cause }),
50 }),
51 ).pipe(Atom.keepAlive),
52 );
53 mocks.diff.mockImplementation((target: { input: { cursor?: string } }) =>
54 queries(target.input.cursor ?? null),
55 );
56 const root = createRoot(document.createElement("div"));
57 let current: ReturnType<typeof usePullRequestDiff>;
58 function Probe() {
59 const result = usePullRequestDiff(
60 {
61 environmentId: "environment",
62 projectId: "project",
63 repository: "repo",
64 number: 1,
65 },
66 sourceControlClients.get("github").changeRequest,
67 );
68 useLayoutEffect(() => {
69 current = result;
70 });
71 return null;
72 }
73 act(() =>
74 root.render(
75 <RegistryContext.Provider value={registry}>
76 <Probe />
77 </RegistryContext.Provider>,
78 ),
79 );
80 return {
81 requests,
82 remount() {
83 act(() =>
84 root.render(
85 <RegistryContext.Provider value={registry}>
86 <Probe key="new-route" />
87 </RegistryContext.Provider>,
88 ),
89 );
90 },
91 get current() {
92 return current;
93 },
94 async succeed(index: number, result: PullRequestDiffResult) {
95 await act(async () => {
96 requests[index]!.resolve(result);
97 });
98 },
99 async fail(index: number) {
100 await act(async () => {
101 requests[index]!.reject(new Error("Connection lost"));
102 });
103 },
104 [Symbol.dispose]() {
105 act(() => root.unmount());
106 registry.dispose();
107 },
108 };
109}
110
111it("reuses the parsed snapshot when a new route reads the same query result", async () => {
112 using parse = vi.spyOn(reviewModel, "buildReviewParsedDiff");
113 using screen = setup();
114 await screen.succeed(0, patch("first.ts"));
115 const parsed = screen.current.parsed;
116 const parses = parse.mock.calls.length;
117 screen.remount();
118 expect(screen.current.parsed).toBe(parsed);
119 expect(parse).toHaveBeenCalledTimes(parses);
120 expect(screen.requests).toHaveLength(1);
121});
122
123function setupEntry() {
124 vi.useFakeTimers();
125 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
126 const frames = new Map<number, FrameRequestCallback>();
127 let frameId = 0;
128 const requestFrame = vi
129 .spyOn(globalThis, "requestAnimationFrame")
130 .mockImplementation((callback) => {
131 frames.set(++frameId, callback);
132 return frameId;
133 });
134 const cancelFrame = vi.spyOn(globalThis, "cancelAnimationFrame").mockImplementation((id) => {
135 if (id != null) frames.delete(id);
136 });
137 const listeners = new Map<string, (event: { data: { closing: boolean } }) => void>();
138 const navigation = {
139 addListener(
140 type: "transitionStart" | "transitionEnd",
141 listener: (event: { data: { closing: boolean } }) => void,
142 ) {
143 listeners.set(type, listener);
144 return () => {
145 listeners.delete(type);
146 };
147 },
148 };
149 const events: string[] = [];
150 const prepare = vi.fn(() => {
151 events.push("prepare");
152 return getCachedNativeReviewDiffData({
153 parsedDiff: reviewModel.buildReviewParsedDiff(
154 patch("first.ts").patch + patch("neighbor.ts").patch,
155 "entry",
156 ),
157 });
158 });
159 function Body() {
160 const [data] = useState(prepare);
161 return <div>{data.files.map((file) => file.path).join(",")}</div>;
162 }
163 function Entry() {
164 const ready = usePullRequestDiffEntry(navigation);
165 useLayoutEffect(() => {
166 events.push(ready ? "body-commit" : "shell-commit");
167 }, [ready]);
168 return ready ? <Body /> : <div>Opening changes</div>;
169 }
170 const container = document.createElement("div");
171 const root = createRoot(container);
172 act(() => root.render(<Entry />));
173 return {
174 prepare,
175 events,
176 container,
177 frame() {
178 const pending = [...frames.values()];
179 frames.clear();
180 act(() => {
181 for (const callback of pending) callback(0);
182 });
183 },
184 event(type: "transitionStart" | "transitionEnd", closing = false) {
185 act(() => listeners.get(type)?.({ data: { closing } }));
186 },
187 fallback() {
188 act(() => vi.runAllTimers());
189 },
190 [Symbol.dispose]() {
191 act(() => root.unmount());
192 requestFrame.mockRestore();
193 cancelFrame.mockRestore();
194 vi.useRealTimers();
195 },
196 };
197}
198
199it("commits the loading shell and waits for the opening transition before building the diff", () => {
200 using screen = setupEntry();
201 expect(screen.events).toEqual(["shell-commit"]);
202 screen.event("transitionStart");
203 screen.frame();
204 screen.frame();
205 screen.event("transitionEnd", true);
206 expect(screen.prepare).not.toHaveBeenCalled();
207 screen.event("transitionEnd");
208 expect(screen.events).toEqual(["shell-commit", "prepare", "body-commit"]);
209 expect(screen.container.textContent).toBe("first.ts,neighbor.ts");
210});
211
212it.each(["unanimated", "missing-completion"] as const)(
213 "opens the diff after a %s presentation without stranding the shell",
214 (presentation) => {
215 using screen = setupEntry();
216 if (presentation === "missing-completion") screen.event("transitionStart");
217 screen.frame();
218 expect(screen.prepare).not.toHaveBeenCalled();
219 screen.frame();
220 if (presentation === "missing-completion") {
221 expect(screen.prepare).not.toHaveBeenCalled();
222 screen.fallback();
223 }
224 expect(screen.prepare).toHaveBeenCalledOnce();
225 },
226);
227
228it("retries a failed continuation without discarding loaded files or restarting page one", async () => {
229 using screen = setup();
230 await screen.succeed(0, patch("first.ts", "second"));
231 act(() => screen.current.loadMore());
232 await screen.fail(1);
233 expect(screen.current.error).not.toBeNull();
234 expect(screen.current.patch).toContain("first.ts");
235
236 act(() => screen.current.retry());
237 expect(screen.requests.map((request) => request.cursor)).toEqual([null, "second", "second"]);
238 expect(screen.current.patch).toContain("first.ts");
239 await screen.succeed(2, patch("second.ts"));
240 expect(screen.current.error).toBeNull();
241 expect(screen.current.parsed.kind).toBe("files");
242 if (screen.current.parsed.kind !== "files") throw new Error("Expected files");
243 expect(screen.current.parsed.files.map((file) => file.path)).toEqual(["first.ts", "second.ts"]);
244 expect(screen.current.nextCursor).toBeNull();
245});
246
247it.each(["failed", "loaded"] as const)(
248 "reloads every page from page one after a continuation %s",
249 async (continuation) => {
250 using screen = setup();
251 await screen.succeed(0, patch("first.ts", "second"));
252 act(() => screen.current.loadMore());
253 if (continuation === "failed") await screen.fail(1);
254 else await screen.succeed(1, patch("second.ts"));
255
256 act(() => screen.current.refresh());
257 expect(screen.requests.map((request) => request.cursor)).toEqual([null, "second", null]);
258 // The page already on screen stays there while its replacement loads.
259 expect(screen.current.patch).toContain("+new");
260 expect(screen.current.patch).not.toContain("second.ts");
261 expect(screen.current.canLoadMore).toBe(false);
262 await screen.succeed(2, patch("first.ts", "second", "pushed"));
263 expect(screen.current.error).toBeNull();
264 expect(screen.current.patch).not.toContain("+new");
265
266 act(() => screen.current.loadMore());
267 expect(screen.requests.map((request) => request.cursor)).toEqual([
268 null,
269 "second",
270 null,
271 "second",
272 ]);
273 expect(screen.current.isPending).toBe(true);
274 await screen.succeed(3, patch("second.ts", null, "pushed"));
275 expect(screen.current.patch).not.toContain("+new");
276 if (screen.current.parsed.kind !== "files") throw new Error("Expected files");
277 expect(screen.current.parsed.files.map((file) => file.path)).toEqual(["first.ts", "second.ts"]);
278 },
279);
280
281it("holds further pages back until a pull to refresh has reread page one", async () => {
282 using screen = setup();
283 await screen.succeed(0, patch("first.ts", "second"));
284
285 // The pull's refetch starts a tick later, so page one still looks settled here.
286 act(() => void screen.current.onPullRefresh());
287 expect(screen.current.patch).toContain("first.ts");
288 expect(screen.current.canLoadMore).toBe(false);
289 act(() => screen.current.loadMore());
290 await act(async () => {});
291 expect(screen.requests.map((request) => request.cursor)).toEqual([null, null]);
292
293 await screen.succeed(1, patch("first.ts", "second", "pushed"));
294 expect(screen.current.patch).toContain("+pushed");
295 expect(screen.current.canLoadMore).toBe(true);
296});
297
298it("keeps only the pull request a route names", () => {
299 const pullRequest = {
300 environmentId: "environment",
301 projectId: "project",
302 repository: "owner/repo",
303 number: 1,
304 host: "git.example.com",
305 navigationUrl: "https://git.example.com/owner/repo/pull/1#discussion_r1",
306 navigationId: 2,
307 };
308 const routeParams = { ...pullRequest, commit: "abc1234", path: "src/index.ts" };
309 expect(pullRequestParams(routeParams)).toEqual(pullRequest);
310});