66 lines
2.5 KiB
TypeScript
66 lines
2.5 KiB
TypeScript
"use client";
|
|
|
|
// PEP-53: voice input for a prompt — the browser's own speech recognition (Web Speech API,
|
|
// Chrome/Safari); nothing is sent to Peppa but the recognized text. Hidden where unsupported.
|
|
import { useEffect, useRef, useState } from "react";
|
|
import { Mic, MicOff } from "lucide-react";
|
|
import { Button } from "@/components/ui/button";
|
|
import { useT } from "@/components/I18n";
|
|
import { intlLocale } from "@peppa/shared/i18n";
|
|
|
|
type Recognition = {
|
|
lang: string;
|
|
interimResults: boolean;
|
|
continuous: boolean;
|
|
start(): void;
|
|
stop(): void;
|
|
onresult: ((e: { resultIndex: number; results: ArrayLike<{ isFinal: boolean; 0: { transcript: string } }> }) => void) | null;
|
|
onend: (() => void) | null;
|
|
onerror: (() => void) | null;
|
|
};
|
|
|
|
export function VoiceInput({ target }: { target: string }) {
|
|
const [supported, setSupported] = useState(false);
|
|
const [on, setOn] = useState(false);
|
|
const rec = useRef<Recognition | null>(null);
|
|
const t = useT();
|
|
useEffect(() => {
|
|
const w = window as unknown as { SpeechRecognition?: new () => Recognition; webkitSpeechRecognition?: new () => Recognition };
|
|
setSupported(!!(w.SpeechRecognition ?? w.webkitSpeechRecognition));
|
|
return () => rec.current?.stop();
|
|
}, []);
|
|
if (!supported) return null;
|
|
|
|
const toggle = () => {
|
|
if (on) {
|
|
rec.current?.stop();
|
|
return;
|
|
}
|
|
const w = window as unknown as { SpeechRecognition?: new () => Recognition; webkitSpeechRecognition?: new () => Recognition };
|
|
const Ctor = (w.SpeechRecognition ?? w.webkitSpeechRecognition)!;
|
|
const r = new Ctor();
|
|
r.lang = intlLocale(t.locale);
|
|
r.interimResults = false;
|
|
r.continuous = true;
|
|
r.onresult = (e) => {
|
|
const el = document.getElementById(target) as HTMLTextAreaElement | HTMLInputElement | null;
|
|
if (!el) return;
|
|
for (let i = e.resultIndex; i < e.results.length; i++) {
|
|
const res = e.results[i]!;
|
|
if (res.isFinal) el.value = `${el.value}${el.value && !/\s$/.test(el.value) ? " " : ""}${res[0].transcript.trim()}`;
|
|
}
|
|
};
|
|
r.onend = () => setOn(false);
|
|
r.onerror = () => setOn(false);
|
|
rec.current = r;
|
|
r.start();
|
|
setOn(true);
|
|
};
|
|
return (
|
|
<Button type="button" size="sm" variant={on ? "default" : "outline"} onClick={toggle} aria-pressed={on} title={on ? t("Остановить диктовку") : t("Надиктовать промпт")}>
|
|
{on ? <MicOff /> : <Mic />}
|
|
{on ? t("Стоп") : t("Голосом")}
|
|
</Button>
|
|
);
|
|
}
|