okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221apps/host: the owner's UI and the Node App Host0b3299a01

main
7.4 KiB118 linesraw
1import { tr } from '../lib/i18n';
2import { useEffect, useRef, useState } from 'react';
3import { createPortal } from 'react-dom';
4import { Btn, Icon, IconBtn } from './ui';
5import { getCommands, MOD } from '../lib/commands';
6import { bindingKeys, useBindings } from '../lib/shortcut-bindings';
7import { createDictation, type DictationState, type RecognizerConstructor } from '../lib/dictation';
8export function DictationControl({ draft, onDraft, sessionId, disabled }: {
9    draft: string;
10    onDraft: (text: string) => void;
11    sessionId?: string;
12    disabled: boolean;
13}) {
14    useBindings();
15    const [visible, setVisible] = useState(false), [state, setState] = useState<DictationState | 'unsupported'>('finished'), [error, setError] = useState(''), [spoken, setSpoken] = useState('');
16    const controller = useRef<ReturnType<typeof createDictation> | null>(null);
17    const latest = useRef({ draft, onDraft });
18    latest.current = { draft, onDraft };
19    const active = useRef(false), base = useRef(''), written = useRef(''), manualEdit = useRef(false);
20    const toggleRef = useRef<() => void>(() => { });
21    const constructor = (window as unknown as {
22        SpeechRecognition?: RecognizerConstructor;
23        webkitSpeechRecognition?: RecognizerConstructor;
24    }).SpeechRecognition ?? (window as unknown as {
25        webkitSpeechRecognition?: RecognizerConstructor;
26    }).webkitSpeechRecognition;
27    const binding = getCommands().find(c => c.id === 'dictation')?.binding ?? null;
28    const shortcut = bindingKeys(binding, MOD).map(k => MOD === '⌘' && k === 'Shift' ? '⇧' : MOD === '⌘' && k === 'Alt' ? '⌥' : k).join(MOD === '⌘' ? '' : '+');
29    const ariaShortcut = binding ? [...(binding.mod ? [MOD === '⌘' ? 'Meta' : 'Control'] : []), ...(binding.alt ? ['Alt'] : []), ...(binding.shift ? ['Shift'] : []), binding.key.toUpperCase()].join('+') : undefined;
30    const listening = ['starting', 'listening', 'speaking', 'finishing'].includes(state);
31    function close() { controller.current?.dispose(); controller.current = null; active.current = false; setState('finished'); setVisible(false); document.querySelector<HTMLTextAreaElement>('.st-composer textarea')?.focus(); }
32    function toggle() {
33        if (active.current) {
34            controller.current?.stop();
35            return;
36        }
37        if (disabled)
38            return;
39        controller.current?.dispose();
40        controller.current = null;
41        setVisible(true);
42        setError('');
43        setSpoken('');
44        if (!constructor) {
45            setState('unsupported');
46            return;
47        }
48        base.current = latest.current.draft;
49        written.current = base.current;
50        manualEdit.current = false;
51        try {
52            const recognizer = new constructor();
53            controller.current = createDictation(recognizer, { lang: navigator.language || 'en-US', onState: (next, message) => {
54                    active.current = ['starting', 'listening', 'speaking', 'finishing'].includes(next);
55                    setState(next);
56                    if (message)
57                        setError(message);
58                }, onText: text => {
59                    setSpoken(text);
60                    if (manualEdit.current)
61                        return;
62                    const value = `${base.current}${base.current && text && !/\s$/.test(base.current) ? ' ' : ''}${text}`;
63                    written.current = value;
64                    latest.current.onDraft(value);
65                } });
66            controller.current.start();
67        }
68        catch {
69            active.current = false;
70            setState('error');
71            setError('Speech recognition is unavailable in this browser. Use your computer’s built-in dictation.');
72        }
73    }
74    toggleRef.current = toggle;
75    useEffect(() => {
76        const event = () => {
77            if (!document.querySelector('.dialog-layer'))
78                toggleRef.current();
79        };
80        window.addEventListener('strata:dictation', event);
81        return () => window.removeEventListener('strata:dictation', event);
82    }, []);
83    useEffect(() => { controller.current?.dispose(); controller.current = null; active.current = false; setState('finished'); setVisible(false); return () => controller.current?.dispose(); }, [sessionId]);
84    useEffect(() => {
85        if (!visible)
86            return;
87        const escape = (event: KeyboardEvent) => {
88            if (event.key === 'Escape' && !event.defaultPrevented && !document.querySelector('.dialog-layer')) {
89                event.preventDefault();
90                close();
91            }
92        };
93        document.addEventListener('keydown', escape);
94        return () => document.removeEventListener('keydown', escape);
95    }, [visible]);
96    useEffect(() => {
97        if (disabled && active.current)
98            controller.current?.stop();
99    }, [disabled]);
100    useEffect(() => {
101        if (active.current && draft !== written.current) {
102            manualEdit.current = true;
103            controller.current?.stop();
104        }
105    }, [draft]);
106    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';
107    return <>
108    <button className="composer-mic" data-speech-supported={!!constructor} aria-label={tr("Speech to text")} title={tr("Speech to text \u00B7 {0}", [shortcut])} aria-keyshortcuts={ariaShortcut} disabled={disabled && !listening} aria-pressed={listening} aria-controls={visible ? 'dictation-feedback' : undefined} onClick={toggle}><Icon name="mic" size={19}/></button>
109    {tr(visible ? createPortal(<aside id="dictation-feedback" className="dictation-feedback" aria-label={tr("Dictation")} data-active={listening || undefined}>
110      <div className="dictation-feedback__head"><span className="dictation-feedback__icon"><Icon name={state === 'finished' ? 'check' : 'mic'} size={19}/></span><strong role="status">{tr(title)}</strong><IconBtn name="x" title={tr("Close dictation")} onClick={close}/></div>
111      {tr(listening ? <div className="voice-wave" data-speaking={state === 'speaking' || undefined} aria-hidden="true">{tr([0, 1, 2, 3, 4].map(i => <span key={i} style={{ animationDelay: `${i * 100}ms` }}/>))}</div> : null)}
112      <p className="small muted">{tr(state === 'unsupported' ? 'This browser does not provide speech recognition. Use your computer’s built-in dictation in the message box.' : state === 'error' ? error : state === 'finished' ? (spoken ? 'Text is in your message box. Review it before sending.' : 'No text was added. Your draft is ready to edit.') : 'Speak naturally. A 3.5-second pause finishes dictation. Text appears in your message box without sending.')}</p>
113      {tr(spoken ? <p className="dictation-feedback__transcript">{tr(spoken)}</p> : null)}
114      <div className="dictation-feedback__actions"><kbd>{tr(shortcut)}</kbd>{tr(listening ? <Btn size="sm" onClick={() => controller.current?.stop()} disabled={state === 'finishing'}>{tr("Stop")}</Btn> : <>{tr(constructor ? <Btn size="sm" onClick={toggle}>{tr(state === 'error' ? 'Try again' : 'Speak again')}</Btn> : null)}<Btn size="sm" onClick={close}>{tr("Done")}</Btn></>)}</div>
115      {tr(listening ? <p className="xs muted dictation-feedback__provider">{tr("Uses your browser\u2019s speech service.")}</p> : null)}
116    </aside>, document.body) : null)}
117  </>;
118}