{"slug":"cylinder-carousel","name":"Cylinder Carousel","description":"A carousel whose items line the inside of a cylinder, receding into the center and growing toward the edges. Drag, scroll or arrow-key to roll it, with a springy glide and snap. Reduced-motion drops the glide.","category":"motion","source_url":"https://beui.dev/r/cylinder-carousel/raw","detail_url":"https://beui.dev/r/cylinder-carousel","raw_url":"https://beui.dev/r/cylinder-carousel/raw","page_url":"https://beui.dev/components/motion/cylinder-carousel","markdown_url":"https://beui.dev/components/motion/cylinder-carousel.md","published_at":"2026-07-04","updated_at":"2026-11-25","dependencies":["@paper-design/shaders-react","clsx","lucide-react","motion","react","tailwind-merge"],"internal":["./engine","@/components/motion/cylinder-carousel","@/components/motion/shader-background","@/components/motion/tabs","@/lib/audio-context","@/lib/ease","@/lib/i18n","@/lib/sound","@/lib/sounds/engine","@/lib/sounds/select","@/lib/touch","@/lib/utils"],"install_slugs":["cylinder-carousel"],"requires_theme":true,"props":[{"displayName":"CylinderCarousel","props":[{"name":"itemSize","type":"number","required":false,"defaultValue":"200","description":"Max item box size in px (square) at full size, i.e. at the container\nedge. Balls shrink below this automatically so the row keeps breathing\nroom in narrow containers."},{"name":"visibleItems","type":"number","required":false,"defaultValue":"5","description":"How many item slots span the container width."},{"name":"variant","type":"\"concave\" | \"convex\"","required":false,"defaultValue":"concave","description":"\"concave\" (default): inside of the cylinder - center ball smallest and\ndipped, growing toward the edges. \"convex\": outside of the cylinder -\ncenter ball biggest and raised, shrinking toward the edges."},{"name":"minScale","type":"number","required":false,"defaultValue":"0.55","description":"Scale of the smallest ball (center for concave, edges for convex);\nthe biggest reaches 1."},{"name":"dragSpeed","type":"number","required":false,"defaultValue":"1.5","description":"Items rolled per item-width dragged - above 1 the wall outruns the\npointer, which reads as a lighter, freer roll."},{"name":"arc","type":"number","required":false,"defaultValue":null,"description":"Curve depth in px: for concave, how far the edge balls ride above the\ncenter one (valley); for convex, how far below (arch). 0 = flat line.\nDefaults to 35% of the item size."},{"name":"snap","type":"boolean","required":false,"defaultValue":"true","description":"Snap to the nearest item when the roll settles."},{"name":"autoRotate","type":"boolean","required":false,"defaultValue":"false","description":"Roll on its own until interacted with."},{"name":"autoRotateSpeed","type":"number","required":false,"defaultValue":"0.4","description":"Auto-roll speed in items per second."},{"name":"defaultIndex","type":"number","required":false,"defaultValue":"0","description":"Zero-based index of the item centered at first. Default: 0"},{"name":"onIndexChange","type":"((index: number) => void)","required":false,"defaultValue":null,"description":"Called with the zero-based index when a new item reaches the center."},{"name":"height","type":"number","required":false,"defaultValue":null,"description":"Stage height in px. Defaults to `itemSize`."},{"name":"labels","type":"Partial<{ roleDescription: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]}],"types":[],"files":[{"path":"components/motion/cylinder-carousel.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/motion/cylinder-carousel\n\nimport {\n  animate,\n  type AnimationPlaybackControls,\n  motion,\n  type MotionValue,\n  useMotionValue,\n  useReducedMotion,\n  useTransform,\n} from \"motion/react\";\nimport {\n  Children,\n  type PointerEvent as ReactPointerEvent,\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useRef,\n  useState,\n  type WheelEvent as ReactWheelEvent,\n} from \"react\";\nimport {\n  capturePointer,\n  releasePointer,\n  TOUCH_GESTURE_CLASS,\n} from \"@/lib/touch\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const cylinderCarouselMessages = {\n  roleDescription: \"carousel\",\n};\n\nexport type CylinderCarouselMessages = typeof cylinderCarouselMessages;\n\n// Carousel-specific: a soft spring that receives the release velocity, so a\n// flick keeps rolling freely, drifts past the snap point and eases back.\nconst GLIDE_SPRING = { stiffness: 40, damping: 20, mass: 3 };\n\n// How far a flick keeps rolling: projected items = release velocity * momentum.\nconst FLICK_MOMENTUM = 0.45;\nconst MAX_FLICK_ITEMS = 6;\n\nexport interface CylinderCarouselProps {\n  children: ReactNode;\n  /** Max item box size in px (square) at full size, i.e. at the container\n   * edge. Balls shrink below this automatically so the row keeps breathing\n   * room in narrow containers. */\n  itemSize?: number;\n  /** How many item slots span the container width. */\n  visibleItems?: number;\n  /** \"concave\" (default): inside of the cylinder - center ball smallest and\n   * dipped, growing toward the edges. \"convex\": outside of the cylinder -\n   * center ball biggest and raised, shrinking toward the edges. */\n  variant?: \"concave\" | \"convex\";\n  /** Scale of the smallest ball (center for concave, edges for convex);\n   * the biggest reaches 1. */\n  minScale?: number;\n  /** Items rolled per item-width dragged - above 1 the wall outruns the\n   * pointer, which reads as a lighter, freer roll. */\n  dragSpeed?: number;\n  /** Curve depth in px: for concave, how far the edge balls ride above the\n   * center one (valley); for convex, how far below (arch). 0 = flat line.\n   * Defaults to 35% of the item size. */\n  arc?: number;\n  /** Snap to the nearest item when the roll settles. */\n  snap?: boolean;\n  /** Roll on its own until interacted with. */\n  autoRotate?: boolean;\n  /** Auto-roll speed in items per second. */\n  autoRotateSpeed?: number;\n  /** Zero-based index of the item centered at first. Default: 0 */\n  defaultIndex?: number;\n  /** Called with the zero-based index when a new item reaches the center. */\n  onIndexChange?: (index: number) => void;\n  /** Stage height in px. Defaults to `itemSize`. */\n  height?: number;\n  /** Override any built-in string. */\n  labels?: Partial<CylinderCarouselMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\n// The frame edge sits at this wall angle; how far the wall curves in frame.\nconst THETA_EDGE = (72 * Math.PI) / 180;\n// Wall angle past which a ball is parked far off-stage (always hidden there).\nconst THETA_CLAMP = (95 * Math.PI) / 180;\n\n/**\n * One ball on the inside wall of the cylinder, rendered through a single\n * perspective projection: the ball sits at wall angle θ, the camera slightly\n * above the ball line, so horizontal position, size and height all share one\n * 1/(cosθ + k) depth term. Center = far wall: smallest, highest, moving\n * slowest; edges = nearest: full size, level, moving fastest, sliding off to\n * be clipped. Nothing overlaps, fades or reorders - the edge is the exit.\n */\nfunction CarouselBall({\n  scroll,\n  index,\n  count,\n  alpha,\n  k,\n  projection,\n  gap,\n  edgeOffset,\n  minScale,\n  convex,\n  arc,\n  halfWidth,\n  itemSize,\n  children,\n}: {\n  scroll: MotionValue<number>;\n  index: number;\n  count: number;\n  /** Wall angle per item step, in radians. */\n  alpha: number;\n  /** Camera distance term for the horizontal projection. */\n  k: number;\n  /** Projection strength: maps sinθ/(cosθ+k) to px so θE lands on the edge. */\n  projection: number;\n  /** Uniform slot width in px - convex spacing. */\n  gap: number;\n  /** Offset at which a ball's center sits on the container edge. */\n  edgeOffset: number;\n  minScale: number;\n  convex: boolean;\n  /** Curve depth in px between the center ball and the edge balls. */\n  arc: number;\n  halfWidth: number;\n  itemSize: number;\n  children: ReactNode;\n}) {\n  // Nearest wrapped offset so items loop around continuously.\n  const offset = useTransform(scroll, (s) => {\n    let o = index - s;\n    o -= Math.round(o / count) * count;\n    return o;\n  });\n  // Concave spacing follows the interior perspective (slow, tight center);\n  // convex pairs its big center balls with uniform spacing - the interior\n  // projection would collapse them into each other.\n  const x = useTransform(offset, (o) => {\n    if (convex) return o * gap;\n    const th = Math.max(-THETA_CLAMP, Math.min(THETA_CLAMP, o * alpha));\n    return (projection * Math.sin(th)) / (Math.cos(th) + k);\n  });\n  // Linear in wall angle, not in depth (the depth curve is near-flat around\n  // the center, which made the middle three read as equal): every step is\n  // visibly bigger than the last - growing outward (concave) or inward\n  // (convex).\n  const scale = useTransform(offset, (o) => {\n    const t = Math.min(Math.abs(o) / edgeOffset, THETA_CLAMP / THETA_EDGE);\n    return convex\n      ? 1 - (1 - minScale) * t\n      : minScale + (1 - minScale) * t;\n  });\n  // Parabola centered on the stage - valley for concave (center ball dips\n  // arc/2 below the midline, edges rise arc/2 above), arch for convex - and\n  // deliberately unclamped: a ball keeps following the same curve as it\n  // crosses the edge, so entries never pop.\n  const y = useTransform(x, (px) => {\n    const t = px / halfWidth;\n    const valley = arc * (0.5 - t * t);\n    return convex ? -valley : valley;\n  });\n  // Fully off-stage balls stop painting (matters for canvas/shader children).\n  const visibility = useTransform(x, (px) =>\n    Math.abs(px) > halfWidth + itemSize ? \"hidden\" : \"visible\",\n  );\n\n  return (\n    <motion.div\n      className=\"absolute top-1/2 left-1/2\"\n      style={{\n        x,\n        y,\n        scale,\n        visibility,\n        width: itemSize,\n        height: itemSize,\n        marginLeft: -itemSize / 2,\n        marginTop: -itemSize / 2,\n      }}\n    >\n      {children}\n    </motion.div>\n  );\n}\n\nexport function CylinderCarousel({\n  children,\n  itemSize = 200,\n  visibleItems = 5,\n  variant = \"concave\",\n  minScale = 0.55,\n  dragSpeed = 1.5,\n  arc: arcProp,\n  snap = true,\n  autoRotate = false,\n  autoRotateSpeed = 0.4,\n  defaultIndex = 0,\n  onIndexChange,\n  height,\n  labels,\n  className,\n}: CylinderCarouselProps) {\n  const reduce = useReducedMotion() ?? false;\n  const t = useMessages(\"cylinderCarousel\", cylinderCarouselMessages, labels);\n  const items = Children.toArray(children);\n  const count = items.length;\n\n  const stageRef = useRef<HTMLDivElement>(null);\n  const [width, setWidth] = useState(0);\n  useEffect(() => {\n    const el = stageRef.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) => {\n      setWidth(entry.contentRect.width);\n    });\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n  // Sized so `visibleItems` balls sit fully in frame and the next one out on\n  // each side straddles the container edge, half visible.\n  const stageWidth = width || 800;\n  const halfWidth = stageWidth / 2;\n  const edgeOffset = (visibleItems + 1) / 2;\n\n  // Fit: the resting row's diameters may take at most ~66% of the stage - the\n  // rest is air between balls plus the half-visible ball on each edge.\n  // `itemSize` only caps the result.\n  const convex = variant === \"convex\";\n  let scaleSum = 0;\n  for (let i = 0; i < visibleItems; i++) {\n    const t = Math.abs(i - (visibleItems - 1) / 2) / edgeOffset;\n    scaleSum += convex\n      ? 1 - (1 - minScale) * t\n      : minScale + (1 - minScale) * t;\n  }\n  const size = Math.min(itemSize, (stageWidth * 0.65) / scaleSum);\n\n  const gap = stageWidth / (visibleItems + 1);\n  const arc = arcProp ?? size * 0.35;\n\n  // Perspective constants. The ball one slot past the frame edge sits at wall\n  // angle THETA_EDGE with its center right on the container edge - scale 1,\n  // half of it in view; k falls out of the requested minScale (clamped so the\n  // projection stays monotonic up to THETA_CLAMP).\n  const alpha = THETA_EDGE / edgeOffset;\n  const k = Math.max(0.2, (minScale - Math.cos(THETA_EDGE)) / (1 - minScale));\n  const projection =\n    (halfWidth * (Math.cos(THETA_EDGE) + k)) / Math.sin(THETA_EDGE);\n\n  // scroll is in item units (continuous); item i sits at x = (i - scroll) * gap.\n  // Drags write it 1:1 so the wall sticks to the pointer; releases hand the\n  // pointer velocity to a soft spring so the roll glides on and settles free.\n  const scroll = useMotionValue(defaultIndex);\n  const indexRef = useRef(defaultIndex);\n  const glideRef = useRef<AnimationPlaybackControls | null>(null);\n  const draggingRef = useRef(false);\n  const hoverRef = useRef(false);\n\n  useEffect(() => {\n    if (count === 0) return;\n    const unsub = scroll.on(\"change\", (v) => {\n      const idx = ((Math.round(v) % count) + count) % count;\n      if (idx !== indexRef.current) {\n        indexRef.current = idx;\n        onIndexChange?.(idx);\n      }\n    });\n    return unsub;\n  }, [scroll, count, onIndexChange]);\n\n  const stopGlide = useCallback(() => {\n    glideRef.current?.stop();\n    glideRef.current = null;\n  }, []);\n\n  // Spring toward `to`, carrying `velocity` (items/s) through so motion never\n  // steps - the roll leaves the finger at finger speed.\n  const glideTo = useCallback(\n    (to: number, velocity: number) => {\n      stopGlide();\n      if (reduce) {\n        scroll.set(to);\n        return;\n      }\n      glideRef.current = animate(scroll, to, {\n        type: \"spring\",\n        ...GLIDE_SPRING,\n        velocity,\n        restDelta: 0.001,\n        restSpeed: 0.005,\n      });\n    },\n    [scroll, stopGlide, reduce],\n  );\n\n  const settle = useCallback(\n    (velocity: number) => {\n      const projected =\n        scroll.get() +\n        Math.max(\n          -MAX_FLICK_ITEMS,\n          Math.min(MAX_FLICK_ITEMS, velocity * FLICK_MOMENTUM),\n        );\n      glideTo(snap ? Math.round(projected) : projected, velocity);\n    },\n    [scroll, snap, glideTo],\n  );\n\n  const drag = useRef({\n    startX: 0,\n    startScroll: 0,\n    lastX: 0,\n    lastT: 0,\n    prevX: 0,\n    prevT: 0,\n  });\n\n  const onPointerDown = useCallback(\n    (e: ReactPointerEvent) => {\n      e.preventDefault();\n      stopGlide();\n      draggingRef.current = true;\n      capturePointer(e.currentTarget, e.pointerId);\n      const now = performance.now();\n      drag.current = {\n        startX: e.clientX,\n        startScroll: scroll.get(),\n        lastX: e.clientX,\n        lastT: now,\n        prevX: e.clientX,\n        prevT: now,\n      };\n    },\n    [scroll, stopGlide],\n  );\n\n  const onPointerMove = useCallback(\n    (e: ReactPointerEvent) => {\n      if (!draggingRef.current) return;\n      const d = drag.current;\n      scroll.set(d.startScroll - ((e.clientX - d.startX) * dragSpeed) / gap);\n      d.prevX = d.lastX;\n      d.prevT = d.lastT;\n      d.lastX = e.clientX;\n      d.lastT = performance.now();\n    },\n    [scroll, gap, dragSpeed],\n  );\n\n  const onPointerUp = useCallback(\n    (e: ReactPointerEvent) => {\n      if (!draggingRef.current) return;\n      draggingRef.current = false;\n      releasePointer(e.currentTarget, e.pointerId);\n      const d = drag.current;\n      const dt = d.lastT - d.prevT;\n      const vpx = dt > 0 ? (d.lastX - d.prevX) / dt : 0; // px per ms\n      settle((-vpx * dragSpeed * 1000) / gap); // items per second\n    },\n    [settle, gap, dragSpeed],\n  );\n\n  const rollBy = useCallback(\n    (dir: number) => {\n      glideTo(Math.round(scroll.get()) + dir, scroll.getVelocity());\n    },\n    [scroll, glideTo],\n  );\n\n  const wheelSettleRef = useRef<number | undefined>(undefined);\n  const onWheel = useCallback(\n    (e: ReactWheelEvent) => {\n      stopGlide();\n      const delta =\n        Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;\n      scroll.set(scroll.get() + delta / gap);\n      if (wheelSettleRef.current) window.clearTimeout(wheelSettleRef.current);\n      wheelSettleRef.current = window.setTimeout(\n        () => settle(scroll.getVelocity()),\n        140,\n      );\n    },\n    [scroll, gap, settle, stopGlide],\n  );\n\n  useEffect(\n    () => () => {\n      window.clearTimeout(wheelSettleRef.current);\n      stopGlide();\n    },\n    [stopGlide],\n  );\n\n  useEffect(() => {\n    if (!autoRotate || reduce || count === 0) return;\n    let raf = 0;\n    let last = performance.now();\n    const tick = (now: number) => {\n      const dt = (now - last) / 1000;\n      last = now;\n      if (!draggingRef.current && !hoverRef.current && !glideRef.current) {\n        scroll.set(scroll.get() + autoRotateSpeed * dt);\n      }\n      raf = requestAnimationFrame(tick);\n    };\n    raf = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(raf);\n  }, [autoRotate, autoRotateSpeed, reduce, count, scroll]);\n\n  const stageHeight = height ?? size;\n\n  return (\n      <div\n        ref={stageRef}\n        role=\"application\"\n        aria-roledescription={t(\"roleDescription\")}\n        // biome-ignore lint/a11y/noNoninteractiveTabindex: focusable custom carousel widget\n        tabIndex={0}\n        onKeyDown={(e) => {\n          if (e.key === \"ArrowRight\") {\n            e.preventDefault();\n            rollBy(1);\n          } else if (e.key === \"ArrowLeft\") {\n            e.preventDefault();\n            rollBy(-1);\n          }\n        }}\n        onPointerDown={onPointerDown}\n        onPointerMove={onPointerMove}\n        onPointerUp={onPointerUp}\n        onPointerCancel={onPointerUp}\n        onWheel={onWheel}\n        onPointerEnter={() => {\n          hoverRef.current = true;\n        }}\n        onPointerLeave={() => {\n          hoverRef.current = false;\n        }}\n        className={cn(\n          // clip-path, not overflow: it also clips the GPU-composited balls\n          \"relative w-full touch-none outline-none [clip-path:inset(0)]\",\n          // The stage drives the roll from the press itself, so iOS must not\n          // claim the same touch for its callout or a slide drag.\n          TOUCH_GESTURE_CLASS,\n          \"cursor-grab active:cursor-grabbing\",\n          \"focus-visible:ring-2 focus-visible:ring-foreground/20\",\n          className,\n        )}\n        style={{ height: stageHeight }}\n      >\n        {items.map((item, i) => (\n          <CarouselBall\n            // biome-ignore lint/suspicious/noArrayIndexKey: slides are positional and stable\n            key={i}\n            scroll={scroll}\n            index={i}\n            count={count}\n            alpha={alpha}\n            k={k}\n            projection={projection}\n            gap={gap}\n            edgeOffset={edgeOffset}\n            minScale={minScale}\n            convex={convex}\n            arc={arc}\n            halfWidth={halfWidth}\n            itemSize={size}\n          >\n            {item}\n          </CarouselBall>\n        ))}\n      </div>\n  );\n}\n"},{"path":"lib/i18n.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/touch.ts","type":"util","content":"// Shared touch primitives. iOS and iPadOS run their own gestures on top of the\n// page - the long-press selection callout and the selection it drags in with\n// it - and they win: once the platform claims a touch it cancels ours\n// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own\n// their gesture have to opt out.\n//\n// What the two classes below cover, precisely:\n// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:\n//   it is not a property other engines have, so it is inert everywhere else.\n// - `user-select: none` stops the long-press selection on every engine,\n//   Android included, and stops a drag from painting a selection under the\n//   cursor. It is inherited, so it reaches every descendant - which is why the\n//   two classes differ only in whether they apply it unconditionally.\n// What neither covers:\n// - Chrome for Android's long-press menu on a link or an image. No CSS\n//   suppresses it; a gesture surface that wraps one needs its own\n//   `onContextMenu` with `preventDefault()`.\n// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is\n//   not inherited and plain divs and buttons are not drag sources, so setting\n//   it on the surface does nothing - the child itself needs `draggable={false}`.\n\n/**\n * Classes for a surface that *is* the control: a thumb, a drum, a stage, a\n * handle, a hold button. Selection is suppressed on every input, because a\n * drag that highlights the control's own label is wrong on a mouse too.\n * Compose with `touch-none` when the surface also owns the scroll axis - leave\n * it off when the page must still scroll from there.\n */\nexport const TOUCH_GESTURE_CLASS = \"select-none [-webkit-touch-callout:none]\";\n\n/**\n * The same opt-out for a gesture surface that wraps content the consumer owns:\n * a scroller, a context-menu trigger, a sheet header, a list row. Selection is\n * suppressed only where the platform runs its own press gestures - a coarse\n * pointer - so a mouse user can still select and copy that content. If the\n * gesture itself would paint a selection under the cursor, add `select-none`\n * for the duration of the gesture rather than reaching for\n * `TOUCH_GESTURE_CLASS`.\n *\n * `pointer: coarse` describes the *primary* pointer and nothing else, so a\n * hybrid machine reads it wrong in both directions: a tablet with a mouse\n * plugged in keeps touch as primary and loses mouse selection, and a laptop\n * with a touchscreen keeps the mouse as primary and leaves selection live\n * under a finger. No media query can answer per interaction - the query is\n * about the device, and the question is about the gesture in progress. The\n * default stays here because it is right on the machines that are one thing or\n * the other, and losing a selection is a nuisance; where the miss costs a\n * *gesture* instead, the surface pairs it with `holdSelection` on the press.\n */\nexport const TOUCH_GESTURE_CONTENT_CLASS =\n  \"[-webkit-touch-callout:none] pointer-coarse:select-none\";\n\n/**\n * Suppress selection on `element` for as long as a gesture is running on it,\n * whatever the primary pointer of the machine happens to be. Returns the\n * release. Inline, so it wins over the class above and is gone again the\n * moment the gesture ends.\n *\n * For the press gestures a native selection would otherwise steal - a\n * long-press that opens a menu. Elsewhere prefer the classes: a surface that\n * takes selection away for the whole session is a surface whose text nobody\n * can copy.\n */\nexport function holdSelection(element: HTMLElement) {\n  element.style.setProperty(\"user-select\", \"none\");\n  element.style.setProperty(\"-webkit-user-select\", \"none\");\n  return () => {\n    element.style.removeProperty(\"user-select\");\n    element.style.removeProperty(\"-webkit-user-select\");\n  };\n}\n\n/**\n * Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer\n * is already gone by the time the handler runs - routine on iOS, where the\n * system can claim the touch first - and an uncaught throw takes the rest of\n * the handler, the gesture included, down with it. Touch pointers carry\n * implicit capture anyway, so losing it is never fatal.\n */\nexport function capturePointer(element: Element, pointerId: number) {\n  try {\n    element.setPointerCapture(pointerId);\n  } catch {\n    // Pointer is no longer active - implicit capture still applies on touch.\n  }\n}\n\n/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */\nexport function releasePointer(element: Element, pointerId: number) {\n  try {\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  } catch {\n    // Capture was already dropped by the browser.\n  }\n}\n\n/**\n * Whether this event came from a pointer that is *hovering*: not a touch, and\n * not currently pressed. Which input the user is holding right now is not\n * something a device capability can answer - a touchscreen laptop hovers and\n * taps, and iPadOS reports a fine hovering pointer for a finger - so both\n * paths stay live and each handler branches on the event it was given.\n *\n * A pen resting on the glass is making contact, not hovering: `buttons` is the\n * tell, and it sends a pen tap down the same route a finger takes.\n *\n * This answers what an *enter* asks. A leave is the other half of a pair and\n * has to be read against the enter that started it - `useHoverGesture` in\n * `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it\n * rather than asking this question twice.\n */\nexport const isHoveringPointer = (event: {\n  pointerType: string;\n  buttons: number;\n}) => event.pointerType !== \"touch\" && event.buttons === 0;\n"},{"path":"lib/utils.ts","type":"util","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"components/previews/motion/cylinder-carousel.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { type ComponentType, useState } from \"react\";\nimport { CylinderCarousel } from \"@/components/motion/cylinder-carousel\";\nimport {\n  ShaderBackground,\n  type ShaderBackgroundVariant,\n} from \"@/components/motion/shader-background\";\nimport { Tabs, TabsList, TabsTrigger } from \"@/components/motion/tabs\";\n\n// Each variant has its own prop shape; the slides only spread their own preset.\nconst Background = ShaderBackground as ComponentType<\n  { variant: ShaderBackgroundVariant; className?: string } & Record<\n    string,\n    unknown\n  >\n>;\n\nconst SLIDES: { variant: ShaderBackgroundVariant; props: Record<string, unknown> }[] = [\n  {\n    variant: \"dithering\",\n    props: { colorBack: \"#1a1030\", colorFront: \"#b98cff\", speed: 0.3 },\n  },\n  {\n    variant: \"metaballs\",\n    props: { colors: [\"#e8e8ef\", \"#8a8a9a\", \"#1a1a22\"], colorBack: \"#c9b9a8\", speed: 0.4 },\n  },\n  {\n    variant: \"warp\",\n    props: { colors: [\"#c8ff00\", \"#3a5a00\", \"#c8ff00\", \"#88bb00\"], speed: 0.4 },\n  },\n  {\n    variant: \"god-rays\",\n    props: { colors: [\"#6a7bff\", \"#00114d\"], colorBack: \"#000000\", speed: 0.5 },\n  },\n  {\n    variant: \"swirl\",\n    props: { colorBack: \"#1a0000\", colors: [\"#ffd1a8\", \"#ff6a3d\", \"#b31a57\"], speed: 0.3 },\n  },\n  {\n    variant: \"mesh-gradient\",\n    props: { colors: [\"#e0eaff\", \"#241d9a\", \"#f75092\", \"#9f50d3\"], speed: 0.3 },\n  },\n  {\n    variant: \"voronoi\",\n    props: { colors: [\"#ff8247\", \"#ffe53d\"], speed: 0.3 },\n  },\n  {\n    variant: \"neuro-noise\",\n    props: { colorFront: \"#ffffff\", colorMid: \"#47a6ff\", colorBack: \"#000000\", speed: 0.4 },\n  },\n];\n\nexport function CylinderCarouselPreview() {\n  const [variant, setVariant] = useState<\"concave\" | \"convex\">(\"concave\");\n\n  return (\n    <div className=\"flex w-full flex-col items-center gap-4 p-6\">\n      <Tabs\n        value={variant}\n        onValueChange={setVariant}\n        variant=\"segment\"\n      >\n        <TabsList>\n          <TabsTrigger value=\"concave\">Concave</TabsTrigger>\n          <TabsTrigger value=\"convex\">Convex</TabsTrigger>\n        </TabsList>\n      </Tabs>\n      {/* clip-path (not overflow) so the rounded corner also clips the GPU-composited balls */}\n      <div className=\"w-full rounded-3xl border border-border/60 bg-muted/20 py-6 [clip-path:inset(0_round_1.5rem)]\">\n        <CylinderCarousel\n          variant={variant}\n          itemSize={230}\n          height={310}\n          className=\"w-full\"\n        >\n          {SLIDES.map((slide) => (\n            <div\n              key={slide.variant}\n              className=\"h-full w-full overflow-hidden rounded-full border border-border/40\"\n            >\n              <Background\n                variant={slide.variant}\n                className=\"h-full w-full\"\n                {...slide.props}\n              />\n            </div>\n          ))}\n        </CylinderCarousel>\n      </div>\n      <p className=\"text-xs text-muted-foreground\">\n        Drag, scroll or use arrow keys to roll\n      </p>\n    </div>\n  );\n}\n"},{"path":"components/motion/shader-background.tsx","type":"util","content":"\"use client\";\n\nimport {\n  ColorPanels,\n  type ColorPanelsProps,\n  Dithering,\n  type DitheringProps,\n  DotGrid,\n  type DotGridProps,\n  DotOrbit,\n  type DotOrbitProps,\n  GodRays,\n  type GodRaysProps,\n  GrainGradient,\n  type GrainGradientProps,\n  Metaballs,\n  type MetaballsProps,\n  MeshGradient,\n  type MeshGradientProps,\n  NeuroNoise,\n  type NeuroNoiseProps,\n  PerlinNoise,\n  type PerlinNoiseProps,\n  PulsingBorder,\n  type PulsingBorderProps,\n  SimplexNoise,\n  type SimplexNoiseProps,\n  SmokeRing,\n  type SmokeRingProps,\n  Spiral,\n  type SpiralProps,\n  StaticMeshGradient,\n  type StaticMeshGradientProps,\n  StaticRadialGradient,\n  type StaticRadialGradientProps,\n  Swirl,\n  type SwirlProps,\n  Voronoi,\n  type VoronoiProps,\n  Warp,\n  type WarpProps,\n  Water,\n  type WaterProps,\n  Waves,\n  type WavesProps,\n} from \"@paper-design/shaders-react\";\nimport { useReducedMotion } from \"motion/react\";\nimport type { ComponentType } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\ntype ShaderVariantProps = {\n  \"mesh-gradient\": MeshGradientProps;\n  \"grain-gradient\": GrainGradientProps;\n  \"dot-grid\": DotGridProps;\n  \"dot-orbit\": DotOrbitProps;\n  warp: WarpProps;\n  waves: WavesProps;\n  water: WaterProps;\n  voronoi: VoronoiProps;\n  swirl: SwirlProps;\n  \"smoke-ring\": SmokeRingProps;\n  \"static-radial-gradient\": StaticRadialGradientProps;\n  \"neuro-noise\": NeuroNoiseProps;\n  metaballs: MetaballsProps;\n  \"god-rays\": GodRaysProps;\n  spiral: SpiralProps;\n  dithering: DitheringProps;\n  \"pulsing-border\": PulsingBorderProps;\n  \"color-panels\": ColorPanelsProps;\n  \"static-mesh-gradient\": StaticMeshGradientProps;\n  \"simplex-noise\": SimplexNoiseProps;\n  \"perlin-noise\": PerlinNoiseProps;\n};\n\nexport type ShaderBackgroundVariant = keyof ShaderVariantProps;\n\nexport type ShaderBackgroundProps = {\n  [K in ShaderBackgroundVariant]: { variant: K } & ShaderVariantProps[K];\n}[ShaderBackgroundVariant];\n\nconst VARIANT_COMPONENTS: {\n  [K in ShaderBackgroundVariant]: ComponentType<ShaderVariantProps[K]>;\n} = {\n  \"mesh-gradient\": MeshGradient,\n  \"grain-gradient\": GrainGradient,\n  \"dot-grid\": DotGrid,\n  \"dot-orbit\": DotOrbit,\n  warp: Warp,\n  waves: Waves,\n  water: Water,\n  voronoi: Voronoi,\n  swirl: Swirl,\n  \"smoke-ring\": SmokeRing,\n  \"static-radial-gradient\": StaticRadialGradient,\n  \"neuro-noise\": NeuroNoise,\n  metaballs: Metaballs,\n  \"god-rays\": GodRays,\n  spiral: Spiral,\n  dithering: Dithering,\n  \"pulsing-border\": PulsingBorder,\n  \"color-panels\": ColorPanels,\n  \"static-mesh-gradient\": StaticMeshGradient,\n  \"simplex-noise\": SimplexNoise,\n  \"perlin-noise\": PerlinNoise,\n};\n\nexport const SHADER_BACKGROUND_VARIANTS = Object.keys(\n  VARIANT_COMPONENTS,\n) as ShaderBackgroundVariant[];\n\n/**\n * Variants with no `speed` param: static patterns that never animate, and that\n * would pass an unknown `speed` through to their DOM node.\n */\nconst STATIC_VARIANTS = new Set<ShaderBackgroundVariant>([\"dot-grid\", \"waves\"]);\n\n/**\n * Reduced motion freezes every animating variant at speed 0, whether or not\n * the caller passed `speed`: the shaders animate by default when it is left\n * out.\n */\nexport function ShaderBackground({\n  variant,\n  className,\n  ...rest\n}: ShaderBackgroundProps) {\n  const reducedMotion = useReducedMotion();\n  const Shader = VARIANT_COMPONENTS[variant] as ComponentType<\n    Record<string, unknown>\n  >;\n  const props = rest as Record<string, unknown>;\n  const speedProps =\n    reducedMotion && !STATIC_VARIANTS.has(variant) ? { speed: 0 } : {};\n\n  return (\n    <Shader\n      {...props}\n      {...speedProps}\n      className={cn(\"h-full w-full\", className)}\n    />\n  );\n}\n"},{"path":"components/motion/tabs.tsx","type":"util","content":"\"use client\";\n\nimport { ChevronLeft, ChevronRight } from \"lucide-react\";\nimport { cancelFrame, frame, motion, MotionConfig, useReducedMotion, useSpring, type MotionValue, type Transition } from \"motion/react\";\nimport {\n  createContext,\n  useCallback,\n  useContext,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useMemo,\n  useState,\n  type ButtonHTMLAttributes,\n  type HTMLAttributes,\n  type KeyboardEvent,\n  type ReactNode,\n} from \"react\";\nimport { EASE_OUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { useSound } from \"@/lib/sound\";\nimport { selectSound } from \"@/lib/sounds/select\";\nimport { cn } from \"@/lib/utils\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const tabsMessages = {\n  scrollLeft: \"Scroll tabs left\",\n  scrollRight: \"Scroll tabs right\",\n};\n\nexport type TabsMessages = typeof tabsMessages;\n\ntype Variant = \"pill\" | \"underline\" | \"segment\";\n/** Whether trigger icons show on every tab or only on the selected one. */\ntype IconDisplay = \"always\" | \"selected\";\n\ntype Ctx = {\n  value: string;\n  setValue: (v: string) => void;\n  layoutId: string;\n  variant: Variant;\n  icons: IconDisplay;\n  /** The pill's box in the list, for tabs whose width changes as they're selected. */\n  track: Track;\n  /** Whether the tracked pill has been measured; until then CSS places it. */\n  placed: boolean;\n  setPlaced: (placed: boolean) => void;\n  /**\n   * The one tab Tab reaches: the selected tab, or the first enabled one when\n   * nothing enabled is selected. `null` until the triggers have registered,\n   * when every enabled tab stays reachable.\n   */\n  tabStop: string | null;\n  registerTab: (value: string, disabled: boolean) => void;\n  unregisterTab: (value: string) => void;\n  /** Values with a mounted panel, so triggers only point at panels that exist. */\n  panels: ReadonlySet<string>;\n  registerPanel: (value: string) => void;\n  unregisterPanel: (value: string) => void;\n  tabId: (value: string) => string;\n  panelId: (value: string) => string;\n  t: (key: keyof TabsMessages) => string;\n};\n\ntype Track = Record<\"x\" | \"y\" | \"width\" | \"height\", MotionValue<number>>;\n\nconst TabsCtx = createContext<Ctx | null>(null);\n\nfunction useTabs() {\n  const ctx = useContext(TabsCtx);\n  if (!ctx) throw new Error(\"Tabs.* must be used inside <Tabs>\");\n  return ctx;\n}\n\n// Settle without overshoot: a scrollable tab list would turn even a small\n// overshoot into a transient scrollbar and layout shift.\n// Scale stiffness and damping together for a quicker glide with the same feel.\nconst transition: Transition = {\n  type: \"spring\",\n  stiffness: 245,\n  damping: 36,\n  mass: 1.2,\n};\n\n/**\n * Pass a union of tab values as `T` (or let `value` infer it) and\n * `onValueChange` receives that union. Every trigger's `value` must be one of\n * them.\n */\nexport function Tabs<T extends string = string>({\n  defaultValue,\n  value,\n  onValueChange,\n  variant = \"pill\",\n  icons = \"always\",\n  labels,\n  sound = false,\n  children,\n  className,\n}: {\n  /** The tab selected at first when uncontrolled. */\n  defaultValue?: T;\n  /** The selected tab's value, for controlled use. */\n  value?: T;\n  /** Called with the tab's value when a tab is picked. */\n  onValueChange?: (v: T) => void;\n  /** Selection style: \"pill\", \"underline\" or \"segment\". Default: \"pill\" */\n  variant?: Variant;\n  /**\n   * With \"selected\", a trigger's icon springs open only on the selected tab\n   * and folds away when another is chosen. Defaults to \"always\".\n   */\n  icons?: IconDisplay;\n  /** Override any built-in string. */\n  labels?: Partial<TabsMessages>;\n  /** Play a soft tick when the user picks another tab. Off by default; a `SoundProvider` can mute it app-wide. */\n  sound?: boolean;\n  children: ReactNode;\n  className?: string;\n}) {\n  const t = useMessages(\"tabs\", tabsMessages, labels);\n  const [internal, setInternal] = useState<string>(defaultValue ?? \"\");\n  const layoutId = useId();\n  const reduce = useReducedMotion();\n  const controlled = value !== undefined;\n  const current = controlled ? value : internal;\n  const play = useSound(selectSound, { enabled: sound });\n  const setValue = useCallback(\n    (v: string) => {\n      if (v !== current) play();\n      if (!controlled) setInternal(v);\n      // Triggers only carry values from `T`, so the string is one of them.\n      onValueChange?.(v as T);\n    },\n    [controlled, onValueChange, current, play],\n  );\n  const x = useSpring(0, transition);\n  const y = useSpring(0, transition);\n  const width = useSpring(0, transition);\n  const height = useSpring(0, transition);\n  const track = useMemo(() => ({ x, y, width, height }), [x, y, width, height]);\n  const [placed, setPlaced] = useState(false);\n  const [tabs, setTabs] = useState<Map<string, boolean>>(new Map());\n  const registerTab = useCallback((tab: string, disabled: boolean) => {\n    setTabs((map) => (map.get(tab) === disabled ? map : new Map(map).set(tab, disabled)));\n  }, []);\n  const unregisterTab = useCallback((tab: string) => {\n    setTabs((map) => {\n      if (!map.has(tab)) return map;\n      const next = new Map(map);\n      next.delete(tab);\n      return next;\n    });\n  }, []);\n  const [panels, setPanels] = useState<ReadonlySet<string>>(new Set());\n  const registerPanel = useCallback((panel: string) => {\n    setPanels((set) => (set.has(panel) ? set : new Set(set).add(panel)));\n  }, []);\n  const unregisterPanel = useCallback((panel: string) => {\n    setPanels((set) => {\n      if (!set.has(panel)) return set;\n      const next = new Set(set);\n      next.delete(panel);\n      return next;\n    });\n  }, []);\n  // Resolved during render so the list has exactly one tab stop in the same\n  // commit that changes the selection or the tabs.\n  let tabStop: string | null = null;\n  if (tabs.size > 0) {\n    const enabled = Array.from(tabs).filter(([, disabled]) => !disabled);\n    tabStop = enabled.some(([tab]) => tab === current) ? current : (enabled[0]?.[0] ?? \"\");\n  }\n  const baseId = useId();\n  const tabId = useCallback((tab: string) => `${baseId}-tab-${tab.replace(/[^\\w-]/g, \"_\")}`, [baseId]);\n  const panelId = useCallback((tab: string) => `${baseId}-panel-${tab.replace(/[^\\w-]/g, \"_\")}`, [baseId]);\n  const contextValue = useMemo(\n    () => ({\n      value: current,\n      setValue,\n      layoutId,\n      variant,\n      icons,\n      track,\n      placed,\n      setPlaced,\n      tabStop,\n      registerTab,\n      unregisterTab,\n      panels,\n      registerPanel,\n      unregisterPanel,\n      tabId,\n      panelId,\n      t,\n    }),\n    [current, icons, layoutId, setValue, variant, track, placed, tabStop, registerTab, unregisterTab, panels, registerPanel, unregisterPanel, tabId, panelId, t],\n  );\n  return (\n    <MotionConfig transition={reduce ? { duration: 0 } : transition}>\n      <TabsCtx.Provider value={contextValue}>\n        {/* layoutRoot: the indicator's layoutId measures in page coordinates, so\n            inside fixed/scrolled containers it would replay scroll offsets as\n            movement. The pill only ever travels within the list, so scoping\n            projection to the Tabs wrapper is always correct. */}\n        <motion.div layoutRoot className={className}>\n          {children}\n        </motion.div>\n      </TabsCtx.Provider>\n    </MotionConfig>\n  );\n}\n\nconst listClasses: Record<Variant, string> = {\n  pill: \"inline-flex items-center gap-1 rounded-full bg-card p-1\",\n  underline: \"inline-flex items-center gap-1 border-b border-border\",\n  segment: \"inline-flex items-center gap-0 rounded-full bg-card p-0.5\",\n};\n\nexport function TabsList({\n  children,\n  className,\n  wrapperClassName,\n  onKeyDown,\n  ...props\n}: {\n  wrapperClassName?: string;\n} & HTMLAttributes<HTMLDivElement>) {\n  const { variant, value, icons, track, placed, setPlaced, t } = useTabs();\n  const reduce = useReducedMotion();\n  const tracked = icons === \"selected\" && variant !== \"underline\";\n  const rootRef = useRef<HTMLDivElement>(null);\n  const viewportRef = useRef<HTMLDivElement>(null);\n  const listRef = useRef<HTMLDivElement>(null);\n  const viewportId = useId();\n  const [edges, setEdges] = useState({ overflow: false, left: false, right: false });\n\n  const measure = useCallback(() => {\n    const root = rootRef.current;\n    const viewport = viewportRef.current;\n    if (!root || !viewport) return;\n    // Overlay controls do not reduce the viewport or change its scroll range.\n    const overflow = viewport.scrollWidth > root.clientWidth + 1;\n    const max = Math.max(0, viewport.scrollWidth - viewport.clientWidth);\n    const rtl = getComputedStyle(viewport).direction === \"rtl\";\n    // Modern browsers expose negative scrollLeft in RTL. Clamp rubber-banding.\n    const fromLeft = Math.max(0, Math.min(max, rtl ? max + viewport.scrollLeft : viewport.scrollLeft));\n    const next = { overflow, left: fromLeft > 1, right: fromLeft < max - 1 };\n    setEdges((previous) => previous.overflow === next.overflow && previous.left === next.left && previous.right === next.right ? previous : next);\n  }, []);\n\n  const reveal = useCallback((tab: HTMLElement | null) => {\n    const viewport = viewportRef.current;\n    if (!viewport || !tab) return;\n    const frame = viewport.getBoundingClientRect();\n    const item = tab.getBoundingClientRect();\n    const max = Math.max(0, viewport.scrollWidth - viewport.clientWidth);\n    const rtl = getComputedStyle(viewport).direction === \"rtl\";\n    const fromLeft = Math.max(0, Math.min(max, rtl ? max + viewport.scrollLeft : viewport.scrollLeft));\n    // Keep the selected/focused label clear of the arrows over the faded edges.\n    const left = frame.left + (fromLeft > 1 ? 36 : 0);\n    const right = frame.right - (fromLeft < max - 1 ? 36 : 0);\n    const delta = item.left < left ? item.left - left : item.right > right ? item.right - right : 0;\n    // Scroll only this viewport; scrollIntoView can also move the whole page.\n    if (delta) viewport.scrollBy({ left: delta, behavior: reduce ? \"instant\" : \"smooth\" });\n  }, [reduce]);\n\n  useLayoutEffect(() => {\n    const root = rootRef.current;\n    const viewport = viewportRef.current;\n    const list = listRef.current;\n    if (!root || !viewport || !list) return;\n    const update = () => {\n      measure();\n      reveal(list.querySelector<HTMLElement>('[role=\"tab\"][aria-selected=\"true\"]'));\n    };\n    const observer = new ResizeObserver(update);\n    observer.observe(root);\n    observer.observe(viewport);\n    observer.observe(list);\n    viewport.addEventListener(\"scroll\", measure, { passive: true });\n    update();\n    return () => {\n      observer.disconnect();\n      viewport.removeEventListener(\"scroll\", measure);\n    };\n  }, [measure, reveal]);\n\n  useLayoutEffect(() => {\n    // Children may change without a resize; controlled selection must also reveal.\n    void children;\n    void value;\n    void edges.overflow;\n    measure();\n    reveal(listRef.current?.querySelector<HTMLElement>('[role=\"tab\"][aria-selected=\"true\"]') ?? null);\n  }, [children, value, edges.overflow, measure, reveal]);\n\n  useLayoutEffect(() => {\n    // With icons=\"selected\" the chosen tab grows as its icon opens and the\n    // last one shrinks. A layout animation measures the tabs mid-change, so\n    // the pill would squeeze and catch up. Instead the pill springs straight\n    // to where the selected tab will settle, with every icon open or closed.\n    if (!tracked) return;\n    const list = listRef.current;\n    if (!list) return;\n    void children;\n    const place = () => {\n      const tabs = Array.from(list.querySelectorAll<HTMLElement>('[role=\"tab\"]'));\n      const target = tabs.find((tab) => tab.dataset.tabsValue === value)?.parentElement;\n      if (!target) return;\n      // Measure the settled layout: open the selected icon and fold the rest\n      // for one synchronous read, then hand the styles back to Motion before\n      // anything paints. Exact in any layout, from flex rows to grids.\n      const icons = Array.from(list.querySelectorAll<HTMLElement>('[role=\"tab\"] > [data-tabs-icon]'));\n      const saved = icons.map((icon) => [icon.style.width, icon.style.marginRight]);\n      for (const icon of icons) {\n        const open = icon.parentElement?.parentElement === target;\n        icon.style.width = open ? \"auto\" : \"0px\";\n        icon.style.marginRight = open ? `${ICON_GAP}px` : \"0px\";\n      }\n      const box = {\n        x: target.offsetLeft,\n        y: target.offsetTop,\n        // Fractional: a rounded width leaves the pill a hair off its tab.\n        width: target.getBoundingClientRect().width,\n        height: target.offsetHeight,\n      };\n      icons.forEach((icon, index) => {\n        [icon.style.width, icon.style.marginRight] = saved[index];\n      });\n      // A first measurement, or one after the list was hidden, lands in place.\n      const instant = reduce || track.width.get() === 0;\n      for (const key of [\"x\", \"y\", \"width\", \"height\"] as const) {\n        if (instant) track[key].jump(box[key]);\n        else track[key].set(box[key]);\n      }\n      // Hand over from the CSS pill once there's a real box, before paint.\n      if (box.width > 0) setPlaced(true);\n    };\n    place();\n    const observer = new ResizeObserver(place);\n    for (const tab of list.querySelectorAll('[role=\"tab\"]')) if (tab.parentElement) observer.observe(tab.parentElement);\n    return () => observer.disconnect();\n  }, [tracked, value, children, reduce, track, setPlaced]);\n\n  useLayoutEffect(() => {\n    if (variant === \"underline\") return;\n    const list = listRef.current;\n    if (!list) return;\n    void children;\n    // `placed` swaps the indicator element, so measure the new one.\n    void placed;\n    const labels = Array.from(list.querySelectorAll<HTMLElement>(\"[data-tabs-label]\"));\n    const indicator = list.querySelector<HTMLElement>(\"[data-tabs-indicator]\");\n    const target = list.querySelector<HTMLElement>('[role=\"tab\"][aria-selected=\"true\"]');\n    if (!indicator || !target || target.dataset.tabsValue !== value) {\n      for (const label of labels) label.style.clipPath = \"inset(0 100% 0 0)\";\n      return;\n    }\n    let frames = 0;\n    let stillFrames = 0;\n    let previous: { left: number; right: number } | undefined;\n    const syncClips = () => {\n      const pill = (reduce ? target : indicator).getBoundingClientRect();\n      // Read ALL geometry before writing ANY masks. A loop per tab interleaved\n      // reads and writes, forcing the browser to flush styles repeatedly.\n      const clips = labels.map((label) => {\n        const bounds = label.getBoundingClientRect();\n        const left = Math.max(0, Math.min(bounds.width, pill.left - bounds.left));\n        const right = Math.max(0, Math.min(bounds.width, bounds.right - pill.right));\n        return left + right >= bounds.width ? \"inset(0 100% 0 0)\" : `inset(0 ${right}px 0 ${left}px)`;\n      });\n      labels.forEach((label, index) => {\n        if (label.style.clipPath !== clips[index]) label.style.clipPath = clips[index];\n      });\n      frames += 1;\n      stillFrames = previous && Math.abs(pill.left - previous.left) < 0.01 && Math.abs(pill.right - previous.right) < 0.01 ? stillFrames + 1 : 0;\n      previous = { left: pill.left, right: pill.right };\n      if (reduce || (frames > 2 && stillFrames >= 2)) cancelFrame(syncClips);\n    };\n    // One shared pass after Motion paints the projected pill keeps every label\n    // in sync, including labels crossed during a long or interrupted glide.\n    frame.postRender(syncClips, true);\n    // A list measured while hidden (display: none, a closed panel, a\n    // breakpoint) gets every mask closed. Sync again once it has a size, or\n    // the selected label stays invisible until the value changes.\n    const resync = () => {\n      frames = 0;\n      stillFrames = 0;\n      previous = undefined;\n      cancelFrame(syncClips);\n      frame.postRender(syncClips, true);\n    };\n    const observer = new ResizeObserver(resync);\n    observer.observe(list);\n    return () => {\n      observer.disconnect();\n      cancelFrame(syncClips);\n    };\n  }, [value, children, variant, reduce, placed]);\n\n  // Arrow keys move along the list and select as focus arrives, wrapping at\n  // the ends; Home and End jump to the first and last enabled tab.\n  const onListKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented) return;\n    const list = listRef.current;\n    if (!list || !(event.target instanceof HTMLElement)) return;\n    const tabs = Array.from(list.querySelectorAll<HTMLButtonElement>('[role=\"tab\"]')).filter(\n      (tab) => !tab.disabled && tab.closest('[role=\"tablist\"]') === list,\n    );\n    const at = tabs.indexOf(event.target as HTMLButtonElement);\n    if (at < 0) return;\n    const rtl = getComputedStyle(list).direction === \"rtl\";\n    const forward = rtl ? \"ArrowLeft\" : \"ArrowRight\";\n    const back = rtl ? \"ArrowRight\" : \"ArrowLeft\";\n    const next =\n      event.key === forward\n        ? tabs[(at + 1) % tabs.length]\n        : event.key === back\n          ? tabs[(at - 1 + tabs.length) % tabs.length]\n          : event.key === \"Home\"\n            ? tabs[0]\n            : event.key === \"End\"\n              ? tabs[tabs.length - 1]\n              : null;\n    if (!next) return;\n    event.preventDefault();\n    next.focus();\n    next.click();\n  };\n\n  const scroll = (direction: number) => {\n    const viewport = viewportRef.current;\n    if (viewport) viewport.scrollBy({ left: direction * viewport.clientWidth * 0.8, behavior: reduce ? \"instant\" : \"smooth\" });\n  };\n  const controlClass = \"absolute inset-y-0 z-20 inline-flex w-9 items-center justify-center text-foreground transition-opacity hover:opacity-70 focus-visible:outline-2 focus-visible:-outline-offset-4 focus-visible:outline-ring disabled:pointer-events-none disabled:opacity-0\";\n  const surfaceClass = variant === \"pill\" ? \"rounded-full bg-card\" : variant === \"segment\" ? \"rounded-full bg-card\" : \"\";\n\n  return (\n    <div ref={rootRef} className={cn(\"relative isolate flex w-full max-w-full min-w-0 items-center\", edges.overflow && surfaceClass, wrapperClassName)}>\n      {edges.overflow && (\n        <button type=\"button\" aria-label={t(\"scrollLeft\")} aria-controls={viewportId} disabled={!edges.left} onClick={() => scroll(-1)} className={cn(controlClass, \"left-0 rounded-l-full\")}>\n          <ChevronLeft size={20} aria-hidden=\"true\" />\n        </button>\n      )}\n      <motion.div\n        ref={viewportRef}\n        id={viewportId}\n        layoutScroll\n        className={cn(\"w-full min-w-0 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\", edges.overflow && \"[border-radius:inherit]\")}\n        style={edges.overflow ? {\n          maskImage: `linear-gradient(to right, ${edges.left ? \"transparent, black 40px\" : \"black, black 0px\"}, ${edges.right ? \"black calc(100% - 40px), transparent\" : \"black 100%\"})`,\n        } : undefined}\n        onFocusCapture={(event) => {\n          if (event.target instanceof HTMLElement && event.target.getAttribute(\"role\") === \"tab\") reveal(event.target);\n        }}\n      >\n        <div {...props} ref={listRef} role=\"tablist\" onKeyDown={onListKeyDown} className={cn(listClasses[variant], \"w-max\", tracked && \"relative\", className)}>\n          {children}\n        </div>\n      </motion.div>\n      {edges.overflow && edges.left && (\n        <span aria-hidden=\"true\" className=\"pointer-events-none absolute inset-y-0 left-0 z-10 w-10 rounded-l-[inherit] backdrop-blur-[2px] [mask-image:linear-gradient(to_right,black,transparent)]\" />\n      )}\n      {edges.overflow && edges.right && (\n        <span aria-hidden=\"true\" className=\"pointer-events-none absolute inset-y-0 right-0 z-10 w-10 rounded-r-[inherit] backdrop-blur-[2px] [mask-image:linear-gradient(to_left,black,transparent)]\" />\n      )}\n      {edges.overflow && (\n        <button type=\"button\" aria-label={t(\"scrollRight\")} aria-controls={viewportId} disabled={!edges.right} onClick={() => scroll(1)} className={cn(controlClass, \"right-0 rounded-r-full\")}>\n          <ChevronRight size={20} aria-hidden=\"true\" />\n        </button>\n      )}\n    </div>\n  );\n}\n\n/** Space between a selected-only icon and its label, in pixels. */\nconst ICON_GAP = 6;\n\n/**\n * A trigger's icon before its label. Shown on every tab, or with\n * `icons=\"selected\"` springing open on the selected tab only.\n */\nfunction TriggerIcon({ icon, active }: { icon: ReactNode; active: boolean }) {\n  const { icons } = useTabs();\n  const reduce = useReducedMotion();\n  if (icons === \"always\") {\n    return (\n      <span aria-hidden=\"true\" className=\"mr-1.5 inline-flex shrink-0 items-center\">\n        {icon}\n      </span>\n    );\n  }\n  return (\n    <motion.span\n      aria-hidden=\"true\"\n      data-tabs-icon=\"\"\n      initial={false}\n      animate={{\n        width: active ? \"auto\" : 0,\n        marginRight: active ? ICON_GAP : 0,\n        opacity: active ? 1 : 0,\n        scale: active ? 1 : 0.6,\n      }}\n      transition={reduce ? { duration: 0 } : SPRING_SWAP}\n      className=\"inline-flex shrink-0 items-center justify-center overflow-hidden\"\n    >\n      {icon}\n    </motion.span>\n  );\n}\n\nexport function TabsTrigger({\n  value,\n  icon,\n  children,\n  className,\n  indicatorClassName,\n  onClick,\n  ...props\n}: {\n  value: string;\n  /** An icon before the label, such as a Lucide icon element. */\n  icon?: ReactNode;\n  indicatorClassName?: string;\n} & Omit<ButtonHTMLAttributes<HTMLButtonElement>, \"value\">) {\n  const {\n    value: current,\n    setValue,\n    layoutId,\n    variant,\n    icons,\n    track,\n    placed,\n    tabStop,\n    registerTab,\n    unregisterTab,\n    panels,\n    tabId,\n    panelId,\n  } = useTabs();\n  const active = current === value;\n  const disabled = Boolean(props.disabled);\n  useLayoutEffect(() => {\n    registerTab(value, disabled);\n  }, [registerTab, value, disabled]);\n  useLayoutEffect(() => () => unregisterTab(value), [unregisterTab, value]);\n  const a11y = {\n    id: tabId(value),\n    \"aria-controls\": panels.has(value) ? panelId(value) : undefined,\n    tabIndex: !disabled && (tabStop === null || tabStop === value) ? 0 : -1,\n  };\n  const content = icon ? (\n    <>\n      <TriggerIcon icon={icon} active={active} />\n      {children}\n    </>\n  ) : (\n    children\n  );\n  // React owns the initial mask only; TabsList synchronizes subsequent masks.\n  const [initialClip] = useState(() => active ? \"inset(0)\" : \"inset(0 100% 0 0)\");\n\n  if (variant === \"underline\") {\n    return (\n      <button\n        // Consumer ids and wiring win, e.g. several tabs sharing one panel.\n        {...a11y}\n        {...props}\n        type=\"button\"\n        role=\"tab\"\n        aria-selected={active}\n        onClick={(event) => {\n          onClick?.(event);\n          if (!event.defaultPrevented) setValue(value);\n        }}\n        className={cn(\n          \"relative isolate px-3 pb-2.5 pt-1 -mb-px text-sm font-medium transition-colors min-h-[44px] inline-flex items-center whitespace-nowrap shrink-0\",\n          active ? \"text-foreground\" : \"text-muted-foreground hover:text-foreground\",\n          className,\n        )}\n      >\n        {content}\n        {active ? (\n        <motion.span\n          layoutId={layoutId}\n          layout\n          className={cn(\n            \"absolute bottom-0 left-0 right-0 h-px bg-primary\",\n            indicatorClassName,\n          )}\n        />\n        ) : null}\n      </button>\n    );\n  }\n\n  // Tracked pills are placed in the list, so this wrapper must not be their\n  // containing block. Server HTML can't measure, so until the first\n  // measurement the pill fills the selected tab with CSS, like the others.\n  const tracked = icons === \"selected\" && placed;\n\n  return (\n    <div className={cn(\"shrink-0\", !tracked && \"relative\")}>\n      {/* Distinct keys: reused across the swap, the CSS pill's leftover\n          `transform: none` would hide the tracked pill's offset until the\n          next value change. */}\n      {active && tracked ? (\n        <motion.span\n          key=\"tracked\"\n          data-tabs-indicator=\"\"\n          style={{ ...track, borderRadius: 9999 }}\n          className={cn(\"absolute top-0 left-0 rounded-full bg-primary\", indicatorClassName)}\n        />\n      ) : active ? (\n        <motion.span\n          key=\"layout\"\n          data-tabs-indicator=\"\"\n          layoutId={layoutId}\n          layout\n          style={{ borderRadius: 9999 }}\n          className={cn(\"absolute inset-0 rounded-full bg-primary\", indicatorClassName)}\n        />\n      ) : null}\n      <button\n        // Consumer ids and wiring win, e.g. several tabs sharing one panel.\n        {...a11y}\n        {...props}\n        type=\"button\"\n        role=\"tab\"\n        aria-selected={active}\n        data-tabs-value={value}\n        onClick={(event) => {\n          onClick?.(event);\n          if (!event.defaultPrevented) setValue(value);\n        }}\n        className={cn(\n          \"relative z-10 inline-flex items-center justify-center whitespace-nowrap bg-transparent px-3.5 py-1.5 text-sm font-medium outline-none\",\n          \"text-muted-foreground hover:text-foreground rounded-full\",\n          className,\n        )}\n      >\n        {content}\n        <span\n          data-tabs-label=\"\"\n          aria-hidden=\"true\"\n          inert\n          className=\"pointer-events-none absolute inset-0 inline-flex items-center justify-center text-primary-foreground [gap:inherit] [padding:inherit]\"\n          style={{ clipPath: initialClip }}\n        >\n          {content}\n        </span>\n      </button>\n    </div>\n  );\n}\n\nexport function TabsContent({\n  value,\n  children,\n  className,\n}: {\n  /** The trigger value that shows this panel. */\n  value: string;\n  children: ReactNode;\n  className?: string;\n}) {\n  const { value: current, registerPanel, unregisterPanel, tabId, panelId } = useTabs();\n  const reduce = useReducedMotion();\n  const active = current === value;\n  useLayoutEffect(() => {\n    registerPanel(value);\n    return () => unregisterPanel(value);\n  }, [registerPanel, unregisterPanel, value]);\n  const a11y = {\n    id: panelId(value),\n    role: \"tabpanel\",\n    \"aria-labelledby\": tabId(value),\n  } as const;\n  // Inactive panels stay mounted but hidden, so their content (e.g. source\n  // code) is present in the server-rendered HTML for crawlers and assistive\n  // tech, instead of being dropped from the DOM.\n  if (!active) {\n    return (\n      <div {...a11y} hidden className={className}>\n        {children}\n      </div>\n    );\n  }\n  return (\n    <motion.div\n      {...a11y}\n      // Reachable with Tab so a panel without controls can still be read.\n      tabIndex={0}\n      key={value}\n      initial={{ opacity: 0, y: reduce ? 0 : 4 }}\n      animate={{ opacity: 1, y: 0 }}\n      transition={{ duration: 0.18, ease: EASE_OUT }}\n      className={cn(\"mt-4 outline-none focus-visible:ring-2 focus-visible:ring-ring/40 rounded-md\", className)}\n    >\n      {children}\n    </motion.div>\n  );\n}\n"},{"path":"lib/ease.ts","type":"util","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps - label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances - modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides - pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/sound.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n} from \"react\";\nimport {\n  registerSoundSettings,\n  retainAudioContext,\n  type SoundSettingsEntry,\n} from \"@/lib/audio-context\";\nimport type { PlayOptions, Sound } from \"@/lib/sounds/engine\";\n\nexport interface SoundSettings {\n  /** False mutes every beUI sound under the provider. */\n  enabled: boolean;\n  /** 0 to 1, scales every beUI sound. */\n  volume: number;\n}\n\nconst SoundContext = createContext<SoundSettings & { depth: number }>({\n  enabled: true,\n  volume: 1,\n  depth: 0,\n});\n\n/**\n * App-wide sound settings. `enabled={false}` mutes every beUI sound, from\n * component `sound` props and `useSound` to the games, Wheel Picker and\n * Bookshelf, and `volume` scales them all. Without a provider, sounds play at\n * full volume. A nested provider overrides the one around it.\n */\nexport function SoundProvider({\n  enabled = true,\n  volume = 1,\n  children,\n}: Partial<SoundSettings> & { children: ReactNode }) {\n  const depth = useContext(SoundContext).depth + 1;\n  const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);\n\n  // Module-level as well (lib/audio-context.ts), so players outside React\n  // and `sound.play()` obey it too.\n  const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });\n  const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);\n  useEffect(() => {\n    registration.current = registerSoundSettings(entry.current);\n    return () => {\n      registration.current?.release();\n      registration.current = null;\n    };\n  }, []);\n  useEffect(() => {\n    Object.assign(entry.current, { depth, enabled, volume });\n    registration.current?.update();\n  }, [depth, enabled, volume]);\n\n  return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;\n}\n\nexport function useSoundSettings(): SoundSettings {\n  return useContext(SoundContext);\n}\n\nexport interface UseSoundOptions {\n  /** False makes `play` do nothing, for a component's `sound` prop. */\n  enabled?: boolean;\n  /** 0 to 1 for this sound, on top of the provider volume. */\n  volume?: number;\n}\n\n/**\n * A stable `play()` for one sound. It does nothing while disabled or muted,\n * and keeps the shared audio context warm only while it can play.\n */\nexport function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {\n  const settings = useSoundSettings();\n  const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;\n  // Read by the stable callback, so a caller's effects don't re-run when\n  // the settings change.\n  const latest = useRef({ on, volume, sound });\n  useLayoutEffect(() => {\n    latest.current = { on, volume, sound };\n  });\n\n  useEffect(() => {\n    if (!on) return;\n    return retainAudioContext();\n  }, [on]);\n\n  return useCallback((options?: PlayOptions) => {\n    const current = latest.current;\n    if (!current.on) return;\n    current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });\n  }, []);\n}\n"},{"path":"lib/sounds/select.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */\nexport const selectSound = defineSound({\n  name: \"Select\",\n  duration: 0.05,\n  room: 0.08,\n  build: (v) => {\n    v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });\n    v.strike({ freq: 1700, material: \"metal\", decay: 0.028, gain: 0.3 });\n    v.strike({ freq: 520, material: \"wood\", bend: 1.15, decay: 0.012, gain: 0.25 });\n  },\n});\n"},{"path":"lib/audio-context.ts","type":"util","content":"// One AudioContext for every synthesized sound on the page: the sounds\n// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino\n// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap\n// concurrent contexts, and a page can show a date made of several WheelPickers\n// next to a game, so they all share this one. It is created on first use and\n// closed once every player is disposed.\n//\n// Every player connects to `audioOutput()` rather than the context's\n// destination, so the page-wide volume and mute from `SoundProvider`\n// (lib/sound.tsx) reach all of them in one place.\n\ntype AudioContextCtor = typeof AudioContext;\n\nlet context: AudioContext | null = null;\nlet master: GainNode | null = null;\nlet users = 0;\n\n/** Settings one mounted `SoundProvider` asks for. */\nexport interface SoundSettingsEntry {\n  /** Nesting depth: the deepest provider decides. */\n  depth: number;\n  enabled: boolean;\n  volume: number;\n}\n\n// Mounted providers in mount order. Module state, so `sound.play()` called\n// outside React obeys them too. The deepest provider wins; among equals, the\n// one mounted last. Effects run child first, so this can't be \"whoever ran\n// last\".\nconst providers = new Set<SoundSettingsEntry>();\nlet allowed = true;\nlet volume = 1;\n\nfunction applySettings() {\n  let chosen: SoundSettingsEntry | undefined;\n  for (const entry of providers) {\n    if (!chosen || entry.depth >= chosen.depth) chosen = entry;\n  }\n  allowed = chosen?.enabled ?? true;\n  volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));\n  if (master) master.gain.value = volume;\n}\n\n/**\n * Registers a provider's settings; call `update` after changing the entry and\n * the returned release function when the provider unmounts.\n */\nexport function registerSoundSettings(entry: SoundSettingsEntry) {\n  providers.add(entry);\n  applySettings();\n  return {\n    update: applySettings,\n    release() {\n      providers.delete(entry);\n      applySettings();\n    },\n  };\n}\n\n/**\n * Registers a sound player. Call the returned function when the player is\n * disposed; the context closes after the last one.\n */\nexport function retainAudioContext() {\n  users++;\n  let released = false;\n  return () => {\n    if (released) return;\n    released = true;\n    users--;\n    if (users === 0 && context) {\n      void context.close();\n      context = null;\n      master = null;\n    }\n  };\n}\n\n/**\n * The shared context, created on first call and resumed if suspended. Null\n * during SSR, in browsers without Web Audio, and while sounds are muted or at\n * zero volume.\n */\nexport function getAudioContext(): AudioContext | null {\n  if (!allowed || volume <= 0) return null;\n  if (!context) {\n    if (typeof window === \"undefined\") return null;\n    const Ctor =\n      window.AudioContext ??\n      (window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;\n    if (!Ctor) return null;\n    context = new Ctor();\n  }\n  // Browsers may refuse outside a user gesture. Players call this from\n  // pointer and key handlers first, so a later call finds it running.\n  if (context.state === \"suspended\") void context.resume().catch(() => undefined);\n  return context;\n}\n\n/** The node every player connects to: the page-wide volume, then the speakers. */\nexport function audioOutput(ctx: AudioContext): AudioNode {\n  if (master?.context !== ctx) {\n    master = ctx.createGain();\n    master.gain.value = volume;\n    master.connect(ctx.destination);\n  }\n  return master;\n}\n\nconst gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();\n\n/**\n * A player's own level, made once per context and routed into `audioOutput`.\n * Players keep their mix this way without rebuilding nodes on every play, and\n * a context closed and recreated gets fresh ones.\n */\nexport function playerGain(ctx: AudioContext, key: string, level: number): GainNode {\n  let byKey = gains.get(ctx);\n  if (!byKey) {\n    byKey = new Map();\n    gains.set(ctx, byKey);\n  }\n  let gain = byKey.get(key);\n  if (!gain) {\n    gain = ctx.createGain();\n    gain.gain.value = level;\n    gain.connect(audioOutput(ctx));\n    byKey.set(key, gain);\n  }\n  return gain;\n}\n"},{"path":"lib/sounds/engine.ts","type":"util","content":"import { audioOutput, getAudioContext } from \"@/lib/audio-context\";\n\n// Every beUI sound is a short recipe played with Web Audio the moment it is\n// asked for. Nothing is downloaded. Recipes are built the way a real tap\n// sounds: a contact click (a millisecond of filtered noise), a body that\n// rings at a few inharmonic partials of a material and settles in pitch, and\n// a little of a small room behind it.\n\n/** Options for one play of a sound. */\nexport interface PlayOptions {\n  /** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */\n  volume?: number;\n  /** Pitch multiplier; 1 is the designed pitch. */\n  pitch?: number;\n}\n\n/** Where a sound renders: the live context, or an offline one for drawing. */\nexport interface SoundTarget {\n  context: BaseAudioContext;\n  destination: AudioNode;\n  /** Start time on the context clock, in seconds. */\n  when: number;\n  volume: number;\n  pitch: number;\n}\n\n/** A plain oscillator with an attack, a decay and an optional glide. */\nexport interface ToneSpec {\n  type?: OscillatorType;\n  /** Start frequency in Hz. */\n  freq: number;\n  /** End frequency in Hz; glides from `freq` over `glide`. */\n  to?: number;\n  /** Glide time in seconds; defaults to the attack plus decay. */\n  glide?: number;\n  /** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** A burst of filtered white noise. */\nexport interface NoiseSpec {\n  filter?: BiquadFilterType;\n  /** Filter frequency in Hz. */\n  freq: number;\n  /** End filter frequency in Hz; sweeps from `freq` over the decay. */\n  to?: number;\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */\nexport interface ClickSpec {\n  /** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */\n  freq: number;\n  /** Band width; higher is narrower and more tonal. */\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time to fade to silence, in seconds. */\n  decay?: number;\n  gain: number;\n}\n\n/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */\nexport interface Material {\n  partials: readonly (readonly [ratio: number, level: number])[];\n  /** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */\n  damping: number;\n}\n\n// Partial ratios follow the modes of small struck objects: a free bar for\n// wood and metal, a cup for glass, a tuned bar for the mallet.\nexport const MATERIALS = {\n  wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },\n  plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },\n  glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },\n  metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },\n  mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },\n  bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },\n} satisfies Record<string, Material>;\n\n/** A struck object: one partial per mode of its material, each with its own decay. */\nexport interface StrikeSpec {\n  /** Fundamental in Hz. */\n  freq: number;\n  /** A name from `MATERIALS` or your own partials. Default: \"plastic\". */\n  material?: keyof typeof MATERIALS | Material;\n  /** Starts this many times higher and settles in about 15 ms. Default: 1.01. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time for the fundamental to fade to silence, in seconds. */\n  decay: number;\n  gain: number;\n}\n\nexport interface Voice {\n  tone(spec: ToneSpec): void;\n  noise(spec: NoiseSpec): void;\n  click(spec: ClickSpec): void;\n  strike(spec: StrikeSpec): void;\n}\n\nexport interface Sound {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Plays the sound now. Silent during SSR and while sounds are muted. */\n  play(options?: PlayOptions): void;\n  /** Schedules the sound on any context; `play` uses the live one. */\n  render(target: SoundTarget): void;\n}\n\nexport interface SoundRecipe {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */\n  vary?: number;\n  /** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */\n  room?: number;\n  /** Adds the sound's layers to the voice on each play. */\n  build: (voice: Voice) => void;\n}\n\n// Keeps a sum of voices well under clipping at volume 1.\nconst MASTER_GAIN = 0.16;\nconst SILENT = 0.0001;\n// Time a strike or bend takes to settle onto its pitch.\nconst SETTLE = 0.015;\n\nconst noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\n/** One second of white noise per context, shared by every noise voice. */\nexport function noiseBuffer(context: BaseAudioContext) {\n  let buffer = noiseBuffers.get(context);\n  if (!buffer) {\n    buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);\n    const data = buffer.getChannelData(0);\n    for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n    noiseBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// A small, soft room: 8 early reflections, then a diffuse tail that falls\n// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls\n// absorb highs first. Generated once per context.\nconst ROOM_LENGTH = 0.3;\n// The convolver's equal-power normalization leaves the room about 15 dB\n// under the dry sound; this brings `room: 0.12` to a tail heard only as space.\nconst ROOM_GAIN = 6;\nconst roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\nfunction roomBuffer(context: BaseAudioContext) {\n  let buffer = roomBuffers.get(context);\n  if (!buffer) {\n    const rate = context.sampleRate;\n    const length = Math.ceil(ROOM_LENGTH * rate);\n    buffer = context.createBuffer(2, length, rate);\n    for (let channel = 0; channel < 2; channel++) {\n      const data = buffer.getChannelData(channel);\n      let smooth = 0;\n      for (let i = Math.floor(0.004 * rate); i < length; i++) {\n        const t = i / rate;\n        // One-pole low-pass whose cutoff closes over the tail.\n        const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;\n        smooth += brightness * (Math.random() * 2 - 1 - smooth);\n        data[i] = smooth * Math.exp(-t / 0.043);\n      }\n      for (let r = 0; r < 8; r++) {\n        const at = Math.floor((0.005 + Math.random() * 0.022) * rate);\n        data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);\n      }\n    }\n    roomBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// One convolver per output node, shared by every play: building one is the\n// expensive part, sending to it is cheap.\nconst rooms = new WeakMap<AudioNode, ConvolverNode>();\n\nfunction roomFor(context: BaseAudioContext, destination: AudioNode) {\n  let room = rooms.get(destination);\n  if (!room) {\n    room = context.createConvolver();\n    room.buffer = roomBuffer(context);\n    room.connect(destination);\n    rooms.set(destination, room);\n  }\n  return room;\n}\n\n/** A linear attack to `peak`, then an exponential fall to silence. */\nfunction envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {\n  param.setValueAtTime(0, start);\n  param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);\n  param.exponentialRampToValueAtTime(SILENT, start + attack + decay);\n}\n\nfunction voiceFor(target: SoundTarget, output: AudioNode): Voice {\n  const { context, when, pitch } = target;\n  // Partials above this only add hiss on small speakers, or alias near Nyquist.\n  const ceiling = Math.min(12000, context.sampleRate * 0.45);\n\n  const tone: Voice[\"tone\"] = ({ type = \"sine\", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const osc = context.createOscillator();\n    const amp = context.createGain();\n    osc.type = type;\n    const base = freq * pitch;\n    osc.frequency.setValueAtTime(base * (bend ?? 1), start);\n    if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);\n    if (to !== undefined) {\n      osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    osc.connect(amp).connect(output);\n    osc.start(start);\n    osc.stop(start + attack + decay + 0.02);\n  };\n\n  const noise: Voice[\"noise\"] = ({ filter = \"bandpass\", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const source = context.createBufferSource();\n    const shape = context.createBiquadFilter();\n    const amp = context.createGain();\n    source.buffer = noiseBuffer(context);\n    shape.type = filter;\n    shape.Q.value = q;\n    shape.frequency.setValueAtTime(freq * pitch, start);\n    if (to !== undefined) {\n      shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    source.connect(shape).connect(amp).connect(output);\n    // A random offset into the buffer keeps each burst a little different.\n    source.start(start, Math.random() * 0.5);\n    source.stop(start + attack + decay + 0.02);\n  };\n\n  return {\n    tone,\n    noise,\n    click({ freq, q = 2, at = 0, decay = 0.005, gain }) {\n      // A little spread on the band, so no two contacts are identical.\n      noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });\n    },\n    strike({ freq, material = \"plastic\", bend = 1.01, at = 0, decay, gain }) {\n      const { partials, damping } = typeof material === \"string\" ? MATERIALS[material] : material;\n      for (const [ratio, level] of partials) {\n        if (freq * ratio * pitch * bend > ceiling) continue;\n        tone({\n          // Real objects are never perfectly tuned; a hair of detune per partial.\n          freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),\n          bend,\n          at,\n          attack: 0.001,\n          decay: decay / ratio ** damping,\n          gain: gain * level,\n        });\n      }\n    },\n  };\n}\n\n/** Turns a recipe into a playable sound. */\nexport function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {\n  const render = (target: SoundTarget) => {\n    const { context, destination } = target;\n    const output = context.createGain();\n    output.gain.value = MASTER_GAIN * target.volume;\n    output.connect(destination);\n    if (room > 0) {\n      const send = context.createGain();\n      send.gain.value = room * ROOM_GAIN;\n      output.connect(send).connect(roomFor(context, destination));\n    }\n    build(voiceFor(target, output));\n  };\n\n  return {\n    name,\n    duration,\n    render,\n    play({ volume = 1, pitch = 1 } = {}) {\n      const context = getAudioContext();\n      if (!context || volume <= 0) return;\n      const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;\n      render({\n        context,\n        // The page-wide volume is applied there.\n        destination: audioOutput(context),\n        when: context.currentTime + 0.005,\n        volume,\n        pitch: pitch * spread,\n      });\n    },\n  };\n}\n"}]}