{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"voice-orb","type":"registry:component","title":"Voice orb","description":"A glassy orb of drifting mist that listens to your real mic, thinks in a slow swirl and breathes as it speaks.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/voice-orb.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\nimport { cn } from \"@/lib/utils\";\n\nexport type OrbState = \"idle\" | \"listening\" | \"thinking\" | \"speaking\";\n\n// The orb's soft accent: mist in a pale blue, a violet and a cool cyan. Raw\n// colours on purpose, as the one accent this component carries; each is a\n// light-dark() pair so the mist glows on a dark page and stays airy on a\n// light one.\nconst MIST = [\n  \"light-dark(oklch(0.72 0.14 255), oklch(0.62 0.17 262))\",\n  \"light-dark(oklch(0.8 0.1 300), oklch(0.62 0.13 300))\",\n  \"light-dark(oklch(0.86 0.09 210), oklch(0.7 0.1 215))\",\n  \"light-dark(oklch(0.78 0.12 240), oklch(0.55 0.14 250))\",\n];\n\n// Per blob: orbit rate and the Lissajous ratio of its path, so the four\n// never fall into step and the mist never repeats visibly.\nconst BLOBS = [\n  { rate: 0.9, a: 1, b: 1.6, phase: 0 },\n  { rate: 0.7, a: 1.4, b: 1, phase: 2.1 },\n  { rate: 1.1, a: 1, b: 1.3, phase: 4.2 },\n  { rate: 0.55, a: 1.7, b: 1.1, phase: 5.3 },\n];\n\n// Per state: how lively the mist is (drift speed) and how far the blobs\n// wander from the centre, as a share of the orb.\n// Slow on purpose: the mist should drift like weather, never race. Even the\n// busiest state takes well over ten seconds per lap.\nconst MOODS: Record<OrbState, { speed: number; spread: number }> = {\n  idle: { speed: 0.14, spread: 0.12 },\n  listening: { speed: 0.22, spread: 0.15 },\n  // A slow shared swirl, so thinking reads as one motion, not noise.\n  thinking: { speed: 0.5, spread: 0.18 },\n  speaking: { speed: 0.32, spread: 0.17 },\n};\n\nconst LABELS: Record<OrbState, string> = {\n  idle: \"Tap listen to talk\",\n  listening: \"Listening\",\n  thinking: \"Thinking\",\n  speaking: \"Speaking\",\n};\n\n// Attack faster than release, so sounds land quickly and fade away, but\n// both soft enough that the orb breathes with a voice instead of twitching\n// on every syllable.\nconst ATTACK = 7;\nconst RELEASE = 2.8;\n\ntype Mic = { stream: MediaStream; ctx: AudioContext; analyser: AnalyserNode };\n\nexport function VoiceOrb({\n  state,\n  size = 208,\n  mic,\n  paused = false,\n  className,\n}: {\n  state: OrbState;\n  size?: number;\n  // A live microphone to follow while listening. Without one, listening\n  // shows a quiet simulated room.\n  mic?: Mic | null;\n  // Holds a still frame and runs nothing, for idle previews.\n  paused?: boolean;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const blobRefs = useRef<(HTMLDivElement | null)[]>([]);\n  const bodyRef = useRef<HTMLDivElement>(null);\n  const ringRefs = useRef<(HTMLDivElement | null)[]>([]);\n  const stateRef = useRef(state);\n  const micRef = useRef(mic);\n\n  useEffect(() => {\n    stateRef.current = state;\n    micRef.current = mic;\n  });\n\n  useEffect(() => {\n    const root = rootRef.current;\n    if (!root || paused) return;\n    let frame = 0;\n    let visible = true;\n    let last = performance.now();\n    let t = 0;\n    // Each blob's angle advances a little every frame. Computing it as\n    // time x speed instead would make any change of speed rescale all the\n    // time gone by, flinging every blob around the orb in one frame.\n    const angles = BLOBS.map((b) => b.phase);\n    let level = 0;\n    let speed = MOODS[stateRef.current].speed;\n    let spread = MOODS[stateRef.current].spread;\n    // Speech: a target that hops every syllable, with the odd pause.\n    let syllable = 0;\n    let target = 0;\n    const samples = new Float32Array(512);\n\n    const read = (dt: number) => {\n      const s = stateRef.current;\n      if (s === \"listening\") {\n        const m = micRef.current;\n        if (m) {\n          m.analyser.getFloatTimeDomainData(samples);\n          let sum = 0;\n          for (const v of samples) sum += v * v;\n          const rms = Math.sqrt(sum / samples.length);\n          // Room tone sits near 0.005; normal speech peaks around 0.1.\n          return Math.min(Math.max((rms - 0.008) * 9, 0), 1);\n        }\n        // No mic: a quiet room with the occasional murmur.\n        return 0.08 + 0.06 * Math.sin(t * 2.3) + 0.04 * Math.sin(t * 5.1);\n      }\n      if (s === \"speaking\") {\n        syllable -= dt;\n        if (syllable <= 0) {\n          const pause = Math.random() < 0.14;\n          syllable = pause ? 0.3 + Math.random() * 0.3 : 0.16 + Math.random() * 0.18;\n          target = pause ? 0.05 : 0.35 + Math.random() * 0.5;\n        }\n        return target;\n      }\n      if (s === \"thinking\") return 0.14 + 0.08 * Math.sin(t * 3.2);\n      return 0.06 + 0.04 * Math.sin(t * 1.3);\n    };\n\n    const step = (now: number) => {\n      const dt = Math.min((now - last) / 1000, 1 / 30);\n      last = now;\n      const mood = MOODS[stateRef.current];\n      // Moods blend rather than switch, so a change of state eases in.\n      // About a second to settle into a new state.\n      const k = 1 - Math.exp(-1.6 * dt);\n      speed += (mood.speed - speed) * k;\n      spread += (mood.spread - spread) * k;\n      const want = read(dt);\n      level += (want - level) * (1 - Math.exp(-(want > level ? ATTACK : RELEASE) * dt));\n      t += dt * (reduceMotion ? 0.2 : 1);\n\n      const drift = reduceMotion ? 0 : 1;\n      BLOBS.forEach((b, i) => {\n        const el = blobRefs.current[i];\n        if (!el) return;\n        angles[i] += dt * speed * b.rate * drift;\n        const angle = angles[i];\n        // The voice mostly swells and brightens the mist; it only nudges\n        // where the blobs are, so loud moments never throw them around.\n        const r = (spread + level * 0.03) * size * drift;\n        const x = Math.cos(angle * b.a) * r;\n        const y = Math.sin(angle * b.b) * r;\n        const s = 1 + level * (i % 2 ? 0.22 : 0.14);\n        el.style.transform = `translate(${x.toFixed(1)}px, ${y.toFixed(1)}px) scale(${s.toFixed(3)})`;\n      });\n      // The whole orb swells a touch with the voice; the rings carry the\n      // rest of it outward, the outer one lagging behind.\n      if (bodyRef.current)\n        bodyRef.current.style.transform = `scale(${(1 + level * 0.025 * drift).toFixed(3)})`;\n      ringRefs.current.forEach((ring, i) => {\n        if (!ring) return;\n        const grow = 1 + (0.06 + i * 0.07) + level * (0.05 + i * 0.06) * drift;\n        ring.style.transform = `scale(${grow.toFixed(3)})`;\n        ring.style.opacity = (0.35 + level * 0.5 - i * 0.12).toFixed(3);\n      });\n\n      frame = visible ? requestAnimationFrame(step) : 0;\n    };\n\n    // Sleeps offscreen, so a page full of other things never pays for it.\n    const io = new IntersectionObserver(([entry]) => {\n      visible = entry.isIntersecting;\n      if (visible && !frame) {\n        last = performance.now();\n        frame = requestAnimationFrame(step);\n      }\n    });\n    io.observe(root);\n    frame = requestAnimationFrame(step);\n    return () => {\n      cancelAnimationFrame(frame);\n      io.disconnect();\n    };\n  }, [paused, reduceMotion, size]);\n\n  const blob = size * 0.62;\n\n  return (\n    <div\n      ref={rootRef}\n      className={cn(\"relative grid place-items-center\", className)}\n      style={{ width: size * 1.5, height: size * 1.5 }}\n    >\n      {/* Two faint rings around the orb carry the voice outward. */}\n      {[0, 1].map((i) => (\n        <div\n          key={i}\n          ref={(el) => void (ringRefs.current[i] = el)}\n          aria-hidden\n          className=\"absolute rounded-full border border-foreground/10\"\n          style={{\n            width: size,\n            height: size,\n            transform: `scale(${1.06 + i * 0.07})`,\n            opacity: 0.35 - i * 0.12,\n          }}\n        />\n      ))}\n      <div\n        ref={bodyRef}\n        aria-hidden\n        className=\"relative overflow-hidden rounded-full bg-[light-dark(oklch(0.985_0.005_250),oklch(0.2_0.02_260))]\"\n        style={{ width: size, height: size }}\n      >\n        {/* The mist: soft blobs drifting on their own paths, blurred together\n            so they read as one moving light inside the glass. */}\n        <div className=\"absolute inset-0 blur-[14px]\">\n          {BLOBS.map((_, i) => (\n            <div\n              key={i}\n              ref={(el) => void (blobRefs.current[i] = el)}\n              className=\"absolute top-1/2 left-1/2 rounded-full\"\n              style={{\n                width: blob,\n                height: blob,\n                marginLeft: -blob / 2,\n                marginTop: -blob / 2,\n                background: `radial-gradient(circle, ${MIST[i]} 0%, transparent 68%)`,\n                opacity: i === 3 ? 0.7 : 0.9,\n              }}\n            />\n          ))}\n        </div>\n        {/* Glass: a lit upper edge, a darker lower one, and a soft\n            highlight, so it reads as a sphere, not a flat disc. */}\n        <div className=\"absolute inset-0 rounded-full shadow-[inset_0_2px_10px_oklch(1_0_0/0.55),inset_0_-14px_30px_oklch(0_0_0/0.06),inset_0_0_0_1px_oklch(0_0_0/0.05)] dark:shadow-[inset_0_2px_12px_oklch(1_0_0/0.12),inset_0_-14px_30px_oklch(0_0_0/0.35),inset_0_0_0_1px_oklch(1_0_0/0.08)]\" />\n        <div className=\"absolute top-[9%] left-[22%] h-[22%] w-[38%] rotate-[-18deg] rounded-full bg-[radial-gradient(closest-side,oklch(1_0_0/0.5),transparent)] dark:opacity-40\" />\n      </div>\n    </div>\n  );\n}\n\nexport function useMicrophone() {\n  const [mic, setMic] = useState<Mic | null>(null);\n  const [error, setError] = useState<string | null>(null);\n\n  const start = async () => {\n    if (mic) return mic;\n    try {\n      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });\n      const ctx = new AudioContext();\n      const analyser = ctx.createAnalyser();\n      analyser.fftSize = 1024;\n      ctx.createMediaStreamSource(stream).connect(analyser);\n      const next = { stream, ctx, analyser };\n      setMic(next);\n      setError(null);\n      return next;\n    } catch {\n      setError(\"Microphone is blocked, so this is a pretend room.\");\n      return null;\n    }\n  };\n\n  const stop = () => {\n    if (!mic) return;\n    mic.stream.getTracks().forEach((track) => track.stop());\n    void mic.ctx.close();\n    setMic(null);\n  };\n\n  // Never leaves the mic open behind a closed page.\n  const micRef = useRef(mic);\n  useEffect(() => {\n    micRef.current = mic;\n  });\n  useEffect(\n    () => () => {\n      const m = micRef.current;\n      m?.stream.getTracks().forEach((track) => track.stop());\n      void m?.ctx.close();\n    },\n    [],\n  );\n\n  return { mic, error, start, stop };\n}\n\nconst ACTIONS: { state: OrbState; label: string }[] = [\n  { state: \"listening\", label: \"Listen\" },\n  { state: \"thinking\", label: \"Think\" },\n  { state: \"speaking\", label: \"Speak\" },\n];\n\nexport default function VoiceOrbDemo() {\n  const play = usePreviewPlay();\n  const [state, setState] = useState<OrbState>(\"idle\");\n  const { mic, error, start, stop } = useMicrophone();\n\n  // In an index card, hovering acts out one exchange: a beat of thought,\n  // then an answer, then back to rest, on repeat.\n  useEffect(() => {\n    if (play !== true) return;\n    const script: [OrbState, number][] = [\n      [\"thinking\", 1100],\n      [\"speaking\", 2800],\n      [\"idle\", 900],\n    ];\n    let i = 0;\n    let timer: ReturnType<typeof setTimeout>;\n    const next = () => {\n      const [s, ms] = script[i % script.length];\n      setState(s);\n      i++;\n      timer = setTimeout(next, ms);\n    };\n    timer = setTimeout(next, 150);\n    // Unhovered: back to rest, through the orb's own easing.\n    return () => {\n      clearTimeout(timer);\n      setState(\"idle\");\n    };\n  }, [play]);\n\n  const choose = async (next: OrbState) => {\n    const leaving = state === next;\n    const target = leaving ? \"idle\" : next;\n    if (target === \"listening\") await start();\n    else stop();\n    setState(target);\n  };\n\n  return (\n    <div className=\"flex w-[min(360px,100%)] flex-col items-center\">\n      <VoiceOrb state={state} mic={mic} paused={play === false} />\n      <div className=\"-mt-6 grid h-6 place-items-center\">\n        <AnimatePresence initial={false} mode=\"popLayout\">\n          <motion.p\n            key={state}\n            aria-live=\"polite\"\n            initial={{ opacity: 0, y: 4, filter: \"blur(4px)\" }}\n            animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n            exit={{ opacity: 0, y: -4, filter: \"blur(4px)\", transition: { duration: 0.12 } }}\n            transition={{ duration: 0.22, ease: [0.23, 1, 0.32, 1] }}\n            className=\"col-start-1 row-start-1 text-[15px] text-muted-foreground\"\n          >\n            {LABELS[state]}\n          </motion.p>\n        </AnimatePresence>\n      </div>\n      <div className=\"mt-5 flex gap-2\">\n        {ACTIONS.map((a) => (\n          <button\n            key={a.state}\n            type=\"button\"\n            aria-pressed={state === a.state}\n            onClick={() => void choose(a.state)}\n            className={cn(\n              \"h-9 touch-manipulation rounded-full px-4 text-sm font-medium outline-hidden transition-[scale,background-color,color] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground active:scale-[0.96]\",\n              state === a.state\n                ? \"bg-foreground text-background\"\n                : \"bg-muted text-foreground hover:bg-foreground/10\",\n            )}\n          >\n            {a.label}\n          </button>\n        ))}\n      </div>\n      <p className=\"mt-3 h-4 text-xs text-muted-foreground\">\n        {state === \"listening\"\n          ? (error ?? (mic ? \"Using your mic. Nothing is recorded.\" : \"\"))\n          : \"\"}\n      </p>\n    </div>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"},{"path":"lib/preview-play.ts","type":"registry:lib","target":"lib/preview-play.ts","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n// Lets a demo know whether it's showing in an index card, and whether that\n// card is hovered or focused. Demos use it to act themselves out on hover:\n// a star button stars itself, a checkbox scribbles, and so on.\n//\n// null: not in a preview (the component's own page, or real use).\n// false: in a preview, at rest.\n// true: in a preview, being hovered or focused: play the show.\nexport const PreviewPlayContext = createContext<boolean | null>(null);\n\nexport function usePreviewPlay() {\n  return useContext(PreviewPlayContext);\n}\n"}],"categories":["cards"],"docs":"From ui lab: https://lab.xevrion.dev/lab/voice-orb"}