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 { setOwnerFocused, session } = global;
26 const latestInput = useRef(input);
27 latestInput.current = input;
28 const mounted = useRef(true);
29 useEffect(() => {
30 mounted.current = true;
31 return () => {
32 mounted.current = false;
33 };
34 }, []);
35
36 useFocusEffect(
37 useCallback(() => {
38 const ownerKey = input.ownerKey;
39 if (!ownerKey) return;
40 setOwnerFocused(ownerKey, true);
41 return () => setOwnerFocused(ownerKey, false);
42 }, [input.ownerKey, setOwnerFocused]),
43 );
44
45 const start = useCallback(() => {
46 const captured = latestInput.current;
47 if (!captured.ownerKey || captured.disabled) return;
48 void session.start({
49 ...createVoiceInputTarget(
50 captured.ownerKey,
51 captured.readDraftMessage,
52 (text, selection) => {
53 captured.onChangeDraftMessage(text);
54 if (mounted.current && latestInput.current.ownerKey === captured.ownerKey) {
55 latestInput.current.onChangeSelection(selection);
56 }
57 },
58 captured.selection,
59 captured.subscribeToDraftChanges,
60 ),
61 label: captured.label,
62 });
63 }, [session]);
64 const state = global.ownerKey === input.ownerKey ? global.state : IDLE_STATE;
65 const isBusy = voiceInputBlocksSubmission(state);
66 return {
67 isAvailable: global.isAvailable && (!global.isBusy || global.ownerKey === input.ownerKey),
68 state,
69 audioLevels: global.audioLevels,
70 elapsedSeconds: global.elapsedSeconds,
71 isBusy,
72 freezesEditor: isBusy,
73 blocksSubmission: isBusy,
74 start,
75 stop: global.stop,
76 cancel: global.cancel,
77 };
78}