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

PullRequestDetailPanel.permissions.browser.test.tsx

298 lines10.7 KB

1import {
2 AuthOrchestrationOperateScope,
3 AuthSourceControlWriteScope,
4 EnvironmentId,
5 ProjectId,
6 SourceControlProviderKind,
7 type PullRequestDetailView,
8} from "@t3tools/contracts";
9import { expect, it, vi } from "vite-plus/test";
10import { page, userEvent } from "vite-plus/test/browser";
11import appCss from "~/index.css?inline";
12import { DraftId, useComposerDraftStore } from "~/composerDraftStore";
13import { act, fakeTimers, render } from "../../../test/render";
14​
15const { command, permissions, reads, shown } = vi.hoisted(() => ({
16 command: vi.fn(),
17 permissions: { checkout: true, operate: true },
18 reads: { diff: [] as unknown[] },
19 shown: { detail: null as PullRequestDetailView | null },
20}));
21​
22vi.mock(import("~/state/session"), async (original) => ({
23 ...(await original()),
24 useEnvironmentScope: (_environmentId: unknown, scope: unknown) =>
25 scope === AuthOrchestrationOperateScope ? permissions.operate : permissions.checkout,
26 readEnvironmentScope: (_environmentId: unknown, scope: unknown) =>
27 scope === AuthOrchestrationOperateScope ? permissions.operate : permissions.checkout,
28}));
29vi.mock(import("~/state/sourceControlActions"), async (original) => ({
30 ...(await original()),
31 usePreparePullRequestThreadAction: (() => ({
32 isAllowed: permissions.checkout,
33 run: vi.fn(),
34 error: null,
35 })) as never,
36}));
37vi.mock(import("./usePullRequestDetail"), async (original) => ({
38 ...(await original()),
39 usePullRequestDetail: (() => ({
40 canWriteSourceControl: permissions.checkout,
41 detailQuery: { isPending: false, refresh: vi.fn() },
42 activityQuery: { isPending: false, refresh: vi.fn(), error: null },
43 activity: null,
44 sharedSummary: shown.detail,
45 coreDetail: shown.detail,
46 detail: shown.detail,
47 })) as never,
48}));
49vi.mock(import("~/state/usePullRequestStack"), async (original) => ({
50 ...(await original()),
51 usePullRequestStack: (() => ({
52 data: null,
53 isFresh: true,
54 isPending: false,
55 error: null,
56 refresh: vi.fn(),
57 })) 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: ((target: unknown) => {
66 reads.diff.push(target);
67 return actual.pullRequestEnvironment.diff(target as never);
68 }) as never,
69 },
70 };
71});
72vi.mock(import("~/state/use-atom-command"), async (original) => ({
73 ...(await original()),
74 useAtomCommand: (() => command) as never,
75}));
76​
77import { createWorkspaceFocusController, workspaceAreaProps } from "~/lib/workspaceFocus";
78import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
79​
80const detail: PullRequestDetailView = {
81 provider: SourceControlProviderKind.make("github"),
82 projectId: ProjectId.make("project"),
83 projectTitle: "Project",
84 workspaceRoot: "/workspace",
85 repository: "owner/repo",
86 number: 1,
87 title: "Test pull request",
88 body: "Original description",
89 url: "https://github.com/owner/repo/pull/1",
90 author: { login: "author", name: null, avatarUrl: null },
91 viewer: "author",
92 state: "open",
93 isDraft: false,
94 mergeability: "conflicting",
95 additions: 1,
96 deletions: 0,
97 changedFiles: 1,
98 headBranch: "feature",
99 baseBranch: "main",
100 createdAt: "2026-09-01T00:00:00Z",
101 updatedAt: "2026-09-01T00:00:00Z",
102 mergedAt: null,
103 closedAt: null,
104 reviewers: [],
105 labels: [],
106 checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
107 comments: [],
108 commentCount: 0,
109 commentsTruncated: false,
110 reviewThreads: [],
111 commits: [],
112 mergeCapabilities: { merge: false, squash: false, rebase: false },
113 capabilities: {
114 diff: true,
115 comment: false,
116 search: true,
117 actions: [],
118 mergeMethods: [],
119 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
120 reviewers: { request: false, listCandidates: false },
121 edit: { changeRequest: true, comment: false },
122 },
123 viewerPermissions: {
124 actions: [],
125 comment: false,
126 resolve: false,
127 verdicts: [],
128 requestReviewers: false,
129 },
130};
131​
132const environmentId = EnvironmentId.make("environment");
133const draftId = DraftId.make("conflicts-draft");
134const panel = (attach = false, reference = detail) => (
135 <PullRequestDetailPanel
136 environmentId={environmentId}
137 reference={reference}
138 context="page"
139 shortcutsEnabled={false}
140 getShortcutContext={() => ({
141 terminalFocus: false,
142 terminalOpen: false,
143 previewFocus: false,
144 previewOpen: false,
145 isWeb: true,
146 isDesktop: false,
147 })}
148 {...(attach ? { composerDraftTarget: draftId } : {})}
149 />
150);
151​
152function setup() {
153 permissions.checkout = true;
154 permissions.operate = true;
155 reads.diff = [];
156 shown.detail = detail;
157 command.mockReset();
158 useComposerDraftStore.setState({ draftsByThreadKey: {} });
160​
161it.each([AuthSourceControlWriteScope, AuthOrchestrationOperateScope])(
162 "disables conflict checkout when the connection loses %s",
163 async (scope) => {
164 setup();
165 await using screen = await render(panel());
166 const resolve = screen.getByRole("button", { name: "Resolve conflicts" });
167 await expect.element(resolve).toBeEnabled();
168 if (scope === AuthSourceControlWriteScope) permissions.checkout = false;
169 else permissions.operate = false;
170 await screen.rerender(panel());
171 await expect.element(resolve).toBeDisabled();
172 },
173);
174​
175it("can still add conflict resolution to an existing composer without checkout scopes", async () => {
176 setup();
177 permissions.checkout = false;
178 permissions.operate = false;
179 await using screen = await render(panel(true));
180 const resolve = screen.getByRole("button", { name: "Resolve conflicts" });
181 await expect.element(resolve).toBeEnabled();
182 await act(() => resolve.click());
183 const draft = useComposerDraftStore.getState().getComposerDraft(draftId);
184 expect(draft?.prompt).toContain("conflicts");
185 expect(draft?.prompt).toContain(detail.url);
186});
187​
188it("keeps a merge and a review on the head the reader was shown until they load new commits", async () => {
189 setup();
190 command.mockResolvedValue({ _tag: "Success", value: undefined });
191 const at = (headSha: string): PullRequestDetailView => ({
192 ...detail,
193 headSha,
194 mergeability: "mergeable",
195 mergeCapabilities: { merge: false, squash: true, rebase: false },
196 capabilities: {
197 ...detail.capabilities,
198 actions: ["merge"],
199 mergeMethods: ["squash"],
200 review: { ...detail.capabilities.review, verdicts: ["approve"] },
201 },
202 viewerPermissions: { ...detail.viewerPermissions, actions: ["merge"], verdicts: ["approve"] },
203 });
204 const sent = (key: "action" | "verdict") =>
205 command.mock.calls.flatMap(([call]) =>
206 call?.input?.[key] === undefined ? [] : [call.input.expectedHeadSha],
207 );
208 const merge = async () => {
209 await screen.getByRole("button", { name: "Squash and merge" }).click();
210 await screen.getByRole("button", { name: "Confirm merge?" }).click();
211 };
212 shown.detail = at("shown-head");
213 await using screen = await render(panel());
214 await expect.element(screen.getByRole("button", { name: "Squash and merge" })).toBeVisible();
215 // A background refresh brings a push the reader has not looked at.
216 shown.detail = at("pushed-head");
217 await screen.rerender(panel());
218 await expect.element(screen.getByText(/still applies to shown-h/)).toBeVisible();
219 await merge();
220 await screen.getByRole("button", { name: "Review pull request" }).click();
221 // The composer popup is portalled outside the rendered tree.
222 await page.getByRole("button", { name: "Submit review" }).click();
223 await vi.waitFor(() => expect(sent("verdict")).toEqual(["shown-head"]));
224 expect(sent("action")).toEqual(["shown-head"]);
225​
226 // The pin moves once the reload has been asked of the host, not at the click.
227 const reload = Promise.withResolvers<{ _tag: "Success"; value: undefined }>();
228 command.mockImplementation((call) =>
229 call?.input?.reference === undefined
230 ? Promise.resolve({ _tag: "Success", value: undefined })
231 : reload.promise,
232 );
233 await screen.getByRole("button", { name: "Load new commits" }).click();
234 await merge();
235 await vi.waitFor(() => expect(sent("action")).toEqual(["shown-head", "shown-head"]));
236 reload.resolve({ _tag: "Success", value: undefined });
237 await expect.element(screen.getByText(/still applies to/)).not.toBeInTheDocument();
238 await merge();
239 await vi.waitFor(() =>
240 expect(sent("action")).toEqual(["shown-head", "shown-head", "pushed-head"]),
241 );
242});
243​
244it("reads the first diff page once the pointer rests on the Code tab", async () => {
245 setup();
246 await using screen = await render(panel());
247 using _timers = fakeTimers({ now: 0 });
248 const code = screen.getByRole("button", { name: "Code", exact: true });
249 await expect.element(code).toBeVisible();
250​
251 await userEvent.hover(code);
252 await act(() => vi.advanceTimersByTime(149));
253 expect(reads.diff).toEqual([]);
254 await act(() => vi.advanceTimersByTime(1));
255 // The page the Code tab reads first, keyed as the tab keys it, so a click paints from it.
256 expect(reads.diff).toContainEqual({
257 environmentId,
258 input: { projectId: detail.projectId, repository: detail.repository, number: detail.number },
259 });
260});
261​
262it("keeps a screen reader's place when scrolling the description condenses the header", async () => {
263 setup();
264 shown.detail = {
265 ...detail,
266 body: Array.from({ length: 80 }, (_, line) => `Line ${line}`).join("\n\n"),
267 };
268 const style = document.createElement("style");
269 style.textContent = appCss;
270 document.head.append(style);
271 using _style = { [Symbol.dispose]: () => style.remove() };
272 const controller = createWorkspaceFocusController(document);
273 using _controller = { [Symbol.dispose]: () => controller.dispose() };
274 await using screen = await render(
275 <div {...workspaceAreaProps("pull-requests", 1)} className="flex h-[600px] flex-col">
276 {panel()}
277 </div>,
278 );
279 const openOnHost = screen.getByRole("button", { name: "Open pull request #1 on host" });
280 await expect.element(openOnHost).toBeVisible();
281 const expanded = openOnHost.element() as HTMLButtonElement;
282 expanded.focus();
283 await expect.element(screen.getByText("Line 79")).toBeInTheDocument();
284 let scroller = screen.getByText("Line 79").element().parentElement;
285 while (scroller && getComputedStyle(scroller).overflowY !== "auto") {
286 scroller = scroller.parentElement;
287 }
288 using _timers = fakeTimers();
289 using moves = vi.spyOn(HTMLElement.prototype, "focus");
290 // Browse mode scrolls a heading into view without moving DOM focus.
291 await act(() => {
292 scroller!.scrollTop = scroller!.scrollHeight;
293 });
294 await vi.waitFor(() => expect(expanded.closest("[inert]")).not.toBeNull());
295 await act(() => vi.advanceTimersToNextFrame());
296 // A programmatic focus() pulls the screen reader's browse cursor back to the header.
297 expect(moves).not.toHaveBeenCalled();
298});