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

useDictationShortcut.browser.test.tsx

262 lines8.9 KB

1import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
2import { createRef, type RefObject } from "react";
3import { expect, it, vi } from "vite-plus/test";
4import { render } from "../../test/render";
5import { useDictationShortcut, type DictationKeyHandlers } from "./useDictationShortcut";
6​
7const settings = vi.hoisted(() => ({ mode: "hold" as "hold" | "auto" | "toggle" }));
8vi.mock("../hooks/useSettings", () => ({ useClientSettings: () => settings.mode }));
9​
10type ShortcutInput = Parameters<typeof useDictationShortcut>[0];
11​
12function Probe({
13 speech,
14 targetRef,
15 subscribeKeys,
16}: {
17 speech: ShortcutInput["speech"];
18 targetRef?: RefObject<HTMLElement | null>;
19 subscribeKeys?: ShortcutInput["subscribeKeys"];
20}) {
21 useDictationShortcut({
22 keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
23 speech,
24 disabled: false,
25 terminalOpen: false,
26 modelPickerOpen: false,
27 ...(targetRef ? { targetRef } : {}),
28 ...(subscribeKeys ? { subscribeKeys, ownsFocus: () => true } : {}),
29 });
30 return null;
32​
33const press = (repeat = false) =>
34 window.dispatchEvent(
35 new KeyboardEvent("keydown", {
36 key: "D",
37 code: "KeyD",
38 ctrlKey: !/Mac/i.test(navigator.platform),
39 metaKey: /Mac/i.test(navigator.platform),
40 shiftKey: true,
41 cancelable: true,
42 repeat,
43 }),
44 );
45​
46function actions(available: boolean, mode: typeof settings.mode = "hold") {
47 settings.mode = mode;
48 return {
49 available,
50 state: { phase: "idle" as const, error: null, errorAction: null },
51 start: vi.fn(async () => {}),
52 stop: vi.fn(async () => {}),
53 cancel: vi.fn(),
54 };
56​
57it("leaves the browser shortcut alone when dictation is off", async () => {
58 const speech = actions(false);
59 await using _screen = await render(<Probe speech={speech} />);
60 expect(press()).toBe(true);
61 expect(speech.start).not.toHaveBeenCalled();
62});
63​
64it("stops on a new press when the OS omitted keyup, but ignores autorepeat", async () => {
65 const speech = actions(true);
66 await using screen = await render(<Probe speech={speech} />);
67 expect(press()).toBe(false);
68 expect(speech.start).toHaveBeenCalledOnce();
69 await screen.rerender(
70 <Probe speech={{ ...speech, state: { ...speech.state, phase: "recording" } }} />,
71 );
72 press(true);
73 expect(speech.stop).not.toHaveBeenCalled();
74 press();
75 expect(speech.stop).toHaveBeenCalledOnce();
76});
77​
78it("finishes a released hold after startup even if the chord was pressed again while preparing", async () => {
79 const speech = actions(true);
80 let finishStart!: () => void;
81 const startup = new Promise<void>((resolve) => {
82 finishStart = resolve;
83 });
84 speech.start.mockReturnValue(startup);
85 await using screen = await render(<Probe speech={speech} />);
86 press();
87 await screen.rerender(
88 <Probe speech={{ ...speech, state: { ...speech.state, phase: "preparing" } }} />,
89 );
90 window.dispatchEvent(new KeyboardEvent("keyup", { code: "KeyD" }));
91 press();
92 window.dispatchEvent(new KeyboardEvent("keyup", { code: "KeyD" }));
93 finishStart();
94 await startup;
95 expect(speech.start).toHaveBeenCalledOnce();
96 expect(speech.stop).toHaveBeenCalledOnce();
97});
98​
99it.each([
100 { mode: "hold", heldMs: 0, stops: 1 },
101 { mode: "auto", heldMs: 300, stops: 1 },
102 { mode: "auto", heldMs: 299, stops: 0 },
103] as const)(
104 "ends a $mode press held $heldMs ms when a chord modifier is released without the letter keyup",
105 async ({ mode, heldMs, stops }) => {
106 const speech = actions(true, mode);
107 using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel");
108 await using _screen = await render(<Probe speech={speech} />);
109 using clock = vi.spyOn(performance, "now").mockReturnValue(0);
110 press();
111 clock.mockReturnValue(heldMs);
112 window.dispatchEvent(new KeyboardEvent("keyup", { key: "Alt", code: "AltLeft" }));
113 await speech.start.mock.results[0]?.value;
114 expect(speech.stop).not.toHaveBeenCalled();
115 window.dispatchEvent(new KeyboardEvent("keyup", { key: "Meta", code: "MetaLeft" }));
116 await speech.start.mock.results[0]?.value;
117 expect(speech.stop).toHaveBeenCalledTimes(stops);
118 },
119);
120​
121const escape = () =>
122 new KeyboardEvent("keydown", { key: "Escape", code: "Escape", bubbles: true, cancelable: true });
123​
124const recording = () => ({
125 ...actions(true),
126 state: { phase: "recording" as const, error: null, errorAction: null },
127});
128​
129it("lets Escape in another dictation editor reach that editor instead of canceling the recording", async () => {
130 const speech = recording();
131 const commentRef = createRef<HTMLTextAreaElement>();
132 const editorEscape = vi.fn();
133 await using screen = await render(
134 <>
135 <Probe speech={speech} />
136 <Probe speech={actions(true)} targetRef={commentRef} />
137 <div
138 role="dialog"
139 aria-label="Edit citation comment"
140 onKeyDown={(event) => {
141 if (event.key === "Escape") editorEscape();
142 }}
143 >
144 <textarea aria-label="Comment" ref={commentRef} />
145 <button type="button">Cancel</button>
146 </div>
147 </>,
148 );
149 for (const control of [
150 screen.getByRole("textbox", { name: "Comment" }).element(),
151 screen.getByRole("button", { name: "Cancel" }).element(),
152 ]) {
153 if (!(control instanceof HTMLElement)) throw new Error("expected a comment editor control");
154 control.focus();
155 control.dispatchEvent(escape());
156 }
157 expect(speech.cancel).not.toHaveBeenCalled();
158 expect(editorEscape).toHaveBeenCalledTimes(2);
159});
160​
161it("lets Escape in another editor of the recording editor's dialog reach that editor", async () => {
162 const speech = recording();
163 const replyRef = createRef<HTMLTextAreaElement>();
164 const otherReplyRef = createRef<HTMLTextAreaElement>();
165 await using screen = await render(
166 <>
167 <Probe speech={speech} targetRef={replyRef} />
168 <Probe speech={actions(true)} targetRef={otherReplyRef} />
169 <div role="dialog" aria-label="Pull request">
170 <textarea aria-label="Reply A" ref={replyRef} />
171 <textarea aria-label="Reply B" ref={otherReplyRef} />
172 </div>
173 </>,
174 );
175 const other = screen.getByRole("textbox", { name: "Reply B" }).element();
176 if (!(other instanceof HTMLElement)) throw new Error("expected a reply editor");
177 other.focus();
178 other.dispatchEvent(escape());
179 expect(speech.cancel).not.toHaveBeenCalled();
180});
181​
182it("lets Escape close a modal opened over the recording before canceling it", async () => {
183 const speech = recording();
184 const closeImage = vi.fn();
185 await using screen = await render(
186 <>
187 <Probe speech={speech} />
188 <div
189 role="dialog"
190 aria-modal="true"
191 aria-label="Expanded image"
192 onKeyDown={(event) => {
193 if (event.key === "Escape") closeImage();
194 }}
195 >
196 <button type="button">Close</button>
197 </div>
198 </>,
199 );
200 const close = screen.getByRole("button", { name: "Close" }).element();
201 if (!(close instanceof HTMLElement)) throw new Error("expected the image dialog's button");
202 close.focus();
203 close.dispatchEvent(escape());
204 expect(speech.cancel).not.toHaveBeenCalled();
205 expect(closeImage).toHaveBeenCalledTimes(1);
206});
207​
208it("cancels the recording on Escape outside other shown dictation editors", async () => {
209 const speech = recording();
210 const reviewRef = createRef<HTMLTextAreaElement>();
211 const commentRef = createRef<HTMLTextAreaElement>();
212 await using screen = await render(
213 <>
214 <Probe speech={speech} targetRef={reviewRef} />
215 <Probe speech={actions(true)} targetRef={commentRef} />
216 <input aria-label="Search" />
217 <div role="dialog" aria-label="Pull request">
218 <textarea aria-label="Review" ref={reviewRef} />
219 <div hidden>
220 <textarea aria-label="Comment" ref={commentRef} />
221 </div>
222 <button type="button">Submit</button>
223 </div>
224 </>,
225 );
226 for (const control of [
227 screen.getByRole("textbox", { name: "Search" }).element(),
228 screen.getByRole("button", { name: "Submit" }).element(),
229 ]) {
230 if (!(control instanceof HTMLElement)) throw new Error("expected a focusable control");
231 control.focus();
232 control.dispatchEvent(escape());
233 }
234 expect(speech.cancel).toHaveBeenCalledTimes(2);
235});
236​
237it.each([
238 ["another editor is recording", false],
239 ["the preview itself is recording", true],
240])(
241 "routes Escape relayed from the preview guest to the preview when %s",
242 async (_name, previewRecords) => {
243 const composer = previewRecords ? actions(true) : recording();
244 const preview = previewRecords ? recording() : actions(true);
245 let relayed: DictationKeyHandlers | undefined;
246 await using _screen = await render(
247 <>
248 <Probe speech={composer} />
249 <Probe
250 speech={preview}
251 subscribeKeys={(handlers) => {
252 relayed = handlers;
253 return () => {};
254 }}
255 />
256 </>,
257 );
258 relayed?.keydown(escape());
259 expect(composer.cancel).not.toHaveBeenCalled();
260 expect(preview.cancel).toHaveBeenCalledTimes(previewRecords ? 1 : 0);
261 },
262);