# Voice bar

> A multimodal AI prompt and voice bar on a dither lattice: every word you say condenses out of the wave into the transcript, and the prompt grows line by line.

Most AI prompt bars bolt a static mic icon next to a one-line text field and swap in a spinning dot when voice starts. This one ties the prompt and every voice state to one 8×8 Bayer dither field: square cells, each a whole number of device pixels, fused white-hot along the base, opening into checkerboards with dark holes and single grains at the crest, over a soft wash. While you talk, the wave is your voice; as each word is recognised, its cells lift off the wave, land in the shape of that word on the same grid and dissolve as the crisp word fades in, so you watch speech turn into text. Muting folds the wave into one dotted row that breathes; thinking cools into a scanner packed densest where it works; the reply condenses word by word the same way. Clicking the waveform splits one circular button through a liquid waist into Mute and Close while comet streaks fire out of it; closing draws the wave back into the button and the frame loop sleeps. Typed prompts grow up to six lines (Shift+Enter for a new line, Enter sends), then scroll. Also exports DitherHorizon and useVoiceAudio for your own surfaces.

## Install

```bash
npx shadcn@latest add https://hairlineui.com/r/voice-bar.json
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): `text-morph`
- Docs and live preview: https://hairlineui.com/ui/voice-bar
- Registry item (source): https://hairlineui.com/r/voice-bar.json

## Usage

```tsx
import { VoiceBar } from "@/components/voice-bar";

<VoiceBar
  onSubmit={(prompt) => askAssistant(prompt)}
  onVoiceStart={() => startVoiceSession()}
  onCancel={() => endVoiceSession()}
/>
```

## Live dictation with Deepgram

Deepgram streams the transcript; the bar shows each word forming out of the wave. Your server mints a 30-second token (the API key never reaches the browser), the browser streams the microphone in 250 ms chunks, and ending voice mode leaves the dictated words in the prompt to edit and send. Uses @deepgram/sdk v5 and DEEPGRAM_API_KEY (Member scope).

```tsx
// app/api/deepgram/token/route.ts
// Mints a short-lived Deepgram token (30 s by default) so the API key never reaches the browser.
import { DeepgramClient } from "@deepgram/sdk";

export async function POST() {
  const deepgram = new DeepgramClient({ apiKey: process.env.DEEPGRAM_API_KEY! });
  const token = await deepgram.auth.v1.tokens.grant();
  return Response.json({ accessToken: token.access_token }, { headers: { "Cache-Control": "no-store" } });
}

// components/dictation-bar.tsx
"use client";
import { useRef, useState } from "react";
import { DeepgramClient } from "@deepgram/sdk";
import { VoiceBar, useVoiceAudio, type VoiceBarState } from "@/components/voice-bar";

