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

voiceInputSession.ts

87 lines2.5 KB

1import {
2 VoiceInputController,
3 voiceInputBlocksSubmission,
4 type VoiceDraftSnapshot,
5 type VoiceInputControllerDependencies,
6} from "@t3tools/client-runtime/voice-input";
7​
8export type VoiceInputTarget = {
9 readonly ownerKey: string;
10 readonly label?: string;
11 readonly readDraft: () => VoiceDraftSnapshot | null;
12 readonly commitDraft: VoiceInputControllerDependencies["commitDraft"];
13 readonly subscribe: () => () => void;
14};
15​
16export function createVoiceInputTarget(
17 ownerKey: string,
18 readText: () => string | null,
19 commitDraft: VoiceInputTarget["commitDraft"],
20 selection: VoiceDraftSnapshot["selection"],
21 subscribeToChanges: (onChange: () => void) => () => void,
22): VoiceInputTarget {
23 let revision = 0;
24 return {
25 ownerKey,
26 readDraft: () => {
27 const text = readText();
28 if (text === null) return null;
29 return { ownerKey, text, selection, revision };
30 },
31 commitDraft,
32 subscribe: () => {
33 let previousText = readText();
34 return subscribeToChanges(() => {
35 const text = readText();
36 if (text !== previousText) {
37 previousText = text;
38 revision += 1;
39 }
40 });
41 },
42 };
44​
45export class VoiceInputSession {
46 readonly controller: VoiceInputController;
47 private target: VoiceInputTarget | null = null;
48 private unsubscribe: (() => void) | null = null;
49​
50 constructor(dependencies: Omit<VoiceInputControllerDependencies, "readDraft" | "commitDraft">) {
51 this.controller = new VoiceInputController({
52 ...dependencies,
53 onStateChange: (state) => {
54 if (!voiceInputBlocksSubmission(state)) {
55 this.unsubscribe?.();
56 this.unsubscribe = null;
57 }
58 dependencies.onStateChange(state);
59 },
60 readDraft: () => this.target?.readDraft() ?? null,
61 commitDraft: (text, selection) => this.target?.commitDraft(text, selection),
62 });
63 }
64​
65 get ownerKey(): string | null {
66 return this.target?.ownerKey ?? null;
67 }
68​
69 get label(): string | null {
70 return this.target?.label ?? null;
71 }
72​
73 cancel(ownerKey: string | null): void {
74 if (ownerKey !== null && this.ownerKey === ownerKey) this.controller.cancel();
75 }
76​
77 retry(): Promise<void> {
78 return this.target ? this.start(this.target) : Promise.resolve();
79 }
80​
81 start(target: VoiceInputTarget): Promise<void> {
82 if (voiceInputBlocksSubmission(this.controller.currentState)) return Promise.resolve();
83 this.target = target;
84 this.unsubscribe = target.subscribe();
85 return this.controller.start();
86 }