Skip to content
Shaken UI
Sign in

Voice Input

Save

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.

Category
AI elements
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Voice Input preview
Tap the mic to dictate

Press the mic, talk or not, then finish to see the waveform turn into text. Escape cancels.

Installation

npx @shakenui/cli add voice-input

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add voice-input --dry-run

Usage

voice-input-example.tsx
"use client";

import { useState } from "react";
import { VoiceInput } from "@/components/shaken/agent/voice-input";

// Swap in your speech-to-text call. The recording carries the audio Blob from the microphone.
async function transcribe() {
  await new Promise((resolve) => setTimeout(resolve, 1400));
  return "Summarize the open pull requests and flag anything that blocks Friday's release.";
}

export default function VoiceInputExample() {
  const [prompt, setPrompt] = useState("");

  return (
    <div className="grid w-full max-w-md gap-3">
      {/* simulated plays a speech-like level, so the demo needs no microphone. Use "microphone" in your app. */}
      <VoiceInput source="simulated" transcribe={transcribe} onTranscript={setPrompt} />
      <p className="px-1 text-xs text-zinc-500">{prompt ? `Prompt: ${prompt}` : "The transcript goes into your prompt."}</p>
    </div>
  );
}

States

Every state, rendered from local fixture data.

Voice Input states
Idle
Tap the mic to dictate
Requesting permission
Waiting for microphone access
Allow microphone access
Listening
Listening
Transcribing
Transcribing
Transcribed
Transcript ready: Move the standup to 10:30 and tell the design team.

Move the standup to 10:30 and tell the design team.

Permission denied
No microphone

API

PropTypeDefaultDescription
source"microphone" | "external" | "simulated""external" when level is set, else "microphone"Where the waveform level comes from: the device through a Web Audio AnalyserNode, your own level prop, or a speech-like simulation for demos.
levelnumber—Audio level from 0 to 1 when you run the audio pipeline yourself.
transcribe(recording: { audio: Blob | null; durationMs: number }) => Promise<string>—Turns the recording into text. Without it, finishing returns to idle.
onTranscript(text: string) => void—Called with the text once transcribe resolves.
onRecordingComplete(recording) => void—Called when the user finishes a recording, with the audio Blob from MediaRecorder when available.
onCancel() => void—Called when the user cancels recording or transcription.
status / onStatusChange"idle" | "requesting" | "listening" | "processing" | "done" | "error"—Controls the state. Leave status unset to let the component run its own flow.
transcriptstring—Text shown in the done state. Defaults to what transcribe returned.
error / errorMessage"permission-denied" | "no-microphone" | "unsupported" | "failed" / string—Which error to show, and an optional sentence that replaces the default.
maxDurationnumber120Seconds before recording stops and transcribes on its own. The timer turns amber in the last 10 seconds.
placeholderstring"Tap the mic to dictate"Hint shown while idle.
labelstring"Voice input"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.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/agent/voice-input.tsxvoice-input
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/voice-input/0.1.0.json.

agent/voice-input.tsxShow
agent/voice-input.tsx
"use client";

import { type KeyboardEvent, type ReactNode, useEffect, useRef, useState } from "react";

