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

RightPanelTabs.keyboard.browser.test.tsx

223 lines7.7 KB

1import { act, type ComponentProps } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4import {
5 compileResolvedKeybindingsConfig,
6 DEFAULT_RESOLVED_KEYBINDINGS,
7} from "@t3tools/shared/keybindings";
8​
9import { RightPanelTabs } from "./RightPanelTabs";
10​
11vi.mock("~/hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "light" }) }));
12vi.mock("~/browser/browserDefaults", () => ({ useBrowserDefaults: () => ({ profiles: [] }) }));
13​
14let root: Root;
15let container: HTMLDivElement;
16const addFiles = vi.fn();
17const noop = () => undefined;
18​
19beforeEach(() => {
20 vi.useFakeTimers();
21 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
22 vi.stubGlobal(
23 "ResizeObserver",
24 class {
25 observe() {}
26 disconnect() {}
27 unobserve() {}
28 },
29 );
30 Object.defineProperty(Element.prototype, "getAnimations", {
31 configurable: true,
32 value: () => [],
33 });
34 vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
35 addFiles.mockClear();
36 container = document.createElement("div");
37 document.body.append(container);
38 root = createRoot(container);
39});
40​
41afterEach(async () => {
42 await act(() => root.unmount());
43 container.remove();
44 vi.restoreAllMocks();
45 vi.unstubAllGlobals();
46 vi.useRealTimers();
47});
48​
49async function renderPanel(overrides: Partial<ComponentProps<typeof RightPanelTabs>> = {}) {
50 await act(() =>
51 root.render(
52 <RightPanelTabs
53 mode="inline"
54 open
55 keybindings={DEFAULT_RESOLVED_KEYBINDINGS}
56 getShortcutContext={() => ({
57 terminalFocus: false,
58 terminalOpen: false,
59 previewFocus: false,
60 previewOpen: false,
61 isWeb: true,
62 isDesktop: false,
63 })}
64 surfaces={[]}
65 environmentId={null}
66 activeSurfaceId={null}
67 pendingSurfaceIds={new Set()}
68 previewSessions={{}}
69 desktopByTabId={{}}
70 terminalLabelsById={new Map()}
71 onActivate={noop}
72 onCloseSurface={noop}
73 onCloseOtherSurfaces={noop}
74 onCloseSurfacesToRight={noop}
75 onCloseAllSurfaces={noop}
76 onCopyFilePath={noop}
77 onAddBrowser={noop}
78 onAddBrowserInProfile={noop}
79 onAddTerminal={noop}
80 onAddDiff={noop}
81 onAddFiles={addFiles}
82 onAddPullRequest={noop}
83 onAddPullRequests={noop}
84 onAddDevice={noop}
85 browserAvailable={false}
86 terminalAvailable={false}
87 diffAvailable={false}
88 filesAvailable
89 pullRequestAvailable={false}
90 pullRequestsAvailable={false}
91 deviceAvailable={false}
92 {...overrides}
93 >
94 content
95 </RightPanelTabs>,
96 ),
97 );
98 await act(() => vi.advanceTimersByTimeAsync(0));
99 await act(() => vi.advanceTimersToNextFrame());
101​
102async function press(key: string, options: KeyboardEventInit = {}) {
103 const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...options });
104 await act(() => (document.activeElement ?? document.body).dispatchEvent(event));
105 await act(() => vi.advanceTimersByTimeAsync(0));
106 await act(() => vi.advanceTimersToNextFrame());
107 return event;
109​
110describe("right panel new-tab shortcut", () => {
111 it.each(["MacIntel", "Win32", "Linux x86_64"])(
112 "opens the menu on %s and chooses a tab",
113 async (platform) => {
114 vi.spyOn(navigator, "platform", "get").mockReturnValue(platform);
115 await renderPanel();
116 const event = await press(
117 "t",
118 platform === "MacIntel" ? { metaKey: true } : { ctrlKey: true },
119 );
120 expect(event.defaultPrevented).toBe(true);
121 expect(document.querySelector('[role="menu"]')?.textContent).toContain(
122 "Linked pull requests",
123 );
124 expect(document.activeElement?.closest('[role="menu"]')).not.toBeNull();
125 expect(
126 (
127 await press("t", {
128 metaKey: platform === "MacIntel",
129 ctrlKey: platform !== "MacIntel",
130 repeat: true,
131 })
132 ).defaultPrevented,
133 ).toBe(true);
134 await press("f");
135 expect(addFiles).toHaveBeenCalledOnce();
136 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
137 },
138 );
139​
140 it("leaves the shortcut alone while the mounted panel is closed", async () => {
141 await renderPanel({ open: false });
142 expect((await press("t", { metaKey: true })).defaultPrevented).toBe(false);
143 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
144 });
145​
146 it.each(["Win32", "Linux x86_64"])(
147 "leaves Ctrl+T for the focused terminal on %s",
148 async (platform) => {
149 vi.spyOn(navigator, "platform", "get").mockReturnValue(platform);
150 await renderPanel({
151 getShortcutContext: () => ({
152 terminalFocus: true,
153 terminalOpen: true,
154 previewFocus: false,
155 previewOpen: false,
156 isWeb: true,
157 isDesktop: false,
158 }),
159 });
160 const terminal = document.createElement("textarea");
161 const onKeyDown = vi.fn();
162 terminal.addEventListener("keydown", onKeyDown);
163 container.append(terminal);
164 await act(() => terminal.focus());
165 const event = await press("t", { ctrlKey: true });
166 expect(event.defaultPrevented).toBe(false);
167 expect(onKeyDown).toHaveBeenCalledWith(event);
168 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
169 },
170 );
171​
172 it("uses a custom binding from a text field and closes on Escape", async () => {
173 const input = document.createElement("input");
174 await renderPanel({
175 keybindings: compileResolvedKeybindingsConfig([{ key: "mod+y", command: "rightPanel.new" }]),
176 });
177 document.body.append(input);
178 input.focus();
179 expect((await press("t", { metaKey: true })).defaultPrevented).toBe(false);
180 await press("y", { metaKey: true });
181 expect(document.querySelector('[role="menu"]')).not.toBeNull();
182 await press("Escape");
183 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
184 // The menu hands focus back to its trigger once its close finishes, a few frames later.
185 // Timers are fake here, so advance them instead of polling in real time.
186 const trigger = container.querySelector('[aria-label="Add panel surface"]');
187 for (let frame = 0; frame < 10 && document.activeElement !== trigger; frame++) {
188 await act(() => vi.advanceTimersToNextFrame());
189 }
190 expect(document.activeElement).toBe(trigger);
191 input.remove();
192 });
193​
194 it("does not open over another popup or during text composition", async () => {
195 await renderPanel();
196 expect((await press("t", { metaKey: true, isComposing: true })).defaultPrevented).toBe(false);
197 const dialog = document.createElement("div");
198 dialog.dataset.slot = "dialog-popup";
199 container.append(dialog);
200 expect((await press("t", { metaKey: true })).defaultPrevented).toBe(false);
201 expect(document.querySelector('[role="menu"]')).toBeNull();
202 });
203​
204 it("supports arrow keys with an existing tab in sheet mode and clears the menu on close", async () => {
205 const panel = {
206 mode: "sheet" as const,
207 surfaces: [{ id: "files" as const, kind: "files" as const }],
208 };
209 await renderPanel(panel);
210 await press("t", { metaKey: true });
211 await press("ArrowDown");
212 await press("ArrowDown");
213 await press("ArrowDown");
214 expect(document.activeElement?.textContent).toContain("Files");
215 await press("Enter");
216 expect(addFiles).toHaveBeenCalledOnce();
217 await press("t", { metaKey: true });
218 await renderPanel({ ...panel, open: false });
219 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
220 await renderPanel(panel);
221 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
222 });
223});