import { useState, useCallback, useRef } from "preact/hooks" import { SpeechRecognizer } from "./SpeechRecognizer.js" import type { SpeechRecognitionTask } from "./SpeechRecognitionTask.js" export function useSpeechRecognizer( recognizer: SpeechRecognizer, config: { onResult: (text: string) => void onStatus?: (status: string | null) => void }, ) { const [recording, setRecording] = useState(false) const [transcribing, setTranscribing] = useState(false) const taskRef = useRef(null) const configRef = useRef(config) configRef.current = config const toggle = useCallback(async () => { if (taskRef.current) { const task = taskRef.current taskRef.current = null setRecording(false) setTranscribing(true) configRef.current.onStatus?.("Transcribing...") try { const result = await task.finish() if (result.text) { configRef.current.onResult(result.text) configRef.current.onStatus?.(null) } else { configRef.current.onStatus?.("Could not transcribe audio.") } } catch { configRef.current.onStatus?.("Could not transcribe audio.") } setTranscribing(false) } else { const task = recognizer.recognitionTask() taskRef.current = task setRecording(true) } }, [recognizer]) return { recording, transcribing, toggle } }