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

PullRequestSummaryTab.browser.test.tsx

473 lines16.1 KB

1import {
2 DEFAULT_CLIENT_SETTINGS,
3 SourceControlProviderKind,
4 type ClientSettings,
5} from "@t3tools/contracts";
6import { EnvironmentId, ProjectId, type PullRequestDetailView } from "@t3tools/contracts";
7import { expect, it, vi } from "vite-plus/test";
8import { userEvent } from "vite-plus/test/browser";
9​
10const state = vi.hoisted(() => ({
11 update: vi.fn(),
12 canUpdate: true,
13 timestampFormat: "locale" as "locale" | "12-hour" | "24-hour",
14 openLink: vi.fn(async () => {}),
15}));
16​
17vi.mock(import("~/browser/useOpenLink"), () => ({ useOpenLink: () => state.openLink }));
18​
19vi.mock(import("~/state/use-atom-command"), async (original) => ({
20 ...(await original()),
21 useAtomCommand: (() => state.update) as never,
22}));
23vi.mock(import("~/state/session"), async (original) => ({
24 ...(await original()),
25 readEnvironmentScope: () => true,
26 useEnvironmentScope: () => true,
27}));
28vi.mock(import("~/hooks/useSettings"), async (original) => ({
29 ...(await original()),
30 useClientSettings: ((select?: (settings: ClientSettings) => unknown) => {
31 const settings = { ...DEFAULT_CLIENT_SETTINGS, timestampFormat: state.timestampFormat };
32 return select ? select(settings) : settings;
33 }) as never,
34}));
35vi.mock(import("~/state/pullRequests"), async (original) => {
36 const actual = await original();
37 const { Atom } = await import("effect/reactivity");
38 const allowed = Atom.make(true);
39 const denied = Atom.make(false);
40 return {
41 ...actual,
42 pullRequestEnvironment: {
43 ...actual.pullRequestEnvironment,
44 update: {
45 ...actual.pullRequestEnvironment.update,
46 permissionAtom: () => (state.canUpdate ? allowed : denied),
47 },
48 },
49 };
50});
51​
52function setup() {
53 state.update.mockReset();
54 state.update.mockResolvedValue({ _tag: "Success", value: undefined });
55 state.canUpdate = true;
56 state.timestampFormat = "locale";
57 state.openLink.mockClear();
59​
60import "~/index.css";
61import { workspaceAreaProps } from "~/lib/workspaceFocus";
62import { act, render as renderUi } from "../../../test/render";
63import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
64​
65const detail: PullRequestDetailView = {
66 provider: SourceControlProviderKind.make("github"),
67 projectId: ProjectId.make("project"),
68 projectTitle: "Project",
69 workspaceRoot: "/workspace",
70 repository: "owner/repo",
71 number: 1,
72 title: "Test pull request",
73 body: "Original description",
74 url: "https://github.com/owner/repo/pull/1",
75 author: { login: "author", name: null, avatarUrl: null },
76 viewer: "author",
77 state: "open",
78 isDraft: false,
79 mergeability: "mergeable",
80 additions: 1,
81 deletions: 0,
82 changedFiles: 1,
83 headBranch: "feature",
84 baseBranch: "main",
85 createdAt: "2026-09-01T00:00:00Z",
86 updatedAt: "2026-09-01T00:00:00Z",
87 mergedAt: null,
88 closedAt: null,
89 reviewers: [],
90 labels: [],
91 checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
92 comments: [],
93 commentCount: 0,
94 commentsTruncated: false,
95 reviewThreads: [],
96 commits: [],
97 mergeCapabilities: { merge: false, squash: false, rebase: false },
98 capabilities: {
99 diff: true,
100 comment: true,
101 search: true,
102 actions: [],
103 mergeMethods: [],
104 review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
105 reviewers: { request: false, listCandidates: false },
106 edit: { changeRequest: true, comment: true },
107 },
108 viewerPermissions: {
109 actions: [],
110 comment: true,
111 resolve: false,
112 verdicts: [],
113 requestReviewers: false,
114 },
115};
116​
117// The comment filter persists to localStorage, so tests that touch it start and end empty.
118​
119const tab = (value = detail) => (
120 <PullRequestSummaryTab
121 scrollerRef={() => {}}
122 environmentId={EnvironmentId.make("environment")}
123 threadRef={null}
124 reference={value}
125 detail={value}
126 observedAt={value.observedAt}
127 activityPending={false}
128 activityError={null}
129 onRefresh={() => {}}
130 />
131);
132​
133async function render(value = detail) {
134 const screen = await renderUi(tab(value));
135 const { container } = screen;
136 const heading = (title: string) => {
137 const section = container.querySelector(`section[aria-label="${title}"]`);
138 expect(section, `section ${title}`).not.toBeNull();
139 return [...section!.querySelectorAll("button")].find(
140 (button) => button.querySelector("span")?.textContent === title,
141 )!;
142 };
143 return Object.assign(screen, {
144 click: (title: string) => act(async () => heading(title).click()),
145 expanded: (title: string) => heading(title).getAttribute("aria-expanded"),
146 visibleText: () => container.innerText,
147 });
149​
150it("keeps an unsaved description when collapsed and reopened, and after a failed save", async () => {
151 setup();
152 state.update.mockResolvedValue({ _tag: "Failure", cause: new Error("offline") });
153 await using screen = await render();
154 await act(async () =>
155 screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
156 );
157 const textarea = screen.container.querySelector("textarea")!;
158 await userEvent.clear(textarea);
159 await userEvent.type(textarea, "Unsaved description");
160 await screen.click("Description");
161 expect(screen.expanded("Description")).toBe("false");
162 await screen.click("Description");
163 expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");
164​
165 await userEvent.click(screen.getByRole("button", { name: "Save" }));
166 expect(state.update).toHaveBeenCalledTimes(1);
167 await expect.element(screen.getByRole("button", { name: "Save" })).toBeEnabled();
168 expect(screen.container.querySelector("textarea")!.value).toBe("Unsaved description");
169});
170​
171it("ticks a description checkbox placed after an attachment and edits from the ticked body", async () => {
172 setup();
173 let finishSave = (_result: unknown) => {};
174 state.update.mockReturnValueOnce(new Promise((resolve) => (finishSave = resolve)));
175 const body = "Intro\n\nhttps://example.com/shot.png\n\n## Test plan\n- [ ] First\n- [ ] Second";
176 const ticked = body.replace("- [ ] Second", "- [x] Second");
177 await using screen = await render({ ...detail, body, observedAt: 1 });
178 const boxes = () => screen.container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]');
179 expect([...boxes()].map((box) => box.disabled)).toEqual([false, false]);
180​
181 await userEvent.click(boxes()[1]!);
182 expect(state.update).toHaveBeenCalledWith({
183 environmentId: "environment",
184 input: expect.objectContaining({ number: 1, body: ticked }),
185 });
186 expect([...boxes()].map((box) => box.checked)).toEqual([false, true]);
187 await act(async () => finishSave({ _tag: "Success", value: undefined }));
188​
189 // The host has not been read since the save, so the editor starts from the ticked body.
190 await act(async () =>
191 screen.container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
192 );
193 expect(screen.container.querySelector("textarea")!.value).toBe(ticked);
194});
195​
196it("leaves description checkboxes read-only without the right to edit it", async () => {
197 setup();
198 const body = "- [ ] First";
199 {
200 await using screen = await render({ ...detail, body, viewer: "someone-else" });
201 expect(
202 screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.disabled,
203 ).toBe(true);
204 }
205 state.canUpdate = false;
206 await using screen = await render({ ...detail, body });
207 expect(screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!.disabled).toBe(
208 true,
209 );
210});
211​
212it("fixes an overview thread as its opening remark, since it has no line to attach", async () => {
213 setup();
214 const author = { login: "reviewer", name: null, avatarUrl: null };
215 const note = { author, createdAt: "2026-09-01T00:00:00Z", url: null };
216 const remark = {
217 ...note,
218 id: "10",
219 kind: "review-comment" as const,
220 body: "Mention the flag in the README",
221 path: null,
222 reviewState: null,
223 };
224 const onFixFinding = vi.fn();
225 const value: PullRequestDetailView = {
226 ...detail,
227 comments: [remark],
228 overviewThreads: [
229 {
230 id: "overview",
231 path: null,
232 line: null,
233 side: "right",
234 isResolved: false,
235 isOutdated: false,
236 comments: [{ ...note, id: "10", body: remark.body }],
237 },
238 ],
239 };
240 await using screen = await renderUi(
241 <PullRequestSummaryTab
242 scrollerRef={() => {}}
243 environmentId={EnvironmentId.make("environment")}
244 threadRef={null}
245 reference={value}
246 detail={value}
247 observedAt={value.observedAt}
248 activityPending={false}
249 activityError={null}
250 onRefresh={() => {}}
251 onFixFinding={onFixFinding}
252 />,
253 );
254​
255 await userEvent.click(screen.getByRole("button", { name: "Fix in a thread" }));
256 expect(onFixFinding).toHaveBeenCalledWith({ kind: "comment", comment: remark });
257});
258​
259it("shows a comment's exact time in the chosen 24-hour clock", async () => {
260 setup();
261 state.timestampFormat = "24-hour";
262 const createdAt = "2026-09-01T17:30:00Z";
263 const comment = {
264 id: "10",
265 kind: "review-comment" as const,
266 body: "A remark",
267 author: { login: "reviewer", name: null, avatarUrl: null },
268 createdAt,
269 url: null,
270 path: null,
271 reviewState: null,
272 };
273 await using screen = await render({ ...detail, comments: [comment], commentCount: 1 });
274​
275 await userEvent.hover(screen.container.querySelector(`time[datetime="${createdAt}"]`)!);
276 const expected = new Date(createdAt).toLocaleString(undefined, { hour12: false });
277 await vi.waitFor(() =>
278 expect(document.querySelector('[data-slot="tooltip-popup"]')?.textContent).toBe(expected),
279 );
280});
281​
282it("keeps the chosen comment order when the right panel remounts the tab", async () => {
283 setup();
284 const comment = (id: string, createdAt: string) => ({
285 id,
286 kind: "review-comment" as const,
287 body: `Remark ${id}`,
288 author: { login: "reviewer", name: null, avatarUrl: null },
289 createdAt,
290 url: null,
291 path: null,
292 reviewState: null,
293 });
294 const value = {
295 ...detail,
296 comments: [comment("10", "2026-09-01T10:00:00Z"), comment("11", "2026-09-02T10:00:00Z")],
297 commentCount: 2,
298 };
299 {
300 await using screen = await render(value);
301 await userEvent.click(screen.getByRole("button", { name: "Show oldest comments first" }));
302 await expect
303 .element(screen.getByRole("button", { name: "Show newest comments first" }))
304 .toBeVisible();
305 }
306 // Switching to another right-panel tab unmounts the pull request surface.
307 await using screen = await render(value);
308 await expect
309 .element(screen.getByRole("button", { name: "Show newest comments first" }))
310 .toBeVisible();
311});
312​
313it("comes back at the scroll position it left when the right panel remounts the tab", async () => {
314 setup();
315 const body = Array.from({ length: 80 }, (_, index) => `Paragraph ${index}`).join("\n\n");
316 const value = { ...detail, body, url: "https://github.com/owner/repo/pull/2" };
317 const mount = async (shown = value) => {
318 const container = document.createElement("div");
319 container.className = "flex h-[300px]";
320 const screen = await renderUi(tab(shown), { container });
321 const scroller = container.querySelector<HTMLElement>("[data-pull-request-summary-scroll]")!;
322 return Object.assign(screen, { scroller });
323 };
324 {
325 await using screen = await mount();
326 screen.scroller.scrollTop = 500;
327 await vi.waitFor(() => expect(screen.scroller.scrollTop).toBe(500));
328 await act(async () => screen.scroller.dispatchEvent(new Event("scroll")));
329 }
330 // The tab can come back before the content that reached that position has loaded.
331 await using screen = await mount({ ...value, body: "Paragraph 0" });
332 await screen.rerender(tab(value));
333 await vi.waitFor(() => expect(screen.scroller.scrollTop).toBe(500));
334 await screen.unmount();
335 await using again = await mount();
336 expect(again.scroller.scrollTop).toBe(500);
337});
338​
339it("scrolls from the keyboard after a click inside it", async () => {
340 setup();
341 const body = Array.from({ length: 80 }, (_, index) => `Paragraph ${index}`).join("\n\n");
342 const container = document.createElement("div");
343 container.className = "flex h-[300px]";
344 await using screen = await renderUi(
345 // The panel area takes focus itself, so a click on plain text lands on it unless the tab can.
346 <div {...workspaceAreaProps("panel", 4, "Workspace panel")} className="flex min-w-0 flex-1">
347 {tab({ ...detail, body })}
348 </div>,
349 { container },
350 );
351 const scroller = container.querySelector<HTMLElement>("[data-pull-request-summary-scroll]")!;
352 await userEvent.click(screen.getByText("Paragraph 0", { exact: true }));
353 await userEvent.keyboard("{PageDown}");
354 await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(0));
355});
356​
357it("opens comment timestamps through the link-target setting, not a popup", async () => {
358 setup();
359 const author = { login: "reviewer", name: null, avatarUrl: null };
360 const comment = (id: string, reviewState: string | null) => ({
361 id,
362 kind: "review" as const,
363 body: `Remark ${id}`,
364 author,
365 createdAt: `2026-09-0${id}T00:00:00Z`,
366 url: `${detail.url}#review-${id}`,
367 path: null,
368 reviewState,
369 });
370 // The dismissed review renders as a collapsed card; show it with the resolved filter on.
371 localStorage.setItem(
372 "t3code:pull-request-comment-filter:v1",
373 JSON.stringify({ bots: false, resolved: true }),
374 );
375 try {
376 await using screen = await render({
377 ...detail,
378 comments: [comment("1", null), comment("2", "DISMISSED")],
379 commentCount: 2,
380 });
381 for (const id of ["1", "2"]) {
382 const href = `${detail.url}#review-${id}`;
383 const link = screen.container.querySelector(`a[href="${href}"]`);
384 expect(link, href).not.toBeNull();
385 state.openLink.mockClear();
386 const click = new MouseEvent("click", { bubbles: true, cancelable: true });
387 link!.dispatchEvent(click);
388​
389 expect(click.defaultPrevented).toBe(true);
390 expect(state.openLink).toHaveBeenCalledOnce();
391 expect(state.openLink).toHaveBeenCalledWith(href, { event: expect.anything() });
392 }
393 } finally {
394 localStorage.removeItem("t3code:pull-request-comment-filter:v1");
395 }
396});
397​
398it("opens a comment author's profile through the link-target setting, not a popup", async () => {
399 setup();
400 await using screen = await render({
401 ...detail,
402 comments: [
403 {
404 id: "1",
405 kind: "issue-comment" as const,
406 body: "Looks good",
407 author: { login: "reviewer", name: null, avatarUrl: null },
408 createdAt: "2026-09-01T00:00:00Z",
409 url: null,
410 path: null,
411 reviewState: null,
412 },
413 ],
414 commentCount: 1,
415 });
416 const link = await vi.waitFor(() => {
417 const found = screen.container.querySelector('a[aria-label="Open reviewer\'s profile"]');
418 expect(found).not.toBeNull();
419 return found!;
420 });
421 const href = link.getAttribute("href")!;
422 const click = new MouseEvent("click", { bubbles: true, cancelable: true });
423 link.dispatchEvent(click);
424​
425 expect(click.defaultPrevented).toBe(true);
426 expect(state.openLink).toHaveBeenCalledOnce();
427 expect(state.openLink).toHaveBeenCalledWith(href, { event: expect.anything() });
428});
429​
430it("opens a thread's remaining replies through the link-target setting, not a popup", async () => {
431 setup();
432 await using screen = await render({
433 ...detail,
434 reviewThreads: [
435 {
436 id: "thread",
437 path: "a.ts",
438 line: 3,
439 side: "right",
440 isResolved: false,
441 isOutdated: false,
442 commentCount: 3,
443 comments: [
444 {
445 id: "comment",
446 body: "Please rename this",
447 author: { login: "reviewer", name: null, avatarUrl: null },
448 createdAt: "2026-09-01T00:00:00Z",
449 url: "https://github.com/owner/repo/pull/1#discussion_r1",
450 },
451 ],
452 },
453 ],
454 });
455 const link = await vi.waitFor(() => {
456 const found = [...screen.container.querySelectorAll("a")].find(
457 (anchor) => anchor.textContent === "View on host",
458 );
459 expect(found).toBeDefined();
460 return found!;
461 });
462 const click = new MouseEvent("click", { bubbles: true, cancelable: true });
463 link.dispatchEvent(click);
464​
465 expect(click.defaultPrevented).toBe(true);
466 expect(state.openLink).toHaveBeenCalledOnce();
467 expect(state.openLink).toHaveBeenCalledWith(
468 "https://github.com/owner/repo/pull/1#discussion_r1",
469 {
470 event: expect.anything(),
471 },
472 );
473});