Open History to see the last commit
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 = [];
131}
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;
169}
170
171async function expectFileHeaderShown(
172 screen: Awaited<ReturnType<typeof render>>,
173 container: HTMLElement,
174 path: string,
175) {
176 const header = screen.getByText(path, { exact: true }).first();
177 await expect.element(header).toBeInTheDocument();
178 await vi.waitFor(() => {
179 const bounds = container.querySelector(".diff-render-surface")!.getBoundingClientRect();
180 const { top, bottom } = header.element().getBoundingClientRect();
181 expect(top).toBeGreaterThanOrEqual(bounds.top);
182 expect(bottom).toBeLessThanOrEqual(bounds.bottom);
183 });
184}
185
186it("scrolls to a file asked for as the tab opens", async () => {
187 setup({ paged: true });
188 const container = pagedContainer();
189 await using screen = await render(tab(0, { path: "early-39.ts", nonce: 1 }), { container });
190
191 await expectFileHeaderShown(screen, container, "early-39.ts");
192});
193
194it("pages forward to a file asked for that is not loaded yet, then scrolls to it", async () => {
195 setup({ paged: true });
196 const container = pagedContainer();
197 await using screen = await render(tab(0), { container });
198 await expect.element(screen.getByText("early-0.ts", { exact: true }).first()).toBeVisible();
199
200 await screen.rerender(tab(0, { path: "late.ts", nonce: 1 }));
201
202 await expectFileHeaderShown(screen, container, "late.ts");
203});
204
205it("never requests the diff of a selected commit the pull request no longer has", async () => {
206 setup({ paged: false });
207 const container = document.createElement("div");
208 container.className = "flex h-[700px] w-[900px]";
209 // The timeline can open a commit that a force-push removed from the pull request.
210 await using screen = await render(
211 <PullRequestCodeTab
212 scrollerRef={() => {}}
213 environmentId={EnvironmentId.make("environment")}
214 reference={detail}
215 detail={{
216 ...detail,
217 commits: [
218 {
219 oid: "kept",
220 messageHeadline: "Kept commit",
221 committedDate: "2026-09-01T00:00:00Z",
222 },
223 ],
224 }}
225 selectedCommitOid="gone"
226 onSelectedCommitChange={() => {}}
227 onRefresh={() => {}}
228 />,
229 { container },
230 );
231
232 await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible();
233 await expect
234 .element(screen.getByRole("button", { name: "Diff scope: All commits" }))
235 .toBeVisible();
236 expect(mocks.diffCommits).not.toContain("gone");
237});