@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 247 lines 8.9 KB
Raw
1 import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts";
2 import { useEffect, useState } from "react";
3 import { expect, it } from "vite-plus/test";
4 import { userEvent } from "vite-plus/test/browser";
5
6 import { surfaceShortcutKey } from "~/lib/surfaceShortcutKey";
7 import { render } from "../../../test/render";
8 import type { ChatComposerHandle } from "./ChatComposer";
9 import { useChatShortcuts } from "./useChatShortcuts";
10
11 const shortcutContext = {
12 terminalFocus: false,
13 terminalOpen: false,
14 previewFocus: false,
15 previewOpen: false,
16 isWeb: true,
17 isDesktop: false,
18 modelPickerOpen: false,
19 };
20
21 const 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.
26 function 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.
50 function 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.
75 const options = { router: false } as const;
76
77 it("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
89 it("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
101 it("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
120 it.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
137 const ctrlShift = (key: string, command: KeybindingCommand) => ({
138 command,
139 shortcut: { key, metaKey: false, ctrlKey: true, shiftKey: true, altKey: false, modKey: false },
140 });
141 const 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.
147 function 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
177 it("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 });
190
191 const ctrlAlt = (key: string, command: KeybindingCommand) => ({
192 command,
193 shortcut: { key, metaKey: false, ctrlKey: true, shiftKey: false, altKey: true, modKey: false },
194 });
195
196 // The main chat's window listener while focus sits in a side chat pane in its right panel.
197 function ChatWithSideChatPane(props: { ran: string[] }) {
198 useChatShortcuts({
199 enabled: true,
200 keybindings: [
201 ctrlAlt("b", "rightPanel.toggle"),
202 ctrlAlt("k", "rightPanel.close"),
203 ctrlShift("x", "thread.stop"),
204 ],
205 scriptKeybindings: [],
206 getShortcutContext: () => shortcutContext,
207 threadFindActive: false,
208 composerRef: {
209 current: {
210 insertTextAtEnd: (key: string) => {
211 props.ran.push(`typed ${key}`);
212 return true;
213 },
214 } as Partial<ChatComposerHandle> as ChatComposerHandle,
215 },
216 branchToolbarRef: { current: null },
217 closeThreadFind: () => {},
218 commands: {
219 "rightPanel.toggle": () => void props.ran.push("toggle"),
220 "rightPanel.close": () => void props.ran.push("close"),
221 "thread.stop": () => void props.ran.push("stop"),
222 },
223 fallback: () => undefined,
224 });
225 return (
226 <div data-side-chat-pane>
227 <div role="region" aria-label="Conversation" tabIndex={0}>
228 A side chat message
229 </div>
230 <textarea aria-label="Message Side chat" />
231 </div>
232 );
233 }
234
235 it("runs right panel commands from inside a side chat pane, but not thread commands", async () => {
236 const ran: string[] = [];
237 await using screen = await render(<ChatWithSideChatPane ran={ran} />, options);
238
239 await userEvent.click(screen.getByLabelText("Message Side chat"));
240 await userEvent.keyboard("{Control>}{Alt>}BK{/Alt}{/Control}");
241 await userEvent.keyboard("{Control>}{Shift>}X{/Shift}{/Control}");
242 await userEvent.click(screen.getByRole("region", { name: "Conversation" }));
243 await userEvent.keyboard("{Control>}{Alt>}B{/Alt}{/Control}");
244 await userEvent.keyboard("q");
245
246 expect(ran).toEqual(["toggle", "close", "toggle"]);
247 });