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

useDictationShortcut.browser.test.tsx

212 lines7.0 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​
7vi.mock("../hooks/useSettings", () => ({ useClientSettings: () => "hold" }));
8​
9type ShortcutInput = Parameters<typeof useDictationShortcut>[0];
10​
11function Probe({
12 speech,
13 targetRef,
14 subscribeKeys,
15}: {
16 speech: ShortcutInput["speech"];
17 targetRef?: RefObject<HTMLElement | null>;
18 subscribeKeys?: ShortcutInput["subscribeKeys"];
19}) {
20 useDictationShortcut({
21 keybindings: DEFAULT_RESOLVED_KEYBINDINGS,
22 speech,
23 disabled: false,
24 terminalOpen: false,
25 modelPickerOpen: false,
26 ...(targetRef ? { targetRef } : {}),
27 ...(subscribeKeys ? { subscribeKeys, ownsFocus: () => true } : {}),
28 });
29 return null;
31​
32const press = (repeat = false) =>
33 window.dispatchEvent(
34 new KeyboardEvent("keydown", {
35 key: "D",
36 code: "KeyD",
37 ctrlKey: !/Mac/i.test(navigator.platform),
38 metaKey: /Mac/i.test(navigator.platform),
39 shiftKey: true,
40 cancelable: true,
41 repeat,
42 }),
43 );
44​
45function actions(available: boolean) {
46 return {
47 available,
48 state: { phase: "idle" as const, error: null, errorAction: null },
49 start: vi.fn(async () => {}),
50 stop: vi.fn(async () => {}),
51 cancel: vi.fn(),
52 };
54​
55it("leaves the browser shortcut alone when dictation is off", async () => {
56 const speech = actions(false);
57 await using _screen = await render(<Probe speech={speech} />);
58 expect(press()).toBe(true);
59 expect(speech.start).not.toHaveBeenCalled();
60});
61​
62it("stops on a new press when the OS omitted keyup, but ignores autorepeat", async () => {
63 const speech = actions(true);
64 await using screen = await render(<Probe speech={speech} />);
65 expect(press()).toBe(false);
66 expect(speech.start).toHaveBeenCalledOnce();
67 await screen.rerender(
68 <Probe speech={{ ...speech, state: { ...speech.state, phase: "recording" } }} />,
69 );
70 press(true);
71 expect(speech.stop).not.toHaveBeenCalled();
72 press();
73 expect(speech.stop).toHaveBeenCalledOnce();
74});
75​
76it("finishes a released hold after startup even if the chord was pressed again while preparing", async () => {
77 const speech = actions(true);
78 let finishStart!: () => void;
79 const startup = new Promise<void>((resolve) => {
80 finishStart = resolve;
81 });
82 speech.start.mockReturnValue(startup);
83 await using screen = await render(<Probe speech={speech} />);
84 press();
85 await screen.rerender(
86 <Probe speech={{ ...speech, state: { ...speech.state, phase: "preparing" } }} />,
87 );
88 window.dispatchEvent(new KeyboardEvent("keyup", { code: "KeyD" }));
89 press();
90 window.dispatchEvent(new KeyboardEvent("keyup", { code: "KeyD" }));
91 finishStart();
92 await startup;
93 expect(speech.start).toHaveBeenCalledOnce();
94 expect(speech.stop).toHaveBeenCalledOnce();
95});
96​
97const escape = () =>
98 new KeyboardEvent("keydown", { key: "Escape", code: "Escape", bubbles: true, cancelable: true });
99​
100const recording = () => ({
101 ...actions(true),
102 state: { phase: "recording" as const, error: null, errorAction: null },
103});
104​
105it("lets Escape in another dictation editor reach that editor instead of canceling the recording", async () => {
106 const speech = recording();
107 const commentRef = createRef<HTMLTextAreaElement>();
108 const editorEscape = vi.fn();
109 await using screen = await render(
110 <>
111 <Probe speech={speech} />
112 <Probe speech={actions(true)} targetRef={commentRef} />
113 <div
114 role="dialog"
115 aria-label="Edit citation comment"
116 onKeyDown={(event) => {
117 if (event.key === "Escape") editorEscape();
118 }}
119 >
120 <textarea aria-label="Comment" ref={commentRef} />
121 <button type="button">Cancel</button>
122 </div>
123 </>,
124 );
125 for (const control of [
126 screen.getByRole("textbox", { name: "Comment" }).element(),
127 screen.getByRole("button", { name: "Cancel" }).element(),
128 ]) {
129 if (!(control instanceof HTMLElement)) throw new Error("expected a comment editor control");
130 control.focus();
131 control.dispatchEvent(escape());
132 }
133 expect(speech.cancel).not.toHaveBeenCalled();
134 expect(editorEscape).toHaveBeenCalledTimes(2);
135});
136​
137it("lets Escape in another editor of the recording editor's dialog reach that editor", async () => {
138 const speech = recording();
139 const replyRef = createRef<HTMLTextAreaElement>();
140 const otherReplyRef = createRef<HTMLTextAreaElement>();
141 await using screen = await render(
142 <>
143 <Probe speech={speech} targetRef={replyRef} />
144 <Probe speech={actions(true)} targetRef={otherReplyRef} />
145 <div role="dialog" aria-label="Pull request">
146 <textarea aria-label="Reply A" ref={replyRef} />
147 <textarea aria-label="Reply B" ref={otherReplyRef} />
148 </div>
149 </>,
150 );
151 const other = screen.getByRole("textbox", { name: "Reply B" }).element();
152 if (!(other instanceof HTMLElement)) throw new Error("expected a reply editor");
153 other.focus();
154 other.dispatchEvent(escape());
155 expect(speech.cancel).not.toHaveBeenCalled();
156});
157​
158it("cancels the recording on Escape outside other shown dictation editors", async () => {
159 const speech = recording();
160 const reviewRef = createRef<HTMLTextAreaElement>();
161 const commentRef = createRef<HTMLTextAreaElement>();
162 await using screen = await render(
163 <>
164 <Probe speech={speech} targetRef={reviewRef} />
165 <Probe speech={actions(true)} targetRef={commentRef} />
166 <input aria-label="Search" />
167 <div role="dialog" aria-label="Pull request">
168 <textarea aria-label="Review" ref={reviewRef} />
169 <div hidden>
170 <textarea aria-label="Comment" ref={commentRef} />
171 </div>
172 <button type="button">Submit</button>
173 </div>
174 </>,
175 );
176 for (const control of [
177 screen.getByRole("textbox", { name: "Search" }).element(),
178 screen.getByRole("button", { name: "Submit" }).element(),
179 ]) {
180 if (!(control instanceof HTMLElement)) throw new Error("expected a focusable control");
181 control.focus();
182 control.dispatchEvent(escape());
183 }
184 expect(speech.cancel).toHaveBeenCalledTimes(2);
185});
186​
187it.each([
188 ["another editor is recording", false],
189 ["the preview itself is recording", true],
190])(
191 "routes Escape relayed from the preview guest to the preview when %s",
192 async (_name, previewRecords) => {
193 const composer = previewRecords ? actions(true) : recording();
194 const preview = previewRecords ? recording() : actions(true);
195 let relayed: DictationKeyHandlers | undefined;
196 await using _screen = await render(
197 <>
198 <Probe speech={composer} />
199 <Probe
200 speech={preview}
201 subscribeKeys={(handlers) => {
202 relayed = handlers;
203 return () => {};
204 }}
205 />
206 </>,
207 );
208 relayed?.keydown(escape());
209 expect(composer.cancel).not.toHaveBeenCalled();
210 expect(preview.cancel).toHaveBeenCalledTimes(previewRecords ? 1 : 0);
211 },
212);