UI

Dictation

Standalone voice dictation control that springs from an idle microphone button into a recording pill with cancel, a live waveform, an elapsed timer, and an insert button.

import { Dictation } from '@uthereal/ui/dictation'

Dictation playground

0:00
Loading interactive preview…

Overview

Dictation renders only the standalone voice input control—never an outer chat box or text field—so you can place it in any composer toolbar. At rest it renders a circular microphone button. When activated, the pill expands toward the inline start into a fixed recording strip containing a cancel button, a live bar waveform, a tabular elapsed timer, and an insert button anchored directly over the idle microphone position.

Pair Dictation with Input or your own text editor when users dictate prompts, notes, or replies and edit before sending. For full-duplex voice calls or audio memo recording, use dedicated call or media controls instead.

Usage

'use client'
import { useState } from 'react'
import { Dictation, type DictationTranscript } from '@uthereal/ui/dictation'

export function ComposerToolbar({
  onAppend,
}: {
  onAppend: (text: string) => void
}) {
  const [live, setLive] = useState<DictationTranscript>({
    final: '',
    interim: '',
  })

  return (
    <div>
      {live.final || live.interim ? (
        <p>
          {live.final} <span>{live.interim}</span>
        </p>
      ) : null}
      <Dictation
        mode="web-speech"
        lang="en-US"
        onTranscript={setLive}
        onCommit={(text) => {
          onAppend(text)
          setLive({ final: '', interim: '' })
        }}
        onCancel={() => setLive({ final: '', interim: '' })}
      />
    </div>
  )
}

By default, mode is simulated, which streams scripted interim corrections and realistic waveform levels without requesting microphone permission. Switch mode to web-speech for built-in browser speech recognition, or pass a custom recognizer adapter for services such as Deepgram, AssemblyAI, or Whisper.

Examples

Recording states

Inspect every active pill face (the idle microphone trigger is live in the playground above): the expanded listening pill with live waveform and elapsed timer, the transcribing spinner while finalizing, and the measured retry pill after microphone denial or recognition error.

0:00
0:00
0:00
0:00

RTL anchoring

Set dir="rtl" (or inherit it from the page) so the recording pill expands naturally from inset-inline-end in right-to-left layouts. Use the playground controls above to inspect sm, md, lg, and recipe.

0:00

States and recognizers

Each lifecycle state keeps the control compact and readable without relying on color alone.

StatusPill faceIcon / indicatorBehavior
idleCircular microphone button (36px at md)Microphone iconClick, Enter, or Space starts dictation and focuses Insert.
startingExpanded recording pill (216px at md)Muted resting dots + timerOpening microphone or session; Cancel aborts immediately.
listeningExpanded recording pill (216px at md)Live bar waveform + timerStreams onTranscript; Insert or Enter finalizes; Escape cancels.
processingExpanded recording pill (216px at md)Check crossfades to spinnerControls set aria-disabled; resolves final text and fires onCommit.
deniedMeasured Try again pillWarning mic-off icon + tooltipExplains site-settings permission block; Escape dismisses.
errorMeasured Try again pillRetry arrow icon + tooltipReports transient failure (no-speech, network, unsupported).

The package also exports the headless primitives behind Dictation:

  • useDictation(options): Headless state machine returning status, transcript, error, startedAt, levelRef, start, confirm, cancel, and dismiss.
  • createSimulatedRecognizer(options): Scripted speech generator with interim corrections, deny testing, and synthetic voice levels.
  • createWebSpeechRecognizer(options): Browser SpeechRecognition / webkitSpeechRecognition adapter with getUserMedia + AnalyserNode levels and automatic track cleanup.
  • DictationError: Typed error carrying a DictationErrorCode (not-allowed, no-speech, audio-capture, network, unsupported, aborted, unknown).

API reference

These serializable arguments and defaults come directly from the component schema.