/** Dictate with Deepgram: each word it hears condenses out of the wave; ending voice mode leaves the words in the prompt to edit and send. */
export function DictationBar({ onSend }: { onSend: (text: string) => Promise<unknown> }) {
  const [state, setState] = useState<VoiceBarState>("idle");
  const [muted, setMuted] = useState(false);
  const [stream, setStream] = useState<MediaStream | null>(null);
  const [transcript, setTranscript] = useState("");
  const [prompt, setPrompt] = useState("");
  const [error, setError] = useState<string>();
  const audio = useVoiceAudio(stream);
  const stop = useRef<() => void>(() => {});

  async function startVoice() {
    setError(undefined);
    setTranscript("");
    try {
      const mic = await navigator.mediaDevices.getUserMedia({ audio: { noiseSuppression: true, echoCancellation: true } });
      const { accessToken } = await (await fetch("/api/deepgram/token", { method: "POST" })).json();
      const deepgram = new DeepgramClient({ accessToken });
      const connection = await deepgram.listen.v1.connect({ model: "nova-3", interim_results: "true", smart_format: "true" });

      let settled = "";
      connection.on("message", (data) => {
        if (data.type !== "Results") return;
        const heard = data.channel.alternatives[0]?.transcript ?? "";
        if (data.is_final) settled = `${settled} ${heard}`.trim();
        // Final words stay put; the interim tail is revised in place. Each word at a new position condenses out of the wave.
        setTranscript(data.is_final ? settled : `${settled} ${heard}`.trim());
      });
      connection.connect();
      await connection.waitForOpen();

      const recorder = new MediaRecorder(mic);
      recorder.ondataavailable = async (e) => {
        if (e.data.size > 0) connection.sendMedia(await e.data.arrayBuffer());
      };
      recorder.start(250);

      stop.current = () => {
        recorder.stop();
        connection.close();
        mic.getTracks().forEach((track) => track.stop());
        setStream(null);
      };
      setStream(mic);
      setMuted(false);
      setState("listening");
    } catch {
      setError("Couldn't start dictation. Allow the microphone and try again.");
      setState("idle");
    }
  }

  return (
    <VoiceBar
      state={state}
      muted={muted}
      transcript={transcript}
      error={error}
      value={prompt}
      onValueChange={setPrompt}
      {...(stream ? audio : {})}
      onVoiceStart={startVoice}
      onStateChange={setState}
      onMutedChange={(next) => {
        setMuted(next);
        stream?.getAudioTracks().forEach((track) => (track.enabled = !next));
      }}
      onCancel={() => {
        stop.current();
        // What was dictated becomes the prompt, to edit and send.
        setPrompt((p) => [p, transcript].filter(Boolean).join(" "));
        setTranscript("");
      }}
      onSubmit={(text) => onSend(text)}
    />
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `state / defaultState / onStateChange` | `"idle" \| "listening" \| "thinking" \| "speaking"` | `"idle"` | Controlled or uncontrolled active state. Drives the dither wave, spawn and dismiss comets and the liquid button split. |
| `layout` | `"bar" \| "card"` | `"bar"` | Compact multimodal prompt bar or expanded voice agent card with a centred streaming transcript and grounded bottom controls. |
| `value / defaultValue / onValueChange` | `string` | `""` | Controlled or uncontrolled prompt in idle state (a textarea that grows up to six lines). Typing sends quiet ticks under the caret and morphs Waveform into Send. |
| `onSubmit` | `(value: string) => void \| Promise<unknown>` | – | Called on Enter or Send. Returning a Promise holds the thinking scanner until it settles; throwing restores the prompt and shows the error inline. |
| `onVoiceStart / onCancel` | `() => void` | – | Called when clicking the waveform button to start voice mode, or clicking Close / pressing Escape to end it. |
| `muted / defaultMuted / onMutedChange` | `boolean` | `false` | Toggled by the split Mic button while listening; sweeps a wipe out of Mic and folds the wave into a breathing dotted row. |
| `transcript / error` | `string / ReactNode` | – | Live dictation or streamed reply: while listening or speaking, each word at a new position condenses out of the wave; plus an inline role="alert" error slot. |
| `getLevel / getSpectrum / level` | `() => number / () => ArrayLike<number> / number` | – | Zero-render frame audio readers (from useVoiceAudio) or a scalar loudness fallback (0..1). Without them, an organic speech rhythm runs. |
| `leading / onAttach / showAttach / attachments` | `ReactNode / () => void / boolean / ReactNode` | `– / – / true / –` | Custom left-side control (such as an Agent mode pill), handler for the default + button (ripples out of that button), and optional chips that fold above the prompt. |
| `palette / colors` | `"spectral" \| "theme" / readonly string[]` | `"spectral"` | Full spectral rainbow (default), theme-token chart colours (--chart-1..5), or any custom CSS colour stops. |
| `interactive / cellSize` | `boolean / number` | `true / 2.5` | Enables ember lift on hover, and sets the dither cell size in CSS px (rounded to whole device pixels, 2–6). |
| `placeholder / labels / disabled` | `string / Partial<VoiceBarLabels> / boolean` | `"Ask me anything..." / – / false` | Shorthand placeholder, full copy overrides for every status and ARIA label, and disabled state. |
| `ref (VoiceBarHandle)` | `{ pulse: (opts?: DitherHorizonPulseOptions) => void; condense: (el: HTMLElement) => number }` | – | pulse() fires a ripple, wipe or keystroke tick from any button or event; condense(el) forms any element’s text out of the wave (the bar calls it for new transcript words) and returns when its cells land, in ms. |
| `DitherHorizon / useVoiceAudio` | `Component / (source: MediaStream \| HTMLMediaElement \| null) => { getLevel, getSpectrum }` | – | Exported alongside VoiceBar so you can mount the dither horizon inside any surface and meter real microphone or audio playback streams. |

## States

- **idle**: A hairline bar with a prompt that grows line by line up to six lines (then scrolls), a left leading/attach control and one circular waveform button. Each keystroke sends a 340ms tick of cells under the caret and morphs the waveform into a primary Send arrow; at rest nothing is drawn and the canvas loop sleeps.
- **activate (idle → listening)**: The waveform circle stretches leftward through a concave liquid waist (~340ms critically damped spring) and snaps into separate Mute and Close circles while 16–28 comet streaks burst out of the button along the rim and light the wave from that side.
- **listening**: Multi-band wave driven by eight real audio bands or a syllable stand-in: a fused white-hot base on dark (deep ink on light), checkerboards with dark holes through the middle, single grains at the crest. Clear onsets send ripples across; hovering lifts embers toward the pointer.
- **words**: A word at a new position in transcript condenses: its cells (one per lattice cell the word covers) leave the wave over 0.16 s, left to right, fly ~0.42 s on a curve, hold hot then colour for 0.16 s and dissolve in Bayer order over 0.34 s; the DOM word fades in from 380 ms.
- **muted**: Pressing the Mic button swaps to MicOff through a 3px blur and sweeps a wipe out of the button; the wave folds into one dotted row (about every other cell lit) that breathes slowly.
- **thinking**: The palette cools into cyan, periwinkle, lavender and violet while the wave flattens into a scanner gliding edge to edge with a trailing wake, its cells packed densest at the scanner; the label runs a light sheen.
- **speaking**: A centre-weighted dome pulses while the reply streams; each new word condenses out of the wave like dictation.
- **error**: If an async onSubmit rejects or error is passed (such as a blocked microphone), the prompt text is kept intact and a polite role="alert" message folds open cleanly inside the bar.
- **dismiss (active → idle)**: Clicking Close or pressing Escape merges Mute and Close back through the liquid waist into the waveform button while the wave breaks into comet streaks that accelerate into the button (~500ms); then nothing is drawn.
- **reduced motion**: No frame loop, comets, condensing or shockwaves: each active state paints one still crest, words fade in plainly and controls switch in place.

## What it handles

Pairing a live voice surface with a text composer usually means a one-line input, a generic audio visualiser and a transcript that just appears. This shows speech becoming words, grows the prompt with its text, and handles the transitions, button geometry, audio metering and light and dark in one drop-in piece.

- **Words form out of your voice**: Each new transcript word is drawn onto the lattice; its cells rise from the wave, land in the word’s shape and dissolve in Bayer order as the real word fades in. A revised word just blurs in.
- **Analytic liquid button mitosis**: One spring-driven SVG path stretches, pinches and splits the single circular button into Mute and Close, keeping a crisp 1px hairline border with zero blur filters.
- **Optical 8×8 Bayer dither**: Cells are a whole number of device pixels, so every cell is the same size and sharp at 1×, 2× and 3×: a fused luminous base opens into checkerboards with dark holes and pinpoint grains, over a soft wash and a 1.5px rim.
- **A prompt that grows**: The prompt is a real textarea that grows line by line up to six lines, then scrolls. Enter sends, Shift+Enter adds a line, and typing sends a quiet tick of cells under the caret.
- **State-coded motion and colour**: Listening runs a multi-band wave with onset ripples; muted folds into a breathing dotted row; thinking glides a cool scanner, densest where it works; speaking centres a dome. Attaching or ref.pulse() ripples out of that control.
- **Light, dark and reduced motion**: Reads the surface’s luminance (a white-hot core on dark, deep ink on light), restores a failed async prompt with an inline error, and paints a still frame with plain word fades under reduced motion.

## Replaces

AI voice composer, audio waveform canvas, SVG gooey filter, Lottie listening animation, streaming transcript fade, framer-motion

## Where it fits

- **Multimodal AI chat**: Type a prompt or switch to live voice inside one hairline bar, with thinking, speaking and inline error states built in.
- **Voice agent popover**: Use layout="card" with a mode pill; each dictated word condenses out of the wave into the centred transcript.
- **Command and search bars**: Mount the exported DitherHorizon along the foot of a command bar to signal listening, processing and action pulses.
- **Realtime dictation**: Stream Deepgram (or any speech-to-text) into transcript and useVoiceAudio into the wave: real bands drive it and each recognised word forms out of it.

## Notes

- The liquid button split uses one analytic SVG path driven by createSpring with no SVG blur/goo filter, so the 1px border stays sharp on retina displays in both light and dark modes.
- The field is one ImageData (a few thousand cells) scaled up by whole device pixels in one drawImage with no smoothing, plus one 16×2 bilinear wash. It held 60fps with the CPU slowed 4× on a phone-sized screen while words condensed, and sleeps when idle, off-screen or in a hidden tab.
- Pressing Escape while active cancels cleanly and returns focus to the primary button; state changes are announced via a polite aria-live region outside the buttons, and errors render in a role="alert" region.
- Surface luminance is read from the host container, so light surfaces get deep-ink cells instead of washing out, and it updates on a theme toggle. Condensed words are measured where they will rest, so their cells land on the text.
- Under prefers-reduced-motion: reduce, the frame loop never starts: each active state paints one still crest, words fade in without condensing and controls switch in place.

License: MIT (https://hairlineui.com/license#components)
