"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"; import { useT } from "@/components/I18n"; /** 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 t = useT(); const [supported, setSupported] = useState(false); const [state, setState] = useState("idle"); const [error, setError] = useState(null); const rec = useRef(null); const timer = useRef | 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 || t("Не получилось распознать ({status})", { status: res.status })); if (!body.text) throw new Error(t("Не разобрал ни слова — попробуйте ещё раз")); 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(t("Нет доступа к микрофону — разрешите его в браузере")); 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" ? t("Стоп") : state === "sending" ? t("Распознаю…") : t("Голосом"); return ( {error && {error}} ); }