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

RightPanelTabs.browser.test.tsx

563 lines20.8 KB

1import "~/index.css";
2​
3import { EnvironmentId } from "@t3tools/contracts";
4import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
5import { describe, expect, it, vi } from "vite-plus/test";
6import { commands, page, userEvent } from "vite-plus/test/browser";
7​
8import { InputGroup, InputGroupAddon, InputGroupInput } from "~/components/ui/input-group";
9import { dismissContextMenu, showContextMenuFallback } from "~/contextMenuFallback";
10import type { RightPanelSurface } from "~/rightPanelStore";
11import { act, render, stubGlobal } from "../../test/render";
12import { HistorySwipeNavigation } from "./HistorySwipeNavigation";
13import { RightPanelTabs, type RightPanelTabsProps } from "./RightPanelTabs";
14import { subscribePreviewAction } from "./preview/previewActionBus";
15​
16const navigateHistory = vi.hoisted(() => vi.fn());
17vi.mock("../navigationHistory", () => ({ canNavigateHistory: () => true, navigateHistory }));
18​
19// Chromium starts a gesture scroll, and Electron reports its begin, only for a
20// wheel event the page did not preventDefault; it then scrolls the latched scroller.
21function trackpad() {
22 const begin = new Set<() => void>();
23 const end = new Set<() => void>();
24 const subscribe = (listeners: Set<() => void>) => (listener: () => void) => {
25 listeners.add(listener);
26 return () => listeners.delete(listener);
27 };
28 let scrolling = false;
29 return {
30 bridge: {
31 onTrackpadScrollBegin: subscribe(begin),
32 onTrackpadScrollEnd: subscribe(end),
33 onMenuAction: () => () => {},
34 },
35 scroll(target: Element, deltas: readonly number[]) {
36 let scroller: Element | null = target;
37 while (
38 scroller &&
39 (scroller.scrollWidth <= scroller.clientWidth ||
40 !/auto|scroll/.test(getComputedStyle(scroller).overflowX))
41 ) {
42 scroller = scroller.parentElement;
43 }
44 for (const deltaX of deltas) {
45 const event = new WheelEvent("wheel", {
46 deltaX,
47 bubbles: true,
48 cancelable: true,
49 composed: true,
50 });
51 target.dispatchEvent(event);
52 if (event.defaultPrevented) continue;
53 if (scroller) scroller.scrollLeft += deltaX;
54 if (scrolling) continue;
55 scrolling = true;
56 for (const listener of begin) listener();
57 }
58 if (scrolling) for (const listener of end) listener();
59 scrolling = false;
60 },
61 };
63​
64const surfaces: RightPanelSurface[] = Array.from({ length: 16 }, (_, index) => ({
65 id: `terminal:${index}`,
66 kind: "terminal",
67 resourceId: `${index}`,
68 terminalIds: [`${index}`],
69 activeTerminalId: `${index}`,
70}));
71​
72describe("RightPanelTabs", () => {
73 it("a flick that scrolls the tab strip to its left edge keeps the thread, and so does a swipe from the edge", async () => {
74 navigateHistory.mockReset();
75 const { bridge, scroll } = trackpad();
76 using _bridge = stubGlobal("desktopBridge", bridge);
77 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
78 const panel = document.createElement("div");
79 panel.style.cssText = "width: 320px; height: 200px; display: flex";
80 const noop = () => {};
81 await using screen = await render(
82 <>
83 <HistorySwipeNavigation />
84 <RightPanelTabs
85 mode="embedded"
86 keybindings={[]}
87 getShortcutContext={() => ({
88 terminalFocus: false,
89 terminalOpen: false,
90 previewFocus: false,
91 previewOpen: false,
92 isWeb: true,
93 isDesktop: false,
94 })}
95 surfaces={surfaces}
96 environmentId={null}
97 activeSurfaceId={null}
98 pendingSurfaceIds={new Set()}
99 previewSessions={{}}
100 desktopByTabId={{}}
101 terminalLabelsById={new Map(surfaces.map((surface) => [surface.id, "Terminal"]))}
102 onActivate={noop}
103 onCloseSurface={noop}
104 onCloseSelectedSurfaces={noop}
105 onCloseOtherSurfaces={noop}
106 onCloseSurfacesToRight={noop}
107 onCloseAllSurfaces={noop}
108 onCopyFilePath={noop}
109 onAddBrowser={noop}
110 onAddBrowserInProfile={noop}
111 onAddTerminal={noop}
112 onAddDiff={noop}
113 onAddFiles={noop}
114 onAddPullRequest={noop}
115 onAddPullRequests={noop}
116 onAddDevice={noop}
117 browserAvailable={false}
118 terminalAvailable
119 diffAvailable={false}
120 filesAvailable={false}
121 pullRequestAvailable={false}
122 pullRequestsAvailable={false}
123 deviceAvailable={false}
124 >
125 {null}
126 </RightPanelTabs>
127 </>,
128 { container: panel },
129 );
130 const viewport = screen.container.querySelector<HTMLElement>(
131 '[data-right-panel-tab-list] [data-slot="scroll-area-viewport"]',
132 )!;
133 expect(viewport.scrollWidth - viewport.clientWidth).toBeGreaterThan(120);
134 viewport.scrollLeft = 120;
135​
136 const momentum = Array.from({ length: 24 }, (_, index) => -60 * 0.85 ** index);
137 scroll(viewport.querySelector("[data-active-tab]")!, [-10, -20, -30, ...momentum]);
138​
139 expect(viewport.scrollLeft).toBe(0);
140 expect(navigateHistory).not.toHaveBeenCalled();
141​
142 viewport.scrollLeft = 0;
143 scroll(viewport.querySelector("[data-active-tab]")!, [-40, -40, -40, -40, -40]);
144​
145 expect(navigateHistory).not.toHaveBeenCalled();
146 });
147});
148​
149const BROWSER_SURFACE: RightPanelSurface = {
150 id: "browser:tab-1",
151 kind: "preview",
152 resourceId: "tab-1",
153};
154const DIFF_SURFACE: RightPanelSurface = { id: "diff", kind: "diff" };
155​
156function panel(activeSurface: RightPanelSurface) {
157 const noop = () => {};
158 const props: RightPanelTabsProps = {
159 mode: "inline",
160 keybindings: [],
161 getShortcutContext: () => ({
162 terminalFocus: false,
163 terminalOpen: false,
164 previewFocus: false,
165 previewOpen: true,
166 isWeb: true,
167 isDesktop: false,
168 }),
169 surfaces: [BROWSER_SURFACE, DIFF_SURFACE],
170 environmentId: EnvironmentId.make("environment-local"),
171 activeSurfaceId: activeSurface.id,
172 pendingSurfaceIds: new Set(),
173 previewSessions: {},
174 desktopByTabId: {},
175 terminalLabelsById: new Map(),
176 onActivate: noop,
177 onCloseSurface: noop,
178 onCloseSelectedSurfaces: noop,
179 onCloseOtherSurfaces: noop,
180 onCloseSurfacesToRight: noop,
181 onCloseAllSurfaces: noop,
182 onCopyFilePath: noop,
183 onAddBrowser: noop,
184 onAddBrowserInProfile: noop,
185 onAddTerminal: noop,
186 onAddDiff: noop,
187 onAddFiles: noop,
188 onAddPullRequest: noop,
189 onAddPullRequests: noop,
190 onAddDevice: noop,
191 browserAvailable: true,
192 terminalAvailable: true,
193 diffAvailable: true,
194 filesAvailable: true,
195 pullRequestAvailable: true,
196 pullRequestsAvailable: true,
197 deviceAvailable: true,
198 children: (
199 <div data-testid="surface-content">
200 {/* Stands in for ServerBrowserSurface, whose page canvas handles thumb buttons itself. */}
201 <canvas data-testid="page-canvas" onMouseUp={(event) => event.preventDefault()} />
202 <InputGroup>
203 <InputGroupInput aria-label="Address" />
204 <InputGroupAddon data-testid="address-addon" align="inline-end" />
205 </InputGroup>
206 </div>
207 ),
208 };
209 return <RightPanelTabs {...props} />;
211​
212it("shows scroll arrows only when the panel tabs and add button cannot fit", async () => {
213 const files: RightPanelSurface[] = ["architecture", "configuration", "implementation"].map(
214 (section) => ({
215 id: `file:${section}`,
216 kind: "file",
217 relativePath: `workspace-${section}-notes.txt`,
218 revealLine: null,
219 revealRequestId: 0,
220 }),
221 );
222 const container = document.createElement("div");
223 container.style.cssText = "width: 320px; height: 200px; display: flex";
224 await using screen = await render(
225 <RightPanelTabs
226 {...(panel(DIFF_SURFACE).props as RightPanelTabsProps)}
227 mode="embedded"
228 surfaces={[DIFF_SURFACE, ...files]}
229 >
230 {null}
231 </RightPanelTabs>,
232 { container },
233 );
234 const arrows = screen.getByRole("group", { name: "Scroll panel tabs" });
235 const addButton = screen.getByRole("button", { name: "Add panel surface" }).element();
236 const viewport = screen.container.querySelector<HTMLElement>(
237 '[data-slot="scroll-area-viewport"]',
238 )!;
239 await expect.element(arrows).toBeVisible();
240​
241 const stripWidth =
242 arrows.element().getBoundingClientRect().right - viewport.getBoundingClientRect().left;
243 const fitWidth = container.clientWidth + viewport.scrollWidth - stripWidth;
244 container.style.width = `${fitWidth + 3}px`;
245 await expect.element(arrows).not.toBeInTheDocument();
246​
247 const visibleBounds = viewport.getBoundingClientRect();
248 for (const element of [...viewport.querySelectorAll("[data-active-tab]"), addButton]) {
249 const bounds = element.getBoundingClientRect();
250 expect(bounds.left).toBeGreaterThanOrEqual(visibleBounds.left);
251 expect(bounds.right).toBeLessThanOrEqual(visibleBounds.right);
252 }
253​
254 container.style.width = `${fitWidth - 3}px`;
255 await expect.element(arrows).toBeVisible();
256 container.style.width = `${fitWidth + 3}px`;
257 await expect.element(arrows).not.toBeInTheDocument();
258});
259​
260it("drags a Shift-clicked range and closes it from a selected tab's menu", async () => {
261 const files: RightPanelSurface = { id: "files", kind: "files" };
262 const linkedItems: RightPanelSurface = { id: "pull-requests", kind: "pull-requests" };
263 const onMoveSurfaces = vi.fn();
264 const onCloseSelectedSurfaces = vi.fn();
265 await using screen = await render(
266 <RightPanelTabs
267 {...(panel(DIFF_SURFACE).props as RightPanelTabsProps)}
268 surfaces={[DIFF_SURFACE, files, linkedItems]}
269 onMoveSurfaces={onMoveSurfaces}
270 onCloseSelectedSurfaces={onCloseSelectedSurfaces}
271 >
272 {null}
273 </RightPanelTabs>,
274 );
275 const diffTab = screen.getByRole("button", { name: "Diff", exact: true });
276 const filesTab = screen.getByRole("button", { name: "Files", exact: true });
277 const linkedItemsTab = screen.getByRole("button", { name: "Linked items", exact: true });
278​
279 await userEvent.click(linkedItemsTab, { modifiers: ["Shift"] });
280 await expect.element(filesTab).toHaveAttribute("aria-pressed", "true");
281 await userEvent.keyboard("{Escape}");
282 await expect.element(filesTab).toHaveAttribute("aria-pressed", "false");
283​
284 await userEvent.click(filesTab, { modifiers: ["Shift"] });
285 await expect.element(diffTab).toHaveAttribute("aria-pressed", "true");
286 await expect.element(filesTab).toHaveAttribute("aria-pressed", "true");
287 await expect.element(linkedItemsTab).toHaveAttribute("aria-pressed", "false");
288​
289 await userEvent.hover(filesTab);
290 await commands.pointerDown();
291 try {
292 await userEvent.hover(filesTab, { position: { x: 1, y: 5 } });
293 await userEvent.hover(linkedItemsTab, { force: true });
294 await vi.waitFor(() => {
295 const dragged = getComputedStyle(filesTab.element().closest("[data-selected-tab]")!);
296 const peer = getComputedStyle(diffTab.element().closest("[data-selected-tab]")!);
297 expect(dragged.transform).not.toBe("none");
298 expect(peer.transform).toBe(dragged.transform);
299 });
300 } finally {
301 await commands.pointerUp();
302 }
303 expect(onMoveSurfaces).toHaveBeenCalledExactlyOnceWith(["diff", "files"], "pull-requests");
304​
305 await userEvent.click(diffTab, { button: "right" });
306 await userEvent.click(page.getByRole("menuitem", { name: "Close selected tabs" }));
307 expect(onCloseSelectedSurfaces).toHaveBeenCalledExactlyOnceWith([DIFF_SURFACE, files]);
308});
309​
310// Chromium focuses on an uncancelled mousedown and runs history back/forward on an
311// uncancelled button 3/4 mouseup.
312function releaseThumbButton(
313 target: Element,
314 button: 3 | 4,
315): { focusMoved: boolean; routerMoved: boolean } {
316 const focused = document.activeElement;
317 const down = new MouseEvent("mousedown", { bubbles: true, cancelable: true, button });
318 const up = new MouseEvent("mouseup", { bubbles: true, cancelable: true, button });
319 target.dispatchEvent(down);
320 target.dispatchEvent(up);
321 return {
322 focusMoved: !down.defaultPrevented || document.activeElement !== focused,
323 routerMoved: !up.defaultPrevented,
324 };
326​
327const STAYS_PUT = { focusMoved: false, routerMoved: false };
328​
329describe("right panel thumb buttons", () => {
330 it("keep the app router still over a surface that is not a browser", async () => {
331 await using screen = await render(panel(DIFF_SURFACE));
332 const tabStrip = screen.container.querySelector("[data-right-panel-tabbar]")!;
333 const content = screen.getByTestId("surface-content").element();
334​
335 expect(releaseThumbButton(tabStrip, 3)).toEqual(STAYS_PUT);
336 expect(releaseThumbButton(tabStrip, 4)).toEqual(STAYS_PUT);
337 expect(releaseThumbButton(content, 3)).toEqual(STAYS_PUT);
338 expect(releaseThumbButton(content, 4)).toEqual(STAYS_PUT);
339 });
340​
341 it("go back and forward in the active browser tab instead of the app router", async () => {
342 const actions: string[] = [];
343 using _subscription = { [Symbol.dispose]: subscribePreviewAction((a) => actions.push(a)) };
344 await using screen = await render(panel(BROWSER_SURFACE));
345 const tabStrip = screen.container.querySelector("[data-right-panel-tabbar]")!;
346 const content = screen.getByTestId("surface-content").element();
347​
348 expect(releaseThumbButton(tabStrip, 3)).toEqual(STAYS_PUT);
349 expect(releaseThumbButton(content, 4)).toEqual(STAYS_PUT);
350 // The address addon focuses its input on press; a thumb press must leave focus alone.
351 expect(releaseThumbButton(screen.getByTestId("address-addon").element(), 3)).toEqual(STAYS_PUT);
352 expect(actions).toEqual(["back", "forward", "back"]);
353​
354 // The page canvas already went back in the tab; the panel must not go back a second time.
355 releaseThumbButton(screen.getByTestId("page-canvas").element(), 3);
356 expect(actions).toEqual(["back", "forward", "back"]);
357 });
358});
359​
360const DEVICE_SURFACE: RightPanelSurface = {
361 id: "device:host:phone",
362 kind: "device",
363 target: { hostId: "host", deviceId: "phone", platform: "ios", name: "Phone" },
364};
365​
366describe("device tab rename", () => {
367 it("shows its tooltip and renames from the tab's padding, not only its label", async () => {
368 const onCloseSurface = vi.fn();
369 const props = panel(DEVICE_SURFACE).props as RightPanelTabsProps;
370 await using screen = await render(
371 <RightPanelTabs
372 {...props}
373 surfaces={[DEVICE_SURFACE]}
374 onRenameDevice={() => {}}
375 onCloseSurface={onCloseSurface}
376 >
377 {null}
378 </RightPanelTabs>,
379 );
380 const tab = screen
381 .getByRole("button", { name: "Phone", exact: true })
382 .element()
383 .closest("[data-active-tab]")!;
384 const { width } = tab.getBoundingClientRect();
385​
386 await userEvent.hover(tab, { position: { x: 2, y: 12 } });
387 await expect.element(page.getByText("Device host · iOS")).toBeVisible();
388​
389 await userEvent.click(screen.getByRole("button", { name: "Close Phone" }));
390 expect(onCloseSurface).toHaveBeenCalledOnce();
391​
392 await userEvent.dblClick(tab, { position: { x: 2, y: 12 } });
393 await expect.element(screen.getByRole("textbox", { name: "Device tab name" })).toBeVisible();
394 await userEvent.keyboard("{Escape}");
395​
396 await userEvent.dblClick(tab, { position: { x: width - 2, y: 1 } });
397 await expect.element(screen.getByRole("textbox", { name: "Device tab name" })).toBeVisible();
398 });
399​
400 it("keeps the editor open on an Enter that confirms an IME candidate", async () => {
401 const onRenameDevice = vi.fn();
402 const props = panel(DEVICE_SURFACE).props as RightPanelTabsProps;
403 await using screen = await render(
404 <RightPanelTabs {...props} surfaces={[DEVICE_SURFACE]} onRenameDevice={onRenameDevice}>
405 {null}
406 </RightPanelTabs>,
407 );
408 await userEvent.dblClick(screen.getByRole("button", { name: "Phone", exact: true }));
409 const input = screen.getByRole("textbox", { name: "Device tab name" });
410 await userEvent.fill(input, "にほん");
411​
412 for (const shape of [
413 { isComposing: true, keyCode: 13 },
414 { isComposing: false, keyCode: 229 },
415 ]) {
416 input
417 .element()
418 .dispatchEvent(
419 new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...shape }),
420 );
421 }
422​
423 await expect.element(input).toHaveFocus();
424 expect(onRenameDevice).not.toHaveBeenCalled();
425 await userEvent.fill(input, "日本語");
426 await userEvent.keyboard("{Enter}");
427 expect(onRenameDevice).toHaveBeenCalledExactlyOnceWith(DEVICE_SURFACE.id, "日本語");
428 });
429});
430​
431async function pressModT() {
432 const event = new KeyboardEvent("keydown", {
433 key: "t",
434 ctrlKey: true,
435 bubbles: true,
436 cancelable: true,
437 });
438 await act(() => {
439 document.body.dispatchEvent(event);
440 });
441 return event.defaultPrevented;
443​
444describe("add surface launcher", () => {
445 it("hides the button, closes the open menu and stops taking Mod+T and the desktop menu action once no surface can be added", async () => {
446 const menuListeners = new Set<(action: string) => void>();
447 using _bridge = stubGlobal("desktopBridge", {
448 onMenuAction: (listener: (action: string) => void) => {
449 menuListeners.add(listener);
450 return () => menuListeners.delete(listener);
451 },
452 });
453 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
454 const tabs = (sideChatAvailable: boolean) => (
455 <RightPanelTabs
456 {...(panel(DIFF_SURFACE).props as RightPanelTabsProps)}
457 open
458 keybindings={DEFAULT_RESOLVED_KEYBINDINGS}
459 browserAvailable={false}
460 terminalAvailable={false}
461 diffAvailable={false}
462 filesAvailable={false}
463 pullRequestAvailable={false}
464 pullRequestsAvailable={false}
465 deviceAvailable={false}
466 onAddSideChat={() => {}}
467 sideChatAvailable={sideChatAvailable}
468 >
469 {null}
470 </RightPanelTabs>
471 );
472 await using screen = await render(tabs(true));
473 const addButton = screen.getByRole("button", { name: "Add panel surface" });
474​
475 await expect.element(addButton).toBeInTheDocument();
476 expect(menuListeners.size).toBe(1);
477 expect(await pressModT()).toBe(true);
478 await expect.element(page.getByRole("menu")).toBeVisible();
479​
480 await screen.rerender(tabs(false));
481 expect(addButton.query()).toBeNull();
482 expect(page.getByRole("menu").query()).toBeNull();
483 expect(menuListeners.size).toBe(0);
484 expect(await pressModT()).toBe(false);
485 expect(page.getByRole("menu").query()).toBeNull();
486 });
487​
488 it("ignores launcher shortcuts and Mod+T while a fallback context menu is open or the panel is closing", async () => {
489 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
490 const onAddFiles = vi.fn();
491 const tabs = (open: boolean) => (
492 <RightPanelTabs
493 {...(panel(DIFF_SURFACE).props as RightPanelTabsProps)}
494 open={open}
495 surfaces={[]}
496 activeSurfaceId={null}
497 keybindings={DEFAULT_RESOLVED_KEYBINDINGS}
498 onAddFiles={onAddFiles}
499 >
500 {null}
501 </RightPanelTabs>
502 );
503 await using screen = await render(tabs(true));
504​
505 try {
506 const menuPromise = showContextMenuFallback([{ id: "pin", label: "Pin thread" }]);
507 await expect.element(page.getByRole("menuitem", { name: "Pin thread" })).toBeVisible();
508​
509 await userEvent.keyboard("f");
510 expect(await pressModT()).toBe(false);
511 expect(onAddFiles).not.toHaveBeenCalled();
512 expect(page.getByRole("menuitem", { name: /Files/ }).query()).toBeNull();
513​
514 await userEvent.keyboard("{Escape}");
515 await expect(menuPromise).resolves.toBeNull();
516 await userEvent.keyboard("f");
517 expect(onAddFiles).toHaveBeenCalledTimes(1);
518​
519 await screen.rerender(tabs(false));
520 await userEvent.keyboard("f");
521 expect(onAddFiles).toHaveBeenCalledTimes(1);
522 expect(document.querySelector("[data-surface-launcher-keys]")).toBeNull();
523 } finally {
524 dismissContextMenu(false);
525 }
526 });
527​
528 it("keeps menu focus and surface shortcuts working when Mod+T is pressed again while the Add menu is open", async () => {
529 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
530 const onAddFiles = vi.fn();
531 await using _screen = await render(
532 <RightPanelTabs
533 {...(panel(DIFF_SURFACE).props as RightPanelTabsProps)}
534 open
535 surfaces={[]}
536 activeSurfaceId={null}
537 keybindings={DEFAULT_RESOLVED_KEYBINDINGS}
538 onAddFiles={onAddFiles}
539 >
540 {null}
541 </RightPanelTabs>,
542 );
543​
544 expect(await pressModT()).toBe(true);
545 const menu = page.getByRole("menu");
546 await expect.element(menu).toBeVisible();
547 await vi.waitFor(() => {
548 expect(menu.element().contains(document.activeElement)).toBe(true);
549 });
550​
551 expect(await pressModT()).toBe(true);
552 await expect.element(menu).toBeVisible();
553 await vi.waitFor(() => {
554 expect(menu.element().contains(document.activeElement)).toBe(true);
555 });
556​
557 await userEvent.keyboard("f");
558 await vi.waitFor(() => {
559 expect(onAddFiles).toHaveBeenCalledTimes(1);
560 });
561 await expect.element(menu).not.toBeInTheDocument();
562 });
563});