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

useDictationShortcut.ts

201 lines7.7 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// The editor itself is checked before dialogs, since one dialog can host several editors.
71function inOtherShortcutTarget(id: symbol, event: Event) {
72 const source = relayedFrom.get(event);
73 if (source) return source !== id;
74 const target = event.target;
75 if (!(target instanceof Node)) return false;
76 const own = shortcutTargets.get(id)?.().targetRef?.current;
77 const others = [...shortcutTargets]
78 .filter(([other]) => other !== id)
79 .map(([, read]) => read().targetRef?.current)
80 .filter((field): field is HTMLElement => !!field?.getClientRects().length);
81 for (const scope of [(field?: HTMLElement | null) => field, targetScope]) {
82 if (scope(own)?.contains(target)) return false;
83 if (others.some((field) => scope(field)?.contains(target))) return true;
84 }
85 return false;
87​
88export function useDictationShortcut(input: ShortcutInput) {
89 const id = useRef(Symbol("dictation-target"));
90 const subscribeKeys = input.subscribeKeys;
91 const mode = useClientSettings((settings) => settings.voiceShortcutMode);
92 const current = useRef(input);
93 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed actions to the window keyboard listener and shortcut registry
94 useEffect(() => {
95 current.current = input;
96 });
97 const generation = useRef(0);
98 const pressed = useRef<{
99 generation: number;
100 code: string;
101 startedAt: number;
102 mode: typeof mode;
103 starting: Promise<void>;
104 } | null>(null);
105​
106 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- owns the window keyboard listeners and dictation target registry entry
107 useEffect(() => {
108 if (typeof window === "undefined") return;
109 let disposed = false;
110 shortcutTargets.set(id.current, () => current.current);
111 const finish = (event: KeyboardEvent | null) => {
112 const press = pressed.current;
113 if (!press || (event && (event.code || event.key) !== press.code)) return;
114 pressed.current = null;
115 if (shouldFinishDictationOnRelease(press.mode, performance.now() - press.startedAt)) {
116 void press.starting.then(() => {
117 if (!disposed && generation.current === press.generation)
118 return current.current.speech.stop();
119 });
120 }
121 };
122​
123 const onKeyDown = (event: KeyboardEvent) => {
124 if (!ownsShortcut(id.current)) return;
125 if (event.isComposing || event.keyCode === 229) return;
126 const { speech } = current.current;
127 if (event.defaultPrevented || isCommandPaletteOpen()) return;
128 if (
129 event.key === "Escape" &&
130 (pressed.current !== null ||
131 (speech.state.phase !== "idle" && speech.state.phase !== "error")) &&
132 !inOtherShortcutTarget(id.current, event)
133 ) {
134 event.preventDefault();
135 event.stopImmediatePropagation();
136 pressed.current = null;
137 generation.current += 1;
138 speech.cancel();
139 return;
140 }
141 const { keybindings, terminalOpen, modelPickerOpen, disabled } = current.current;
142 const previewFocus = current.current.previewFocus ?? false;
143 const command = resolveShortcutCommand(event, keybindings, {
144 context: {
145 terminalFocus: getTerminalFocusOwner() !== null,
146 terminalOpen,
147 modelPickerOpen,
148 previewFocus,
149 previewOpen: previewFocus,
150 ...(previewFocus ? { editableFocus: true } : {}),
151 },
152 });
153 if (command !== "composer.dictation") return;
154 const canStart = speech.state.phase === "idle" || speech.state.phase === "error";
155 if (canStart && (!speech.available || disabled)) return;
156 event.preventDefault();
157 event.stopPropagation();
158 if (event.repeat || (!canStart && speech.state.phase !== "recording")) return;
159 // macOS may omit the previous non-modifier keyup while Command is held.
160 pressed.current = null;
161 generation.current += 1;
162 if (speech.state.phase === "recording") {
163 void speech.stop();
164 return;
165 }
166 pressed.current = {
167 generation: generation.current,
168 code: event.code || event.key,
169 startedAt: performance.now(),
170 mode,
171 starting: speech.start(),
172 };
173 };
174 const onBlur = () => finish(null);
175 const relay = (event: KeyboardEvent) => {
176 relayedFrom.set(event, id.current);
177 window.dispatchEvent(event);
178 };
179 const unsubscribe = subscribeKeys?.({
180 keydown: relay,
181 keyup: relay,
182 blur: onBlur,
183 });
184 window.addEventListener("keydown", onKeyDown, true);
185 window.addEventListener("keyup", finish, true);
186 window.addEventListener("blur", onBlur);
187 return () => {
188 disposed = true;
189 pressed.current = null;
190 shortcutTargets.delete(id.current);
191 unsubscribe?.();
192 window.removeEventListener("keydown", onKeyDown, true);
193 window.removeEventListener("keyup", finish, true);
194 window.removeEventListener("blur", onBlur);
195 };
196 }, [mode, subscribeKeys]);
197​
198 return shortcutLabelForCommand(input.keybindings, "composer.dictation", {
199 context: { terminalFocus: false, terminalOpen: input.terminalOpen },
200 });