{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"voice-orb","type":"registry:component","title":"Voice orb","description":"Voice mode for your assistant: ink in water that the voice moves, with the talk button, the microphone and the reply wired to your own backend.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/voice-orb.tsx","type":"registry:component","content":"// Hairline UI · voice-orb · 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, type Spring } from \"./ui-interaction-motion\";\nimport { BANDS, createAudioMeter, elementSource, type AudioMeter } from \"./voice-audio\";\nimport { createFluidOrb, resolveColors, waterCss, type Emitter, type FluidOrb, type Rgb, type Water } from \"./voice-orb-gl\";\n\n/* ─────────────────────────────────────────────────────────\n * VOICE ORB: ink in water that the voice moves\n *\n * A real fluid runs inside a round vessel, and each state is a way\n * of moving it, so the orb shows which way the sound is going:\n *   listening  sound comes in: the voice's frequency bands push\n *              ink in from the rim, low notes in the first colour,\n *              high notes in the last\n *   speaking   sound goes out: each syllable blooms ink outward\n *              from the centre, band by band\n *   thinking   no sound: a slow vortex stirs the ink and folds the\n *              colours into each other\n *   idle       the ink drifts, barely moving; a finger or a cursor\n *              stirs it\n *\n * The states are spring weights, so they blend: speech fading into\n * thought hands the ink from one motion to the next. Loudness and\n * bands are read once a frame from functions, never through React\n * state. Off screen or in a hidden tab it stops.\n *\n * Reduced motion: one still, settled picture per state.\n * ───────────────────────────────────────────────────────── */\n\nexport type VoiceOrbState = \"idle\" | \"listening\" | \"thinking\" | \"speaking\";\n\nexport interface VoiceOrbProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"children\"> {\n  state?: VoiceOrbState;\n  /** Read every frame, 0 to 1: the microphone while listening, the voice while speaking. useVoiceAudio makes one. */\n  getLevel?: () => number;\n  /** Read every frame: loudness per frequency band, 0 to 1, low to high (eight is plenty). useVoiceAudio makes one. */\n  getSpectrum?: () => ArrayLike<number>;\n  /** The loudness as a prop instead; getLevel wins when both are given. */\n  level?: number;\n  /** Diameter in px. */\n  size?: number;\n  /** Three CSS colours for the ink, low notes to high. Theme variables welcome. */\n  colors?: [string, string, string];\n  /** What it's called for screen readers; the state is added to it. */\n  label?: string;\n}\n\nconst COLORS: [string, string, string] = [\"var(--chart-1, var(--primary))\", \"var(--chart-3, var(--primary))\", \"var(--chart-2, var(--primary))\"];\n/** Inks for themes without colour of their own: blue, teal and coral. */\nconst INKS: Rgb[] = [\n  [0.23, 0.42, 0.95],\n  [0.08, 0.66, 0.6],\n  [0.96, 0.46, 0.38],\n];\nconst SAY: Record<VoiceOrbState, string> = { idle: \"ready\", listening: \"listening\", thinking: \"thinking\", speaking: \"speaking\" };\nconst SILENT = new Float32Array(BANDS);\nconst TAU = Math.PI * 2;\n\n// How each state moves the water: accelerations in grid cells per second², and ink poured per second.\nconst PULL_IN = 1450;\nconst PUSH_OUT = 1750;\nconst DRIFT = 45;\nconst INK_IN = 7;\nconst INK_OUT = 7;\nconst MOOD = { stiffness: 60, damping: 15 };\nconst LEVEL = { stiffness: 320, damping: 30 };\n\nconst clamp01 = (n: number) => (Number.isFinite(n) ? Math.max(0, Math.min(1, n)) : 0);\nconst mixRgb = (a: Rgb, b: Rgb, t: number): Rgb => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];\n/** Low notes in the first colour, through the second, high notes in the third. */\nconst bandColor = (palette: Rgb[], b: number) => {\n  const t = (b / (BANDS - 1)) * 2;\n  return t <= 1 ? mixRgb(palette[0], palette[1], t) : mixRgb(palette[1], palette[2], t - 1);\n};\n\n/** Where the three pools of dilute ink sit in the water (the vessel's box, y down): low notes top left, high notes below. */\nconst POOLS: [number, number][] = [\n  [0.32, 0.36],\n  [0.68, 0.4],\n  [0.5, 0.72],\n];\n\n/** The water's look: the pools turned by phase (they drift a full turn in about a minute), deeper in the dark. */\nfunction waterLook(dark: boolean, phase: number): Omit<Water, \"inks\"> {\n  const c = Math.cos(phase), s = Math.sin(phase);\n  return {\n    pools: POOLS.map(([x, y]): [number, number] => [0.5 + (x - 0.5) * c - (y - 0.5) * s, 0.5 + (x - 0.5) * s + (y - 0.5) * c]),\n    poolAlpha: dark ? 0.36 : 0.3,\n    poolRadius: 0.46,\n    base: dark ? [0.09, 0.2] : [0.07, 0.16],\n    line: dark ? 0.4 : 0.32,\n  };\n}\n\n/** The inks and whether the page is dark, read from the theme. A theme whose chart colours are greys (shadcn's default)\n * would pour grey ink, so then the orb uses inks of its own. */\nfunction readTheme(host: HTMLElement, colorKey: string) {\n  const [r1, r2, r3, bg] = resolveColors(host, [...colorKey.split(\"|\"), \"var(--background, #fff)\"]);\n  const chroma = (c: Rgb) => Math.max(...c) - Math.min(...c);\n  const inks = [r1, r2, r3].some((c) => chroma(c) > 0.12) ? [r1, r2, r3] : INKS;\n  return { inks, dark: 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2] < 0.45 };\n}\n\nconst rgbCss = (c: Rgb) => `rgb(${Math.round(c[0] * 255)} ${Math.round(c[1] * 255)} ${Math.round(c[2] * 255)})`;\n\ntype Weights = { listen: number; speak: number; think: number };\nconst WEIGHTS: Record<VoiceOrbState, Weights> = {\n  idle: { listen: 0, speak: 0, think: 0 },\n  listening: { listen: 1, speak: 0, think: 0 },\n  thinking: { listen: 0, speak: 0, think: 1 },\n  speaking: { listen: 0, speak: 1, think: 0 },\n};\n\ninterface Clock {\n  time: number;\n  turn: number;\n  stir: number;\n}\n\n/** Everything a state does to the water this frame. Pure: the same inputs make the same emitters. */\nfunction emittersFor(w: Weights, bands: ArrayLike<number>, palette: Rgb[], clock: Clock, dt: number): Emitter[] {\n  const out: Emitter[] = [];\n  const idle = Math.max(0, 1 - w.listen - w.speak - w.think);\n  for (let b = 0; b < BANDS; b++) {\n    const e = clamp01(bands[b] ?? 0);\n    const color = bandColor(palette, b);\n    if (w.listen > 0.02 && e > 0.03) {\n      const a = clock.turn + (b * TAU) / BANDS;\n      const c = Math.cos(a), s = Math.sin(a);\n      const k = e * w.listen;\n      out.push({ x: 0.5 + 0.43 * c, y: 0.5 + 0.43 * s, radius: 0.038, fx: -c * PULL_IN * k * dt, fy: -s * PULL_IN * k * dt, color, amount: k * INK_IN * dt });\n    }\n    if (w.speak > 0.02 && e > 0.03) {\n      // Each band blooms out on two opposite sides, so the voice opens the ink evenly instead of shooting one plume.\n      const a = -clock.turn * 1.3 + (b * Math.PI) / BANDS + (b % 2) * Math.PI + 0.4;\n      const c = Math.cos(a), s = Math.sin(a);\n      const k = e * w.speak;\n      out.push({ x: 0.5 + 0.04 * c, y: 0.5 + 0.04 * s, radius: 0.036, fx: c * PUSH_OUT * k * dt, fy: s * PUSH_OUT * k * dt, color, amount: k * INK_OUT * dt });\n    }\n  }\n  // Thinking and idle feed the body from two points circling near the middle; the turning water winds it into arms.\n  const feed = 0.9 * w.think;\n  if (feed > 0.02) {\n    for (let k = 0; k < 2; k++) {\n      const a = clock.stir + k * Math.PI;\n      out.push({ x: 0.5 + 0.12 * Math.cos(a), y: 0.5 + 0.12 * Math.sin(a), radius: 0.026, color: palette[k], amount: feed * 2.2 * dt });\n    }\n  }\n  if (idle > 0.02) {\n    const t = clock.time;\n    const x = 0.5 + 0.2 * Math.cos(t * 0.23), y = 0.5 + 0.2 * Math.sin(t * 0.17 + 1);\n    const a = Math.atan2(y - 0.5, x - 0.5) + Math.PI / 2;\n    out.push({ x, y, radius: 0.09, fx: Math.cos(a) * DRIFT * idle * dt, fy: Math.sin(a) * DRIFT * idle * dt });\n  }\n  return out;\n}\n\n/** How the water itself behaves in a blend of states: eddies, how fast motion and ink fade, and the turn. */\nfunction waterFor(w: Weights) {\n  const idle = Math.max(0, 1 - w.listen - w.speak - w.think);\n  const voice = w.listen + w.speak;\n  return {\n    curl: 2 * idle + 1.2 * w.think + 6 * voice,\n    velocityFade: 0.9 * idle + 0.7 * w.think + 0.8 * voice,\n    inkFade: 0.1 * idle + 0.22 * w.think + 0.34 * voice,\n    rimFade: 0.35 * idle + 0.25 * w.think + 0.05 * w.listen + 0.12 * w.speak,\n    swirl: 0.08 * idle + 0.6 * w.think + 0.05 * w.listen - 0.04 * w.speak,\n  };\n}\n\n/** Bands from loudness alone, for sources that only give a level: speech-like, never all bands in step. */\nfunction bandsFromLevel(level: number, time: number, out: Float32Array) {\n  for (let b = 0; b < BANDS; b++) out[b] = clamp01(level * (0.55 + 0.45 * Math.sin(time * 5.3 + b * 1.9 + Math.sin(time * 1.3 + b * 0.7) * 2)));\n  return out;\n}\n\n/** The first drops: three small ones, wound into wisps before the first frame, so it never starts empty. */\nfunction seedFor(palette: Rgb[]): Emitter[] {\n  return [\n    { x: 0.44, y: 0.56, radius: 0.045, color: palette[0], amount: 1.4 },\n    { x: 0.58, y: 0.47, radius: 0.04, color: palette[1], amount: 1.2 },\n    { x: 0.46, y: 0.41, radius: 0.03, color: palette[2], amount: 0.8 },\n  ];\n}\n\nexport function VoiceOrb({ state = \"idle\", getLevel, getSpectrum, level, size = 160, colors = COLORS, label = \"Voice assistant\", className = \"\", style, ...props }: VoiceOrbProps) {\n  const reduced = useInteractionReducedMotion();\n  const { ref: activityRef, active } = useInteractionActivity<HTMLDivElement>();\n  const canvas = React.useRef<HTMLCanvasElement>(null);\n  const fallback = React.useRef<HTMLSpanElement>(null);\n  const [failed, setFailed] = React.useState(false);\n  const colorKey = colors.join(\"|\");\n\n  const input = React.useRef({ state, getLevel, getSpectrum, level });\n  React.useLayoutEffect(() => {\n    input.current = { state, getLevel, getSpectrum, level };\n  });\n\n  const engine = React.useRef<{\n    fluid: FluidOrb;\n    palette: Rgb[];\n    dark: boolean;\n    /** Seconds the water has been shown; the pools drift with it. */\n    waterTime: number;\n    springs: { listen: Spring; speak: Spring; think: Spring; level: Spring };\n    clock: Clock;\n    bands: Float32Array;\n    stirs: Emitter[];\n    /** True while the first ink is being folded, a few steps a frame; the loop waits for it. */\n    pouring: boolean;\n    frame: (dt: number) => void;\n    settle: (target: Weights) => void;\n  } | null>(null);\n\n  // The fluid lives as long as the canvas; its size is fixed when it starts.\n  React.useEffect(() => {\n    const el = canvas.current;\n    if (!el) return;\n    const dpr = Math.min(2, window.devicePixelRatio || 1);\n    el.width = Math.round(size * dpr);\n    el.height = Math.round(size * dpr);\n    let fluid: FluidOrb | null = null;\n    try {\n      fluid = createFluidOrb(el);\n    } catch {\n      fluid = null;\n    }\n    if (!fluid) {\n      const frame = requestAnimationFrame(() => setFailed(true));\n      return () => cancelAnimationFrame(frame);\n    }\n    const f = fluid;\n    const start = WEIGHTS[input.current.state];\n    const quiet = () => {};\n    const springs = {\n      listen: createSpring(start.listen, MOOD, quiet, 0.002),\n      speak: createSpring(start.speak, MOOD, quiet, 0.002),\n      think: createSpring(start.think, MOOD, quiet, 0.002),\n      level: createSpring(0, LEVEL, quiet, 0.002),\n    };\n    const clock: Clock = { time: 0, turn: 0, stir: 0 };\n    const bands = new Float32Array(BANDS);\n\n    const e: NonNullable<typeof engine.current> = {\n      fluid: f,\n      palette: [[0.19, 0.36, 0.87], [0.11, 0.69, 0.48], [0.91, 0.45, 0.23]],\n      dark: false,\n      waterTime: 0,\n      springs,\n      clock,\n      bands,\n      stirs: [],\n      pouring: false,\n      frame(dt) {\n        if (e.pouring) return;\n        const { state: s, getLevel: read, getSpectrum: spectrum, level: given } = input.current;\n        const moving = s === \"listening\" || s === \"speaking\";\n        const raw = moving ? clamp01(read ? read() : (given ?? 0)) : 0;\n        springs.level.set(raw);\n        const lv = Math.max(0, springs.level.get());\n        if (moving && spectrum) {\n          const got = spectrum();\n          for (let b = 0; b < BANDS; b++) bands[b] = clamp01(got[Math.floor((b * got.length) / BANDS)] ?? 0);\n        } else bandsFromLevel(lv, clock.time, bands);\n        const w = { listen: Math.max(0, springs.listen.get()), speak: Math.max(0, springs.speak.get()), think: Math.max(0, springs.think.get()) };\n        clock.time += dt;\n        clock.turn += dt * (0.22 + 0.5 * w.think);\n        clock.stir += dt * 1.5;\n        const emitters = emittersFor(w, bands, e.palette, clock, dt);\n        if (e.stirs.length) emitters.push(...e.stirs.splice(0));\n        f.step({ dt, emitters, ...waterFor(w) });\n        e.waterTime += dt;\n        f.draw({ radius: 0.455 + 0.025 * lv * (w.listen + w.speak) - 0.012 * w.think, water: { inks: e.palette, ...waterLook(e.dark, e.waterTime * 0.1) }, dark: e.dark });\n      },\n      settle(target) {\n        if (e.pouring) return;\n        // A still picture of a state: run it for a moment at speech-like loudness, then hold.\n        const w = target;\n        bandsFromLevel(0.55, clock.time, bands);\n        for (let i = 0; i < 50; i++) {\n          clock.time += 1 / 30;\n          clock.turn += (1 / 30) * 0.3;\n          clock.stir += (1 / 30) * 1.5;\n          f.step({ dt: 1 / 30, emitters: emittersFor(w, bands, e.palette, clock, 1 / 30), ...waterFor(w) });\n        }\n        f.draw({ radius: 0.455, water: { inks: e.palette, ...waterLook(e.dark, e.waterTime * 0.1) }, dark: e.dark });\n      },\n    };\n    engine.current = e;\n\n    const lost = (event: Event) => {\n      event.preventDefault();\n      setFailed(true);\n    };\n    el.addEventListener(\"webglcontextlost\", lost);\n    return () => {\n      el.removeEventListener(\"webglcontextlost\", lost);\n      Object.values(springs).forEach((s) => s.stop());\n      f.dispose();\n      engine.current = null;\n    };\n  }, [size]);\n\n  // The stand-in is the same water the fluid starts in, in CSS, so handing over to the fluid changes nothing but the ink.\n  // It is painted with the resolved theme before the first paint (the markup's own picture only shows before hydration).\n  const paintStandIn = React.useCallback((theme: { inks: Rgb[]; dark: boolean }) => {\n    const el = fallback.current;\n    if (!el) return;\n    const css = waterCss(waterLook(theme.dark, 0), theme.inks.map(rgbCss));\n    el.style.background = css.background;\n    el.style.boxShadow = css.boxShadow;\n  }, []);\n  React.useLayoutEffect(() => {\n    const el = fallback.current;\n    if (el) paintStandIn(readTheme(el.parentElement ?? document.body, colorKey));\n  }, [colorKey, paintStandIn]);\n\n  // Colours from the theme, again whenever the theme changes. The first time, the ink is poured and settled before it shows.\n  const poured = React.useRef(false);\n  React.useEffect(() => {\n    const el = canvas.current;\n    if (!el || failed) return;\n    poured.current = false;\n    let pour = 0;\n    const apply = () => {\n      const e = engine.current;\n      if (!e) return;\n      const theme = readTheme(el.parentElement ?? document.body, colorKey);\n      e.palette = theme.inks;\n      e.dark = theme.dark;\n      paintStandIn(theme);\n      const reveal = () => {\n        // A true crossfade: both show the same water, so fading one in as the other fades out keeps the water still and\n        // only the ink appears. (The stand-in's slow fade is only for a WebGL failure.)\n        const standIn = fallback.current;\n        if (!standIn) return;\n        el.style.transition = standIn.style.transition = \"opacity 240ms linear\";\n        el.style.opacity = \"1\";\n        standIn.style.opacity = \"0\";\n      };\n      if (poured.current) {\n        e.frame(0.0001);\n        return reveal();\n      }\n      poured.current = true;\n      // Pour, then fold it with a stir before it shows, so it starts as ink that has been moving. It waits for the shaders\n      // to finish compiling in the background, then folds a few steps a frame behind the stand-in, never as one long task.\n      const fold = { listen: 0, speak: 0, think: 1 };\n      const stir = (steps: number) => {\n        for (let i = 0; i < steps; i++) {\n          e.clock.time += 1 / 30;\n          e.clock.stir += (1 / 30) * 1.5;\n          e.fluid.step({ dt: 1 / 30, emitters: emittersFor(fold, e.bands, e.palette, e.clock, 1 / 30), ...waterFor(fold) });\n        }\n      };\n      const still = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n      e.pouring = true;\n      let left = -1;\n      const chunk = () => {\n        if (engine.current !== e) return;\n        try {\n          if (!e.fluid.ready()) {\n            pour = requestAnimationFrame(chunk);\n            return;\n          }\n        } catch {\n          setFailed(true);\n          return;\n        }\n        if (left < 0) {\n          e.fluid.seed(seedFor(e.palette));\n          left = 54;\n        }\n        const n = still ? left : Math.min(6, left);\n        stir(n);\n        left -= n;\n        if (left > 0) {\n          pour = requestAnimationFrame(chunk);\n          return;\n        }\n        e.pouring = false;\n        if (still) e.settle(WEIGHTS[input.current.state]);\n        else e.frame(1 / 60);\n        reveal();\n      };\n      pour = requestAnimationFrame(chunk);\n    };\n    apply();\n    // Only a theme switch matters (a class or data-theme on <html>); other attribute writes are ignored.\n    const root = document.documentElement;\n    let theme = `${root.className}|${root.dataset.theme ?? \"\"}`;\n    const watch = new MutationObserver(() => {\n      const next = `${root.className}|${root.dataset.theme ?? \"\"}`;\n      if (next === theme) return;\n      theme = next;\n      apply();\n    });\n    watch.observe(root, { attributes: true, attributeFilter: [\"class\", \"data-theme\"] });\n    return () => {\n      watch.disconnect();\n      cancelAnimationFrame(pour);\n      if (engine.current) engine.current.pouring = false;\n    };\n  }, [colorKey, failed, size, paintStandIn]);\n\n  // A state change re-aims the weights from wherever they are; under reduced motion it settles a still of the new state.\n  React.useEffect(() => {\n    const e = engine.current;\n    if (!e) return;\n    const w = WEIGHTS[state];\n    if (reduced) {\n      e.springs.listen.jump(w.listen);\n      e.springs.speak.jump(w.speak);\n      e.springs.think.jump(w.think);\n      e.settle(w);\n      return;\n    }\n    e.springs.listen.set(w.listen);\n    e.springs.speak.set(w.speak);\n    e.springs.think.set(w.think);\n  }, [state, reduced]);\n\n  // The loop: only while on screen and the tab is visible, never under reduced motion.\n  React.useEffect(() => {\n    if (!active || reduced || failed) return;\n    let frame = 0;\n    let last = 0;\n    const tick = (now: number) => {\n      const dt = last ? Math.min(1 / 30, (now - last) / 1000) : 1 / 60;\n      last = now;\n      engine.current?.frame(dt);\n      frame = requestAnimationFrame(tick);\n    };\n    frame = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(frame);\n  }, [active, reduced, failed]);\n\n  // A finger or a cursor stirs the water: no ink, just a push along the way it moved.\n  const lastPoint = React.useRef<{ x: number; y: number } | null>(null);\n  const stir = (event: React.PointerEvent<HTMLDivElement>) => {\n    const e = engine.current;\n    if (!e || reduced) return;\n    const box = event.currentTarget.getBoundingClientRect();\n    const x = (event.clientX - box.left) / box.width;\n    const y = 1 - (event.clientY - box.top) / box.height;\n    const prev = lastPoint.current;\n    lastPoint.current = { x, y };\n    if (!prev || Math.hypot(x - 0.5, y - 0.5) > 0.46) return;\n    const dx = x - prev.x, dy = y - prev.y;\n    if (Math.abs(dx) + Math.abs(dy) < 0.002) return;\n    e.stirs.push({ x, y, radius: 0.06, fx: Math.max(-120, Math.min(120, dx * 4000)), fy: Math.max(-120, Math.min(120, dy * 4000)) });\n  };\n\n  return (\n    <div\n      ref={activityRef}\n      role=\"img\"\n      aria-label={`${label}, ${SAY[state]}`}\n      {...props}\n      onPointerMove={(event) => {\n        props.onPointerMove?.(event);\n        stir(event);\n      }}\n      onPointerLeave={(event) => {\n        props.onPointerLeave?.(event);\n        lastPoint.current = null;\n      }}\n      className={`relative inline-grid shrink-0 place-items-center ${className}`}\n      style={{ width: size, height: size, ...style }}\n    >\n      {/* First paint, and the whole orb where WebGL 2 isn't available: the fluid's water, without the moving ink. */}\n      <span\n        ref={fallback}\n        aria-hidden=\"true\"\n        className=\"absolute rounded-full transition-[opacity,scale] duration-700 ease-[cubic-bezier(0.16,1,0.3,1)]\"\n        style={{\n          width: \"91%\",\n          height: \"91%\",\n          opacity: 1,\n          // The vessel's size in the state it opens in, so the hand-over to the fluid has one edge.\n          scale: state === \"thinking\" ? 0.443 / 0.455 : 1,\n          [\"--orb-d\" as string]: `${size * 0.91}px`,\n          ...waterCss(waterLook(false, 0), colors),\n        }}\n      />\n      <canvas ref={canvas} aria-hidden=\"true\" className=\"absolute inset-0 size-full\" style={{ display: failed ? \"none\" : undefined, opacity: 0 }} />\n      <span role=\"status\" className=\"sr-only\">\n        {SAY[state]}\n      </span>\n    </div>\n  );\n}\n\n/* ─────────────────────────────────────────────────────────\n * useVoiceAudio: what the orb reads from a real source\n *\n *   MediaStream        a microphone from getUserMedia, or a\n *                      remote track from WebRTC\n *   HTMLMediaElement   an <audio> playing the assistant's voice\n *\n * Returns { getLevel, getSpectrum }: functions that read the sound\n * right now, so the orb can call them every frame without\n * re-rendering anything. Spread them onto the orb.\n * ───────────────────────────────────────────────────────── */\n\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,\n    }),\n    [],\n  );\n}\n\nexport default VoiceOrb;\n"},{"path":"registry/voice-orb-gl.ts","type":"registry:component","content":"// Hairline UI · voice-orb · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * VOICE ORB renderer: ink in water (WebGL 2, React-free)\n *\n * A real fluid: velocity and ink live in half-float textures and\n * every frame runs the stable-fluids steps on the GPU:\n *   curl → vorticity confinement → forces and ink → divergence →\n *   pressure (Jacobi) → projection → advection\n * The water sits in a round vessel: velocity dies at the wall, so\n * ink pushed outward rolls back along it instead of leaving.\n *\n * The picture is the ink alone. Its thickness sets how opaque it\n * is (thin ink is a haze, thick ink is solid colour), and the\n * slope of the thickness lights the folds, so it reads as silk in\n * water, never as a shaded ball.\n * ───────────────────────────────────────────────────────── */\n\nexport type Rgb = [number, number, number];\n\n/** A push and/or some ink at a point. Positions in 0–1 across the orb (y up), radius as a fraction of it. */\nexport interface Emitter {\n  x: number;\n  y: number;\n  radius: number;\n  /** Force in grid cells per second, added once. */\n  fx?: number;\n  fy?: number;\n  /** Ink colour and how much. */\n  color?: Rgb;\n  amount?: number;\n}\n\nexport interface FluidStep {\n  dt: number;\n  emitters: Emitter[];\n  /** How strongly small eddies are kept alive. */\n  curl: number;\n  /** Fraction of the speed and of the ink lost per second. */\n  velocityFade: number;\n  inkFade: number;\n  /** Extra fade toward the wall, per second. */\n  rimFade: number;\n  /** How hard the whole body of water is turned. */\n  swirl: number;\n}\n\nexport interface FluidLook {\n  /** The vessel's radius as a fraction of the canvas (0.5 fills it). */\n  radius: number;\n  /** The water the ink sits in: dilute pools of the inks over a tint, so the body reads even where no ink moves. */\n  water: Water;\n  dark: boolean;\n}\n\n/** Laid out in the vessel's own box (0 to 1, y down) and composited exactly as CSS radial gradients are, so a CSS\n * picture of it (waterCss) matches the first frame. */\nexport interface Water {\n  /** One colour per pool; the first also tints the water and draws the rim. */\n  inks: Rgb[];\n  /** Pool centres. */\n  pools: [number, number][];\n  /** A pool's opacity at its centre, fading linearly to nothing at its radius (a fraction of the diameter). */\n  poolAlpha: number;\n  poolRadius: number;\n  /** The tint's opacity inside half the radius, and at the rim. */\n  base: [number, number];\n  /** The 1px rim's opacity. */\n  line: number;\n}\n\nconst SIM = 128;\nconst JACOBI = 18;\nconst MAX_EMIT = 8;\n\nconst VERTEX = `#version 300 es\nin vec2 aPos;\nout vec2 vUv;\nvoid main() { vUv = aPos * 0.5 + 0.5; gl_Position = vec4(aPos, 0.0, 1.0); }`;\n\nconst head = `#version 300 es\nprecision highp float;\nprecision highp sampler2D;\nin vec2 vUv;\nout vec4 o;\n`;\n\nconst ADVECT = `${head}\nuniform sampler2D uVel;\nuniform sampler2D uSrc;\nuniform vec2 uSimTexel;\nuniform vec2 uSrcTexel;\nuniform float uDt;\nuniform float uKeep;\nuniform float uWall;\nuniform float uCap;\nuniform float uRim;\nuniform float uSharp;\nvoid main() {\n  vec2 back = vUv - uDt * texture(uVel, vUv).xy * uSimTexel;\n  vec4 r = texture(uSrc, back);\n  if (uSharp > 0.5) {\n    // MacCormack: carry the result forward again, measure what the round trip lost and put it back, clamped to the\n    // cells it came from so it can never ring. Keeps ink in fine filaments instead of smearing them every frame.\n    vec2 ahead = back + uDt * texture(uVel, back).xy * uSimTexel;\n    r += 0.5 * (texture(uSrc, vUv) - texture(uSrc, ahead));\n    vec2 cell = (floor(back / uSrcTexel - 0.5) + 0.5) * uSrcTexel;\n    vec4 c0 = texture(uSrc, cell);\n    vec4 c1 = texture(uSrc, cell + vec2(uSrcTexel.x, 0.0));\n    vec4 c2 = texture(uSrc, cell + vec2(0.0, uSrcTexel.y));\n    vec4 c3 = texture(uSrc, cell + uSrcTexel);\n    r = clamp(r, min(min(c0, c1), min(c2, c3)), max(max(c0, c1), max(c2, c3)));\n  }\n  r *= uKeep;\n  // Ink clears faster toward the wall, so the picture is one body in clear water.\n  r /= 1.0 + uRim * uDt * smoothstep(0.2, 0.44, length(vUv - 0.5));\n  if (uWall > 0.5) r.xy *= 1.0 - smoothstep(0.43, 0.49, length(vUv - 0.5));\n  if (uCap > 0.0 && r.a > uCap) r *= uCap / r.a;\n  o = r;\n}`;\n\nconst CURL = `${head}\nuniform sampler2D uVel;\nuniform vec2 uTexel;\nvoid main() {\n  float l = texture(uVel, vUv - vec2(uTexel.x, 0.0)).y;\n  float r = texture(uVel, vUv + vec2(uTexel.x, 0.0)).y;\n  float b = texture(uVel, vUv - vec2(0.0, uTexel.y)).x;\n  float t = texture(uVel, vUv + vec2(0.0, uTexel.y)).x;\n  o = vec4(0.5 * (r - l - t + b), 0.0, 0.0, 1.0);\n}`;\n\nconst VORTICITY = `${head}\nuniform sampler2D uVel;\nuniform sampler2D uCurl;\nuniform vec2 uTexel;\nuniform float uAmount;\nuniform float uDt;\nuniform float uSwirl;\nvoid main() {\n  float l = texture(uCurl, vUv - vec2(uTexel.x, 0.0)).x;\n  float r = texture(uCurl, vUv + vec2(uTexel.x, 0.0)).x;\n  float b = texture(uCurl, vUv - vec2(0.0, uTexel.y)).x;\n  float t = texture(uCurl, vUv + vec2(0.0, uTexel.y)).x;\n  float c = texture(uCurl, vUv).x;\n  vec2 f = 0.5 * vec2(abs(t) - abs(b), abs(r) - abs(l));\n  f /= length(f) + 0.0001;\n  f *= uAmount * c;\n  f.y *= -1.0;\n  // The water turns as a whole, faster near the middle, so stirred ink winds into arms instead of crinkling.\n  vec2 p = vUv - 0.5;\n  float inside = 1.0 - smoothstep(0.36, 0.47, length(p));\n  vec2 turn = vec2(-p.y, p.x) / (length(p) + 0.3) * 128.0 * uSwirl * inside;\n  vec2 v = texture(uVel, vUv).xy + (f + turn) * uDt;\n  o = vec4(clamp(v, -1000.0, 1000.0), 0.0, 1.0);\n}`;\n\nconst SPLAT = `${head}\nuniform sampler2D uSrc;\nuniform vec4 uPoint[${MAX_EMIT}];\nuniform vec4 uValue[${MAX_EMIT}];\nuniform int uCount;\nvoid main() {\n  vec4 base = texture(uSrc, vUv);\n  for (int i = 0; i < ${MAX_EMIT}; i++) {\n    if (i >= uCount) break;\n    vec2 d = vUv - uPoint[i].xy;\n    base += uValue[i] * exp(-dot(d, d) / uPoint[i].z);\n  }\n  o = base;\n}`;\n\nconst DIVERGENCE = `${head}\nuniform sampler2D uVel;\nuniform vec2 uTexel;\nvoid main() {\n  float l = texture(uVel, vUv - vec2(uTexel.x, 0.0)).x;\n  float r = texture(uVel, vUv + vec2(uTexel.x, 0.0)).x;\n  float b = texture(uVel, vUv - vec2(0.0, uTexel.y)).y;\n  float t = texture(uVel, vUv + vec2(0.0, uTexel.y)).y;\n  o = vec4(0.5 * (r - l + t - b), 0.0, 0.0, 1.0);\n}`;\n\nconst SCALE = `${head}\nuniform sampler2D uSrc;\nuniform float uKeep;\nvoid main() { o = texture(uSrc, vUv) * uKeep; }`;\n\nconst JACOBI_FS = `${head}\nuniform sampler2D uPressure;\nuniform sampler2D uDiv;\nuniform vec2 uTexel;\nvoid main() {\n  float l = texture(uPressure, vUv - vec2(uTexel.x, 0.0)).x;\n  float r = texture(uPressure, vUv + vec2(uTexel.x, 0.0)).x;\n  float b = texture(uPressure, vUv - vec2(0.0, uTexel.y)).x;\n  float t = texture(uPressure, vUv + vec2(0.0, uTexel.y)).x;\n  float d = texture(uDiv, vUv).x;\n  o = vec4((l + r + b + t - d) * 0.25, 0.0, 0.0, 1.0);\n}`;\n\nconst GRADIENT = `${head}\nuniform sampler2D uPressure;\nuniform sampler2D uVel;\nuniform vec2 uTexel;\nvoid main() {\n  float l = texture(uPressure, vUv - vec2(uTexel.x, 0.0)).x;\n  float r = texture(uPressure, vUv + vec2(uTexel.x, 0.0)).x;\n  float b = texture(uPressure, vUv - vec2(0.0, uTexel.y)).x;\n  float t = texture(uPressure, vUv + vec2(0.0, uTexel.y)).x;\n  vec2 v = texture(uVel, vUv).xy - vec2(r - l, t - b);\n  o = vec4(v, 0.0, 1.0);\n}`;\n\nconst DISPLAY = `${head}\nuniform sampler2D uDye;\nuniform vec2 uTexel;\nuniform float uRadius;\nuniform float uAa;\nuniform vec2 uPx;\nuniform vec3 uInk[3];\nuniform vec2 uPool[3];\nuniform float uPoolA;\nuniform float uPoolR;\nuniform vec2 uBase;\nuniform float uLine;\nuniform float uDark;\nvoid main() {\n  float dist = length(vUv - 0.5);\n  float vessel = 1.0 - smoothstep(uRadius - uAa, uRadius + uAa, dist);\n  if (vessel <= 0.0) { o = vec4(0.0); return; }\n  vec4 d = max(texture(uDye, vUv), 0.0);\n  float amt = d.a;\n  vec3 col = d.rgb / max(amt, 0.001);\n\n  // The folds: the slope of the ink's thickness, lit from the top left like silk under water.\n  float al = texture(uDye, vUv - vec2(uTexel.x, 0.0)).a;\n  float ar = texture(uDye, vUv + vec2(uTexel.x, 0.0)).a;\n  float ab = texture(uDye, vUv - vec2(0.0, uTexel.y)).a;\n  float at = texture(uDye, vUv + vec2(0.0, uTexel.y)).a;\n  vec3 n = normalize(vec3((al - ar) * 1.3, (ab - at) * 1.3, 1.0));\n  vec3 l = normalize(vec3(-0.5, 0.62, 0.75));\n  float shade = 0.8 + 0.28 * dot(n, l);\n  float sheen = pow(max(dot(reflect(-l, n), vec3(0.0, 0.0, 1.0)), 0.0), 22.0) * smoothstep(0.08, 0.6, amt);\n\n  // Ink has an edge: opacity rises steeply with thickness, with a little haze kept so the edge isn't cut out.\n  float a = mix(smoothstep(0.07, 0.55, amt), 1.0 - exp(-amt * 3.0), 0.3);\n  a *= 1.0 - smoothstep(uRadius - 0.09, uRadius, dist);\n  // Mixed inks keep their colour: chroma pushed back out from the grey that averaging makes.\n  float lum = dot(col, vec3(0.299, 0.587, 0.114));\n  col = clamp(mix(vec3(lum), col, 1.18), 0.0, 1.0);\n  // Lit from behind: thin ink glows lighter, thick ink deepens, so the body has depth without a shaded sphere.\n  float thick = smoothstep(0.2, 1.9, amt);\n  col = mix(mix(col, vec3(1.0), 0.3), col * 0.74, thick);\n  col = col * shade + sheen * mix(0.14, 0.1, uDark);\n  // In the dark, ink is lit from within rather than muddied by the background.\n  col = mix(col, col * 1.18 + 0.05, uDark);\n\n  // The water, layered the way CSS layers radial gradients (premultiplied, the first pool on top), so the stand-in\n  // drawn in CSS before the shaders are ready is this same picture: a tint deepening toward the rim, a dilute pool of\n  // each ink, and a 1px rim.\n  float rr = dist / uRadius;\n  vec2 q = vec2(vUv.x - 0.5, 0.5 - vUv.y) / (2.0 * uRadius) + 0.5;\n  float ba = mix(uBase.x, uBase.y, clamp(rr * 2.0 - 1.0, 0.0, 1.0));\n  vec4 water = vec4(uInk[0] * ba, ba);\n  for (int i = 2; i >= 0; i--) {\n    float pa = uPoolA * max(0.0, 1.0 - length(q - uPool[i]) / uPoolR);\n    water = vec4(uInk[i] * pa, pa) + water * (1.0 - pa);\n  }\n  // The rim: one CSS pixel just inside the edge, box-filtered at the device pixel, like the stand-in's inset ring.\n  float line = clamp((0.5 * uPx.x + 0.5 * uPx.y - abs(dist - (uRadius - 0.5 * uPx.x))) / uPx.y, 0.0, 1.0) * uLine;\n  water = vec4(uInk[0] * line, line) + water * (1.0 - line);\n  o = (vec4(col * a, a) + water * (1.0 - a)) * vessel;\n}`;\n\ntype Target = { tex: WebGLTexture; fb: WebGLFramebuffer; w: number; h: number };\ntype Double = { read: Target; write: Target; swap: () => void };\n\nexport function createFluidOrb(canvas: HTMLCanvasElement) {\n  const gl = canvas.getContext(\"webgl2\", { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, preserveDrawingBuffer: false, powerPreference: \"low-power\" });\n  if (!gl) return null;\n  if (!gl.getExtension(\"EXT_color_buffer_float\") && !gl.getExtension(\"EXT_color_buffer_half_float\")) return null;\n\n  const compile = (type: number, source: string) => {\n    const s = gl.createShader(type)!;\n    gl.shaderSource(s, source);\n    gl.compileShader(s);\n    return s;\n  };\n  // Shaders compile in the background where the browser can (KHR_parallel_shader_compile): asking for a compile or link\n  // status straight away would block the page until the GPU process is done, so statuses are only read once ready().\n  const parallel = gl.getExtension(\"KHR_parallel_shader_compile\");\n  const vertex = compile(gl.VERTEX_SHADER, VERTEX);\n  const programs: WebGLProgram[] = [];\n  const program = (fragment: string) => {\n    const p = gl.createProgram()!;\n    gl.attachShader(p, vertex);\n    gl.attachShader(p, compile(gl.FRAGMENT_SHADER, fragment));\n    gl.bindAttribLocation(p, 0, \"aPos\");\n    gl.linkProgram(p);\n    programs.push(p);\n    const cache = new Map<string, WebGLUniformLocation | null>();\n    const u = (name: string) => {\n      if (!cache.has(name)) cache.set(name, gl.getUniformLocation(p, name));\n      return cache.get(name) ?? null;\n    };\n    return { p, u };\n  };\n  const P = {\n    advect: program(ADVECT),\n    curl: program(CURL),\n    vorticity: program(VORTICITY),\n    splat: program(SPLAT),\n    divergence: program(DIVERGENCE),\n    scale: program(SCALE),\n    jacobi: program(JACOBI_FS),\n    gradient: program(GRADIENT),\n    display: program(DISPLAY),\n  };\n\n  const vao = gl.createVertexArray();\n  gl.bindVertexArray(vao);\n  const buffer = gl.createBuffer();\n  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);\n  gl.enableVertexAttribArray(0);\n  gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);\n\n  const targets: Target[] = [];\n  const target = (w: number, h: number): Target => {\n    const tex = gl.createTexture()!;\n    gl.bindTexture(gl.TEXTURE_2D, tex);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, w, h, 0, gl.RGBA, gl.HALF_FLOAT, null);\n    const fb = gl.createFramebuffer()!;\n    gl.bindFramebuffer(gl.FRAMEBUFFER, fb);\n    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);\n    if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) throw new Error(\"half-float targets unsupported\");\n    gl.viewport(0, 0, w, h);\n    gl.clearColor(0, 0, 0, 0);\n    gl.clear(gl.COLOR_BUFFER_BIT);\n    const t = { tex, fb, w, h };\n    targets.push(t);\n    return t;\n  };\n  const double = (w: number, h: number): Double => {\n    const d = { read: target(w, h), write: target(w, h), swap: () => ([d.read, d.write] = [d.write, d.read]) };\n    return d;\n  };\n\n  const ink = Math.max(128, Math.min(384, canvas.width));\n  const velocity = double(SIM, SIM);\n  const pressure = double(SIM, SIM);\n  const dye = double(ink, ink);\n  const divergence = target(SIM, SIM);\n  const curl = target(SIM, SIM);\n  const simTexel: [number, number] = [1 / SIM, 1 / SIM];\n  const dyeTexel: [number, number] = [1 / ink, 1 / ink];\n\n  const bind = (unit: number, tex: WebGLTexture, loc: WebGLUniformLocation | null) => {\n    gl.activeTexture(gl.TEXTURE0 + unit);\n    gl.bindTexture(gl.TEXTURE_2D, tex);\n    gl.uniform1i(loc, unit);\n  };\n  const blit = (out: Target | null) => {\n    if (out) {\n      gl.bindFramebuffer(gl.FRAMEBUFFER, out.fb);\n      gl.viewport(0, 0, out.w, out.h);\n    } else {\n      gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n      gl.viewport(0, 0, canvas.width, canvas.height);\n    }\n    gl.drawArrays(gl.TRIANGLES, 0, 3);\n  };\n\n  const points = new Float32Array(MAX_EMIT * 4);\n  const values = new Float32Array(MAX_EMIT * 4);\n  const splat = (field: Double, emitters: Emitter[], kind: \"force\" | \"ink\") => {\n    const list = emitters.filter((e) => (kind === \"force\" ? e.fx || e.fy : e.amount && e.color));\n    for (let start = 0; start < list.length; start += MAX_EMIT) {\n      const chunk = list.slice(start, start + MAX_EMIT);\n      points.fill(0);\n      values.fill(0);\n      chunk.forEach((e, i) => {\n        points.set([e.x, e.y, e.radius * e.radius, 0], i * 4);\n        if (kind === \"force\") values.set([e.fx ?? 0, e.fy ?? 0, 0, 0], i * 4);\n        else {\n          const a = e.amount ?? 0;\n          const c = e.color ?? [0, 0, 0];\n          values.set([c[0] * a, c[1] * a, c[2] * a, a], i * 4);\n        }\n      });\n      gl.useProgram(P.splat.p);\n      bind(0, field.read.tex, P.splat.u(\"uSrc\"));\n      gl.uniform4fv(P.splat.u(\"uPoint\"), points);\n      gl.uniform4fv(P.splat.u(\"uValue\"), values);\n      gl.uniform1i(P.splat.u(\"uCount\"), chunk.length);\n      blit(field.write);\n      field.swap();\n    }\n  };\n\n  let lost = false;\n  canvas.addEventListener(\"webglcontextlost\", () => (lost = true));\n  let linked = false;\n\n  return {\n    /** True once every program has linked; until then nothing may be drawn. Throws if one failed. */\n    ready() {\n      if (linked) return true;\n      if (parallel && !programs.every((p) => gl.getProgramParameter(p, parallel.COMPLETION_STATUS_KHR))) return false;\n      for (const p of programs) if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p) ?? \"link\");\n      linked = true;\n      return true;\n    },\n    /** Ink only, no force: for the first cloud. */\n    seed(emitters: Emitter[]) {\n      if (lost) return;\n      gl.disable(gl.BLEND);\n      splat(dye, emitters, \"ink\");\n    },\n    step({ dt, emitters, curl: curlAmount, velocityFade, inkFade, rimFade, swirl }: FluidStep) {\n      if (lost || dt <= 0) return;\n      gl.disable(gl.BLEND);\n\n      gl.useProgram(P.curl.p);\n      bind(0, velocity.read.tex, P.curl.u(\"uVel\"));\n      gl.uniform2fv(P.curl.u(\"uTexel\"), simTexel);\n      blit(curl);\n\n      gl.useProgram(P.vorticity.p);\n      bind(0, velocity.read.tex, P.vorticity.u(\"uVel\"));\n      bind(1, curl.tex, P.vorticity.u(\"uCurl\"));\n      gl.uniform2fv(P.vorticity.u(\"uTexel\"), simTexel);\n      gl.uniform1f(P.vorticity.u(\"uAmount\"), curlAmount);\n      gl.uniform1f(P.vorticity.u(\"uDt\"), dt);\n      gl.uniform1f(P.vorticity.u(\"uSwirl\"), swirl);\n      blit(velocity.write);\n      velocity.swap();\n\n      splat(velocity, emitters, \"force\");\n      splat(dye, emitters, \"ink\");\n\n      gl.useProgram(P.divergence.p);\n      bind(0, velocity.read.tex, P.divergence.u(\"uVel\"));\n      gl.uniform2fv(P.divergence.u(\"uTexel\"), simTexel);\n      blit(divergence);\n\n      gl.useProgram(P.scale.p);\n      bind(0, pressure.read.tex, P.scale.u(\"uSrc\"));\n      gl.uniform1f(P.scale.u(\"uKeep\"), 0.8);\n      blit(pressure.write);\n      pressure.swap();\n\n      gl.useProgram(P.jacobi.p);\n      gl.uniform2fv(P.jacobi.u(\"uTexel\"), simTexel);\n      bind(1, divergence.tex, P.jacobi.u(\"uDiv\"));\n      for (let i = 0; i < JACOBI; i++) {\n        bind(0, pressure.read.tex, P.jacobi.u(\"uPressure\"));\n        blit(pressure.write);\n        pressure.swap();\n      }\n\n      gl.useProgram(P.gradient.p);\n      bind(0, pressure.read.tex, P.gradient.u(\"uPressure\"));\n      bind(1, velocity.read.tex, P.gradient.u(\"uVel\"));\n      gl.uniform2fv(P.gradient.u(\"uTexel\"), simTexel);\n      blit(velocity.write);\n      velocity.swap();\n\n      gl.useProgram(P.advect.p);\n      gl.uniform2fv(P.advect.u(\"uSimTexel\"), simTexel);\n      gl.uniform1f(P.advect.u(\"uDt\"), dt);\n      bind(0, velocity.read.tex, P.advect.u(\"uVel\"));\n      bind(1, velocity.read.tex, P.advect.u(\"uSrc\"));\n      gl.uniform1f(P.advect.u(\"uKeep\"), 1 / (1 + velocityFade * dt));\n      gl.uniform1f(P.advect.u(\"uWall\"), 1);\n      gl.uniform1f(P.advect.u(\"uCap\"), 0);\n      gl.uniform1f(P.advect.u(\"uRim\"), 0);\n      gl.uniform1f(P.advect.u(\"uSharp\"), 0);\n      gl.uniform2fv(P.advect.u(\"uSrcTexel\"), simTexel);\n      blit(velocity.write);\n      velocity.swap();\n\n      bind(0, velocity.read.tex, P.advect.u(\"uVel\"));\n      bind(1, dye.read.tex, P.advect.u(\"uSrc\"));\n      gl.uniform1f(P.advect.u(\"uKeep\"), 1 / (1 + inkFade * dt));\n      gl.uniform1f(P.advect.u(\"uWall\"), 0);\n      gl.uniform1f(P.advect.u(\"uCap\"), 2.4);\n      gl.uniform1f(P.advect.u(\"uRim\"), rimFade);\n      gl.uniform1f(P.advect.u(\"uSharp\"), 1);\n      gl.uniform2fv(P.advect.u(\"uSrcTexel\"), dyeTexel);\n      blit(dye.write);\n      dye.swap();\n    },\n    draw({ radius, water, dark }: FluidLook) {\n      if (lost) return;\n      gl.disable(gl.BLEND);\n      gl.useProgram(P.display.p);\n      bind(0, dye.read.tex, P.display.u(\"uDye\"));\n      gl.uniform2fv(P.display.u(\"uTexel\"), dyeTexel);\n      gl.uniform1f(P.display.u(\"uRadius\"), radius);\n      gl.uniform1f(P.display.u(\"uAa\"), 1.2 / canvas.width);\n      // One CSS pixel and one device pixel, in the canvas's 0 to 1 space (the canvas is sized at up to 2x).\n      gl.uniform2f(P.display.u(\"uPx\"), Math.min(2, window.devicePixelRatio || 1) / canvas.width, 1 / canvas.width);\n      gl.uniform3fv(P.display.u(\"uInk\"), water.inks.flat());\n      gl.uniform2fv(P.display.u(\"uPool\"), water.pools.flat());\n      gl.uniform1f(P.display.u(\"uPoolA\"), water.poolAlpha);\n      gl.uniform1f(P.display.u(\"uPoolR\"), water.poolRadius);\n      gl.uniform2fv(P.display.u(\"uBase\"), water.base);\n      gl.uniform1f(P.display.u(\"uLine\"), water.line);\n      gl.uniform1f(P.display.u(\"uDark\"), dark ? 1 : 0);\n      gl.clearColor(0, 0, 0, 0);\n      gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n      gl.clear(gl.COLOR_BUFFER_BIT);\n      blit(null);\n    },\n    dispose() {\n      targets.forEach((t) => {\n        gl.deleteTexture(t.tex);\n        gl.deleteFramebuffer(t.fb);\n      });\n      programs.forEach((p) => gl.deleteProgram(p));\n      gl.deleteShader(vertex);\n      gl.deleteBuffer(buffer);\n      gl.deleteVertexArray(vao);\n    },\n  };\n}\n\nexport type FluidOrb = NonNullable<ReturnType<typeof createFluidOrb>>;\n\n/** Any CSS colour, theme variables included, as 0–1 RGB: resolved by the browser, read back from one pixel. */\nexport function resolveColors(host: HTMLElement, colors: string[]): Rgb[] {\n  const probe = document.createElement(\"span\");\n  probe.style.cssText = \"position:absolute;width:0;height:0;overflow:hidden;pointer-events:none\";\n  host.appendChild(probe);\n  const paint = document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n  const out = colors.map((css): Rgb => {\n    probe.style.color = \"\";\n    probe.style.color = css;\n    const computed = getComputedStyle(probe).color;\n    if (!paint) return [0.2, 0.36, 0.87];\n    paint.clearRect(0, 0, 1, 1);\n    paint.fillStyle = \"#3a5ddd\";\n    paint.fillStyle = computed;\n    paint.fillRect(0, 0, 1, 1);\n    const [r, g, b] = paint.getImageData(0, 0, 1, 1).data;\n    return [r / 255, g / 255, b / 255];\n  });\n  probe.remove();\n  return out;\n}\n\n/** The water as CSS: the same layers the display shader composites, for the picture shown before WebGL is ready (and\n * instead of it where WebGL 2 is missing). Colours are CSS colours, so theme variables work before anything resolves. */\nexport function waterCss(water: Omit<Water, \"inks\">, inks: string[]) {\n  const at = (n: number) => `${(n * 100).toFixed(2)}%`;\n  const mix = (css: string, a: number) => `color-mix(in srgb, ${css} ${(a * 100).toFixed(1)}%, transparent)`;\n  const pools = water.pools.map(([x, y], i) => `radial-gradient(circle calc(${water.poolRadius} * var(--orb-d)) at ${at(x)} ${at(y)}, ${mix(inks[i], water.poolAlpha)}, transparent)`);\n  const base = `radial-gradient(circle closest-side, ${mix(inks[0], water.base[0])} 50%, ${mix(inks[0], water.base[1])} 100%)`;\n  return { background: [...pools, base].join(\", \"), boxShadow: `inset 0 0 0 1px ${mix(inks[0], water.line)}` };\n}\n"},{"path":"registry/voice-audio.ts","type":"registry:component","content":"// Hairline UI · voice-orb · 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/voice-session.ts","type":"registry:component","content":"// Hairline UI · voice-orb · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { BANDS, createAudioMeter, elementSource, type AudioMeter } from \"./voice-audio\";\n\n/* ─────────────────────────────────────────────────────────\n * useVoiceSession: a voice conversation, plugged into your backend\n *\n * Two ways in, pick the one your stack has:\n *\n *   onTurn    record-then-reply. It records until the person\n *             stops talking, hands you the audio, and plays what\n *             you return: your own speech-to-text, model and\n *             text-to-speech, or one endpoint that does all three\n *   connect   realtime. It opens the microphone and hands it to\n *             you; you return the voice coming back (a WebRTC\n *             track, an <audio> element). Listening and speaking\n *             are read from the audio on each side, and you can\n *             set the state yourself from your provider's events\n *\n * It owns everything around the call: microphone permission and\n * its errors, recording, end of speech, thinking, playing the\n * reply, interrupting it, cancelling a request mid-flight, and\n * letting go of the microphone when it's done.\n * ───────────────────────────────────────────────────────── */\n\nexport type VoicePhase = \"idle\" | \"starting\" | \"listening\" | \"thinking\" | \"speaking\" | \"error\";\n/** What the orb shows for each phase. */\nexport type VoiceOrbPhase = \"idle\" | \"listening\" | \"thinking\" | \"speaking\";\n\n/** A spoken reply in any shape a backend gives one: audio data, a fetch response, a URL, an element or a live stream. */\nexport type VoiceReply = Blob | ArrayBuffer | Response | string | HTMLMediaElement | MediaStream | null | undefined | void;\n\nexport interface VoiceTurnContext {\n  /** Aborted if the person cancels or starts again: pass it to fetch. */\n  signal: AbortSignal;\n  mimeType: string;\n  /** Length of the recording in ms. */\n  duration: number;\n}\n\nexport interface VoiceConnection {\n  /** The voice coming back: a remote MediaStream, or an <audio> element you already play it in. */\n  output: MediaStream | HTMLMediaElement;\n  /** Called when the session ends. */\n  close?: () => void;\n}\n\nexport interface VoiceConnectContext {\n  signal: AbortSignal;\n  /** Set the state from your provider's events; null goes back to reading it from the audio. */\n  setState: (state: VoiceOrbPhase | null) => void;\n  /** End the session from your side (the call dropped, the agent hung up). */\n  end: () => void;\n}\n\nexport type VoiceErrorKind = \"permission\" | \"no-microphone\" | \"unsupported\" | \"no-speech\" | \"turn\" | \"playback\" | \"connection\";\n\nexport class VoiceError extends Error {\n  kind: VoiceErrorKind;\n  constructor(kind: VoiceErrorKind, message: string, cause?: unknown) {\n    super(message, { cause });\n    this.kind = kind;\n    this.name = \"VoiceError\";\n  }\n}\n\nexport interface VoiceSessionOptions {\n  /** Record-then-reply: gets each finished turn's audio, returns the spoken reply (or nothing). Throw to show an error. */\n  onTurn?: (audio: Blob, context: VoiceTurnContext) => Promise<VoiceReply> | VoiceReply;\n  /** Realtime: gets the open microphone, returns the voice coming back. */\n  connect?: (microphone: MediaStream, context: VoiceConnectContext) => Promise<VoiceConnection> | VoiceConnection;\n  /** Your own microphone stream (a device picker, an SDK that owns it). Default: getUserMedia with echo cancellation. */\n  getMicrophone?: () => Promise<MediaStream>;\n  /** After a reply, listen again, hands-free. */\n  continuous?: boolean;\n  /** Quiet after speech that ends a turn, in ms. */\n  silence?: number;\n  /** Longest turn, in ms; it is sent when reached. */\n  maxTurn?: number;\n  /** How long to wait for any speech before giving up, in ms. */\n  waitForSpeech?: number;\n  onPhaseChange?: (phase: VoicePhase) => void;\n  onError?: (error: VoiceError) => void;\n}\n\nexport interface VoiceSession {\n  phase: VoicePhase;\n  /** The phase as the orb shows it. */\n  state: VoiceOrbPhase;\n  error: VoiceError | null;\n  /** Start listening (or connect, in realtime). Call it from a click or a key press: browsers only open the mic then. */\n  start: () => void;\n  /** End the turn now and send it. */\n  send: () => void;\n  /** Stop the reply and listen again. */\n  interrupt: () => void;\n  /** End everything: cancel the request, stop the reply, close the connection, let go of the microphone. */\n  stop: () => void;\n  /** The one-button behaviour: talk, send, cancel, interrupt or retry, by phase. */\n  toggle: () => void;\n  /** For the orb: the microphone while listening, the reply while speaking. */\n  getLevel: () => number;\n  getSpectrum: () => ArrayLike<number>;\n}\n\nlet warmed = false;\nconst MIME = [\"audio/webm;codecs=opus\", \"audio/webm\", \"audio/mp4\", \"audio/ogg;codecs=opus\"];\nconst SILENT = new Float32Array(BANDS);\n// One frame of silence, played inside the first click so Safari lets the reply play later without one.\nconst UNLOCK = \"data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAIA+AAACABAAZGF0YQAAAAA=\";\nconst SPEECH = 0.14;\nconst QUIET = 0.08;\n\nconst orbPhase = (phase: VoicePhase): VoiceOrbPhase => (phase === \"listening\" || phase === \"thinking\" || phase === \"speaking\" ? phase : \"idle\");\n\nfunction micError(error: unknown) {\n  const name = error instanceof DOMException ? error.name : \"\";\n  if (name === \"NotAllowedError\" || name === \"SecurityError\") return new VoiceError(\"permission\", \"Microphone access was blocked.\", error);\n  if (name === \"NotFoundError\" || name === \"OverconstrainedError\" || name === \"NotReadableError\")\n    return new VoiceError(\"no-microphone\", \"No microphone was found.\", error);\n  return new VoiceError(\"unsupported\", \"This browser can't record audio here.\", error);\n}\n\ninterface Runtime {\n  generation: number;\n  context: AudioContext | null;\n  mic: MediaStream | null;\n  micMeter: AudioMeter | null;\n  outMeter: AudioMeter | null;\n  recorder: MediaRecorder | null;\n  chunks: Blob[];\n  controller: AbortController | null;\n  player: HTMLAudioElement | null;\n  streamPlayer: HTMLAudioElement | null;\n  playing: HTMLMediaElement | null;\n  url: string | null;\n  connection: VoiceConnection | null;\n  manual: VoiceOrbPhase | null;\n  timer: number;\n  phase: VoicePhase;\n  turnStart: number;\n}\n\n/** The session itself, outside React: created once per hook, it holds its options and reports phase and error back. */\nfunction createSession(setPhaseState: (phase: VoicePhase) => void, setError: (error: VoiceError | null) => void) {\n  const opts: { current: VoiceSessionOptions } = { current: {} };\n  const r: Runtime = {\n    generation: 0,\n    context: null,\n    mic: null,\n    micMeter: null,\n    outMeter: null,\n    recorder: null,\n    chunks: [],\n    controller: null,\n    player: null,\n    streamPlayer: null,\n    playing: null,\n    url: null,\n    connection: null,\n    manual: null,\n    timer: 0,\n    phase: \"idle\",\n    turnStart: 0,\n  };\n\n  const setPhase = (next: VoicePhase) => {\n    if (r.phase === next) return;\n    r.phase = next;\n    setPhaseState(next);\n    opts.current.onPhaseChange?.(next);\n  };\n  const fail = (err: VoiceError) => {\n    release();\n    setError(err);\n    setPhase(\"error\");\n    opts.current.onError?.(err);\n  };\n\n  const clearTimer = () => {\n    if (r.timer) window.clearInterval(r.timer);\n    r.timer = 0;\n  };\n  const stopOutput = () => {\n    r.outMeter?.disconnect();\n    r.outMeter = null;\n    if (r.playing) {\n      r.playing.onended = null;\n      r.playing.onerror = null;\n      r.playing.pause();\n    }\n    r.playing = null;\n    if (r.streamPlayer) r.streamPlayer.srcObject = null;\n    if (r.url) URL.revokeObjectURL(r.url);\n    r.url = null;\n  };\n  const releaseMic = () => {\n    r.micMeter?.disconnect();\n    r.micMeter = null;\n    // A microphone you handed in stays yours; one we opened, we close, so the browser's recording light goes off.\n    if (r.mic && !opts.current.getMicrophone) r.mic.getTracks().forEach((t) => t.stop());\n    r.mic = null;\n  };\n  /** Everything off, back to rest. Bumping the generation makes any late reply land nowhere. */\n  function release() {\n    r.generation++;\n    clearTimer();\n    r.controller?.abort();\n    r.controller = null;\n    if (r.recorder && r.recorder.state !== \"inactive\") {\n      r.recorder.ondataavailable = null;\n      r.recorder.onstop = null;\n      r.recorder.stop();\n    }\n    r.recorder = null;\n    r.chunks = [];\n    stopOutput();\n    r.connection?.close?.();\n    r.connection = null;\n    r.manual = null;\n    releaseMic();\n  }\n\n  const audio = () => {\n    r.context ??= new AudioContext();\n    void r.context.resume().catch(() => {});\n    return r.context;\n  };\n  const microphone = async () => {\n    if (r.mic?.getAudioTracks().some((t) => t.readyState === \"live\")) return r.mic;\n    const own = opts.current.getMicrophone;\n    if (own) return (r.mic = await own());\n    if (!navigator.mediaDevices?.getUserMedia) throw new VoiceError(\"unsupported\", \"Recording needs a secure (https) page.\");\n    try {\n      r.mic = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } });\n    } catch (err) {\n      throw micError(err);\n    }\n    return r.mic;\n  };\n\n  /** Record a turn, listening for the end of speech. */\n  const listen = async () => {\n    const gen = r.generation;\n    setError(null);\n    setPhase(\"starting\");\n    let mic: MediaStream;\n    try {\n      mic = await microphone();\n    } catch (err) {\n      if (gen === r.generation) fail(err instanceof VoiceError ? err : micError(err));\n      return;\n    }\n    if (gen !== r.generation) return;\n    const ctx = audio();\n    r.micMeter ??= createAudioMeter(ctx, ctx.createMediaStreamSource(mic));\n    if (typeof MediaRecorder === \"undefined\") return fail(new VoiceError(\"unsupported\", \"This browser can't record audio.\"));\n    const mimeType = MIME.find((m) => MediaRecorder.isTypeSupported(m)) ?? \"\";\n    const recorder = new MediaRecorder(mic, mimeType ? { mimeType } : undefined);\n    r.recorder = recorder;\n    r.chunks = [];\n    recorder.ondataavailable = (e) => e.data.size && r.chunks.push(e.data);\n    recorder.start(250);\n    r.turnStart = performance.now();\n    setPhase(\"listening\");\n\n    const startedAt = performance.now();\n    let loud = 0;\n    let spoke = false;\n    let quietSince = 0;\n    const { silence = 900, maxTurn = 30000, waitForSpeech = 8000 } = opts.current;\n    clearTimer();\n    r.timer = window.setInterval(() => {\n      const now = performance.now();\n      const level = r.micMeter?.getLevel() ?? 0;\n      if (level > SPEECH) {\n        // Speech is three loud ticks in a row, so a click or a cough doesn't start the countdown.\n        if (++loud >= 3) spoke = true;\n        quietSince = 0;\n      } else {\n        loud = 0;\n        if (spoke && level < QUIET) quietSince ||= now;\n      }\n      if (spoke && quietSince && now - quietSince > silence) void send();\n      else if (now - startedAt > maxTurn) void send();\n      else if (!spoke && now - startedAt > waitForSpeech) {\n        fail(new VoiceError(\"no-speech\", \"Didn't hear anything.\"));\n      }\n    }, 50);\n  };\n\n  /** Play a reply, metering it for the orb. */\n  const play = async (reply: VoiceReply, gen: number) => {\n    if (reply == null) return done(gen);\n    const ctx = audio();\n    let element: HTMLMediaElement;\n    if (reply instanceof MediaStream) {\n      element = r.streamPlayer ??= new Audio();\n      element.srcObject = reply;\n      r.outMeter = createAudioMeter(ctx, ctx.createMediaStreamSource(reply));\n    } else if (reply instanceof HTMLMediaElement) {\n      element = reply;\n      const source = elementSource(element, ctx);\n      r.outMeter = createAudioMeter(source.context, source.node);\n    } else {\n      element = r.player ??= new Audio();\n      let src: string;\n      if (typeof reply === \"string\") {\n        // A URL plays as it streams in. Web Audio can only meter it if it's same-origin or sent with CORS.\n        element.crossOrigin = \"anonymous\";\n        src = reply;\n      } else {\n        const blob = reply instanceof Response ? await reply.blob() : reply instanceof Blob ? reply : new Blob([reply as ArrayBuffer]);\n        if (gen !== r.generation) return;\n        src = r.url = URL.createObjectURL(blob);\n      }\n      element.src = src;\n      const source = elementSource(element, ctx);\n      r.outMeter = createAudioMeter(source.context, source.node);\n    }\n    r.playing = element;\n    element.onended = () => done(gen);\n    element.onerror = () => gen === r.generation && fail(new VoiceError(\"playback\", \"Couldn't play the reply.\"));\n    setPhase(\"speaking\");\n    try {\n      await element.play();\n    } catch (err) {\n      if (gen === r.generation) fail(new VoiceError(\"playback\", \"Couldn't play the reply.\", err));\n    }\n  };\n\n  const done = (gen: number) => {\n    if (gen !== r.generation) return;\n    stopOutput();\n    if (opts.current.continuous) void listen();\n    else {\n      release();\n      setPhase(\"idle\");\n    }\n  };\n\n  /** End the turn and hand it to onTurn. */\n  async function send() {\n    const recorder = r.recorder;\n    if (r.phase !== \"listening\" || !recorder) return;\n    clearTimer();\n    const gen = r.generation;\n    const mimeType = recorder.mimeType;\n    const stopped = new Promise<void>((resolve) => (recorder.onstop = () => resolve()));\n    recorder.stop();\n    r.recorder = null;\n    setPhase(\"thinking\");\n    await stopped;\n    if (gen !== r.generation) return;\n    const blob = new Blob(r.chunks, { type: mimeType });\n    r.chunks = [];\n    if (!opts.current.continuous) releaseMic();\n    const controller = new AbortController();\n    r.controller = controller;\n    let reply: VoiceReply;\n    try {\n      reply = await opts.current.onTurn?.(blob, { signal: controller.signal, mimeType, duration: Math.round(performance.now() - r.turnStart) });\n    } catch (err) {\n      if (gen === r.generation && !controller.signal.aborted)\n        fail(new VoiceError(\"turn\", err instanceof Error && err.message ? err.message : \"The assistant didn't answer.\", err));\n      return;\n    }\n    if (gen !== r.generation) return;\n    r.controller = null;\n    await play(reply, gen);\n  }\n\n  /** Realtime: open the mic, hand it over, read the states from both sides of the audio. */\n  const connect = async () => {\n    const gen = r.generation;\n    setError(null);\n    setPhase(\"starting\");\n    let mic: MediaStream;\n    try {\n      mic = await microphone();\n    } catch (err) {\n      if (gen === r.generation) fail(err instanceof VoiceError ? err : micError(err));\n      return;\n    }\n    const ctx = audio();\n    const controller = new AbortController();\n    r.controller = controller;\n    let connection: VoiceConnection;\n    try {\n      connection = await opts.current.connect!(mic, {\n        signal: controller.signal,\n        setState: (s) => (r.manual = s),\n        end: () => {\n          if (gen !== r.generation) return;\n          release();\n          setPhase(\"idle\");\n        },\n      });\n    } catch (err) {\n      if (gen === r.generation && !controller.signal.aborted)\n        fail(new VoiceError(\"connection\", err instanceof Error && err.message ? err.message : \"Couldn't connect.\", err));\n      return;\n    }\n    if (gen !== r.generation) {\n      connection.close?.();\n      return;\n    }\n    r.connection = connection;\n    r.micMeter ??= createAudioMeter(ctx, ctx.createMediaStreamSource(mic));\n    const out = connection.output;\n    if (out instanceof MediaStream) {\n      // A remote WebRTC stream only plays from an element; it's metered separately, not routed twice.\n      const element = (r.streamPlayer ??= new Audio());\n      element.srcObject = out;\n      void element.play().catch(() => {});\n      r.outMeter = createAudioMeter(ctx, ctx.createMediaStreamSource(out));\n    } else {\n      const source = elementSource(out, ctx);\n      r.outMeter = createAudioMeter(source.context, source.node);\n    }\n    setPhase(\"listening\");\n    let voiceUntil = 0;\n    let heardAt = 0;\n    let loud = 0;\n    clearTimer();\n    r.timer = window.setInterval(() => {\n      const now = performance.now();\n      if (r.manual) return setPhase(r.manual);\n      const outLevel = r.outMeter?.getLevel() ?? 0;\n      const inLevel = r.micMeter?.getLevel() ?? 0;\n      if (outLevel > 0.08) voiceUntil = now + 350;\n      if (now < voiceUntil) {\n        heardAt = 0;\n        return setPhase(\"speaking\");\n      }\n      if (inLevel > SPEECH) {\n        if (++loud >= 3) heardAt = now;\n      } else loud = 0;\n      // After the person stops, and before the voice comes back: the model is working.\n      const waiting = heardAt && now - heardAt > 600 && now - heardAt < 8000 && inLevel < QUIET;\n      setPhase(waiting ? \"thinking\" : \"listening\");\n    }, 60);\n  };\n\n  const start = () => {\n    if (r.phase !== \"idle\" && r.phase !== \"error\") return;\n    // Inside the click: the audio context and the player are unlocked now, while the browser still counts it as a gesture.\n    audio();\n    if (!r.player) {\n      r.player = new Audio();\n      r.player.src = UNLOCK;\n      void r.player.play().catch(() => {});\n    }\n    if (opts.current.connect) void connect();\n    else void listen();\n  };\n  const stop = () => {\n    release();\n    setError(null);\n    setPhase(\"idle\");\n  };\n  const interrupt = () => {\n    if (r.phase !== \"speaking\") return;\n    if (opts.current.connect) return;\n    r.generation++;\n    stopOutput();\n    void listen();\n  };\n  const toggle = () => {\n    const p = r.phase;\n    if (p === \"idle\" || p === \"error\") start();\n    else if (p === \"listening\") {\n      if (opts.current.connect) stop();\n      else void send();\n    } else if (p === \"speaking\") {\n      if (opts.current.connect) stop();\n      else interrupt();\n    } else stop();\n  };\n\n  return {\n    configure: (next: VoiceSessionOptions) => {\n      opts.current = next;\n    },\n    start,\n    send: () => void send(),\n    interrupt,\n    stop,\n    toggle,\n    getLevel: () => (r.phase === \"listening\" ? (r.micMeter?.getLevel() ?? 0) : r.phase === \"speaking\" ? (r.outMeter?.getLevel() ?? 0) : 0),\n    getSpectrum: () =>\n      r.phase === \"listening\" ? (r.micMeter?.getSpectrum() ?? SILENT) : r.phase === \"speaking\" ? (r.outMeter?.getSpectrum() ?? SILENT) : SILENT,\n    dispose() {\n      release();\n      void r.context?.close().catch(() => {});\n      r.context = null;\n    },\n  };\n}\n\nexport function useVoiceSession(options: VoiceSessionOptions = {}): VoiceSession {\n  const [phase, setPhase] = React.useState<VoicePhase>(\"idle\");\n  const [error, setError] = React.useState<VoiceError | null>(null);\n  const [api] = React.useState(() => createSession(setPhase, setError));\n  React.useLayoutEffect(() => {\n    api.configure(options);\n  });\n  React.useEffect(() => () => api.dispose(), [api]);\n  // The first recorder a page makes is slow to build (the browser looks up its encoders, and on some systems that\n  // stalls drawing for a few frames), so build a throwaway one while the page is idle instead of inside the press.\n  React.useEffect(() => {\n    if (warmed || typeof MediaRecorder === \"undefined\" || options.connect) return;\n    const warm = () => {\n      warmed = true;\n      try {\n        const mimeType = MIME.find((m) => MediaRecorder.isTypeSupported(m));\n        new MediaRecorder(new MediaStream(), mimeType ? { mimeType } : undefined);\n      } catch {}\n    };\n    if (typeof window.requestIdleCallback === \"function\") {\n      const id = window.requestIdleCallback(warm, { timeout: 2000 });\n      return () => window.cancelIdleCallback(id);\n    }\n    const id = setTimeout(warm, 1200);\n    return () => clearTimeout(id);\n    // Once per mount is enough; the connect option doesn't change between renders in practice.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  return React.useMemo(\n    () => ({\n      phase,\n      state: orbPhase(phase),\n      error,\n      start: api.start,\n      send: api.send,\n      interrupt: api.interrupt,\n      stop: api.stop,\n      toggle: api.toggle,\n      getLevel: api.getLevel,\n      getSpectrum: api.getSpectrum,\n    }),\n    [phase, error, api],\n  );\n}\n"},{"path":"registry/voice-talk.tsx","type":"registry:component","content":"// Hairline UI · voice-orb · 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, RotateCcw, Square, X } from \"lucide-react\";\nimport { TextMorph } from \"./text-morph\";\nimport { EASE_OUT, INTERACTION_FOCUS, INTERACTION_PRESS, useInteractionReducedMotion } from \"./ui-interaction-motion\";\nimport { VoiceOrb } from \"./voice-orb\";\nimport { useVoiceSession, type VoiceError, type VoicePhase, type VoiceSession, type VoiceSessionOptions } from \"./voice-session\";\n\n/* ─────────────────────────────────────────────────────────\n * VOICE TALK: the voice orb with its controls, wired to a session\n *\n *   one button  says what pressing it does next and morphs into\n *               it: Talk → Send → Thinking (press to cancel) →\n *               Interrupt → Talk. Hold mode: press and talk,\n *               let go to send\n *   end         slides in beside it while a session is on, and\n *               ends everything\n *   errors      the button turns into the fix (\"Allow the\n *               microphone\", \"Try again\") and the reason folds\n *               open under it\n *\n * Give it onTurn or connect (see useVoiceSession), or pass a\n * session you made yourself to drive it from elsewhere too.\n * ───────────────────────────────────────────────────────── */\n\nexport interface VoiceTalkLabels {\n  idle: string;\n  hold: string;\n  starting: string;\n  listening: string;\n  holding: string;\n  thinking: string;\n  speaking: string;\n  live: string;\n  end: string;\n  retry: string;\n  permission: string;\n  noMicrophone: string;\n  noSpeech: string;\n}\n\nexport interface VoiceTalkProps extends VoiceSessionOptions {\n  /** A session from useVoiceSession, to control it from elsewhere too. Without one it makes its own from these props. */\n  session?: VoiceSession;\n  /** Tap to talk (it sends when you stop talking, or when tapped), or hold to talk and let go to send. */\n  mode?: \"tap\" | \"hold\";\n  /** The orb's diameter in px. */\n  size?: number;\n  colors?: [string, string, string];\n  /** The assistant's name, for screen readers. */\n  label?: string;\n  labels?: Partial<VoiceTalkLabels>;\n  className?: string;\n}\n\nconst LABELS: VoiceTalkLabels = {\n  idle: \"Talk\",\n  hold: \"Hold to talk\",\n  starting: \"Starting\",\n  listening: \"Send\",\n  holding: \"Release to send\",\n  thinking: \"Thinking\",\n  speaking: \"Interrupt\",\n  live: \"Listening\",\n  end: \"End\",\n  retry: \"Try again\",\n  permission: \"Allow the microphone\",\n  noMicrophone: \"No microphone\",\n  noSpeech: \"Didn't hear you\",\n};\n\nconst HELP: Partial<Record<VoiceError[\"kind\"], string>> = {\n  permission: \"Microphone access is blocked. Allow it from the icon in the address bar, then try again.\",\n  \"no-microphone\": \"No microphone was found. Plug one in or pick one in your system settings.\",\n  unsupported: \"This browser can't record audio on this page. It needs a secure (https) page and a recent browser.\",\n};\n\ntype Icon = \"mic\" | \"send\" | \"stop\" | \"spin\" | \"retry\";\n\nfunction iconFor(phase: VoicePhase, mode: \"tap\" | \"hold\", realtime: boolean): Icon {\n  if (phase === \"starting\") return \"spin\";\n  if (phase === \"listening\") return realtime || mode === \"hold\" ? \"stop\" : \"send\";\n  if (phase === \"thinking\") return realtime ? \"stop\" : \"spin\";\n  if (phase === \"speaking\") return realtime ? \"stop\" : \"mic\";\n  if (phase === \"error\") return \"retry\";\n  return \"mic\";\n}\n\nfunction labelFor(phase: VoicePhase, error: VoiceError | null, mode: \"tap\" | \"hold\", realtime: boolean, holding: boolean, l: VoiceTalkLabels) {\n  if (phase === \"error\") {\n    if (error?.kind === \"permission\") return l.permission;\n    if (error?.kind === \"no-microphone\") return l.noMicrophone;\n    if (error?.kind === \"no-speech\") return l.noSpeech;\n    return l.retry;\n  }\n  if (phase === \"starting\") return l.starting;\n  if (realtime && phase !== \"idle\") return phase === \"thinking\" ? l.thinking : phase === \"speaking\" ? l.speaking : l.live;\n  if (phase === \"listening\") return holding ? l.holding : l.listening;\n  if (phase === \"thinking\") return l.thinking;\n  if (phase === \"speaking\") return l.speaking;\n  return mode === \"hold\" ? l.hold : l.idle;\n}\n\nfunction Spinner() {\n  return (\n    <svg viewBox=\"0 0 16 16\" className=\"size-4 animate-spin\" fill=\"none\" aria-hidden=\"true\">\n      <circle cx=\"8\" cy=\"8\" r=\"6\" stroke=\"currentColor\" strokeOpacity=\"0.25\" strokeWidth=\"1.8\" />\n      <path d=\"M14 8a6 6 0 0 0-6-6\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" />\n    </svg>\n  );\n}\n\nexport function VoiceTalk({ session: given, mode = \"tap\", size = 200, colors, label = \"Voice assistant\", labels, className = \"\", ...options }: VoiceTalkProps) {\n  const own = useVoiceSession(options);\n  const session = given ?? own;\n  const { phase, error } = session;\n  const reduced = useInteractionReducedMotion();\n  const [holding, setHolding] = React.useState(false);\n  const button = React.useRef<HTMLButtonElement>(null);\n  const realtime = Boolean(options.connect);\n  const l = { ...LABELS, ...labels };\n\n  // \"Starting\" only shows if opening the microphone takes a moment (a permission prompt); usually it's instant, and\n  // flashing a word for one frame would morph the label twice.\n  const [slowStart, setSlowStart] = React.useState(false);\n  React.useEffect(() => {\n    if (phase !== \"starting\") return;\n    const timer = window.setTimeout(() => setSlowStart(true), 350);\n    return () => {\n      window.clearTimeout(timer);\n      setSlowStart(false);\n    };\n  }, [phase]);\n  const active = phase !== \"idle\" && phase !== \"error\";\n  const icon = iconFor(phase, mode, realtime);\n  const text = phase === \"starting\" && !slowStart ? labelFor(\"idle\", null, mode, realtime, holding, l) : labelFor(phase, error, mode, realtime, holding, l);\n  const help = phase === \"error\" && error ? (HELP[error.kind] ?? error.message) : \"\";\n  const primary = !active;\n\n  // The help keeps its last words while it folds away, so it never empties on the way out.\n  const [shownHelp, setShownHelp] = React.useState(help);\n  if (help && help !== shownHelp) setShownHelp(help);\n\n  const press = () => {\n    if (mode === \"tap\") return session.toggle();\n    if (phase === \"idle\" || phase === \"error\") session.start();\n    else if (phase === \"speaking\") session.interrupt();\n    else if (phase === \"thinking\") session.stop();\n    setHolding(true);\n  };\n  const release = () => {\n    if (mode !== \"hold\" || !holding) return;\n    setHolding(false);\n    if (phase === \"listening\") session.send();\n    else if (phase === \"starting\") session.stop();\n  };\n\n  const say = phase === \"error\" ? (error?.message ?? \"\") : phase === \"idle\" ? \"\" : phase === \"starting\" ? l.starting : phase === \"listening\" ? l.live : phase === \"thinking\" ? l.thinking : \"Speaking\";\n\n  return (\n    <div className={`flex flex-col items-center ${className}`}>\n      <div className={mode === \"tap\" ? \"cursor-pointer\" : undefined} onClick={mode === \"tap\" ? () => session.toggle() : undefined}>\n        <VoiceOrb state={session.state} getLevel={session.getLevel} getSpectrum={session.getSpectrum} size={size} colors={colors} label={label} />\n      </div>\n\n      <div className=\"mt-5 flex items-center\">\n        <button\n          ref={button}\n          type=\"button\"\n          aria-pressed={mode === \"hold\" ? holding : undefined}\n          onClick={mode === \"tap\" ? press : undefined}\n          onPointerDown={\n            mode === \"hold\"\n              ? (event) => {\n                  if (event.button !== 0) return;\n                  event.currentTarget.setPointerCapture(event.pointerId);\n                  press();\n                }\n              : undefined\n          }\n          onPointerUp={mode === \"hold\" ? release : undefined}\n          onPointerCancel={mode === \"hold\" ? release : undefined}\n          onKeyDown={\n            mode === \"hold\"\n              ? (event) => {\n                  if ((event.key === \" \" || event.key === \"Enter\") && !event.repeat) {\n                    event.preventDefault();\n                    press();\n                  }\n                }\n              : undefined\n          }\n          onKeyUp={\n            mode === \"hold\"\n              ? (event) => {\n                  if (event.key === \" \" || event.key === \"Enter\") release();\n                }\n              : undefined\n          }\n          className={`group/talk relative isolate inline-flex h-11 cursor-pointer touch-none select-none items-center gap-2 rounded-full pl-4 pr-5 text-[14px] font-medium transition-colors duration-300 [-webkit-touch-callout:none] ${INTERACTION_PRESS} ${INTERACTION_FOCUS} ${\n            primary ? \"text-primary-foreground\" : \"text-foreground\"\n          }`}\n        >\n          {/* The two faces of the button are layers that cross-fade, so changing face never repaints the label under it. */}\n          <span aria-hidden=\"true\" className=\"absolute inset-0 -z-10 rounded-full bg-background shadow-[inset_0_0_0_1px_var(--border)] group-hover/talk:bg-accent\" />\n          <span\n            aria-hidden=\"true\"\n            className=\"absolute inset-0 -z-10 rounded-full bg-primary will-change-[opacity] group-hover/talk:brightness-110\"\n            style={{ opacity: primary ? 1 : 0, transition: reduced ? \"none\" : `opacity 300ms ${EASE_OUT}` }}\n          />\n          <span aria-hidden=\"true\" className=\"relative grid size-4 place-items-center\">\n            {([\"mic\", \"send\", \"stop\", \"spin\", \"retry\"] as Icon[]).map((name) => (\n              // Icons swap by scale and fade only: a blur at 16px is invisible and costs a repaint every frame.\n              <span\n                key={name}\n                className=\"absolute inset-0 grid place-items-center will-change-transform\"\n                style={{\n                  opacity: icon === name ? 1 : 0,\n                  transform: icon === name ? \"none\" : \"scale(0.6)\",\n                  transition: reduced ? \"none\" : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}`,\n                }}\n              >\n                {name === \"mic\" && <Mic className=\"size-4\" strokeWidth={2} />}\n                {name === \"send\" && <ArrowUp className=\"size-4\" strokeWidth={2.2} />}\n                {name === \"stop\" && <Square className=\"size-3 fill-current\" strokeWidth={0} />}\n                {name === \"spin\" && icon === \"spin\" && <Spinner />}\n                {name === \"retry\" && <RotateCcw className=\"size-4\" strokeWidth={2} />}\n              </span>\n            ))}\n          </span>\n          <TextMorph>{text}</TextMorph>\n        </button>\n\n        {/* End: slides in beside the button while a session is on. */}\n        <span\n          className=\"grid\"\n          style={{\n            gridTemplateColumns: active ? \"1fr\" : \"0fr\",\n            opacity: active ? 1 : 0,\n            transition: reduced ? \"none\" : `grid-template-columns 420ms ${EASE_OUT}, opacity ${active ? \"260ms 80ms\" : \"160ms\"} ${EASE_OUT}`,\n          }}\n        >\n          <span className=\"min-w-0 [clip-path:inset(-4px)]\">\n            <span className=\"block pl-2\">\n              <button\n                type=\"button\"\n                aria-label={l.end}\n                tabIndex={active ? undefined : -1}\n                onClick={() => {\n                  session.stop();\n                  button.current?.focus({ preventScroll: true });\n                }}\n                className={`grid size-11 cursor-pointer place-items-center rounded-full bg-background text-muted-foreground shadow-[inset_0_0_0_1px_var(--border)] transition-colors hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n              >\n                <X className=\"size-4\" strokeWidth={2} />\n              </button>\n            </span>\n          </span>\n        </span>\n      </div>\n\n      {/* Why it failed, folded open under the button that fixes it. */}\n      <div\n        className=\"grid w-full max-w-[300px]\"\n        style={{ gridTemplateRows: help ? \"1fr\" : \"0fr\", opacity: help ? 1 : 0, transition: reduced ? \"none\" : `grid-template-rows 420ms ${EASE_OUT}, opacity 260ms ${EASE_OUT}` }}\n      >\n        <p className=\"min-h-0 overflow-clip text-center text-[12.5px] leading-[18px] text-muted-foreground\">\n          <span className=\"block pt-3\">{shownHelp}</span>\n        </p>\n      </div>\n\n      <span role=\"status\" className=\"sr-only\">\n        {say}\n      </span>\n    </div>\n  );\n}\n\nexport default VoiceTalk;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · voice-orb · 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":{},"docs":"Docs and live preview: https://hairlineui.com/ui/voice-orb. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}