{
  "schemaVersion": 1,
  "target": "react",
  "name": "voice-input",
  "version": "0.1.0",
  "category": "ai-elements",
  "title": "Voice Input",
  "description": "Dictation for a prompt: a mic that asks for permission, a live waveform with an elapsed timer while listening, cancel and finish, and a transcribing state whose waveform settles into dots and fades into the transcript.",
  "tags": [
    "ai",
    "agent",
    "voice",
    "dictation",
    "speech",
    "microphone",
    "waveform",
    "composer"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {},
  "registryDependencies": [],
  "docsPath": "/components/voice-input",
  "props": [
    {
      "name": "source",
      "type": "\"microphone\" | \"external\" | \"simulated\"",
      "default": "\"external\" when level is set, else \"microphone\"",
      "description": "Where the waveform level comes from: the device through a Web Audio AnalyserNode, your own level prop, or a speech-like simulation for demos."
    },
    {
      "name": "level",
      "type": "number",
      "description": "Audio level from 0 to 1 when you run the audio pipeline yourself."
    },
    {
      "name": "transcribe",
      "type": "(recording: { audio: Blob | null; durationMs: number }) => Promise<string>",
      "description": "Turns the recording into text. Without it, finishing returns to idle."
    },
    {
      "name": "onTranscript",
      "type": "(text: string) => void",
      "description": "Called with the text once transcribe resolves."
    },
    {
      "name": "onRecordingComplete",
      "type": "(recording) => void",
      "description": "Called when the user finishes a recording, with the audio Blob from MediaRecorder when available."
    },
    {
      "name": "onCancel",
      "type": "() => void",
      "description": "Called when the user cancels recording or transcription."
    },
    {
      "name": "status / onStatusChange",
      "type": "\"idle\" | \"requesting\" | \"listening\" | \"processing\" | \"done\" | \"error\"",
      "description": "Controls the state. Leave status unset to let the component run its own flow."
    },
    {
      "name": "transcript",
      "type": "string",
      "description": "Text shown in the done state. Defaults to what transcribe returned."
    },
    {
      "name": "error / errorMessage",
      "type": "\"permission-denied\" | \"no-microphone\" | \"unsupported\" | \"failed\" / string",
      "description": "Which error to show, and an optional sentence that replaces the default."
    },
    {
      "name": "maxDuration",
      "type": "number",
      "default": "120",
      "description": "Seconds before recording stops and transcribes on its own. The timer turns amber in the last 10 seconds."
    },
    {
      "name": "placeholder",
      "type": "string",
      "default": "\"Tap the mic to dictate\"",
      "description": "Hint shown while idle."
    },
    {
      "name": "label",
      "type": "string",
      "default": "\"Voice input\"",
      "description": "Accessible name of the control group."
    }
  ],
  "accessibility": [
    "The control is a labelled group. One primary button keeps focus through every state, and its name changes with it: Start dictation, Waiting for microphone, Stop and transcribe, Transcribing, Record again, Try again.",
    "While the microphone is pending or transcription runs, the primary button is aria-disabled and aria-busy rather than disabled, so focus is not lost.",
    "Cancel is a labelled button, and Escape cancels while requesting, listening, or transcribing; focus returns to the primary button.",
    "A polite status region announces Listening, Transcribing, and the finished transcript; errors use role=\"alert\". The elapsed time is a role=\"timer\", which is not announced every second.",
    "The waveform is decorative (aria-hidden). The microphone opens only after the user presses the button.",
    "With reduced motion the waveform stops scrolling and updates in place at half the rate, the transcribing wave and spinner hold still, and the transcript appears without the word fade."
  ],
  "states": [
    "idle",
    "requesting",
    "listening",
    "processing",
    "done",
    "permission-denied",
    "no-microphone",
    "error"
  ],
  "files": [
    {
      "path": "agent/voice-input.tsx",
      "content": "\"use client\";\n\nimport { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from \"react\";\n\nfunction cx(...classes: Array<string | false | null | undefined>) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nconst ease = \"ease-[cubic-bezier(0.23,1,0.32,1)]\";\nconst stroke = { fill: \"none\", stroke: \"currentColor\", strokeWidth: 1.5, strokeLinecap: \"round\", strokeLinejoin: \"round\" } as const;\n\nexport type VoiceInputStatus = \"idle\" | \"requesting\" | \"listening\" | \"processing\" | \"done\" | \"error\";\nexport type VoiceInputError = \"permission-denied\" | \"no-microphone\" | \"unsupported\" | \"failed\";\n/** microphone opens the device through Web Audio; external reads `level`; simulated plays a speech-like level for demos. */\nexport type VoiceInputSource = \"microphone\" | \"external\" | \"simulated\";\n\n/** What the recording produced. `audio` is null when the source is not the microphone or MediaRecorder is missing. */\nexport interface VoiceRecording {\n  audio: Blob | null;\n  durationMs: number;\n}\n\nexport interface VoiceInputProps {\n  /** Controls the state. Leave unset to let the component run its own flow. */\n  status?: VoiceInputStatus;\n  onStatusChange?: (status: VoiceInputStatus) => void;\n  /** Where the waveform's level comes from. @default \"external\" when `level` is set, otherwise \"microphone\" */\n  source?: VoiceInputSource;\n  /** Audio level from 0 to 1, for an audio pipeline you run yourself. */\n  level?: number;\n  /** Turns the recording into text. Without it, finishing returns to idle after `onRecordingComplete`. */\n  transcribe?: (recording: VoiceRecording) => Promise<string>;\n  /** Called with the text once `transcribe` resolves. */\n  onTranscript?: (text: string) => void;\n  /** Called when the user finishes a recording, before transcribing. */\n  onRecordingComplete?: (recording: VoiceRecording) => void;\n  onCancel?: () => void;\n  /** Text shown in the done state. Defaults to what `transcribe` returned. */\n  transcript?: string;\n  /** Which error to show in the error state. */\n  error?: VoiceInputError;\n  /** Replaces the default error sentence. */\n  errorMessage?: string;\n  /** Recording stops and transcribes on its own after this many seconds. @default 120 */\n  maxDuration?: number;\n  /** Hint shown while idle. @default \"Tap the mic to dictate\" */\n  placeholder?: string;\n  /** Names the control for screen readers. @default \"Voice input\" */\n  label?: string;\n  className?: string;\n}\n\nconst BARS = 56;\nconst PITCH = 5; // bar width 3px + gap 2px\nconst STEP_MS = 70; // a new bar enters every 70ms\nconst REST = 0.09; // a resting bar is a 2px dot in a 24px box\n\nconst errorText: Record<VoiceInputError, string> = {\n  \"permission-denied\": \"Microphone access is blocked. Allow it in site settings.\",\n  \"no-microphone\": \"No microphone found. Connect one and try again.\",\n  unsupported: \"This browser can't record audio.\",\n  failed: \"Couldn't transcribe that. Try again.\",\n};\n\ninterface AudioRig {\n  stream: MediaStream;\n  context: AudioContext;\n  analyser: AnalyserNode;\n  data: Uint8Array<ArrayBuffer>;\n  recorder: MediaRecorder | null;\n  chunks: Blob[];\n}\n\nfunction errorKind(error: unknown): VoiceInputError {\n  const name = error instanceof Error || error instanceof DOMException ? error.name : \"\";\n  if (name === \"NotAllowedError\" || name === \"SecurityError\" || name === \"PermissionDeniedError\") return \"permission-denied\";\n  if (name === \"NotFoundError\" || name === \"DevicesNotFoundError\" || name === \"OverconstrainedError\") return \"no-microphone\";\n  return \"failed\";\n}\n\n/** A speech-like level: syllables inside phrases, with short pauses between them. */\nfunction simulatedLevel(seconds: number) {\n  const phrase = Math.sin(seconds * 0.9) + Math.sin(seconds * 0.37 + 2);\n  if (phrase < -0.7) return 0.02 + Math.random() * 0.03;\n  const syllable = Math.abs(Math.sin(seconds * 9.5)) * (0.55 + 0.45 * Math.sin(seconds * 2.3 + 1));\n  return Math.min(1, 0.1 + syllable * 0.75 + Math.random() * 0.12);\n}\n\nfunction formatClock(ms: number) {\n  const total = Math.max(0, Math.floor(ms / 1000));\n  return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, \"0\")}`;\n}\n\nfunction prefersReducedMotion() {\n  return typeof window !== \"undefined\" && window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n}\n\n/**\n * Dictation for a prompt. The mic asks for permission, then a waveform scrolls with the live level\n * from a Web Audio AnalyserNode next to an elapsed timer, with cancel and finish. While transcribing\n * the bars settle into a row of dots, and when the text arrives they fade out as the words fade in.\n * Feed your own level, or run a simulated one for demos.\n */\nexport function VoiceInput({\n  status: statusProp,\n  onStatusChange,\n  source: sourceProp,\n  level,\n  transcribe,\n  onTranscript,\n  onRecordingComplete,\n  onCancel,\n  transcript: transcriptProp,\n  error: errorProp,\n  errorMessage,\n  maxDuration = 120,\n  placeholder = \"Tap the mic to dictate\",\n  label = \"Voice input\",\n  className,\n}: VoiceInputProps) {\n  const source: VoiceInputSource = sourceProp ?? (level !== undefined ? \"external\" : \"microphone\");\n  const [innerStatus, setInnerStatus] = useState<VoiceInputStatus>(\"idle\");\n  const [innerError, setInnerError] = useState<VoiceInputError>(\"failed\");\n  const [innerTranscript, setInnerTranscript] = useState(\"\");\n  const status = statusProp ?? innerStatus;\n  const errorKindShown = errorProp ?? innerError;\n  const transcript = transcriptProp ?? innerTranscript;\n\n  const rootRef = useRef<HTMLDivElement>(null);\n  const trackRef = useRef<HTMLDivElement>(null);\n  const clockRef = useRef<HTMLSpanElement>(null);\n  const primaryRef = useRef<HTMLButtonElement>(null);\n  const rigRef = useRef<AudioRig | null>(null);\n  const runRef = useRef(0);\n  const startedRef = useRef(0);\n  const levelRef = useRef(level);\n  levelRef.current = level;\n\n  const latest = useRef({ onStatusChange, statusProp, status });\n  latest.current = { onStatusChange, statusProp, status };\n\n  function setStatus(next: VoiceInputStatus) {\n    if (latest.current.statusProp === undefined) setInnerStatus(next);\n    latest.current.onStatusChange?.(next);\n  }\n\n  function fail(kind: VoiceInputError) {\n    setInnerError(kind);\n    setStatus(\"error\");\n  }\n\n  function release() {\n    const rig = rigRef.current;\n    if (!rig) return;\n    rigRef.current = null;\n    if (rig.recorder && rig.recorder.state !== \"inactive\") rig.recorder.stop();\n    rig.stream.getTracks().forEach((track) => track.stop());\n    void rig.context.close().catch(() => {});\n  }\n\n  /** Stops the recorder, waits for its last chunk, then releases the microphone. */\n  function finishRecording(): Promise<Blob | null> {\n    const rig = rigRef.current;\n    const recorder = rig?.recorder;\n    if (!rig || !recorder || recorder.state === \"inactive\") {\n      release();\n      return Promise.resolve(null);\n    }\n    return new Promise((resolve) => {\n      recorder.addEventListener(\n        \"stop\",\n        () => {\n          const blob = rig.chunks.length ? new Blob(rig.chunks, { type: recorder.mimeType || \"audio/webm\" }) : null;\n          release();\n          resolve(blob);\n        },\n        { once: true },\n      );\n      recorder.stop();\n    });\n  }\n\n  function start() {\n    runRef.current++;\n    setInnerTranscript(\"\");\n    setStatus(\"requesting\");\n  }\n\n  function cancel() {\n    runRef.current++;\n    release();\n    setStatus(\"idle\");\n    onCancel?.();\n    primaryRef.current?.focus();\n  }\n\n  async function finish() {\n    if (latest.current.status !== \"listening\") return;\n    const run = ++runRef.current;\n    const durationMs = performance.now() - startedRef.current;\n    const audio = await finishRecording();\n    if (run !== runRef.current) return;\n    const recording = { audio, durationMs };\n    onRecordingComplete?.(recording);\n    if (!transcribe) {\n      setStatus(\"idle\");\n      return;\n    }\n    setStatus(\"processing\");\n    try {\n      const text = await transcribe(recording);\n      if (run !== runRef.current) return;\n      setInnerTranscript(text);\n      onTranscript?.(text);\n      setStatus(\"done\");\n    } catch {\n      if (run === runRef.current) fail(\"failed\");\n    }\n  }\n\n  const finishRef = useRef(finish);\n  finishRef.current = finish;\n\n  // Ask for the microphone (or skip ahead for external and simulated levels).\n  useEffect(() => {\n    if (status !== \"requesting\") return;\n    let cancelled = false;\n    if (source !== \"microphone\") {\n      const timer = setTimeout(() => !cancelled && setStatus(\"listening\"), source === \"simulated\" ? 500 : 0);\n      return () => {\n        cancelled = true;\n        clearTimeout(timer);\n      };\n    }\n    if (typeof navigator === \"undefined\" || !navigator.mediaDevices?.getUserMedia) {\n      fail(\"unsupported\");\n      return;\n    }\n    navigator.mediaDevices.getUserMedia({ audio: true }).then(\n      (stream) => {\n        if (cancelled) {\n          stream.getTracks().forEach((track) => track.stop());\n          return;\n        }\n        try {\n          const AudioCtor = window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;\n          const context = new AudioCtor();\n          const analyser = context.createAnalyser();\n          analyser.fftSize = 1024;\n          context.createMediaStreamSource(stream).connect(analyser);\n          let recorder: MediaRecorder | null = null;\n          const chunks: Blob[] = [];\n          if (typeof MediaRecorder !== \"undefined\") {\n            recorder = new MediaRecorder(stream);\n            recorder.addEventListener(\"dataavailable\", (event) => event.data.size && chunks.push(event.data));\n            recorder.start();\n          }\n          rigRef.current = { stream, context, analyser, data: new Uint8Array(analyser.fftSize), recorder, chunks };\n          setStatus(\"listening\");\n        } catch {\n          stream.getTracks().forEach((track) => track.stop());\n          fail(\"unsupported\");\n        }\n      },\n      (reason) => !cancelled && fail(errorKind(reason)),\n    );\n    return () => {\n      cancelled = true;\n    };\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [status, source]);\n\n  // Release the microphone whenever the flow leaves recording, and on unmount.\n  useEffect(() => {\n    if (status !== \"requesting\" && status !== \"listening\") release();\n  }, [status]);\n  useEffect(() => () => release(), []);\n\n  // The waveform: written straight to the DOM each frame, so React does not re-render at 60fps.\n  useEffect(() => {\n    const track = trackRef.current;\n    if (!track) return;\n    const bars = Array.from(track.children) as HTMLElement[];\n    const reduce = prefersReducedMotion();\n    bars.forEach((bar) => bar.getAnimations().forEach((animation) => animation.cancel()));\n\n    if (status === \"listening\") {\n      const history = new Float32Array(BARS);\n      const startedAt = performance.now();\n      startedRef.current = startedAt;\n      let last = startedAt;\n      let acc = 0;\n      let smooth = 0;\n      let raf = 0;\n      const scale = (value: number) => `scaleY(${REST + (1 - REST) * Math.pow(Math.min(1, value), 0.75)})`;\n      bars.forEach((bar) => {\n        bar.style.opacity = \"1\";\n        bar.style.transform = scale(0);\n      });\n\n      const frame = (now: number) => {\n        const dt = now - last;\n        last = now;\n        let raw = 0;\n        const rig = rigRef.current;\n        if (levelRef.current !== undefined) raw = levelRef.current;\n        else if (source === \"simulated\") raw = simulatedLevel((now - startedAt) / 1000);\n        else if (rig) {\n          rig.analyser.getByteTimeDomainData(rig.data);\n          let sum = 0;\n          for (const sample of rig.data) sum += ((sample - 128) / 128) ** 2;\n          raw = Math.min(1, Math.sqrt(sum / rig.data.length) * 4);\n        }\n        // Fast attack, slow release, like a VU needle.\n        smooth += (raw - smooth) * (raw > smooth ? 0.45 : 0.12);\n        acc += dt;\n        const step = reduce ? STEP_MS * 2 : STEP_MS;\n        if (acc >= step) {\n          acc %= step;\n          history.copyWithin(0, 1);\n          history[BARS - 1] = smooth;\n          for (let i = 0; i < BARS - 1; i++) bars[i]!.style.transform = scale(history[i]!);\n        }\n        bars[BARS - 1]!.style.transform = scale(smooth);\n        track.style.transform = reduce ? \"\" : `translateX(${(-acc / step) * PITCH}px)`;\n        const elapsed = now - startedAt;\n        if (clockRef.current) {\n          clockRef.current.textContent = formatClock(elapsed);\n          clockRef.current.dataset.near = elapsed >= (maxDuration - 10) * 1000 ? \"true\" : \"false\";\n        }\n        if (elapsed >= maxDuration * 1000) {\n          void finishRef.current();\n          return;\n        }\n        raf = requestAnimationFrame(frame);\n      };\n      raf = requestAnimationFrame(frame);\n      return () => cancelAnimationFrame(raf);\n    }\n\n    track.style.transform = \"\";\n    if (status === \"processing\") {\n      // Bars settle into dots, then a slow wave travels along them while the text is on its way.\n      bars.forEach((bar, i) => {\n        bar.style.opacity = \"1\";\n        bar.style.transform = `scaleY(${REST})`;\n        if (!reduce) {\n          bar.animate([{ transform: `scaleY(${REST})` }, { transform: \"scaleY(0.34)\" }, { transform: `scaleY(${REST})` }], {\n            duration: 1300,\n            delay: 280 + i * 22,\n            iterations: Infinity,\n            easing: \"cubic-bezier(0.45,0,0.55,1)\",\n          });\n        }\n      });\n    } else if (status === \"done\") {\n      // The dots go out left to right as the words come in.\n      bars.forEach((bar, i) => {\n        bar.style.transform = `scaleY(${REST})`;\n        bar.style.opacity = \"0\";\n        if (!reduce) bar.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 220, delay: i * 6, easing: \"ease-out\", fill: \"backwards\" });\n      });\n    } else {\n      bars.forEach((bar) => {\n        bar.style.transform = `scaleY(${REST})`;\n        bar.style.opacity = \"1\";\n      });\n    }\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [status, source, maxDuration]);\n\n  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {\n    if (event.key === \"Escape\" && (status === \"requesting\" || status === \"listening\" || status === \"processing\")) {\n      event.preventDefault();\n      cancel();\n    }\n  }\n\n  const recording = status === \"requesting\" || status === \"listening\";\n  const busy = status === \"requesting\" || status === \"processing\";\n  const wave = status === \"listening\" || status === \"processing\" || status === \"done\";\n  const secondaryLabel =\n    status === \"processing\" ? \"Cancel transcription\" : status === \"done\" ? \"Clear transcript\" : status === \"error\" ? \"Dismiss\" : \"Cancel recording\";\n  const primaryLabel =\n    status === \"requesting\"\n      ? \"Waiting for microphone\"\n      : status === \"listening\"\n        ? transcribe\n          ? \"Stop and transcribe\"\n          : \"Finish recording\"\n        : status === \"processing\"\n          ? \"Transcribing\"\n          : status === \"done\"\n            ? \"Record again\"\n            : status === \"error\"\n              ? \"Try again\"\n              : \"Start dictation\";\n  const announcement =\n    status === \"requesting\"\n      ? \"Waiting for microphone access\"\n      : status === \"listening\"\n        ? \"Listening\"\n        : status === \"processing\"\n          ? \"Transcribing\"\n          : status === \"done\"\n            ? `Transcript ready: ${transcript}`\n            : \"\";\n  const words = transcript.split(/(\\s+)/).filter(Boolean);\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"group\"\n      aria-label={label}\n      data-status={status}\n      onKeyDown={onKeyDown}\n      className={cx(\n        \"relative flex min-h-12 w-full max-w-md items-center gap-1 rounded-xl border p-2 text-sm\",\n        \"bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]\",\n        \"transition-[border-color,background-color] duration-200 ease-out motion-reduce:transition-none\",\n        status === \"error\"\n          ? \"border-red-500/35 bg-red-500/[0.04] dark:bg-red-500/[0.06]\"\n          : recording || status === \"processing\"\n            ? \"border-zinc-950/15 dark:border-white/20\"\n            : \"border-zinc-950/10 dark:border-white/10\",\n        className,\n      )}\n    >\n      <span role=\"status\" className=\"sr-only\">\n        {announcement}\n      </span>\n\n      {status !== \"idle\" ? (\n        <button\n          type=\"button\"\n          aria-label={secondaryLabel}\n          onClick={status === \"done\" || status === \"error\" ? () => { setStatus(\"idle\"); primaryRef.current?.focus(); } : cancel}\n          className={cx(\n            \"inline-flex size-8 shrink-0 cursor-pointer items-center justify-center self-start rounded-full text-zinc-500\",\n            \"transition-[background-color,color,opacity,scale] duration-200 starting:scale-90 starting:opacity-0 active:scale-[0.94] active:duration-100 motion-reduce:transition-none\",\n            ease,\n            \"hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white\",\n            \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n          )}\n        >\n          <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" {...stroke} className=\"size-4\">\n            <path d=\"M4.75 4.75l6.5 6.5M11.25 4.75l-6.5 6.5\" />\n          </svg>\n        </button>\n      ) : null}\n\n      {/* Every state's middle content shares one grid cell, so they cross-fade in place. */}\n      <div className=\"grid min-w-0 flex-1 grid-cols-1 items-center self-stretch [&>*]:col-start-1 [&>*]:row-start-1\">\n        <Layer show={status === \"idle\"} className=\"pl-2 text-zinc-500\">\n          {placeholder}\n        </Layer>\n\n        <Layer show={status === \"requesting\"} className=\"flex items-center gap-2 pl-1 text-zinc-600 dark:text-zinc-400\">\n          Allow microphone access\n        </Layer>\n\n        <div\n          aria-hidden=\"true\"\n          className={cx(\n            \"mt-1 flex min-w-0 items-center gap-2.5 self-start pl-1\",\n            \"transition-opacity duration-200 ease-out motion-reduce:transition-none\",\n            wave ? \"opacity-100\" : \"pointer-events-none opacity-0\",\n          )}\n        >\n          <div className=\"relative h-6 min-w-0 flex-1 overflow-hidden [mask-image:linear-gradient(to_right,transparent,#000_28%)]\">\n            <div ref={trackRef} className=\"absolute top-0 -right-[5px] flex h-6 items-center gap-[2px] will-change-transform\">\n              {Array.from({ length: BARS }, (_, i) => (\n                <span\n                  key={i}\n                  className={cx(\n                    \"block h-6 w-[3px] shrink-0 rounded-full bg-zinc-950 dark:bg-white\",\n                    status === \"listening\" ? \"\" : \"transition-transform duration-300 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none\",\n                  )}\n                  style={{ transform: `scaleY(${REST})` }}\n                />\n              ))}\n            </div>\n          </div>\n          {status === \"listening\" ? (\n            <span className=\"flex shrink-0 items-center gap-1.5 font-mono text-xs text-zinc-600 tabular-nums dark:text-zinc-400\">\n              <span aria-hidden=\"true\" className=\"size-1.5 rounded-full bg-red-500\" />\n              <span ref={clockRef} role=\"timer\" className=\"data-[near=true]:text-amber-600 dark:data-[near=true]:text-amber-400\">\n                0:00\n              </span>\n            </span>\n          ) : status === \"processing\" ? (\n            <span className=\"shrink-0 pr-1 text-xs text-zinc-500\">Transcribing…</span>\n          ) : null}\n        </div>\n\n        {status === \"done\" ? (\n          <p className=\"min-w-0 py-1 pl-1 leading-6 text-pretty text-zinc-950 dark:text-white\">\n            {words.map((word, i) => (\n              <span\n                key={i}\n                className={cx(\n                  \"transition-[opacity,filter,translate] duration-300 starting:translate-y-0.5 starting:opacity-0 starting:blur-[3px] motion-reduce:transition-none\",\n                  ease,\n                )}\n                style={{ transitionDelay: `${Math.min(i, 40) * 14}ms` }}\n              >\n                {word}\n              </span>\n            ))}\n          </p>\n        ) : null}\n\n        {status === \"error\" ? (\n          <p role=\"alert\" className=\"py-1 pl-1 leading-6 text-red-600 dark:text-red-400\">\n            {errorMessage ?? errorText[errorKindShown]}\n          </p>\n        ) : null}\n      </div>\n\n      <button\n        ref={primaryRef}\n        type=\"button\"\n        aria-label={primaryLabel}\n        aria-disabled={busy || undefined}\n        aria-busy={busy || undefined}\n        onClick={() => {\n          if (busy) return;\n          if (status === \"listening\") void finish();\n          else start();\n        }}\n        className={cx(\n          \"relative inline-grid size-8 shrink-0 cursor-pointer place-items-center self-start rounded-full [&>*]:col-start-1 [&>*]:row-start-1\",\n          \"transition-[background-color,color,border-color,box-shadow,scale] duration-150 ease-out active:duration-100 motion-reduce:transition-none\",\n          \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500 aria-disabled:cursor-default\",\n          status === \"listening\"\n            ? \"bg-zinc-950 text-white shadow-[inset_0_1px_0_rgb(255_255_255/0.12),0_1px_2px_rgb(0_0_0/0.2)] hover:bg-zinc-800 motion-safe:active:scale-[0.94] dark:bg-white dark:text-black dark:shadow-[inset_0_-1px_0_rgb(0_0_0/0.12)] dark:hover:bg-zinc-200\"\n            : status === \"requesting\"\n              ? \"text-sky-600 shadow-[inset_0_0_0_1px_rgb(14_165_233/0.4)] dark:text-sky-400\"\n              : busy\n                ? \"text-zinc-500 shadow-[inset_0_0_0_1px_rgb(9_9_11/0.1)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.12)]\"\n                : \"text-zinc-700 shadow-[inset_0_0_0_1px_rgb(9_9_11/0.12)] hover:bg-zinc-950/[0.04] hover:text-zinc-950 motion-safe:active:scale-[0.94] dark:text-zinc-300 dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.16)] dark:hover:bg-white/[0.06] dark:hover:text-white\",\n        )}\n      >\n        <Glyph show={status === \"idle\" || status === \"requesting\" || status === \"done\"}>\n          <path d=\"M8 2.25a2 2 0 0 0-2 2v3.5a2 2 0 1 0 4 0v-3.5a2 2 0 0 0-2-2Z\" />\n          <path d=\"M4.25 7.5a3.75 3.75 0 0 0 7.5 0M8 11.25v2.5\" />\n        </Glyph>\n        <Glyph show={status === \"listening\"}>\n          <path d=\"m3.75 8.25 2.75 2.75 5.75-6\" />\n        </Glyph>\n        <Glyph show={status === \"processing\"} spin>\n          <path d=\"M8 2.5a5.5 5.5 0 1 1-5.5 5.5\" />\n        </Glyph>\n        <Glyph show={status === \"error\"}>\n          <path d=\"M12.5 8a4.5 4.5 0 1 1-1.32-3.18M12.5 2.75v2.5H10\" />\n        </Glyph>\n      </button>\n    </div>\n  );\n}\n\nfunction Layer({ show, className, children }: { show: boolean; className?: string; children: ReactNode }) {\n  return (\n    <span\n      aria-hidden={!show || undefined}\n      className={cx(\n        \"min-w-0 truncate transition-[opacity,translate] duration-200 motion-reduce:transition-none\",\n        ease,\n        show ? \"translate-y-0 opacity-100\" : \"pointer-events-none translate-y-1 opacity-0\",\n        className,\n      )}\n    >\n      {children}\n    </span>\n  );\n}\n\n/** Icons stacked in one cell; the active one scales in from 0.9 as the others fade. */\nfunction Glyph({ show, spin = false, children }: { show: boolean; spin?: boolean; children: ReactNode }) {\n  return (\n    <svg\n      aria-hidden=\"true\"\n      viewBox=\"0 0 16 16\"\n      {...stroke}\n      className={cx(\n        \"size-4 transition-[opacity,scale] duration-200 motion-reduce:transition-none\",\n        ease,\n        show ? \"scale-100 opacity-100\" : \"scale-90 opacity-0\",\n        spin && \"motion-safe:animate-spin\",\n      )}\n    >\n      {children}\n    </svg>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { VoiceInput } from \"@/components/shaken/agent/voice-input\";\n\n// Swap in your speech-to-text call. The recording carries the audio Blob from the microphone.\nasync function transcribe() {\n  await new Promise((resolve) => setTimeout(resolve, 1400));\n  return \"Summarize the open pull requests and flag anything that blocks Friday's release.\";\n}\n\nexport default function VoiceInputExample() {\n  const [prompt, setPrompt] = useState(\"\");\n\n  return (\n    <div className=\"grid w-full max-w-md gap-3\">\n      {/* simulated plays a speech-like level, so the demo needs no microphone. Use \"microphone\" in your app. */}\n      <VoiceInput source=\"simulated\" transcribe={transcribe} onTranscript={setPrompt} />\n      <p className=\"px-1 text-xs text-zinc-500\">{prompt ? `Prompt: ${prompt}` : \"The transcript goes into your prompt.\"}</p>\n    </div>\n  );\n}\n"
  }
}
