Open History to see the last commit
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());
100}
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;
108}
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("opens Files while a closed popup remains mounted", async () => {
141 await renderPanel();
142 const popup = document.createElement("div");
143 popup.dataset.slot = "menu-popup";
144 popup.dataset.closed = "";
145 container.append(popup);
146
147 expect((await press("f")).defaultPrevented).toBe(true);
148 expect(addFiles).toHaveBeenCalledOnce();
149 });
150
151 it("opens the add-surface menu while a closed popup remains mounted", async () => {
152 await renderPanel();
153 const popup = document.createElement("div");
154 popup.dataset.slot = "menu-popup";
155 popup.dataset.closed = "";
156 container.append(popup);
157
158 expect((await press("t", { metaKey: true })).defaultPrevented).toBe(true);
159 expect(document.querySelector('[role="menu"]:not([data-closed])')).not.toBeNull();
160 });
161
162 it("leaves the shortcut alone while the mounted panel is closed", async () => {
163 await renderPanel({ open: false });
164 expect((await press("t", { metaKey: true })).defaultPrevented).toBe(false);
165 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
166 });
167
168 it.each(["Win32", "Linux x86_64"])(
169 "leaves Ctrl+T for the focused terminal on %s",
170 async (platform) => {
171 vi.spyOn(navigator, "platform", "get").mockReturnValue(platform);
172 await renderPanel({
173 getShortcutContext: () => ({
174 terminalFocus: true,
175 terminalOpen: true,
176 previewFocus: false,
177 previewOpen: false,
178 isWeb: true,
179 isDesktop: false,
180 }),
181 });
182 const terminal = document.createElement("textarea");
183 const onKeyDown = vi.fn();
184 terminal.addEventListener("keydown", onKeyDown);
185 container.append(terminal);
186 await act(() => terminal.focus());
187 const event = await press("t", { ctrlKey: true });
188 expect(event.defaultPrevented).toBe(false);
189 expect(onKeyDown).toHaveBeenCalledWith(event);
190 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
191 },
192 );
193
194 it("uses a custom binding from a text field and closes on Escape", async () => {
195 const input = document.createElement("input");
196 await renderPanel({
197 keybindings: compileResolvedKeybindingsConfig([{ key: "mod+y", command: "rightPanel.new" }]),
198 });
199 document.body.append(input);
200 input.focus();
201 expect((await press("t", { metaKey: true })).defaultPrevented).toBe(false);
202 await press("y", { metaKey: true });
203 expect(document.querySelector('[role="menu"]')).not.toBeNull();
204 await press("Escape");
205 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
206 // The menu hands focus back to its trigger once its close finishes, a few frames later.
207 // Timers are fake here, so advance them instead of polling in real time.
208 const trigger = container.querySelector('[aria-label="Add panel surface"]');
209 for (let frame = 0; frame < 10 && document.activeElement !== trigger; frame++) {
210 await act(() => vi.advanceTimersToNextFrame());
211 }
212 expect(document.activeElement).toBe(trigger);
213 input.remove();
214 });
215
216 it("does not open over another popup or during text composition", async () => {
217 await renderPanel();
218 expect((await press("t", { metaKey: true, isComposing: true })).defaultPrevented).toBe(false);
219 const dialog = document.createElement("div");
220 dialog.dataset.slot = "dialog-popup";
221 container.append(dialog);
222 for (const state of ["data-open", "data-ending-style"]) {
223 dialog.setAttribute(state, "");
224 expect((await press("f")).defaultPrevented, state).toBe(false);
225 expect(addFiles, state).not.toHaveBeenCalled();
226 expect((await press("t", { metaKey: true })).defaultPrevented, state).toBe(false);
227 expect(document.querySelector('[role="menu"]'), state).toBeNull();
228 dialog.removeAttribute(state);
229 }
230 });
231
232 it("supports arrow keys with an existing tab in sheet mode and clears the menu on close", async () => {
233 const panel = {
234 mode: "sheet" as const,
235 surfaces: [{ id: "files" as const, kind: "files" as const }],
236 };
237 await renderPanel(panel);
238 await press("t", { metaKey: true });
239 await press("ArrowDown");
240 await press("ArrowDown");
241 await press("ArrowDown");
242 expect(document.activeElement?.textContent).toContain("Files");
243 await press("Enter");
244 expect(addFiles).toHaveBeenCalledOnce();
245 await press("t", { metaKey: true });
246 await renderPanel({ ...panel, open: false });
247 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
248 await renderPanel(panel);
249 expect(document.querySelector('[role="menu"]:not([data-closed])')).toBeNull();
250 });
251});