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

voiceInputSession.ts

227 lines7.2 KB

1import {
2 VOICE_RECORDING_LIMIT_SECONDS,
3 VoiceInputController,
4 voiceInputBlocksSubmission,
5 type VoiceDraftSnapshot,
6 type VoiceInputControllerDependencies,
7 type VoiceInputPhase,
8 type VoiceInputState,
9} from "@t3tools/client-runtime/voice-input";
10​
11import { normalizeVoiceInputDecibels, VOICE_WAVEFORM_SAMPLE_COUNT } from "./voiceInputMetering";
12​
13const VOICE_METERING_INTERVAL_MS = 80;
14const IDLE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
15const SILENT_LEVELS: ReadonlyArray<number> = Array<number>(VOICE_WAVEFORM_SAMPLE_COUNT).fill(0);
16​
17export type VoiceInputTarget = {
18 readonly ownerKey: string;
19 readonly label?: string;
20 readonly readDraft: () => VoiceDraftSnapshot | null;
21 readonly commitDraft: VoiceInputControllerDependencies["commitDraft"];
22 readonly subscribe: () => () => void;
23};
24​
25export type VoiceInputSnapshot = {
26 readonly state: VoiceInputState;
27 readonly ownerKey: string | null;
28 readonly label: string | null;
29 readonly elapsedSeconds: number;
30 readonly focusedOwners: ReadonlySet<string>;
31};
32​
33export type VoiceRecordingSample = {
34 readonly durationMillis: number;
35 readonly metering: number | undefined;
36};
37​
38export type VoiceInputSessionDependencies = Omit<
39 VoiceInputControllerDependencies,
40 "readDraft" | "commitDraft" | "onStateChange"
41> & {
42 /** Reads the live recorder, or null when it is not capturing. */
43 readonly sampleRecording: () => VoiceRecordingSample | null;
44 /** Levels change every metering tick, so they bypass React state. */
45 readonly publishAudioLevels: (levels: ReadonlyArray<number>) => void;
46 /** Holds the screen awake while recording; returns the release. */
47 readonly keepAwake: () => () => void;
48};
49​
50export function createVoiceInputTarget(
51 ownerKey: string,
52 readText: () => string | null,
53 commitDraft: VoiceInputTarget["commitDraft"],
54 selection: VoiceDraftSnapshot["selection"],
55 subscribeToChanges: (onChange: () => void) => () => void,
56): VoiceInputTarget {
57 let revision = 0;
58 return {
59 ownerKey,
60 readDraft: () => {
61 const text = readText();
62 if (text === null) return null;
63 return { ownerKey, text, selection, revision };
64 },
65 commitDraft,
66 subscribe: () => {
67 let previousText = readText();
68 return subscribeToChanges(() => {
69 const text = readText();
70 if (text !== previousText) {
71 previousText = text;
72 revision += 1;
73 }
74 });
75 },
76 };
78​
79/**
80 * The app's single voice input: it owns the controller, the recording-only
81 * side effects (keep-awake, metering) and publishes what the UI renders.
82 */
83export class VoiceInputSession {
84 readonly controller: VoiceInputController;
85 private readonly dependencies: VoiceInputSessionDependencies;
86 private target: VoiceInputTarget | null = null;
87 private unsubscribe: (() => void) | null = null;
88 private snapshot: VoiceInputSnapshot = {
89 state: IDLE_STATE,
90 ownerKey: null,
91 label: null,
92 elapsedSeconds: 0,
93 focusedOwners: new Set(),
94 };
95 private readonly listeners = new Set<() => void>();
96 private audioLevels = SILENT_LEVELS;
97 private releaseKeepAwake: (() => void) | null = null;
98 private meteringInterval: ReturnType<typeof setInterval> | null = null;
99​
100 constructor(dependencies: VoiceInputSessionDependencies) {
101 this.dependencies = dependencies;
102 this.controller = new VoiceInputController({
103 ...dependencies,
104 onStateChange: (state) => this.handleStateChange(state),
105 readDraft: () => this.target?.readDraft() ?? null,
106 commitDraft: (text, selection) => this.target?.commitDraft(text, selection),
107 });
108 }
109​
110 get ownerKey(): string | null {
111 return this.target?.ownerKey ?? null;
112 }
113​
114 get label(): string | null {
115 return this.target?.label ?? null;
116 }
117​
118 readonly subscribe = (listener: () => void): (() => void) => {
119 this.listeners.add(listener);
120 return () => this.listeners.delete(listener);
121 };
122​
123 readonly getSnapshot = (): VoiceInputSnapshot => this.snapshot;
124​
125 setOwnerFocused(ownerKey: string, focused: boolean): void {
126 if (this.snapshot.focusedOwners.has(ownerKey) === focused) return;
127 const focusedOwners = new Set(this.snapshot.focusedOwners);
128 if (focused) focusedOwners.add(ownerKey);
129 else focusedOwners.delete(ownerKey);
130 this.publish({ ...this.snapshot, focusedOwners });
131 }
132​
133 cancel(ownerKey: string | null): void {
134 if (ownerKey !== null && this.ownerKey === ownerKey) this.controller.cancel();
135 }
136​
137 retry(): Promise<void> {
138 return this.target ? this.start(this.target) : Promise.resolve();
139 }
140​
141 start(target: VoiceInputTarget): Promise<void> {
142 if (voiceInputBlocksSubmission(this.controller.currentState)) return Promise.resolve();
143 this.target = target;
144 this.unsubscribe = target.subscribe();
145 return this.controller.start();
146 }
147​
148 dispose(): void {
149 this.controller.dispose();
150 this.stopRecordingActivity();
151 this.unsubscribe?.();
152 this.unsubscribe = null;
153 this.listeners.clear();
154 }
155​
156 private handleStateChange(state: VoiceInputState): void {
157 if (!voiceInputBlocksSubmission(state)) {
158 this.unsubscribe?.();
159 this.unsubscribe = null;
160 }
161 const previousPhase = this.snapshot.state.phase;
162 let elapsedSeconds = this.snapshot.elapsedSeconds;
163 if (state.phase !== previousPhase) {
164 if (previousPhase === "recording") this.stopRecordingActivity();
165 if (capturesAudio(state.phase)) {
166 if (this.audioLevels.some((level) => level !== 0)) this.setAudioLevels(SILENT_LEVELS);
167 elapsedSeconds = 0;
168 }
169 }
170 this.publish({
171 ...this.snapshot,
172 state,
173 ownerKey: this.ownerKey,
174 label: this.label,
175 elapsedSeconds,
176 });
177 if (state.phase === "recording" && previousPhase !== "recording") {
178 this.startRecordingActivity();
179 }
180 }
181​
182 private startRecordingActivity(): void {
183 this.releaseKeepAwake = this.dependencies.keepAwake();
184 this.sampleRecording();
185 this.meteringInterval = setInterval(() => this.sampleRecording(), VOICE_METERING_INTERVAL_MS);
186 }
187​
188 private stopRecordingActivity(): void {
189 if (this.meteringInterval !== null) clearInterval(this.meteringInterval);
190 this.meteringInterval = null;
191 this.releaseKeepAwake?.();
192 this.releaseKeepAwake = null;
193 }
194​
195 private sampleRecording(): void {
196 if (this.controller.currentState.phase !== "recording") return;
197 const sample = this.dependencies.sampleRecording();
198 if (!sample) return;
199​
200 const level = normalizeVoiceInputDecibels(sample.metering);
201 if (level !== 0 || this.audioLevels.some((sample) => sample !== 0)) {
202 this.setAudioLevels([...this.audioLevels.slice(1), level]);
203 }
204​
205 const elapsedSeconds = Math.min(
206 VOICE_RECORDING_LIMIT_SECONDS,
207 Math.max(0, Math.floor(sample.durationMillis / 1_000)),
208 );
209 if (elapsedSeconds !== this.snapshot.elapsedSeconds) {
210 this.publish({ ...this.snapshot, elapsedSeconds });
211 }
212 }
213​
214 private setAudioLevels(levels: ReadonlyArray<number>): void {
215 this.audioLevels = levels;
216 this.dependencies.publishAudioLevels(levels);
217 }
218​
219 private publish(snapshot: VoiceInputSnapshot): void {
220 this.snapshot = snapshot;
221 for (const listener of this.listeners) listener();
222 }
224​
225function capturesAudio(phase: VoiceInputPhase): boolean {
226 return phase === "preparing" || phase === "recording";