{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "voice-05",
  "title": "Sound ring",
  "description": "A ring of rounded bars in three sizes where a peak travels round the ring and turns faster with the sound, quiet when idle, sitting beside a label, inside a button or alone.",
  "dependencies": [
    "motion"
  ],
  "registryDependencies": [
    "https://ui.ndekocode.dev/r/button.json",
    "https://ui.ndekocode.dev/r/demonstration.json",
    "https://ui.ndekocode.dev/r/live-region.json",
    "https://ui.ndekocode.dev/r/motion-word-roll.json",
    "https://ui.ndekocode.dev/r/speech-envelope.json",
    "https://ui.ndekocode.dev/r/theme.json",
    "https://ui.ndekocode.dev/r/use-agent-run.json",
    "https://ui.ndekocode.dev/r/use-autoplay.json",
    "https://ui.ndekocode.dev/r/use-kept-height.json",
    "https://ui.ndekocode.dev/r/use-prefers-reduced-motion.json",
    "https://ui.ndekocode.dev/r/utils.json"
  ],
  "files": [
    {
      "path": "registry/ndeko/components/voice/voice-05.tsx",
      "content": "'use client';\n\nimport { useState } from 'react';\n\nimport { WordRoll } from '@/components/core/word-roll';\nimport {\n  useAutoplay,\n  type AutoplayStep,\n} from '@/registry/ndeko/hooks/use-autoplay';\nimport { useKeptHeight } from '@/registry/ndeko/hooks/use-kept-height';\nimport {\n  hold,\n  PRESS_LEAD_MS,\n  pressedQuietOf,\n  spokenUnless,\n  usePress,\n} from '@/registry/ndeko/lib/demonstration';\nimport { cn } from '@/registry/ndeko/lib/utils';\nimport { Button } from '@/registry/ndeko/ui/button';\nimport { LiveRegion } from '@/registry/ndeko/ui/live-region';\n\nimport {\n  restStyleOf,\n  RING_SPEC,\n  stillStyleOf,\n  type RingSpec,\n  type SoundRingSize,\n} from './_parts/ring-geometry';\nimport { usePlayWhileSeen } from './_parts/use-play-while-seen';\nimport { useRingMotion } from './_parts/use-ring-motion';\n\nexport type { SoundRingSize } from './_parts/ring-geometry';\n\nfunction accessibilityOf(label: string | undefined) {\n  if (label === undefined) {\n    return { 'aria-hidden': true } as const;\n  }\n  return { role: 'img', 'aria-label': label } as const;\n}\n\nfunction barStyleOf(index: number, spec: RingSpec, showsStill: boolean) {\n  if (showsStill) {\n    return stillStyleOf(index, spec);\n  }\n  return restStyleOf(index, spec);\n}\n\nexport type SoundRingProps = {\n  /** While false the ring is quiet: its bars rest and nothing runs. */\n  isActive: boolean;\n  /** The live level of the sound, between 0 and 1, read about eight times a second: the louder it is, the faster the peak turns. Left out, a simulated voice drives the ring. */\n  level?: () => number;\n  /** `sm` is 20px and sits beside a label, `md` is 40px and fits a button, `lg` is 96px and stands alone. */\n  size?: SoundRingSize;\n  /** Names the ring for screen readers when it stands alone. Left out, it is decorative. */\n  label?: string;\n  className?: string;\n};\n\nexport function SoundRing({\n  isActive,\n  level,\n  size = 'md',\n  label,\n  className,\n}: SoundRingProps) {\n  const spec = RING_SPEC[size];\n  const { ref, isOnScreen, isStill } = usePlayWhileSeen<HTMLSpanElement>();\n  const showsStill = isActive && isStill;\n  const accessibility = accessibilityOf(label);\n  const indexes = Array.from({ length: spec.bars }, (_, index) => index);\n\n  useRingMotion(ref, { spec, isActive, isStill, isOnScreen, level });\n\n  return (\n    <span\n      ref={ref}\n      {...accessibility}\n      style={{ width: spec.px, height: spec.px }}\n      className={cn('text-primary relative inline-block shrink-0', className)}\n    >\n      {indexes.map((index) => (\n        <span\n          key={index}\n          data-bar=''\n          style={barStyleOf(index, spec, showsStill)}\n          className='absolute bottom-1/2 left-1/2 origin-bottom rounded-full bg-current transition-[transform,opacity] duration-300 ease-(--ease-out-strong)'\n        />\n      ))}\n    </span>\n  );\n}\n\nconst STATE_WORDS = ['Idle', 'Listening'];\n\nfunction stateWordOf(isActive: boolean) {\n  if (isActive) {\n    return 'Listening';\n  }\n  return 'Idle';\n}\n\nexport default function Voice05() {\n  const [isActive, setIsActive] = useState(true);\n  const { pressed, press } = usePress<'listen'>();\n  const stateWord = stateWordOf(isActive);\n\n  function toggle() {\n    setIsActive((current) => !current);\n  }\n\n  function goQuiet() {\n    setIsActive(false);\n  }\n\n  function goActive() {\n    setIsActive(true);\n  }\n\n  const steps: AutoplayStep[] = [\n    { after: 5200, run: () => press('listen') },\n    { after: PRESS_LEAD_MS, run: goQuiet },\n    { after: 2200, run: () => press('listen') },\n    { after: PRESS_LEAD_MS, run: goActive },\n    { after: 2600, run: hold },\n  ];\n  const { ref, isAutoplaying } = useAutoplay(steps, {\n    loopAfter: 600,\n    onReset: goActive,\n  });\n\n  useKeptHeight(ref);\n\n  return (\n    <div\n      ref={ref}\n      className='flex w-full max-w-[22rem] flex-col items-center gap-4'\n    >\n      <div className='bg-card hairline-ring ring-border flex w-full flex-col items-center gap-6 rounded-xl px-4 py-6 shadow-[0_1px_2px_rgb(0_0_0/0.04)]'>\n        <SoundRing size='lg' isActive={isActive} label={stateWord} />\n        <div className='flex w-full items-center justify-between gap-3'>\n          <p className='flex min-w-0 items-center gap-2 text-[13px] font-medium'>\n            <SoundRing size='sm' isActive={isActive} />\n            <WordRoll text={stateWord} labels={STATE_WORDS} />\n          </p>\n          <Button\n            type='button'\n            variant='outline'\n            aria-label='Listen'\n            aria-pressed={isActive}\n            onClick={toggle}\n            className={cn('size-14 p-0', pressedQuietOf(pressed === 'listen'))}\n          >\n            <SoundRing size='md' isActive={isActive} />\n          </Button>\n        </div>\n      </div>\n      <LiveRegion message={spokenUnless(isAutoplaying, stateWord)} />\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/voice/voice-05.tsx"
    },
    {
      "path": "registry/ndeko/components/voice/_parts/level.ts",
      "content": "const ATTACK_S = 0.04;\n\nconst RELEASE_S = 0.2;\n\n/** Rises fast and falls slowly, whatever the frame rate. */\nexport function followLevel(current: number, target: number, step: number) {\n  const gap = target - current;\n  const isRising = gap > 0;\n  let constant = RELEASE_S;\n  if (isRising) {\n    constant = ATTACK_S;\n  }\n  const amount = 1 - Math.exp(-step / constant);\n  return current + gap * amount;\n}\n",
      "type": "registry:component",
      "target": "components/voice/_parts/level.ts"
    },
    {
      "path": "registry/ndeko/components/voice/_parts/ring-geometry.ts",
      "content": "import type { CSSProperties } from 'react';\n\nexport type SoundRingSize = 'sm' | 'md' | 'lg';\n\nexport type RingSpec = {\n  px: number;\n  bars: number;\n  inner: number;\n  length: number;\n  width: number;\n};\n\n/** A bar at full scale ends at the edge of the square: inner plus length is half of it. */\nexport const RING_SPEC: Record<SoundRingSize, RingSpec> = {\n  sm: { px: 20, bars: 24, inner: 6, length: 4, width: 1 },\n  md: { px: 40, bars: 24, inner: 12, length: 8, width: 2 },\n  lg: { px: 96, bars: 32, inner: 28.8, length: 19.2, width: 4 },\n};\n\n/** One turn of the peak round the ring at its base speed: the level makes it shorter or longer. */\nexport const LAP_MS = 1800;\n\nconst REST_SCALE = 0.22;\n\nconst REST_OPACITY = 0.32;\n\n/** A peak is a smooth hump that falls to nothing this many bars away on each side. */\nconst REACH_BARS = 5;\n\nconst PEAK_LIFT = 0.88;\n\nconst ECHO_LIFT = 0.36;\n\n/** The echo comes half a lap after the peak, straight across the ring. */\nconst ECHO_SHARE_OF_LAP = 0.5;\n\n/** Under reduced motion the peak stands this share of the ring clockwise from the top. */\nconst STILL_PEAK_SHARE = 0.15;\n\nfunction wrappedGap(first: number, second: number, bars: number) {\n  const difference = Math.abs(first - second);\n  const gap = difference % bars;\n  const other = bars - gap;\n  return Math.min(gap, other);\n}\n\nfunction humpOf(distance: number) {\n  if (distance >= REACH_BARS) {\n    return 0;\n  }\n  const share = distance / REACH_BARS;\n  const angle = Math.PI * share;\n  const cosine = Math.cos(angle);\n  const lifted = 1 + cosine;\n  return lifted / 2;\n}\n\n/**\n * How high a bar stands, from 0 at rest to 1 at full height, at a place of its lap counted in bars.\n * A lap starts at rest, so a bar that has not begun its lap yet is already in the right pose.\n */\nfunction liftAt(place: number, bars: number) {\n  const echoOffset = bars * ECHO_SHARE_OF_LAP;\n  const echoCenter = REACH_BARS + echoOffset;\n  const peakGap = wrappedGap(place, REACH_BARS, bars);\n  const echoGap = wrappedGap(place, echoCenter, bars);\n  const peakHump = humpOf(peakGap);\n  const echoHump = humpOf(echoGap);\n  const peak = PEAK_LIFT * peakHump;\n  const echo = ECHO_LIFT * echoHump;\n  const total = peak + echo;\n  return Math.min(1, total);\n}\n\nfunction roundedTo(value: number, digits: number) {\n  const factor = 10 ** digits;\n  const scaled = value * factor;\n  const rounded = Math.round(scaled);\n  return rounded / factor;\n}\n\nfunction liftedFrom(rest: number, lift: number) {\n  const span = 1 - rest;\n  const climb = span * lift;\n  return rest + climb;\n}\n\ntype BarPose = {\n  transform: string;\n  opacity: number;\n};\n\nfunction poseOf(spec: RingSpec, lift: number): BarPose {\n  const scale = liftedFrom(REST_SCALE, lift);\n  const opacity = liftedFrom(REST_OPACITY, lift);\n  const scaleText = roundedTo(scale, 3);\n  const shownOpacity = roundedTo(opacity, 3);\n  const transform = `translateY(-${spec.inner}px) scaleY(${scaleText})`;\n  return { transform, opacity: shownOpacity };\n}\n\nfunction lapLiftsOf(bars: number) {\n  const lifts: number[] = [];\n  for (let knot = 0; knot <= bars; knot += 1) {\n    lifts.push(liftAt(knot, bars));\n  }\n  return lifts;\n}\n\nfunction isNeededKnot(lifts: number[], knot: number) {\n  const isEdge = knot === 0 || knot === lifts.length - 1;\n  const isLifted = lifts[knot] > 0;\n  const followsLift = lifts[knot - 1] > 0;\n  const precedesLift = lifts[knot + 1] > 0;\n  return isEdge || isLifted || followsLift || precedesLift;\n}\n\n/**\n * The lap of one bar, shared by every bar of the ring: a knot per bar along the lap, where the\n * stretches of rest between the two humps need no knot of their own.\n */\nexport function lapKeyframesOf(spec: RingSpec) {\n  const lifts = lapLiftsOf(spec.bars);\n  const keyframes: Keyframe[] = [];\n  for (let knot = 0; knot < lifts.length; knot += 1) {\n    if (!isNeededKnot(lifts, knot)) {\n      continue;\n    }\n    const pose = poseOf(spec, lifts[knot]);\n    const offset = knot / spec.bars;\n    keyframes.push({ offset, ...pose });\n  }\n  return keyframes;\n}\n\n/** Each bar starts its lap a bar later than the one before it, so the peak turns clockwise. */\nexport function lapDelayOf(index: number, bars: number) {\n  const share = index / bars;\n  return share * LAP_MS;\n}\n\nfunction barStyleOf(\n  index: number,\n  spec: RingSpec,\n  lift: number\n): CSSProperties {\n  const share = index / spec.bars;\n  const degrees = share * 360;\n  const halfWidth = spec.width / 2;\n  const pose = poseOf(spec, lift);\n  return {\n    width: spec.width,\n    height: spec.length,\n    marginLeft: -halfWidth,\n    rotate: `${degrees}deg`,\n    transform: pose.transform,\n    opacity: pose.opacity,\n  };\n}\n\nexport function restStyleOf(index: number, spec: RingSpec) {\n  return barStyleOf(index, spec, 0);\n}\n\nfunction stillLiftOf(index: number, bars: number) {\n  const peakBar = STILL_PEAK_SHARE * bars;\n  const fromPeak = index - peakBar;\n  const place = REACH_BARS - fromPeak;\n  return liftAt(place, bars);\n}\n\n/** The pose of a bar under reduced motion: the ring stands on one frame of its lap and stays there. */\nexport function stillStyleOf(index: number, spec: RingSpec) {\n  const lift = stillLiftOf(index, spec.bars);\n  return barStyleOf(index, spec, lift);\n}\n",
      "type": "registry:component",
      "target": "components/voice/_parts/ring-geometry.ts"
    },
    {
      "path": "registry/ndeko/components/voice/_parts/ring-loops.ts",
      "content": "import {\n  LAP_MS,\n  lapDelayOf,\n  lapKeyframesOf,\n  type RingSpec,\n} from './ring-geometry';\nimport { BASE_PACE, rateOf } from './ring-pace';\n\nconst LAND_MS = 300;\n\nconst LAND_EASING = 'cubic-bezier(0.23, 1, 0.32, 1)';\n\nconst LAND_TIMING: KeyframeAnimationOptions = {\n  duration: LAND_MS,\n  easing: LAND_EASING,\n};\n\nexport type RingLoops = {\n  animations: Animation[];\n  pace: number;\n};\n\nfunction barsOf(root: HTMLElement) {\n  return Array.from(root.querySelectorAll('[data-bar]'));\n}\n\n/**\n * One animation per bar on transform and opacity, all with the same keyframes: the browser's own\n * animation engine plays them, so the page does no work per frame.\n */\nexport function startRingLoops(root: HTMLElement, spec: RingSpec): RingLoops {\n  const keyframes = lapKeyframesOf(spec);\n  const bars = barsOf(root);\n  const animations = bars.map((bar, index) => {\n    const delay = lapDelayOf(index, spec.bars);\n    return bar.animate(keyframes, {\n      duration: LAP_MS,\n      delay,\n      iterations: Infinity,\n    });\n  });\n  return { animations, pace: BASE_PACE };\n}\n\n/** Every bar changes speed in the same task, so the peak keeps its shape while the lap gets faster or slower. */\nexport function setLapPace(loops: RingLoops, pace: number) {\n  if (pace === loops.pace) {\n    return;\n  }\n  loops.pace = pace;\n  const rate = rateOf(pace);\n  for (const animation of loops.animations) {\n    animation.updatePlaybackRate(rate);\n  }\n}\n\n/**\n * A cancelled animation is left alone: playing or even pausing it would bring it back and hold its\n * bar in a pose its ring has already left.\n */\nfunction isCancelled(animation: Animation) {\n  return animation.playState === 'idle';\n}\n\nexport function playAll(animations: readonly Animation[]) {\n  for (const animation of animations) {\n    if (!isCancelled(animation)) {\n      animation.play();\n    }\n  }\n}\n\nexport function pauseAll(animations: readonly Animation[]) {\n  for (const animation of animations) {\n    if (!isCancelled(animation)) {\n      animation.pause();\n    }\n  }\n}\n\nexport function cancelAll(animations: readonly Animation[]) {\n  for (const animation of animations) {\n    animation.cancel();\n  }\n}\n\ntype Pose = {\n  transform: string;\n  opacity: string;\n};\n\ntype Landing = {\n  target: Element;\n  shown: Pose;\n};\n\nfunction targetOf(animation: Animation) {\n  const effect = animation.effect;\n  if (effect instanceof KeyframeEffect) {\n    return effect.target;\n  }\n  return null;\n}\n\nfunction poseOf(element: Element): Pose {\n  const styles = getComputedStyle(element);\n  return { transform: styles.transform, opacity: styles.opacity };\n}\n\nfunction landingsOf(animations: readonly Animation[]) {\n  const landings: Landing[] = [];\n  for (const animation of animations) {\n    const target = targetOf(animation);\n    if (target?.isConnected) {\n      const shown = poseOf(target);\n      landings.push({ target, shown });\n    }\n  }\n  return landings;\n}\n\n/**\n * From the pose its lap left it in, each bar glides back to its resting style, then lets go. The\n * poses are read together, then the laps are dropped, then the resting poses are read together,\n * so the page restyles twice whatever the number of bars.\n */\nexport function landAll(animations: readonly Animation[]) {\n  const landings = landingsOf(animations);\n  cancelAll(animations);\n  const rests = landings.map((landing) => poseOf(landing.target));\n  landings.forEach((landing, index) => {\n    const keyframes = [landing.shown, rests[index]];\n    landing.target.animate(keyframes, LAND_TIMING);\n  });\n}\n",
      "type": "registry:component",
      "target": "components/voice/_parts/ring-loops.ts"
    },
    {
      "path": "registry/ndeko/components/voice/_parts/ring-pace.ts",
      "content": "import { speechLevelAt } from '@/registry/ndeko/lib/speech-envelope';\n\n/** The lap is never retimed more often than this: every retiming asks the browser to restart each bar's animation. */\nexport const POLL_MS = 125;\n\nexport const POLL_S = POLL_MS / 1000;\n\n/** Until the first reading the lap runs at its base speed. */\nexport const BASE_PACE = 10;\n\nexport const START_LEVEL = 0.3;\n\nconst TENTHS = 10;\n\n/** A pace counts tenths of the base speed: 0.6x when quiet, 2.2x at full level. */\nconst SLOWEST_PACE = 6;\n\nconst FASTEST_PACE = 22;\n\nconst HEARD_SEED = 0.9;\n\nconst WINDOW_SAMPLES = 4;\n\nconst SIMULATED_GAIN = 1.3;\n\nexport function rateOf(pace: number) {\n  return pace / TENTHS;\n}\n\nexport function paceOf(level: number) {\n  const span = FASTEST_PACE - SLOWEST_PACE;\n  const climb = span * level;\n  const exact = SLOWEST_PACE + climb;\n  return Math.round(exact);\n}\n\nfunction boundedLevelOf(value: number) {\n  if (!Number.isFinite(value)) {\n    return 0;\n  }\n  const atLeastZero = Math.max(0, value);\n  return Math.min(1, atLeastZero);\n}\n\n/** The mean over the last poll: a syllable lasts about as long as one poll, so a single sample would catch it at random. */\nfunction simulatedLevelAt(elapsed: number) {\n  let total = 0;\n  for (let sample = 0; sample < WINDOW_SAMPLES; sample += 1) {\n    const share = sample / WINDOW_SAMPLES;\n    const age = share * POLL_MS;\n    const time = elapsed - age;\n    total += speechLevelAt(time, HEARD_SEED);\n  }\n  const mean = total / WINDOW_SAMPLES;\n  const gained = mean * SIMULATED_GAIN;\n  return Math.min(1, gained);\n}\n\nexport function heardLevelOf(\n  provider: (() => number) | undefined,\n  elapsed: number\n) {\n  if (provider) {\n    const heard = provider();\n    return boundedLevelOf(heard);\n  }\n  return simulatedLevelAt(elapsed);\n}\n",
      "type": "registry:component",
      "target": "components/voice/_parts/ring-pace.ts"
    },
    {
      "path": "registry/ndeko/components/voice/_parts/use-play-while-seen.ts",
      "content": "'use client';\n\nimport { useInView } from 'motion/react';\nimport { useRef } from 'react';\n\nimport { useDocumentVisible } from '@/registry/ndeko/hooks/use-agent-run';\nimport { usePrefersReducedMotion } from '@/registry/ndeko/hooks/use-prefers-reduced-motion';\n\nconst IN_VIEW_SHARE = 0.2;\n\n/**\n * A voice indicator moves only while someone can see it: on screen, in the tab that is shown,\n * without reduced motion. `isStill` asks for the still frame instead, and `isOnScreen` is for the\n * clocks that keep a session going under reduced motion.\n */\nexport function usePlayWhileSeen<Element extends HTMLElement = HTMLElement>() {\n  const ref = useRef<Element>(null);\n  const isInView = useInView(ref, { amount: IN_VIEW_SHARE });\n  const isTabVisible = useDocumentVisible();\n  const isStill = usePrefersReducedMotion();\n  const isOnScreen = isInView && isTabVisible;\n  const isPlaying = isOnScreen && !isStill;\n\n  return { ref, isOnScreen, isPlaying, isStill };\n}\n",
      "type": "registry:component",
      "target": "components/voice/_parts/use-play-while-seen.ts"
    },
    {
      "path": "registry/ndeko/components/voice/_parts/use-ring-motion.ts",
      "content": "'use client';\n\nimport { useEffect, useEffectEvent, useRef, type RefObject } from 'react';\n\nimport { followLevel } from './level';\nimport type { RingSpec } from './ring-geometry';\nimport {\n  cancelAll,\n  landAll,\n  pauseAll,\n  playAll,\n  setLapPace,\n  startRingLoops,\n  type RingLoops,\n} from './ring-loops';\nimport {\n  heardLevelOf,\n  paceOf,\n  POLL_MS,\n  POLL_S,\n  START_LEVEL,\n} from './ring-pace';\n\ntype RingMotionOptions = {\n  spec: RingSpec;\n  isActive: boolean;\n  isStill: boolean;\n  isOnScreen: boolean;\n  level: (() => number) | undefined;\n};\n\n/**\n * The animations of a ring are made when it becomes active and paused whenever it is not seen, so\n * they ask for no frame off screen or in a hidden tab. While it is seen a timer reads the level a\n * few times a second and retimes the lap. When the ring goes quiet each bar glides back to rest and\n * the animations are gone. Under reduced motion none are made.\n */\nexport function useRingMotion(\n  rootRef: RefObject<HTMLElement | null>,\n  { spec, isActive, isStill, isOnScreen, level }: RingMotionOptions\n) {\n  const running = useRef<RingLoops | null>(null);\n  const canLoop = isActive && !isStill;\n  const isLive = canLoop && isOnScreen;\n\n  const levelAt = useEffectEvent((elapsed: number) => {\n    return heardLevelOf(level, elapsed);\n  });\n\n  /** Stopped by the reduced motion setting, a ring goes straight to rest instead of gliding there. */\n  const finish = useEffectEvent(\n    (animations: Animation[], root: HTMLElement) => {\n      const canGlide = root.isConnected && !isStill;\n      if (canGlide) {\n        landAll(animations);\n        return;\n      }\n      cancelAll(animations);\n    }\n  );\n\n  useEffect(() => {\n    const root = rootRef.current;\n    if (!root || !canLoop) {\n      return;\n    }\n    const loops = startRingLoops(root, spec);\n    pauseAll(loops.animations);\n    running.current = loops;\n    return () => {\n      running.current = null;\n      finish(loops.animations, root);\n    };\n  }, [rootRef, canLoop, spec]);\n\n  useEffect(() => {\n    const loops = running.current;\n    if (!loops || !isLive) {\n      return;\n    }\n    playAll(loops.animations);\n    return () => pauseAll(loops.animations);\n  }, [canLoop, isLive, spec]);\n\n  useEffect(() => {\n    if (!isLive) {\n      return;\n    }\n    const startedAt = performance.now();\n    let followed = START_LEVEL;\n\n    function retime() {\n      const loops = running.current;\n      if (!loops) {\n        return;\n      }\n      const now = performance.now();\n      const elapsed = now - startedAt;\n      const heard = levelAt(elapsed);\n      followed = followLevel(followed, heard, POLL_S);\n      const pace = paceOf(followed);\n      setLapPace(loops, pace);\n    }\n\n    const timer = setInterval(retime, POLL_MS);\n    return () => clearInterval(timer);\n  }, [isLive]);\n}\n",
      "type": "registry:component",
      "target": "components/voice/_parts/use-ring-motion.ts"
    }
  ],
  "categories": [
    "components",
    "voice"
  ],
  "type": "registry:component"
}