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

KeybindingsSettings.browser.test.tsx

415 lines15.8 KB

1import "~/index.css";
2​
3import { RegistryProvider } from "@effect/atom-react";
4import { describe, expect, it, vi } from "vite-plus/test";
5import { page, userEvent, type Locator } from "vite-plus/test/browser";
6​
7import { act, render } from "../../../test/render";
8import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings";
9import * as atomCommands from "../../state/use-atom-command";
10​
11vi.mock(import("../../state/session"), async (original) => ({
12 ...(await original()),
13 useEnvironmentScope: () => true,
14 useEnvironmentsWithScope: ((environments: ReadonlyArray<{ environmentId: string }>) =>
15 new Set(environments.map(({ environmentId }) => environmentId))) as never,
16 readEnvironmentScope: () => true,
17}));
18vi.mock(import("../../state/use-atom-command"), async (original) => ({
19 ...(await original()),
20 useAtomCommand: vi.fn(() => vi.fn()) as never,
21}));
22vi.mock(import("./SettingsScopeContext"), async (original) => ({
23 ...(await original()),
24 useSettingsScope: (() => {
25 const environment = {
26 environmentId: "env",
27 label: "Build workstation",
28 serverConfig: {
29 keybindings: compileResolvedKeybindingsConfig([
30 { command: "composer.sendBackground", key: "mod+alt+enter", when: "false" },
31 ]),
32 keybindingsConfigPath: null,
33 availableEditors: [],
34 },
35 };
36 return {
37 scope: { kind: "environment" },
38 environment,
39 environments: [environment],
40 connectedEnvironments: [environment],
41 targets: [],
42 target: null,
43 };
44 }) as never,
45}));
46​
47import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";
48import { KeybindingsSettingsPanel } from "./KeybindingsSettings";
49​
50// The modal dialog's inert layer swallows pointer events in this harness, so drive the DOM.
51async function activate(locator: Locator, action: "click" | "focus") {
52 await expect.element(locator).toBeVisible();
53 (locator.element() as HTMLElement)[action]();
55​
56const existingField = page.getByRole("textbox", { name: "Keybinding for Sidebar: Toggle" });
57const existingPill = page.getByRole("button", { name: /^Edit shortcut for Sidebar: Toggle:/ });
58const newField = page.getByRole("textbox", { name: "Keybinding for new keybinding" });
59​
60describe("Esc in a shortcut recorder", () => {
61 it.each<{
62 name: string;
63 field: Locator;
64 open: () => Promise<void>;
65 expectReset: () => Promise<void>;
66 }>([
67 {
68 name: "existing binding",
69 field: existingField,
70 open: () => activate(existingPill, "click"),
71 expectReset: async () => {
72 await expect.element(existingField).not.toBeInTheDocument();
73 await expect.element(existingPill).toHaveFocus();
74 await expect.element(page.getByRole("button", { name: "Save" })).not.toBeInTheDocument();
75 },
76 },
77 {
78 name: "new binding",
79 field: newField,
80 open: async () => {
81 await activate(page.getByRole("button", { name: "Add keybinding" }), "click");
82 await activate(newField, "focus");
83 },
84 expectReset: async () => {
85 await expect.element(newField).toHaveValue("");
86 await expect.element(newField).toHaveAttribute("placeholder", "Unassigned");
87 },
88 },
89 ])("leaves the $name field without closing Settings", async ({ field, open, expectReset }) => {
90 const onOpenChange = vi.fn();
91 await using _screen = await render(
92 <Dialog open onOpenChange={onOpenChange}>
93 <DialogPopup>
94 <DialogTitle>Settings</DialogTitle>
95 <KeybindingsSettingsPanel />
96 </DialogPopup>
97 </Dialog>,
98 );
99​
100 await open();
101 await userEvent.keyboard("{Control>}k{/Control}");
102 await expect.element(field).not.toHaveValue("");
103 await userEvent.tab();
104 await activate(field, "focus");
105 await expect.element(field).toHaveAttribute("placeholder", "Press shortcut");
106​
107 await userEvent.keyboard("{Escape}");
108​
109 expect(onOpenChange).not.toHaveBeenCalled();
110 expect(document.activeElement?.matches("[data-keybinding-capture]")).toBe(false);
111 await expectReset();
112​
113 await userEvent.keyboard("{Escape}");
114 expect(onOpenChange).toHaveBeenCalledWith(false, expect.anything());
115 });
116​
117 it.each([
118 { name: "existing binding", field: existingField, open: () => activate(existingPill, "click") },
119 {
120 name: "new binding",
121 field: newField,
122 open: async () => {
123 await activate(page.getByRole("button", { name: "Add keybinding" }), "click");
124 await activate(newField, "focus");
125 },
126 },
127 ])("records Shift+Esc in the $name field", async ({ field, open }) => {
128 const onOpenChange = vi.fn();
129 await using _screen = await render(
130 <Dialog open onOpenChange={onOpenChange}>
131 <DialogPopup>
132 <DialogTitle>Settings</DialogTitle>
133 <KeybindingsSettingsPanel />
134 </DialogPopup>
135 </Dialog>,
136 );
137​
138 await open();
139 await userEvent.keyboard("{Shift>}{Escape}{/Shift}");
140​
141 await expect.element(field).toHaveValue("shift+esc");
142 expect(onOpenChange).not.toHaveBeenCalled();
143 });
144});
145​
146it("unassigns a default shortcut and restores its condition when one is assigned again", async () => {
147 const mutate = vi.fn(async () => ({ _tag: "Success", value: [] }));
148 await vi.mocked(atomCommands.useAtomCommand).withImplementation(
149 () => mutate as never,
150 async () => {
151 await using screen = await render(<KeybindingsSettingsPanel />);
152​
153 await screen.getByRole("button", { name: "Actions for Sidebar: Toggle" }).click();
154 await screen.getByRole("menuitem", { name: "Unassign" }).click();
155 expect(mutate).toHaveBeenLastCalledWith({
156 environmentId: "env",
157 input: {
158 command: "sidebar.toggle",
159 key: "mod+b",
160 when: "false",
161 replace: { command: "sidebar.toggle", key: "mod+b" },
162 },
163 });
164​
165 const unassigned = screen.getByRole("button", {
166 name: "Edit shortcut for Composer: Start in Background: Unassigned",
167 });
168 const save = screen.getByRole("button", { name: "Save" });
169 await unassigned.click();
170 await userEvent.keyboard("{Control>}{Alt>}j{/Alt}{/Control}");
171 await expect.element(save).toBeVisible();
172 await userEvent.keyboard("{Escape}");
173 await expect.element(save).not.toBeInTheDocument();
174​
175 await unassigned.click();
176 await userEvent.keyboard("{Control>}{Alt>}j{/Alt}{/Control}");
177 await save.click();
178 expect(mutate).toHaveBeenLastCalledWith({
179 environmentId: "env",
180 input: expect.objectContaining({
181 command: "composer.sendBackground",
182 when: "composerFocus && draftThreadRoute",
183 replace: { command: "composer.sendBackground", key: "mod+alt+enter", when: "false" },
184 }),
185 });
186 },
187 );
188});
189​
190it("Esc in the keybindings search clears the query without closing Settings", async () => {
191 const onOpenChange = vi.fn();
192 await using _screen = await render(
193 <Dialog open onOpenChange={onOpenChange}>
194 <DialogPopup>
195 <DialogTitle>Settings</DialogTitle>
196 <KeybindingsSettingsPanel />
197 </DialogPopup>
198 </Dialog>,
199 );
200 const search = page.getByRole("searchbox", { name: "Search keybindings" });
201 await search.fill("sidebar");
202 for (const composition of [
203 { key: "Escape", isComposing: true, keyCode: 27 },
204 { key: "Escape", isComposing: false, keyCode: 229 },
205 ]) {
206 const keydown = new KeyboardEvent("keydown", {
207 ...composition,
208 bubbles: true,
209 cancelable: true,
210 });
211 await act(() => {
212 // Safari ends the composition just before the Escape keydown.
213 if (!composition.isComposing)
214 search.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true }));
215 search.element().dispatchEvent(keydown);
216 });
217 expect(keydown.defaultPrevented).toBe(false);
218 await expect.element(search).toHaveValue("sidebar");
219 await expect.element(search).toHaveFocus();
220 }
221 expect(search.element().getAttribute("type")).toBe("text");
222​
223 await userEvent.keyboard("{Escape}");
224 await expect.element(search).toHaveValue("");
225 await expect.element(search).toHaveFocus();
226​
227 await act(() =>
228 search.element().dispatchEvent(
229 new KeyboardEvent("keydown", {
230 key: "Escape",
231 repeat: true,
232 bubbles: true,
233 cancelable: true,
234 }),
235 ),
236 );
237 await expect.element(search).toHaveValue("");
238 await expect.element(search).toHaveFocus();
239 expect(onOpenChange).not.toHaveBeenCalled();
240​
241 await search.fill("sidebar");
242 await userEvent.keyboard("{Shift>}{Escape}{/Shift}");
243 await expect.element(search).toHaveValue("sidebar");
244 await expect.element(search).toHaveFocus();
245 expect(onOpenChange).toHaveBeenCalledWith(false, expect.anything());
246});
247​
248it("re-enables Save when a When editor closes on an expression it could not parse", async () => {
249 await using screen = await render(
250 <RegistryProvider>
251 <KeybindingsSettingsPanel />
252 </RegistryProvider>,
253 );
254 const whenTrigger = screen.getByRole("button", { name: "Edit when clause for Terminal: Toggle" });
255 const expression = screen.getByRole("textbox", { name: "When expression" });
256​
257 await whenTrigger.click();
258 await userEvent.type(expression, "terminalFocus");
259 await userEvent.type(expression, " &&");
260 await expect.element(screen.getByRole("button", { name: "Save" })).toBeDisabled();
261​
262 await userEvent.keyboard("{Escape}");
263 await whenTrigger.click();
264​
265 await expect.element(expression).toHaveValue("terminalFocus");
266 await expect.element(screen.getByRole("button", { name: "Save" })).toBeEnabled();
267});
268​
269it("blocks visual When builder edits while the expression cannot be parsed", async () => {
270 await using screen = await render(<KeybindingsSettingsPanel />);
271 await screen.getByRole("button", { name: "Edit when clause for Terminal: Close" }).click();
272 const expression = screen.getByRole("textbox", { name: "When expression" });
273 const addCondition = screen.getByRole("button", { name: "Condition", exact: true });
274 const addGroup = screen.getByRole("button", { name: "Group", exact: true });
275 const negate = screen.getByRole("button", { name: "Negate terminalFocus" });
276 await expect.element(expression).toHaveValue("terminalFocus");
277​
278 await expression.fill("terminalFocus &&");
279 const overlay = screen.getByText("Fix the expression above to continue editing visually.");
280 await expect.element(overlay).toBeVisible();
281 await expect.element(addCondition).toBeDisabled();
282 await expect.element(addGroup).toBeDisabled();
283​
284 await negate.click({ force: true });
285 await expect.element(expression).toHaveValue("terminalFocus &&");
286​
287 await expression.fill("terminalFocus");
288 await expect.element(overlay).not.toBeInTheDocument();
289 await expect.element(addCondition).toBeEnabled();
290 await expect.element(addGroup).toBeEnabled();
291 await negate.click();
292 await expect.element(expression).toHaveValue("!terminalFocus");
293});
294​
295it("filters actions and allows additional shortcuts for assigned commands", async () => {
296 await using screen = await render(<KeybindingsSettingsPanel />);
297 await screen.getByRole("button", { name: "Add keybinding" }).click();
298 const dialog = page.getByRole("dialog", { name: "Command", exact: true });
299 const search = dialog.getByRole("combobox", { name: "Search", exact: true });
300 await expect.element(search).toHaveFocus();
301 await userEvent.keyboard("sidebar.toggle");
302 const assigned = page.getByRole("option", { name: /Sidebar: Toggle/ });
303 await expect.element(assigned).not.toHaveAttribute("aria-disabled", "true");
304 await expect.element(assigned.element().querySelector("kbd")!).toBeVisible();
305 await vi.waitFor(() => expect(page.getByRole("option").elements()).toHaveLength(1));
306 await assigned.click();
307 const command = screen.getByRole("combobox", { name: "Command", exact: true });
308 await expect.element(command).toHaveTextContent("Sidebar: Toggle");
309 await command.click();
310 await search.fill("Opposite Queue");
311 await expect
312 .element(page.getByRole("option", { name: /Composer: Opposite Queue or Steer Action/ }))
313 .toBeVisible();
314 await vi.waitFor(() => expect(page.getByRole("option").elements()).toHaveLength(1));
315 await search.fill("no-such-action");
316 await expect.element(page.getByText("No results found.")).toBeVisible();
317 await search.fill("composer.cycleHost");
318 const available = page.getByRole("option", { name: "Composer: Cycle Host" });
319 await expect.element(available).not.toHaveAttribute("aria-disabled", "true");
320 await available.click();
321 await expect
322 .element(screen.getByRole("combobox", { name: "Command", exact: true }))
323 .toHaveTextContent("Composer: Cycle Host");
324});
325​
326it.each([
327 {
328 name: "macOS",
329 platform: "MacIntel",
330 terminalPreviousMac: {
331 ariaLabel: "Edit shortcut for Terminal: Previous: ⇧⌘[",
332 keys: ["⇧", "⌘", "["],
333 },
334 terminalPreviousCtrl: {
335 ariaLabel: "Edit shortcut for Terminal: Previous: ⌃⌥[",
336 keys: ["⌃", "⌥", "["],
337 },
338 editQueued: {
339 ariaLabel: "Edit shortcut for Queue: Edit Last Queued Message: ⌥Up",
340 keys: ["⌥", "Up"],
341 },
342 focusNext: { ariaLabel: "Edit shortcut for Focus Next Workspace Area: F6", keys: ["F6"] },
343 },
344 {
345 name: "Linux",
346 platform: "Linux x86_64",
347 terminalPreviousMac: {
348 ariaLabel: "Edit shortcut for Terminal: Previous: Shift+Meta+[",
349 keys: ["Shift", "Meta", "["],
350 },
351 terminalPreviousCtrl: {
352 ariaLabel: "Edit shortcut for Terminal: Previous: Ctrl+Alt+[",
353 keys: ["Ctrl", "Alt", "["],
354 },
355 editQueued: {
356 ariaLabel: "Edit shortcut for Queue: Edit Last Queued Message: Alt+Up",
357 keys: ["Alt", "Up"],
358 },
359 focusNext: { ariaLabel: "Edit shortcut for Focus Next Workspace Area: F6", keys: ["F6"] },
360 },
361])(
362 "renders platform modifier symbols and formatted key labels in shortcut pills on $name",
363 async ({ platform, terminalPreviousMac, terminalPreviousCtrl, editQueued, focusNext }) => {
364 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue(platform);
365 await using screen = await render(<KeybindingsSettingsPanel />);
366​
367 for (const expected of [terminalPreviousMac, terminalPreviousCtrl, editQueued, focusNext]) {
368 const button = screen.getByRole("button", { name: expected.ariaLabel, exact: true });
369 await expect.element(button).toBeVisible();
370 const kbdTexts = Array.from(
371 button.element().querySelectorAll('[data-slot="kbd"]'),
372 (el) => el.textContent,
373 );
374 expect(kbdTexts).toEqual(expected.keys);
375 }
376 },
377);
378​
379it("keeps an unsaved new keybinding open when another row's shortcut is saved", async () => {
380 const mutate = vi.fn(async () => ({ _tag: "Success", value: [] }));
381 await vi.mocked(atomCommands.useAtomCommand).withImplementation(
382 () => mutate as never,
383 async () => {
384 await using screen = await render(<KeybindingsSettingsPanel />);
385​
386 await screen.getByRole("button", { name: "Add keybinding" }).click();
387 await userEvent.keyboard("composer.cycleHost");
388 await page.getByRole("option", { name: "Composer: Cycle Host" }).click();
389 await expect
390 .element(screen.getByRole("combobox", { name: "Command", exact: true }))
391 .toHaveTextContent("Composer: Cycle Host");
392​
393 await existingPill.click();
394 await userEvent.keyboard("{Control>}{Alt>}j{/Alt}{/Control}");
395 const saves = screen.getByRole("button", { name: "Save" });
396 await vi.waitFor(() => expect(saves.elements()).toHaveLength(2));
397 const rowSave = saves.elements().find((button) => !(button as HTMLButtonElement).disabled);
398 (rowSave as HTMLButtonElement).click();
399 await vi.waitFor(() =>
400 expect(mutate).toHaveBeenLastCalledWith({
401 environmentId: "env",
402 input: expect.objectContaining({ command: "sidebar.toggle" }),
403 }),
404 );
405 await act(async () => {
406 await mutate.mock.results.at(-1)?.value;
407 });
408 await expect.element(screen.getByText("Saving")).not.toBeInTheDocument();
409​
410 expect(
411 screen.getByRole("combobox", { name: "Command", exact: true }).elements(),
412 ).toHaveLength(1);
413 },
414 );
415});