{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "speech-input",
  "type": "registry:ui",
  "title": "Speech input",
  "description": "React speech to text button on the Web Speech API: live interim text, a mic ring that follows your voice, Escape to stop, no API key and no dependencies.",
  "author": "MiniDev UI <https://ui.minidev.pro>",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "https://ui.minidev.pro/r/icon-button.json",
    "https://ui.minidev.pro/r/kbd.json",
    "https://ui.minidev.pro/r/tooltip.json",
    "utils"
  ],
  "files": [
    {
      "path": "registry/ui/speech-input.tsx",
      "type": "registry:ui",
      "target": "components/ui/speech-input.tsx",
      "content": "\"use client\"\nimport * as React from \"react\"\nimport { useReducedMotion } from \"motion/react\"\nimport { MicIcon, SquareIcon } from \"lucide-react\"\nimport { IconButton } from \"@/components/ui/icon-button\"\nimport { Kbd } from \"@/components/ui/kbd\"\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"@/components/ui/tooltip\"\nimport { cn } from \"@/lib/utils\"\n\n/**\n * SpeechInput — a mic button that turns speech into text with the browser's Web Speech API, with a ring that follows your voice.\n *\n * Put it in the toolbar of PromptInput or AiComposer. Click to start, click again or press Escape to\n * stop. `onTranscript(text, { final })` fires with grey-preview text (`final: false`) while you speak\n * and with settled text (`final: true`) when a phrase ends: append final text, replace the preview.\n * It needs `SpeechRecognition`, which Chrome, Edge and Safari have and Firefox does not; there the\n * button is disabled with a tooltip that says so. It calls no service of its own and needs no API\n * key. To record an audio file instead of text use AudioRecorder.\n *\n * @example\n * const [preview, setPreview] = React.useState(\"\")\n * <SpeechInput onTranscript={(text, { final }) => {\n *   if (final) { setPrompt((p) => `${p} ${text.trim()}`.trim()); setPreview(\"\") } else setPreview(text)\n * }} />\n */\n\ntype SpeechInputProps = {\n  /** Fires with recognised text. `final: false` is a live guess that will be replaced; `final: true` is settled. */\n  onTranscript?: (text: string, meta: { final: boolean }) => void\n  /** BCP 47 language to recognise, e.g. \"en-GB\" or \"hi-IN\". Defaults to the browser language (`navigator.language`). */\n  lang?: string\n  /** Keep listening across pauses until stopped. When false, it stops after the first phrase. */\n  continuous?: boolean\n  /** Send interim guesses (`final: false`) while the user speaks. */\n  interim?: boolean\n  /** Fires with the Web Speech error code: \"not-allowed\", \"audio-capture\", \"network\", \"no-speech\"... */\n  onError?: (error: string) => void\n  /** Fires once after mount when the browser has no speech recognition. */\n  onUnsupported?: () => void\n  /** Disables the button and stops listening if it is on. */\n  disabled?: boolean\n  /** 32px (sm) or 36px (md). */\n  size?: \"sm\" | \"md\"\n  /** Accessible name of the button, also its tooltip. Defaults to \"Dictate\". */\n  \"aria-label\"?: string\n  className?: string\n}\n\ntype Alternative = { transcript: string }\ntype RecognitionResult = ArrayLike<Alternative> & { isFinal: boolean }\ntype Recognition = {\n  lang: string\n  continuous: boolean\n  interimResults: boolean\n  start: () => void\n  stop: () => void\n  abort: () => void\n  onresult: ((e: { resultIndex: number; results: ArrayLike<RecognitionResult> }) => void) | null\n  onerror: ((e: { error: string }) => void) | null\n  onend: (() => void) | null\n}\ntype RecognitionCtor = new () => Recognition\n\nconst getRecognition = (): RecognitionCtor | undefined => {\n  if (typeof window === \"undefined\") return undefined\n  const w = window as unknown as { SpeechRecognition?: RecognitionCtor; webkitSpeechRecognition?: RecognitionCtor }\n  return w.SpeechRecognition ?? w.webkitSpeechRecognition\n}\nconst noopSubscribe = () => () => {}\nconst isSupported = () => !!getRecognition()\n\nconst UNSUPPORTED = \"Voice input is not supported in this browser\"\nconst MESSAGES: Record<string, string> = {\n  \"not-allowed\": \"Microphone access is blocked. Allow it in the browser's site settings.\",\n  \"service-not-allowed\": \"Microphone access is blocked. Allow it in the browser's site settings.\",\n  \"audio-capture\": \"No microphone found.\",\n  network: \"Voice input needs a network connection.\",\n  \"no-speech\": \"No speech heard. Try again.\",\n}\n\nfunction SpeechInput({\n  onTranscript,\n  lang,\n  continuous = true,\n  interim = true,\n  onError,\n  onUnsupported,\n  disabled,\n  size = \"md\",\n  \"aria-label\": ariaLabel = \"Dictate\",\n  className,\n}: SpeechInputProps) {\n  const reduce = useReducedMotion()\n  // true on the server and during hydration, so supported browsers never flash a disabled button.\n  const supported = React.useSyncExternalStore(noopSubscribe, isSupported, () => true)\n  const [listening, setListening] = React.useState(false)\n  const [message, setMessage] = React.useState<string | null>(null)\n  const descId = React.useId()\n  const recognition = React.useRef<Recognition | null>(null)\n  const ring = React.useRef<HTMLSpanElement>(null)\n  const meter = React.useRef<{ stream?: MediaStream; ctx?: AudioContext; raf: number; session: number }>({ raf: 0, session: 0 })\n  // Read the latest callbacks when results arrive, not the ones captured when listening started.\n  const cb = React.useRef({ onTranscript, onError })\n  React.useEffect(() => {\n    cb.current = { onTranscript, onError }\n  })\n\n  React.useEffect(() => {\n    if (!supported) onUnsupported?.()\n    // Only on the support answer: a new onUnsupported function each render must not fire it again.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [supported])\n\n  const stopMeter = React.useCallback(() => {\n    const m = meter.current\n    m.session++\n    cancelAnimationFrame(m.raf)\n    m.stream?.getTracks().forEach((t) => t.stop())\n    m.ctx?.close().catch(() => {})\n    m.stream = undefined\n    m.ctx = undefined\n    if (ring.current) ring.current.style.transform = \"\"\n  }, [])\n\n  // The ring scales with the microphone level: a second, analysis-only stream, never recorded.\n  const startMeter = () => {\n    const m = meter.current\n    const session = ++m.session\n    if (reduce || !navigator.mediaDevices?.getUserMedia) return\n    navigator.mediaDevices\n      .getUserMedia({ audio: true })\n      .then((stream) => {\n        if (session !== m.session) return stream.getTracks().forEach((t) => t.stop())\n        const ctx = new AudioContext()\n        const analyser = ctx.createAnalyser()\n        analyser.fftSize = 256\n        ctx.createMediaStreamSource(stream).connect(analyser)\n        m.stream = stream\n        m.ctx = ctx\n        const buf = new Uint8Array(analyser.fftSize)\n        let level = 0\n        const tick = () => {\n          analyser.getByteTimeDomainData(buf)\n          let sum = 0\n          for (let i = 0; i < buf.length; i++) sum += ((buf[i] - 128) / 128) ** 2\n          level = level * 0.75 + Math.min(1, Math.sqrt(sum / buf.length) * 5) * 0.25\n          if (ring.current) ring.current.style.transform = `scale(${1 + level * 0.4})`\n          m.raf = requestAnimationFrame(tick)\n        }\n        tick()\n      })\n      // The meter is decoration. A denied microphone is reported by the recognition error instead.\n      .catch(() => {})\n  }\n\n  const stop = React.useCallback(() => recognition.current?.stop(), [])\n\n  const start = () => {\n    const Ctor = getRecognition()\n    if (!Ctor) return\n    const rec = new Ctor()\n    rec.lang = lang ?? navigator.language\n    rec.continuous = continuous\n    rec.interimResults = interim\n    rec.onresult = (e) => {\n      let settled = \"\"\n      let guess = \"\"\n      for (let i = e.resultIndex; i < e.results.length; i++) {\n        const r = e.results[i]\n        if (r.isFinal) settled += r[0].transcript\n        else guess += r[0].transcript\n      }\n      if (settled) cb.current.onTranscript?.(settled, { final: true })\n      if (guess) cb.current.onTranscript?.(guess, { final: false })\n    }\n    rec.onerror = (e) => {\n      if (e.error === \"aborted\") return\n      setMessage(MESSAGES[e.error] ?? \"Voice input stopped unexpectedly.\")\n      cb.current.onError?.(e.error)\n    }\n    rec.onend = () => {\n      if (recognition.current === rec) recognition.current = null\n      setListening(false)\n      stopMeter()\n    }\n    setMessage(null)\n    try {\n      rec.start()\n    } catch {\n      setMessage(\"Voice input stopped unexpectedly.\")\n      return\n    }\n    recognition.current = rec\n    setListening(true)\n    startMeter()\n  }\n\n  // Escape stops dictation wherever focus is, so it works while typing in the prompt.\n  React.useEffect(() => {\n    if (!listening) return\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key === \"Escape\") stop()\n    }\n    document.addEventListener(\"keydown\", onKey)\n    return () => document.removeEventListener(\"keydown\", onKey)\n  }, [listening, stop])\n\n  // Stop listening when disabled mid-session, and release the microphone on unmount.\n  React.useEffect(() => {\n    if (disabled) recognition.current?.stop()\n  }, [disabled])\n  React.useEffect(\n    () => () => {\n      const rec = recognition.current\n      if (rec) {\n        rec.onend = null\n        rec.abort()\n      }\n      stopMeter()\n    },\n    [stopMeter]\n  )\n\n  const unavailable = !supported\n  return (\n    <span data-slot=\"speech-input\" className={cn(\"inline-flex items-center gap-2\", className)}>\n      <span className=\"relative inline-grid\">\n        <span\n          ref={ring}\n          aria-hidden\n          data-slot=\"speech-input-ring\"\n          className={cn(\n            \"pointer-events-none absolute inset-0 rounded-full bg-accent-soft ring-1 ring-accent-line ring-inset\",\n            \"transition-[opacity] duration-200 ease-hairline\",\n            listening ? \"scale-[1.12] opacity-100\" : \"opacity-0\"\n          )}\n        />\n        <Tooltip>\n          <TooltipTrigger\n            render={\n              <IconButton\n                aria-label={ariaLabel}\n                aria-pressed={listening}\n                aria-describedby={unavailable ? descId : undefined}\n                variant={listening ? \"soft\" : \"ghost\"}\n                size={size === \"sm\" ? \"icon-sm\" : \"icon\"}\n                disabled={disabled || unavailable}\n                focusableWhenDisabled={unavailable}\n                onClick={() => (listening ? stop() : start())}\n                className=\"relative rounded-full focus-visible:ring-offset-surface data-[disabled]:pointer-events-auto data-[disabled]:cursor-not-allowed\"\n              >\n                {listening ? <SquareIcon className=\"size-3 fill-current\" /> : <MicIcon />}\n              </IconButton>\n            }\n          />\n          <TooltipContent>\n            {unavailable ? (\n              UNSUPPORTED\n            ) : listening ? (\n              <>\n                Stop <Kbd>Esc</Kbd>\n              </>\n            ) : (\n              ariaLabel\n            )}\n          </TooltipContent>\n        </Tooltip>\n      </span>\n      {unavailable ? (\n        <span id={descId} hidden>\n          {UNSUPPORTED}\n        </span>\n      ) : null}\n      {message && !listening ? (\n        <span role=\"alert\" className=\"text-xs text-fg-muted\">\n          {message}\n        </span>\n      ) : null}\n    </span>\n  )\n}\n\nexport { SpeechInput }\nexport type { SpeechInputProps }\n"
    }
  ],
  "categories": [
    "ai-chat"
  ],
  "docs": "import { SpeechInput } from \"@/components/ui/speech-input\"\nNeeds the MiniDev tokens stylesheet (https://ui.minidev.pro/r/styles.css) imported after Tailwind.\nDocs: https://ui.minidev.pro/docs/speech-input · Markdown for agents: https://ui.minidev.pro/docs/speech-input.md",
  "meta": {
    "tier": "free",
    "kind": "ui",
    "category": "ai-chat",
    "import": "@/components/ui/speech-input",
    "npmImport": "minidev-ui-kit/ui/speech-input",
    "exports": [
      "SpeechInput"
    ],
    "related": [
      "prompt-input",
      "ai-composer",
      "audio-recorder"
    ],
    "docsUrl": "https://ui.minidev.pro/docs/speech-input",
    "markdownUrl": "https://ui.minidev.pro/docs/speech-input.md",
    "keywords": [
      "react speech to text",
      "voice input button react",
      "web speech api react"
    ]
  }
}
