{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "voice-01",
  "title": "Voice orb",
  "description": "A disc and a ring of fine bars drawn on a canvas: it breathes when idle, follows your voice or a simulated one, sweeps while thinking and swells while speaking.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/animated-size.json",
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/chat-motion.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/icons.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/segments.json",
    "https://ui.ndekocode.dev/r/speech-envelope.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/voice/voice-01.tsx",
      "content": "'use client';\n\nimport { useInView } from 'motion/react';\nimport { useCallback, useEffect, useRef, useState } from 'react';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport {\n  useAutoplay,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\nimport { spokenUnless } from '@/registry/ndeko/lib/demonstration';\nimport {\n  CircleAlertIcon,\n  LoaderIcon,\n  MicIcon,\n  MicOffIcon,\n} from '@/registry/ndeko/lib/icons';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { AnimatedSize } from '@/registry/ndeko/ui/animated-size';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { Swap } from '@/registry/ndeko/ui/chat-motion';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\nimport { Segments, type Segment } from '@/registry/ndeko/ui/segments';\n\nimport { speechLevelAt } from '@/registry/ndeko/lib/speech-envelope';\n\nexport type VoiceState = 'idle' | 'listening' | 'thinking' | 'speaking';\n\nconst STATES: VoiceState[] = ['idle', 'listening', 'thinking', 'speaking'];\n\nconst STATE_WORD: Record<VoiceState, string> = {\n  idle: 'Idle',\n  listening: 'Listening',\n  thinking: 'Thinking',\n  speaking: 'Speaking',\n};\n\nconst STATE_LABELS = STATES.map((state) => STATE_WORD[state]);\n\nconst TAU = Math.PI * 2;\n\nconst BAR_COUNT = 72;\n\nconst TICK_COUNT = 120;\n\n/** One tick in ten is longer, so the slow turn of the fine ring can be read. */\nconst LONG_TICK_EVERY = 10;\n\nconst DISC_SHARE = 0.235;\n\nconst RING_GAP_SHARE = 0.055;\n\nconst REST_LENGTH_SHARE = 0.022;\n\nconst MAX_LENGTH_SHARE = 0.125;\n\nconst TICK_RING_SHARE = 0.455;\n\nconst TICK_LENGTH_SHARE = 0.012;\n\nconst LONG_TICK_LENGTH_SHARE = 0.028;\n\nconst BAR_WIDTH = 1.6;\n\nconst TICK_WIDTH = 1;\n\nconst ARC_WIDTH = 2.5;\n\nconst BASE_BAR_ALPHA = 0.24;\n\nconst TICK_ALPHA = 0.16;\n\nconst SPOKEN_ALPHA = 0.85;\n\n/** How far the bars reach while the agent speaks, as a share of their reach while it listens. */\nconst SPOKEN_REACH = 0.7;\n\nconst SWEEP_LIFT = 0.45;\n\nconst BREATH_HERTZ = 0.22;\n\nconst BREATH_DEPTH = 0.02;\n\n/** The disc grows by this share at the loudest level: it follows the voice without swelling. */\nconst LEVEL_DEPTH = 0.03;\n\n/** Radians per second: the bars drift one way and the fine ring the other, twice as fast, about a turn a minute. */\nconst BAR_DRIFT = 0.05;\n\nconst TICK_DRIFT = -0.1;\n\n/** Radians per second: a full turn of the thinking arc takes about four seconds. */\nconst SWEEP_SPEED = 1.6;\n\nconst SWEEP_WIDTH = 0.62;\n\n/** Radians: the length of the arc that travels the ring while the agent thinks. */\nconst ARC_SPAN = 0.7;\n\n/** Seconds for the orb to ease most of the way into a new state. */\nconst STATE_EASE_S = 0.22;\n\nconst ATTACK = 0.45;\n\nconst RELEASE = 0.12;\n\nconst COLOR_REFRESH_MS = 500;\n\nconst INPUT_SEED = 0.4;\n\nconst OUTPUT_SEED = 2.2;\n\ntype Weights = Record<VoiceState, number>;\n\ntype Palette = {\n  primary: string;\n  foreground: string;\n};\n\ntype OrbFrame = {\n  weights: Weights;\n  input: number;\n  output: number;\n  seconds: number;\n};\n\ntype Geometry = {\n  size: number;\n  centre: number;\n  disc: number;\n  ringStart: number;\n  restLength: number;\n  maxLength: number;\n  tickRing: number;\n  tickLength: number;\n  longTickLength: number;\n};\n\nfunction oneHotOf(state: VoiceState): Weights {\n  return {\n    idle: Number(state === 'idle'),\n    listening: Number(state === 'listening'),\n    thinking: Number(state === 'thinking'),\n    speaking: Number(state === 'speaking'),\n  };\n}\n\nfunction paletteOf(element: HTMLElement): Palette {\n  const styles = getComputedStyle(element);\n  const primary = styles.getPropertyValue('--primary').trim();\n  const foreground = styles.getPropertyValue('--foreground').trim();\n  const fallback = styles.color;\n  return {\n    primary: primary || fallback,\n    foreground: foreground || fallback,\n  };\n}\n\nfunction geometryOf(size: number): Geometry {\n  const disc = size * DISC_SHARE;\n  return {\n    size,\n    centre: size / 2,\n    disc,\n    ringStart: disc + size * RING_GAP_SHARE,\n    restLength: size * REST_LENGTH_SHARE,\n    maxLength: size * MAX_LENGTH_SHARE,\n    tickRing: size * TICK_RING_SHARE,\n    tickLength: size * TICK_LENGTH_SHARE,\n    longTickLength: size * LONG_TICK_LENGTH_SHARE,\n  };\n}\n\nfunction angleOfBar(index: number, seconds: number) {\n  const share = index / BAR_COUNT;\n  const angle = share * TAU;\n  const drift = seconds * BAR_DRIFT;\n  return angle + drift - Math.PI / 2;\n}\n\nfunction angleOfTick(index: number, seconds: number) {\n  const share = index / TICK_COUNT;\n  const angle = share * TAU;\n  const drift = seconds * TICK_DRIFT;\n  return angle + drift - Math.PI / 2;\n}\n\nfunction sweepAngleOf(seconds: number) {\n  return seconds * SWEEP_SPEED - Math.PI / 2;\n}\n\n/** A slow organic variation around the ring, so the bars never move as one block. */\nfunction shapeOf(index: number, seconds: number) {\n  const wobblePhase = index * 0.55 + seconds * 2.1;\n  const ripplePhase = index * 1.7 - seconds * 3.3;\n  const wobble = Math.sin(wobblePhase);\n  const ripple = Math.sin(ripplePhase);\n  const mixed = wobble * 0.6 + ripple * 0.4;\n  const lifted = (mixed + 1) / 2;\n  return 0.35 + lifted * 0.65;\n}\n\nfunction angularDistance(first: number, second: number) {\n  const gap = Math.abs(first - second);\n  const wrapped = gap % TAU;\n  const other = TAU - wrapped;\n  return Math.min(wrapped, other);\n}\n\n/** How much a bar is lit by the thinking arc as it passes: 1 under it, 0 away from it. */\nfunction sweepOf(barAngle: number, seconds: number) {\n  const distance = angularDistance(barAngle, sweepAngleOf(seconds));\n  const closeness = 1 - distance / SWEEP_WIDTH;\n  const bounded = Math.max(0, closeness);\n  return bounded * bounded;\n}\n\nfunction discScaleOf(frame: OrbFrame) {\n  const breathAngle = frame.seconds * TAU * BREATH_HERTZ;\n  const breath = Math.sin(breathAngle) * BREATH_DEPTH;\n  const calm = frame.weights.idle + frame.weights.thinking;\n  const heard = frame.weights.listening * frame.input;\n  const spoken = frame.weights.speaking * frame.output;\n  const level = heard + spoken;\n  return 1 + calm * breath + level * LEVEL_DEPTH;\n}\n\nfunction tickLengthOf(index: number, geometry: Geometry) {\n  const isLong = index % LONG_TICK_EVERY === 0;\n  if (isLong) {\n    return geometry.longTickLength;\n  }\n  return geometry.tickLength;\n}\n\n/** Where a bar ends: its rest length, plus what the voice and the passing arc add to it. */\nfunction barEndOf(\n  index: number,\n  angle: number,\n  frame: OrbFrame,\n  geometry: Geometry\n) {\n  const shape = shapeOf(index, frame.seconds);\n  const sweep = sweepOf(angle, frame.seconds) * frame.weights.thinking;\n  const heard = frame.weights.listening * frame.input * shape;\n  const spoken = frame.weights.speaking * frame.output * SPOKEN_REACH * shape;\n  const lit = sweep * SWEEP_LIFT;\n  const reach = heard + spoken + lit;\n  const length = geometry.restLength + reach * geometry.maxLength;\n  return geometry.ringStart + length;\n}\n\nfunction addSpoke(\n  context: CanvasRenderingContext2D,\n  centre: number,\n  angle: number,\n  from: number,\n  to: number\n) {\n  const cos = Math.cos(angle);\n  const sin = Math.sin(angle);\n  context.moveTo(centre + cos * from, centre + sin * from);\n  context.lineTo(centre + cos * to, centre + sin * to);\n}\n\n/** The fine ring: every tick in one path, turning against the bars. */\nfunction drawTicks(\n  context: CanvasRenderingContext2D,\n  geometry: Geometry,\n  seconds: number,\n  palette: Palette\n) {\n  context.globalAlpha = TICK_ALPHA;\n  context.strokeStyle = palette.foreground;\n  context.lineWidth = TICK_WIDTH;\n  context.beginPath();\n  for (let index = 0; index < TICK_COUNT; index += 1) {\n    const angle = angleOfTick(index, seconds);\n    const end = geometry.tickRing + tickLengthOf(index, geometry);\n    addSpoke(context, geometry.centre, angle, geometry.tickRing, end);\n  }\n  context.stroke();\n}\n\n/** The ring that follows the voice: neutral while it hears, in the brand colour while the agent speaks. */\nfunction drawBars(\n  context: CanvasRenderingContext2D,\n  geometry: Geometry,\n  frame: OrbFrame,\n  palette: Palette\n) {\n  context.lineWidth = BAR_WIDTH;\n  context.beginPath();\n  for (let index = 0; index < BAR_COUNT; index += 1) {\n    const angle = angleOfBar(index, frame.seconds);\n    const end = barEndOf(index, angle, frame, geometry);\n    addSpoke(context, geometry.centre, angle, geometry.ringStart, end);\n  }\n  context.globalAlpha = BASE_BAR_ALPHA;\n  context.strokeStyle = palette.foreground;\n  context.stroke();\n  const spokenAlpha = frame.weights.speaking * SPOKEN_ALPHA;\n  if (spokenAlpha < 0.01) {\n    return;\n  }\n  context.globalAlpha = spokenAlpha;\n  context.strokeStyle = palette.primary;\n  context.stroke();\n}\n\n/** The bars the thinking arc passes over take its colour, the nearest the most. */\nfunction drawLitBars(\n  context: CanvasRenderingContext2D,\n  geometry: Geometry,\n  frame: OrbFrame,\n  palette: Palette\n) {\n  const strength = frame.weights.thinking;\n  if (strength < 0.01) {\n    return;\n  }\n  context.lineWidth = BAR_WIDTH;\n  context.strokeStyle = palette.primary;\n  for (let index = 0; index < BAR_COUNT; index += 1) {\n    const angle = angleOfBar(index, frame.seconds);\n    const sweep = sweepOf(angle, frame.seconds) * strength;\n    if (sweep < 0.01) {\n      continue;\n    }\n    const end = barEndOf(index, angle, frame, geometry);\n    context.globalAlpha = sweep;\n    context.beginPath();\n    addSpoke(context, geometry.centre, angle, geometry.ringStart, end);\n    context.stroke();\n  }\n}\n\n/** While the agent thinks, a short arc travels the fine ring. */\nfunction drawThinkingArc(\n  context: CanvasRenderingContext2D,\n  geometry: Geometry,\n  frame: OrbFrame,\n  palette: Palette\n) {\n  const strength = frame.weights.thinking;\n  if (strength < 0.01) {\n    return;\n  }\n  const head = sweepAngleOf(frame.seconds);\n  const radius = geometry.tickRing + geometry.longTickLength / 2;\n  context.globalAlpha = strength;\n  context.strokeStyle = palette.primary;\n  context.lineWidth = ARC_WIDTH;\n  context.beginPath();\n  context.arc(geometry.centre, geometry.centre, radius, head - ARC_SPAN, head);\n  context.stroke();\n}\n\nfunction drawDisc(\n  context: CanvasRenderingContext2D,\n  geometry: Geometry,\n  frame: OrbFrame,\n  palette: Palette\n) {\n  const radius = geometry.disc * discScaleOf(frame);\n  context.globalAlpha = 1;\n  context.fillStyle = palette.primary;\n  context.beginPath();\n  context.arc(geometry.centre, geometry.centre, radius, 0, TAU);\n  context.fill();\n}\n\nfunction drawOrb(\n  context: CanvasRenderingContext2D,\n  geometry: Geometry,\n  frame: OrbFrame,\n  palette: Palette\n) {\n  context.clearRect(0, 0, geometry.size, geometry.size);\n  context.lineCap = 'round';\n  drawTicks(context, geometry, frame.seconds, palette);\n  drawBars(context, geometry, frame, palette);\n  drawLitBars(context, geometry, frame, palette);\n  drawThinkingArc(context, geometry, frame, palette);\n  drawDisc(context, geometry, frame, palette);\n}\n\nfunction followOf(current: number, target: number) {\n  const gap = target - current;\n  const isRising = gap > 0;\n  if (isRising) {\n    return current + gap * ATTACK;\n  }\n  return current + gap * RELEASE;\n}\n\nfunction levelFrom(\n  provider: (() => number) | undefined,\n  elapsed: number,\n  seed: number\n) {\n  if (provider) {\n    return provider();\n  }\n  return speechLevelAt(elapsed, seed);\n}\n\nfunction easeWeights(weights: Weights, target: Weights, amount: number) {\n  for (const state of STATES) {\n    const gap = target[state] - weights[state];\n    weights[state] += gap * amount;\n  }\n}\n\nfunction stillFrameOf(state: VoiceState): OrbFrame {\n  return { weights: oneHotOf(state), input: 0.55, output: 0.5, seconds: 0.4 };\n}\n\nfunction sizeCanvas(canvas: HTMLCanvasElement, size: number) {\n  const ratio = window.devicePixelRatio || 1;\n  const pixels = Math.round(size * ratio);\n  if (canvas.width !== pixels) {\n    canvas.width = pixels;\n    canvas.height = pixels;\n  }\n  const context = canvas.getContext('2d');\n  context?.setTransform(ratio, 0, 0, ratio, 0, 0);\n  return context;\n}\n\nexport type VoiceOrbProps = {\n  state: VoiceState;\n  /** The live level of what is heard, between 0 and 1. Left out, a simulated voice drives it. */\n  inputLevel?: () => number;\n  /** The live level of what the agent says, between 0 and 1. Left out, a simulated voice drives it. */\n  outputLevel?: () => number;\n  size?: number;\n  className?: string;\n};\n\nexport function VoiceOrb({\n  state,\n  inputLevel,\n  outputLevel,\n  size = 176,\n  className,\n}: VoiceOrbProps) {\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const stateRef = useRef(state);\n  const inputRef = useRef(inputLevel);\n  const outputRef = useRef(outputLevel);\n  const isInView = useInView(canvasRef, { amount: 0.2 });\n  const shouldReduceMotion = usePrefersReducedMotion();\n\n  useEffect(() => {\n    stateRef.current = state;\n    inputRef.current = inputLevel;\n    outputRef.current = outputLevel;\n  }, [state, inputLevel, outputLevel]);\n\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    if (!canvas) {\n      return;\n    }\n    const isStill = shouldReduceMotion || !isInView;\n    if (!isStill) {\n      return;\n    }\n    const context = sizeCanvas(canvas, size);\n    if (!context) {\n      return;\n    }\n    drawOrb(context, geometryOf(size), stillFrameOf(state), paletteOf(canvas));\n  }, [shouldReduceMotion, isInView, state, size]);\n\n  useEffect(() => {\n    const canvas = canvasRef.current;\n    if (!canvas) {\n      return;\n    }\n    const isLive = isInView && !shouldReduceMotion;\n    if (!isLive) {\n      return;\n    }\n    const context = sizeCanvas(canvas, size);\n    if (!context) {\n      return;\n    }\n    const surface: HTMLCanvasElement = canvas;\n    const pen: CanvasRenderingContext2D = context;\n    const geometry = geometryOf(size);\n    const weights = oneHotOf(stateRef.current);\n    const shown: OrbFrame = { weights, input: 0, output: 0, seconds: 0 };\n    let palette = paletteOf(surface);\n    let paletteAt = performance.now();\n    let last = performance.now();\n    const startedAt = last;\n    let frame = 0;\n\n    function draw(now: number) {\n      const sinceLast = (now - last) / 1000;\n      const step = Math.min(0.05, sinceLast);\n      last = now;\n      const elapsed = now - startedAt;\n      const amount = 1 - Math.exp(-step / STATE_EASE_S);\n      easeWeights(weights, oneHotOf(stateRef.current), amount);\n      const heard = levelFrom(inputRef.current, elapsed, INPUT_SEED);\n      const spoken = levelFrom(outputRef.current, elapsed, OUTPUT_SEED);\n      shown.input = followOf(shown.input, heard);\n      shown.output = followOf(shown.output, spoken);\n      shown.seconds = elapsed / 1000;\n      const isPaletteStale = now - paletteAt > COLOR_REFRESH_MS;\n      if (isPaletteStale) {\n        palette = paletteOf(surface);\n        paletteAt = now;\n      }\n      drawOrb(pen, geometry, shown, palette);\n      frame = requestAnimationFrame(draw);\n    }\n\n    frame = requestAnimationFrame(draw);\n    return () => cancelAnimationFrame(frame);\n  }, [isInView, shouldReduceMotion, size]);\n\n  return (\n    <canvas\n      ref={canvasRef}\n      aria-hidden='true'\n      style={{ width: size, height: size }}\n      className={cn('block', className)}\n    />\n  );\n}\n\ntype MicStatus =\n  'off' | 'starting' | 'on' | 'refused' | 'missing' | 'failed' | 'unsupported';\n\ntype MicSession = {\n  stream: MediaStream;\n  context: AudioContext;\n  analyser: AnalyserNode;\n  samples: Uint8Array<ArrayBuffer>;\n};\n\nconst MIC_GAIN = 3.4;\n\nfunction statusOfError(error: unknown): MicStatus {\n  if (!(error instanceof DOMException)) {\n    return 'failed';\n  }\n  const isRefused = error.name === 'NotAllowedError';\n  const isSecurity = error.name === 'SecurityError';\n  if (isRefused || isSecurity) {\n    return 'refused';\n  }\n  const isMissing = error.name === 'NotFoundError';\n  const isOverconstrained = error.name === 'OverconstrainedError';\n  if (isMissing || isOverconstrained) {\n    return 'missing';\n  }\n  return 'failed';\n}\n\nfunction canAskForMicrophone() {\n  const devices = navigator.mediaDevices;\n  if (!devices) {\n    return false;\n  }\n  return typeof devices.getUserMedia === 'function';\n}\n\nfunction rmsOf(samples: Uint8Array<ArrayBuffer>) {\n  let sum = 0;\n  for (const sample of samples) {\n    const centred = (sample - 128) / 128;\n    sum += centred * centred;\n  }\n  const mean = sum / samples.length;\n  return Math.sqrt(mean);\n}\n\nfunction stopTracks(stream: MediaStream) {\n  const tracks = stream.getTracks();\n  for (const track of tracks) {\n    track.stop();\n  }\n}\n\nfunction stopSession(session: MicSession) {\n  stopTracks(session.stream);\n  void session.context.close();\n}\n\n/**\n * The microphone level through an analyser. It starts only on an explicit press and every track\n * stops on Stop, on a refusal and on unmount.\n */\nfunction useMicrophoneLevel() {\n  const [status, setStatus] = useState<MicStatus>('off');\n  const session = useRef<MicSession | null>(null);\n  const attempt = useRef(0);\n\n  const release = useCallback(() => {\n    attempt.current += 1;\n    const current = session.current;\n    session.current = null;\n    if (current) {\n      stopSession(current);\n    }\n  }, []);\n\n  useEffect(() => release, [release]);\n\n  async function start() {\n    if (!canAskForMicrophone()) {\n      setStatus('unsupported');\n      return;\n    }\n    release();\n    const token = attempt.current;\n    setStatus('starting');\n    try {\n      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });\n      const context = new AudioContext();\n      const isStale = token !== attempt.current;\n      if (isStale) {\n        stopTracks(stream);\n        void context.close();\n        return;\n      }\n      await context.resume();\n      const source = context.createMediaStreamSource(stream);\n      const analyser = context.createAnalyser();\n      analyser.fftSize = 512;\n      source.connect(analyser);\n      const samples = new Uint8Array(analyser.fftSize);\n      session.current = { stream, context, analyser, samples };\n      setStatus('on');\n    } catch (error) {\n      const isStale = token !== attempt.current;\n      if (isStale) {\n        return;\n      }\n      setStatus(statusOfError(error));\n    }\n  }\n\n  function stop() {\n    release();\n    setStatus('off');\n  }\n\n  const readLevel = useCallback(() => {\n    const current = session.current;\n    if (!current) {\n      return 0;\n    }\n    current.analyser.getByteTimeDomainData(current.samples);\n    const rms = rmsOf(current.samples);\n    const level = rms * MIC_GAIN;\n    return Math.min(1, level);\n  }, []);\n\n  return { status, start, stop, readLevel };\n}\n\nconst MIC_MESSAGE: Partial<Record<MicStatus, string>> = {\n  refused:\n    'Microphone access was refused. Allow it for this site in the browser settings, then try again.',\n  missing: 'No microphone was found. Connect one and try again.',\n  failed: 'The microphone could not start. Try again.',\n  unsupported:\n    'This page cannot reach a microphone here: it needs a secure connection.',\n};\n\nconst MIC_ANNOUNCEMENT: Partial<Record<MicStatus, string>> = {\n  starting: 'Asking for the microphone',\n  on: 'Microphone on, the orb follows your voice',\n  off: '',\n};\n\nconst SEGMENTS: Segment<VoiceState>[] = STATES.map((state) => ({\n  value: state,\n  label: STATE_WORD[state],\n}));\n\ntype MicButtonLook = {\n  key: string;\n  label: string;\n  icon: React.ReactNode;\n};\n\nfunction micButtonOf(status: MicStatus): MicButtonLook {\n  if (status === 'on') {\n    return { key: 'stop', label: 'Stop microphone', icon: <MicOffIcon /> };\n  }\n  if (status === 'starting') {\n    return {\n      key: 'starting',\n      label: 'Asking for access',\n      icon: <LoaderIcon className='animate-spin' />,\n    };\n  }\n  return { key: 'use', label: 'Use microphone', icon: <MicIcon /> };\n}\n\nfunction micAnnouncementOf(status: MicStatus) {\n  const announcement = MIC_ANNOUNCEMENT[status];\n  if (announcement !== undefined) {\n    return announcement;\n  }\n  return MIC_MESSAGE[status] ?? '';\n}\n\nfunction sourceWordOf(status: MicStatus) {\n  if (status === 'on') {\n    return 'Your microphone';\n  }\n  return 'Simulated voice';\n}\n\nfunction inputOf(status: MicStatus, readLevel: () => number) {\n  if (status === 'on') {\n    return readLevel;\n  }\n  return undefined;\n}\n\n/** How long the demonstration stays in each state. */\nconst STATE_HOLD_MS = 2400;\n\nconst START_STATE: VoiceState = 'listening';\n\nexport default function Voice01() {\n  const [state, setState] = useState<VoiceState>(START_STATE);\n  const microphone = useMicrophoneLevel();\n  const button = micButtonOf(microphone.status);\n  const isOn = microphone.status === 'on';\n  const isStarting = microphone.status === 'starting';\n  const problem = MIC_MESSAGE[microphone.status];\n  const micAnnouncement = micAnnouncementOf(microphone.status);\n  const announcement = `${STATE_WORD[state]}. ${micAnnouncement}`;\n  const inputLevel = inputOf(microphone.status, microphone.readLevel);\n\n  async function toggleMicrophone() {\n    if (isOn) {\n      microphone.stop();\n      return;\n    }\n    setState('listening');\n    await microphone.start();\n  }\n\n  const steps: AutoplayStep[] = [\n    { after: STATE_HOLD_MS, run: () => setState('thinking') },\n    { after: STATE_HOLD_MS, run: () => setState('speaking') },\n    { after: STATE_HOLD_MS, run: () => setState('idle') },\n  ];\n  const { ref, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: STATE_HOLD_MS,\n    onReset: () => setState(START_STATE),\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='flex w-full max-w-[22rem] flex-col items-center gap-4'\n    >\n      <div className='bg-card hairline-ring ring-border flex w-full flex-col items-center gap-3 rounded-xl px-4 pt-6 pb-4 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'>\n        <VoiceOrb state={state} inputLevel={inputLevel} />\n        <div className='flex flex-col items-center gap-0.5'>\n          <p className='text-sm font-medium'>\n            <WordRoll text={STATE_WORD[state]} labels={STATE_LABELS} />\n          </p>\n          <p className='text-muted-foreground text-xs'>\n            <Swap swapKey={microphone.status}>\n              {sourceWordOf(microphone.status)}\n            </Swap>\n          </p>\n        </div>\n        <Segments\n          value={state}\n          segments={SEGMENTS}\n          onValueChange={setState}\n          label='Voice state'\n          className='w-full max-w-[19rem]'\n        />\n      </div>\n      <div className='flex w-full flex-col items-center gap-2'>\n        <Button\n          type='button'\n          variant='outline'\n          size='sm'\n          disabled={isStarting}\n          focusableWhenDisabled\n          onClick={toggleMicrophone}\n        >\n          <AnimatedSize\n            as='span'\n            axis='width'\n            contentClassName='flex items-center'\n          >\n            <Swap swapKey={button.key}>\n              <span className='flex items-center gap-1.5'>\n                {button.icon}\n                {button.label}\n              </span>\n            </Swap>\n          </AnimatedSize>\n        </Button>\n        <AnimatedSize className='w-full'>\n          {problem && (\n            <p className='text-muted-foreground flex items-start justify-center gap-2 px-2 text-center text-xs leading-5 text-balance'>\n              <CircleAlertIcon className='text-warning-foreground mt-0.5 size-3.5 shrink-0' />\n              {problem}\n            </p>\n          )}\n        </AnimatedSize>\n      </div>\n      <LiveRegion message={spokenUnless(isAutoplaying, announcement)} />\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "categories": [
    "components",
    "voice"
  ],
  "type": "registry:component"
}