Open History to see the last commit
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);
14}
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;
61}
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);
90}
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 (event.defaultPrevented || isCommandPaletteOpen()) return;
136 if (
137 event.key === "Escape" &&
138 (pressed.current !== null ||
139 (speech.state.phase !== "idle" && speech.state.phase !== "error")) &&
140 !inOtherShortcutTarget(id.current, event)
141 ) {
142 event.preventDefault();
143 event.stopImmediatePropagation();
144 pressed.current = null;
145 generation.current += 1;
146 speech.cancel();
147 return;
148 }
149 const { keybindings, terminalOpen, modelPickerOpen, disabled } = current.current;
150 const previewFocus = current.current.previewFocus ?? false;
151 const command = resolveShortcutCommand(event, keybindings, {
152 context: {
153 terminalFocus: getTerminalFocusOwner() !== null,
154 terminalOpen,
155 modelPickerOpen,
156 previewFocus,
157 previewOpen: previewFocus,
158 ...(previewFocus ? { editableFocus: true } : {}),
159 },
160 });
161 if (command !== "composer.dictation") return;
162 const canStart = speech.state.phase === "idle" || speech.state.phase === "error";
163 if (canStart && (!speech.available || disabled)) return;
164 event.preventDefault();
165 event.stopPropagation();
166 if (event.repeat || (!canStart && speech.state.phase !== "recording")) return;
167 // macOS may omit the previous non-modifier keyup while Command is held.
168 pressed.current = null;
169 generation.current += 1;
170 if (speech.state.phase === "recording") {
171 void speech.stop();
172 return;
173 }
174 pressed.current = {
175 generation: generation.current,
176 code: event.code || event.key,
177 modifiers: ["Alt", "Control", "Meta", "Shift"].filter((key) => event.getModifierState(key)),
178 startedAt: performance.now(),
179 mode,
180 starting: speech.start(),
181 };
182 };
183 const onBlur = () => finish(null);
184 const relay = (event: KeyboardEvent) => {
185 relayedFrom.set(event, id.current);
186 window.dispatchEvent(event);
187 };
188 const unsubscribe = subscribeKeys?.({
189 keydown: relay,
190 keyup: relay,
191 blur: onBlur,
192 });
193 window.addEventListener("keydown", onKeyDown, true);
194 window.addEventListener("keyup", finish, true);
195 window.addEventListener("blur", onBlur);
196 return () => {
197 disposed = true;
198 pressed.current = null;
199 shortcutTargets.delete(id.current);
200 unsubscribe?.();
201 window.removeEventListener("keydown", onKeyDown, true);
202 window.removeEventListener("keyup", finish, true);
203 window.removeEventListener("blur", onBlur);
204 };
205 }, [mode, subscribeKeys]);
206
207 return shortcutLabelForCommand(input.keybindings, "composer.dictation", {
208 context: { terminalFocus: false, terminalOpen: input.terminalOpen },
209 });
210}