import { tr } from '../lib/i18n'; import { useEffect, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import { Btn, Icon, IconBtn } from './ui'; import { getCommands, MOD } from '../lib/commands'; import { bindingKeys, useBindings } from '../lib/shortcut-bindings'; import { createDictation, type DictationState, type RecognizerConstructor } from '../lib/dictation'; export function DictationControl({ draft, onDraft, sessionId, disabled }: { draft: string; onDraft: (text: string) => void; sessionId?: string; disabled: boolean; }) { useBindings(); const [visible, setVisible] = useState(false), [state, setState] = useState('finished'), [error, setError] = useState(''), [spoken, setSpoken] = useState(''); const controller = useRef | null>(null); const latest = useRef({ draft, onDraft }); latest.current = { draft, onDraft }; const active = useRef(false), base = useRef(''), written = useRef(''), manualEdit = useRef(false); const toggleRef = useRef<() => void>(() => { }); const constructor = (window as unknown as { SpeechRecognition?: RecognizerConstructor; webkitSpeechRecognition?: RecognizerConstructor; }).SpeechRecognition ?? (window as unknown as { webkitSpeechRecognition?: RecognizerConstructor; }).webkitSpeechRecognition; const binding = getCommands().find(c => c.id === 'dictation')?.binding ?? null; const shortcut = bindingKeys(binding, MOD).map(k => MOD === '⌘' && k === 'Shift' ? '⇧' : MOD === '⌘' && k === 'Alt' ? '⌥' : k).join(MOD === '⌘' ? '' : '+'); const ariaShortcut = binding ? [...(binding.mod ? [MOD === '⌘' ? 'Meta' : 'Control'] : []), ...(binding.alt ? ['Alt'] : []), ...(binding.shift ? ['Shift'] : []), binding.key.toUpperCase()].join('+') : undefined; const listening = ['starting', 'listening', 'speaking', 'finishing'].includes(state); function close() { controller.current?.dispose(); controller.current = null; active.current = false; setState('finished'); setVisible(false); document.querySelector('.st-composer textarea')?.focus(); } function toggle() { if (active.current) { controller.current?.stop(); return; } if (disabled) return; controller.current?.dispose(); controller.current = null; setVisible(true); setError(''); setSpoken(''); if (!constructor) { setState('unsupported'); return; } base.current = latest.current.draft; written.current = base.current; manualEdit.current = false; try { const recognizer = new constructor(); controller.current = createDictation(recognizer, { lang: navigator.language || 'en-US', onState: (next, message) => { active.current = ['starting', 'listening', 'speaking', 'finishing'].includes(next); setState(next); if (message) setError(message); }, onText: text => { setSpoken(text); if (manualEdit.current) return; const value = `${base.current}${base.current && text && !/\s$/.test(base.current) ? ' ' : ''}${text}`; written.current = value; latest.current.onDraft(value); } }); controller.current.start(); } catch { active.current = false; setState('error'); setError('Speech recognition is unavailable in this browser. Use your computer’s built-in dictation.'); } } toggleRef.current = toggle; useEffect(() => { const event = () => { if (!document.querySelector('.dialog-layer')) toggleRef.current(); }; window.addEventListener('strata:dictation', event); return () => window.removeEventListener('strata:dictation', event); }, []); useEffect(() => { controller.current?.dispose(); controller.current = null; active.current = false; setState('finished'); setVisible(false); return () => controller.current?.dispose(); }, [sessionId]); useEffect(() => { if (!visible) return; const escape = (event: KeyboardEvent) => { if (event.key === 'Escape' && !event.defaultPrevented && !document.querySelector('.dialog-layer')) { event.preventDefault(); close(); } }; document.addEventListener('keydown', escape); return () => document.removeEventListener('keydown', escape); }, [visible]); useEffect(() => { if (disabled && active.current) controller.current?.stop(); }, [disabled]); useEffect(() => { if (active.current && draft !== written.current) { manualEdit.current = true; controller.current?.stop(); } }, [draft]); const title = state === 'unsupported' ? 'Dictation unavailable' : state === 'error' ? 'Dictation stopped' : state === 'finished' ? 'Dictation finished' : state === 'starting' ? 'Starting microphone…' : state === 'finishing' ? 'Finishing dictation…' : state === 'speaking' ? 'Listening to you…' : 'Ready to listen'; return <> {tr(visible ? createPortal(, document.body) : null)} ; }