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

PullRequestCodeTab.browser.test.tsx

449 lines15.3 KB

1import { sha256 } from "@noble/hashes/sha2";
2import { bytesToHex } from "@noble/hashes/utils";
3import {
4 EnvironmentId,
5 ProjectId,
6 SourceControlProviderKind,
7 type PullRequestDetailView,
8 type PullRequestDiffResult,
9} from "@t3tools/contracts";
10import { expect, it, vi } from "vite-plus/test";
11​
12import "~/index.css";
13import { __setClientSettingsForTests } from "../../hooks/useSettings";
14import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
15​
16const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => {
17 const { AsyncResult, Atom } = await import("effect/reactivity");
18 const filePatch = (path: string) =>
19 [
20 `diff --git a/${path} b/${path}`,
21 "index 1111111..2222222 100644",
22 `--- a/${path}`,
23 `+++ b/${path}`,
24 "@@ -1,6 +1,6 @@",
25 "-before()",
26 "+after()",
27 " one()",
28 " two()",
29 " three()",
30 " four()",
31 " five()",
32 "",
33 ].join("\n");
34 const firstPage: PullRequestDiffResult = {
35 patch: filePatch("a.ts"),
36 truncated: false,
37 nextCursor: null,
38 };
39 const pages: Record<string, PullRequestDiffResult> = {
40 first: {
41 patch: Array.from({ length: 40 }, (_, index) =>
42 filePatch(index === 1 ? "early-1.test.ts" : `early-${index}.ts`),
43 ).join(""),
44 truncated: true,
45 nextCursor: "page-2",
46 },
47 "page-2": { patch: filePatch("late.test.ts"), truncated: false, nextCursor: null },
48 };
49 return {
50 // An environment query whose refetch returns equal content hands back the previous value
51 // itself, so a refresh publishes a new result around the very same page.
52 diffAtom: Atom.make(() => AsyncResult.success(firstPage)),
53 pagedDiffAtom: Atom.family((cursor: string) =>
54 Atom.make(() => AsyncResult.success(pages[cursor]!)),
55 ),
56 };
57});
58​
59const mocks = vi.hoisted(() => ({
60 paged: false,
61 diffCommits: [] as Array<string | undefined>,
62 viewedPaths: null as ReadonlySet<string> | null,
63 viewedListeners: new Set<() => void>(),
64}));
65​
66function deliverViewedPaths(paths: ReadonlySet<string> | null) {
67 mocks.viewedPaths = paths;
68 for (const listener of mocks.viewedListeners) listener();
70​
71vi.mock(import("~/state/use-atom-command"), async (original) => ({
72 ...(await original()),
73 useAtomCommand: (() => vi.fn()) as never,
74}));
75vi.mock(import("./usePullRequestFilesViewed"), async () => {
76 const { useSyncExternalStore } = await import("react");
77 const subscribe = (listener: () => void) => {
78 mocks.viewedListeners.add(listener);
79 return () => mocks.viewedListeners.delete(listener);
80 };
81 return {
82 usePullRequestFilesViewed: () => {
83 const viewedPaths = useSyncExternalStore(subscribe, () => mocks.viewedPaths);
84 return {
85 enabled: viewedPaths !== null,
86 isViewed: (path: string) => viewedPaths?.has(path) === true,
87 isStale: () => false,
88 setViewed: () => {},
89 truncated: false,
90 error: null,
91 refresh: () => {},
92 };
93 },
94 };
95});
96vi.mock(import("~/state/pullRequests"), async (original) => {
97 const actual = await original();
98 return {
99 ...actual,
100 pullRequestEnvironment: {
101 ...actual.pullRequestEnvironment,
102 diff: (({ input }: { input: { cursor?: string; commit?: string } }) => {
103 mocks.diffCommits.push(input.commit);
104 return mocks.paged ? pagedDiffAtom(input.cursor ?? "first") : diffAtom;
105 }) as never,
106 },
107 };
108});
109​
110import { render } from "../../../test/render";
111import PullRequestCodeTab from "./PullRequestCodeTab";
112​
113const detail: PullRequestDetailView = {
114 provider: SourceControlProviderKind.make("github"),
115 projectId: ProjectId.make("project"),
116 projectTitle: "Project",
117 workspaceRoot: "/workspace",
118 repository: "owner/repo",
119 number: 1,
120 title: "Test pull request",
121 body: "",
122 url: "https://github.com/owner/repo/pull/1",
123 author: { login: "author", name: null, avatarUrl: null },
124 viewer: "author",
125 state: "open",
126 isDraft: false,
127 mergeability: "mergeable",
128 additions: 1,
129 deletions: 1,
130 changedFiles: 1,
131 headBranch: "feature",
132 baseBranch: "main",
133 createdAt: "2026-09-01T00:00:00Z",
134 updatedAt: "2026-09-01T00:00:00Z",
135 mergedAt: null,
136 closedAt: null,
137 reviewers: [],
138 labels: [],
139 checks: [],
140 comments: [],
141 commentCount: 0,
142 commentsTruncated: false,
143 reviewThreads: [],
144 commits: [],
145 mergeCapabilities: { merge: false, squash: false, rebase: false },
146 capabilities: {
147 diff: true,
148 comment: false,
149 search: true,
150 actions: [],
151 mergeMethods: [],
152 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
153 reviewers: { request: false, listCandidates: false },
154 edit: { changeRequest: false, comment: false },
155 },
156 viewerPermissions: {
157 actions: [],
158 comment: false,
159 resolve: false,
160 verdicts: [],
161 requestReviewers: false,
162 },
163};
164​
165function setup({ paged }: { paged: boolean }) {
166 window.localStorage.removeItem("t3code.diffHideTestFiles");
167 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
168 mocks.paged = paged;
169 mocks.diffCommits = [];
170 mocks.viewedPaths = null;
171 mocks.viewedListeners.clear();
173​
174const tab = (
175 refreshToken: number,
176 revealRequest: { readonly path: string; readonly nonce: number } | null = null,
177 revealUrl?: string,
178 onRevealSettled?: (url: string) => void,
179) => (
180 <PullRequestCodeTab
181 scrollerRef={() => {}}
182 environmentId={EnvironmentId.make("environment")}
183 reference={detail}
184 detail={detail}
185 selectedCommitOid={null}
186 onSelectedCommitChange={() => {}}
187 onRefresh={() => {}}
188 refreshToken={refreshToken}
189 revealRequest={revealRequest}
190 revealUrl={revealUrl}
191 onRevealSettled={onRevealSettled}
192 />
193);
194​
195it("keeps the diff after a refresh that brings back the same page", async () => {
196 setup({ paged: false });
197 const container = document.createElement("div");
198 container.className = "flex h-[700px] w-[900px]";
199 await using screen = await render(tab(0), { container });
200 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
201​
202 await screen.rerender(tab(1));
203​
204 await expect
205 .element(screen.getByText("This pull request has no file changes."))
206 .not.toBeInTheDocument();
207 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
208});
209​
210// regression: #13279 a Viewed answer that lands after a link reveals a file must not fold it
211it("keeps a revealed file open when its Viewed mark loads afterwards", async () => {
212 setup({ paged: false });
213 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false });
214 using _preferences = {
215 [Symbol.dispose]() {
216 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
217 },
218 };
219 mocks.viewedPaths = new Set();
220 const container = document.createElement("div");
221 container.className = "flex h-[700px] w-[900px]";
222 await using screen = await render(tab(0, { path: "a.ts", nonce: 1 }), { container });
223 await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
224​
225 deliverViewedPaths(new Set(["a.ts"]));
226 await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).toBeChecked();
227​
228 await expect
229 .element(screen.getByRole("button", { name: "Collapse diff" }))
230 .toHaveAttribute("aria-expanded", "true");
231 await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
232});
233​
234function pagedContainer() {
235 const container = document.createElement("div");
236 container.className = "flex h-[500px] w-[900px]";
237 return container;
239​
240async function expectFileHeaderShown(
241 screen: Awaited<ReturnType<typeof render>>,
242 container: HTMLElement,
243 path: string,
244) {
245 const header = screen.getByText(path, { exact: true }).first();
246 await expect.element(header).toBeInTheDocument();
247 await vi.waitFor(() => {
248 const bounds = container.querySelector(".diff-render-surface")!.getBoundingClientRect();
249 const { top, bottom } = header.element().getBoundingClientRect();
250 expect(top).toBeGreaterThanOrEqual(bounds.top);
251 expect(bottom).toBeLessThanOrEqual(bounds.bottom);
252 });
254​
255it("scrolls to a file asked for as the tab opens", async () => {
256 setup({ paged: true });
257 const container = pagedContainer();
258 await using screen = await render(tab(0, { path: "early-39.ts", nonce: 1 }), { container });
259​
260 await expectFileHeaderShown(screen, container, "early-39.ts");
261});
262​
263it("pages forward to a file asked for that is not loaded yet, then scrolls to it", async () => {
264 setup({ paged: true });
265 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: true });
266 using _preferences = {
267 [Symbol.dispose]() {
268 window.localStorage.removeItem("t3code.diffHideTestFiles");
269 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
270 },
271 };
272 const container = pagedContainer();
273 await using screen = await render(tab(0), { container });
274 await expect.element(screen.getByText("early-0.ts", { exact: true }).first()).toBeVisible();
275 await screen.getByRole("button", { name: "Hide test files" }).click();
276​
277 const url = `${detail.url}/files#diff-${bytesToHex(sha256(new TextEncoder().encode("late.test.ts")))}R4-R5`;
278 const settled = vi.fn();
279 await screen.rerender(tab(0, null, url, settled));
280​
281 await expectFileHeaderShown(screen, container, "late.test.ts");
282 await expect.element(screen.getByText("three()", { exact: true })).toBeVisible();
283 await vi.waitFor(() => expect(settled).toHaveBeenCalledWith(url));
284 // A settled link keeps its test file past the filter, and a later click reveals it again.
285 await screen.rerender(tab(0, { path: "early-0.ts", nonce: 1 }));
286 await expectFileHeaderShown(screen, container, "early-0.ts");
287 await screen.rerender(tab(0, { path: "early-0.ts", nonce: 1 }, url, settled));
288 await expectFileHeaderShown(screen, container, "late.test.ts");
289});
290​
291it("never requests the diff of a selected commit the pull request no longer has", async () => {
292 setup({ paged: false });
293 const container = document.createElement("div");
294 container.className = "flex h-[700px] w-[900px]";
295 // The timeline can open a commit that a force-push removed from the pull request.
296 await using screen = await render(
297 <PullRequestCodeTab
298 scrollerRef={() => {}}
299 environmentId={EnvironmentId.make("environment")}
300 reference={detail}
301 detail={{
302 ...detail,
303 commits: [
304 {
305 oid: "kept",
306 messageHeadline: "Kept commit",
307 committedDate: "2026-09-01T00:00:00Z",
308 },
309 ],
310 }}
311 selectedCommitOid="gone"
312 onSelectedCommitChange={() => {}}
313 onRefresh={() => {}}
314 />,
315 { container },
316 );
317​
318 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
319 await expect
320 .element(screen.getByRole("button", { name: "Diff scope: All commits" }))
321 .toBeVisible();
322 expect(mocks.diffCommits).not.toContain("gone");
323});
324​
325it("answers a commit's diff link only once that commit's diff is shown", async () => {
326 setup({ paged: false });
327 const container = document.createElement("div");
328 container.className = "flex h-[700px] w-[900px]";
329 const oid = "c".repeat(40);
330 const withCommit = {
331 ...detail,
332 commits: [{ oid, messageHeadline: "Linked commit", committedDate: "2026-09-01T00:00:00Z" }],
333 };
334 const url = `${detail.url}/commits/${oid}#diff-${bytesToHex(sha256(new TextEncoder().encode("a.ts")))}R2`;
335 const settled = vi.fn();
336 const scoped = (selectedCommitOid: string | null, revealUrl?: string) => (
337 <PullRequestCodeTab
338 scrollerRef={() => {}}
339 environmentId={EnvironmentId.make("environment")}
340 reference={detail}
341 detail={withCommit}
342 selectedCommitOid={selectedCommitOid}
343 onSelectedCommitChange={() => {}}
344 onRefresh={() => {}}
345 revealUrl={revealUrl}
346 onRevealSettled={settled}
347 />
348 );
349 await using screen = await render(scoped(null), { container });
350 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
351​
352 // The panel selects the link's commit after this tab has already seen the link.
353 await screen.rerender(scoped(null, url));
354 expect(settled).not.toHaveBeenCalled();
355 await screen.rerender(scoped(oid, url));
356 await vi.waitFor(() => expect(settled).toHaveBeenCalledWith(url));
357});
358​
359it("hides a resolved conversation behind avatars on its line until they are clicked", async () => {
360 setup({ paged: false });
361 __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false });
362 using _preferences = {
363 [Symbol.dispose]() {
364 __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
365 },
366 };
367 const container = document.createElement("div");
368 container.className = "flex h-[700px] w-[900px]";
369 const comment = {
370 author: { login: "reviewer", name: null, avatarUrl: null },
371 body: "Rename this.",
372 createdAt: "2026-09-01T00:00:00Z",
373 url: null,
374 };
375 const withThread = (isResolved: boolean, oldSideToo = false) => (
376 <PullRequestCodeTab
377 scrollerRef={() => {}}
378 environmentId={EnvironmentId.make("environment")}
379 reference={detail}
380 detail={{
381 ...detail,
382 capabilities: {
383 ...detail.capabilities,
384 review: { ...detail.capabilities.review, reply: true },
385 },
386 viewerPermissions: { ...detail.viewerPermissions, comment: true },
387 reviewThreads: [
388 {
389 id: "thread",
390 path: "a.ts",
391 line: 3,
392 side: "right",
393 isResolved,
394 isOutdated: false,
395 comments: [{ id: "comment", ...comment }],
396 },
397 ...(oldSideToo
398 ? [
399 {
400 id: "old-side",
401 path: "a.ts",
402 line: 3,
403 side: "left" as const,
404 isResolved: true,
405 isOutdated: false,
406 comments: [{ id: "old-side-comment", ...comment }],
407 },
408 ]
409 : []),
410 ],
411 }}
412 selectedCommitOid={null}
413 onSelectedCommitChange={() => {}}
414 onRefresh={() => {}}
415 />
416 );
417 await using screen = await render(withThread(true), { container });
418 const marker = screen.getByRole("button", { name: "Resolved conversation", exact: true });
419 const card = (state: string) => screen.getByRole("button", { name: `${state} · 1 comment` });
420 const reply = () => screen.getByRole("textbox", { name: "Reply to this conversation" });
421​
422 await expect.element(marker).toHaveAttribute("aria-expanded", "false");
423 await expect.element(card("Resolved")).not.toBeInTheDocument();
424​
425 await marker.click();
426 await expect.element(marker).toHaveAttribute("aria-expanded", "true");
427 await expect.element(card("Resolved")).toHaveAttribute("aria-expanded", "true");
428 await screen.getByRole("button", { name: "Reply", exact: true }).click();
429 await reply().fill("Unsent");
430​
431 // Hidden conversations stay mounted, so the unsent reply is still there.
432 await marker.click();
433 await expect.element(card("Resolved")).not.toBeInTheDocument();
434 await marker.click();
435 await expect.element(reply()).toHaveValue("Unsent");
436 await marker.click();
437​
438 // Seen open and then resolved, it stays until the avatars are clicked.
439 await screen.rerender(withThread(false));
440 await expect.element(card("Open")).toBeVisible();
441 await screen.rerender(withThread(true));
442 await expect.element(card("Resolved")).toBeVisible();
443​
444 // Stacked view draws a context row once, so both sides' conversations share the avatars.
445 await screen.rerender(withThread(true, true));
446 await expect
447 .element(screen.getByRole("button", { name: "2 resolved conversations" }))
448 .toBeVisible();
449});