peppa/apps/web/components/DictateButton.tsx
2026-11-15 21:43:49 +05:00

113 lines
4.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
// PEP-108: a microphone next to a text field — records in the browser (MediaRecorder), sends the
// audio to Peppa (POST /api/transcribe → the speech-to-text service, the same as the Telegram
// bot's) and appends the text to the field; the user edits it and sends as usual. Rendered only
// when the server has speech to text (see Dictate) and the browser can record.
import { useEffect, useRef, useState } from "react";
import { Loader2, Mic, Square } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
/** Longest recording; the bot's voice limit is the same 3 minutes. */
const MAX_MS = 3 * 60_000;
type State = "idle" | "recording" | "sending";
/** Appends text to an input/textarea so that React-controlled fields notice it too. */
function appendTo(target: string, text: string) {
const el = document.getElementById(target) as HTMLInputElement | HTMLTextAreaElement | null;
if (!el) return;
const value = `${el.value}${el.value && !/\s$/.test(el.value) ? " " : ""}${text}`;
const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
Object.getOwnPropertyDescriptor(proto, "value")?.set?.call(el, value);
el.dispatchEvent(new Event("input", { bubbles: true }));
el.focus();
}
function pickMime(): string | undefined {
for (const t of ["audio/webm;codecs=opus", "audio/webm", "audio/mp4", "audio/ogg;codecs=opus"]) {
if (MediaRecorder.isTypeSupported?.(t)) return t;
}
return undefined;
}
export function DictateButton({ target, className, compact = false }: { target: string; className?: string; compact?: boolean }) {
const [supported, setSupported] = useState(false);
const [state, setState] = useState<State>("idle");
const [error, setError] = useState<string | null>(null);
const rec = useRef<MediaRecorder | null>(null);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
setSupported(typeof window !== "undefined" && !!navigator.mediaDevices?.getUserMedia && typeof MediaRecorder !== "undefined");
return () => {
if (timer.current) clearTimeout(timer.current);
rec.current?.stream.getTracks().forEach((t) => t.stop());
};
}, []);
if (!supported) return null;
async function send(blob: Blob) {
setState("sending");
try {
const form = new FormData();
form.set("file", blob, "dictation");
const res = await fetch("/api/transcribe", { method: "POST", body: form });
const body = (await res.json().catch(() => ({}))) as { text?: string; error?: string };
if (!res.ok) throw new Error(body.error || `Не получилось распознать (${res.status})`);
if (!body.text) throw new Error("Не разобрал ни слова — попробуйте ещё раз");
appendTo(target, body.text);
} catch (e) {
setError((e as Error).message);
} finally {
setState("idle");
}
}
async function start() {
setError(null);
let stream: MediaStream;
try {
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
} catch {
setError("Нет доступа к микрофону — разрешите его в браузере");
return;
}
const mimeType = pickMime();
const r = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
const chunks: Blob[] = [];
r.ondataavailable = (e) => e.data.size && chunks.push(e.data);
r.onstop = () => {
stream.getTracks().forEach((t) => t.stop());
if (timer.current) clearTimeout(timer.current);
void send(new Blob(chunks, { type: r.mimeType || mimeType || "audio/webm" }));
};
rec.current = r;
r.start();
setState("recording");
timer.current = setTimeout(() => r.state === "recording" && r.stop(), MAX_MS);
}
const label = state === "recording" ? "Стоп" : state === "sending" ? "Распознаю…" : "Голосом";
return (
<span className={cn("inline-flex flex-col items-start gap-1", className)}>
<Button
type="button"
size="sm"
variant={state === "recording" ? "destructive" : "outline"}
disabled={state === "sending"}
onClick={() => (state === "recording" ? rec.current?.stop() : void start())}
aria-pressed={state === "recording"}
title={state === "recording" ? "Остановить запись и распознать" : "Наговорить текст голосом"}
data-dictate={target}
>
{state === "recording" ? <Square /> : state === "sending" ? <Loader2 className="animate-spin" /> : <Mic />}
{!compact && label}
{compact && <span className="sr-only">{label}</span>}
</Button>
{error && <span role="alert" className="text-xs text-destructive">{error}</span>}
</span>
);
}