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

useDictationShortcut.ts

215 lines8.3 KB

1import type { VoiceInputState } from "@t3tools/client-runtime/voice-input";
2import type { ResolvedKeybindingsConfig } from "@t3tools/contracts";
3import { useEffect, useRef, type RefObject } from "react";
4​
5import { isCommandPaletteOpen } from "../commandPaletteBus";
6import { useClientSettings } from "../hooks/useSettings";
7import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
8import { getTerminalFocusOwner } from "../lib/terminalFocus";
9​
10const HOLD_THRESHOLD_MS = 300;
11​
12function shouldFinishDictationOnRelease(mode: "auto" | "hold" | "toggle", elapsedMs: number) {
13 return mode === "hold" || (mode === "auto" && elapsedMs >= HOLD_THRESHOLD_MS);
15​
16type SpeechActions = {
17 available: boolean;
18 state: VoiceInputState;
19 start(): Promise<void>;
20 stop(): Promise<void>;
21 cancel(): void;
22};
23​
24export type DictationKeyHandlers = {
25 keydown(event: KeyboardEvent): void;
26 keyup(event: KeyboardEvent): void;
27 blur(): void;
28};
29​
30type ShortcutInput = {
31 keybindings: ResolvedKeybindingsConfig;
32 speech: SpeechActions;
33 disabled: boolean;
34 terminalOpen: boolean;
35 modelPickerOpen: boolean;
36 /** Resolve the chord as if the preview had focus; the keys arrive relayed from its guest. */
37 previewFocus?: boolean;
38 /** When set, the chord targets this editor only while it has focus. */
39 targetRef?: RefObject<HTMLElement | null>;
40 /** An editor outside this document reports whether it holds the keyboard. */
41 ownsFocus?: () => boolean;
42 /** Receives handlers that replay keys an outside editor relayed, as if typed here. */
43 subscribeKeys?: (handlers: DictationKeyHandlers) => () => void;
44};
45​
46// Several editors can bind the chord; the busy one, then the focused one, then the untargeted one wins.
47const shortcutTargets = new Map<symbol, () => ShortcutInput>();
48​
49function ownsShortcut(id: symbol) {
50 const entries = [...shortcutTargets];
51 const busy = entries.find(([, read]) => {
52 const phase = read().speech.state.phase;
53 return phase !== "idle" && phase !== "error";
54 });
55 if (busy) return busy[0] === id;
56 const focused =
57 entries.find(([, read]) => read().ownsFocus?.()) ??
58 entries.find(([, read]) => read().targetRef?.current?.contains(document.activeElement));
59 if (focused) return focused[0] === id;
60 return entries.find(([, read]) => !read().targetRef && !read().ownsFocus)?.[0] === id;
62​
63const targetScope = (field: HTMLElement | null | undefined) =>
64 field?.closest('[role="dialog"]') ?? field;
65​
66// Keys an outside editor (the preview guest) relays arrive on window, so remember their editor.
67const relayedFrom = new WeakMap<Event, symbol>();
68​
69// Escape inside another shown dictation editor, or the dialog hosting it, belongs to that editor;
70// Escape inside any other dialog belongs to that dialog, so it closes before dictation cancels.
71// The editor itself is checked before dialogs, since one dialog can host several editors.
72function inOtherShortcutTarget(id: symbol, event: Event) {
73 const source = relayedFrom.get(event);
74 if (source) return source !== id;
75 const target = event.target;
76 if (!(target instanceof Node)) return false;
77 const own = shortcutTargets.get(id)?.().targetRef?.current;
78 const others = [...shortcutTargets]
79 .filter(([other]) => other !== id)
80 .map(([, read]) => read().targetRef?.current)
81 .filter((field): field is HTMLElement => !!field?.getClientRects().length);
82 for (const scope of [(field?: HTMLElement | null) => field, targetScope]) {
83 if (scope(own)?.contains(target)) return false;
84 if (others.some((field) => scope(field)?.contains(target))) return true;
85 }
86 const dialog = (target instanceof Element ? target : target.parentElement)?.closest(
87 '[role="dialog"]',
88 );
89 return !!dialog && !dialog.contains(own ?? null);
91​
92export function useDictationShortcut(input: ShortcutInput) {
93 const id = useRef(Symbol("dictation-target"));
94 const subscribeKeys = input.subscribeKeys;
95 const mode = useClientSettings((settings) => settings.voiceShortcutMode);
96 const current = useRef(input);
97 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed actions to the window keyboard listener and shortcut registry
98 useEffect(() => {
99 current.current = input;
100 });
101 const generation = useRef(0);
102 const pressed = useRef<{
103 generation: number;
104 code: string;
105 modifiers: string[];
106 startedAt: number;
107 mode: typeof mode;
108 starting: Promise<void>;
109 } | null>(null);
110​
111 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- owns the window keyboard listeners and dictation target registry entry
112 useEffect(() => {
113 if (typeof window === "undefined") return;
114 let disposed = false;
115 shortcutTargets.set(id.current, () => current.current);
116 const finish = (event: KeyboardEvent | null) => {
117 const press = pressed.current;
118 if (!press) return;
119 // macOS can omit the letter keyup while Command is held; releasing a chord modifier ends it too.
120 if (event && (event.code || event.key) !== press.code && !press.modifiers.includes(event.key))
121 return;
122 pressed.current = null;
123 if (shouldFinishDictationOnRelease(press.mode, performance.now() - press.startedAt)) {
124 void press.starting.then(() => {
125 if (!disposed && generation.current === press.generation)
126 return current.current.speech.stop();
127 });
128 }
129 };
130​
131 const onKeyDown = (event: KeyboardEvent) => {
132 if (!ownsShortcut(id.current)) return;
133 if (event.isComposing || event.keyCode === 229) return;
134 const { speech } = current.current;
135 if (
136 event.defaultPrevented ||
137 isCommandPaletteOpen() ||
138 (event.target instanceof Element && event.target.closest("[data-keybinding-capture]"))
139 )
140 return;
141 if (
142 event.key === "Escape" &&
143 (pressed.current !== null ||
144 (speech.state.phase !== "idle" && speech.state.phase !== "error")) &&
145 !inOtherShortcutTarget(id.current, event)
146 ) {
147 event.preventDefault();
148 event.stopImmediatePropagation();
149 pressed.current = null;
150 generation.current += 1;
151 speech.cancel();
152 return;
153 }
154 const { keybindings, terminalOpen, modelPickerOpen, disabled } = current.current;
155 const previewFocus = current.current.previewFocus ?? false;
156 const command = resolveShortcutCommand(event, keybindings, {
157 context: {
158 terminalFocus: getTerminalFocusOwner() !== null,
159 terminalOpen,
160 modelPickerOpen,
161 previewFocus,
162 previewOpen: previewFocus,
163 ...(previewFocus ? { editableFocus: true } : {}),
164 },
165 });
166 if (command !== "composer.dictation") return;
167 const canStart = speech.state.phase === "idle" || speech.state.phase === "error";
168 if (canStart && (!speech.available || disabled)) return;
169 event.preventDefault();
170 event.stopPropagation();
171 if (event.repeat || (!canStart && speech.state.phase !== "recording")) return;
172 // macOS may omit the previous non-modifier keyup while Command is held.
173 pressed.current = null;
174 generation.current += 1;
175 if (speech.state.phase === "recording") {
176 void speech.stop();
177 return;
178 }
179 pressed.current = {
180 generation: generation.current,
181 code: event.code || event.key,
182 modifiers: ["Alt", "Control", "Meta", "Shift"].filter((key) => event.getModifierState(key)),
183 startedAt: performance.now(),
184 mode,
185 starting: speech.start(),
186 };
187 };
188 const onBlur = () => finish(null);
189 const relay = (event: KeyboardEvent) => {
190 relayedFrom.set(event, id.current);
191 window.dispatchEvent(event);
192 };
193 const unsubscribe = subscribeKeys?.({
194 keydown: relay,
195 keyup: relay,
196 blur: onBlur,
197 });
198 window.addEventListener("keydown", onKeyDown, true);
199 window.addEventListener("keyup", finish, true);
200 window.addEventListener("blur", onBlur);
201 return () => {
202 disposed = true;
203 pressed.current = null;
204 shortcutTargets.delete(id.current);
205 unsubscribe?.();
206 window.removeEventListener("keydown", onKeyDown, true);
207 window.removeEventListener("keyup", finish, true);
208 window.removeEventListener("blur", onBlur);
209 };
210 }, [mode, subscribeKeys]);
211​
212 return shortcutLabelForCommand(input.keybindings, "composer.dictation", {
213 context: { terminalFocus: false, terminalOpen: input.terminalOpen },
214 });