function cx(...classes: Array<string | false | null | undefined>) {
  return classes.filter(Boolean).join(" ");
}

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
const stroke = { fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" } as const;

export type VoiceInputStatus = "idle" | "requesting" | "listening" | "processing" | "done" | "error";
export type VoiceInputError = "permission-denied" | "no-microphone" | "unsupported" | "failed";
/** microphone opens the device through Web Audio; external reads `level`; simulated plays a speech-like level for demos. */
export type VoiceInputSource = "microphone" | "external" | "simulated";

/** What the recording produced. `audio` is null when the source is not the microphone or MediaRecorder is missing. */
export interface VoiceRecording {
  audio: Blob | null;
  durationMs: number;
}

export interface VoiceInputProps {
  /** Controls the state. Leave unset to let the component run its own flow. */
  status?: VoiceInputStatus;
  onStatusChange?: (status: VoiceInputStatus) => void;
  /** Where the waveform's level comes from. @default "external" when `level` is set, otherwise "microphone" */
  source?: VoiceInputSource;
  /** Audio level from 0 to 1, for an audio pipeline you run yourself. */
  level?: number;
  /** Turns the recording into text. Without it, finishing returns to idle after `onRecordingComplete`. */
  transcribe?: (recording: VoiceRecording) => Promise<string>;
  /** Called with the text once `transcribe` resolves. */
  onTranscript?: (text: string) => void;
  /** Called when the user finishes a recording, before transcribing. */
  onRecordingComplete?: (recording: VoiceRecording) => void;
  onCancel?: () => void;
  /** Text shown in the done state. Defaults to what `transcribe` returned. */
  transcript?: string;
  /** Which error to show in the error state. */
  error?: VoiceInputError;
  /** Replaces the default error sentence. */
  errorMessage?: string;
  /** Recording stops and transcribes on its own after this many seconds. @default 120 */
  maxDuration?: number;
  /** Hint shown while idle. @default "Tap the mic to dictate" */
  placeholder?: string;
  /** Names the control for screen readers. @default "Voice input" */
  label?: string;
  className?: string;
}

const BARS = 56;
const PITCH = 5; // bar width 3px + gap 2px
const STEP_MS = 70; // a new bar enters every 70ms
const REST = 0.09; // a resting bar is a 2px dot in a 24px box

const errorText: Record<VoiceInputError, string> = {
  "permission-denied": "Microphone access is blocked. Allow it in site settings.",
  "no-microphone": "No microphone found. Connect one and try again.",
  unsupported: "This browser can't record audio.",
  failed: "Couldn't transcribe that. Try again.",
};

interface AudioRig {
  stream: MediaStream;
  context: AudioContext;
  analyser: AnalyserNode;
  data: Uint8Array<ArrayBuffer>;
  recorder: MediaRecorder | null;
  chunks: Blob[];
}

function errorKind(error: unknown): VoiceInputError {
  const name = error instanceof Error || error instanceof DOMException ? error.name : "";
  if (name === "NotAllowedError" || name === "SecurityError" || name === "PermissionDeniedError") return "permission-denied";
  if (name === "NotFoundError" || name === "DevicesNotFoundError" || name === "OverconstrainedError") return "no-microphone";
  return "failed";
}

/** A speech-like level: syllables inside phrases, with short pauses between them. */
function simulatedLevel(seconds: number) {
  const phrase = Math.sin(seconds * 0.9) + Math.sin(seconds * 0.37 + 2);
  if (phrase < -0.7) return 0.02 + Math.random() * 0.03;
  const syllable = Math.abs(Math.sin(seconds * 9.5)) * (0.55 + 0.45 * Math.sin(seconds * 2.3 + 1));
  return Math.min(1, 0.1 + syllable * 0.75 + Math.random() * 0.12);
}

function formatClock(ms: number) {
  const total = Math.max(0, Math.floor(ms / 1000));
  return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
}

function prefersReducedMotion() {
  return typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}

/**
 * Dictation for a prompt. The mic asks for permission, then a waveform scrolls with the live level
 * from a Web Audio AnalyserNode next to an elapsed timer, with cancel and finish. While transcribing
 * the bars settle into a row of dots, and when the text arrives they fade out as the words fade in.
 * Feed your own level, or run a simulated one for demos.
 */
export function VoiceInput({
  status: statusProp,
  onStatusChange,
  source: sourceProp,
  level,
  transcribe,
  onTranscript,
  onRecordingComplete,
  onCancel,
  transcript: transcriptProp,
  error: errorProp,
  errorMessage,
  maxDuration = 120,
  placeholder = "Tap the mic to dictate",
  label = "Voice input",
  className,
}: VoiceInputProps) {
  const source: VoiceInputSource = sourceProp ?? (level !== undefined ? "external" : "microphone");
  const [innerStatus, setInnerStatus] = useState<VoiceInputStatus>("idle");
  const [innerError, setInnerError] = useState<VoiceInputError>("failed");
  const [innerTranscript, setInnerTranscript] = useState("");
  const status = statusProp ?? innerStatus;
  const errorKindShown = errorProp ?? innerError;
  const transcript = transcriptProp ?? innerTranscript;

  const rootRef = useRef<HTMLDivElement>(null);
  const trackRef = useRef<HTMLDivElement>(null);
  const clockRef = useRef<HTMLSpanElement>(null);
  const primaryRef = useRef<HTMLButtonElement>(null);
  const rigRef = useRef<AudioRig | null>(null);
  const runRef = useRef(0);
  const startedRef = useRef(0);
  const levelRef = useRef(level);
  levelRef.current = level;

  const latest = useRef({ onStatusChange, statusProp, status });
  latest.current = { onStatusChange, statusProp, status };

  function setStatus(next: VoiceInputStatus) {
    if (latest.current.statusProp === undefined) setInnerStatus(next);
    latest.current.onStatusChange?.(next);
  }

  function fail(kind: VoiceInputError) {
    setInnerError(kind);
    setStatus("error");
  }

  function release() {
    const rig = rigRef.current;
    if (!rig) return;
    rigRef.current = null;
    if (rig.recorder && rig.recorder.state !== "inactive") rig.recorder.stop();
    rig.stream.getTracks().forEach((track) => track.stop());
    void rig.context.close().catch(() => {});
  }

  /** Stops the recorder, waits for its last chunk, then releases the microphone. */
  function finishRecording(): Promise<Blob | null> {
    const rig = rigRef.current;
    const recorder = rig?.recorder;
    if (!rig || !recorder || recorder.state === "inactive") {
      release();
      return Promise.resolve(null);
    }
    return new Promise((resolve) => {
      recorder.addEventListener(
        "stop",
        () => {
          const blob = rig.chunks.length ? new Blob(rig.chunks, { type: recorder.mimeType || "audio/webm" }) : null;
          release();
          resolve(blob);
        },
        { once: true },
      );
      recorder.stop();
    });
  }

  function start() {
    runRef.current++;
    setInnerTranscript("");
    setStatus("requesting");
  }

  function cancel() {
    runRef.current++;
    release();
    setStatus("idle");
    onCancel?.();
    primaryRef.current?.focus();
  }

  async function finish() {
    if (latest.current.status !== "listening") return;
    const run = ++runRef.current;
    const durationMs = performance.now() - startedRef.current;
    const audio = await finishRecording();
    if (run !== runRef.current) return;
    const recording = { audio, durationMs };
    onRecordingComplete?.(recording);
    if (!transcribe) {
      setStatus("idle");
      return;
    }
    setStatus("processing");
    try {
      const text = await transcribe(recording);
      if (run !== runRef.current) return;
      setInnerTranscript(text);
      onTranscript?.(text);
      setStatus("done");
    } catch {
      if (run === runRef.current) fail("failed");
    }
  }

  const finishRef = useRef(finish);
  finishRef.current = finish;

  // Ask for the microphone (or skip ahead for external and simulated levels).
  useEffect(() => {
    if (status !== "requesting") return;
    let cancelled = false;
    if (source !== "microphone") {
      const timer = setTimeout(() => !cancelled && setStatus("listening"), source === "simulated" ? 500 : 0);
      return () => {
        cancelled = true;
        clearTimeout(timer);
      };
    }
    if (typeof navigator === "undefined" || !navigator.mediaDevices?.getUserMedia) {
      fail("unsupported");
      return;
    }
    navigator.mediaDevices.getUserMedia({ audio: true }).then(
      (stream) => {
        if (cancelled) {
          stream.getTracks().forEach((track) => track.stop());
          return;
        }
        try {
          const AudioCtor = window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
          const context = new AudioCtor();
          const analyser = context.createAnalyser();
          analyser.fftSize = 1024;
          context.createMediaStreamSource(stream).connect(analyser);
          let recorder: MediaRecorder | null = null;
          const chunks: Blob[] = [];
          if (typeof MediaRecorder !== "undefined") {
            recorder = new MediaRecorder(stream);
            recorder.addEventListener("dataavailable", (event) => event.data.size && chunks.push(event.data));
            recorder.start();
          }
          rigRef.current = { stream, context, analyser, data: new Uint8Array(analyser.fftSize), recorder, chunks };
          setStatus("listening");
        } catch {
          stream.getTracks().forEach((track) => track.stop());
          fail("unsupported");
        }
      },
      (reason) => !cancelled && fail(errorKind(reason)),
    );
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [status, source]);

  // Release the microphone whenever the flow leaves recording, and on unmount.
  useEffect(() => {
    if (status !== "requesting" && status !== "listening") release();
  }, [status]);
  useEffect(() => () => release(), []);

  // The waveform: written straight to the DOM each frame, so React does not re-render at 60fps.
  useEffect(() => {
    const track = trackRef.current;
    if (!track) return;
    const bars = Array.from(track.children) as HTMLElement[];
    const reduce = prefersReducedMotion();
    bars.forEach((bar) => bar.getAnimations().forEach((animation) => animation.cancel()));

    if (status === "listening") {
      const history = new Float32Array(BARS);
      const startedAt = performance.now();
      startedRef.current = startedAt;
      let last = startedAt;
      let acc = 0;
      let smooth = 0;
      let raf = 0;
      const scale = (value: number) => `scaleY(${REST + (1 - REST) * Math.pow(Math.min(1, value), 0.75)})`;
      bars.forEach((bar) => {
        bar.style.opacity = "1";
        bar.style.transform = scale(0);
      });

      const frame = (now: number) => {
        const dt = now - last;
        last = now;
        let raw = 0;
        const rig = rigRef.current;
        if (levelRef.current !== undefined) raw = levelRef.current;
        else if (source === "simulated") raw = simulatedLevel((now - startedAt) / 1000);
        else if (rig) {
          rig.analyser.getByteTimeDomainData(rig.data);
          let sum = 0;
          for (const sample of rig.data) sum += ((sample - 128) / 128) ** 2;
          raw = Math.min(1, Math.sqrt(sum / rig.data.length) * 4);
        }
        // Fast attack, slow release, like a VU needle.
        smooth += (raw - smooth) * (raw > smooth ? 0.45 : 0.12);
        acc += dt;
        const step = reduce ? STEP_MS * 2 : STEP_MS;
        if (acc >= step) {
          acc %= step;
          history.copyWithin(0, 1);
          history[BARS - 1] = smooth;
          for (let i = 0; i < BARS - 1; i++) bars[i]!.style.transform = scale(history[i]!);
        }
        bars[BARS - 1]!.style.transform = scale(smooth);
        track.style.transform = reduce ? "" : `translateX(${(-acc / step) * PITCH}px)`;
        const elapsed = now - startedAt;
        if (clockRef.current) {
          clockRef.current.textContent = formatClock(elapsed);
          clockRef.current.dataset.near = elapsed >= (maxDuration - 10) * 1000 ? "true" : "false";
        }
        if (elapsed >= maxDuration * 1000) {
          void finishRef.current();
          return;
        }
        raf = requestAnimationFrame(frame);
      };
      raf = requestAnimationFrame(frame);
      return () => cancelAnimationFrame(raf);
    }

    track.style.transform = "";
    if (status === "processing") {
      // Bars settle into dots, then a slow wave travels along them while the text is on its way.
      bars.forEach((bar, i) => {
        bar.style.opacity = "1";
        bar.style.transform = `scaleY(${REST})`;
        if (!reduce) {
          bar.animate([{ transform: `scaleY(${REST})` }, { transform: "scaleY(0.34)" }, { transform: `scaleY(${REST})` }], {
            duration: 1300,
            delay: 280 + i * 22,
            iterations: Infinity,
            easing: "cubic-bezier(0.45,0,0.55,1)",
          });
        }
      });
    } else if (status === "done") {
      // The dots go out left to right as the words come in.
      bars.forEach((bar, i) => {
        bar.style.transform = `scaleY(${REST})`;
        bar.style.opacity = "0";
        if (!reduce) bar.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 220, delay: i * 6, easing: "ease-out", fill: "backwards" });
      });
    } else {
      bars.forEach((bar) => {
        bar.style.transform = `scaleY(${REST})`;
        bar.style.opacity = "1";
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [status, source, maxDuration]);

  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
    if (event.key === "Escape" && (status === "requesting" || status === "listening" || status === "processing")) {
      event.preventDefault();
      cancel();
    }
  }

  const recording = status === "requesting" || status === "listening";
  const busy = status === "requesting" || status === "processing";
  const wave = status === "listening" || status === "processing" || status === "done";
  const secondaryLabel =
    status === "processing" ? "Cancel transcription" : status === "done" ? "Clear transcript" : status === "error" ? "Dismiss" : "Cancel recording";
  const primaryLabel =
    status === "requesting"
      ? "Waiting for microphone"
      : status === "listening"
        ? transcribe
          ? "Stop and transcribe"
          : "Finish recording"
        : status === "processing"
          ? "Transcribing"
          : status === "done"
            ? "Record again"
            : status === "error"
              ? "Try again"
              : "Start dictation";
  const announcement =
    status === "requesting"
      ? "Waiting for microphone access"
      : status === "listening"
        ? "Listening"
        : status === "processing"
          ? "Transcribing"
          : status === "done"
            ? `Transcript ready: ${transcript}`
            : "";
  const words = transcript.split(/(\s+)/).filter(Boolean);

  return (
    <div
      ref={rootRef}
      role="group"
      aria-label={label}
      data-status={status}
      onKeyDown={onKeyDown}
      className={cx(
        "relative flex min-h-12 w-full max-w-md items-center gap-1 rounded-xl border p-2 text-sm",
        "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)]",
        "transition-[border-color,background-color] duration-200 ease-out motion-reduce:transition-none",
        status === "error"
          ? "border-red-500/35 bg-red-500/[0.04] dark:bg-red-500/[0.06]"
          : recording || status === "processing"
            ? "border-zinc-950/15 dark:border-white/20"
            : "border-zinc-950/10 dark:border-white/10",
        className,
      )}
    >
      <span role="status" className="sr-only">
        {announcement}
      </span>

      {status !== "idle" ? (
        <button
          type="button"
          aria-label={secondaryLabel}
          onClick={status === "done" || status === "error" ? () => { setStatus("idle"); primaryRef.current?.focus(); } : cancel}
          className={cx(
            "inline-flex size-8 shrink-0 cursor-pointer items-center justify-center self-start rounded-full text-zinc-500",
            "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",
            ease,
            "hover:bg-zinc-950/[0.05] hover:text-zinc-950 dark:hover:bg-white/[0.08] dark:hover:text-white",
            "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
          )}
        >
          <svg aria-hidden="true" viewBox="0 0 16 16" {...stroke} className="size-4">
            <path d="M4.75 4.75l6.5 6.5M11.25 4.75l-6.5 6.5" />
          </svg>
        </button>
      ) : null}

      {/* Every state's middle content shares one grid cell, so they cross-fade in place. */}
      <div className="grid min-w-0 flex-1 grid-cols-1 items-center self-stretch [&>*]:col-start-1 [&>*]:row-start-1">
        <Layer show={status === "idle"} className="pl-2 text-zinc-500">
          {placeholder}
        </Layer>

        <Layer show={status === "requesting"} className="flex items-center gap-2 pl-1 text-zinc-600 dark:text-zinc-400">
          Allow microphone access
        </Layer>

        <div
          aria-hidden="true"
          className={cx(
            "mt-1 flex min-w-0 items-center gap-2.5 self-start pl-1",
            "transition-opacity duration-200 ease-out motion-reduce:transition-none",
            wave ? "opacity-100" : "pointer-events-none opacity-0",
          )}
        >
          <div className="relative h-6 min-w-0 flex-1 overflow-hidden [mask-image:linear-gradient(to_right,transparent,#000_28%)]">
            <div ref={trackRef} className="absolute top-0 -right-[5px] flex h-6 items-center gap-[2px] will-change-transform">
              {Array.from({ length: BARS }, (_, i) => (
                <span
                  key={i}
                  className={cx(
                    "block h-6 w-[3px] shrink-0 rounded-full bg-zinc-950 dark:bg-white",
                    status === "listening" ? "" : "transition-transform duration-300 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
                  )}
                  style={{ transform: `scaleY(${REST})` }}
                />
              ))}
            </div>
          </div>
          {status === "listening" ? (
            <span className="flex shrink-0 items-center gap-1.5 font-mono text-xs text-zinc-600 tabular-nums dark:text-zinc-400">
              <span aria-hidden="true" className="size-1.5 rounded-full bg-red-500" />
              <span ref={clockRef} role="timer" className="data-[near=true]:text-amber-600 dark:data-[near=true]:text-amber-400">
                0:00
              </span>
            </span>
          ) : status === "processing" ? (
            <span className="shrink-0 pr-1 text-xs text-zinc-500">Transcribing…</span>
          ) : null}
        </div>

        {status === "done" ? (
          <p className="min-w-0 py-1 pl-1 leading-6 text-pretty text-zinc-950 dark:text-white">
            {words.map((word, i) => (
              <span
                key={i}
                className={cx(
                  "transition-[opacity,filter,translate] duration-300 starting:translate-y-0.5 starting:opacity-0 starting:blur-[3px] motion-reduce:transition-none",
                  ease,
                )}
                style={{ transitionDelay: `${Math.min(i, 40) * 14}ms` }}
              >
                {word}
              </span>
            ))}
          </p>
        ) : null}

        {status === "error" ? (
          <p role="alert" className="py-1 pl-1 leading-6 text-red-600 dark:text-red-400">
            {errorMessage ?? errorText[errorKindShown]}
          </p>
        ) : null}
      </div>

      <button
        ref={primaryRef}
        type="button"
        aria-label={primaryLabel}
        aria-disabled={busy || undefined}
        aria-busy={busy || undefined}
        onClick={() => {
          if (busy) return;
          if (status === "listening") void finish();
          else start();
        }}
        className={cx(
          "relative inline-grid size-8 shrink-0 cursor-pointer place-items-center self-start rounded-full [&>*]:col-start-1 [&>*]:row-start-1",
          "transition-[background-color,color,border-color,box-shadow,scale] duration-150 ease-out active:duration-100 motion-reduce:transition-none",
          "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500 aria-disabled:cursor-default",
          status === "listening"
            ? "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"
            : status === "requesting"
              ? "text-sky-600 shadow-[inset_0_0_0_1px_rgb(14_165_233/0.4)] dark:text-sky-400"
              : busy
                ? "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)]"
                : "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",
        )}
      >
        <Glyph show={status === "idle" || status === "requesting" || status === "done"}>
          <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" />
          <path d="M4.25 7.5a3.75 3.75 0 0 0 7.5 0M8 11.25v2.5" />
        </Glyph>
        <Glyph show={status === "listening"}>
          <path d="m3.75 8.25 2.75 2.75 5.75-6" />
        </Glyph>
        <Glyph show={status === "processing"} spin>
          <path d="M8 2.5a5.5 5.5 0 1 1-5.5 5.5" />
        </Glyph>
        <Glyph show={status === "error"}>
          <path d="M12.5 8a4.5 4.5 0 1 1-1.32-3.18M12.5 2.75v2.5H10" />
        </Glyph>
      </button>
    </div>
  );
}

function Layer({ show, className, children }: { show: boolean; className?: string; children: ReactNode }) {
  return (
    <span
      aria-hidden={!show || undefined}
      className={cx(
        "min-w-0 truncate transition-[opacity,translate] duration-200 motion-reduce:transition-none",
        ease,
        show ? "translate-y-0 opacity-100" : "pointer-events-none translate-y-1 opacity-0",
        className,
      )}
    >
      {children}
    </span>
  );
}

/** Icons stacked in one cell; the active one scales in from 0.9 as the others fade. */
function Glyph({ show, spin = false, children }: { show: boolean; spin?: boolean; children: ReactNode }) {
  return (
    <svg
      aria-hidden="true"
      viewBox="0 0 16 16"
      {...stroke}
      className={cx(
        "size-4 transition-[opacity,scale] duration-200 motion-reduce:transition-none",
        ease,
        show ? "scale-100 opacity-100" : "scale-90 opacity-0",
        spin && "motion-safe:animate-spin",
      )}
    >
      {children}
    </svg>
  );
}