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

RightPanelTabs.browser.test.tsx

251 lines9.1 KB

1import "~/index.css";
2​
3import { EnvironmentId } from "@t3tools/contracts";
4import { describe, expect, it, vi } from "vite-plus/test";
5​
6import { InputGroup, InputGroupAddon, InputGroupInput } from "~/components/ui/input-group";
7import type { RightPanelSurface } from "~/rightPanelStore";
8import { render, stubGlobal } from "../../test/render";
9import { HistorySwipeNavigation } from "./HistorySwipeNavigation";
10import { RightPanelTabs, type RightPanelTabsProps } from "./RightPanelTabs";
11import { subscribePreviewAction } from "./preview/previewActionBus";
12​
13const navigateHistory = vi.hoisted(() => vi.fn());
14vi.mock("../navigationHistory", () => ({ canNavigateHistory: () => true, navigateHistory }));
15​
16// Chromium starts a gesture scroll, and Electron reports its begin, only for a
17// wheel event the page did not preventDefault; it then scrolls the latched scroller.
18function trackpad() {
19 const begin = new Set<() => void>();
20 const end = new Set<() => void>();
21 const subscribe = (listeners: Set<() => void>) => (listener: () => void) => {
22 listeners.add(listener);
23 return () => listeners.delete(listener);
24 };
25 let scrolling = false;
26 return {
27 bridge: { onTrackpadScrollBegin: subscribe(begin), onTrackpadScrollEnd: subscribe(end) },
28 scroll(target: Element, deltas: readonly number[]) {
29 let scroller: Element | null = target;
30 while (
31 scroller &&
32 (scroller.scrollWidth <= scroller.clientWidth ||
33 !/auto|scroll/.test(getComputedStyle(scroller).overflowX))
34 ) {
35 scroller = scroller.parentElement;
36 }
37 for (const deltaX of deltas) {
38 const event = new WheelEvent("wheel", {
39 deltaX,
40 bubbles: true,
41 cancelable: true,
42 composed: true,
43 });
44 target.dispatchEvent(event);
45 if (event.defaultPrevented) continue;
46 if (scroller) scroller.scrollLeft += deltaX;
47 if (scrolling) continue;
48 scrolling = true;
49 for (const listener of begin) listener();
50 }
51 if (scrolling) for (const listener of end) listener();
52 scrolling = false;
53 },
54 };
56​
57const surfaces: RightPanelSurface[] = Array.from({ length: 16 }, (_, index) => ({
58 id: `terminal:${index}`,
59 kind: "terminal",
60 resourceId: `${index}`,
61 terminalIds: [`${index}`],
62 activeTerminalId: `${index}`,
63}));
64​
65describe("RightPanelTabs", () => {
66 it("a flick that scrolls the tab strip to its left edge keeps the thread, a swipe from the edge goes back", async () => {
67 navigateHistory.mockReset();
68 const { bridge, scroll } = trackpad();
69 using _bridge = stubGlobal("desktopBridge", bridge);
70 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
71 const panel = document.createElement("div");
72 panel.style.cssText = "width: 320px; height: 200px; display: flex";
73 const noop = () => {};
74 await using screen = await render(
75 <>
76 <HistorySwipeNavigation />
77 <RightPanelTabs
78 mode="embedded"
79 keybindings={[]}
80 getShortcutContext={() => ({
81 terminalFocus: false,
82 terminalOpen: false,
83 previewFocus: false,
84 previewOpen: false,
85 isWeb: true,
86 isDesktop: false,
87 })}
88 surfaces={surfaces}
89 environmentId={null}
90 activeSurfaceId={null}
91 pendingSurfaceIds={new Set()}
92 previewSessions={{}}
93 desktopByTabId={{}}
94 terminalLabelsById={new Map(surfaces.map((surface) => [surface.id, "Terminal"]))}
95 onActivate={noop}
96 onCloseSurface={noop}
97 onCloseOtherSurfaces={noop}
98 onCloseSurfacesToRight={noop}
99 onCloseAllSurfaces={noop}
100 onCopyFilePath={noop}
101 onAddBrowser={noop}
102 onAddBrowserInProfile={noop}
103 onAddTerminal={noop}
104 onAddDiff={noop}
105 onAddFiles={noop}
106 onAddPullRequest={noop}
107 onAddPullRequests={noop}
108 onAddDevice={noop}
109 browserAvailable={false}
110 terminalAvailable
111 diffAvailable={false}
112 filesAvailable={false}
113 pullRequestAvailable={false}
114 pullRequestsAvailable={false}
115 deviceAvailable={false}
116 >
117 {null}
118 </RightPanelTabs>
119 </>,
120 { container: panel },
121 );
122 const viewport = screen.container.querySelector<HTMLElement>(
123 '[data-right-panel-tab-list] [data-slot="scroll-area-viewport"]',
124 )!;
125 expect(viewport.scrollWidth - viewport.clientWidth).toBeGreaterThan(120);
126 viewport.scrollLeft = 120;
127​
128 const momentum = Array.from({ length: 24 }, (_, index) => -60 * 0.85 ** index);
129 scroll(viewport.querySelector("[data-active-tab]")!, [-10, -20, -30, ...momentum]);
130​
131 expect(viewport.scrollLeft).toBe(0);
132 expect(navigateHistory).not.toHaveBeenCalled();
133​
134 viewport.scrollLeft = 0;
135 scroll(viewport.querySelector("[data-active-tab]")!, [-40, -40, -40, -40, -40]);
136​
137 expect(navigateHistory).toHaveBeenCalledExactlyOnceWith("back");
138 });
139});
140​
141const BROWSER_SURFACE: RightPanelSurface = {
142 id: "browser:tab-1",
143 kind: "preview",
144 resourceId: "tab-1",
145};
146const DIFF_SURFACE: RightPanelSurface = { id: "diff", kind: "diff" };
147​
148function panel(activeSurface: RightPanelSurface) {
149 const noop = () => {};
150 const props: RightPanelTabsProps = {
151 mode: "inline",
152 keybindings: [],
153 getShortcutContext: () => ({
154 terminalFocus: false,
155 terminalOpen: false,
156 previewFocus: false,
157 previewOpen: true,
158 isWeb: true,
159 isDesktop: false,
160 }),
161 surfaces: [BROWSER_SURFACE, DIFF_SURFACE],
162 environmentId: EnvironmentId.make("environment-local"),
163 activeSurfaceId: activeSurface.id,
164 pendingSurfaceIds: new Set(),
165 previewSessions: {},
166 desktopByTabId: {},
167 terminalLabelsById: new Map(),
168 onActivate: noop,
169 onCloseSurface: noop,
170 onCloseOtherSurfaces: noop,
171 onCloseSurfacesToRight: noop,
172 onCloseAllSurfaces: noop,
173 onCopyFilePath: noop,
174 onAddBrowser: noop,
175 onAddBrowserInProfile: noop,
176 onAddTerminal: noop,
177 onAddDiff: noop,
178 onAddFiles: noop,
179 onAddPullRequest: noop,
180 onAddPullRequests: noop,
181 onAddDevice: noop,
182 browserAvailable: true,
183 terminalAvailable: true,
184 diffAvailable: true,
185 filesAvailable: true,
186 pullRequestAvailable: true,
187 pullRequestsAvailable: true,
188 deviceAvailable: true,
189 children: (
190 <div data-testid="surface-content">
191 {/* Stands in for ServerBrowserSurface, whose page canvas handles thumb buttons itself. */}
192 <canvas data-testid="page-canvas" onMouseUp={(event) => event.preventDefault()} />
193 <InputGroup>
194 <InputGroupInput aria-label="Address" />
195 <InputGroupAddon data-testid="address-addon" align="inline-end" />
196 </InputGroup>
197 </div>
198 ),
199 };
200 return <RightPanelTabs {...props} />;
202​
203// Chromium focuses on an uncancelled mousedown and runs history back/forward on an
204// uncancelled button 3/4 mouseup.
205function releaseThumbButton(
206 target: Element,
207 button: 3 | 4,
208): { focusMoved: boolean; routerMoved: boolean } {
209 const focused = document.activeElement;
210 const down = new MouseEvent("mousedown", { bubbles: true, cancelable: true, button });
211 const up = new MouseEvent("mouseup", { bubbles: true, cancelable: true, button });
212 target.dispatchEvent(down);
213 target.dispatchEvent(up);
214 return {
215 focusMoved: !down.defaultPrevented || document.activeElement !== focused,
216 routerMoved: !up.defaultPrevented,
217 };
219​
220const STAYS_PUT = { focusMoved: false, routerMoved: false };
221​
222describe("right panel thumb buttons", () => {
223 it("keep the app router still over a surface that is not a browser", async () => {
224 await using screen = await render(panel(DIFF_SURFACE));
225 const tabStrip = screen.container.querySelector("[data-right-panel-tabbar]")!;
226 const content = screen.getByTestId("surface-content").element();
227​
228 expect(releaseThumbButton(tabStrip, 3)).toEqual(STAYS_PUT);
229 expect(releaseThumbButton(tabStrip, 4)).toEqual(STAYS_PUT);
230 expect(releaseThumbButton(content, 3)).toEqual(STAYS_PUT);
231 expect(releaseThumbButton(content, 4)).toEqual(STAYS_PUT);
232 });
233​
234 it("go back and forward in the active browser tab instead of the app router", async () => {
235 const actions: string[] = [];
236 using _subscription = { [Symbol.dispose]: subscribePreviewAction((a) => actions.push(a)) };
237 await using screen = await render(panel(BROWSER_SURFACE));
238 const tabStrip = screen.container.querySelector("[data-right-panel-tabbar]")!;
239 const content = screen.getByTestId("surface-content").element();
240​
241 expect(releaseThumbButton(tabStrip, 3)).toEqual(STAYS_PUT);
242 expect(releaseThumbButton(content, 4)).toEqual(STAYS_PUT);
243 // The address addon focuses its input on press; a thumb press must leave focus alone.
244 expect(releaseThumbButton(screen.getByTestId("address-addon").element(), 3)).toEqual(STAYS_PUT);
245 expect(actions).toEqual(["back", "forward", "back"]);
246​
247 // The page canvas already went back in the tab; the panel must not go back a second time.
248 releaseThumbButton(screen.getByTestId("page-canvas").element(), 3);
249 expect(actions).toEqual(["back", "forward", "back"]);
250 });
251});