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}) {
62 useChatShortcuts({
63 enabled: true,
64 keybindings: [ctrl("f", "chat.find")],
65 scriptKeybindings: [],
66 getShortcutContext: () => shortcutContext,
67 threadFindActive: false,
68 // Type-to-focus only calls insertTextAtEnd, so the stand-in composer implements just that.
69 composerRef: {
70 current: {
71 insertTextAtEnd: (key: string) => {
72 props.composerKeys.push(key);
73 return true;
74 },
75 } as Partial<ChatComposerHandle> as ChatComposerHandle,
76 },
77 branchToolbarRef: { current: null },
78 closeThreadFind: () => {},
79 commands: { "chat.find": () => void props.finds?.push("main") },
80 fallback: () => undefined,
81 });
82 return props.launcher ? <Launcher {...props.launcher} /> : null;
83}
84
85// router: false because the chat shortcuts and the launcher stand-in never navigate.
86const options = { router: false } as const;
87
88it("leaves the launcher's letters to the launcher, in either case", async () => {
89 const composerKeys: string[] = [];
90 const received: string[] = [];
91 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
92 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
93
94 await userEvent.keyboard("tT");
95
96 expect(received).toEqual(["t", "T"]);
97 expect(composerKeys).toEqual([]);
98});
99
100it("still types other letters into the composer while the launcher is open", async () => {
101 const composerKeys: string[] = [];
102 const received: string[] = [];
103 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
104 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
105
106 await userEvent.keyboard("a");
107
108 expect(composerKeys).toEqual(["a"]);
109 expect(received).toEqual([]);
110});
111
112it("leaves a non-Latin launcher letter to the launcher by its physical key", async () => {
113 const composerKeys: string[] = [];
114 const received: string[] = [];
115 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
116 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
117
118 // Playwright cannot press a key its US layout lacks, so send what a Ukrainian T key sends.
119 const event = new KeyboardEvent("keydown", {
120 key: "\u0435",
121 code: "KeyT",
122 bubbles: true,
123 cancelable: true,
124 });
125 (document.activeElement ?? document.body).dispatchEvent(event);
126
127 expect(composerKeys).toEqual([]);
128 expect(received).toEqual(["\u0435"]);
129});
130
131it.each([
132 { key: "b", code: "KeyN", composer: [], launcher: ["b"] },
133 { key: "x", code: "KeyB", composer: ["x"], launcher: [] },
134 { key: "è", code: "KeyT", composer: ["è"], launcher: [] },
135])("routes $key on $code by the typed letter", async ({ key, code, composer, launcher }) => {
136 const composerKeys: string[] = [];
137 const received: string[] = [];
138 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
139 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
140
141 const event = new KeyboardEvent("keydown", { key, code, bubbles: true, cancelable: true });
142 (document.activeElement ?? document.body).dispatchEvent(event);
143
144 expect(composerKeys).toEqual(composer);
145 expect(received).toEqual(launcher);
146});
147
148const sideChatKeybindings: ResolvedKeybindingsConfig = [
149 ctrl("m", "modelPicker.toggle", true),
150 ctrl("x", "thread.stop", true),
151 // The default find rule, with ctrl for mod so it matches on every platform.
152 ...compileResolvedKeybindingsConfig([
153 { key: "ctrl+f", command: "chat.find", when: "!terminalFocus && !previewFocus" },
154 ]),
155];
156
157// A side chat in the main chat's right panel: no window listeners, only its pane's find and its
158// composer's own chords. Passing `findCloses` opens its find.
159function SideChat(props: {
160 toggles: string[];
161 stops: string[];
162 finds?: string[];
163 findCloses?: string[];
164}) {
165 const [composerElement, setComposerElement] = useState<HTMLDivElement | null>(null);
166 useChatShortcuts({
167 enabled: false,
168 embedded: true,
169 composerElement,
170 keybindings: sideChatKeybindings,
171 scriptKeybindings: [],
172 getShortcutContext: () => ({ ...shortcutContext, previewFocus: isPreviewFocused() }),
173 threadFindActive: props.findCloses !== undefined,
174 composerRef: {
175 current: {
176 toggleModelPicker: () => props.toggles.push("model"),
177 } as Partial<ChatComposerHandle> as ChatComposerHandle,
178 },
179 branchToolbarRef: { current: null },
180 closeThreadFind: () => void props.findCloses?.push("side"),
181 commands: {
182 "thread.stop": () => void props.stops.push("stop"),
183 "chat.find": () => void props.finds?.push("side"),
184 },
185 fallback: () => undefined,
186 });
187 return (
188 <>
189 <div data-preview-panel-mode="inline">
190 <div data-side-chat-pane>
191 <input aria-label="Side chat find" />
192 <div tabIndex={0} aria-label="Side chat timeline">
193 Conversation
194 </div>
195 <div ref={setComposerElement}>
196 <textarea aria-label="Side chat composer" />
197 </div>
198 </div>
199 </div>
200 <textarea aria-label="Main composer" />
201 </>
202 );
203}
204
205it("runs a side chat's composer chords only from its composer, and never thread commands", async () => {
206 const toggles: string[] = [];
207 const stops: string[] = [];
208 await using screen = await render(<SideChat toggles={toggles} stops={stops} />, options);
209
210 await userEvent.click(screen.getByLabelText("Side chat composer"));
211 await userEvent.keyboard("{Control>}{Shift>}MX{/Shift}{/Control}");
212 await userEvent.click(screen.getByLabelText("Main composer"));
213 await userEvent.keyboard("{Control>}{Shift>}M{/Shift}{/Control}");
214
215 expect(toggles).toEqual(["model"]);
216 expect(stops).toEqual([]);
217});
218
219it("opens the side chat's own find for mod+F anywhere in its pane, not the main chat's", async () => {
220 const finds: string[] = [];
221 await using screen = await render(
222 <>
223 <Chat composerKeys={[]} finds={finds} />
224 <SideChat toggles={[]} stops={[]} finds={finds} />
225 </>,
226 options,
227 );
228
229 await userEvent.click(screen.getByLabelText("Side chat composer"));
230 await userEvent.keyboard("{Control>}f{/Control}");
231 await userEvent.click(screen.getByLabelText("Side chat timeline"));
232 await userEvent.keyboard("{Control>}f{/Control}");
233
234 expect(finds).toEqual(["side", "side"]);
235});
236
237it("closes the side chat's find for Escape in its find input and elsewhere in its pane", async () => {
238 const findCloses: string[] = [];
239 await using screen = await render(
240 <SideChat toggles={[]} stops={[]} findCloses={findCloses} />,
241 options,
242 );
243 // Stands in for the narrow right panel sheet, which also closes on an Escape that reaches it.
244 const sheetEscapes: string[] = [];
245 const onSheetKeyDown = (event: KeyboardEvent) => {
246 if (event.key === "Escape") sheetEscapes.push("sheet");
247 };
248 document.addEventListener("keydown", onSheetKeyDown);
249 using _sheet = {
250 [Symbol.dispose]: () => document.removeEventListener("keydown", onSheetKeyDown),
251 };
252
253 await userEvent.click(screen.getByLabelText("Side chat find"));
254 await userEvent.keyboard("{Escape}");
255 await userEvent.click(screen.getByLabelText("Side chat timeline"));
256 await userEvent.keyboard("{Escape}");
257
258 expect(findCloses).toEqual(["side", "side"]);
259 expect(sheetEscapes).toEqual([]);
260});
261
262const ctrlAlt = (key: string, command: KeybindingCommand) => ({
263 command,
264 shortcut: { key, metaKey: false, ctrlKey: true, shiftKey: false, altKey: true, modKey: false },
265});
266
267// The main chat's window listener while focus sits in a side chat pane in its right panel.
268function ChatWithSideChatPane(props: { ran: string[] }) {
269 useChatShortcuts({
270 enabled: true,
271 keybindings: [
272 ctrlAlt("b", "rightPanel.toggle"),
273 ctrlAlt("k", "rightPanel.close"),
274 ctrl("x", "thread.stop", true),
275 ],
276 scriptKeybindings: [],
277 getShortcutContext: () => shortcutContext,
278 threadFindActive: false,
279 composerRef: {
280 current: {
281 insertTextAtEnd: (key: string) => {
282 props.ran.push(`typed ${key}`);
283 return true;
284 },
285 } as Partial<ChatComposerHandle> as ChatComposerHandle,
286 },
287 branchToolbarRef: { current: null },
288 closeThreadFind: () => {},
289 commands: {
290 "rightPanel.toggle": () => void props.ran.push("toggle"),
291 "rightPanel.close": () => void props.ran.push("close"),
292 "thread.stop": () => void props.ran.push("stop"),
293 },
294 fallback: () => undefined,
295 });
296 return (
297 <div data-side-chat-pane>
298 <div role="region" aria-label="Conversation" tabIndex={0}>
299 A side chat message
300 </div>
301 <textarea aria-label="Message Side chat" />
302 </div>
303 );
304}
305
306it("runs right panel commands from inside a side chat pane, but not thread commands", async () => {
307 const ran: string[] = [];
308 await using screen = await render(<ChatWithSideChatPane ran={ran} />, options);
309
310 await userEvent.click(screen.getByLabelText("Message Side chat"));
311 await userEvent.keyboard("{Control>}{Alt>}BK{/Alt}{/Control}");
312 await userEvent.keyboard("{Control>}{Shift>}X{/Shift}{/Control}");
313 await userEvent.click(screen.getByRole("region", { name: "Conversation" }));
314 await userEvent.keyboard("{Control>}{Alt>}B{/Alt}{/Control}");
315 await userEvent.keyboard("q");
316
317 expect(ran).toEqual(["toggle", "close", "toggle"]);
318});
319
320it("leaves keys to a focused video player with controls", async () => {
321 const composerKeys: string[] = [];
322 await using _screen = await render(
323 <>
324 <Chat composerKeys={composerKeys} />
325 <video ref={focusOnMount} controls />
326 </>,
327 options,
328 );
329
330 await userEvent.keyboard(" m");
331 expect(composerKeys).toEqual([]);
332
333 (document.activeElement as HTMLElement).blur();
334 await userEvent.keyboard("a");
335 expect(composerKeys).toEqual(["a"]);
336});