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

useDictationShortcut.ts

171 lines6.4 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​
63export function useDictationShortcut(input: ShortcutInput) {
64 const id = useRef(Symbol("dictation-target"));
65 const subscribeKeys = input.subscribeKeys;
66 const mode = useClientSettings((settings) => settings.voiceShortcutMode);
67 const current = useRef(input);
68 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed actions to the window keyboard listener and shortcut registry
69 useEffect(() => {
70 current.current = input;
71 });
72 const generation = useRef(0);
73 const pressed = useRef<{
74 generation: number;
75 code: string;
76 startedAt: number;
77 mode: typeof mode;
78 starting: Promise<void>;
79 } | null>(null);
80​
81 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- owns the window keyboard listeners and dictation target registry entry
82 useEffect(() => {
83 if (typeof window === "undefined") return;
84 let disposed = false;
85 shortcutTargets.set(id.current, () => current.current);
86 const finish = (event: KeyboardEvent | null) => {
87 const press = pressed.current;
88 if (!press || (event && (event.code || event.key) !== press.code)) return;
89 pressed.current = null;
90 if (shouldFinishDictationOnRelease(press.mode, performance.now() - press.startedAt)) {
91 void press.starting.then(() => {
92 if (!disposed && generation.current === press.generation)
93 return current.current.speech.stop();
94 });
95 }
96 };
97​
98 const onKeyDown = (event: KeyboardEvent) => {
99 if (!ownsShortcut(id.current)) return;
100 if (event.isComposing || event.keyCode === 229) return;
101 const { speech } = current.current;
102 if (event.defaultPrevented || isCommandPaletteOpen()) return;
103 if (
104 event.key === "Escape" &&
105 (pressed.current !== null ||
106 (speech.state.phase !== "idle" && speech.state.phase !== "error"))
107 ) {
108 event.preventDefault();
109 event.stopImmediatePropagation();
110 pressed.current = null;
111 generation.current += 1;
112 speech.cancel();
113 return;
114 }
115 const { keybindings, terminalOpen, modelPickerOpen, disabled } = current.current;
116 const previewFocus = current.current.previewFocus ?? false;
117 const command = resolveShortcutCommand(event, keybindings, {
118 context: {
119 terminalFocus: getTerminalFocusOwner() !== null,
120 terminalOpen,
121 modelPickerOpen,
122 previewFocus,
123 previewOpen: previewFocus,
124 ...(previewFocus ? { editableFocus: true } : {}),
125 },
126 });
127 if (command !== "composer.dictation") return;
128 const canStart = speech.state.phase === "idle" || speech.state.phase === "error";
129 if (canStart && (!speech.available || disabled)) return;
130 event.preventDefault();
131 event.stopPropagation();
132 if (event.repeat || (!canStart && speech.state.phase !== "recording")) return;
133 // macOS may omit the previous non-modifier keyup while Command is held.
134 pressed.current = null;
135 generation.current += 1;
136 if (speech.state.phase === "recording") {
137 void speech.stop();
138 return;
139 }
140 pressed.current = {
141 generation: generation.current,
142 code: event.code || event.key,
143 startedAt: performance.now(),
144 mode,
145 starting: speech.start(),
146 };
147 };
148 const onBlur = () => finish(null);
149 const unsubscribe = subscribeKeys?.({
150 keydown: (event) => window.dispatchEvent(event),
151 keyup: (event) => window.dispatchEvent(event),
152 blur: onBlur,
153 });
154 window.addEventListener("keydown", onKeyDown, true);
155 window.addEventListener("keyup", finish, true);
156 window.addEventListener("blur", onBlur);
157 return () => {
158 disposed = true;
159 pressed.current = null;
160 shortcutTargets.delete(id.current);
161 unsubscribe?.();
162 window.removeEventListener("keydown", onKeyDown, true);
163 window.removeEventListener("keyup", finish, true);
164 window.removeEventListener("blur", onBlur);
165 };
166 }, [mode, subscribeKeys]);
167​
168 return shortcutLabelForCommand(input.keybindings, "composer.dictation", {
169 context: { terminalFocus: false, terminalOpen: input.terminalOpen },
170 });