{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"voice-bar","type":"registry:component","title":"Voice bar","description":"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.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/voice-bar.tsx","type":"registry:component","content":"// Hairline UI · voice-bar · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { ArrowUp, Mic, MicOff, Plus, X } from \"lucide-react\";\nimport {\n  DitherHorizon,\n  type DitherHorizonHandle,\n  type DitherHorizonPalette,\n  type DitherHorizonProps,\n  type DitherHorizonPulseOptions,\n  type DitherHorizonState,\n} from \"./dither-horizon\";\nimport { TextMorph } from \"./text-morph\";\nimport {\n  EASE_OUT,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  createSpring,\n  interactionIcon,\n  useInteractionReducedMotion,\n  type Spring,\n} from \"./ui-interaction-motion\";\nimport { BANDS, createAudioMeter, elementSource, type AudioMeter } from \"./voice-audio\";\n\n/* ─────────────────────────────────────────────────────────\n * VOICE BAR: multimodal AI & voice composer on a dither lattice\n *\n *   idle        clean hairline bar (\"Ask me anything…\") with a prompt that\n *               grows line by line up to six lines (Shift+Enter for a new\n *               line, Enter sends), left leading/attach control and one\n *               right waveform button. Typing sends a quiet tick of cells\n *               under the caret and morphs Waveform into Send\n *   activate    clicking the waveform stretches one circle through a\n *               concave liquid waist (analytic SVG geometry, no blur\n *               filter) into [Mic] and [X], while cell comets burst\n *               out of the button and light the dither wave\n *   actions     every control talks to the dither: attaching a file,\n *               switching Agent mode or calling ref.pulse() fires a\n *               localized Bayer shockwave + micro-sparks from that button;\n *               muting sweeps a directional wipe out of [Mic]\n *   listening   multi-band wave driven by real mic FFT (useVoiceAudio) or\n *               level/spectrum props; muting folds it into a dotted row\n *   words       every new word of the transcript condenses out of the\n *               wave: its cells lift off, land in the word's shape on the\n *               same grid and dissolve as the crisp word fades in\n *   thinking    cools into cyan → periwinkle → lavender → violet and\n *               flattens into a horizontal scanner gliding edge to edge\n *   speaking    center-weighted crest; the reply's words condense the\n *               same way\n *   dismiss     clicking [X] (or Escape) merges [Mic] and [X] back\n *               through the liquid waist into [Waveform] while the wave\n *               breaks into cell comets drawn into the button, then sleeps\n * ───────────────────────────────────────────────────────── */\n\nexport type VoiceBarState = DitherHorizonState;\nexport type VoiceBarLayout = \"bar\" | \"card\";\nexport type VoiceBarHandle = DitherHorizonHandle;\n\nexport interface VoiceBarLabels {\n  placeholder: string;\n  listening: string;\n  muted: string;\n  thinking: string;\n  speaking: string;\n  startVoice: string;\n  send: string;\n  mute: string;\n  unmute: string;\n  cancel: string;\n  attach: string;\n}\n\nexport interface VoiceBarProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onSubmit\" | \"defaultValue\"> {\n  ref?: React.Ref<VoiceBarHandle>;\n  /** Controlled state. Omit for uncontrolled state via defaultState. */\n  state?: VoiceBarState;\n  defaultState?: VoiceBarState;\n  onStateChange?: (state: VoiceBarState) => void;\n  /** Controlled text prompt in idle mode. */\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Called when the user submits typed text. Returning a Promise holds thinking until it settles. */\n  onSubmit?: (value: string) => void | Promise<unknown>;\n  /** Called when voice mode starts from the waveform button. */\n  onVoiceStart?: () => void;\n  /** Called when active mode is dismissed via X or Escape. */\n  onCancel?: () => void;\n  /** Controlled muted state while listening. */\n  muted?: boolean;\n  defaultMuted?: boolean;\n  onMutedChange?: (muted: boolean) => void;\n  /** Live partial dictation or streamed reply shown with word-by-word blur reveal. */\n  transcript?: string;\n  /** Optional attachment chips that fold smoothly open above the prompt input. */\n  attachments?: React.ReactNode;\n  /** Inline error message shown in place (e.g. microphone blocked or failed request). */\n  error?: React.ReactNode;\n  /** Read every frame (0..1) without re-rendering React. Pairs with useVoiceAudio. */\n  getLevel?: () => number;\n  /** Read every frame (frequency bands 0..1). Pairs with useVoiceAudio. */\n  getSpectrum?: () => ArrayLike<number>;\n  /** Scalar loudness fallback (0..1). */\n  level?: number;\n  /** \"bar\" (compact multimodal prompt bar) or \"card\" (voice agent card with centered transcript and grounded controls). */\n  layout?: VoiceBarLayout;\n  /** Left-side control (e.g. an Agent/mode pill). Defaults to a + button when omitted. */\n  leading?: React.ReactNode;\n  /** Click handler for the default + button when `leading` is omitted. */\n  onAttach?: () => void;\n  /** Hide the default + button when neither `leading` nor `onAttach` is wanted. */\n  showAttach?: boolean;\n  /** \"spectral\" (vivid rainbow listening + cool cyan/violet thinking) or \"theme\" (--chart-1..5). */\n  palette?: DitherHorizonPalette;\n  /** Custom CSS color stops for the dither horizon. */\n  colors?: readonly string[];\n  /** Pointer hover pulls pinpoint embers up off the dither crest. */\n  interactive?: boolean;\n  /** Dither cell size in CSS px, rounded to whole device pixels (default 2.5). */\n  cellSize?: number;\n  /** Prompt placeholder (shorthand for labels.placeholder). */\n  placeholder?: string;\n  labels?: Partial<VoiceBarLabels>;\n  disabled?: boolean;\n}\n\nconst DEFAULT_LABELS: VoiceBarLabels = {\n  placeholder: \"Ask me anything...\",\n  listening: \"Listening...\",\n  muted: \"Muted\",\n  thinking: \"Thinking...\",\n  speaking: \"Speaking...\",\n  startVoice: \"Start voice mode\",\n  send: \"Send prompt\",\n  mute: \"Mute microphone\",\n  unmute: \"Unmute microphone\",\n  cancel: \"End voice mode\",\n  attach: \"Add attachment\",\n};\n\nconst SHEEN =\n  \"[mask-image:linear-gradient(90deg,rgb(0_0_0/0.48)_34%,#000_50%,rgb(0_0_0/0.48)_66%)] [mask-size:200%_100%] animate-[ui-sheen_1.6s_linear_infinite] motion-reduce:animate-none motion-reduce:[mask-image:none]\";\n\n// Analytic liquid mitosis constants (two 36px circles with a 10px gap inside an 84×38 stage)\nconst STAGE_W = 84;\nconst STAGE_H = 38;\nconst CIRCLE_R = 18;\nconst CY = 19;\nconst CX_RIGHT = 65;\nconst SPLIT_DIST = 46; // cx1 = 19, cx2 = 65 -> 10px gap between two 36px circles\nconst SNAP_DIST = CIRCLE_R * 2 + 7; // 43px: concave neck thins and snaps cleanly into two circles\nconst MITOSIS_SPRING = { stiffness: 195, damping: 23 };\n\nconst clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);\nconst n2 = (v: number) => Math.round(v * 100) / 100;\nconst smoothstep = (e0: number, e1: number, x: number) => {\n  const t = clamp((x - e0) / (e1 - e0), 0, 1);\n  return t * t * (3 - 2 * t);\n};\n\nfunction circleSubpath(cx: number, cy: number, r: number) {\n  return `M${n2(cx - r)} ${n2(cy)}A${n2(r)} ${n2(r)} 0 1 0 ${n2(cx + r)} ${n2(cy)}A${n2(r)} ${n2(r)} 0 1 0 ${n2(cx - r)} ${n2(cy)}Z`;\n}\n\n/** Pure analytic liquid mitosis outline for two circles separating by `dist`. Zero SVG blur filters. */\nexport function mitosisPath(dist: number, cx2 = CX_RIGHT, cy = CY, r = CIRCLE_R) {\n  const d = Math.max(0, dist);\n  if (d < 0.35) return circleSubpath(cx2, cy, r);\n  const cx1 = cx2 - d;\n  if (d >= SNAP_DIST) return `${circleSubpath(cx1, cy, r)} ${circleSubpath(cx2, cy, r)}`;\n\n  const u = clamp(d / SNAP_DIST, 0, 1);\n  const pinch = smoothstep(0.14, 1, u);\n  const thin = r * (1 - 0.88 * Math.pow(pinch, 1.3));\n  const mid = (cx1 + cx2) * 0.5;\n  const pull = (mid - cx1) * 0.56;\n\n  return (\n    `M${n2(cx1)} ${n2(cy - r)}` +\n    `C${n2(cx1 + pull)} ${n2(cy - r)} ${n2(mid - pull)} ${n2(cy - thin)} ${n2(mid)} ${n2(cy - thin)}` +\n    `C${n2(mid + pull)} ${n2(cy - thin)} ${n2(cx2 - pull)} ${n2(cy - r)} ${n2(cx2)} ${n2(cy - r)}` +\n    `A${n2(r)} ${n2(r)} 0 0 1 ${n2(cx2)} ${n2(cy + r)}` +\n    `C${n2(cx2 - pull)} ${n2(cy + r)} ${n2(mid + pull)} ${n2(cy + thin)} ${n2(mid)} ${n2(cy + thin)}` +\n    `C${n2(mid - pull)} ${n2(cy + thin)} ${n2(cx1 + pull)} ${n2(cy + r)} ${n2(cx1)} ${n2(cy + r)}` +\n    `A${n2(r)} ${n2(r)} 0 0 1 ${n2(cx1)} ${n2(cy - r)}Z`\n  );\n}\n\nfunction WaveformGlyph({ className = \"size-[17px]\" }: { className?: string }) {\n  return (\n    <svg viewBox=\"0 0 18 18\" fill=\"currentColor\" aria-hidden=\"true\" className={className}>\n      <rect x=\"2.25\" y=\"7\" width=\"1.9\" height=\"4\" rx=\"0.95\" />\n      <rect x=\"6.05\" y=\"4.5\" width=\"1.9\" height=\"9\" rx=\"0.95\" />\n      <rect x=\"9.85\" y=\"2.75\" width=\"1.9\" height=\"12.5\" rx=\"0.95\" />\n      <rect x=\"13.65\" y=\"6\" width=\"1.9\" height=\"6\" rx=\"0.95\" />\n    </svg>\n  );\n}\n\n/** When a condensing word's text fades in: as its cells land (DitherHorizon: spread 0.16 s + flight 0.42 s). */\nconst WORD_LANDS_MS = 380;\n\n/**\n * Word-by-word streaming transcript. Words already shown stay mounted; a word at a new position is reported through\n * onNewWords (the bar condenses it out of the dither) and fades in as its cells land. A revised last word just blurs in.\n */\nfunction StreamingTranscript({\n  text,\n  reduced,\n  centered,\n  onNewWords,\n}: {\n  text: string;\n  reduced: boolean;\n  centered: boolean;\n  onNewWords?: (els: HTMLElement[]) => void;\n}) {\n  const words = text.trim() ? text.trim().split(/\\s+/) : [];\n  const ref = React.useRef<HTMLParagraphElement>(null);\n  // Which positions are new since the last text: everything from the old count on (nothing on first mount).\n  const [seen, setSeen] = React.useState({ text, from: words.length, count: words.length });\n  if (seen.text !== text) setSeen({ text, from: Math.min(seen.count, words.length), count: words.length });\n  const condensing = Boolean(onNewWords) && !reduced;\n\n  React.useLayoutEffect(() => {\n    if (!condensing) return;\n    const els = ref.current ? Array.from(ref.current.querySelectorAll<HTMLElement>(\"[data-new]:not([data-condensed])\")) : [];\n    if (!els.length) return;\n    els.forEach((el) => (el.dataset.condensed = \"\"));\n    onNewWords?.(els);\n  }, [text, condensing, onNewWords]);\n\n  return (\n    <p\n      ref={ref}\n      className={`text-foreground ${\n        centered\n          ? \"max-w-[26ch] text-center text-[18px] leading-[1.42] tracking-[-0.018em]\"\n          : \"text-[15px] leading-[1.45] tracking-[-0.01em]\"\n      }`}\n    >\n      {words.map((word, idx) => {\n        const fresh = condensing && idx >= seen.from;\n        return (\n          <React.Fragment key={`${idx}:${word}`}>\n            <span\n              data-new={fresh ? \"\" : undefined}\n              className={`inline-block ${reduced ? \"\" : \"animate-[ui-empty-in_340ms_cubic-bezier(0.16,1,0.3,1)_backwards]\"}`}\n              style={fresh ? { animationDelay: `${WORD_LANDS_MS}ms` } : undefined}\n            >\n              {word}\n            </span>\n            {idx < words.length - 1 ? \" \" : null}\n          </React.Fragment>\n        );\n      })}\n    </p>\n  );\n}\n\n/** Smooth height fold for optional attachment chips. */\nfunction Fold({ show, reduced, children }: { show: boolean; reduced: boolean; children: React.ReactNode }) {\n  const [last, setLast] = React.useState(children);\n  if (show && children !== last) setLast(children);\n  return (\n    <div\n      aria-hidden={!show || undefined}\n      inert={!show || undefined}\n      className={`grid ${!show ? \"pointer-events-none\" : \"\"}`}\n      style={{\n        gridTemplateRows: show ? \"1fr\" : \"0fr\",\n        opacity: show ? 1 : 0,\n        transition: reduced ? \"none\" : `grid-template-rows 340ms ${EASE_OUT}, opacity ${show ? \"260ms\" : \"140ms\"} ${EASE_OUT}`,\n      }}\n    >\n      <div className=\"min-h-0 overflow-hidden\">{show ? children : last}</div>\n    </div>\n  );\n}\n\ninterface MitosisControlsProps {\n  active: boolean;\n  canSend: boolean;\n  muted: boolean;\n  disabled: boolean;\n  reduced: boolean;\n  labels: VoiceBarLabels;\n  rightBtnRef: React.RefObject<HTMLButtonElement | null>;\n  micBtnRef: React.RefObject<HTMLButtonElement | null>;\n  onPrimaryClick: () => void;\n  onMicClick: () => void;\n}\n\nfunction MitosisControls({\n  active,\n  canSend,\n  muted,\n  disabled,\n  reduced,\n  labels,\n  rightBtnRef,\n  micBtnRef,\n  onPrimaryClick,\n  onMicClick,\n}: MitosisControlsProps) {\n  const pathRef = React.useRef<SVGPathElement>(null);\n  const micWrapRef = React.useRef<HTMLDivElement>(null);\n  const springRef = React.useRef<Spring | null>(null);\n\n  const paint = React.useCallback(() => {\n    const s = springRef.current;\n    if (!s) return;\n    const dist = clamp(s.get(), 0, SPLIT_DIST + 4);\n    pathRef.current?.setAttribute(\"d\", mitosisPath(dist));\n    const wrap = micWrapRef.current;\n    if (wrap) {\n      const offsetX = SPLIT_DIST - dist;\n      const progress = clamp(dist / SPLIT_DIST, 0, 1);\n      wrap.style.transform = `translate3d(${n2(offsetX)}px, 0, 0) scale(${n2(0.7 + 0.3 * progress)})`;\n      wrap.style.opacity = `${n2(smoothstep(0.18, 0.72, progress))}`;\n    }\n  }, []);\n\n  React.useLayoutEffect(() => {\n    const start = active ? SPLIT_DIST : 0;\n    const sp = createSpring(start, MITOSIS_SPRING, paint, 0.06);\n    springRef.current = sp;\n    paint();\n    return () => {\n      sp.stop();\n      springRef.current = null;\n    };\n    // Mount only; target changes below re-aim the existing spring keeping velocity.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [paint]);\n\n  React.useEffect(() => {\n    const sp = springRef.current;\n    if (!sp) return;\n    const target = active ? SPLIT_DIST : 0;\n    if (reduced) sp.jump(target);\n    else sp.set(target);\n  }, [active, reduced]);\n\n  const sendVisual = !active && canSend;\n  const rightLabel = active ? labels.cancel : canSend ? labels.send : labels.startVoice;\n  const micLabel = muted ? labels.unmute : labels.mute;\n\n  return (\n    <div className=\"relative shrink-0 select-none\" style={{ width: STAGE_W, height: STAGE_H }}>\n      <svg viewBox={`0 0 ${STAGE_W} ${STAGE_H}`} aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 size-full overflow-visible\">\n        <path\n          ref={pathRef}\n          d={mitosisPath(active ? SPLIT_DIST : 0)}\n          className={`transition-[fill,stroke] duration-200 motion-reduce:transition-none ${\n            sendVisual ? \"fill-primary stroke-transparent\" : \"fill-muted stroke-border\"\n          }`}\n          strokeWidth={1}\n          vectorEffect=\"non-scaling-stroke\"\n        />\n      </svg>\n\n      {/* Left circle (Mic / Mute): rides out of the right circle during liquid mitosis. */}\n      <div\n        ref={micWrapRef}\n        className=\"absolute left-[1px] top-[1px] size-[36px]\"\n        style={{\n          transform: active ? \"translate3d(0px, 0, 0) scale(1)\" : `translate3d(${SPLIT_DIST}px, 0, 0) scale(0.7)`,\n          opacity: active ? 1 : 0,\n          pointerEvents: active ? \"auto\" : \"none\",\n        }}\n      >\n        <button\n          ref={micBtnRef}\n          type=\"button\"\n          inert={!active || undefined}\n          disabled={disabled}\n          aria-label={micLabel}\n          aria-pressed={muted}\n          onClick={onMicClick}\n          className={`relative flex size-full cursor-pointer items-center justify-center rounded-full hover:bg-foreground/[0.06] disabled:cursor-default disabled:opacity-45 ${\n            muted ? \"text-muted-foreground\" : \"text-foreground\"\n          } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n        >\n          <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(!muted, reduced)}>\n            <Mic className=\"size-[16px]\" strokeWidth={1.9} />\n          </span>\n          <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(muted, reduced)}>\n            <MicOff className=\"size-[16px]\" strokeWidth={1.9} />\n          </span>\n        </button>\n      </div>\n\n      {/* Right circle (Waveform / Send / Cancel): anchored origin for spawn & dismiss comet streaks. */}\n      <button\n        ref={rightBtnRef}\n        type=\"button\"\n        disabled={disabled}\n        aria-label={rightLabel}\n        onClick={onPrimaryClick}\n        className={`absolute right-[1px] top-[1px] flex size-[36px] cursor-pointer items-center justify-center rounded-full disabled:cursor-default disabled:opacity-45 ${\n          sendVisual ? \"text-primary-foreground hover:bg-white/10\" : \"text-foreground hover:bg-foreground/[0.06]\"\n        } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n      >\n        <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(!active && !canSend, reduced)}>\n          <WaveformGlyph />\n        </span>\n        <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(sendVisual, reduced)}>\n          <ArrowUp className=\"size-[16px]\" strokeWidth={2.2} />\n        </span>\n        <span\n          aria-hidden=\"true\"\n          className=\"absolute inset-0 flex items-center justify-center\"\n          style={{\n            ...interactionIcon(active, reduced),\n            transform: active ? \"rotate(0deg) scale(1)\" : \"rotate(-45deg) scale(0.6)\",\n          }}\n        >\n          <X className=\"size-[16px]\" strokeWidth={2.1} />\n        </span>\n      </button>\n    </div>\n  );\n}\n\nexport function VoiceBar({\n  ref,\n  state: controlledState,\n  defaultState = \"idle\",\n  onStateChange,\n  value: controlledValue,\n  defaultValue = \"\",\n  onValueChange,\n  onSubmit,\n  onVoiceStart,\n  onCancel,\n  muted: controlledMuted,\n  defaultMuted = false,\n  onMutedChange,\n  transcript,\n  attachments,\n  error,\n  getLevel,\n  getSpectrum,\n  level,\n  layout = \"bar\",\n  leading,\n  onAttach,\n  showAttach = true,\n  palette = \"spectral\",\n  colors,\n  interactive = true,\n  cellSize = 2.5,\n  placeholder,\n  labels: labelOverrides,\n  disabled = false,\n  className = \"\",\n  ...props\n}: VoiceBarProps) {\n  const reduced = useInteractionReducedMotion();\n  const labels = React.useMemo(\n    () => ({ ...DEFAULT_LABELS, ...labelOverrides, ...(placeholder !== undefined ? { placeholder } : {}) }),\n    [labelOverrides, placeholder],\n  );\n\n  const [ownState, setOwnState] = React.useState<VoiceBarState>(defaultState);\n  const state = controlledState ?? ownState;\n  const setState = React.useCallback(\n    (next: VoiceBarState) => {\n      if (controlledState === undefined) setOwnState(next);\n      onStateChange?.(next);\n    },\n    [controlledState, onStateChange],\n  );\n\n  const [ownValue, setOwnValue] = React.useState(defaultValue);\n  const text = controlledValue ?? ownValue;\n  const setText = React.useCallback(\n    (next: string) => {\n      if (controlledValue === undefined) setOwnValue(next);\n      onValueChange?.(next);\n    },\n    [controlledValue, onValueChange],\n  );\n\n  const [ownMuted, setOwnMuted] = React.useState(defaultMuted);\n  const muted = controlledMuted ?? ownMuted;\n  const setMuted = React.useCallback(\n    (next: boolean) => {\n      if (controlledMuted === undefined) setOwnMuted(next);\n      onMutedChange?.(next);\n    },\n    [controlledMuted, onMutedChange],\n  );\n\n  const [submitError, setSubmitError] = React.useState<string | null>(null);\n  const displayError = error ?? submitError;\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const horizonRef = React.useRef<DitherHorizonHandle>(null);\n  const rightBtnRef = React.useRef<HTMLButtonElement>(null);\n  const micBtnRef = React.useRef<HTMLButtonElement>(null);\n  const attachBtnRef = React.useRef<HTMLButtonElement>(null);\n  const inputRef = React.useRef<HTMLTextAreaElement>(null);\n\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      pulse(opts?: DitherHorizonPulseOptions) {\n        horizonRef.current?.pulse(opts);\n      },\n      condense(el: HTMLElement) {\n        return horizonRef.current?.condense(el) ?? 0;\n      },\n    }),\n    [],\n  );\n\n  const active = state !== \"idle\";\n  const isCard = layout === \"card\";\n  const canSend = !active && text.trim().length > 0;\n  const hasAttachments = Boolean(attachments);\n\n  const submitText = React.useCallback(() => {\n    const trimmed = text.trim();\n    if (!trimmed || disabled) return;\n    setSubmitError(null);\n    const res = onSubmit?.(trimmed);\n    setText(\"\");\n    if (res && typeof (res as Promise<unknown>).then === \"function\") {\n      setState(\"thinking\");\n      void (res as Promise<unknown>).then(\n        () => {\n          if (controlledState === undefined) setState(\"idle\");\n        },\n        (err: unknown) => {\n          // Restore the prompt so the user never loses what they typed and show the error in place.\n          setText(trimmed);\n          setSubmitError(err instanceof Error && err.message ? err.message : \"Something went wrong. Try again.\");\n          if (controlledState === undefined) setState(\"idle\");\n        },\n      );\n    }\n  }, [text, disabled, onSubmit, setText, setState, controlledState]);\n\n  const handlePrimaryClick = React.useCallback(() => {\n    if (disabled) return;\n    setSubmitError(null);\n    if (active) {\n      setMuted(false);\n      setState(\"idle\");\n      onCancel?.();\n      return;\n    }\n    if (canSend) {\n      submitText();\n      return;\n    }\n    setMuted(false);\n    setState(\"listening\");\n    onVoiceStart?.();\n  }, [disabled, active, canSend, setMuted, setState, onCancel, submitText, onVoiceStart]);\n\n  const handleMicClick = React.useCallback(() => {\n    if (disabled || !active) return;\n    horizonRef.current?.pulse({ kind: \"wipe\", origin: micBtnRef.current, strength: 0.72 });\n    if (state === \"thinking\" || state === \"speaking\") {\n      setMuted(false);\n      setState(\"listening\");\n      return;\n    }\n    setMuted(!muted);\n  }, [disabled, active, state, muted, setMuted, setState]);\n\n  const handleAttachClick = React.useCallback(() => {\n    if (disabled) return;\n    horizonRef.current?.pulse({ kind: \"ripple\", origin: attachBtnRef.current, strength: 0.85 });\n    onAttach?.();\n  }, [disabled, onAttach]);\n\n  const handleInputChange = (next: string) => {\n    if (submitError) setSubmitError(null);\n    setText(next);\n    if (!active && next.length > 0) {\n      // A quiet tick under the caret's approximate column on its current line.\n      const line = next.slice(0, inputRef.current?.selectionStart ?? next.length).split(\"\\n\").pop() ?? \"\";\n      const approxU = isCard ? 0.5 : clamp(0.07 + line.length * 0.018, 0.08, 0.78);\n      horizonRef.current?.pulse({ kind: \"spark\", origin: approxU, strength: 0.55 });\n    }\n  };\n\n  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    props.onKeyDown?.(event);\n    if (event.defaultPrevented) return;\n    if (event.key === \"Escape\" && active) {\n      event.preventDefault();\n      setMuted(false);\n      setState(\"idle\");\n      onCancel?.();\n      rightBtnRef.current?.focus();\n    }\n  };\n\n  const statusText =\n    state === \"thinking\"\n      ? labels.thinking\n      : state === \"speaking\"\n        ? labels.speaking\n        : state === \"listening\"\n          ? muted\n            ? labels.muted\n            : labels.listening\n          : \"\";\n\n  const hasTranscript = active && Boolean(transcript?.trim());\n  // New words condense out of the dither while dictating or while the reply is spoken.\n  const condenseWords = React.useCallback((els: HTMLElement[]) => {\n    for (const el of els) horizonRef.current?.condense(el);\n  }, []);\n  const layerStyle = (on: boolean): React.CSSProperties => ({\n    opacity: on ? 1 : 0,\n    filter: on ? \"blur(0px)\" : \"blur(4px)\",\n    transform: on ? \"none\" : \"translateY(3px)\",\n    transition: reduced\n      ? \"none\"\n      : on\n        ? `opacity 300ms ${EASE_OUT} 70ms, filter 300ms ${EASE_OUT} 70ms, transform 320ms ${EASE_OUT} 70ms`\n        : \"opacity 140ms ease-out, filter 140ms ease-out, transform 140ms ease-out\",\n  });\n\n  return (\n    <div\n      ref={rootRef}\n      data-state={state}\n      data-layout={layout}\n      onKeyDown={handleKeyDown}\n      className={`relative isolate flex w-full flex-col justify-between overflow-clip border border-border bg-card text-card-foreground shadow-[inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.07)] ${\n        isCard ? \"min-h-[196px] rounded-[28px]\" : \"min-h-[112px] rounded-[26px]\"\n      } ${className}`}\n      {...props}\n    >\n      {/* Optical 8×8 Bayer dither horizon + spawn/dismiss comets + action shockwaves + pointer embers. */}\n      <DitherHorizon\n        ref={horizonRef}\n        state={state}\n        muted={muted}\n        getLevel={getLevel}\n        getSpectrum={getSpectrum}\n        level={level}\n        originRef={rightBtnRef}\n        pointerRef={rootRef}\n        shape={layout}\n        palette={palette}\n        colors={colors}\n        interactive={interactive}\n        cellSize={cellSize}\n        className=\"z-0\"\n      />\n\n      {/* Optional attachment chips folding open above the prompt without shifting the bottom dock. */}\n      <Fold show={hasAttachments} reduced={reduced}>\n        <div className={`relative z-10 flex flex-wrap items-center gap-1.5 ${isCard ? \"justify-center px-5 pt-4\" : \"px-4 pt-3.5\"}`}>\n          {attachments}\n        </div>\n      </Fold>\n\n      {/* Content stage: crisp blur crossfade between editable input (idle) and live status / streaming transcript (active). */}\n      <div\n        className={`relative z-10 grid min-w-0 ${\n          isCard ? \"flex-1 place-items-center px-6 pt-7 pb-3\" : hasAttachments ? \"px-4 pt-2 pb-1.5\" : \"px-4 pt-3.5 pb-1.5\"\n        }`}\n      >\n        <div\n          aria-hidden={active || undefined}\n          inert={active || undefined}\n          className={`[grid-area:1/1] w-full ${active ? \"pointer-events-none\" : \"\"}`}\n          style={layerStyle(!active)}\n        >\n          {isCard && !onSubmit && transcript?.trim() ? (\n            <p className=\"mx-auto max-w-[26ch] text-center text-[18px] leading-[1.42] tracking-[-0.018em] text-foreground\">{transcript}</p>\n          ) : (\n            // A prompt that grows with its text, line by line, up to six lines, then scrolls. An invisible copy of the\n            // text sizes the grid cell; the textarea fills it, so the height is always the text's own.\n            <div className={`grid w-full ${isCard ? \"text-center text-[18px] leading-[1.42] tracking-[-0.018em]\" : \"text-[16px] leading-[1.45] tracking-[-0.01em] sm:text-[15px]\"}`}>\n              <span aria-hidden=\"true\" className=\"invisible max-h-[8.7em] overflow-hidden whitespace-pre-wrap [grid-area:1/1] [overflow-wrap:anywhere]\">\n                {text + \"\\u200b\"}\n              </span>\n              <textarea\n                ref={inputRef}\n                rows={1}\n                value={text}\n                disabled={disabled}\n                placeholder={labels.placeholder}\n                aria-label={labels.placeholder}\n                onChange={(e) => handleInputChange(e.target.value)}\n                onKeyDown={(e) => {\n                  if (e.key === \"Enter\" && !e.shiftKey && !e.nativeEvent.isComposing) {\n                    e.preventDefault();\n                    submitText();\n                  }\n                }}\n                className=\"max-h-[8.7em] w-full resize-none overflow-y-auto bg-transparent p-0 text-foreground outline-none [grid-area:1/1] [overflow-wrap:anywhere] [scrollbar-width:thin] placeholder:text-muted-foreground/80 disabled:opacity-50\"\n                style={{ font: \"inherit\", letterSpacing: \"inherit\", textAlign: \"inherit\" }}\n              />\n            </div>\n          )}\n        </div>\n\n        <div\n          aria-hidden={!active || undefined}\n          className={`[grid-area:1/1] w-full ${!active ? \"pointer-events-none\" : \"\"}`}\n          style={layerStyle(active)}\n        >\n          {hasTranscript ? (\n            <div className={isCard ? \"flex justify-center\" : \"\"}>\n              <StreamingTranscript\n                text={transcript!}\n                reduced={reduced}\n                centered={isCard}\n                onNewWords={state === \"listening\" || state === \"speaking\" ? condenseWords : undefined}\n              />\n            </div>\n          ) : (\n            <span\n              className={`inline-block text-muted-foreground ${\n                isCard ? \"w-full text-center text-[18px] tracking-[-0.018em]\" : \"text-[15px] tracking-[-0.01em]\"\n              } ${state === \"thinking\" ? `text-foreground/85 ${SHEEN}` : \"\"}`}\n            >\n              <TextMorph animateWidth={false}>{statusText || labels.listening}</TextMorph>\n            </span>\n          )}\n        </div>\n      </div>\n\n      {/* Inline error message folding smoothly open when a mic permission or async submit fails. */}\n      <Fold show={Boolean(displayError)} reduced={reduced}>\n        <p\n          role=\"alert\"\n          className={`relative z-10 text-[12.5px] leading-5 text-red-600 dark:text-red-400 ${\n            isCard ? \"px-5 pb-1 text-center\" : \"px-4 pb-1\"\n          }`}\n        >\n          {displayError}\n        </p>\n      </Fold>\n\n      {/* Bottom control dock: always grounded concentrically at the bottom corners (never floating mid-card). */}\n      <div className={`relative z-10 flex items-center justify-between gap-2 ${isCard ? \"px-3.5 pb-3.5 pt-2\" : \"px-3 pb-3 pt-1.5\"}`}>\n        <div className=\"flex min-w-0 items-center gap-2\">\n          {leading !== undefined ? (\n            leading\n          ) : showAttach ? (\n            <button\n              ref={attachBtnRef}\n              type=\"button\"\n              disabled={disabled}\n              aria-label={labels.attach}\n              onClick={handleAttachClick}\n              className={`flex size-[36px] shrink-0 cursor-pointer items-center justify-center rounded-full border border-border bg-muted text-foreground hover:bg-accent disabled:cursor-default disabled:opacity-45 ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n            >\n              <Plus className=\"size-[17px]\" strokeWidth={1.9} />\n            </button>\n          ) : null}\n        </div>\n\n        <MitosisControls\n          active={active}\n          canSend={canSend}\n          muted={muted}\n          disabled={disabled}\n          reduced={reduced}\n          labels={labels}\n          rightBtnRef={rightBtnRef}\n          micBtnRef={micBtnRef}\n          onPrimaryClick={handlePrimaryClick}\n          onMicClick={handleMicClick}\n        />\n      </div>\n\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {statusText}\n      </span>\n    </div>\n  );\n}\n\nconst SILENT_SPECTRUM = new Float32Array(BANDS);\n\n/** Meter a real microphone MediaStream or playing <audio> element for DitherHorizon / VoiceBar without re-rendering React. */\nexport function useVoiceAudio(source: MediaStream | HTMLMediaElement | null | undefined) {\n  const meter = React.useRef<AudioMeter | null>(null);\n\n  React.useEffect(() => {\n    if (!source) return;\n    let context: AudioContext;\n    let node: AudioNode;\n    let own = false;\n    if (source instanceof HTMLMediaElement) {\n      ({ context, node } = elementSource(source));\n    } else {\n      context = new AudioContext();\n      node = context.createMediaStreamSource(source);\n      own = true;\n    }\n    meter.current = createAudioMeter(context, node);\n    const resume = () => void context.resume().catch(() => {});\n    resume();\n    window.addEventListener(\"pointerdown\", resume, { once: true });\n    return () => {\n      window.removeEventListener(\"pointerdown\", resume);\n      meter.current?.disconnect();\n      meter.current = null;\n      if (own) void context.close().catch(() => {});\n    };\n  }, [source]);\n\n  return React.useMemo(\n    () => ({\n      getLevel: () => meter.current?.getLevel() ?? 0,\n      getSpectrum: (): ArrayLike<number> => meter.current?.getSpectrum() ?? SILENT_SPECTRUM,\n    }),\n    [],\n  );\n}\n\nexport { DitherHorizon };\nexport type { DitherHorizonHandle, DitherHorizonProps, DitherHorizonPulseOptions, DitherHorizonState, DitherHorizonPalette };\nexport default VoiceBar;\n"},{"path":"registry/dither-horizon.tsx","type":"registry:component","content":"// Hairline UI · voice-bar · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { createSpring, useInteractionActivity, useInteractionReducedMotion } from \"./ui-interaction-motion\";\nimport { BANDS } from \"./voice-audio\";\n\n/* ─────────────────────────────────────────────────────────\n * DITHER HORIZON: an 8×8 Bayer light field under a voice bar\n *\n *   field      each column's cells are lit where the wave's energy\n *              clears an 8×8 Bayer threshold: a fused white-hot base on\n *              dark (deep ink on light), checkerboards with dark holes\n *              through the middle, single grains at the crest. Cells are\n *              a whole number of device pixels, so every cell is the same\n *              size and sharp; a soft wash and a 1.5px rim sit under them\n *   listening  eight audio bands shape the crest; clear onsets send\n *              ripples across; a pointer lifts embers toward it\n *   muted      the wave folds into one dotted row that breathes\n *   thinking   cools into a scanner gliding edge to edge, densest where\n *              it is working\n *   spawn      leaving idle fires comet streaks out of originRef along\n *              the rim; returning to idle draws them back into it\n *   words      ref.condense(el): the cells of a word lift off the wave\n *              and land in that word's shape on the grid, then dissolve\n *              in Bayer order as the real text fades in over them\n *   idle       nothing is drawn and the frame loop sleeps\n * ───────────────────────────────────────────────────────── */\n\nexport type DitherHorizonState = \"idle\" | \"listening\" | \"thinking\" | \"speaking\";\nexport type DitherHorizonPalette = \"spectral\" | \"theme\";\nexport type DitherPulseKind = \"ripple\" | \"wipe\" | \"spark\";\n\nexport interface DitherHorizonPulseOptions {\n  /** Normalized horizontal origin (0..1) or an element whose center determines the origin. */\n  origin?: number | HTMLElement | null;\n  /** Optional CSS color accent for the shockwave crest. */\n  color?: string;\n  /** Impulse strength 0.2..1.4 (default 0.85). */\n  strength?: number;\n  /** \"ripple\" expands outward with micro-comets, \"wipe\" sweeps smoothly, \"spark\" is a quiet keystroke tick. */\n  kind?: DitherPulseKind;\n}\n\nexport interface DitherHorizonHandle {\n  /** Trigger a localized shockwave from any action, mode change or keystroke. */\n  pulse: (options?: DitherHorizonPulseOptions) => void;\n  /** Lift cells off the wave into the shape of this element's text (a word just recognised). Returns the landing time in ms. */\n  condense: (target: HTMLElement) => number;\n}\n\nexport interface DitherHorizonProps extends Omit<React.CanvasHTMLAttributes<HTMLCanvasElement>, \"children\"> {\n  ref?: React.Ref<DitherHorizonHandle>;\n  state?: DitherHorizonState;\n  /** While listening, folds the wave down into a quiet dotted row along the edge. */\n  muted?: boolean;\n  /** Read every frame (0..1) without re-rendering React. */\n  getLevel?: () => number;\n  /** Read every frame (frequency bands 0..1, low to high). */\n  getSpectrum?: () => ArrayLike<number>;\n  /** Scalar loudness fallback (0..1) when getLevel is not passed. */\n  level?: number;\n  /** Element whose center comets burst out from on spawn and return to on dismiss. */\n  originRef?: React.RefObject<HTMLElement | null>;\n  /** Container that captures pointer movement for ember lift. Defaults to the canvas parent. */\n  pointerRef?: React.RefObject<HTMLElement | null>;\n  /** Wave envelope: \"bar\" spans the full edge, \"card\" rises through the lower center channel. */\n  shape?: \"bar\" | \"card\";\n  /** \"spectral\" (full rainbow listening + cool cyan/violet thinking) or \"theme\" (--chart-1..5 / --primary). */\n  palette?: DitherHorizonPalette;\n  /** Custom CSS color stops (theme vars work too). Overrides palette. */\n  colors?: readonly string[];\n  /** Hovering lifts single-cell embers off the crest toward the pointer. */\n  interactive?: boolean;\n  /** Cell size in CSS px, rounded to whole device pixels (default 2.5). */\n  cellSize?: number;\n}\n\ntype Rgb = [number, number, number];\n\ninterface Comet {\n  mode: \"spawn\" | \"dismiss\" | \"burst\";\n  sx: number;\n  sy: number;\n  cx: number;\n  cy: number;\n  ex: number;\n  ey: number;\n  age: number;\n  delay: number;\n  life: number;\n  size: number;\n  rgb: Rgb;\n}\n\ninterface Ember {\n  x: number;\n  y: number;\n  vx: number;\n  vy: number;\n  age: number;\n  life: number;\n  size: number;\n  seed: number;\n  rgb: Rgb;\n}\n\ninterface PulseWave {\n  kind: DitherPulseKind;\n  originU: number;\n  age: number;\n  life: number;\n  strength: number;\n  rgb: Rgb | null;\n}\n\n/** One cell of a word: flies from the wave to its place in the word, holds, then dissolves. */\ninterface Grain {\n  col: number;\n  row: number;\n  sx: number;\n  sy: number;\n  cx: number;\n  cy: number;\n  age: number;\n  delay: number;\n  fly: number;\n  rgb: Rgb;\n}\n\n// 8×8 ordered Bayer matrix: 64 thresholds, the same everywhere, so the pattern never swims.\nconst BAYER8: Float32Array = (() => {\n  const m = [\n    [0, 32, 8, 40, 2, 34, 10, 42],\n    [48, 16, 56, 24, 50, 18, 58, 26],\n    [12, 44, 4, 36, 14, 46, 6, 38],\n    [60, 28, 52, 20, 62, 30, 54, 22],\n    [3, 35, 11, 43, 1, 33, 9, 41],\n    [51, 19, 59, 27, 49, 17, 57, 25],\n    [15, 47, 7, 39, 13, 45, 5, 37],\n    [63, 31, 55, 23, 61, 29, 53, 21],\n  ];\n  const out = new Float32Array(64);\n  for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) out[(y << 3) | x] = (m[y][x] + 0.5) / 64;\n  return out;\n})();\nconst bayer = (col: number, row: number) => BAYER8[((row & 7) << 3) | (col & 7)];\n\nconst SPECTRAL_DARK: Rgb[] = [\n  [255, 132, 28],\n  [255, 48, 108],\n  [230, 68, 245],\n  [98, 118, 255],\n  [32, 198, 255],\n  [28, 234, 172],\n  [250, 202, 42],\n];\n\nconst SPECTRAL_LIGHT: Rgb[] = [\n  [222, 88, 12],\n  [218, 24, 84],\n  [176, 32, 212],\n  [66, 78, 228],\n  [6, 140, 218],\n  [8, 162, 116],\n  [208, 142, 10],\n];\n\nconst THINK_DARK: Rgb[] = [\n  [28, 228, 248],\n  [76, 184, 255],\n  [136, 148, 255],\n  [198, 112, 248],\n  [238, 96, 180],\n  [76, 184, 255],\n];\n\nconst THINK_LIGHT: Rgb[] = [\n  [6, 152, 186],\n  [24, 120, 222],\n  [88, 88, 226],\n  [152, 62, 214],\n  [196, 44, 136],\n  [24, 120, 222],\n];\n\nconst EMBER_DARK: Rgb = [255, 104, 34];\nconst EMBER_LIGHT: Rgb = [226, 64, 18];\n\nconst SPAWN_SPRING = { stiffness: 155, damping: 20 };\nconst DISMISS_SPRING = { stiffness: 265, damping: 28 };\nconst MOOD_SPRING = { stiffness: 70, damping: 16 };\nconst LEVEL_SPRING = { stiffness: 145, damping: 20 };\n\n/** A word's cells: flight, hold on landing, Bayer dissolve (s). */\nconst GRAIN_FLY = 0.42;\nconst GRAIN_SPREAD = 0.16;\nconst GRAIN_HOLD = 0.16;\nconst GRAIN_FADE = 0.34;\n\nconst clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);\nconst clamp01 = (v: number) => (Number.isFinite(v) ? clamp(v, 0, 1) : 0);\nconst lerp = (a: number, b: number, t: number) => a + (b - a) * t;\nconst smoothstep = (e0: number, e1: number, x: number) => {\n  const t = clamp01((x - e0) / (e1 - e0));\n  return t * t * (3 - 2 * t);\n};\n\nconst IS_LE = (() => {\n  const b = new ArrayBuffer(4);\n  new Uint32Array(b)[0] = 0x0a0b0c0d;\n  return new Uint8Array(b)[0] === 0x0d;\n})();\n\nfunction packRgba(r: number, g: number, b: number, a: number): number {\n  const ri = r < 0 ? 0 : r > 255 ? 255 : r | 0;\n  const gi = g < 0 ? 0 : g > 255 ? 255 : g | 0;\n  const bi = b < 0 ? 0 : b > 255 ? 255 : b | 0;\n  const ai = a < 0 ? 0 : a > 255 ? 255 : a | 0;\n  return IS_LE ? ((ai << 24) | (bi << 16) | (gi << 8) | ri) >>> 0 : ((ri << 24) | (gi << 16) | (bi << 8) | ai) >>> 0;\n}\n\nfunction sampleStops(stops: readonly Rgb[], pos: number, out: Rgb): Rgb {\n  const n = stops.length;\n  if (n === 0) {\n    out[0] = 56;\n    out[1] = 189;\n    out[2] = 248;\n    return out;\n  }\n  if (n === 1) {\n    out[0] = stops[0][0];\n    out[1] = stops[0][1];\n    out[2] = stops[0][2];\n    return out;\n  }\n  const wrapped = ((pos % 1) + 1) % 1;\n  const scaled = wrapped * n;\n  const i0 = Math.floor(scaled) % n;\n  const i1 = (i0 + 1) % n;\n  const f = scaled - Math.floor(scaled);\n  const a = stops[i0];\n  const b = stops[i1];\n  out[0] = a[0] + (b[0] - a[0]) * f;\n  out[1] = a[1] + (b[1] - a[1]) * f;\n  out[2] = a[2] + (b[2] - a[2]) * f;\n  return out;\n}\n\nlet swatchCtx: CanvasRenderingContext2D | null = null;\nfunction cssToRgb(host: Element, cssColor: string, fallback: Rgb): Rgb {\n  const probe = document.createElement(\"span\");\n  probe.style.display = \"none\";\n  probe.style.color = cssColor;\n  host.appendChild(probe);\n  const resolved = getComputedStyle(probe).color;\n  probe.remove();\n  if (/^rgba?\\(/.test(resolved)) {\n    const m = resolved.match(/[\\d.]+/g)?.map(Number);\n    if (m && m.length >= 3) return [m[0], m[1], m[2]];\n  }\n  if (!swatchCtx) {\n    const c = document.createElement(\"canvas\");\n    c.width = 1;\n    c.height = 1;\n    swatchCtx = c.getContext(\"2d\", { willReadFrequently: true });\n  }\n  if (swatchCtx) {\n    swatchCtx.clearRect(0, 0, 1, 1);\n    swatchCtx.fillStyle = \"#808080\";\n    swatchCtx.fillStyle = resolved;\n    swatchCtx.fillRect(0, 0, 1, 1);\n    const d = swatchCtx.getImageData(0, 0, 1, 1).data;\n    return [d[0], d[1], d[2]];\n  }\n  return fallback;\n}\n\nfunction detectLightSurface(el: Element | null): boolean {\n  if (!el) return false;\n  const rgb = cssToRgb(el, getComputedStyle(el).color, [240, 240, 240]);\n  const lum = (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) / 255;\n  return lum < 0.52;\n}\n\nfunction resolvePalette(host: Element, palette: DitherHorizonPalette, colors: readonly string[] | undefined, isLight: boolean): Rgb[] {\n  if (colors && colors.length > 0) {\n    return colors.map((c, i) => cssToRgb(host, c, SPECTRAL_DARK[i % SPECTRAL_DARK.length]));\n  }\n  if (palette === \"theme\") {\n    const vars = [\"var(--chart-1)\", \"var(--chart-2)\", \"var(--chart-3)\", \"var(--chart-4)\", \"var(--chart-5)\"];\n    const resolved = vars.map((v, i) => cssToRgb(host, v, SPECTRAL_DARK[i % SPECTRAL_DARK.length]));\n    const spread = resolved.reduce((acc, c, i) => {\n      const next = resolved[(i + 1) % resolved.length];\n      return acc + Math.abs(c[0] - next[0]) + Math.abs(c[1] - next[1]) + Math.abs(c[2] - next[2]);\n    }, 0);\n    if (spread < 30) {\n      const p = cssToRgb(host, \"var(--primary)\", [48, 93, 222]);\n      return [p, [56, 189, 248], [168, 85, 247], [244, 63, 94], p];\n    }\n    return resolved;\n  }\n  return isLight ? SPECTRAL_LIGHT : SPECTRAL_DARK;\n}\n\n/** Organic syllable-like speech stand-in when no microphone level/spectrum is supplied. */\nfunction speechFallback(t: number, out: Float32Array): number {\n  const phrase = 0.5 + 0.5 * Math.sin(t * 1.02 + Math.sin(t * 0.41) * 1.2);\n  const pause = phrase < 0.14 ? 0.24 : 1;\n  const syll = Math.pow(Math.max(0, Math.sin(t * 5.6 + Math.sin(t * 1.85) * 2.1)), 1.35);\n  const lv = clamp01((0.28 + 0.62 * syll * (0.55 + 0.45 * phrase)) * pause);\n  const formant = 2.4 + Math.sin(t * 2.0) * 1.6;\n  const sibilant = Math.sin(t * 3.6 + 0.8) > 0.72 ? 0.75 : 0;\n  for (let b = 0; b < BANDS; b++) {\n    const bell = Math.exp(-((b - formant) ** 2) / 3.8);\n    const wave = 0.5 + 0.5 * Math.sin(t * 4.1 + b * 1.35);\n    out[b] = clamp01(lv * (0.45 + 0.75 * bell + (b > 5 ? sibilant * 0.55 : 0)) * (0.65 + 0.35 * wave));\n  }\n  return lv;\n}\n\n/**\n * An element's box in the canvas's own CSS px, from layout offsets: unaffected by any CSS transform on the page, a zoomed\n * container or the element's own entrance. Null when the element isn't laid out inside the canvas's positioned parent.\n */\nfunction boxWithin(el: HTMLElement, canvas: HTMLCanvasElement) {\n  const root = canvas.offsetParent;\n  let x = 0;\n  let y = 0;\n  let node: Element | null = el;\n  while (node && node !== root) {\n    if (!(node instanceof HTMLElement)) return null;\n    x += node.offsetLeft;\n    y += node.offsetTop;\n    node = node.offsetParent;\n  }\n  if (!node || !el.offsetWidth) return null;\n  return { left: x - canvas.offsetLeft, top: y - canvas.offsetTop, width: el.offsetWidth, height: el.offsetHeight };\n}\n\nfunction quadPoint(sx: number, sy: number, cx: number, cy: number, ex: number, ey: number, t: number, out: [number, number]) {\n  const it = 1 - t;\n  out[0] = it * it * sx + 2 * it * t * cx + t * t * ex;\n  out[1] = it * it * sy + 2 * it * t * cy + t * t * ey;\n  return out;\n}\n\nexport function DitherHorizon({\n  ref,\n  state = \"idle\",\n  muted = false,\n  getLevel,\n  getSpectrum,\n  level,\n  originRef,\n  pointerRef,\n  shape = \"bar\",\n  palette = \"spectral\",\n  colors,\n  interactive = true,\n  cellSize = 2.5,\n  className = \"\",\n  ...props\n}: DitherHorizonProps) {\n  const reduced = useInteractionReducedMotion();\n  const { ref: canvasRef, active: onScreen } = useInteractionActivity<HTMLCanvasElement>();\n  const colorsKey = colors?.join(\"|\") ?? \"\";\n\n  const inputRef = React.useRef({ state, muted, getLevel, getSpectrum, level, shape, interactive, cellSize, reduced });\n  React.useLayoutEffect(() => {\n    inputRef.current = { state, muted, getLevel, getSpectrum, level, shape, interactive, cellSize, reduced };\n  });\n\n  const engineRef = React.useRef<{\n    firePulse: (opts?: DitherHorizonPulseOptions) => void;\n    condense: (el: HTMLElement) => number;\n    triggerTransition: (prev: DitherHorizonState, next: DitherHorizonState) => void;\n    stepAndDraw: (dt: number) => boolean;\n    wake: () => void;\n    springs: Record<\"active\" | \"listen\" | \"think\" | \"speak\" | \"mute\" | \"level\", ReturnType<typeof createSpring>>;\n    clearParticles: () => void;\n    lastState: DitherHorizonState;\n  } | null>(null);\n\n  const rafRef = React.useRef(0);\n  const runningRef = React.useRef(false);\n  const wakeRef = React.useRef<() => void>(() => {});\n\n  React.useImperativeHandle(\n    ref,\n    () => ({\n      pulse(opts) {\n        engineRef.current?.firePulse(opts);\n      },\n      condense(el) {\n        return engineRef.current?.condense(el) ?? 0;\n      },\n    }),\n    [],\n  );\n\n  React.useEffect(() => {\n    const canvas = canvasRef.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!canvas || !ctx) return;\n\n    // The lattice: one ImageData cell per grid cell, scaled up by a whole number of device pixels with no smoothing.\n    const gridCanvas = document.createElement(\"canvas\");\n    const gridCtx = gridCanvas.getContext(\"2d\");\n    if (!gridCtx) return;\n    let gridImg: ImageData | null = null;\n    let gridU32 = new Uint32Array(0);\n    // 16×2 strip stretched with bilinear filtering: the soft wash under the cells, in one drawImage.\n    const BLOOM_W = 16;\n    const bloomCanvas = document.createElement(\"canvas\");\n    bloomCanvas.width = BLOOM_W;\n    bloomCanvas.height = 2;\n    const bloomCtx = bloomCanvas.getContext(\"2d\");\n    const bloomImg = bloomCtx?.createImageData(BLOOM_W, 2) ?? null;\n    const bloomU32 = bloomImg ? new Uint32Array(bloomImg.data.buffer) : null;\n    let frameLevel = new Uint8Array(0); // what each cell got this frame (0 = off), so a word's cells draw over the wave\n    let cols = 0;\n    let rows = 0;\n    let cellPx = 6; // device px\n    let offY = 0; // device px: the grid sits on the canvas's bottom edge\n    let cellCss = 3;\n\n    const layoutGrid = () => {\n      const raw = clamp(inputRef.current.cellSize, 2, 6);\n      cellPx = Math.max(2, Math.round(raw * dpr));\n      cellCss = cellPx / dpr;\n      const nc = Math.max(1, Math.ceil(canvas.width / cellPx));\n      const nr = Math.max(1, Math.ceil(canvas.height / cellPx));\n      offY = canvas.height - nr * cellPx;\n      if (nc === cols && nr === rows && gridImg) return;\n      cols = nc;\n      rows = nr;\n      gridCanvas.width = cols;\n      gridCanvas.height = rows;\n      gridImg = gridCtx.createImageData(cols, rows);\n      gridU32 = new Uint32Array(gridImg.data.buffer);\n      frameLevel = new Uint8Array(cols * rows);\n    };\n\n    const quiet = () => {};\n    const initState = inputRef.current.state;\n    const isInitActive = initState !== \"idle\";\n    const springs = {\n      active: createSpring(isInitActive ? 1 : 0, SPAWN_SPRING, quiet, 0.002),\n      listen: createSpring(initState === \"listening\" ? 1 : 0, MOOD_SPRING, quiet, 0.002),\n      think: createSpring(initState === \"thinking\" ? 1 : 0, MOOD_SPRING, quiet, 0.002),\n      speak: createSpring(initState === \"speaking\" ? 1 : 0, MOOD_SPRING, quiet, 0.002),\n      mute: createSpring(inputRef.current.muted ? 1 : 0, MOOD_SPRING, quiet, 0.002),\n      level: createSpring(0.45, LEVEL_SPRING, quiet, 0.002),\n    };\n\n    const tempA: Rgb = [0, 0, 0];\n    const tempB: Rgb = [0, 0, 0];\n    const cellRgb: Rgb = [0, 0, 0];\n    const pt: [number, number] = [0, 0];\n    const fallbackBands = new Float32Array(BANDS);\n    let colHeights = new Float32Array(0);\n    let colBoost = new Float32Array(0);\n    let colTint = new Float32Array(0);\n    let colTintR = new Float32Array(0);\n    let colTintG = new Float32Array(0);\n    let colTintB = new Float32Array(0);\n\n    let w = 0; // CSS px\n    let h = 0;\n    let dpr = Math.min(2, window.devicePixelRatio || 1);\n    let isLight = false;\n    let stops: Rgb[] = SPECTRAL_DARK;\n    let thinkStops: Rgb[] = THINK_DARK;\n    let originX = 0;\n    let originY = 0;\n    let time = 2.1;\n    let colorPhase = 0.4;\n    let thinkPhase = 0.6;\n    let ignite = isInitActive ? 1 : 0;\n    let igniteOriginU = 0.88;\n    let recentLv = 0;\n    let lastOnset = -5;\n    let emberClock = 0;\n    const bands = new Float32Array(BANDS);\n    let comets: Comet[] = [];\n    const embers: Ember[] = [];\n    const pulses: PulseWave[] = [];\n    let grains: Grain[] = [];\n    const ptr = { x: 0, y: 0, tx: 0, ty: 0, on: 0, target: 0, speed: 0 };\n\n    // The three tones of a colour: dim (the colour, see-through), colour, and the hot core (toward white on dark, deeper ink on light).\n    const tones = (rgb: Rgb, out: Uint32Array, i: number, dimOut: Uint32Array, topOut: Uint32Array) => {\n      dimOut[i] = packRgba(rgb[0], rgb[1], rgb[2], isLight ? 108 : 118);\n      out[i] = packRgba(rgb[0], rgb[1], rgb[2], 255);\n      topOut[i] = isLight\n        ? packRgba(rgb[0] * 0.7, rgb[1] * 0.7, rgb[2] * 0.7, 255)\n        : packRgba(lerp(rgb[0], 255, 0.62), lerp(rgb[1], 255, 0.62), lerp(rgb[2], 255, 0.62), 255);\n    };\n    const one = { dim: new Uint32Array(1), mid: new Uint32Array(1), top: new Uint32Array(1) };\n    const toneOf = (rgb: Rgb, level: number) => {\n      tones(rgb, one.mid, 0, one.dim, one.top);\n      return level >= 3 ? one.top[0] : level === 2 ? one.mid[0] : one.dim[0];\n    };\n\n    /** Write a cell if it is brighter than what's there this frame. */\n    const plot = (col: number, row: number, level: number, color: number) => {\n      if (col < 0 || row < 0 || col >= cols || row >= rows || level <= 0) return;\n      const i = row * cols + col;\n      if (frameLevel[i] >= level) return;\n      frameLevel[i] = level;\n      gridU32[i] = color;\n    };\n    /** CSS px → lattice cell. */\n    const colAt = (x: number) => Math.floor((x * dpr) / cellPx);\n    const rowAt = (y: number) => Math.floor((y * dpr - offY) / cellPx);\n\n    const measureOrigin = () => {\n      if (w <= 0 || h <= 0) return;\n      const originEl = originRef?.current;\n      const box = originEl ? boxWithin(originEl, canvas) : null;\n      if (box) {\n        originX = clamp(box.left + box.width * 0.5, 12, w - 12);\n        originY = clamp(box.top + box.height * 0.5, 12, h - 12);\n        return;\n      }\n      originX = Math.max(16, w - 34);\n      originY = Math.max(16, h - 32);\n    };\n\n    const refreshTheme = () => {\n      const host = canvas.parentElement ?? canvas;\n      isLight = detectLightSurface(host);\n      stops = resolvePalette(host, palette, colorsKey ? colorsKey.split(\"|\") : undefined, isLight);\n      thinkStops = isLight ? THINK_LIGHT : THINK_DARK;\n    };\n\n    const liveColor = (u: number, wThink: number, scanU: number, out: Rgb): Rgb => {\n      const phase = u * 1.45 - colorPhase * 0.22 + 0.05 * Math.sin(u * 7.5 + time * 0.6);\n      sampleStops(stops, phase, tempA);\n      if (wThink > 0.01) {\n        sampleStops(thinkStops, (u - scanU) * 0.92 + 0.35 - colorPhase * 0.12, tempB);\n        out[0] = lerp(tempA[0], tempB[0], wThink);\n        out[1] = lerp(tempA[1], tempB[1], wThink);\n        out[2] = lerp(tempA[2], tempB[2], wThink);\n      } else {\n        out[0] = tempA[0];\n        out[1] = tempA[1];\n        out[2] = tempA[2];\n      }\n      return out;\n    };\n\n    const eng: NonNullable<typeof engineRef.current> = {\n      springs,\n      lastState: initState,\n\n      clearParticles() {\n        comets = [];\n        embers.length = 0;\n        pulses.length = 0;\n        grains = [];\n      },\n\n      firePulse(opts = {}) {\n        if (inputRef.current.reduced || w <= 0 || h <= 0) return;\n        const kind = opts.kind ?? \"ripple\";\n        const strength = clamp(opts.strength ?? 0.85, 0.2, 1.4);\n        let originU = 0.5;\n        let ox = w * 0.5;\n        let oy = h - 24;\n        if (typeof opts.origin === \"number\") {\n          originU = clamp01(opts.origin);\n          ox = originU * w;\n          oy = h - 6;\n        } else if (opts.origin instanceof HTMLElement) {\n          const box = boxWithin(opts.origin, canvas);\n          if (box) {\n            ox = clamp(box.left + box.width * 0.5, 10, w - 10);\n            oy = clamp(box.top + box.height * 0.5, 10, h - 10);\n            originU = clamp01(ox / w);\n          }\n        }\n        const host = canvas.parentElement ?? canvas;\n        const rgb = opts.color ? cssToRgb(host, opts.color, stops[0]) : null;\n        const life = kind === \"spark\" ? 0.34 : kind === \"wipe\" ? 0.55 : 0.72;\n        if (pulses.length > 10) pulses.shift();\n        pulses.push({ kind, originU, age: 0, life, strength, rgb });\n\n        // Action ripples (attach, mode switch) throw a few cell comets out of that control along the rim.\n        if (kind === \"ripple\") {\n          const dir = originU < 0.5 ? 1 : -1;\n          for (let i = 0; i < 7; i++) {\n            const reach = (0.14 + (i / 6) * 0.42 + Math.random() * 0.08) * dir;\n            const targetU = clamp(originU + reach, 0.05, 0.95);\n            const ex = targetU * w;\n            const ey = h - 2 - Math.random() * 10;\n            const sx = ox + (Math.random() - 0.5) * 10;\n            const sy = oy + (Math.random() - 0.5) * 8;\n            const cRgb: Rgb = rgb ? [rgb[0], rgb[1], rgb[2]] : [0, 0, 0];\n            if (!rgb) sampleStops(stops, targetU * 1.4 - colorPhase * 0.22, cRgb);\n            comets.push({ mode: \"burst\", sx, sy, cx: lerp(sx, ex, 0.38), cy: h - 1, ex, ey, age: 0, delay: i * 0.015, life: 0.28 + Math.random() * 0.16, size: 2.5 + Math.random() * 0.9, rgb: cRgb });\n          }\n        }\n        eng.wake();\n      },\n\n      condense(el) {\n        if (inputRef.current.reduced || w <= 0 || h <= 0 || cols === 0) return 0;\n        const text = el.textContent?.trim();\n        if (!text) return 0;\n        // Where the word rests in layout (offsets ignore its entrance and any zoom or tilt on the page).\n        const r = boxWithin(el, canvas);\n        if (!r || r.width <= 0 || r.height <= 0) return 0;\n        const left = r.left;\n        const top = r.top;\n        // Rasterise the word on the lattice itself: one mask pixel per cell.\n        const c0 = colAt(left);\n        const r0 = rowAt(top);\n        const mw = Math.max(1, Math.ceil((left + r.width) * dpr / cellPx) - c0 + 1);\n        const mh = Math.max(1, Math.ceil(((top + r.height) * dpr - offY) / cellPx) - r0 + 1);\n        const mask = document.createElement(\"canvas\");\n        mask.width = mw;\n        mask.height = mh;\n        const mctx = mask.getContext(\"2d\", { willReadFrequently: true });\n        if (!mctx) return 0;\n        const cs = getComputedStyle(el);\n        const scale = 1 / cellCss;\n        mctx.font = `${cs.fontStyle} ${cs.fontWeight} ${parseFloat(cs.fontSize) * scale}px ${cs.fontFamily}`;\n        mctx.textBaseline = \"middle\";\n        mctx.fillStyle = \"#000\";\n        // Where the word's box starts inside its first cell, in mask px.\n        const fx = (left * dpr) / cellPx - c0;\n        const fy = ((top * dpr - offY) / cellPx - r0);\n        mctx.fillText(text, fx, fy + (r.height * scale) / 2);\n        const data = mctx.getImageData(0, 0, mw, mh).data;\n        const sym = Math.abs(clamp01((left + r.width / 2) / w) - 0.5);\n        const added: Grain[] = [];\n        for (let y = 0; y < mh; y++) {\n          for (let x = 0; x < mw; x++) {\n            if (data[(y * mw + x) * 4 + 3] < 96) continue;\n            const col = c0 + x;\n            const row = r0 + y;\n            const tx = ((col + 0.5) * cellPx) / dpr;\n            // Each cell starts on the wave, a little to either side of where it will land, and rises to it.\n            const sx = clamp(tx + (Math.random() - 0.5) * 64, 4, w - 4);\n            const sy = h - 3 - Math.random() * Math.min(26, h * 0.25);\n            const ty = ((row + 0.5) * cellPx + offY) / dpr;\n            const rgb: Rgb = [0, 0, 0];\n            sampleStops(stops, (sx / w) * 1.45 - colorPhase * 0.22 + sym * 0.1, rgb);\n            added.push({ col, row, sx, sy, cx: lerp(sx, tx, 0.7), cy: Math.min(sy, ty) - 14 - Math.random() * 18, age: 0, delay: (x / Math.max(1, mw)) * GRAIN_SPREAD + Math.random() * 0.05, fly: GRAIN_FLY * (0.8 + Math.random() * 0.4), rgb });\n          }\n        }\n        if (grains.length + added.length > 1400) grains.splice(0, grains.length + added.length - 1400);\n        grains.push(...added);\n        eng.wake();\n        return Math.round((GRAIN_SPREAD + GRAIN_FLY) * 1000);\n      },\n\n      triggerTransition(prev, next) {\n        if (w <= 0 || h <= 0) return;\n        measureOrigin();\n        const ox = originX;\n        const oy = originY;\n        const origU = clamp01(ox / w);\n\n        // SPAWN: idle -> active. Cell comets burst out of the button and light the field.\n        if (prev === \"idle\" && next !== \"idle\") {\n          ignite = 0;\n          igniteOriginU = origU;\n          comets = comets.filter((c) => c.mode !== \"dismiss\");\n          const count = Math.min(28, Math.max(16, Math.round(w / 20)));\n          const st = next === \"thinking\" ? thinkStops : stops;\n          for (let i = 0; i < count; i++) {\n            const frac = (i + 0.3 + Math.random() * 0.4) / count;\n            const targetU = clamp(0.05 + frac * 0.88, 0.04, 0.95);\n            const ex = targetU * w;\n            const ey = h - 2 - Math.random() * 12;\n            const sx = ox + (Math.random() - 0.5) * 12;\n            const sy = oy + (Math.random() - 0.5) * 10;\n            const rgb: Rgb = [0, 0, 0];\n            sampleStops(st, targetU * 1.35 - colorPhase * 0.22, rgb);\n            comets.push({\n              mode: \"spawn\",\n              sx,\n              sy,\n              cx: lerp(sx, ex, 0.34) - (sx - ex) * 0.06,\n              cy: h - 1 + Math.random() * 4,\n              ex,\n              ey,\n              age: 0,\n              delay: (1 - targetU) * 0.08 + Math.random() * 0.06,\n              life: 0.34 + Math.abs(origU - targetU) * 0.26 + Math.random() * 0.07,\n              size: 2.6 + Math.random() * 1.1,\n              rgb,\n            });\n          }\n        }\n\n        // DISMISS: active -> idle. The wave breaks into cell comets drawn back into the button.\n        if (prev !== \"idle\" && next === \"idle\") {\n          comets = comets.filter((c) => c.mode !== \"spawn\");\n          grains = [];\n          const count = Math.min(32, Math.max(18, Math.round(w / 17)));\n          const st = springs.think.get() > 0.5 ? thinkStops : stops;\n          const peakH = inputRef.current.shape === \"card\" ? Math.min(h * 0.38, 66) : Math.min(h * 0.42, 46);\n          for (let i = 0; i < count; i++) {\n            const u = clamp(0.06 + (i / Math.max(1, count - 1)) * 0.8 + (Math.random() - 0.5) * 0.05, 0.04, 0.9);\n            const sx = u * w;\n            const sy = h - 2.5 - Math.random() * peakH * (0.25 + 0.75 * Math.sin(Math.PI * u));\n            const ex = ox + (Math.random() - 0.5) * 8;\n            const ey = oy + (Math.random() - 0.5) * 8;\n            const rgb: Rgb = [0, 0, 0];\n            sampleStops(st, u * 1.35 - colorPhase * 0.22, rgb);\n            comets.push({ mode: \"dismiss\", sx, sy, cx: lerp(sx, ex, 0.75), cy: h - 2 - Math.random() * 7, ex, ey, age: 0, delay: (1 - u) * 0.055 + Math.random() * 0.075, life: 0.34 + (1 - u) * 0.2 + Math.random() * 0.07, size: 2.6 + Math.random() * 1.1, rgb });\n          }\n        }\n      },\n\n      stepAndDraw(dt) {\n        if (w <= 0 || h <= 0) return false;\n        layoutGrid();\n        const { state: s, muted: isMuted, getLevel: readLevel, getSpectrum: readSpec, level: scalarLevel, shape: sh, interactive: canHover } = inputRef.current;\n\n        const wActive = clamp01(springs.active.get());\n        const wListen = clamp01(springs.listen.get());\n        const wThink = clamp01(springs.think.get());\n        const wSpeak = clamp01(springs.speak.get());\n        const wMute = clamp01(springs.mute.get());\n\n        time += dt;\n        colorPhase += dt * (0.42 + 0.38 * wListen + 0.52 * wSpeak + 0.72 * wThink);\n        thinkPhase += dt * (1.82 + 1.05 * wThink);\n        if (s !== \"idle\" && ignite < 1) ignite = Math.min(1, ignite + dt / 0.5);\n\n        const voiced = (s === \"listening\" && !isMuted) || s === \"speaking\";\n        let targetLv = 0;\n        if (voiced) {\n          if (readLevel) targetLv = clamp01(readLevel());\n          else if (scalarLevel !== undefined) targetLv = clamp01(scalarLevel);\n          else targetLv = speechFallback(time + (s === \"speaking\" ? 2.4 : 0), fallbackBands);\n        }\n        springs.level.set(targetLv);\n        const lv = clamp01(springs.level.get());\n\n        // A clear spoken syllable sends a ripple outward across the cells.\n        if (voiced && dt > 0 && lv - recentLv > 0.16 && lv > 0.42 && time - lastOnset > 0.65) {\n          lastOnset = time;\n          if (pulses.length < 8) pulses.push({ kind: \"wipe\", originU: 0.5 + (Math.random() - 0.5) * 0.24, age: 0, life: 0.68, strength: 0.42, rgb: null });\n        }\n        recentLv += (lv - recentLv) * (1 - Math.exp(-dt * 4.5));\n\n        const riseRate = 1 - Math.exp(-dt * 12);\n        const fallRate = 1 - Math.exp(-dt * 3.4);\n        for (let b = 0; b < BANDS; b++) {\n          let v = 0;\n          if (voiced && readSpec) {\n            const got = readSpec();\n            v = clamp01(got[Math.floor((b * got.length) / BANDS)] ?? 0);\n          } else if (voiced && readLevel === undefined && scalarLevel === undefined) v = fallbackBands[b];\n          else if (voiced) v = clamp01(lv * (0.55 + 0.45 * Math.sin(time * 4.8 + b * 1.5)));\n          bands[b] += (v - bands[b]) * (v > bands[b] ? riseRate : fallRate);\n        }\n\n        if (pulses.length > 0 && dt > 0) {\n          let pw = 0;\n          for (let i = 0; i < pulses.length; i++) {\n            const p = pulses[i];\n            p.age += dt;\n            if (p.age < p.life) pulses[pw++] = p;\n          }\n          pulses.length = pw;\n        }\n\n        const ptrSmooth = 1 - Math.exp(-dt * 14);\n        const px0 = ptr.x;\n        const py0 = ptr.y;\n        ptr.x += (ptr.tx - ptr.x) * ptrSmooth;\n        ptr.y += (ptr.ty - ptr.y) * ptrSmooth;\n        ptr.on += (ptr.target - ptr.on) * (1 - Math.exp(-dt * 7));\n        ptr.speed = dt > 0 ? Math.hypot(ptr.x - px0, ptr.y - py0) / dt : 0;\n\n        gridU32.fill(0);\n        frameLevel.fill(0);\n\n        const isCard = sh === \"card\";\n        const maxH = isCard ? Math.min(h * 0.42, 78) : Math.min(h * 0.56, 62);\n        if (colHeights.length !== cols) {\n          colHeights = new Float32Array(cols);\n          colBoost = new Float32Array(cols);\n          colTint = new Float32Array(cols);\n          colTintR = new Float32Array(cols);\n          colTintG = new Float32Array(cols);\n          colTintB = new Float32Array(cols);\n        }\n\n        const hasField = wActive > 0.004 || pulses.length > 0;\n        const t = time;\n        const ptrU = clamp01(ptr.x / Math.max(1, w));\n        const ptrBoost = canHover ? ptr.on * wActive * (1 - wMute * 0.72) : 0;\n        const scanU = 0.5 + 0.44 * Math.sin(thinkPhase);\n        const scanDir = Math.cos(thinkPhase) >= 0 ? 1 : -1;\n        const muteRowH = cellCss * (1.5 + 0.4 * Math.sin(t * 1.6)); // the folded, breathing dotted row\n        const muteMix = wMute * wListen;\n\n        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n        ctx.clearRect(0, 0, w, h);\n\n        if (hasField) {\n          for (let c = 0; c < cols; c++) {\n            const u = (c + 0.5) / cols;\n            const taper = isCard ? Math.pow(Math.sin(Math.PI * u), 1.45) : Math.pow(Math.sin(Math.PI * u), 0.52);\n            const distFromOrigin = Math.abs(u - igniteOriginU);\n            const ign = wActive > 0.004 ? smoothstep(distFromOrigin - 0.14, distFromOrigin + 0.08, ignite * 1.18) : 0;\n\n            let pHeight = 0;\n            let pBoost = 0;\n            let pTint = 0;\n            let pR = 0;\n            let pG = 0;\n            let pB = 0;\n            for (let pi = 0; pi < pulses.length; pi++) {\n              const p = pulses[pi];\n              const k = p.age / p.life;\n              const env = Math.sin(Math.PI * Math.pow(k, 0.65));\n              if (p.kind === \"spark\") {\n                const d = (u - p.originU) / (0.065 + 0.12 * k);\n                const g = Math.exp(-d * d) * env * p.strength;\n                pHeight += g * 16;\n                pBoost += g * 0.55;\n              } else {\n                const d = (Math.abs(u - p.originU) - k * 1.05) / (p.kind === \"wipe\" ? 0.11 : 0.085);\n                const ring = Math.exp(-d * d) * env * p.strength;\n                pHeight += ring * (p.kind === \"ripple\" ? 26 : 16);\n                pBoost += ring * 0.6;\n                if (p.rgb && ring > 0.02) {\n                  pTint = Math.min(1, pTint + ring * 0.78);\n                  pR = p.rgb[0];\n                  pG = p.rgb[1];\n                  pB = p.rgb[2];\n                }\n              }\n            }\n            colBoost[c] = pBoost;\n            colTint[c] = pTint;\n            colTintR[c] = pR;\n            colTintG[c] = pG;\n            colTintB[c] = pB;\n\n            let baseH = 0;\n            if (wActive > 0.004) {\n              const sym = Math.abs(u - 0.5) * 2;\n              const bandVal = bands[clamp(Math.floor(sym * (BANDS - 1)), 0, BANDS - 1)];\n              const centerDome = Math.exp(-((u - 0.5) ** 2) / (isCard ? 0.056 : 0.105));\n              const peakA = Math.exp(-((u - (0.31 + 0.11 * Math.sin(t * 0.9))) ** 2) / 0.022);\n              const peakB = Math.exp(-((u - (0.65 + 0.1 * Math.cos(t * 0.78))) ** 2) / 0.024);\n              const harmonic = 0.5 + 0.5 * Math.sin(u * 14 - t * 3.1) * Math.cos(u * 7.5 + t * 2.1);\n              const listenLive = (0.18 + 0.46 * centerDome + 0.24 * peakA + 0.22 * peakB + 0.16 * harmonic) * (0.45 + 0.7 * (0.55 * lv + 0.45 * bandVal));\n              const hListen = lerp(listenLive, muteRowH / maxH, wMute);\n\n              const dx = u - scanU;\n              const scanner = Math.tanh(Math.exp(-(dx * dx) / 0.07) * 1.45);\n              const behind = -dx * scanDir;\n              const trail = behind > 0 ? Math.exp(-behind / 0.36) * 0.34 : 0;\n              const floor = 0.11 + 0.05 * (0.5 + 0.5 * Math.sin(u * 22 - t * 3.8));\n              const hThink = clamp01((floor + 0.54 * scanner + trail) * 0.86);\n\n              const speakDome = Math.exp(-((u - 0.5) ** 2) / (isCard ? 0.048 : 0.082));\n              const speakRipple = 0.13 * (0.5 + 0.5 * Math.sin(u * 16 + t * 3.8));\n              const hSpeak = clamp01((0.2 + 0.74 * speakDome + speakRipple) * (0.48 + 0.65 * (0.6 * lv + 0.4 * bandVal)));\n\n              const totalW = Math.max(0.001, wListen + wThink + wSpeak);\n              let hNorm = (hListen * wListen + hThink * wThink + hSpeak * wSpeak) / totalW;\n              if (ptrBoost > 0.01) {\n                const pDist = u - ptrU;\n                hNorm += 0.28 * ptrBoost * Math.exp(-(pDist * pDist) / 0.016);\n              }\n              // A muted row runs the full width (no taper), so it reads as a dotted line, not a hump.\n              baseH = clamp(hNorm, 0, 1.14) * maxH * lerp(taper, 1, muteMix) * wActive * ign;\n            }\n            colHeights[c] = Math.min(maxH * 1.3, baseH + pHeight * (0.35 + 0.65 * taper));\n          }\n\n          // LAYER 1: the soft horizon wash, one bilinear drawImage of a 16×2 strip.\n          if (bloomCtx && bloomImg && bloomU32) {\n            bloomU32.fill(0);\n            for (let i = 0; i < BLOOM_W; i++) {\n              const u = (i + 0.5) / BLOOM_W;\n              const ch = colHeights[clamp(Math.floor(u * cols), 0, cols - 1)];\n              if (ch < 2) continue;\n              liveColor(u, wThink, scanU, cellRgb);\n              const alpha = (isLight ? 0.09 : 0.24) * clamp01(ch / (maxH * 0.52)) * (1 - 0.6 * muteMix);\n              bloomU32[BLOOM_W + i] = packRgba(cellRgb[0], cellRgb[1], cellRgb[2], alpha * 255);\n            }\n            bloomCtx.putImageData(bloomImg, 0, 0);\n            const washH = Math.max(24, maxH * 1.15);\n            ctx.save();\n            ctx.imageSmoothingEnabled = true;\n            ctx.globalCompositeOperation = isLight ? \"source-over\" : \"lighter\";\n            ctx.drawImage(bloomCanvas, 0, h - washH, w, washH + 2);\n            ctx.restore();\n          }\n\n          // LAYER 2: the 1.5px rim along the bottom edge, faded out before the corners so it never pokes past them.\n          if (muteMix < 0.5) {\n            const rimGrad = ctx.createLinearGradient(0, 0, w, 0);\n            for (let i = 0; i <= 8; i++) {\n              const u = i / 8;\n              const strength = clamp01(colHeights[clamp(Math.floor(u * (cols - 1)), 0, cols - 1)] / (maxH * 0.25)) * smoothstep(0, 0.1, u) * smoothstep(1, 0.9, u);\n              liveColor(u, wThink, scanU, cellRgb);\n              const a = (isLight ? 0.36 : 0.76) * strength * (1 - muteMix * 2);\n              rimGrad.addColorStop(u, `rgba(${cellRgb[0] | 0},${cellRgb[1] | 0},${cellRgb[2] | 0},${a.toFixed(3)})`);\n            }\n            ctx.fillStyle = rimGrad;\n            ctx.fillRect(0, h - 1.5, w, 1.5);\n          }\n\n          // LAYER 3: the ordered 8×8 Bayer field. Each column's cells from the bottom up: lit where its energy clears the\n          // Bayer threshold, so density falls from a fused base through checkerboards (the dark holes) into single grains.\n          const breath = 0.5 + 0.06 * Math.sin(t * 1.6); // the muted row: about every other cell lit, breathing\n          for (let c = 0; c < cols; c++) {\n            const ch = colHeights[c];\n            if (ch < 1.2) continue;\n            const u = (c + 0.5) / cols;\n            liveColor(u, wThink, scanU, cellRgb);\n            const pTint = colTint[c];\n            if (pTint > 0.01) {\n              cellRgb[0] = lerp(cellRgb[0], colTintR[c], pTint);\n              cellRgb[1] = lerp(cellRgb[1], colTintG[c], pTint);\n              cellRgb[2] = lerp(cellRgb[2], colTintB[c], pTint);\n            }\n            const pBoost = colBoost[c];\n            const scan = wThink > 0.01 ? wThink * Math.exp(-((u - scanU) ** 2) / 0.012) : 0;\n            const maxR = Math.min(rows, Math.ceil((ch + cellCss) / cellCss));\n            for (let r = 0; r < maxR; r++) {\n              const v = ((r + 0.35) * cellCss) / Math.max(cellCss, ch);\n              if (v >= 1.04) break;\n              const baseE = Math.pow(clamp01(1 - v), 1.22);\n              const shimmer = 0.035 * Math.sin(c * 0.65 + r * 1.15 - t * 5.6);\n              let energy = clamp01(baseE + pBoost * 0.22 * (1 - v * 0.4) + scan * 0.18 * (1 - v) + shimmer * (1 - baseE * 0.6));\n              if (muteMix > 0.01) energy = lerp(energy, r === 0 ? breath + pBoost * 0.3 : 0, muteMix);\n\n              const threshold = BAYER8[((r & 7) << 3) | (c & 7)];\n              const hit = clamp01((energy - threshold + 0.035) / 0.075);\n              if (hit <= 0.02) continue;\n\n              let cr = cellRgb[0];\n              let cg = cellRgb[1];\n              let cb = cellRgb[2];\n              if (!isLight) {\n                // White-hot where the cells fuse along the base, plus a glint on a passing wavefront.\n                const hot = (Math.pow(clamp01((energy - 0.5) / 0.5), 1.35) * (0.72 - 0.08 * wThink) + pBoost * 0.32 * (1 - v * 0.5)) * (1 - muteMix);\n                if (hot > 0.005) {\n                  const k = Math.min(0.86, hot);\n                  cr = lerp(cr, 255, k);\n                  cg = lerp(cg, 255, k);\n                  cb = lerp(cb, 255, k);\n                }\n              } else {\n                // Deeper ink where the cells fuse on light surfaces.\n                const deep = Math.pow(clamp01((energy - 0.58) / 0.42), 1.15) * 0.2 * (1 - muteMix);\n                if (deep > 0.005) {\n                  cr *= 1 - deep;\n                  cg *= 1 - deep;\n                  cb *= 1 - deep;\n                }\n              }\n              const alpha = hit * (isLight ? 0.94 : 0.98) * (0.55 + 0.45 * Math.pow(energy, 0.38));\n              const i = (rows - 1 - r) * cols + c;\n              gridU32[i] = packRgba(cr, cg, cb, alpha * 255);\n              frameLevel[i] = 1;\n            }\n          }\n        }\n\n        // A word's cells: rise from the wave, land in the word's shape, hold, then switch off in Bayer order.\n        if (grains.length > 0) {\n          let write = 0;\n          for (let i = 0; i < grains.length; i++) {\n            const g = grains[i];\n            g.age += dt;\n            const tl = g.age - g.delay;\n            if (tl < 0) {\n              grains[write++] = g;\n              continue;\n            }\n            if (tl < g.fly) {\n              const k = 1 - Math.pow(1 - tl / g.fly, 3);\n              const tx = ((g.col + 0.5) * cellPx) / dpr;\n              const ty = ((g.row + 0.5) * cellPx + offY) / dpr;\n              quadPoint(g.sx, g.sy, g.cx, g.cy, tx, ty, k, pt);\n              plot(colAt(pt[0]), rowAt(pt[1]), 3, toneOf(g.rgb, 3));\n              quadPoint(g.sx, g.sy, g.cx, g.cy, tx, ty, Math.max(0, k - 0.12), pt);\n              plot(colAt(pt[0]), rowAt(pt[1]), 2, toneOf(g.rgb, 1));\n              grains[write++] = g;\n              continue;\n            }\n            const after = tl - g.fly;\n            if (after >= GRAIN_HOLD + GRAIN_FADE) continue;\n            const fade = after < GRAIN_HOLD ? 0 : (after - GRAIN_HOLD) / GRAIN_FADE;\n            if (fade < bayer(g.col, g.row)) {\n              const level = after < GRAIN_HOLD * 0.5 ? 3 : 2;\n              plot(g.col, g.row, level, toneOf(g.rgb, level));\n            }\n            grains[write++] = g;\n          }\n          grains.length = write;\n        }\n\n        // The grid, scaled up by whole device pixels with no smoothing, on the canvas's bottom edge.\n        if (gridImg) {\n          gridCtx.putImageData(gridImg, 0, 0);\n          ctx.save();\n          ctx.setTransform(1, 0, 0, 1, 0, 0);\n          ctx.imageSmoothingEnabled = false;\n          ctx.drawImage(gridCanvas, 0, offY, cols * cellPx, rows * cellPx);\n          ctx.restore();\n        }\n\n        // LAYER 4A: embers the pointer lifts off the crest.\n        if (ptrBoost > 0.08 && wActive > 0.35 && dt > 0) {\n          const emitInterval = clamp(0.03 - Math.min(ptr.speed, 600) * 0.000025, 0.014, 0.03);\n          emberClock += dt;\n          while (emberClock >= emitInterval && embers.length < 56) {\n            emberClock -= emitInterval;\n            const ex = clamp(ptr.x + (Math.random() - 0.5) * 72, 6, w - 6);\n            const localH = colHeights[clamp(colAt(ex), 0, Math.max(0, cols - 1))] ?? 10;\n            const ey = h - Math.max(3, localH * (0.52 + Math.random() * 0.48));\n            const waveRgb: Rgb = [0, 0, 0];\n            sampleStops(wThink > 0.5 ? thinkStops : stops, (ex / Math.max(1, w)) * 1.45 - colorPhase * 0.22, waveRgb);\n            const warm = isLight ? EMBER_LIGHT : EMBER_DARK;\n            const mix = wThink > 0.5 ? 0.22 : 0.58;\n            embers.push({\n              x: ex,\n              y: ey,\n              vx: (ptr.x - ex) * (0.75 + Math.random() * 0.55) + (Math.random() - 0.5) * 16,\n              vy: -34 - Math.random() * 42,\n              age: 0,\n              life: 0.54 + Math.random() * 0.4,\n              size: 2.2 + Math.random() * 0.9,\n              seed: Math.random() * Math.PI * 2,\n              rgb: [lerp(waveRgb[0], warm[0], mix), lerp(waveRgb[1], warm[1], mix), lerp(waveRgb[2], warm[2], mix)],\n            });\n          }\n        }\n        if (embers.length > 0) {\n          let write = 0;\n          for (let i = 0; i < embers.length; i++) {\n            const p = embers[i];\n            p.age += dt;\n            if (p.age >= p.life) continue;\n            const k = p.age / p.life;\n            if (ptr.on > 0.1) {\n              p.vx += (ptr.x - p.x) * 2.2 * dt;\n              p.vy += (Math.min(ptr.y, h - 16) - p.y) * 1.15 * dt;\n            }\n            p.vx += Math.sin(p.age * 8.5 + p.seed) * 30 * dt;\n            p.vy -= 20 * dt;\n            const damp = Math.pow(0.24, dt);\n            p.vx *= damp;\n            p.vy *= damp;\n            p.x += p.vx * dt;\n            p.y += p.vy * dt;\n            const sz = p.size * (1 - 0.35 * k);\n            ctx.globalAlpha = clamp01(Math.sin(Math.PI * Math.pow(k, 0.72)) * (isLight ? 0.92 : 0.96));\n            ctx.fillStyle = `rgb(${p.rgb[0] | 0},${p.rgb[1] | 0},${p.rgb[2] | 0})`;\n            ctx.fillRect(p.x - sz * 0.5, p.y - sz * 0.5, sz, sz);\n            embers[write++] = p;\n          }\n          embers.length = write;\n          ctx.globalAlpha = 1;\n        }\n\n        // LAYER 4B: comets (spawn burst, dismiss return, action bursts).\n        if (comets.length > 0) {\n          ctx.save();\n          ctx.lineCap = \"round\";\n          if (!isLight) ctx.globalCompositeOperation = \"lighter\";\n          let write = 0;\n          for (let i = 0; i < comets.length; i++) {\n            const c = comets[i];\n            c.age += dt;\n            const tl = c.age - c.delay;\n            if (tl < 0) {\n              comets[write++] = c;\n              continue;\n            }\n            const k = tl / c.life;\n            if (k >= 1) continue;\n            const isOut = c.mode !== \"dismiss\";\n            const eased = isOut ? 1 - Math.pow(1 - k, 2.7) : Math.pow(k, 2.35);\n            const tailK = isOut ? Math.max(0, 1 - Math.pow(1 - Math.max(0, k - 0.14), 2.7)) : Math.pow(Math.max(0, k - 0.17), 2.35);\n            quadPoint(c.sx, c.sy, c.cx, c.cy, c.ex, c.ey, eased, pt);\n            const nx = pt[0];\n            const ny = pt[1];\n            quadPoint(c.sx, c.sy, c.cx, c.cy, c.ex, c.ey, tailK, pt);\n            const tx = pt[0];\n            const ty = pt[1];\n            const alpha = isOut ? Math.sin(Math.PI * Math.min(1, k * 1.05)) : smoothstep(0, 0.12, k) * (1 - smoothstep(0.84, 1, k));\n            const r = c.rgb[0] | 0;\n            const g = c.rgb[1] | 0;\n            const b = c.rgb[2] | 0;\n            if (Math.hypot(nx - tx, ny - ty) > 1.2) {\n              const streak = ctx.createLinearGradient(tx, ty, nx, ny);\n              streak.addColorStop(0, `rgba(${r},${g},${b},0)`);\n              streak.addColorStop(0.55, `rgba(${r},${g},${b},${(alpha * 0.55).toFixed(3)})`);\n              streak.addColorStop(1, `rgba(${r},${g},${b},${(alpha * 0.95).toFixed(3)})`);\n              ctx.strokeStyle = streak;\n              ctx.lineWidth = c.mode === \"burst\" ? 1.25 : 1.5;\n              ctx.beginPath();\n              ctx.moveTo(tx, ty);\n              ctx.lineTo(nx, ny);\n              ctx.stroke();\n            }\n            const head = c.size * (1 - 0.25 * k);\n            ctx.globalAlpha = clamp01(alpha);\n            ctx.fillStyle = isLight ? `rgb(${r},${g},${b})` : `rgb(${Math.min(255, r + 68)},${Math.min(255, g + 68)},${Math.min(255, b + 68)})`;\n            ctx.fillRect(nx - head * 0.5, ny - head * 0.5, head, head);\n            ctx.globalAlpha = 1;\n            comets[write++] = c;\n          }\n          comets.length = write;\n          ctx.restore();\n        }\n\n        // Sleep when idle and every particle, pulse and spring has settled.\n        return (\n          s !== \"idle\" ||\n          wActive > 0.004 ||\n          comets.length > 0 ||\n          embers.length > 0 ||\n          pulses.length > 0 ||\n          grains.length > 0 ||\n          Math.abs(springs.active.getVelocity()) > 0.005\n        );\n      },\n\n      wake() {\n        wakeRef.current();\n      },\n    };\n\n    engineRef.current = eng;\n\n    const resize = () => {\n      // Layout size, not screen size: a zoomed or tilted container mustn't change the lattice.\n      const nw = canvas.offsetWidth;\n      const nh = canvas.offsetHeight;\n      if (nw <= 0 || nh <= 0) return;\n      const nd = Math.min(2, window.devicePixelRatio || 1);\n      if (nw !== w || nh !== h || nd !== dpr) {\n        w = nw;\n        h = nh;\n        dpr = nd;\n        canvas.width = Math.round(nw * nd);\n        canvas.height = Math.round(nh * nd);\n        cols = 0; // re-lay the grid\n      }\n      measureOrigin();\n      refreshTheme();\n      eng.stepAndDraw(0);\n    };\n\n    resize();\n    const ro = new ResizeObserver(resize);\n    ro.observe(canvas);\n\n    const mo = new MutationObserver(() => {\n      refreshTheme();\n      eng.stepAndDraw(0);\n    });\n    mo.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n\n    const hostEl = pointerRef?.current ?? canvas.parentElement;\n    const onPointerMove = (ev: PointerEvent) => {\n      if (!inputRef.current.interactive) return;\n      const cr = canvas.getBoundingClientRect();\n      ptr.tx = ev.clientX - cr.left;\n      ptr.ty = ev.clientY - cr.top;\n      if (ptr.target === 0) {\n        ptr.x = ptr.tx;\n        ptr.y = ptr.ty;\n      }\n      ptr.target = 1;\n      eng.wake();\n    };\n    const onPointerLeave = () => {\n      ptr.target = 0;\n    };\n    hostEl?.addEventListener(\"pointermove\", onPointerMove, { passive: true });\n    hostEl?.addEventListener(\"pointerleave\", onPointerLeave, { passive: true });\n\n    return () => {\n      ro.disconnect();\n      mo.disconnect();\n      hostEl?.removeEventListener(\"pointermove\", onPointerMove);\n      hostEl?.removeEventListener(\"pointerleave\", onPointerLeave);\n      Object.values(springs).forEach((sp) => sp.stop());\n      engineRef.current = null;\n    };\n  }, [canvasRef, palette, colorsKey, originRef, pointerRef]);\n\n  React.useEffect(() => {\n    const eng = engineRef.current;\n    if (!eng) return;\n    const prev = eng.lastState;\n    eng.lastState = state;\n    const isAct = state !== \"idle\";\n    if (reduced) {\n      eng.clearParticles();\n      eng.springs.active.jump(isAct ? 1 : 0);\n      eng.springs.listen.jump(state === \"listening\" ? 1 : 0);\n      eng.springs.think.jump(state === \"thinking\" ? 1 : 0);\n      eng.springs.speak.jump(state === \"speaking\" ? 1 : 0);\n      eng.springs.mute.jump(muted ? 1 : 0);\n      eng.springs.level.jump(muted ? 0.1 : 0.62);\n      eng.stepAndDraw(0);\n      return;\n    }\n    if (prev !== state) eng.triggerTransition(prev, state);\n    eng.springs.active.configure(isAct ? SPAWN_SPRING : DISMISS_SPRING);\n    eng.springs.active.set(isAct ? 1 : 0);\n    eng.springs.listen.set(state === \"listening\" ? 1 : 0);\n    eng.springs.think.set(state === \"thinking\" ? 1 : 0);\n    eng.springs.speak.set(state === \"speaking\" ? 1 : 0);\n    eng.springs.mute.set(muted ? 1 : 0);\n    eng.wake();\n  }, [state, muted, reduced]);\n\n  React.useEffect(() => {\n    if (!onScreen || reduced) {\n      if (rafRef.current) {\n        cancelAnimationFrame(rafRef.current);\n        rafRef.current = 0;\n      }\n      runningRef.current = false;\n      if (reduced) engineRef.current?.stepAndDraw(0);\n      return;\n    }\n    let last = 0;\n    const tick = (now: number) => {\n      const dt = last ? Math.min(1 / 24, (now - last) / 1000) : 1 / 60;\n      last = now;\n      const eng = engineRef.current;\n      if (!eng) {\n        rafRef.current = 0;\n        runningRef.current = false;\n        return;\n      }\n      if (eng.stepAndDraw(dt)) rafRef.current = requestAnimationFrame(tick);\n      else {\n        rafRef.current = 0;\n        runningRef.current = false;\n      }\n    };\n    const start = () => {\n      if (runningRef.current) return;\n      runningRef.current = true;\n      last = 0;\n      rafRef.current = requestAnimationFrame(tick);\n    };\n    wakeRef.current = start;\n    start();\n    return () => {\n      wakeRef.current = () => {};\n      if (rafRef.current) {\n        cancelAnimationFrame(rafRef.current);\n        rafRef.current = 0;\n      }\n      runningRef.current = false;\n    };\n  }, [onScreen, reduced]);\n\n  return <canvas ref={canvasRef} aria-hidden=\"true\" className={`pointer-events-none absolute inset-0 size-full ${className}`} {...props} />;\n}\n\nexport default DitherHorizon;\n"},{"path":"registry/voice-audio.ts","type":"registry:component","content":"// Hairline UI · voice-bar · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * VOICE AUDIO: meters for the voice orb (React-free)\n *\n * A meter taps any Web Audio node and answers two questions, as\n * often as you like, without allocating: how loud is it right now\n * (0–1), and how loud is each of eight bands spaced like hearing,\n * from the voice's floor (90 Hz) to its sibilants (7 kHz).\n * ───────────────────────────────────────────────────────── */\n\nexport const BANDS = 8;\n\nexport interface AudioMeter {\n  getLevel: () => number;\n  getSpectrum: () => Float32Array;\n  disconnect: () => void;\n}\n\nexport function createAudioMeter(context: BaseAudioContext, node: AudioNode): AudioMeter {\n  const analyser = context.createAnalyser();\n  analyser.fftSize = 1024;\n  analyser.smoothingTimeConstant = 0.3;\n  analyser.minDecibels = -85;\n  analyser.maxDecibels = -25;\n  node.connect(analyser);\n  const wave = new Uint8Array(new ArrayBuffer(analyser.fftSize));\n  const freq = new Uint8Array(new ArrayBuffer(analyser.frequencyBinCount));\n  const bands = new Float32Array(BANDS);\n  const hz = context.sampleRate / analyser.fftSize;\n  const edges = Array.from({ length: BANDS + 1 }, (_, b) => Math.max(1, Math.floor((90 * Math.pow(7000 / 90, b / BANDS)) / hz)));\n  let level = 0;\n  return {\n    getLevel() {\n      analyser.getByteTimeDomainData(wave);\n      let sum = 0;\n      for (let i = 0; i < wave.length; i++) {\n        const v = (wave[i] - 128) / 128;\n        sum += v * v;\n      }\n      // Loudness on a rough curve, so normal speech lands mid-range instead of hugging zero.\n      const next = Math.min(1, Math.pow(Math.sqrt(sum / wave.length) * 4.2, 0.8));\n      level += (next - level) * (next > level ? 0.6 : 0.18);\n      return level;\n    },\n    getSpectrum() {\n      analyser.getByteFrequencyData(freq);\n      for (let b = 0; b < BANDS; b++) {\n        const lo = edges[b];\n        const hi = Math.max(lo + 1, edges[b + 1]);\n        let sum = 0;\n        for (let i = lo; i < hi && i < freq.length; i++) sum += freq[i];\n        const v = Math.pow(sum / (hi - lo) / 255, 1.4);\n        bands[b] += (v - bands[b]) * (v > bands[b] ? 0.6 : 0.2);\n      }\n      return bands;\n    },\n    disconnect() {\n      try {\n        node.disconnect(analyser);\n      } catch {}\n    },\n  };\n}\n\n/** A media element can be routed into Web Audio only once in its life, so every caller shares one source per element. */\nconst elementSources = new WeakMap<HTMLMediaElement, { context: AudioContext; node: MediaElementAudioSourceNode }>();\n\nexport function elementSource(element: HTMLMediaElement, context?: AudioContext) {\n  let entry = elementSources.get(element);\n  if (!entry) {\n    const ctx = context ?? new AudioContext();\n    entry = { context: ctx, node: ctx.createMediaElementSource(element) };\n    // Routed through Web Audio, it must still reach the speakers.\n    entry.node.connect(ctx.destination);\n    elementSources.set(element, entry);\n  }\n  return entry;\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · voice-bar · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{"@keyframes ui-empty-in":{"from":{"opacity":"0","transform":"translateY(4px)","filter":"blur(4px)"},"to":{"opacity":"1","transform":"none","filter":"none"}},"@keyframes ui-sheen":{"from":{"mask-position":"150% 0"},"to":{"mask-position":"-50% 0"}}},"docs":"Docs and live preview: https://hairlineui.com/ui/voice-bar. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}