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 { surfaceShortcutKey } from "~/lib/surfaceShortcutKey";
7import { render } from "../../../test/render";
8import type { ChatComposerHandle } from "./ChatComposer";
9import { useChatShortcuts } from "./useChatShortcuts";
10
11const shortcutContext = {
12 terminalFocus: false,
13 terminalOpen: false,
14 previewFocus: false,
15 previewOpen: false,
16 isWeb: true,
17 isDesktop: false,
18 modelPickerOpen: false,
19};
20
21const focusOnMount = (element: HTMLElement | null) => element?.focus();
22
23// Stands in for the right panel's launcher, which needs the whole app around it. Like the
24// real one it takes focus, advertises its letters in `data-surface-launcher-keys`, and
25// claims one from its own window capture listener unless the key was already handled.
26function Launcher(props: { keys: string; received: string[] }) {
27 useEffect(() => {
28 const claim = (event: KeyboardEvent) => {
29 if (event.defaultPrevented) return;
30 const key = surfaceShortcutKey(event);
31 if (key === null || !props.keys.toLowerCase().includes(key)) return;
32 event.preventDefault();
33 props.received.push(event.key);
34 };
35 window.addEventListener("keydown", claim, true);
36 return () => window.removeEventListener("keydown", claim, true);
37 }, [props.keys, props.received]);
38 return (
39 <div
40 ref={focusOnMount}
41 tabIndex={0}
42 aria-label="Open a surface"
43 data-surface-launcher-keys={props.keys}
44 />
45 );
46}
47
48// The chat's shortcut listener registers when the chat mounts, so a launcher that opens
49// later registers after it. Tests mount the chat first and add the launcher by rerendering.
50function Chat(props: { composerKeys: string[]; launcher?: { keys: string; received: string[] } }) {
51 useChatShortcuts({
52 enabled: true,
53 keybindings: [],
54 scriptKeybindings: [],
55 getShortcutContext: () => shortcutContext,
56 threadFindActive: false,
57 // Type-to-focus only calls insertTextAtEnd, so the stand-in composer implements just that.
58 composerRef: {
59 current: {
60 insertTextAtEnd: (key: string) => {
61 props.composerKeys.push(key);
62 return true;
63 },
64 } as Partial<ChatComposerHandle> as ChatComposerHandle,
65 },
66 branchToolbarRef: { current: null },
67 closeThreadFind: () => {},
68 commands: {},
69 fallback: () => undefined,
70 });
71 return props.launcher ? <Launcher {...props.launcher} /> : null;
72}
73
74// router: false because the chat shortcuts and the launcher stand-in never navigate.
75const options = { router: false } as const;
76
77it("leaves the launcher's letters to the launcher, in either case", async () => {
78 const composerKeys: string[] = [];
79 const received: string[] = [];
80 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
81 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
82
83 await userEvent.keyboard("tT");
84
85 expect(received).toEqual(["t", "T"]);
86 expect(composerKeys).toEqual([]);
87});
88
89it("still types other letters into the composer while the launcher is open", async () => {
90 const composerKeys: string[] = [];
91 const received: string[] = [];
92 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
93 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
94
95 await userEvent.keyboard("a");
96
97 expect(composerKeys).toEqual(["a"]);
98 expect(received).toEqual([]);
99});
100
101it("leaves a non-Latin launcher letter to the launcher by its physical key", async () => {
102 const composerKeys: string[] = [];
103 const received: string[] = [];
104 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
105 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
106
107 // Playwright cannot press a key its US layout lacks, so send what a Ukrainian T key sends.
108 const event = new KeyboardEvent("keydown", {
109 key: "\u0435",
110 code: "KeyT",
111 bubbles: true,
112 cancelable: true,
113 });
114 (document.activeElement ?? document.body).dispatchEvent(event);
115
116 expect(composerKeys).toEqual([]);
117 expect(received).toEqual(["\u0435"]);
118});
119
120it.each([
121 { key: "b", code: "KeyN", composer: [], launcher: ["b"] },
122 { key: "x", code: "KeyB", composer: ["x"], launcher: [] },
123 { key: "è", code: "KeyT", composer: ["è"], launcher: [] },
124])("routes $key on $code by the typed letter", async ({ key, code, composer, launcher }) => {
125 const composerKeys: string[] = [];
126 const received: string[] = [];
127 await using screen = await render(<Chat composerKeys={composerKeys} />, options);
128 await screen.rerender(<Chat composerKeys={composerKeys} launcher={{ keys: "BT", received }} />);
129
130 const event = new KeyboardEvent("keydown", { key, code, bubbles: true, cancelable: true });
131 (document.activeElement ?? document.body).dispatchEvent(event);
132
133 expect(composerKeys).toEqual(composer);
134 expect(received).toEqual(launcher);
135});
136
137const ctrlShift = (key: string, command: KeybindingCommand) => ({
138 command,
139 shortcut: { key, metaKey: false, ctrlKey: true, shiftKey: true, altKey: false, modKey: false },
140});
141const sideChatKeybindings: ResolvedKeybindingsConfig = [
142 ctrlShift("m", "modelPicker.toggle"),
143 ctrlShift("x", "thread.stop"),
144];
145
146// A side chat in the main chat's panel: no window listeners, only its composer's own chords.
147function SideChat(props: { toggles: string[]; stops: string[] }) {
148 const [composerElement, setComposerElement] = useState<HTMLDivElement | null>(null);
149 useChatShortcuts({
150 enabled: false,
151 embedded: true,
152 composerElement,
153 keybindings: sideChatKeybindings,
154 scriptKeybindings: [],
155 getShortcutContext: () => shortcutContext,
156 threadFindActive: false,
157 composerRef: {
158 current: {
159 toggleModelPicker: () => props.toggles.push("model"),
160 } as Partial<ChatComposerHandle> as ChatComposerHandle,
161 },
162 branchToolbarRef: { current: null },
163 closeThreadFind: () => {},
164 commands: { "thread.stop": () => void props.stops.push("stop") },
165 fallback: () => undefined,
166 });
167 return (
168 <>
169 <div ref={setComposerElement}>
170 <textarea aria-label="Side chat composer" />
171 </div>
172 <textarea aria-label="Main composer" />
173 </>
174 );
175}
176
177it("runs a side chat's composer chords only from its composer, and never thread commands", async () => {
178 const toggles: string[] = [];
179 const stops: string[] = [];
180 await using screen = await render(<SideChat toggles={toggles} stops={stops} />, options);
181
182 await userEvent.click(screen.getByLabelText("Side chat composer"));
183 await userEvent.keyboard("{Control>}{Shift>}MX{/Shift}{/Control}");
184 await userEvent.click(screen.getByLabelText("Main composer"));
185 await userEvent.keyboard("{Control>}{Shift>}M{/Shift}{/Control}");
186
187 expect(toggles).toEqual(["model"]);
188 expect(stops).toEqual([]);
189});