{"slug":"wheel-picker","name":"Wheel Picker","description":"iOS-style picker wheel: a 3D drum on native momentum scroll that snaps to the nearest notch, with wheel, drag and keyboard control. Composes side by side for date and time pickers, reduced-motion safe.","category":"motion","source_url":"https://beui.dev/r/wheel-picker/raw","detail_url":"https://beui.dev/r/wheel-picker","raw_url":"https://beui.dev/r/wheel-picker/raw","page_url":"https://beui.dev/components/motion/wheel-picker","markdown_url":"https://beui.dev/components/motion/wheel-picker.md","published_at":"2026-07-09","updated_at":"2026-07-09","dependencies":["clsx","motion","react","tailwind-merge"],"internal":["@/components/motion/switch","@/components/motion/wheel-picker","@/lib/tick-sound","@/lib/touch","@/lib/utils"],"files":[{"path":"components/motion/wheel-picker.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/motion/wheel-picker\n\nimport { useReducedMotion } from \"motion/react\";\nimport {\n  type KeyboardEvent,\n  type PointerEvent,\n  useCallback,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createTickPlayer } from \"@/lib/tick-sound\";\nimport {\n  capturePointer,\n  releasePointer,\n  TOUCH_GESTURE_CLASS,\n} from \"@/lib/touch\";\nimport { cn } from \"@/lib/utils\";\n\nexport type WheelPickerOption = string | { label: string; value: string };\n\nexport interface WheelPickerProps {\n  options: WheelPickerOption[];\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Rows visible through the window, odd. More = flatter curve. Default 5. */\n  visibleCount?: number;\n  /** Row height in px. Default 36. */\n  itemHeight?: number;\n  disabled?: boolean;\n  /** Play a short tick each time the selected value changes. Default false. */\n  sound?: boolean;\n  className?: string;\n  \"aria-label\"?: string;\n}\n\nconst DEG = Math.PI / 180;\n// Physics constants, tuned for an iOS-like flick rather than reused from the\n// shared spring tokens: the wheel coasts in whole-row units and springs to an\n// integer detent, which a layout spring can't express cleanly.\nconst DECELERATION = 0.00042; // rows per ms², how fast a flick bleeds off (lower = freer)\nconst MAX_VELOCITY = 0.18; // rows per ms, caps a hard fling\nconst VELOCITY_WINDOW = 90; // ms of recent drag to average a release velocity over\nconst WHEEL_SENS = 0.012; // rows per pixel of wheel delta\nconst WHEEL_SETTLE = 110; // ms of wheel idle before snapping to a row\nconst easeOutCubic = (p: number) => 1 - (1 - p) ** 3;\n// Overshoots the target by a few percent then settles — the little spring\n// bounce as a row snaps home. `BACK` sets how far it drifts past.\nconst BACK = 1.35;\nconst easeOutBack = (p: number) =>\n  1 + (BACK + 1) * (p - 1) ** 3 + BACK * (p - 1) ** 2;\n\nconst clamp = (v: number, lo: number, hi: number) =>\n  Math.max(lo, Math.min(v, hi));\n\nfunction optionValue(option: WheelPickerOption) {\n  return typeof option === \"string\" ? option : option.value;\n}\nfunction optionLabel(option: WheelPickerOption) {\n  return typeof option === \"string\" ? option : option.label;\n}\n\nexport function WheelPicker({\n  options,\n  value,\n  defaultValue,\n  onValueChange,\n  visibleCount = 5,\n  itemHeight = 36,\n  disabled = false,\n  sound = false,\n  className,\n  \"aria-label\": ariaLabel,\n}: WheelPickerProps) {\n  const reduce = useReducedMotion() ?? false;\n  const controlled = value !== undefined;\n  const last = options.length - 1;\n\n  const indexOf = useCallback(\n    (v: string | undefined) => {\n      const i = options.findIndex((o) => optionValue(o) === v);\n      return i < 0 ? 0 : i;\n    },\n    [options],\n  );\n\n  const [internal, setInternal] = useState(() => defaultValue ?? value);\n  const currentValue = controlled ? value : internal;\n  const [grabbing, setGrabbing] = useState(false);\n\n  // Cylinder geometry. Each row spans `itemAngle`; `radius` seats the rows on\n  // the drum; rows past `hideBeyond` sit behind the horizon and are dropped.\n  const { itemAngle, radius, height, hideBeyond } = useMemo(() => {\n    const rowsEachSide = Math.max(1, Math.floor(visibleCount / 2));\n    const cutoff = rowsEachSide + 1;\n    const angle = 90 / cutoff;\n    const r = itemHeight / Math.tan(angle * DEG);\n    return {\n      itemAngle: angle,\n      radius: r,\n      hideBeyond: cutoff,\n      height: Math.round(\n        2 * r * Math.sin(rowsEachSide * angle * DEG) + itemHeight,\n      ),\n    };\n  }, [visibleCount, itemHeight]);\n\n  const container = useRef<HTMLDivElement>(null);\n  const drumRef = useRef<HTMLUListElement>(null);\n  const bandRef = useRef<HTMLUListElement>(null);\n  // Scroll position measured in rows (a float index). One source of truth for\n  // both layers: the drum rotates by `itemAngle·scroll`, the crisp band slides\n  // by `itemHeight·scroll`.\n  const scroll = useRef(indexOf(currentValue));\n  const raf = useRef(0);\n  const emitted = useRef(currentValue);\n  const tickPlayer = useRef<ReturnType<typeof createTickPlayer> | null>(null);\n  const lastTick = useRef(indexOf(currentValue));\n\n  const paint = useCallback(\n    (s: number) => {\n      const drum = drumRef.current;\n      const band = bandRef.current;\n      if (drum) {\n        drum.style.transform = `translateZ(${-radius}px) rotateX(${itemAngle * s}deg)`;\n        for (const node of Array.from(drum.children)) {\n          const li = node as HTMLLIElement;\n          const i = Number(li.dataset.index);\n          const want = Math.abs(i - s) > hideBeyond ? \"hidden\" : \"visible\";\n          // Write only on change — an unconditional write every frame thrashes\n          // style recalc and is what made the drag feel draggy on mobile.\n          if (li.style.visibility !== want) li.style.visibility = want;\n        }\n      }\n      // The band is the SAME drum, clipped to the centre row — driven by the\n      // identical transform so the crisp copy sits exactly on the dimmed one,\n      // with no parallax ghost as rows cross the window. It needs the same\n      // horizon cull, or the row on the back of the drum bleeds into the front.\n      if (band) {\n        band.style.transform = `translateZ(${-radius}px) rotateX(${itemAngle * s}deg)`;\n        for (const node of Array.from(band.children)) {\n          const li = node as HTMLLIElement;\n          const i = Number(li.dataset.index);\n          const want = Math.abs(i - s) > hideBeyond ? \"hidden\" : \"visible\";\n          if (li.style.visibility !== want) li.style.visibility = want;\n        }\n      }\n    },\n    [radius, itemAngle, hideBeyond],\n  );\n\n  const getPlayer = useCallback(() => {\n    if (!tickPlayer.current) tickPlayer.current = createTickPlayer();\n    return tickPlayer.current;\n  }, []);\n\n  const emit = useCallback(\n    (i: number) => {\n      const v = optionValue(options[clamp(i, 0, last)]);\n      if (v === emitted.current) return;\n      emitted.current = v;\n      // Reduced motion has no drum/glide path to tick from — it's an\n      // onClick straight into emit, so the tick lives here instead.\n      if (sound && reduce) getPlayer().play();\n      if (!controlled) setInternal(v);\n      onValueChange?.(v);\n    },\n    [options, last, controlled, onValueChange, sound, reduce, getPlayer],\n  );\n\n  // Drum path: fires a tick whenever the nearest row changes, independent of\n  // `emit` (which only fires on settle during a glide/fling, not per row\n  // crossed). Gated on `!reduce` since the reduced render never calls this.\n  const maybeTick = useCallback(\n    (pos: number) => {\n      const row = clamp(Math.round(pos), 0, last);\n      if (!sound || reduce) {\n        lastTick.current = row;\n        return;\n      }\n      if (row === lastTick.current) return;\n      lastTick.current = row;\n      getPlayer().play();\n    },\n    [sound, reduce, last, getPlayer],\n  );\n\n  const stop = useCallback(() => cancelAnimationFrame(raf.current), []);\n\n  // Ease `scroll` from where it is to an integer detent over `duration`. The\n  // easing may overshoot (spring bounce) before it resolves exactly on `to`.\n  const glide = useCallback(\n    (\n      to: number,\n      duration: number,\n      ease: (p: number) => number = easeOutCubic,\n    ) => {\n      stop();\n      const from = scroll.current;\n      const dist = to - from;\n      if (!dist || duration <= 0) {\n        scroll.current = to;\n        paint(to);\n        maybeTick(to);\n        emit(to);\n        return;\n      }\n      const start = performance.now();\n      const tick = (now: number) => {\n        const p = (now - start) / duration;\n        if (p >= 1) {\n          scroll.current = to;\n          paint(to);\n          maybeTick(to);\n          emit(to);\n          return;\n        }\n        scroll.current = from + dist * ease(p);\n        paint(scroll.current);\n        maybeTick(scroll.current);\n        raf.current = requestAnimationFrame(tick);\n      };\n      raf.current = requestAnimationFrame(tick);\n    },\n    [stop, paint, emit, maybeTick],\n  );\n\n  // Project where a flick of `velocity` (rows/ms) coasts to, snap to a row.\n  const fling = useCallback(\n    (velocity: number) => {\n      const from = scroll.current;\n      if (from < 0 || from > last) {\n        glide(clamp(Math.round(from), 0, last), 260); // rubber-band back\n        return;\n      }\n      const dir = Math.sign(velocity);\n      const coast = ((velocity * velocity) / (2 * DECELERATION)) * dir;\n      const to = clamp(Math.round(from + coast), 0, last);\n      // Long, spring-tipped settle so a hard flick reads as free momentum\n      // coasting to rest with a gentle bounce, never a clipped stop.\n      const duration = clamp(\n        Math.sqrt(Math.abs(to - from)) * 300 + 240,\n        280,\n        1700,\n      );\n      glide(to, duration, easeOutBack);\n    },\n    [glide, last],\n  );\n\n  const step = useCallback(\n    (by: number) =>\n      glide(clamp(Math.round(scroll.current) + by, 0, last), 300, easeOutBack),\n    [glide, last],\n  );\n\n  // Drag: track recent points for a release velocity; rubber-band past the ends.\n  const drag = useRef<{\n    y: number;\n    scroll: number;\n    pts: [number, number][];\n  } | null>(null);\n  // Coalesce touch/pointer moves to one paint per animation frame — raw move\n  // events fire several times per frame (and off-frame) on high-refresh\n  // screens, and painting each one is what made the drag feel choppy.\n  const dragFrame = useRef(0);\n  const latestY = useRef(0);\n  // Shared drag core, driven by a Y coordinate from either a mouse pointer or a\n  // native touch. Touch is bound with non-passive listeners in the effect below\n  // so the move can preventDefault the page scroll — React's synthetic touch\n  // events are passive and can't, which is why finger-drag did nothing on\n  // mobile.\n  const beginDrag = useCallback(\n    (y: number) => {\n      stop();\n      if (sound) getPlayer().prepare();\n      setGrabbing(true);\n      drag.current = {\n        y,\n        scroll: scroll.current,\n        pts: [[y, performance.now()]],\n      };\n    },\n    [stop, sound, getPlayer],\n  );\n  const moveDrag = useCallback(\n    (y: number) => {\n      const d = drag.current;\n      if (!d) return;\n      // Record every sample for an accurate release velocity, but only render\n      // the newest position once per frame.\n      latestY.current = y;\n      d.pts.push([y, performance.now()]);\n      if (d.pts.length > 8) d.pts.shift();\n      if (dragFrame.current) return;\n      dragFrame.current = requestAnimationFrame(() => {\n        dragFrame.current = 0;\n        const dd = drag.current;\n        if (!dd) return;\n        let next = dd.scroll + (dd.y - latestY.current) / itemHeight;\n        if (next < 0) next *= 0.3;\n        else if (next > last) next = last + (next - last) * 0.3;\n        scroll.current = next;\n        paint(next);\n        maybeTick(next);\n        emit(Math.round(clamp(next, 0, last)));\n      });\n    },\n    [itemHeight, last, paint, emit, maybeTick],\n  );\n  const endDrag = useCallback(() => {\n    const d = drag.current;\n    if (!d) return;\n    if (dragFrame.current) {\n      cancelAnimationFrame(dragFrame.current);\n      dragFrame.current = 0;\n    }\n    drag.current = null;\n    setGrabbing(false);\n    // Average velocity over the last `VELOCITY_WINDOW` ms of movement rather\n    // than the final two samples — a single noisy frame otherwise makes an\n    // even flick feel like it caught or slipped.\n    const pts = d.pts;\n    let v = 0;\n    if (pts.length > 1) {\n      const latest = pts[pts.length - 1];\n      let ref = pts[0];\n      for (const p of pts) {\n        if (latest[1] - p[1] <= VELOCITY_WINDOW) {\n          ref = p;\n          break;\n        }\n      }\n      const dt = latest[1] - ref[1];\n      if (dt > 0) {\n        const raw = (ref[0] - latest[0]) / itemHeight / dt;\n        v = clamp(raw, -MAX_VELOCITY, MAX_VELOCITY);\n      }\n    }\n    fling(v);\n  }, [itemHeight, fling]);\n\n  // Mouse / pen only — touch runs through the native listeners in the effect.\n  const onPointerDown = useCallback(\n    (event: PointerEvent<HTMLDivElement>) => {\n      if (disabled || reduce || event.pointerType === \"touch\") return;\n      beginDrag(event.clientY);\n      capturePointer(event.currentTarget, event.pointerId);\n    },\n    [disabled, reduce, beginDrag],\n  );\n  const onPointerMove = useCallback(\n    (event: PointerEvent<HTMLDivElement>) => {\n      if (event.pointerType === \"touch\") return;\n      moveDrag(event.clientY);\n    },\n    [moveDrag],\n  );\n  const onPointerUp = useCallback(\n    (event: PointerEvent<HTMLDivElement>) => {\n      if (event.pointerType === \"touch\") return;\n      // Also the pointercancel handler, where the capture is already gone —\n      // an unguarded release throws there and the drum never settles.\n      releasePointer(event.currentTarget, event.pointerId);\n      endDrag();\n    },\n    [endDrag],\n  );\n\n  // Wheel drives `scroll` continuously — like a drag — then snaps once it goes\n  // idle. Firing a fresh eased step per notch instead stacks overlapping\n  // animations that keep interrupting each other, which read as lag.\n  const wheelSnap = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const onWheel = useCallback(\n    (event: globalThis.WheelEvent) => {\n      // Native (non-passive) so preventDefault actually stops the page from\n      // scrolling behind the wheel — React's synthetic wheel listener is\n      // passive, so a handler on the element cannot cancel the scroll.\n      if (disabled || reduce) return;\n      event.preventDefault();\n      if (sound) getPlayer().prepare();\n      stop();\n      const px = event.deltaMode === 1 ? event.deltaY * 16 : event.deltaY;\n      const next = clamp(scroll.current + px * WHEEL_SENS, 0, last);\n      scroll.current = next;\n      paint(next);\n      maybeTick(next);\n      emit(Math.round(next));\n      if (wheelSnap.current) clearTimeout(wheelSnap.current);\n      wheelSnap.current = setTimeout(() => {\n        glide(clamp(Math.round(scroll.current), 0, last), 240, easeOutBack);\n      }, WHEEL_SETTLE);\n    },\n    [\n      disabled,\n      reduce,\n      sound,\n      last,\n      paint,\n      emit,\n      stop,\n      glide,\n      maybeTick,\n      getPlayer,\n    ],\n  );\n\n  const onKeyDown = useCallback(\n    (event: KeyboardEvent<HTMLDivElement>) => {\n      if (disabled) return;\n      const at = Math.round(scroll.current);\n      const map: Record<string, number> = {\n        ArrowUp: -1,\n        ArrowDown: 1,\n        Home: -at,\n        End: last - at,\n      };\n      if (event.key in map) {\n        event.preventDefault();\n        if (sound) getPlayer().prepare();\n        step(map[event.key]);\n      }\n    },\n    [disabled, sound, last, step, getPlayer],\n  );\n\n  // Paint the starting frame, and follow controlled/value changes from outside\n  // unless a gesture is mid-flight.\n  useEffect(() => {\n    if (drag.current) return;\n    const target = indexOf(currentValue);\n    emitted.current = currentValue;\n    if (Math.abs(Math.round(scroll.current) - target) < 0.001) {\n      paint(scroll.current);\n      return;\n    }\n    glide(target, 260);\n  }, [currentValue, indexOf, paint, glide]);\n\n  useEffect(\n    () => () => {\n      cancelAnimationFrame(raf.current);\n      cancelAnimationFrame(dragFrame.current);\n      if (wheelSnap.current) clearTimeout(wheelSnap.current);\n      tickPlayer.current?.dispose();\n    },\n    [],\n  );\n\n  // Native touch + wheel listeners, bound non-passively so touchmove and wheel\n  // can block the page from scrolling while the wheel spins. React's synthetic\n  // touch/wheel handlers are passive, so preventDefault there is a no-op and the\n  // gesture scrolls the page instead of driving the drum.\n  useEffect(() => {\n    const el = container.current;\n    if (!el || reduce || disabled) return;\n    const onStart = (e: TouchEvent) => {\n      const t = e.touches[0];\n      if (t) beginDrag(t.clientY);\n    };\n    const onMove = (e: TouchEvent) => {\n      const t = e.touches[0];\n      if (!t || !drag.current) return;\n      e.preventDefault();\n      moveDrag(t.clientY);\n    };\n    const onEnd = () => endDrag();\n    el.addEventListener(\"touchstart\", onStart, { passive: true });\n    el.addEventListener(\"touchmove\", onMove, { passive: false });\n    el.addEventListener(\"touchend\", onEnd);\n    el.addEventListener(\"touchcancel\", onEnd);\n    el.addEventListener(\"wheel\", onWheel, { passive: false });\n    return () => {\n      el.removeEventListener(\"touchstart\", onStart);\n      el.removeEventListener(\"touchmove\", onMove);\n      el.removeEventListener(\"touchend\", onEnd);\n      el.removeEventListener(\"touchcancel\", onEnd);\n      el.removeEventListener(\"wheel\", onWheel);\n    };\n  }, [reduce, disabled, beginDrag, moveDrag, endDrag, onWheel]);\n\n  const maskFade =\n    \"[mask-image:linear-gradient(to_bottom,transparent,#000_22%,#000_78%,transparent)]\";\n\n  if (reduce) {\n    const pad = (height - itemHeight) / 2;\n    return (\n      <div\n        className={cn(\n          \"relative overflow-hidden rounded-2xl border border-border bg-card\",\n          disabled && \"pointer-events-none opacity-50\",\n          className,\n        )}\n        style={{ height }}\n      >\n        <div\n          className=\"pointer-events-none absolute inset-x-0 top-1/2 z-10 -translate-y-1/2 border-border border-y bg-foreground/[0.04]\"\n          style={{ height: itemHeight }}\n        />\n        <ul\n          className={cn(\n            \"h-full snap-y snap-mandatory overflow-y-auto scroll-smooth [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\",\n            maskFade,\n          )}\n          style={{ paddingTop: pad, paddingBottom: pad }}\n        >\n          {options.map((option) => {\n            const v = optionValue(option);\n            return (\n              <li key={v} className=\"snap-center\">\n                <button\n                  type=\"button\"\n                  disabled={disabled}\n                  onClick={() => emit(options.indexOf(option))}\n                  className={cn(\n                    \"flex w-full items-center justify-center font-medium\",\n                    v === currentValue\n                      ? \"text-foreground\"\n                      : \"text-muted-foreground\",\n                  )}\n                  style={{ height: itemHeight }}\n                >\n                  {optionLabel(option)}\n                </button>\n              </li>\n            );\n          })}\n        </ul>\n      </div>\n    );\n  }\n\n  return (\n    <div\n      ref={container}\n      role=\"listbox\"\n      aria-label={ariaLabel}\n      tabIndex={disabled ? -1 : 0}\n      onKeyDown={onKeyDown}\n      onPointerDown={onPointerDown}\n      onPointerMove={onPointerMove}\n      onPointerUp={onPointerUp}\n      onPointerCancel={onPointerUp}\n      className={cn(\n        \"relative touch-none overflow-hidden rounded-2xl border border-border bg-card outline-none focus-visible:ring-2 focus-visible:ring-foreground/20\",\n        // The drum owns the whole gesture; iOS must not open its callout or\n        // start a drag out of the same press and cancel ours.\n        TOUCH_GESTURE_CLASS,\n        grabbing ? \"cursor-grabbing\" : \"cursor-grab\",\n        disabled && \"pointer-events-none opacity-50\",\n        maskFade,\n        className,\n      )}\n      style={{ height, perspective: 1000 }}\n    >\n      {/* Curved drum of dimmed rows. */}\n      <ul\n        ref={drumRef}\n        aria-hidden\n        className=\"absolute inset-x-0 top-1/2 m-0 h-0 list-none p-0 [backface-visibility:hidden] [transform-style:preserve-3d] [will-change:transform]\"\n      >\n        {options.map((option, i) => (\n          <li\n            key={optionValue(option)}\n            data-index={i}\n            className=\"absolute inset-x-0 flex items-center justify-center font-medium text-muted-foreground\"\n            style={{\n              top: -itemHeight / 2,\n              height: itemHeight,\n              transform: `rotateX(${-itemAngle * i}deg) translateZ(${radius}px)`,\n            }}\n          >\n            {optionLabel(option)}\n          </li>\n        ))}\n      </ul>\n\n      {/* Center band: the very same drum, clipped to one row and drawn crisp.\n          Its own perspective, centred on the container middle, matches the main\n          drum's projection so the two copies register exactly. */}\n      <div\n        className=\"pointer-events-none absolute inset-x-0 top-1/2 z-10 -translate-y-1/2 overflow-hidden rounded-md bg-foreground/[0.04]\"\n        style={{ height: itemHeight, perspective: 1000 }}\n      >\n        <ul\n          ref={bandRef}\n          aria-hidden\n          className=\"absolute inset-x-0 top-1/2 m-0 h-0 list-none p-0 [backface-visibility:hidden] [transform-style:preserve-3d] [will-change:transform]\"\n        >\n          {options.map((option, i) => (\n            <li\n              key={optionValue(option)}\n              data-index={i}\n              className=\"absolute inset-x-0 flex items-center justify-center font-medium text-foreground\"\n              style={{\n                top: -itemHeight / 2,\n                height: itemHeight,\n                transform: `rotateX(${-itemAngle * i}deg) translateZ(${radius}px)`,\n              }}\n            >\n              {optionLabel(option)}\n            </li>\n          ))}\n        </ul>\n      </div>\n    </div>\n  );\n}\n"},{"path":"lib/tick-sound.ts","type":"util","content":"// Synthesizes a short, dry mechanical detent for gesture feedback (e.g. the\n// WheelPicker row-cross click) entirely at runtime. Several inharmonic modes\n// make it read as a tiny physical impact instead of an oscillator beep, while\n// the high-passed transient gives it definition through phone speakers.\n\nconst DURATION = 0.016; // seconds, short enough to stay distinct during a fling\nconst MASTER_GAIN = 0.055;\n\nconst MODES = [\n  { frequency: 980, decay: 0.0038, gain: 0.5, phase: 0 },\n  { frequency: 1820, decay: 0.0024, gain: 0.3, phase: 0.65 },\n  { frequency: 3160, decay: 0.00115, gain: 0.12, phase: 1.3 },\n] as const;\n\ntype AudioContextCtor = typeof AudioContext;\n\nfunction getAudioContextCtor(): AudioContextCtor | undefined {\n  if (typeof window === \"undefined\") return undefined;\n  return (\n    window.AudioContext ??\n    (window as unknown as { webkitAudioContext?: AudioContextCtor })\n      .webkitAudioContext\n  );\n}\n\n// One shared context/buffer/gain for the whole page, ref-counted across every\n// `createTickPlayer()` caller. Components like WheelPicker commonly compose\n// several side by side (a date made of month/day/year drums) — giving each\n// its own AudioContext would waste resources and risk hitting a browser's cap\n// on concurrent contexts. The context only closes once every consumer that\n// created a player has called `dispose()`.\nlet ctx: AudioContext | null = null;\nlet masterGain: GainNode | null = null;\nlet clickBuffer: AudioBuffer | null = null;\nlet consumers = 0;\n\nfunction buildClickBuffer(context: AudioContext): AudioBuffer {\n  const sampleRate = context.sampleRate;\n  const length = Math.ceil(DURATION * sampleRate);\n  const buffer = context.createBuffer(1, length, sampleRate);\n  const data = buffer.getChannelData(0);\n\n  let peak = 0;\n  let previousNoise = 0;\n  for (let i = 0; i < length; i++) {\n    const t = i / sampleRate;\n    const attack = Math.min(1, t / 0.00012);\n    const fadeOut = Math.min(1, (DURATION - t) / 0.001);\n    let resonance = 0;\n    for (const mode of MODES) {\n      resonance +=\n        Math.sin(2 * Math.PI * mode.frequency * t + mode.phase) *\n        Math.exp(-t / mode.decay) *\n        mode.gain;\n    }\n\n    // Differencing consecutive noise samples removes the low, papery part of\n    // white noise and leaves only a tiny impact at the front of the sound.\n    const noise = Math.random() * 2 - 1;\n    const transient =\n      (noise - previousNoise) * Math.exp(-t / 0.00038) * 0.035;\n    previousNoise = noise;\n\n    data[i] = (resonance + transient) * attack * fadeOut;\n    peak = Math.max(peak, Math.abs(data[i]));\n  }\n  if (peak > 0) {\n    const norm = 0.9 / peak;\n    for (let i = 0; i < length; i++) data[i] *= norm;\n  }\n\n  return buffer;\n}\n\nfunction ensureContext() {\n  if (ctx) return;\n  const Ctor = getAudioContextCtor();\n  if (!Ctor) return;\n  ctx = new Ctor();\n  masterGain = ctx.createGain();\n  masterGain.gain.value = MASTER_GAIN;\n  masterGain.connect(ctx.destination);\n  clickBuffer = buildClickBuffer(ctx);\n}\n\nfunction prepareContext() {\n  ensureContext();\n  if (ctx?.state === \"suspended\") {\n    // Browsers may reject this when it is not called from a trusted gesture.\n    // Pointer, touch, wheel and keyboard entry points call `prepare()` first;\n    // this repeat attempt keeps direct `play()` calls safe as well.\n    void ctx.resume().catch(() => undefined);\n  }\n}\n\ninterface TickPlayer {\n  prepare: () => void;\n  play: () => void;\n  dispose: () => void;\n}\n\n/**\n * Lazily-initialized tick player. No `AudioContext` is created until the first\n * `prepare()` or `play()` call anywhere on the page. Every player shares the\n * same context/buffer, ref-counted so `dispose()` only tears it down once the\n * last consumer is gone. Safe during SSR or in browsers without Web Audio:\n * `prepare()` and `play()` become silent no-ops.\n */\nexport function createTickPlayer(): TickPlayer {\n  consumers++;\n  let disposed = false;\n  let activeSource: AudioBufferSourceNode | null = null;\n\n  return {\n    prepare() {\n      if (disposed) return;\n      prepareContext();\n    },\n    play() {\n      if (disposed) return;\n      prepareContext();\n      if (!ctx || !masterGain || !clickBuffer) return;\n      // A fast fling can cross rows more quickly than the tail of a tick.\n      // Cutting that tail keeps the feedback dry instead of stacking into a\n      // louder metallic ring.\n      activeSource?.stop();\n      const source = ctx.createBufferSource();\n      source.buffer = clickBuffer;\n      source.connect(masterGain);\n      source.onended = () => {\n        source.disconnect();\n        if (activeSource === source) activeSource = null;\n      };\n      activeSource = source;\n      source.start();\n    },\n    dispose() {\n      if (disposed) return;\n      disposed = true;\n      activeSource?.stop();\n      activeSource = null;\n      consumers = Math.max(0, consumers - 1);\n      if (consumers === 0 && ctx) {\n        ctx.close();\n        ctx = null;\n        masterGain = null;\n        clickBuffer = null;\n      }\n    },\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/wheel-picker.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { Switch } from \"@/components/motion/switch\";\nimport { WheelPicker } from \"@/components/motion/wheel-picker\";\n\nconst MONTHS = [\n  \"January\",\n  \"February\",\n  \"March\",\n  \"April\",\n  \"May\",\n  \"June\",\n  \"July\",\n  \"August\",\n  \"September\",\n  \"October\",\n  \"November\",\n  \"December\",\n];\nconst YEARS = Array.from({ length: 60 }, (_, i) => String(1980 + i));\n\nfunction daysIn(month: number, year: number) {\n  return new Date(year, month + 1, 0).getDate();\n}\n\nexport function WheelPickerPreview() {\n  const [month, setMonth] = useState(\"June\");\n  const [year, setYear] = useState(\"2004\");\n  const [day, setDay] = useState(\"9\");\n  const [sound, setSound] = useState(false);\n\n  const monthIndex = MONTHS.indexOf(month);\n  const dayCount = daysIn(monthIndex, Number(year));\n  const days = Array.from({ length: dayCount }, (_, i) => String(i + 1));\n\n  // A short month or a non-leap February can strand the day past the end —\n  // pull it back to the last valid day.\n  useEffect(() => {\n    if (Number(day) > dayCount) setDay(String(dayCount));\n  }, [day, dayCount]);\n\n  return (\n    <div className=\"flex flex-col items-center gap-4\">\n      <span className=\"text-sm text-muted-foreground\">\n        Born{\" \"}\n        <span className=\"font-medium text-foreground tabular-nums\">\n          {month} {day}, {year}\n        </span>\n      </span>\n      <div className=\"flex items-stretch gap-1 rounded-3xl border border-border bg-background p-2\">\n        <WheelPicker\n          options={MONTHS}\n          value={month}\n          onValueChange={setMonth}\n          className=\"w-32 border-0 bg-transparent\"\n          visibleCount={7}\n          itemHeight={42}\n          sound={sound}\n          aria-label=\"Month\"\n        />\n        <WheelPicker\n          options={days}\n          value={day}\n          onValueChange={setDay}\n          className=\"w-14 border-0 bg-transparent\"\n          visibleCount={7}\n          itemHeight={42}\n          sound={sound}\n          aria-label=\"Day\"\n        />\n        <WheelPicker\n          options={YEARS}\n          value={year}\n          onValueChange={setYear}\n          className=\"w-20 border-0 bg-transparent\"\n          visibleCount={7}\n          itemHeight={42}\n          sound={sound}\n          aria-label=\"Year\"\n        />\n      </div>\n      <Switch\n        checked={sound}\n        onCheckedChange={setSound}\n        label=\"Tick sound\"\n        className=\"origin-left scale-[0.85] [&_label]:text-sm\"\n      />\n    </div>\n  );\n}\n"},{"path":"components/motion/switch.tsx","type":"util","content":"\"use client\";\n\nimport { animate, motion, MotionConfig, useReducedMotion } from \"motion/react\";\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\n// Heavy, deliberate thumb — high mass keeps the travel weighty without wobble.\nconst THUMB_SPRING = { type: \"spring\", stiffness: 800, damping: 80, mass: 4 } as const;\n\nexport interface SwitchProps {\n  checked: boolean;\n  onCheckedChange: (checked: boolean) => void;\n  disabled?: boolean;\n  label?: string;\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function Switch({\n  checked,\n  onCheckedChange,\n  disabled,\n  label,\n  ariaLabel,\n  className,\n}: SwitchProps) {\n  const id = useId();\n  const thumbRef = useRef<HTMLDivElement>(null);\n  const reduce = useReducedMotion();\n  const [isPressed, setIsPressed] = useState(false);\n  const [isPointer, setIsPointer] = useState(false);\n\n  // Disabled shake feedback when pressed.\n  useEffect(() => {\n    if (!thumbRef.current || reduce) return;\n    if (disabled && isPressed) {\n      animate(\n        thumbRef.current,\n        { x: [0, -2, 2, -1, 0] },\n        { delay: 0.2, duration: 0.6 },\n      );\n    }\n  }, [disabled, isPressed, reduce]);\n\n  const squish = !disabled && isPointer && isPressed && !reduce;\n\n  return (\n    <MotionConfig transition={reduce ? { duration: 0 } : THUMB_SPRING}>\n      <span className={cn(\"inline-flex items-center gap-3\", className)}>\n        <motion.button\n          id={id}\n          type=\"button\"\n          role=\"switch\"\n          aria-checked={checked}\n          aria-label={ariaLabel}\n          disabled={disabled}\n          onClick={() => !disabled && onCheckedChange(!checked)}\n          onPointerDown={(e) => {\n            setIsPressed(true);\n            setIsPointer(e.type.startsWith(\"pointer\"));\n          }}\n          onPointerUp={() => setIsPressed(false)}\n          onPointerLeave={() => setIsPressed(false)}\n          initial={false}\n          data-state={checked ? \"checked\" : \"unchecked\"}\n          className={cn(\n            \"group peer inline-flex h-7 w-12 shrink-0 cursor-pointer items-center px-1 rounded-full outline-none transition-colors duration-200\",\n            \"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n            \"disabled:cursor-not-allowed disabled:opacity-60\",\n            checked ? \"justify-end bg-primary\" : \"justify-start bg-muted-foreground/60\",\n          )}\n        >\n          <motion.div\n            ref={thumbRef}\n            layout\n            animate={{ scale: squish ? 0.9 : 1 }}\n            className=\"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-md\"\n          >\n            {/* Stretch toward the destination while active. */}\n            <div\n              className={cn(\n                \"size-5\",\n                squish && (checked ? \"ml-1\" : \"mr-1\"),\n              )}\n            />\n          </motion.div>\n        </motion.button>\n        {label ? (\n          <label htmlFor={id} className=\"cursor-pointer text-sm text-foreground\">\n            {label}\n          </label>\n        ) : null}\n      </span>\n    </MotionConfig>\n  );\n}\n"}]}