Open History to see the last commit
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 { page, userEvent } from "vite-plus/test/browser";
7
8import { InputGroup, InputGroupAddon, InputGroupInput } from "~/components/ui/input-group";
9import type { RightPanelSurface } from "~/rightPanelStore";
10import { act, render, stubGlobal } from "../../test/render";
11import { HistorySwipeNavigation } from "./HistorySwipeNavigation";
12import { RightPanelTabs, type RightPanelTabsProps } from "./RightPanelTabs";
13import { subscribePreviewAction } from "./preview/previewActionBus";
14
15const navigateHistory = vi.hoisted(() => vi.fn());
16vi.mock("../navigationHistory", () => ({ canNavigateHistory: () => true, navigateHistory }));
17
18// Chromium starts a gesture scroll, and Electron reports its begin, only for a
19// wheel event the page did not preventDefault; it then scrolls the latched scroller.
20function trackpad() {
21 const begin = new Set<() => void>();
22 const end = new Set<() => void>();
23 const subscribe = (listeners: Set<() => void>) => (listener: () => void) => {
24 listeners.add(listener);
25 return () => listeners.delete(listener);
26 };
27 let scrolling = false;
28 return {
29 bridge: {
30 onTrackpadScrollBegin: subscribe(begin),
31 onTrackpadScrollEnd: subscribe(end),
32 onMenuAction: () => () => {},
33 },
34 scroll(target: Element, deltas: readonly number[]) {
35 let scroller: Element | null = target;
36 while (
37 scroller &&
38 (scroller.scrollWidth <= scroller.clientWidth ||
39 !/auto|scroll/.test(getComputedStyle(scroller).overflowX))
40 ) {
41 scroller = scroller.parentElement;
42 }
43 for (const deltaX of deltas) {
44 const event = new WheelEvent("wheel", {
45 deltaX,
46 bubbles: true,
47 cancelable: true,
48 composed: true,
49 });
50 target.dispatchEvent(event);
51 if (event.defaultPrevented) continue;
52 if (scroller) scroller.scrollLeft += deltaX;
53 if (scrolling) continue;
54 scrolling = true;
55 for (const listener of begin) listener();
56 }
57 if (scrolling) for (const listener of end) listener();
58 scrolling = false;
59 },
60 };
61}
62
63const surfaces: RightPanelSurface[] = Array.from({ length: 16 }, (_, index) => ({
64 id: `terminal:${index}`,
65 kind: "terminal",
66 resourceId: `${index}`,
67 terminalIds: [`${index}`],
68 activeTerminalId: `${index}`,
69}));
70
71describe("RightPanelTabs", () => {
72 it("a flick that scrolls the tab strip to its left edge keeps the thread, and so does a swipe from the edge", async () => {
73 navigateHistory.mockReset();
74 const { bridge, scroll } = trackpad();
75 using _bridge = stubGlobal("desktopBridge", bridge);
76 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
77 const panel = document.createElement("div");
78 panel.style.cssText = "width: 320px; height: 200px; display: flex";
79 const noop = () => {};
80 await using screen = await render(
81 <>
82 <HistorySwipeNavigation />
83 <RightPanelTabs
84 mode="embedded"
85 keybindings={[]}
86 getShortcutContext={() => ({
87 terminalFocus: false,
88 terminalOpen: false,
89 previewFocus: false,
90 previewOpen: false,
91 isWeb: true,
92 isDesktop: false,
93 })}
94 surfaces={surfaces}
95 environmentId={null}
96 activeSurfaceId={null}
97 pendingSurfaceIds={new Set()}
98 previewSessions={{}}
99 desktopByTabId={{}}
100 terminalLabelsById={new Map(surfaces.map((surface) => [surface.id, "Terminal"]))}
101 onActivate={noop}
102 onCloseSurface={noop}
103 onCloseOtherSurfaces={noop}
104 onCloseSurfacesToRight={noop}
105 onCloseAllSurfaces={noop}
106 onCopyFilePath={noop}
107 onAddBrowser={noop}
108 onAddBrowserInProfile={noop}
109 onAddTerminal={noop}
110 onAddDiff={noop}
111 onAddFiles={noop}
112 onAddPullRequest={noop}
113 onAddPullRequests={noop}
114 onAddDevice={noop}
115 browserAvailable={false}
116 terminalAvailable
117 diffAvailable={false}
118 filesAvailable={false}
119 pullRequestAvailable={false}
120 pullRequestsAvailable={false}
121 deviceAvailable={false}
122 >
123 {null}
124 </RightPanelTabs>
125 </>,
126 { container: panel },
127 );
128 const viewport = screen.container.querySelector<HTMLElement>(
129 '[data-right-panel-tab-list] [data-slot="scroll-area-viewport"]',
130 )!;
131 expect(viewport.scrollWidth - viewport.clientWidth).toBeGreaterThan(120);
132 viewport.scrollLeft = 120;
133
134 const momentum = Array.from({ length: 24 }, (_, index) => -60 * 0.85 ** index);
135 scroll(viewport.querySelector("[data-active-tab]")!, [-10, -20, -30, ...momentum]);
136
137 expect(viewport.scrollLeft).toBe(0);
138 expect(navigateHistory).not.toHaveBeenCalled();
139
140 viewport.scrollLeft = 0;
141 scroll(viewport.querySelector("[data-active-tab]")!, [-40, -40, -40, -40, -40]);
142
143 expect(navigateHistory).not.toHaveBeenCalled();
144 });
145});
146
147const BROWSER_SURFACE: RightPanelSurface = {
148 id: "browser:tab-1",
149 kind: "preview",
150 resourceId: "tab-1",
151};
152const DIFF_SURFACE: RightPanelSurface = { id: "diff", kind: "diff" };
153
154function panel(activeSurface: RightPanelSurface) {
155 const noop = () => {};
156 const props: RightPanelTabsProps = {
157 mode: "inline",
158 keybindings: [],
159 getShortcutContext: () => ({
160 terminalFocus: false,
161 terminalOpen: false,
162 previewFocus: false,
163 previewOpen: true,
164 isWeb: true,
165 isDesktop: false,
166 }),
167 surfaces: [BROWSER_SURFACE, DIFF_SURFACE],
168 environmentId: EnvironmentId.make("environment-local"),
169 activeSurfaceId: activeSurface.id,
170 pendingSurfaceIds: new Set(),
171 previewSessions: {},
172 desktopByTabId: {},
173 terminalLabelsById: new Map(),
174 onActivate: noop,
175 onCloseSurface: noop,
176 onCloseOtherSurfaces: noop,
177 onCloseSurfacesToRight: noop,
178 onCloseAllSurfaces: noop,
179 onCopyFilePath: noop,
180 onAddBrowser: noop,
181 onAddBrowserInProfile: noop,
182 onAddTerminal: noop,
183 onAddDiff: noop,
184 onAddFiles: noop,
185 onAddPullRequest: noop,
186 onAddPullRequests: noop,
187 onAddDevice: noop,
188 browserAvailable: true,
189 terminalAvailable: true,
190 diffAvailable: true,
191 filesAvailable: true,
192 pullRequestAvailable: true,
193 pullRequestsAvailable: true,
194 deviceAvailable: true,
195 children: (
196 <div data-testid="surface-content">
197 {/* Stands in for ServerBrowserSurface, whose page canvas handles thumb buttons itself. */}
198 <canvas data-testid="page-canvas" onMouseUp={(event) => event.preventDefault()} />
199 <InputGroup>
200 <InputGroupInput aria-label="Address" />
201 <InputGroupAddon data-testid="address-addon" align="inline-end" />
202 </InputGroup>
203 </div>
204 ),
205 };
206 return <RightPanelTabs {...props} />;
207}
208
209// Chromium focuses on an uncancelled mousedown and runs history back/forward on an
210// uncancelled button 3/4 mouseup.
211function releaseThumbButton(
212 target: Element,
213 button: 3 | 4,
214): { focusMoved: boolean; routerMoved: boolean } {
215 const focused = document.activeElement;
216 const down = new MouseEvent("mousedown", { bubbles: true, cancelable: true, button });
217 const up = new MouseEvent("mouseup", { bubbles: true, cancelable: true, button });
218 target.dispatchEvent(down);
219 target.dispatchEvent(up);
220 return {
221 focusMoved: !down.defaultPrevented || document.activeElement !== focused,
222 routerMoved: !up.defaultPrevented,
223 };
224}
225
226const STAYS_PUT = { focusMoved: false, routerMoved: false };
227
228describe("right panel thumb buttons", () => {
229 it("keep the app router still over a surface that is not a browser", async () => {
230 await using screen = await render(panel(DIFF_SURFACE));
231 const tabStrip = screen.container.querySelector("[data-right-panel-tabbar]")!;
232 const content = screen.getByTestId("surface-content").element();
233
234 expect(releaseThumbButton(tabStrip, 3)).toEqual(STAYS_PUT);
235 expect(releaseThumbButton(tabStrip, 4)).toEqual(STAYS_PUT);
236 expect(releaseThumbButton(content, 3)).toEqual(STAYS_PUT);
237 expect(releaseThumbButton(content, 4)).toEqual(STAYS_PUT);
238 });
239
240 it("go back and forward in the active browser tab instead of the app router", async () => {
241 const actions: string[] = [];
242 using _subscription = { [Symbol.dispose]: subscribePreviewAction((a) => actions.push(a)) };
243 await using screen = await render(panel(BROWSER_SURFACE));
244 const tabStrip = screen.container.querySelector("[data-right-panel-tabbar]")!;
245 const content = screen.getByTestId("surface-content").element();
246
247 expect(releaseThumbButton(tabStrip, 3)).toEqual(STAYS_PUT);
248 expect(releaseThumbButton(content, 4)).toEqual(STAYS_PUT);
249 // The address addon focuses its input on press; a thumb press must leave focus alone.
250 expect(releaseThumbButton(screen.getByTestId("address-addon").element(), 3)).toEqual(STAYS_PUT);
251 expect(actions).toEqual(["back", "forward", "back"]);
252
253 // The page canvas already went back in the tab; the panel must not go back a second time.
254 releaseThumbButton(screen.getByTestId("page-canvas").element(), 3);
255 expect(actions).toEqual(["back", "forward", "back"]);
256 });
257});
258
259const DEVICE_SURFACE: RightPanelSurface = {
260 id: "device:host:phone",
261 kind: "device",
262 target: { hostId: "host", deviceId: "phone", platform: "ios", name: "Phone" },
263};
264
265describe("device tab rename", () => {
266 it("keeps the editor open on an Enter that confirms an IME candidate", async () => {
267 const onRenameDevice = vi.fn();
268 const props = panel(DEVICE_SURFACE).props as RightPanelTabsProps;
269 await using screen = await render(
270 <RightPanelTabs {...props} surfaces={[DEVICE_SURFACE]} onRenameDevice={onRenameDevice}>
271 {null}
272 </RightPanelTabs>,
273 );
274 await userEvent.dblClick(screen.getByRole("button", { name: "Phone", exact: true }));
275 const input = screen.getByRole("textbox", { name: "Device tab name" });
276 await userEvent.fill(input, "にほん");
277
278 for (const shape of [
279 { isComposing: true, keyCode: 13 },
280 { isComposing: false, keyCode: 229 },
281 ]) {
282 input
283 .element()
284 .dispatchEvent(
285 new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true, ...shape }),
286 );
287 }
288
289 await expect.element(input).toHaveFocus();
290 expect(onRenameDevice).not.toHaveBeenCalled();
291 await userEvent.fill(input, "日本語");
292 await userEvent.keyboard("{Enter}");
293 expect(onRenameDevice).toHaveBeenCalledExactlyOnceWith(DEVICE_SURFACE.id, "日本語");
294 });
295});
296
297describe("add surface launcher", () => {
298 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 () => {
299 const menuListeners = new Set<(action: string) => void>();
300 using _bridge = stubGlobal("desktopBridge", {
301 onMenuAction: (listener: (action: string) => void) => {
302 menuListeners.add(listener);
303 return () => menuListeners.delete(listener);
304 },
305 });
306 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
307 const tabs = (sideChatAvailable: boolean) => (
308 <RightPanelTabs
309 {...(panel(DIFF_SURFACE).props as RightPanelTabsProps)}
310 open
311 keybindings={DEFAULT_RESOLVED_KEYBINDINGS}
312 browserAvailable={false}
313 terminalAvailable={false}
314 diffAvailable={false}
315 filesAvailable={false}
316 pullRequestAvailable={false}
317 pullRequestsAvailable={false}
318 deviceAvailable={false}
319 onAddSideChat={() => {}}
320 sideChatAvailable={sideChatAvailable}
321 >
322 {null}
323 </RightPanelTabs>
324 );
325 const pressModT = async () => {
326 const event = new KeyboardEvent("keydown", {
327 key: "t",
328 ctrlKey: true,
329 bubbles: true,
330 cancelable: true,
331 });
332 await act(() => {
333 document.body.dispatchEvent(event);
334 });
335 return event.defaultPrevented;
336 };
337 await using screen = await render(tabs(true));
338 const addButton = screen.getByRole("button", { name: "Add panel surface" });
339
340 await expect.element(addButton).toBeInTheDocument();
341 expect(menuListeners.size).toBe(1);
342 expect(await pressModT()).toBe(true);
343 await expect.element(page.getByRole("menu")).toBeVisible();
344
345 await screen.rerender(tabs(false));
346 expect(addButton.query()).toBeNull();
347 expect(page.getByRole("menu").query()).toBeNull();
348 expect(menuListeners.size).toBe(0);
349 expect(await pressModT()).toBe(false);
350 expect(page.getByRole("menu").query()).toBeNull();
351 });
352});