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

PullRequestCodeTab.browser.test.tsx

238 lines7.2 KB

1import {
2 EnvironmentId,
3 ProjectId,
4 SourceControlProviderKind,
5 type PullRequestDetailView,
6 type PullRequestDiffResult,
7} from "@t3tools/contracts";
8import { expect, it, vi } from "vite-plus/test";
9​
10import "~/index.css";
11​
12const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => {
13 const { AsyncResult, Atom } = await import("effect/reactivity");
14 const filePatch = (path: string) =>
15 [
16 `diff --git a/${path} b/${path}`,
17 "index 1111111..2222222 100644",
18 `--- a/${path}`,
19 `+++ b/${path}`,
20 "@@ -1,6 +1,6 @@",
21 "-before()",
22 "+after()",
23 " one()",
24 " two()",
25 " three()",
26 " four()",
27 " five()",
28 "",
29 ].join("\n");
30 const firstPage: PullRequestDiffResult = {
31 patch: filePatch("a.ts"),
32 truncated: false,
33 nextCursor: null,
34 };
35 const pages: Record<string, PullRequestDiffResult> = {
36 first: {
37 patch: Array.from({ length: 40 }, (_, index) => filePatch(`early-${index}.ts`)).join(""),
38 truncated: true,
39 nextCursor: "page-2",
40 },
41 "page-2": { patch: filePatch("late.ts"), truncated: false, nextCursor: null },
42 };
43 return {
44 // An environment query whose refetch returns equal content hands back the previous value
45 // itself, so a refresh publishes a new result around the very same page.
46 diffAtom: Atom.make(() => AsyncResult.success(firstPage)),
47 pagedDiffAtom: Atom.family((cursor: string) =>
48 Atom.make(() => AsyncResult.success(pages[cursor]!)),
49 ),
50 };
51});
52​
53const mocks = vi.hoisted(() => ({ paged: false, diffCommits: [] as Array<string | undefined> }));
54​
55vi.mock(import("~/state/use-atom-command"), async (original) => ({
56 ...(await original()),
57 useAtomCommand: (() => vi.fn()) as never,
58}));
59vi.mock(import("~/state/pullRequests"), async (original) => {
60 const actual = await original();
61 return {
62 ...actual,
63 pullRequestEnvironment: {
64 ...actual.pullRequestEnvironment,
65 diff: (({ input }: { input: { cursor?: string; commit?: string } }) => {
66 mocks.diffCommits.push(input.commit);
67 return mocks.paged ? pagedDiffAtom(input.cursor ?? "first") : diffAtom;
68 }) as never,
69 },
70 };
71});
72​
73import { render } from "../../../test/render";
74import PullRequestCodeTab from "./PullRequestCodeTab";
75​
76const detail: PullRequestDetailView = {
77 provider: SourceControlProviderKind.make("github"),
78 projectId: ProjectId.make("project"),
79 projectTitle: "Project",
80 workspaceRoot: "/workspace",
81 repository: "owner/repo",
82 number: 1,
83 title: "Test pull request",
84 body: "",
85 url: "https://github.com/owner/repo/pull/1",
86 author: { login: "author", name: null, avatarUrl: null },
87 viewer: "author",
88 state: "open",
89 isDraft: false,
90 mergeability: "mergeable",
91 additions: 1,
92 deletions: 1,
93 changedFiles: 1,
94 headBranch: "feature",
95 baseBranch: "main",
96 createdAt: "2026-09-01T00:00:00Z",
97 updatedAt: "2026-09-01T00:00:00Z",
98 mergedAt: null,
99 closedAt: null,
100 reviewers: [],
101 labels: [],
102 checks: [],
103 comments: [],
104 commentCount: 0,
105 commentsTruncated: false,
106 reviewThreads: [],
107 commits: [],
108 mergeCapabilities: { merge: false, squash: false, rebase: false },
109 capabilities: {
110 diff: true,
111 comment: false,
112 search: true,
113 actions: [],
114 mergeMethods: [],
115 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
116 reviewers: { request: false, listCandidates: false },
117 edit: { changeRequest: false, comment: false },
118 },
119 viewerPermissions: {
120 actions: [],
121 comment: false,
122 resolve: false,
123 verdicts: [],
124 requestReviewers: false,
125 },
126};
127​
128function setup({ paged }: { paged: boolean }) {
129 mocks.paged = paged;
130 mocks.diffCommits = [];
132​
133const tab = (
134 refreshToken: number,
135 revealRequest: { readonly path: string; readonly nonce: number } | null = null,
136) => (
137 <PullRequestCodeTab
138 scrollerRef={() => {}}
139 environmentId={EnvironmentId.make("environment")}
140 reference={detail}
141 detail={detail}
142 selectedCommitOid={null}
143 onSelectedCommitChange={() => {}}
144 onRefresh={() => {}}
145 refreshToken={refreshToken}
146 revealRequest={revealRequest}
147 />
148);
149​
150it("keeps the diff after a refresh that brings back the same page", async () => {
151 setup({ paged: false });
152 const container = document.createElement("div");
153 container.className = "flex h-[700px] w-[900px]";
154 await using screen = await render(tab(0), { container });
155 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
156​
157 await screen.rerender(tab(1));
158​
159 await expect
160 .element(screen.getByText("This pull request has no file changes."))
161 .not.toBeInTheDocument();
162 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
163});
164​
165function pagedContainer() {
166 const container = document.createElement("div");
167 container.className = "flex h-[500px] w-[900px]";
168 return container;
170​
171// Rows are virtualized, so a header far down is not rendered until the view scrolls to it.
172async function expectFileHeaderShown(
173 screen: Awaited<ReturnType<typeof render>>,
174 container: HTMLElement,
175 path: string,
176) {
177 const header = screen.getByText(path, { exact: true }).first();
178 await expect.element(header).toBeInTheDocument();
179 await vi.waitFor(() => {
180 const top = header.element().getBoundingClientRect().top;
181 const bounds = container.getBoundingClientRect();
182 expect(top).toBeGreaterThanOrEqual(bounds.top);
183 expect(top).toBeLessThan(bounds.top + bounds.height / 2);
184 });
186​
187it("scrolls to a file asked for as the tab opens", async () => {
188 setup({ paged: true });
189 const container = pagedContainer();
190 await using screen = await render(tab(0, { path: "early-39.ts", nonce: 1 }), { container });
191​
192 await expectFileHeaderShown(screen, container, "early-39.ts");
193});
194​
195it("pages forward to a file asked for that is not loaded yet, then scrolls to it", async () => {
196 setup({ paged: true });
197 const container = pagedContainer();
198 await using screen = await render(tab(0), { container });
199 await expect.element(screen.getByText("early-0.ts", { exact: true }).first()).toBeVisible();
200​
201 await screen.rerender(tab(0, { path: "late.ts", nonce: 1 }));
202​
203 await expectFileHeaderShown(screen, container, "late.ts");
204});
205​
206it("never requests the diff of a selected commit the pull request no longer has", async () => {
207 setup({ paged: false });
208 const container = document.createElement("div");
209 container.className = "flex h-[700px] w-[900px]";
210 // The timeline can open a commit that a force-push removed from the pull request.
211 await using screen = await render(
212 <PullRequestCodeTab
213 scrollerRef={() => {}}
214 environmentId={EnvironmentId.make("environment")}
215 reference={detail}
216 detail={{
217 ...detail,
218 commits: [
219 {
220 oid: "kept",
221 messageHeadline: "Kept commit",
222 committedDate: "2026-09-01T00:00:00Z",
223 },
224 ],
225 }}
226 selectedCommitOid="gone"
227 onSelectedCommitChange={() => {}}
228 onRefresh={() => {}}
229 />,
230 { container },
231 );
232​
233 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
234 await expect
235 .element(screen.getByRole("button", { name: "Diff scope: All commits" }))
236 .toBeVisible();
237 expect(mocks.diffCommits).not.toContain("gone");
238});