Open History to see the last commit
1import { useFocusEffect } from "@react-navigation/native";
2import { useCallback, useEffect, useRef } from "react";
3import {
4 voiceInputBlocksSubmission,
5 type VoiceInputState,
6} from "@t3tools/client-runtime/voice-input";
7
8import type { ComposerEditorSelection } from "../../components/ComposerEditor";
9import { useGlobalVoiceInput } from "./VoiceInputProvider";
10import { createVoiceInputTarget } from "./voiceInputSession";
11
12const IDLE_STATE: VoiceInputState = { phase: "idle", error: null, errorAction: null };
13
14export function useVoiceInputController(input: {
15 readonly ownerKey: string | null;
16 readonly label: string;
17 readonly readDraftMessage: () => string | null;
18 readonly subscribeToDraftChanges: (onChange: () => void) => () => void;
19 readonly selection: ComposerEditorSelection;
20 readonly disabled?: boolean;
21 readonly onChangeDraftMessage: (value: string) => void;
22 readonly onChangeSelection: (selection: ComposerEditorSelection) => void;
23}) {
24 const global = useGlobalVoiceInput();
25 const { session } = global;
26 const latestInput = useRef(input);
27 // oxlint-disable-next-line react/refs -- Transcription finishes asynchronously and must reach the composer's current selection setter, not the one captured at start.
28 latestInput.current = input;
29 const mounted = useRef(true);
30 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tracks mount so async transcription results skip a composer that has unmounted
31 useEffect(() => {
32 mounted.current = true;
33 return () => {
34 mounted.current = false;
35 };
36 }, []);
37
38 useFocusEffect(
39 useCallback(() => {
40 const ownerKey = input.ownerKey;
41 if (!ownerKey) return;
42 session.setOwnerFocused(ownerKey, true);
43 return () => session.setOwnerFocused(ownerKey, false);
44 }, [input.ownerKey, session]),
45 );
46
47 const start = useCallback(() => {
48 const captured = latestInput.current;
49 if (!captured.ownerKey || captured.disabled) return;
50 void session.start({
51 ...createVoiceInputTarget(
52 captured.ownerKey,
53 captured.readDraftMessage,
54 (text, selection) => {
55 captured.onChangeDraftMessage(text);
56 if (mounted.current && latestInput.current.ownerKey === captured.ownerKey) {
57 latestInput.current.onChangeSelection(selection);
58 }
59 },
60 captured.selection,
61 captured.subscribeToDraftChanges,
62 ),
63 label: captured.label,
64 });
65 }, [session]);
66 const state = global.ownerKey === input.ownerKey ? global.state : IDLE_STATE;
67 const isBusy = voiceInputBlocksSubmission(state);
68 return {
69 isAvailable: global.isAvailable && (!global.isBusy || global.ownerKey === input.ownerKey),
70 state,
71 audioLevels: global.audioLevels,
72 elapsedSeconds: global.elapsedSeconds,
73 isBusy,
74 freezesEditor: isBusy,
75 blocksSubmission: isBusy,
76 start,
77 stop: global.stop,
78 cancel: global.cancel,
79 };
80}