Open History to see the last commit
1import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
2import { createRef, type RefObject, useState } from "react";
3import { page, userEvent } from "vite-plus/test/browser";
4import { describe, expect, it, vi } from "vite-plus/test";
5
6const prPageState = vi.hoisted(() => ({
7 noop: () => {},
8 search: { involvement: "all", state: "open" } as const,
9 environments: {
10 environments: [
11 {
12 environmentId: "env-1",
13 label: "Local",
14 connection: { phase: "connected" },
15 serverConfig: {
16 environment: { capabilities: { pullRequests: true }, platform: { machine: "linux" } },
17 },
18 },
19 ],
20 },
21 projects: [] as ReadonlyArray<never>,
22 hostList: {
23 data: { entries: [], providers: [], viewers: {}, errors: [], cursors: {}, hosts: [] },
24 error: null,
25 isPending: false,
26 observations: [],
27 refresh: () => {},
28 retry: () => {},
29 },
30 stats: {
31 stats: null,
32 isPending: false,
33 refresh: () => {},
34 },
35 turnRefreshes: [] as ReadonlyArray<never>,
36}));
37
38vi.mock(import("@tanstack/react-router"), async (original) => ({
39 ...(await original()),
40 useNavigate: (() => prPageState.noop) as never,
41 useSearch: (() => prPageState.search) as never,
42}));
43vi.mock(import("~/state/server"), async (original) => {
44 const { Atom } = await import("effect/reactivity");
45 return {
46 ...(await original()),
47 primaryServerKeybindingsAtom: Atom.make(DEFAULT_RESOLVED_KEYBINDINGS) as never,
48 };
49});
50vi.mock(import("~/state/environments"), async (original) => ({
51 ...(await original()),
52 useEnvironments: (() => prPageState.environments) as never,
53}));
54vi.mock(import("~/state/entities"), async (original) => ({
55 ...(await original()),
56 useProjects: () => prPageState.projects,
57 useAllEnvironmentShellsBootstrapped: () => true,
58}));
59vi.mock(import("~/state/pullRequests"), async (original) => ({
60 ...(await original()),
61 usePullRequestHostList: (() => prPageState.hostList) as never,
62 usePullRequestListStats: (() => prPageState.stats) as never,
63 usePullRequestTurnRefreshes: (() => prPageState.turnRefreshes) as never,
64 useSharedPullRequestSummary: () => null,
65}));
66
67import { act, render } from "../../../test/render";
68import {
69 PULL_REQUESTS_PANEL_REF,
70 selectThreadRightPanelState,
71 useRightPanelStore,
72} from "~/rightPanelStore";
73import { registerCommands } from "../../shortcuts/dispatcher";
74import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
75import { PullRequestChecksPopover } from "./PullRequestChecksPopover";
76import { PullRequestFiltersMenu, PullRequestSearchInput } from "./PullRequestListFilters";
77import { PullRequestsColumn } from "./PullRequestsColumn";
78import { PullRequestsPage } from "./PullRequestsPage";
79
80import "~/index.css";
81
82function createColumn(maximizedAway: boolean, scrollRef: RefObject<HTMLDivElement | null>) {
83 return (
84 <PullRequestsColumn
85 refreshing={false}
86 onRefresh={() => {}}
87 searchValue=""
88 involvement="all"
89 state="open"
90 host={undefined}
91 hostMenuOptions={[]}
92 onInvolvement={() => {}}
93 onState={() => {}}
94 onHost={() => {}}
95 searchInput={<input aria-label="Search pull requests" />}
96 sortMenu={null}
97 filtersMenu={null}
98 savedViewsMenu={null}
99 rightPanelControl={null}
100 titlebarControls={null}
101 rightPanelOpen={maximizedAway}
102 maximizedAway={maximizedAway}
103 listBody={null}
104 scrollRef={scrollRef}
105 />
106 );
107}
108
109function dispatchFindShortcut(target: EventTarget = window) {
110 const event = new KeyboardEvent("keydown", {
111 key: "f",
112 ctrlKey: true,
113 bubbles: true,
114 cancelable: true,
115 });
116 target.dispatchEvent(event);
117 return event;
118}
119
120describe("PullRequestsColumn find shortcut", () => {
121 it("leaves Cmd/Ctrl+F to the browser while the detail panel is maximized", async () => {
122 const scrollRef = createRef<HTMLDivElement>();
123 await using screen = await render(createColumn(false, scrollRef));
124
125 await screen.rerender(createColumn(true, scrollRef));
126 expect(dispatchFindShortcut().defaultPrevented).toBe(false);
127
128 await screen.rerender(createColumn(false, scrollRef));
129 expect(dispatchFindShortcut().defaultPrevented).toBe(true);
130 await expect
131 .element(screen.getByRole("textbox", { name: "Search pull requests" }))
132 .toHaveFocus();
133 });
134
135 it("ignores Cmd/Ctrl+F while a dialog is open", async () => {
136 const scrollRef = createRef<HTMLDivElement>();
137 await using screen = await render(
138 <>
139 {createColumn(false, scrollRef)}
140 <div role="dialog">
141 <input aria-label="View name" />
142 </div>
143 </>,
144 );
145 const dialogInput = screen.getByRole("textbox", { name: "View name" });
146 await userEvent.click(dialogInput);
147 expect(dispatchFindShortcut(dialogInput.element()).defaultPrevented).toBe(false);
148 await expect.element(dialogInput).toHaveFocus();
149 });
150
151 it("ignores Cmd/Ctrl+F while a menu is open", async () => {
152 const scrollRef = createRef<HTMLDivElement>();
153 await using screen = await render(
154 <>
155 {createColumn(false, scrollRef)}
156 <Menu>
157 <MenuTrigger>Sort</MenuTrigger>
158 <MenuPopup>
159 <MenuItem>Newest</MenuItem>
160 </MenuPopup>
161 </Menu>
162 </>,
163 );
164 await userEvent.click(screen.getByRole("button", { name: "Sort" }));
165 const menu = page.getByRole("menu");
166 await expect.element(menu).toHaveFocus();
167
168 expect(dispatchFindShortcut(menu.element()).defaultPrevented).toBe(false);
169 await expect.element(menu).toHaveFocus();
170 await expect
171 .element(screen.getByRole("textbox", { name: "Search pull requests" }))
172 .not.toHaveFocus();
173 });
174});
175
176function CondensedSearchColumn({
177 scrollRef,
178 onSubmit,
179}: {
180 scrollRef: RefObject<HTMLDivElement | null>;
181 onSubmit: (value: string) => void;
182}) {
183 const [query, setQuery] = useState("label:bug");
184 return (
185 <div style={{ display: "flex", height: 400 }}>
186 <PullRequestsColumn
187 refreshing={false}
188 onRefresh={() => {}}
189 searchValue={query}
190 involvement="all"
191 state="open"
192 host={undefined}
193 hostMenuOptions={[]}
194 onInvolvement={() => {}}
195 onState={() => {}}
196 onHost={() => {}}
197 searchInput={
198 <PullRequestSearchInput
199 value={query}
200 label="Search pull requests"
201 placeholder="Search pull requests"
202 onChange={setQuery}
203 onSubmit={onSubmit}
204 />
205 }
206 sortMenu={null}
207 filtersMenu={null}
208 savedViewsMenu={null}
209 rightPanelControl={null}
210 titlebarControls={null}
211 rightPanelOpen={false}
212 maximizedAway={false}
213 listBody={<div style={{ height: 2000 }} />}
214 scrollRef={scrollRef}
215 />
216 <button type="button">Elsewhere</button>
217 </div>
218 );
219}
220
221describe("PullRequestsColumn condensed search", () => {
222 it("Escape clears the topbar search before the page's Escape leaves", async () => {
223 const onSubmit = vi.fn();
224 const scrollRef = createRef<HTMLDivElement>();
225 await using _screen = await render(
226 <CondensedSearchColumn scrollRef={scrollRef} onSubmit={onSubmit} />,
227 );
228 // Mirrors the /pull-requests observer, which leaves on an unclaimed Escape.
229 const leave = vi.fn();
230 using stack = new DisposableStack();
231 stack.defer(
232 registerCommands(
233 {},
234 {
235 observe: (event, consumed) => {
236 if (!consumed && !event.repeat && !event.isComposing && event.key === "Escape") leave();
237 },
238 },
239 ),
240 );
241 scrollRef.current?.scrollTo({ top: 1000 });
242 const searches = page.getByRole("searchbox", { name: "Search pull requests" });
243 // The topbar copy comes first and mounts once the header condenses.
244 await expect.element(searches.nth(1)).toBeInTheDocument();
245 const search = searches.nth(0);
246 // Safari ends the composition just before the confirming keydown, reporting only keyCode 229.
247 const pressDuringComposition = (key: string) =>
248 act(() => {
249 for (const composition of [{ isComposing: true }, { keyCode: 229 }]) {
250 search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true }));
251 search
252 .element()
253 .dispatchEvent(new KeyboardEvent("keydown", { key, ...composition, bubbles: true }));
254 }
255 });
256
257 await userEvent.click(search);
258 await pressDuringComposition("Enter");
259 await pressDuringComposition("Escape");
260 expect(onSubmit).not.toHaveBeenCalled();
261 expect(leave).not.toHaveBeenCalled();
262 await expect.element(search).toHaveValue("label:bug");
263
264 await userEvent.keyboard("{Escape}");
265 await expect.element(search).toHaveValue("");
266 await expect.element(search).toHaveFocus();
267 expect(leave).not.toHaveBeenCalled();
268
269 await userEvent.keyboard("{Escape}");
270 expect(leave).toHaveBeenCalledOnce();
271
272 await userEvent.click(page.getByRole("button", { name: "Elsewhere" }));
273 await expect
274 .element(page.getByRole("button", { name: "Search pull requests" }))
275 .toBeInTheDocument();
276 });
277});
278
279describe("PullRequestChecksPopover", () => {
280 it("keeps clicks inside the popover from selecting the parent row", async () => {
281 const onSelect = vi.fn();
282 await using screen = await render(
283 <button type="button" onClick={onSelect}>
284 <span>Open PR</span>
285 <PullRequestChecksPopover
286 checksState="failing"
287 checks={[
288 { name: "Lint", status: "failure", description: null, url: null },
289 { name: "Test", status: "success", description: null, url: null },
290 ]}
291 />
292 </button>,
293 );
294
295 await userEvent.click(
296 screen.getByRole("button", { name: "Checks: Some checks were not successful" }),
297 );
298 await userEvent.click(page.getByRole("button", { name: "Show all" }));
299 await expect.element(page.getByText("Test", { exact: true })).toBeInTheDocument();
300 expect(onSelect).not.toHaveBeenCalled();
301
302 await userEvent.keyboard("{Escape}");
303 await userEvent.click(screen.getByText("Open PR", { exact: true }));
304 expect(onSelect).toHaveBeenCalledOnce();
305 });
306});
307
308describe("PullRequestsPage shortcuts", () => {
309 it("ignores right panel shortcuts while a menu is open", async () => {
310 useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} });
311 useRightPanelStore.getState().openPullRequest(PULL_REQUESTS_PANEL_REF, {
312 environmentId: "env-1",
313 projectId: "project-1",
314 repository: "owner/repo",
315 number: 7,
316 });
317 using _cleanup = {
318 [Symbol.dispose]: () =>
319 useRightPanelStore.setState({ byThreadKey: {}, userActionRevisionByThreadKey: {} }),
320 };
321 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
322 await using screen = await render(<PullRequestsPage />);
323 const panelState = () =>
324 selectThreadRightPanelState(
325 useRightPanelStore.getState().byThreadKey,
326 PULL_REQUESTS_PANEL_REF,
327 );
328 await vi.waitFor(() => expect(panelState().isOpen).toBe(true));
329
330 await userEvent.click(screen.getByRole("button", { name: /^Sort pull requests:/ }));
331 const menu = page.getByRole("menu");
332 await expect.element(menu).toBeVisible();
333
334 await act(() => {
335 for (const init of [
336 { key: "b", ctrlKey: true, altKey: true },
337 { key: "w", ctrlKey: true },
338 ]) {
339 document.body.dispatchEvent(
340 new KeyboardEvent("keydown", { ...init, bubbles: true, cancelable: true }),
341 );
342 }
343 });
344
345 await expect.element(menu).toBeVisible();
346 await vi.waitFor(() => {
347 const panel = panelState();
348 expect(panel.isOpen).toBe(true);
349 expect(panel.surfaces).toHaveLength(1);
350 });
351 });
352});
353
354describe("PullRequestFiltersMenu keyboard focus", () => {
355 it("focuses Author and Labels search inputs when opened from the keyboard", async () => {
356 const onFilters = vi.fn();
357 const Icon = () => null;
358 await using screen = await render(
359 <PullRequestFiltersMenu
360 state="open"
361 stateOptions={[{ value: "open", label: "Open", Icon }]}
362 onState={() => {}}
363 involvement="all"
364 involvementOptions={[{ value: "all", label: "All", Icon }]}
365 onInvolvement={() => {}}
366 filters={{}}
367 onFilters={onFilters}
368 authorOptions={[
369 { actor: { login: "alice", name: null, avatarUrl: null }, count: 1, mergedCount: 0 },
370 { actor: { login: "julius", name: null, avatarUrl: null }, count: 2, mergedCount: 2 },
371 ]}
372 labelOptions={[
373 { name: "bug", color: "d73a4a", count: 3 },
374 { name: "docs", color: "0075ca", count: 1 },
375 ]}
376 optionScope={[]}
377 host={undefined}
378 hostOptions={[]}
379 onHost={() => {}}
380 server={undefined}
381 serverOptions={[]}
382 onServer={() => {}}
383 projects={[]}
384 projectId={undefined}
385 projectEnvironmentId={undefined}
386 unavailable={new Map()}
387 onProject={() => {}}
388 />,
389 { router: false },
390 );
391
392 const filtersButton = screen.getByRole("button", { name: "Filters" });
393 filtersButton.element().focus();
394 await expect.element(filtersButton).toHaveFocus();
395 await userEvent.keyboard("{Enter}");
396
397 const authorTrigger = page.getByRole("menuitem", { name: /Author/ });
398 const labelsTrigger = page.getByRole("menuitem", { name: /Labels/ });
399 await expect.element(authorTrigger).toBeVisible();
400
401 await userEvent.keyboard("{ArrowDown}{ArrowDown}");
402 await expect.element(authorTrigger).toHaveFocus();
403 await userEvent.keyboard("{ArrowRight}");
404
405 const authorSearch = page.getByPlaceholder("Search authors");
406 await expect.element(authorSearch).toHaveFocus();
407
408 await userEvent.keyboard("{ArrowLeft}");
409 await expect.element(authorSearch).not.toBeInTheDocument();
410 await expect.element(authorTrigger).toHaveFocus();
411
412 await userEvent.keyboard("{ArrowRight}");
413 await expect.element(authorSearch).toHaveFocus();
414 await userEvent.keyboard("jul");
415 await expect.element(page.getByRole("menuitemradio", { name: /julius/ })).toBeVisible();
416 await expect
417 .element(page.getByRole("menuitemradio", { name: /alice/ }))
418 .not.toBeInTheDocument();
419
420 await userEvent.keyboard("{ArrowLeft}");
421 await vi.waitFor(() => {
422 expect((authorSearch.element() as HTMLInputElement).selectionStart).toBe(2);
423 });
424
425 await userEvent.keyboard("{ArrowDown}{ArrowDown}{Enter}");
426 await vi.waitFor(() => {
427 expect(onFilters).toHaveBeenLastCalledWith({ author: "julius" });
428 });
429
430 await userEvent.keyboard("{Escape}");
431 await expect.element(authorTrigger).toHaveFocus();
432
433 await userEvent.keyboard("{ArrowDown}");
434 await expect.element(labelsTrigger).toHaveFocus();
435 await userEvent.keyboard("{Enter}");
436
437 const labelsSearch = page.getByPlaceholder("Search labels");
438 await expect.element(labelsSearch).toHaveFocus();
439 await userEvent.keyboard("docs");
440 await expect.element(page.getByRole("menuitemcheckbox", { name: /docs/ })).toBeVisible();
441 await expect
442 .element(page.getByRole("menuitemcheckbox", { name: /bug/ }))
443 .not.toBeInTheDocument();
444
445 await userEvent.keyboard("{ArrowDown}{Enter}");
446 await vi.waitFor(() => {
447 expect(onFilters).toHaveBeenLastCalledWith({ labels: [["docs"]] });
448 });
449
450 await userEvent.keyboard("{Escape}");
451 await expect.element(labelsTrigger).toHaveFocus();
452 });
453});