Open History to see the last commit
1import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts";
2import { useEffect, useState } from "react";
3import { expect, it } from "vite-plus/test";
4import { userEvent } from "vite-plus/test/browser";
5
6import { compileResolvedKeybindingsConfig } from "@t3tools/shared/keybindings";
7import { isPreviewFocused } from "~/lib/previewFocus";
8import { surfaceShortcutKey } from "~/lib/surfaceShortcutKey";
9import { render } from "../../../test/render";
10import type { ChatComposerHandle } from "./ChatComposer";
11import { useChatShortcuts } from "./useChatShortcuts";
12
13const shortcutContext = {
14 terminalFocus: false,
15 terminalOpen: false,
16 previewFocus: false,
17 previewOpen: false,
18 isWeb: true,
19 isDesktop: false,
20 modelPickerOpen: false,
21};
22
23const focusOnMount = (element: HTMLElement | null) => element?.focus();
24
25const ctrl = (key: string, command: KeybindingCommand, shiftKey = false) => ({
26 command,
27 shortcut: { key, metaKey: false, ctrlKey: true, shiftKey, altKey: false, modKey: false },
28});
29
30// Stands in for the right panel's launcher, which needs the whole app around it. Like the
31// real one it takes focus, advertises its letters in `data-surface-launcher-keys`, and
32// claims one from its own window capture listener unless the key was already handled.
33function Launcher(props: { keys: string; received: string[] }) {
34 useEffect(() => {
35 const claim = (event: KeyboardEvent) => {
36 if (event.defaultPrevented) return;
37 const key = surfaceShortcutKey(event);
38 if (key === null || !props.keys.toLowerCase().includes(key)) return;
39 event.preventDefault();
40 props.received.push(event.key);
41 };
42 window.addEventListener("keydown", claim, true);
43 return () => window.removeEventListener("keydown", claim, true);
44 }, [props.keys, props.received]);
45 return (
46 <div
47 ref={focusOnMount}
48 tabIndex={0}
49 aria-label="Open a surface"
50 data-surface-launcher-keys={props.keys}
51 />
52 );
53}
54
55// The chat's shortcut listener registers when the chat mounts, so a launcher that opens
56// later registers after it. Tests mount the chat first and add the launcher by rerendering.
57function Chat(props: {
58 composerKeys: string[];
59 launcher?: { keys: string; received: string[] };
60 finds?: string[];
61 scriptKeybindings?: ResolvedKeybindingsConfig;
62 scriptsRan?: string[];
63}) {
64 useChatShortcuts({
65 enabled: true,
66 keybindings: [ctrl("f", "chat.find")],
67 scriptKeybindings: props.scriptKeybindings ?? [],
68 getShortcutContext: () => shortcutContext,
69 threadFindActive: false,
70 // Type-to-focus only calls insertTextAtEnd, so the stand-in composer implements just that.
71 composerRef: {
72 current: {
73 insertTextAtEnd: (key: string) => {
74 props.composerKeys.push(key);
75 return true;
76 },
77 } as Partial<ChatComposerHandle> as ChatComposerHandle,
78 },
79 branchToolbarRef: { current: null },
80 closeThreadFind: () => {},
81 commands: { "chat.find": () => void props.finds?.push("main") },
82 fallback: (command) =>
83 props.scriptsRan ? () => void props.scriptsRan?.push(command) : undefined,
84 });
85 return props.launcher ? <Launcher {...props.launcher} /> : null;
86}
87
88// router: false because the chat shortcuts and the launcher stand-in never navigate.
89const options = { router: false } as const;
90
91it("leaves the launcher's letters to the launcher, in either case", async () => {
92 const composerKeys: string[] = [];
93 const received: string[] = [];
94 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
95 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
96
97 await userEvent.keyboard("tT");
98
99 expect(received).toEqual(["t", "T"]);
100 expect(composerKeys).toEqual([]);
101});
102
103it("still types other letters into the composer while the launcher is open", async () => {
104 const composerKeys: string[] = [];
105 const received: string[] = [];
106 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
107 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
108
109 await userEvent.keyboard("a");
110
111 expect(composerKeys).toEqual(["a"]);
112 expect(received).toEqual([]);
113});
114
115it("leaves a non-Latin launcher letter to the launcher by its physical key", async () => {
116 const composerKeys: string[] = [];
117 const received: string[] = [];
118 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
119 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
120
121 // Playwright cannot press a key its US layout lacks, so send what a Ukrainian T key sends.
122 const event = new KeyboardEvent("keydown", {
123 key: "\u0435",
124 code: "KeyT",
125 bubbles: true,
126 cancelable: true,
127 });
128 (document.activeElement ?? document.body).dispatchEvent(event);
129
130 expect(composerKeys).toEqual([]);
131 expect(received).toEqual(["\u0435"]);
132});
133
134it.each([
135 { key: "b", code: "KeyN", composer: [], launcher: ["b"] },
136 { key: "x", code: "KeyB", composer: ["x"], launcher: [] },
137 { key: "è", code: "KeyT", composer: ["è"], launcher: [] },
138])("routes $key on $code by the typed letter", async ({ key, code, composer, launcher }) => {
139 const composerKeys: string[] = [];
140 const received: string[] = [];
141 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
142 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
143
144 const event = new KeyboardEvent("keydown", { key, code, bubbles: true, cancelable: true });
145 (document.activeElement ?? document.body).dispatchEvent(event);
146
147 expect(composerKeys).toEqual(composer);
148 expect(received).toEqual(launcher);
149});
150
151function UnavailableTerminalCommand({
152 command,
153 owner,
154}: {
155 command: KeybindingCommand;
156 owner: "drawer" | "right-panel" | null;
157}) {
158 useChatShortcuts({
159 enabled: true,
160 keybindings: compileResolvedKeybindingsConfig([
161 { key: command === "terminal.previous" ? "cmd+shift+[" : "cmd+shift+]", command },
162 ]),
163 scriptKeybindings: [],
164 getShortcutContext: () => ({ ...shortcutContext, terminalFocus: owner !== null }),
165 threadFindActive: false,
166 composerRef: { current: null },
167 branchToolbarRef: { current: null },
168 closeThreadFind: () => {},
169 commands: { [command]: () => false },
170 fallback: () => undefined,
171 });
172 return (
173 <div data-terminal-owner={owner ?? undefined}>
174 <input ref={focusOnMount} />
175 </div>
176 );
177}
178
179it.each([
180 ["terminal.previous", "drawer", true],
181 ["terminal.next", "drawer", true],
182 ["terminal.new", "drawer", false],
183 ["terminal.previous", "right-panel", true],
184 ["terminal.next", "right-panel", true],
185 ["terminal.previous", null, false],
186 ["terminal.next", null, false],
187] as const)("handles unavailable %s with focus owner %s", async (command, owner, prevented) => {
188 await using screen = await render(
189 <UnavailableTerminalCommand command={command} owner={owner} />,
190 options,
191 );
192 const input = screen.container.querySelector("input")!;
193 const received: string[] = [];
194 input.addEventListener("keydown", (event) => received.push(event.key));
195 const previous = command === "terminal.previous";
196 const key = previous ? "{" : "}";
197 const event = new KeyboardEvent("keydown", {
198 key,
199 code: previous ? "BracketLeft" : "BracketRight",
200 shiftKey: true,
201 metaKey: true,
202 bubbles: true,
203 cancelable: true,
204 });
205 input.dispatchEvent(event);
206 expect(event.defaultPrevented).toBe(prevented);
207 expect(received).toEqual(prevented ? [] : [key]);
208});
209
210const sideChatKeybindings: ResolvedKeybindingsConfig = [
211 ctrl("m", "modelPicker.toggle", true),
212 ctrl("x", "thread.stop", true),
213 // The default find rule, with ctrl for mod so it matches on every platform.
214 ...compileResolvedKeybindingsConfig([
215 { key: "ctrl+f", command: "chat.find", when: "!terminalFocus && !previewFocus" },
216 ]),
217];
218
219// A side chat in the main chat's right panel: no window listeners, only its pane's find and its
220// composer's own chords. Passing `findCloses` opens its find.
221function SideChat(props: {
222 toggles: string[];
223 stops: string[];
224 finds?: string[];
225 findCloses?: string[];
226}) {
227 const [composerElement, setComposerElement] = useState<HTMLDivElement | null>(null);
228 useChatShortcuts({
229 enabled: false,
230 embedded: true,
231 composerElement,
232 keybindings: sideChatKeybindings,
233 scriptKeybindings: [],
234 getShortcutContext: () => ({ ...shortcutContext, previewFocus: isPreviewFocused() }),
235 threadFindActive: props.findCloses !== undefined,
236 composerRef: {
237 current: {
238 toggleModelPicker: () => props.toggles.push("model"),
239 } as Partial<ChatComposerHandle> as ChatComposerHandle,
240 },
241 branchToolbarRef: { current: null },
242 closeThreadFind: () => void props.findCloses?.push("side"),
243 commands: {
244 "thread.stop": () => void props.stops.push("stop"),
245 "chat.find": () => void props.finds?.push("side"),
246 },
247 fallback: () => undefined,
248 });
249 return (
250 <>
251 <div data-preview-panel-mode="inline">
252 <div data-side-chat-pane>
253 <input aria-label="Side chat find" />
254 <div tabIndex={0} aria-label="Side chat timeline">
255 Conversation
256 </div>
257 <div ref={setComposerElement}>
258 <textarea aria-label="Side chat composer" />
259 </div>
260 </div>
261 </div>
262 <textarea aria-label="Main composer" />
263 </>
264 );
265}
266
267it("runs a side chat's composer chords only from its composer, and never thread commands", async () => {
268 const toggles: string[] = [];
269 const stops: string[] = [];
270 await using screen = await render(<SideChat toggles={toggles} stops={stops} />, options);
271
272 await userEvent.click(screen.getByLabelText("Side chat composer"));
273 await userEvent.keyboard("{Control>}{Shift>}MX{/Shift}{/Control}");
274 await userEvent.click(screen.getByLabelText("Main composer"));
275 await userEvent.keyboard("{Control>}{Shift>}M{/Shift}{/Control}");
276
277 expect(toggles).toEqual(["model"]);
278 expect(stops).toEqual([]);
279});
280
281it("opens the side chat's own find for mod+F anywhere in its pane, not the main chat's", async () => {
282 const finds: string[] = [];
283 await using screen = await render(
284 <>
285 <Chat composerKeys={[]} finds={finds} />
286 <SideChat toggles={[]} stops={[]} finds={finds} />
287 </>,
288 options,
289 );
290
291 await userEvent.click(screen.getByLabelText("Side chat composer"));
292 await userEvent.keyboard("{Control>}f{/Control}");
293 await userEvent.click(screen.getByLabelText("Side chat timeline"));
294 await userEvent.keyboard("{Control>}f{/Control}");
295
296 expect(finds).toEqual(["side", "side"]);
297});
298
299it("closes the side chat's find for Escape in its find input and elsewhere in its pane", async () => {
300 const findCloses: string[] = [];
301 await using screen = await render(
302 <SideChat toggles={[]} stops={[]} findCloses={findCloses} />,
303 options,
304 );
305 // Stands in for the narrow right panel sheet, which also closes on an Escape that reaches it.
306 const sheetEscapes: string[] = [];
307 const onSheetKeyDown = (event: KeyboardEvent) => {
308 if (event.key === "Escape") sheetEscapes.push("sheet");
309 };
310 document.addEventListener("keydown", onSheetKeyDown);
311 using _sheet = {
312 [Symbol.dispose]: () => document.removeEventListener("keydown", onSheetKeyDown),
313 };
314
315 await userEvent.click(screen.getByLabelText("Side chat find"));
316 await userEvent.keyboard("{Escape}");
317 await userEvent.click(screen.getByLabelText("Side chat timeline"));
318 await userEvent.keyboard("{Escape}");
319
320 expect(findCloses).toEqual(["side", "side"]);
321 expect(sheetEscapes).toEqual([]);
322});
323
324const ctrlAlt = (key: string, command: KeybindingCommand) => ({
325 command,
326 shortcut: { key, metaKey: false, ctrlKey: true, shiftKey: false, altKey: true, modKey: false },
327});
328
329// The main chat's window listener while focus sits in a side chat pane in its right panel.
330function ChatWithSideChatPane(props: { ran: string[] }) {
331 useChatShortcuts({
332 enabled: true,
333 keybindings: [
334 ctrlAlt("b", "rightPanel.toggle"),
335 ctrlAlt("k", "rightPanel.close"),
336 ctrl("x", "thread.stop", true),
337 ],
338 scriptKeybindings: [],
339 getShortcutContext: () => shortcutContext,
340 threadFindActive: false,
341 composerRef: {
342 current: {
343 insertTextAtEnd: (key: string) => {
344 props.ran.push(`typed ${key}`);
345 return true;
346 },
347 } as Partial<ChatComposerHandle> as ChatComposerHandle,
348 },
349 branchToolbarRef: { current: null },
350 closeThreadFind: () => {},
351 commands: {
352 "rightPanel.toggle": () => void props.ran.push("toggle"),
353 "rightPanel.close": () => void props.ran.push("close"),
354 "thread.stop": () => void props.ran.push("stop"),
355 },
356 fallback: () => undefined,
357 });
358 return (
359 <div data-side-chat-pane>
360 <div role="region" aria-label="Conversation" tabIndex={0}>
361 A side chat message
362 </div>
363 <textarea aria-label="Message Side chat" />
364 </div>
365 );
366}
367
368it("runs right panel commands from inside a side chat pane, but not thread commands", async () => {
369 const ran: string[] = [];
370 await using screen = await render(<ChatWithSideChatPane ran={ran} />, options);
371
372 await userEvent.click(screen.getByLabelText("Message Side chat"));
373 await userEvent.keyboard("{Control>}{Alt>}BK{/Alt}{/Control}");
374 await userEvent.keyboard("{Control>}{Shift>}X{/Shift}{/Control}");
375 await userEvent.click(screen.getByRole("region", { name: "Conversation" }));
376 await userEvent.keyboard("{Control>}{Alt>}B{/Alt}{/Control}");
377 await userEvent.keyboard("q");
378
379 expect(ran).toEqual(["toggle", "close", "toggle"]);
380});
381
382it("leaves keys to a focused video player with controls", async () => {
383 const composerKeys: string[] = [];
384 await using _screen = await render(
385 <>
386 <Chat composerKeys={composerKeys} />
387 <video ref={focusOnMount} controls />
388 </>,
389 options,
390 );
391
392 await userEvent.keyboard(" m");
393 expect(composerKeys).toEqual([]);
394
395 (document.activeElement as HTMLElement).blur();
396 await userEvent.keyboard("a");
397 expect(composerKeys).toEqual(["a"]);
398});
399
400it("leaves project-script shortcuts alone inside a keybinding capture field", async () => {
401 const scriptsRan: string[] = [];
402 const prevented: boolean[] = [];
403 await using screen = await render(
404 <>
405 <Chat
406 composerKeys={[]}
407 scriptKeybindings={[ctrl("y", "script.build.run", true)]}
408 scriptsRan={scriptsRan}
409 />
410 <input
411 ref={focusOnMount}
412 aria-label="Keybinding"
413 data-keybinding-capture=""
414 readOnly
415 onKeyDown={(event) => {
416 if (event.key.toLowerCase() === "y") prevented.push(event.defaultPrevented);
417 }}
418 />
419 <button type="button">Outside</button>
420 </>,
421 options,
422 );
423
424 await userEvent.keyboard("{Control>}{Shift>}Y{/Shift}{/Control}");
425 expect(scriptsRan).toEqual([]);
426 expect(prevented).toEqual([false]);
427
428 await userEvent.click(screen.getByRole("button", { name: "Outside" }));
429 await userEvent.keyboard("{Control>}{Shift>}Y{/Shift}{/Control}");
430 expect(scriptsRan).toEqual(["script.build.run"]);
431});