ArgumentType / defaultDescription
labelstringDefault: "Dictate"Accessible name and tooltip of the idle microphone button.
cancelLabelstringDefault: "Cancel dictation"Accessible name and tooltip of the cancel button while recording.
insertLabelstringDefault: "Insert transcript"Accessible name and tooltip of the insert button while listening.
processingLabelstringDefault: "Transcribing"Accessible name, tooltip, and announcement shown while transcribing.
retryLabelstringDefault: "Try again"Visible button label of the recovery pill after microphone denial or error.
statusidle | starting | listening | processing | denied | error—Controlled lifecycle state. Omit to run the built-in dictation state machine automatically.
errorCodenot-allowed | no-speech | audio-capture | network | unsupported | aborted | unknown—Error reason paired with controlled denied or error status for the tooltip and live announcement.
maxDurationintegerDefault: 120Maximum listening duration in seconds before auto-inserting. Set to 0 to disable the limit.
modesimulated | web-speech | customDefault: "simulated"Speech recognizer source when uncontrolled: simulated streams scripted text without touching the microphone; web-speech uses browser SpeechRecognition; custom uses a React recognizer adapter.
langstring—BCP 47 language tag passed to the Web Speech recognizer when mode is web-speech.
sizesm | md | lgDefault: "md"Control size scale: sm (32px), md (36px), or lg (44px).
disabledbooleanDefault: falsePrevents starting or retrying dictation.
commitActionstring—Registered host action requested when the dictated transcript is inserted.
cancelActionstring—Registered host action requested when an active dictation session is cancelled.
recipestudio | softDefault: "studio"Visual treatment. Both recipes preserve interaction behavior.
themeDictationThemeDefault: {}Color mode, accent, and typed semantic token overrides.
motionnone | subtle | expressiveDefault: "subtle"Animation preset. System reduced-motion preferences take precedence.
motionOptionsDictationMotionOptionsDefault: {}Pill width spring and face crossfade timing overrides in milliseconds.
dirltr | rtl—Reading direction; inherited from the page when omitted.

React integration

PropPurpose
recognizerCustom DictationRecognizer adapter (handlers, signal) => Promise<{ stop(): Promise<string> }>.
levelExternal audio input level (0 to 1) used to drive the waveform when status is controlled.
onTranscript(transcript)Called with cumulative { final, interim } text as speech arrives.
onCommit(text)Called with the trimmed final transcript when the user confirms insertion.
onCancel()Called when the user cancels an active session so you can discard live interim text.
onSpeechEnd()Called when the recognizer detects the end of a spoken utterance.
onStatusChange(status, err)Called on every lifecycle transition, including the DictationErrorCode on failure.
onAction(action)Called for registered host actions (commitAction, cancelAction).
presetApplication defaults overridden by explicit instance arguments.
tokensCSS variables applied after the typed theme.
ref, className, styleApplied to the root inline container.
Native attributesid, aria-*, data-*, and remaining <div> props forwarded to the root container.

Keyboard & accessibility

KeyAction
Enter / SpaceOn the idle microphone button: starts dictation and moves focus to Insert.
EnterWhile listening: stops recording and inserts the transcript.
EscapeWhile listening: cancels and returns focus to the mic. On retry: dismisses error.
TabMoves between visible controls only; hidden pill faces are marked inert.

All three pill faces stay mounted for smooth crossfades, and inactive faces receive the native inert attribute so keyboard focus and screen readers only see the active face. Focus follows every user-initiated transition: mic to Insert on start, Insert or Cancel back to mic on finish, and failed start to Try again.

A pre-mounted polite role="status" live region outside the buttons announces listening (with a simulated-microphone notice in simulated mode), transcribing, inserted word count, cancellation, and recovery copy for errors—never streaming interim words. The elapsed counter uses role="timer" with tabular-nums, and the waveform is marked aria-hidden="true". Logical CSS (inset-inline-end) anchors expansion cleanly in dir="rtl", and forced-colors: active maps pill borders, waveform bars, the Insert fill, and focus outlines to system colors.

Motion and theming

The pill inline width animates on a critically damped 240ms spring with zero overshoot while inactive and active faces crossfade (100ms out, 160ms in after a 40ms delay). The waveform samples levelRef every 60ms and eases 3px rounded bars directly in the DOM with zero per-frame React re-renders, settling to dots when listening stops and pausing offscreen or in background tabs. prefers-reduced-motion: reduce removes pill size springs, replaces waveform travel with calm in-place voice pulsing, slows the spinner to 1.6s, and keeps 120ms opacity crossfades; motion="none" makes every transition immediate (0ms).

theme accepts a mode, an accent, and semantic tokens for surfaces, text, accent fill, focus ring, and sizing. An application-wide UtherealProvider supplies defaults.

Composition

In an agent composition, Dictation is a leaf control placed alongside an input or toolbar. Set commitAction and cancelAction to registered host actions when the host handles transcript commits. See Building with agents.

{
  "type": "Dictation",
  "props": {
    "label": "Dictate",
    "mode": "simulated",
    "size": "md",
    "maxDuration": 120,
    "commitAction": "insert_dictation",
    "cancelAction": "cancel_dictation"
  },
  "children": []
}

On this page