{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "user-audio-control",
  "title": "User Audio Control",
  "description": "Microphone control with toggle and push-to-talk modes, live audio visualizer, and a mic/speaker device picker in a split-button dropdown.",
  "dependencies": [
    "@pipecat-ai/client-js@^1.14.0",
    "@pipecat-ai/client-react@^1.9.0",
    "lucide-react@^1.41.0"
  ],
  "registryDependencies": [
    "button",
    "button-group",
    "dropdown-menu",
    "kbd",
    "switch",
    "@pipecat/device-select",
    "@pipecat/audio-visualizer-bar"
  ],
  "files": [
    {
      "path": "src/components/user-audio-control.tsx",
      "content": "\"use client\";\n\nimport type { DeviceErrorReason } from \"@pipecat-ai/client-js\";\nimport {\n  type OptionalMediaDeviceInfo,\n  PipecatClientMicToggle,\n  useMediaState,\n  usePipecatClient,\n  usePipecatClientMediaTrack,\n} from \"@pipecat-ai/client-react\";\nimport {\n  ChevronDownIcon,\n  Loader2Icon,\n  MicIcon,\n  MicOffIcon,\n  Volume2Icon,\n} from \"lucide-react\";\nimport { Fragment, useCallback, useEffect, useRef, useState } from \"react\";\n\nimport {\n  formatDeviceLabel,\n  usePipecatDevices,\n} from \"@/components/pipecat/device-select\";\nimport {\n  AudioVisualizerBarView,\n  type AudioVisualizerBarViewProps,\n} from \"@/components/pipecat/audio-visualizer-bar\";\nimport { Button } from \"@/components/ui/button\";\nimport { ButtonGroup } from \"@/components/ui/button-group\";\nimport {\n  DropdownMenu,\n  DropdownMenuCheckboxItem,\n  DropdownMenuContent,\n  DropdownMenuGroup,\n  DropdownMenuItem,\n  DropdownMenuLabel,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\";\nimport { Kbd } from \"@/components/ui/kbd\";\nimport { Switch } from \"@/components/ui/switch\";\nimport { cn } from \"@/lib/utils\";\n\ntype ButtonProps = React.ComponentProps<typeof Button>;\n\n// Muted styling per variant, applied while muted (data-state also flips\n// for consumer styling): solid variants fill with the inactive color,\n// outline keeps its border + tint (nova's destructive-button idiom),\n// secondary tints without a border, ghost only recolors content. Unknown\n// (consumer-added) variants get the ghost treatment.\nconst INACTIVE_VARIANT_CLASSES: Record<string, string> = {\n  default: \"bg-inactive text-inactive-foreground hover:bg-inactive/80\",\n  outline:\n    \"border-inactive/30 bg-inactive/10 text-inactive hover:bg-inactive/20 hover:text-inactive dark:bg-inactive/20\",\n  secondary:\n    \"bg-inactive/10 text-inactive hover:bg-inactive/20 dark:bg-inactive/20\",\n  ghost: \"text-inactive hover:text-inactive\",\n};\n\nfunction inactiveClasses(variant: ButtonProps[\"variant\"]): string {\n  return (\n    INACTIVE_VARIANT_CLASSES[variant ?? \"default\"] ??\n    INACTIVE_VARIANT_CLASSES.ghost!\n  );\n}\n\n// The visualizer draws in pixels: known Button sizes map to bar heights,\n// anything else (including custom cva sizes) falls back to 18. Override\n// per-instance via visualizerProps.barMaxHeight.\nconst VISUALIZER_HEIGHT: Partial<\n  Record<NonNullable<ButtonProps[\"size\"]>, number>\n> = {\n  xs: 12,\n  sm: 14,\n  lg: 22,\n};\n\n// Nova's icon-* sizes render a square button; the toggle responds by going\n// icon-only (no label, hotkey hint, or visualizer — and no min-width).\nfunction isIconSize(size: ButtonProps[\"size\"]): boolean {\n  return typeof size === \"string\" && size.startsWith(\"icon\");\n}\n\n// Nova's icon sizes mirror the text sizes by suffix (sm ↔ icon-sm), so the\n// picker trigger derives its size from the control's mechanically.\nfunction iconSize(size: ButtonProps[\"size\"]): ButtonProps[\"size\"] {\n  if (isIconSize(size)) return size;\n  return !size || size === \"default\"\n    ? \"icon\"\n    : (`icon-${size}` as ButtonProps[\"size\"]);\n}\n\n/** Human label for a KeyboardEvent.code (\"KeyM\" → \"M\", \"Backquote\" → \"`\"). */\nfunction keyLabel(code: string): string {\n  if (code.startsWith(\"Key\")) return code.slice(3);\n  if (code.startsWith(\"Digit\")) return code.slice(5);\n  return code === \"Backquote\" ? \"`\" : code;\n}\n\n/**\n * Renders the hotkey hint, replacing \"[key]\" with the key chip. Wrapped in\n * its own span so it's a single flex item inside the button — the button's\n * gap separates it from the label, same as the icon and visualizer.\n */\nfunction renderKeyHint(template: string, code: string): React.ReactNode {\n  return (\n    <span data-slot=\"ptt-hint\" className=\"inline-flex items-center gap-1\">\n      {template.split(\"[key]\").map((part, i) => (\n        <Fragment key={i}>\n          {i > 0 && <Kbd>{keyLabel(code)}</Kbd>}\n          {part}\n        </Fragment>\n      ))}\n    </span>\n  );\n}\n\n// Keys with native meaning on focused controls (activation, menu/list\n// navigation). When the hotkey is one of these, push-to-talk yields to\n// focused interactive elements; any other key can be claimed page-wide.\nconst ACTIVATION_KEYS = new Set([\n  \"Space\",\n  \"Enter\",\n  \"NumpadEnter\",\n  \"ArrowUp\",\n  \"ArrowDown\",\n  \"ArrowLeft\",\n  \"ArrowRight\",\n  \"Home\",\n  \"End\",\n  \"PageUp\",\n  \"PageDown\",\n  \"Escape\",\n  \"Tab\",\n]);\n\nexport interface UserAudioControlViewProps {\n  /** Whether the microphone is currently enabled. */\n  isMicEnabled?: boolean;\n  /** Called when the user clicks the mute toggle. */\n  onToggleMic?: () => void;\n  /** Disables the control and shows a spinner (e.g. while devices initialize). */\n  isLoading?: boolean;\n  /** Content shown next to the spinner while loading. Spinner only by default. */\n  loadingText?: React.ReactNode;\n  /**\n   * When set, the control renders disabled with this message instead of the\n   * toggle (mic blocked, in use, not found, …). Takes precedence over the\n   * interactive state; isLoading takes precedence over both.\n   */\n  unavailableText?: React.ReactNode;\n  /** Microphones offered in the picker. */\n  mics?: MediaDeviceInfo[];\n  /** Currently selected microphone, matched by deviceId. */\n  selectedMic?: OptionalMediaDeviceInfo;\n  /** Called with the deviceId when the user picks a microphone. */\n  onMicChange?: (deviceId: string) => void;\n  /** Speakers offered in the picker. */\n  speakers?: MediaDeviceInfo[];\n  /** Currently selected speaker, matched by deviceId. */\n  selectedSpeaker?: OptionalMediaDeviceInfo;\n  /** Called with the deviceId when the user picks a speaker. */\n  onSpeakerChange?: (deviceId: string) => void;\n  /** Hide the device picker dropdown entirely. */\n  noDevicePicker?: boolean;\n  /** Hide the microphone section of the picker. */\n  noMicrophones?: boolean;\n  /** Hide the speaker section of the picker. */\n  noSpeakers?: boolean;\n  /** Label shown while the mic is live (toggle mode only). */\n  activeText?: React.ReactNode;\n  /** Label shown while the mic is muted (toggle mode only). */\n  inactiveText?: React.ReactNode;\n  /** Hide the mic icon. */\n  noIcon?: boolean;\n  /** Hide the audio visualizer. */\n  noVisualizer?: boolean;\n  /** Local audio track rendered by the visualizer while the mic is live. */\n  audioTrack?: MediaStreamTrack | null;\n  /** Overrides merged onto the embedded visualizer (wins over defaults). */\n  visualizerProps?: Partial<AudioVisualizerBarViewProps>;\n  /** Interaction mode: click to toggle, or hold to talk (default \"toggle\"). */\n  mode?: \"toggle\" | \"push-to-talk\";\n  /**\n   * Called when the user flips the push-to-talk switch in the device\n   * dropdown. The switch only renders when this is provided.\n   */\n  onModeChange?: (mode: \"toggle\" | \"push-to-talk\") => void;\n  /** Hide the push-to-talk switch in the device dropdown. */\n  noModeSwitch?: boolean;\n  /**\n   * Sets the mic to an absolute state. Push-to-talk prefers this over\n   * onToggleMic (its fallback), which can race across quick presses. The\n   * connected control wires it to client.enableMic().\n   */\n  onMicEnabledChange?: (enabled: boolean) => void;\n  /** Global push-to-talk KeyboardEvent.code (default \"Backquote\"). Interactive elements retain their activation keys; null disables the hotkey. */\n  pttKey?: string | null;\n  /**\n   * Text around the hotkey chip; \"[key]\" marks where the chip renders\n   * (default \"press [key] to talk\"). \"[key]\" alone shows just the chip;\n   * an empty string hides the hint.\n   */\n  pttKeyLabel?: string;\n  /**\n   * Quiet period in ms between releasing push-to-talk and re-muting.\n   * Pressing again inside the window cancels the re-mute, so rapid taps\n   * can't thrash the WebRTC track (default 200).\n   */\n  debounceMs?: number;\n  /** Pulse the push-to-talk outline (default true); respects reduced motion. */\n  pttActiveOutline?: boolean;\n  /**\n   * Called when push-to-talk engages the mic (e.g. to play an on-air\n   * chime). Fires once per hold, not per press source.\n   */\n  onPttOn?: () => void;\n  /**\n   * Called when push-to-talk re-mutes after the debounced release — a\n   * re-press inside the window keeps the hold alive without firing this.\n   */\n  onPttOff?: () => void;\n  /** Button variant for the toggle and picker trigger. */\n  variant?: ButtonProps[\"variant\"];\n  /**\n   * Button size for the toggle; the visualizer and picker trigger scale\n   * with it. Icon sizes (\"icon\", \"icon-sm\", …) render the toggle\n   * icon-only: label, hotkey hint, and visualizer are hidden.\n   */\n  size?: ButtonProps[\"size\"];\n  /** Classes for the outer ButtonGroup. */\n  className?: string;\n  /** Extra content rendered inside the toggle, between label and visualizer. */\n  children?: React.ReactNode;\n}\n\n/** Toggle or hold-to-talk microphone control. Loading takes precedence over unavailability. */\nexport function UserAudioControlView({\n  isMicEnabled = false,\n  onToggleMic,\n  isLoading = false,\n  loadingText,\n  unavailableText,\n  mics,\n  selectedMic,\n  onMicChange,\n  speakers,\n  selectedSpeaker,\n  onSpeakerChange,\n  noDevicePicker = false,\n  noMicrophones = false,\n  noSpeakers = false,\n  activeText,\n  inactiveText,\n  noIcon = false,\n  noVisualizer = false,\n  audioTrack = null,\n  visualizerProps,\n  mode = \"toggle\",\n  onModeChange,\n  noModeSwitch = false,\n  onMicEnabledChange,\n  pttKey = \"Backquote\",\n  pttKeyLabel = \"press [key] to talk\",\n  debounceMs = 200,\n  pttActiveOutline = true,\n  onPttOn,\n  onPttOff,\n  variant = \"outline\",\n  size = \"default\",\n  className,\n  children,\n}: UserAudioControlViewProps) {\n  const hasMics = !noMicrophones && (mics?.length ?? 0) > 0;\n  const hasSpeakers = !noSpeakers && (speakers?.length ?? 0) > 0;\n  const noDropdown = noDevicePicker || (noMicrophones && noSpeakers);\n  const showModeSwitch = !noModeSwitch && !!onModeChange;\n\n  const isPtt = mode === \"push-to-talk\";\n  const pttActive = isPtt && !isLoading && !unavailableText;\n  const iconOnly = isIconSize(size);\n\n  // Push-to-talk shows the key hint instead of the toggle state labels;\n  // icon sizes show neither.\n  const stateText =\n    isPtt || iconOnly ? undefined : isMicEnabled ? activeText : inactiveText;\n\n  // Push-to-talk plumbing. The mic setter and chime callbacks read fresh\n  // props through a ref so the hold handlers stay stable; holds are tracked\n  // per source (global hotkey, pointer, focused-button keys) so overlapping\n  // presses behave.\n  const liveRef = useRef({\n    isMicEnabled,\n    onMicEnabledChange,\n    onToggleMic,\n    onPttOn,\n    onPttOff,\n  });\n  liveRef.current = {\n    isMicEnabled,\n    onMicEnabledChange,\n    onToggleMic,\n    onPttOn,\n    onPttOff,\n  };\n  const setMic = useCallback((enabled: boolean) => {\n    const current = liveRef.current;\n    if (enabled === current.isMicEnabled) return;\n    if (current.onMicEnabledChange) current.onMicEnabledChange(enabled);\n    else current.onToggleMic?.();\n  }, []);\n\n  const holds = useRef({ key: false, pointer: false, focus: false });\n  const engaged = useRef(false);\n  const releaseTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const toggleRef = useRef<HTMLButtonElement>(null);\n\n  const updateHold = useCallback(\n    (source: \"key\" | \"pointer\" | \"focus\", held: boolean) => {\n      const h = holds.current;\n      if (h[source] === held) return;\n      h[source] = held;\n      if (releaseTimer.current) {\n        clearTimeout(releaseTimer.current);\n        releaseTimer.current = null;\n      }\n      if (h.key || h.pointer || h.focus) {\n        setMic(true);\n        // One engage edge per hold: re-presses inside the debounce window\n        // and second press sources don't re-fire the chime.\n        if (!engaged.current) {\n          engaged.current = true;\n          liveRef.current.onPttOn?.();\n        }\n      } else {\n        // Debounced release: pressing again inside the window cancels the\n        // re-mute instead of bouncing the WebRTC track.\n        releaseTimer.current = setTimeout(() => {\n          releaseTimer.current = null;\n          const s = holds.current;\n          if (s.key || s.pointer || s.focus) return;\n          setMic(false);\n          if (engaged.current) {\n            engaged.current = false;\n            liveRef.current.onPttOff?.();\n          }\n        }, debounceMs);\n      }\n    },\n    [setMic, debounceMs],\n  );\n\n  const releaseAllHolds = useCallback(() => {\n    updateHold(\"key\", false);\n    updateHold(\"pointer\", false);\n    updateHold(\"focus\", false);\n  }, [updateHold]);\n\n  // Push-to-talk invariant: the mic is muted unless held. Entering the\n  // mode — via the dropdown switch, a controlled mode change, mounting\n  // with defaultMode, or devices becoming ready while in it — closes the\n  // channel until the first press.\n  useEffect(() => {\n    if (!pttActive) return;\n    const h = holds.current;\n    if (!(h.key || h.pointer || h.focus)) setMic(false);\n  }, [pttActive, setMic]);\n\n  // Global hotkey. Text fields always win; keys with native control\n  // semantics (Space, Enter, arrows) additionally yield to focused\n  // interactive elements — the talk button handles its own held keys.\n  // Window blur releases every hold so cmd-tabbing mid-press can't leave\n  // the mic open.\n  useEffect(() => {\n    if (!pttActive) return;\n    const editable = (t: EventTarget | null) => {\n      const el = t as HTMLElement | null;\n      return (\n        !!el && !!el.closest?.(\"input, textarea, select, [contenteditable]\")\n      );\n    };\n    const handlesOwnKeys = (t: EventTarget | null) => {\n      const el = t as HTMLElement | null;\n      return (\n        !!el &&\n        !!el.closest?.(\n          \"button, a[href], \" +\n            '[role=\"menu\"], [role=\"menuitem\"], [role=\"menuitemcheckbox\"], ' +\n            '[role=\"listbox\"], [role=\"option\"], [role=\"combobox\"], [role=\"dialog\"]',\n        )\n      );\n    };\n    const onKeyDown = (e: KeyboardEvent) => {\n      if (!pttKey || e.code !== pttKey) return;\n      if (e.repeat || e.defaultPrevented || editable(e.target)) return;\n      if (ACTIVATION_KEYS.has(pttKey) && handlesOwnKeys(e.target)) return;\n      e.preventDefault();\n      updateHold(\"key\", true);\n    };\n    const onKeyUp = (e: KeyboardEvent) => {\n      if (pttKey && e.code === pttKey) updateHold(\"key\", false);\n    };\n    window.addEventListener(\"keydown\", onKeyDown);\n    window.addEventListener(\"keyup\", onKeyUp);\n    window.addEventListener(\"blur\", releaseAllHolds);\n    return () => {\n      window.removeEventListener(\"keydown\", onKeyDown);\n      window.removeEventListener(\"keyup\", onKeyUp);\n      window.removeEventListener(\"blur\", releaseAllHolds);\n      releaseAllHolds();\n    };\n  }, [pttActive, pttKey, updateHold, releaseAllHolds]);\n\n  useEffect(\n    () => () => {\n      if (releaseTimer.current) clearTimeout(releaseTimer.current);\n      if (engaged.current) {\n        engaged.current = false;\n        const current = liveRef.current;\n        // Cancel even if the SDK has not reported the preceding enable yet.\n        if (current.onMicEnabledChange) current.onMicEnabledChange(false);\n        else if (current.isMicEnabled) current.onToggleMic?.();\n        current.onPttOff?.();\n      }\n    },\n    [],\n  );\n\n  if (isLoading || unavailableText) {\n    return (\n      <ButtonGroup data-slot=\"user-audio-control\" className={className}>\n        <Button\n          variant={variant}\n          size={size}\n          disabled\n          aria-busy={isLoading || undefined}\n          data-state={isLoading ? \"loading\" : \"unavailable\"}\n          aria-label={\n            !iconOnly\n              ? undefined\n              : isLoading\n                ? \"Microphone loading\"\n                : typeof unavailableText === \"string\"\n                  ? unavailableText\n                  : \"Microphone unavailable\"\n          }\n          className={cn(\"grow\", !iconOnly && \"min-w-32\")}\n        >\n          {isLoading ? (\n            <>\n              <Loader2Icon className=\"animate-spin\" />\n              {!iconOnly && loadingText}\n            </>\n          ) : (\n            <>\n              {!noIcon && <MicOffIcon />}\n              {!iconOnly && unavailableText}\n            </>\n          )}\n        </Button>\n        {/* Keep the (disabled) picker trigger while loading so the split\n            button doesn't collapse; it stays hidden for unavailable, which\n            is a terminal state until permissions change. */}\n        {isLoading && !noDropdown && (\n          <Button\n            variant={variant}\n            size={iconSize(size)}\n            disabled\n            aria-label=\"Audio devices\"\n          >\n            <ChevronDownIcon />\n          </Button>\n        )}\n      </ButtonGroup>\n    );\n  }\n\n  return (\n    <ButtonGroup data-slot=\"user-audio-control\" className={className}>\n      <Button\n        ref={toggleRef}\n        variant={variant}\n        size={size}\n        data-state={isMicEnabled ? \"active\" : \"inactive\"}\n        data-mode={mode}\n        aria-pressed={isMicEnabled}\n        aria-label={\n          stateText\n            ? undefined\n            : isPtt\n              ? \"Hold to talk\"\n              : isMicEnabled\n                ? \"Mute microphone\"\n                : \"Unmute microphone\"\n        }\n        aria-keyshortcuts={isPtt && pttKey ? keyLabel(pttKey) : undefined}\n        className={cn(\n          // Fills a group given a width; content-sized groups are unaffected.\n          \"grow\",\n          !isMicEnabled && inactiveClasses(variant),\n          !iconOnly && \"min-w-32\",\n          isPtt && \"touch-none\",\n          // outline-solid: the button base resets outline-none, which\n          // outline-<width> alone would inherit. z-10 lifts the outline\n          // above the adjacent picker trigger in the ButtonGroup.\n          isPtt &&\n            pttActiveOutline &&\n            isMicEnabled &&\n            \"outline-active motion-safe:animate-ptt-pulse z-10 outline-3 outline-offset-2 outline-solid\",\n        )}\n        {...(isPtt\n          ? {\n              onPointerDown: (e: React.PointerEvent<HTMLButtonElement>) => {\n                if (e.button === 0) updateHold(\"pointer\", true);\n              },\n              onPointerUp: () => updateHold(\"pointer\", false),\n              onPointerLeave: () => updateHold(\"pointer\", false),\n              onPointerCancel: () => updateHold(\"pointer\", false),\n              // Holding Space/Enter on the focused button talks too;\n              // preventDefault suppresses the native click-toggle.\n              onKeyDown: (e: React.KeyboardEvent<HTMLButtonElement>) => {\n                if ((e.key === \" \" || e.key === \"Enter\") && !e.repeat) {\n                  e.preventDefault();\n                  updateHold(\"focus\", true);\n                }\n              },\n              onKeyUp: (e: React.KeyboardEvent<HTMLButtonElement>) => {\n                if (e.key === \" \" || e.key === \"Enter\")\n                  updateHold(\"focus\", false);\n              },\n              // Tabbing away mid-hold would swallow the keyup.\n              onBlur: () => updateHold(\"focus\", false),\n            }\n          : { onClick: onToggleMic })}\n      >\n        {!noIcon && (isMicEnabled ? <MicIcon /> : <MicOffIcon />)}\n        {stateText}\n        {children}\n        {isPtt &&\n          !iconOnly &&\n          pttKey &&\n          pttKeyLabel &&\n          renderKeyHint(pttKeyLabel, pttKey)}\n        {!noVisualizer && !iconOnly && (\n          <AudioVisualizerBarView\n            track={isMicEnabled ? audioTrack : null}\n            // On the solid inactive fill (default variant) the bars use the\n            // foreground token — background-colored bars would disappear.\n            barColor={\n              isMicEnabled\n                ? \"--active-background\"\n                : variant === \"default\"\n                  ? \"--inactive-foreground\"\n                  : \"--inactive-background\"\n            }\n            barGap={2}\n            barWidth={3}\n            barMaxHeight={VISUALIZER_HEIGHT[size ?? \"default\"] ?? 18}\n            barOrigin=\"center\"\n            className=\"w-auto\"\n            {...visualizerProps}\n          />\n        )}\n      </Button>\n      {!noDropdown && (\n        <DropdownMenu>\n          <DropdownMenuTrigger\n            render={\n              <Button\n                variant={variant}\n                size={iconSize(size)}\n                aria-label=\"Audio devices\"\n              >\n                <ChevronDownIcon />\n              </Button>\n            }\n          />\n          <DropdownMenuContent align=\"end\" className=\"min-w-56\">\n            {/* Base UI requires GroupLabel to live inside a Group. */}\n            {hasMics && (\n              <DropdownMenuGroup>\n                <DropdownMenuLabel className=\"text-muted-foreground flex items-center gap-1.5 text-xs\">\n                  <MicIcon className=\"size-3\" />\n                  Microphones\n                </DropdownMenuLabel>\n                {mics!.map((device, index) => (\n                  <DropdownMenuCheckboxItem\n                    key={`mic-${device.deviceId || index}`}\n                    checked={selectedMic?.deviceId === device.deviceId}\n                    onCheckedChange={(checked) => {\n                      if (checked) onMicChange?.(device.deviceId);\n                    }}\n                  >\n                    {formatDeviceLabel(device, \"Microphone\")}\n                  </DropdownMenuCheckboxItem>\n                ))}\n              </DropdownMenuGroup>\n            )}\n            {hasMics && hasSpeakers && <DropdownMenuSeparator />}\n            {hasSpeakers && (\n              <DropdownMenuGroup>\n                <DropdownMenuLabel className=\"text-muted-foreground flex items-center gap-1.5 text-xs\">\n                  <Volume2Icon className=\"size-3\" />\n                  Speakers\n                </DropdownMenuLabel>\n                {speakers!.map((device, index) => (\n                  <DropdownMenuCheckboxItem\n                    key={`speaker-${device.deviceId || index}`}\n                    checked={selectedSpeaker?.deviceId === device.deviceId}\n                    onCheckedChange={(checked) => {\n                      if (checked) onSpeakerChange?.(device.deviceId);\n                    }}\n                  >\n                    {formatDeviceLabel(device, \"Speaker\")}\n                  </DropdownMenuCheckboxItem>\n                ))}\n              </DropdownMenuGroup>\n            )}\n            {!hasMics && !hasSpeakers && (\n              <DropdownMenuGroup>\n                <DropdownMenuLabel className=\"text-muted-foreground font-normal\">\n                  No devices found\n                </DropdownMenuLabel>\n              </DropdownMenuGroup>\n            )}\n            {showModeSwitch && (\n              <>\n                <DropdownMenuSeparator />\n                <DropdownMenuGroup>\n                  {/* Enabling push-to-talk closes the menu and moves focus\n                      to the talk button — otherwise focus returns to the\n                      dropdown trigger, where Space reopens the menu instead\n                      of talking. Disabling keeps the menu open. */}\n                  <DropdownMenuItem\n                    closeOnClick={!isPtt}\n                    onClick={() => {\n                      const next = isPtt ? \"toggle\" : \"push-to-talk\";\n                      onModeChange?.(next);\n                      if (next === \"push-to-talk\") {\n                        requestAnimationFrame(() => toggleRef.current?.focus());\n                      }\n                    }}\n                  >\n                    Push to talk\n                    {/* Inert visual — the menu item handles the toggle. */}\n                    <Switch\n                      checked={isPtt}\n                      tabIndex={-1}\n                      className=\"pointer-events-none ml-auto\"\n                    />\n                  </DropdownMenuItem>\n                </DropdownMenuGroup>\n              </>\n            )}\n          </DropdownMenuContent>\n        </DropdownMenu>\n      )}\n    </ButtonGroup>\n  );\n}\n\n/** Short, user-facing message for a mic device error. */\nfunction micErrorText(reason: DeviceErrorReason): string {\n  switch (reason) {\n    case \"blocked\":\n      return \"Microphone blocked\";\n    case \"already-in-use\":\n      return \"Microphone in use\";\n    case \"not-found\":\n      return \"No microphone\";\n    case \"not-supported\":\n      return \"Audio not supported\";\n    case \"unknown\":\n    default:\n      return \"Microphone unavailable\";\n  }\n}\n\nexport interface UserAudioControlProps extends Omit<\n  UserAudioControlViewProps,\n  | \"isMicEnabled\"\n  | \"onToggleMic\"\n  | \"onMicEnabledChange\"\n  | \"mics\"\n  | \"selectedMic\"\n  | \"onMicChange\"\n  | \"speakers\"\n  | \"selectedSpeaker\"\n  | \"onSpeakerChange\"\n  | \"audioTrack\"\n  | \"isLoading\"\n  | \"unavailableText\"\n> {\n  /** Replaces the automatically derived device-error message. */\n  unavailableText?: React.ReactNode;\n  /** Initial mode when `mode` is left uncontrolled (default \"toggle\"). */\n  defaultMode?: \"toggle\" | \"push-to-talk\";\n}\n\n/** Requires PipecatClientProvider. Manages device state, selection, and toggle or push-to-talk interaction. */\nexport function UserAudioControl({\n  unavailableText,\n  mode: controlledMode,\n  defaultMode = \"toggle\",\n  onModeChange,\n  ...props\n}: UserAudioControlProps) {\n  const client = usePipecatClient();\n  const {\n    devices: mics,\n    selectedDevice: selectedMic,\n    updateDevice: onMicChange,\n  } = usePipecatDevices(\"audioinput\");\n  const {\n    devices: speakers,\n    selectedDevice: selectedSpeaker,\n    updateDevice: onSpeakerChange,\n  } = usePipecatDevices(\"audiooutput\");\n  const audioTrack = usePipecatClientMediaTrack(\"audio\", \"local\");\n\n  const [uncontrolledMode, setUncontrolledMode] = useState(defaultMode);\n  const mode = controlledMode ?? uncontrolledMode;\n  const handleModeChange = useCallback(\n    (next: \"toggle\" | \"push-to-talk\") => {\n      setUncontrolledMode(next);\n      onModeChange?.(next);\n    },\n    [onModeChange],\n  );\n\n  // \"uninitialized\" is deliberately not treated as loading: it also covers\n  // post-init setups where the transport didn't acquire the mic. In those\n  // cases nothing is in flight, so the control just renders muted.\n  const { mic } = useMediaState();\n  const isLoading = mic.state === \"initializing\";\n  const derivedUnavailable =\n    mic.state === \"error\" ? micErrorText(mic.reason) : undefined;\n\n  return (\n    <PipecatClientMicToggle>\n      {({ isMicEnabled, onClick }) => (\n        <UserAudioControlView\n          isMicEnabled={isMicEnabled}\n          onToggleMic={onClick}\n          onMicEnabledChange={(enabled) => client?.enableMic(enabled)}\n          mode={mode}\n          onModeChange={handleModeChange}\n          isLoading={isLoading}\n          unavailableText={unavailableText ?? derivedUnavailable}\n          mics={mics}\n          selectedMic={selectedMic}\n          onMicChange={onMicChange}\n          speakers={speakers}\n          selectedSpeaker={selectedSpeaker}\n          onSpeakerChange={onSpeakerChange}\n          audioTrack={audioTrack}\n          {...props}\n        />\n      )}\n    </PipecatClientMicToggle>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/pipecat/user-audio-control.tsx"
    }
  ],
  "cssVars": {
    "theme": {
      "animate-ptt-pulse": "ptt-pulse 1.5s ease-in-out infinite",
      "color-active": "var(--active-background)",
      "color-active-foreground": "var(--active-foreground)",
      "color-inactive": "var(--inactive-background)",
      "color-inactive-foreground": "var(--inactive-foreground)"
    },
    "light": {
      "active-background": "oklch(0.696 0.17 162.48)",
      "active-foreground": "oklch(0.979 0.021 166.113)",
      "inactive-background": "oklch(0.702 0.189 22.23)",
      "inactive-foreground": "oklch(0.971 0.013 17.38)"
    },
    "dark": {
      "active-background": "oklch(0.702 0.158 160.44)",
      "active-foreground": "oklch(0.979 0.021 166.11)",
      "inactive-background": "oklch(0.702 0.189 22.23)",
      "inactive-foreground": "oklch(0.971 0.013 17.38)"
    }
  },
  "css": {
    "@keyframes ptt-pulse": {
      "50%": {
        "outline-color": "color-mix(in oklab, var(--active-background) 30%, transparent)"
      }
    }
  },
  "docs": "Render inside a PipecatClientProvider. Mic mute state, device errors, and the picker are wired automatically.",
  "categories": [
    "voice"
  ],
  "type": "registry:component"
}