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

useChatShortcuts.browser.test.tsx

754 lines27.2 KB

1import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts";
2import { useEffect, useRef, useState } from "react";
3import { createPortal } from "react-dom";
4import { expect, it, vi } from "vite-plus/test";
5import { page, userEvent } from "vite-plus/test/browser";
6​
7import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings";
8import { dismissContextMenu, showContextMenuFallback } from "~/contextMenuFallback";
9import { isPreviewFocused } from "~/lib/previewFocus";
10import { surfaceShortcutKey } from "~/lib/surfaceShortcutKey";
11import { render } from "../../../test/render";
12import { RightPanelSheet } from "../RightPanelSheet";
13import { Dialog, DialogPopup } from "../ui/dialog";
14import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
15import { Popover, PopoverPopup } from "../ui/popover";
16import type { ChatComposerHandle } from "./ChatComposer";
17import { composerFloatingLayerProps } from "./composerEventScope";
18import { useChatShortcuts } from "./useChatShortcuts";
19​
20const shortcutContext = {
21 terminalFocus: false,
22 terminalOpen: false,
23 previewFocus: false,
24 previewOpen: false,
25 isWeb: true,
26 isDesktop: false,
27 modelPickerOpen: false,
28};
29​
30const focusOnMount = (element: HTMLElement | null) => element?.focus();
31​
32const ctrl = (key: string, command: KeybindingCommand, shiftKey = false) => ({
33 command,
34 shortcut: { key, metaKey: false, ctrlKey: true, shiftKey, altKey: false, modKey: false },
35});
36​
37// Stands in for the right panel's launcher, which needs the whole app around it. Like the
38// real one it takes focus, advertises its letters in `data-surface-launcher-keys`, and
39// claims one from its own window capture listener unless the key was already handled.
40function Launcher(props: { keys: string; received: string[] }) {
41 useEffect(() => {
42 const claim = (event: KeyboardEvent) => {
43 if (event.defaultPrevented) return;
44 const key = surfaceShortcutKey(event);
45 if (key === null || !props.keys.toLowerCase().includes(key)) return;
46 event.preventDefault();
47 props.received.push(event.key);
48 };
49 window.addEventListener("keydown", claim, true);
50 return () => window.removeEventListener("keydown", claim, true);
51 }, [props.keys, props.received]);
52 return (
53 <div
54 ref={focusOnMount}
55 tabIndex={0}
56 aria-label="Open a surface"
57 data-surface-launcher-keys={props.keys}
58 />
59 );
61​
62// The chat's shortcut listener registers when the chat mounts, so a launcher that opens
63// later registers after it. Tests mount the chat first and add the launcher by rerendering.
64function Chat(props: {
65 composerKeys: string[];
66 launcher?: { keys: string; received: string[] };
67 finds?: string[];
68 toggles?: string[];
69 stops?: string[];
70 findCloses?: string[];
71 scriptKeybindings?: ResolvedKeybindingsConfig;
72 scriptsRan?: string[];
73 queued?: string[];
74}) {
75 useChatShortcuts({
76 enabled: true,
77 keybindings: [
78 ctrl("f", "chat.find"),
79 ctrl("m", "modelPicker.toggle", true),
80 ctrl("x", "thread.stop", true),
81 ...compileResolvedKeybindingsConfig([
82 { key: "ctrl+shift+enter", command: "thread.steerQueuedMessage" },
83 { key: "alt+arrowup", command: "thread.editQueuedMessage" },
84 ]),
85 ],
86 scriptKeybindings: props.scriptKeybindings ?? [],
87 getShortcutContext: () => shortcutContext,
88 threadFindActive: props.findCloses !== undefined,
89 // The stand-in composer implements only the methods these shortcut tests invoke.
90 composerRef: {
91 current: {
92 insertTextAtEnd: (key: string) => {
93 props.composerKeys.push(key);
94 return true;
95 },
96 isModelPickerOpen: () => false,
97 toggleModelPicker: () => void props.toggles?.push("main"),
98 } as Partial<ChatComposerHandle> as ChatComposerHandle,
99 },
100 branchToolbarRef: { current: null },
101 closeThreadFind: () => void props.findCloses?.push("main"),
102 commands: {
103 "chat.find": () => void props.finds?.push("main"),
104 "thread.stop": () => void props.stops?.push("main"),
105 "thread.steerQueuedMessage": () => void props.queued?.push("main steer"),
106 "thread.editQueuedMessage": () => void props.queued?.push("main edit"),
107 },
108 fallback: (command) =>
109 props.scriptsRan ? () => void props.scriptsRan?.push(command) : undefined,
110 });
111 return props.launcher ? <Launcher {...props.launcher} /> : null;
113​
114// router: false because the chat shortcuts and the launcher stand-in never navigate.
115const options = { router: false } as const;
116​
117it("leaves the launcher's letters to the launcher, in either case", async () => {
118 const composerKeys: string[] = [];
119 const received: string[] = [];
120 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
121 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
122​
123 await userEvent.keyboard("tT");
124​
125 expect(received).toEqual(["t", "T"]);
126 expect(composerKeys).toEqual([]);
127});
128​
129it("still types other letters into the composer while the launcher is open", async () => {
130 const composerKeys: string[] = [];
131 const received: string[] = [];
132 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
133 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
134​
135 await userEvent.keyboard("a");
136​
137 expect(composerKeys).toEqual(["a"]);
138 expect(received).toEqual([]);
139});
140​
141it("leaves a non-Latin launcher letter to the launcher by its physical key", async () => {
142 const composerKeys: string[] = [];
143 const received: string[] = [];
144 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
145 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
146​
147 // Playwright cannot press a key its US layout lacks, so send what a Ukrainian T key sends.
148 const event = new KeyboardEvent("keydown", {
149 key: "\u0435",
150 code: "KeyT",
151 bubbles: true,
152 cancelable: true,
153 });
154 (document.activeElement ?? document.body).dispatchEvent(event);
155​
156 expect(composerKeys).toEqual([]);
157 expect(received).toEqual(["\u0435"]);
158});
159​
160it.each([
161 { key: "b", code: "KeyN", composer: [], launcher: ["b"] },
162 { key: "x", code: "KeyB", composer: ["x"], launcher: [] },
163 { key: "è", code: "KeyT", composer: ["è"], launcher: [] },
164])("routes $key on $code by the typed letter", async ({ key, code, composer, launcher }) => {
165 const composerKeys: string[] = [];
166 const received: string[] = [];
167 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
168 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
169​
170 const event = new KeyboardEvent("keydown", { key, code, bubbles: true, cancelable: true });
171 (document.activeElement ?? document.body).dispatchEvent(event);
172​
173 expect(composerKeys).toEqual(composer);
174 expect(received).toEqual(launcher);
175});
176​
177function UnavailableTerminalCommand({
178 command,
179 owner,
180}: {
181 command: KeybindingCommand;
182 owner: "drawer" | "right-panel" | null;
183}) {
184 useChatShortcuts({
185 enabled: true,
186 keybindings: compileResolvedKeybindingsConfig([
187 { key: command === "terminal.previous" ? "cmd+shift+[" : "cmd+shift+]", command },
188 ]),
189 scriptKeybindings: [],
190 getShortcutContext: () => ({ ...shortcutContext, terminalFocus: owner !== null }),
191 threadFindActive: false,
192 composerRef: { current: null },
193 branchToolbarRef: { current: null },
194 closeThreadFind: () => {},
195 commands: { [command]: () => false },
196 fallback: () => undefined,
197 });
198 return (
199 <div data-terminal-owner={owner ?? undefined}>
200 <input ref={focusOnMount} />
201 </div>
202 );
204​
205it.each([
206 ["terminal.previous", "drawer", true],
207 ["terminal.next", "drawer", true],
208 ["terminal.new", "drawer", false],
209 ["terminal.previous", "right-panel", true],
210 ["terminal.next", "right-panel", true],
211 ["terminal.previous", null, false],
212 ["terminal.next", null, false],
213] as const)("handles unavailable %s with focus owner %s", async (command, owner, prevented) => {
214 await using screen = await render(
215 <UnavailableTerminalCommand command={command} owner={owner} />,
216 options,
217 );
218 const input = screen.container.querySelector("input")!;
219 const received: string[] = [];
220 input.addEventListener("keydown", (event) => received.push(event.key));
221 const previous = command === "terminal.previous";
222 const key = previous ? "{" : "}";
223 const event = new KeyboardEvent("keydown", {
224 key,
225 code: previous ? "BracketLeft" : "BracketRight",
226 shiftKey: true,
227 metaKey: true,
228 bubbles: true,
229 cancelable: true,
230 });
231 input.dispatchEvent(event);
232 expect(event.defaultPrevented).toBe(prevented);
233 expect(received).toEqual(prevented ? [] : [key]);
234});
235​
236const sideChatKeybindings: ResolvedKeybindingsConfig = [
237 ctrl("m", "modelPicker.toggle", true),
238 ctrl("x", "thread.stop", true),
239 // The default find and queue rules, with ctrl for mod so they match on every platform.
240 ...compileResolvedKeybindingsConfig([
241 { key: "ctrl+f", command: "chat.find", when: "!terminalFocus && !previewFocus" },
242 { key: "ctrl+shift+enter", command: "thread.steerQueuedMessage", when: "!terminalFocus" },
243 { key: "alt+arrowup", command: "thread.editQueuedMessage", when: "composerFocus" },
244 ]),
245];
246​
247// A side chat in the main chat's right panel: only its pane's find and queue, and its composer's
248// own chords. Passing `findCloses` opens its find.
249function SideChat(props: {
250 toggles: string[];
251 stops: string[];
252 finds?: string[];
253 findCloses?: string[];
254 queued?: string[];
255}) {
256 const [composerElement, setComposerElement] = useState<HTMLDivElement | null>(null);
257 useChatShortcuts({
258 enabled: false,
259 embedded: true,
260 composerElement,
261 keybindings: sideChatKeybindings,
262 scriptKeybindings: [],
263 getShortcutContext: () => ({
264 ...shortcutContext,
265 previewFocus: isPreviewFocused(),
266 composerFocus: document.activeElement?.getAttribute("aria-label") === "Side chat composer",
267 }),
268 threadFindActive: props.findCloses !== undefined,
269 composerRef: {
270 current: {
271 isModelPickerOpen: () => false,
272 toggleModelPicker: () => props.toggles.push("model"),
273 } as Partial<ChatComposerHandle> as ChatComposerHandle,
274 },
275 branchToolbarRef: { current: null },
276 closeThreadFind: () => void props.findCloses?.push("side"),
277 commands: {
278 "thread.stop": () => void props.stops.push("stop"),
279 "chat.find": () => void props.finds?.push("side"),
280 "thread.steerQueuedMessage": () => void props.queued?.push("side steer"),
281 "thread.editQueuedMessage": () => void props.queued?.push("side edit"),
282 },
283 fallback: () => undefined,
284 });
285 return (
286 <>
287 <div data-preview-panel-mode="inline">
288 <div data-side-chat-pane>
289 <input aria-label="Side chat find" />
290 <div tabIndex={0} aria-label="Side chat timeline">
291 Conversation
292 </div>
293 <Menu>
294 <MenuTrigger>Side chat actions</MenuTrigger>
295 <MenuPopup>
296 <MenuItem>Copy</MenuItem>
297 </MenuPopup>
298 </Menu>
299 <div ref={setComposerElement}>
300 <textarea aria-label="Side chat composer" />
301 </div>
302 </div>
303 </div>
304 <textarea aria-label="Main composer" />
305 </>
306 );
308​
309it("runs a side chat's composer chords only from its composer, and never thread.stop", async () => {
310 const toggles: string[] = [];
311 const stops: string[] = [];
312 await using screen = await render(<SideChat toggles={toggles} stops={stops} />, options);
313​
314 await userEvent.click(screen.getByLabelText("Side chat composer"));
315 await userEvent.keyboard("{Control>}{Shift>}MX{/Shift}{/Control}");
316 await userEvent.click(screen.getByLabelText("Main composer"));
317 await userEvent.keyboard("{Control>}{Shift>}M{/Shift}{/Control}");
318​
319 expect(toggles).toEqual(["model"]);
320 expect(stops).toEqual([]);
321});
322​
323it("opens the side chat's own find for mod+F anywhere in its pane, not the main chat's", async () => {
324 const finds: string[] = [];
325 await using screen = await render(
326 <>
327 <Chat composerKeys={[]} finds={finds} />
328 <SideChat toggles={[]} stops={[]} finds={finds} />
329 </>,
330 options,
331 );
332​
333 await userEvent.click(screen.getByLabelText("Side chat composer"));
334 await userEvent.keyboard("{Control>}f{/Control}");
335 await userEvent.click(screen.getByLabelText("Side chat timeline"));
336 await userEvent.keyboard("{Control>}f{/Control}");
337​
338 expect(finds).toEqual(["side", "side"]);
339});
340​
341it("steers and edits the side chat's own queue from its pane, not the main chat's", async () => {
342 const queued: string[] = [];
343 await using screen = await render(
344 <>
345 <Chat composerKeys={[]} queued={queued} />
346 <SideChat toggles={[]} stops={[]} queued={queued} />
347 </>,
348 options,
349 );
350​
351 await userEvent.click(screen.getByLabelText("Side chat composer"));
352 await userEvent.keyboard("{Control>}{Shift>}{Enter}{/Shift}{/Control}");
353 await userEvent.keyboard("{Alt>}{ArrowUp}{/Alt}");
354 await userEvent.click(screen.getByLabelText("Side chat timeline"));
355 await userEvent.keyboard("{Control>}{Shift>}{Enter}{/Shift}{/Control}");
356​
357 expect(queued).toEqual(["side steer", "side edit", "side steer"]);
358});
359​
360function PortalledPopup(props: { label: string; composerLayer?: boolean }) {
361 return createPortal(
362 <div {...(props.composerLayer ? composerFloatingLayerProps : undefined)}>
363 <input aria-label={props.label} />
364 </div>,
365 document.body,
366 );
368​
369it("routes shortcuts in portalled popups to the chat that opened them", async () => {
370 const toggles: string[] = [];
371 const finds: string[] = [];
372 const stops: string[] = [];
373 const findCloses: string[] = [];
374 await using screen = await render(
375 <>
376 <Chat
377 composerKeys={[]}
378 toggles={toggles}
379 finds={finds}
380 stops={stops}
381 findCloses={findCloses}
382 />
383 <SideChat toggles={toggles} stops={stops} finds={finds} />
384 <PortalledPopup label="Composer popup" composerLayer />
385 <PortalledPopup label="Non-composer popup" />
386 {createPortal(<span tabIndex={0} data-base-ui-focus-guard="" />, document.body)}
387 </>,
388 options,
389 );
390​
391 // Side chat owns portalled composer floating layers across Base UI focus-guard wraps.
392 await userEvent.click(screen.getByLabelText("Side chat composer"));
393 document.querySelector<HTMLElement>("[data-base-ui-focus-guard]")?.focus();
394 await userEvent.click(screen.getByLabelText("Composer popup"));
395 await userEvent.keyboard("{Control>}{Shift>}MX{/Shift}f{/Control}{Escape}");
396 await vi.waitFor(() => {
397 expect(toggles).toEqual(["model"]);
398 expect(finds).toEqual(["side"]);
399 });
400​
401 // Focusing the main chat hands composer popups back to the main chat.
402 await userEvent.click(screen.getByLabelText("Main composer"));
403 await userEvent.click(screen.getByLabelText("Composer popup"));
404 await userEvent.keyboard("{Control>}{Shift>}M{/Shift}f{/Control}");
405 await vi.waitFor(() => {
406 expect(toggles).toEqual(["model", "main"]);
407 expect(finds).toEqual(["side", "main"]);
408 });
409​
410 // A menu the side chat opened portals out of its pane and keeps its keys from both chats.
411 await userEvent.click(screen.getByRole("button", { name: "Side chat actions" }));
412 await expect.element(screen.getByRole("menuitem", { name: "Copy" })).toBeVisible();
413 await userEvent.keyboard("{Control>}{Shift>}MX{/Shift}f{/Control}");
414 await vi.waitFor(() => {
415 expect(toggles).toEqual(["model", "main"]);
416 expect(finds).toEqual(["side", "main"]);
417 });
418 await expect.element(screen.getByRole("menu")).toHaveFocus();
419 await userEvent.keyboard("{Escape}");
420 await expect.element(screen.getByRole("menuitem", { name: "Copy" })).not.toBeInTheDocument();
421​
422 // Portalled elements that are not popups still route to the main chat.
423 await userEvent.click(screen.getByLabelText("Side chat composer"));
424 await userEvent.click(screen.getByLabelText("Non-composer popup"));
425 await userEvent.keyboard("{Control>}{Shift>}M{/Shift}f{/Control}");
426 await vi.waitFor(() => {
427 expect(toggles).toEqual(["model", "main", "main"]);
428 expect(finds).toEqual(["side", "main", "main"]);
429 });
430​
431 // Blurring out of the side chat to document.body lets a main shortcut reclaim popup ownership.
432 await userEvent.click(screen.getByLabelText("Side chat composer"));
433 (document.activeElement as HTMLElement).blur();
434 expect(document.activeElement).toBe(document.body);
435 await userEvent.keyboard("{Control>}{Shift>}M{/Shift}{/Control}");
436 await vi.waitFor(() => {
437 expect(toggles).toEqual(["model", "main", "main", "main"]);
438 });
439 (screen.getByLabelText("Composer popup").element() as HTMLElement).focus();
440 await userEvent.keyboard("{Control>}{Shift>}M{/Shift}f{/Control}");
441 await vi.waitFor(() => {
442 expect(toggles).toEqual(["model", "main", "main", "main", "main"]);
443 expect(finds).toEqual(["side", "main", "main", "main"]);
444 expect(stops).toEqual([]);
445 expect(findCloses).toEqual([]);
446 });
447});
448​
449it("closes the side chat's find for Escape in its find input and elsewhere in its pane", async () => {
450 const findCloses: string[] = [];
451 await using screen = await render(
452 <SideChat toggles={[]} stops={[]} findCloses={findCloses} />,
453 options,
454 );
455 // Stands in for the narrow right panel sheet, which also closes on an Escape that reaches it.
456 const sheetEscapes: string[] = [];
457 const onSheetKeyDown = (event: KeyboardEvent) => {
458 if (event.key === "Escape") sheetEscapes.push("sheet");
459 };
460 document.addEventListener("keydown", onSheetKeyDown);
461 using _sheet = {
462 [Symbol.dispose]: () => document.removeEventListener("keydown", onSheetKeyDown),
463 };
464​
465 await userEvent.click(screen.getByLabelText("Side chat find"));
466 await userEvent.keyboard("{Escape}");
467 await userEvent.click(screen.getByLabelText("Side chat timeline"));
468 await userEvent.keyboard("{Escape}");
469​
470 expect(findCloses).toEqual(["side", "side"]);
471 expect(sheetEscapes).toEqual([]);
472});
473​
474const ctrlAlt = (key: string, command: KeybindingCommand) => ({
475 command,
476 shortcut: { key, metaKey: false, ctrlKey: true, shiftKey: false, altKey: true, modKey: false },
477});
478​
479// The main chat's window listener while focus sits in a side chat pane in its right panel.
480function ChatWithSideChatPane(props: { ran: string[] }) {
481 useChatShortcuts({
482 enabled: true,
483 keybindings: [
484 ctrlAlt("b", "rightPanel.toggle"),
485 ctrlAlt("k", "rightPanel.close"),
486 ctrl("j", "terminal.toggle"),
487 ctrl("x", "thread.stop", true),
488 ],
489 scriptKeybindings: [],
490 getShortcutContext: () => shortcutContext,
491 threadFindActive: false,
492 composerRef: {
493 current: {
494 insertTextAtEnd: (key: string) => {
495 props.ran.push(`typed ${key}`);
496 return true;
497 },
498 } as Partial<ChatComposerHandle> as ChatComposerHandle,
499 },
500 branchToolbarRef: { current: null },
501 closeThreadFind: () => {},
502 commands: {
503 "rightPanel.toggle": () => void props.ran.push("toggle"),
504 "rightPanel.close": () => void props.ran.push("close"),
505 "terminal.toggle": () => void props.ran.push("terminal"),
506 "thread.stop": () => void props.ran.push("stop"),
507 },
508 fallback: () => undefined,
509 });
510 return (
511 <div data-side-chat-pane>
512 <div role="region" aria-label="Conversation" tabIndex={0}>
513 A side chat message
514 </div>
515 <textarea aria-label="Message Side chat" />
516 </div>
517 );
519​
520it("runs right panel commands from inside a side chat pane, but not thread commands", async () => {
521 const ran: string[] = [];
522 await using screen = await render(<ChatWithSideChatPane ran={ran} />, options);
523​
524 await userEvent.click(screen.getByLabelText("Message Side chat"));
525 await userEvent.keyboard("{Control>}{Alt>}BK{/Alt}{/Control}");
526 await userEvent.keyboard("{Control>}{Shift>}X{/Shift}{/Control}");
527 await userEvent.click(screen.getByRole("region", { name: "Conversation" }));
528 await userEvent.keyboard("{Control>}{Alt>}B{/Alt}{/Control}");
529 await userEvent.keyboard("q");
530​
531 expect(ran).toEqual(["toggle", "close", "toggle"]);
532});
533​
534it("leaves the right panel alone while a context menu has focus", async () => {
535 const ran: string[] = [];
536 await using _screen = await render(<ChatWithSideChatPane ran={ran} />, options);
537 const menu = showContextMenuFallback([{ id: "close", label: "Close" }]);
538 try {
539 await expect.element(page.getByRole("menu", { name: "Context menu" })).toHaveFocus();
540 await userEvent.keyboard("{Control>}{Alt>}BK{/Alt}{/Control}");
541 await userEvent.keyboard("{Control>}{Shift>}X{/Shift}{/Control}");
542 expect(ran).toEqual(["stop"]);
543 } finally {
544 dismissContextMenu();
545 await menu;
546 }
547});
548​
549it("leaves the right panel and terminal alone while a dialog is open", async () => {
550 const ran: string[] = [];
551 const view = (dialogOpen: boolean) => (
552 <>
553 <ChatWithSideChatPane ran={ran} />
554 <RightPanelSheet open={!dialogOpen} animationDurationMs={0} onClose={() => {}}>
555 <div>Panel</div>
556 </RightPanelSheet>
557 {dialogOpen ? (
558 <Dialog open>
559 <DialogPopup aria-label="Commit changes">
560 <input aria-label="Commit message" />
561 </DialogPopup>
562 </Dialog>
563 ) : null}
564 </>
565 );
566 await using screen = await render(view(true), options);
567 await expect.element(page.getByLabelText("Commit message")).toHaveFocus();
568 await userEvent.keyboard("{Control>}{Alt>}BK{/Alt}{/Control}");
569 await userEvent.keyboard("{Control>}j{/Control}");
570 await userEvent.keyboard("{Control>}{Shift>}X{/Shift}{/Control}");
571 await vi.waitFor(() => expect(ran).toEqual(["stop"]));
572​
573 await screen.rerender(view(false));
574 await expect
575 .element(page.getByRole("dialog", { name: "Commit changes" }))
576 .not.toBeInTheDocument();
577 await expect.element(page.getByRole("dialog", { name: "Workspace panel" })).toBeVisible();
578 await userEvent.keyboard("{Control>}{Alt>}BK{/Alt}{/Control}");
579 await userEvent.keyboard("{Control>}j{/Control}");
580 await vi.waitFor(() => expect(ran).toEqual(["stop", "toggle", "close", "terminal"]));
581});
582​
583it("lets Escape close the narrow right panel instead of stopping the thread", async () => {
584 const ran: string[] = [];
585 function ChatWithEscapeStop() {
586 const [open, setOpen] = useState(true);
587 useChatShortcuts({
588 enabled: true,
589 keybindings: compileResolvedKeybindingsConfig([{ key: "escape", command: "thread.stop" }]),
590 scriptKeybindings: [],
591 getShortcutContext: () => shortcutContext,
592 threadFindActive: false,
593 composerRef: { current: null },
594 branchToolbarRef: { current: null },
595 closeThreadFind: () => {},
596 commands: { "thread.stop": () => void ran.push("stop") },
597 fallback: () => undefined,
598 });
599 return (
600 <RightPanelSheet
601 open={open}
602 animationDurationMs={0}
603 onClose={() => {
604 ran.push("close");
605 setOpen(false);
606 }}
607 >
608 <button type="button">Close Files</button>
609 </RightPanelSheet>
610 );
611 }
612 await using _screen = await render(<ChatWithEscapeStop />, options);
613 const panel = page.getByRole("dialog", { name: "Workspace panel" });
614 const closeFiles = panel.getByRole("button", { name: "Close Files" });
615 (closeFiles.element() as HTMLElement).focus();
616 await expect.element(closeFiles).toHaveFocus();
617​
618 await userEvent.keyboard("{Escape}");
619​
620 await vi.waitFor(() => expect(ran).toEqual(["close"]));
621 await expect.element(panel).not.toBeInTheDocument();
622​
623 await userEvent.keyboard("{Escape}");
624​
625 await vi.waitFor(() => expect(ran).toEqual(["close", "stop"]));
626});
627​
628it.each(["video", "audio"] as const)(
629 "leaves keys to a focused %s player with controls",
630 async (media) => {
631 const composerKeys: string[] = [];
632 await using _screen = await render(
633 <>
634 <Chat composerKeys={composerKeys} />
635 {media === "video" ? (
636 <video ref={focusOnMount} controls />
637 ) : (
638 <audio ref={focusOnMount} controls />
639 )}
640 </>,
641 options,
642 );
643​
644 await userEvent.keyboard(" m");
645 expect(composerKeys).toEqual([]);
646​
647 (document.activeElement as HTMLElement).blur();
648 await userEvent.keyboard("a");
649 expect(composerKeys).toEqual(["a"]);
650 },
651);
652​
653it("leaves keys alone while a fallback context menu is open", async () => {
654 const composerKeys: string[] = [];
655 await using screen = await render(
656 <>
657 <Chat composerKeys={composerKeys} />
658 <div ref={focusOnMount} role="menu" data-context-menu="true" tabIndex={-1} />
659 </>,
660 options,
661 );
662​
663 await userEvent.keyboard("a");
664 expect(composerKeys).toEqual([]);
665​
666 await screen.rerender(<Chat composerKeys={composerKeys} />);
667 await userEvent.keyboard("a");
668 expect(composerKeys).toEqual(["a"]);
669});
670​
671it("leaves project-script shortcuts alone inside a keybinding capture field", async () => {
672 const scriptsRan: string[] = [];
673 const prevented: boolean[] = [];
674 await using screen = await render(
675 <>
676 <Chat
677 composerKeys={[]}
678 scriptKeybindings={[ctrl("y", "script.build.run", true)]}
679 scriptsRan={scriptsRan}
680 />
681 <input
682 ref={focusOnMount}
683 aria-label="Keybinding"
684 data-keybinding-capture=""
685 readOnly
686 onKeyDown={(event) => {
687 if (event.key.toLowerCase() === "y") prevented.push(event.defaultPrevented);
688 }}
689 />
690 <button type="button">Outside</button>
691 </>,
692 options,
693 );
694​
695 await userEvent.keyboard("{Control>}{Shift>}Y{/Shift}{/Control}");
696 expect(scriptsRan).toEqual([]);
697 expect(prevented).toEqual([false]);
698​
699 await userEvent.click(screen.getByRole("button", { name: "Outside" }));
700 await userEvent.keyboard("{Control>}{Shift>}Y{/Shift}{/Control}");
701 expect(scriptsRan).toEqual(["script.build.run"]);
702});
703​
704it("closes an open menu when modelPicker.toggle opens and toggles the picker off on a second press", async () => {
705 function MenuAndPicker() {
706 const [open, setOpen] = useState(false);
707 const searchInputRef = useRef<HTMLInputElement | null>(null);
708 useChatShortcuts({
709 enabled: true,
710 keybindings: [ctrl("m", "modelPicker.toggle", true)],
711 scriptKeybindings: [],
712 getShortcutContext: () => shortcutContext,
713 threadFindActive: false,
714 composerRef: {
715 current: {
716 isModelPickerOpen: () => open,
717 toggleModelPicker: () => setOpen((wasOpen) => !wasOpen),
718 } as Partial<ChatComposerHandle> as ChatComposerHandle,
719 },
720 branchToolbarRef: { current: null },
721 closeThreadFind: () => {},
722 commands: {},
723 fallback: () => undefined,
724 });
725 return (
726 <>
727 <Menu>
728 <MenuTrigger>Actions</MenuTrigger>
729 <MenuPopup>
730 <MenuItem>Rename</MenuItem>
731 </MenuPopup>
732 </Menu>
733 <Popover open={open} onOpenChange={setOpen}>
734 <PopoverPopup initialFocus={searchInputRef}>
735 <input ref={searchInputRef} placeholder="Search models..." />
736 </PopoverPopup>
737 </Popover>
738 </>
739 );
740 }
741​
742 await using screen = await render(<MenuAndPicker />, options);
743 await userEvent.click(screen.getByRole("button", { name: "Actions" }));
744 const item = page.getByRole("menuitem", { name: "Rename" });
745 await expect.element(item).toBeVisible();
746​
747 await userEvent.keyboard("{Control>}{Shift>}M{/Shift}{/Control}");
748 const searchInput = page.getByPlaceholder("Search models...");
749 await expect.element(item).not.toBeInTheDocument();
750 await expect.element(searchInput).toHaveFocus();
751​
752 await userEvent.keyboard("{Control>}{Shift>}M{/Shift}{/Control}");
753 await expect.element(searchInput).not.toBeInTheDocument();
754});