{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"wheel-picker","type":"registry:component","title":"Wheel picker","description":"Spins through the hours on a curved drum, just like iOS.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/wheel-picker.tsx","type":"registry:component","content":"\"use client\";\n\nimport { memo, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport { animate } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport type Time = { hour: number; minute: number; period: \"AM\" | \"PM\" };\n\nconst ROW = 40;\n// Five and a half rows: two full rows either side of the selection plus the\n// foreshortened edge of a third, which is what sells the curve.\nconst HEIGHT = 220;\nconst PAD = (HEIGHT - ROW) / 2;\n// Each row sits this far around the drum, so the fifth row away reaches 90deg\n// and turns edge-on right as it leaves the column.\nconst STEP = 18;\n// The drum radius whose arc between neighbours is exactly one row, so rows\n// near the centre keep their spacing and only the far ones bunch up.\nconst RADIUS = ROW / ((STEP * Math.PI) / 180);\n// Apple's projection constant, a touch below scroll's 0.998 so a flick\n// travels a handful of rows rather than the whole column.\nconst DECELERATION = 0.995;\n// Critically damped: a wheel that overshoots would flash the wrong value.\nconst GLIDE = { type: \"spring\", visualDuration: 0.35, bounce: 0 } as const;\n// Past this many px a mouse press becomes a drag rather than a click.\nconst DRAG_SLOP = 4;\n\nconst HOURS = Array.from({ length: 12 }, (_, i) => String(i + 1));\nconst MINUTES = Array.from({ length: 60 }, (_, i) => String(i).padStart(2, \"0\"));\nconst PERIODS = [\"AM\", \"PM\"];\n\nconst clamp = (v: number, lo: number, hi: number) => Math.min(Math.max(v, lo), hi);\n\nexport function WheelPicker({\n  value,\n  onChange,\n  className,\n}: {\n  value: Time;\n  onChange: (value: Time) => void;\n  className?: string;\n}) {\n  const minute = String(value.minute).padStart(2, \"0\");\n  return (\n    <div\n      role=\"group\"\n      aria-label=\"Time\"\n      className={cn(\n        \"flex w-[min(360px,100%)] flex-col items-center gap-5 rounded-[28px] bg-background px-4 pt-4 pb-6 shadow-raised\",\n        className,\n      )}\n    >\n      <div className=\"relative flex w-full justify-center gap-2\">\n        {/* Behind the columns, which are transparent, so the middle row\n            reads as sitting on the band. */}\n        <div\n          aria-hidden\n          className=\"absolute inset-x-0 top-1/2 h-10 -translate-y-1/2 rounded-[12px] bg-muted\"\n        />\n        <Column\n          label=\"Hour\"\n          options={HOURS}\n          index={value.hour - 1}\n          onIndexChange={(i) => onChange({ ...value, hour: i + 1 })}\n        />\n        <Column\n          label=\"Minute\"\n          options={MINUTES}\n          index={value.minute}\n          onIndexChange={(i) => onChange({ ...value, minute: i })}\n        />\n        <Column\n          label=\"AM or PM\"\n          options={PERIODS}\n          index={PERIODS.indexOf(value.period)}\n          onIndexChange={(i) =>\n            onChange({ ...value, period: PERIODS[i] as Time[\"period\"] })\n          }\n        />\n      </div>\n      <output\n        aria-label=\"Selected time\"\n        className=\"text-5xl font-semibold tracking-[-0.03em] text-foreground tabular-nums\"\n      >\n        {value.hour}:{minute}\n        <span className=\"ml-2 text-2xl font-medium tracking-normal text-muted-foreground\">\n          {value.period}\n        </span>\n      </output>\n    </div>\n  );\n}\n\ntype Glide = ReturnType<typeof animate>;\n\nconst Column = memo(function Column({\n  label,\n  options,\n  index,\n  onIndexChange,\n}: {\n  label: string;\n  options: string[];\n  index: number;\n  onIndexChange: (index: number) => void;\n}) {\n  const reduceMotion = useReducedMotion();\n  const ref = useRef<HTMLDivElement>(null);\n  // The row under the band right now, written per frame without rendering.\n  const current = useRef(index);\n  // Where a glide in flight will land, so repeated key presses stack up.\n  const goal = useRef(index);\n  const glide = useRef<Glide | null>(null);\n  const report = useRef(onIndexChange);\n  const drag = useRef<{\n    y: number;\n    top: number;\n    active: boolean;\n    samples: { y: number; t: number }[];\n  } | null>(null);\n  const suppressClick = useRef(false);\n  const last = options.length - 1;\n\n  useEffect(() => {\n    report.current = onIndexChange;\n  });\n\n  // Rows are painted straight to the DOM from scroll position, so wheel,\n  // trackpad and touch momentum stay fully native and React never renders\n  // per frame. Only rows near the band are touched each frame.\n  useLayoutEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const rows = el.children as HTMLCollectionOf<HTMLElement>;\n    el.scrollTop = current.current * ROW;\n    let lo = 0;\n    let hi = rows.length - 1;\n    let frame = 0;\n\n    const paint = () => {\n      frame = 0;\n      const pos = el.scrollTop / ROW;\n      const nextLo = Math.max(0, Math.floor(pos) - 6);\n      const nextHi = Math.min(rows.length - 1, Math.ceil(pos) + 6);\n      for (let i = Math.min(lo, nextLo); i <= Math.max(hi, nextHi); i++) {\n        const style = rows[i].style;\n        const offset = i - pos;\n        const angle = offset * STEP;\n        if (Math.abs(angle) >= 90) {\n          style.opacity = \"0\";\n          style.transform = \"\";\n          continue;\n        }\n        const rad = (angle * Math.PI) / 180;\n        // Moves each row from its flat scroll position onto the cylinder.\n        const dy = RADIUS * Math.sin(rad) - offset * ROW;\n        const dz = RADIUS * (Math.cos(rad) - 1);\n        style.transform = `translate3d(0, ${dy}px, ${dz}px) rotateX(${-angle}deg)`;\n        style.opacity = String(Math.max(1 - Math.abs(offset) * 0.2, 0));\n      }\n      lo = nextLo;\n      hi = nextHi;\n      const centred = clamp(Math.round(pos), 0, rows.length - 1);\n      if (centred !== current.current) {\n        current.current = centred;\n        report.current(centred);\n      }\n    };\n\n    paint();\n    const onScroll = () => {\n      if (!frame) frame = requestAnimationFrame(paint);\n    };\n    el.addEventListener(\"scroll\", onScroll, { passive: true });\n    return () => {\n      el.removeEventListener(\"scroll\", onScroll);\n      cancelAnimationFrame(frame);\n      glide.current?.stop();\n    };\n  }, [options]);\n\n  const restoreSnap = () => {\n    if (ref.current) ref.current.style.scrollSnapType = \"\";\n  };\n\n  const interrupt = () => {\n    if (!glide.current) return;\n    glide.current.stop();\n    glide.current = null;\n    restoreSnap();\n  };\n\n  // Snapping is switched off while we drive scrollTop ourselves, otherwise\n  // the browser would re-snap every frame of the spring.\n  const glideTo = (target: number, velocity = 0) => {\n    const el = ref.current;\n    if (!el) return;\n    glide.current?.stop();\n    const row = clamp(target, 0, last);\n    goal.current = row;\n    if (reduceMotion) {\n      glide.current = null;\n      restoreSnap();\n      el.scrollTop = row * ROW;\n      return;\n    }\n    el.style.scrollSnapType = \"none\";\n    glide.current = animate(el.scrollTop, row * ROW, {\n      ...GLIDE,\n      velocity,\n      onUpdate: (v) => {\n        el.scrollTop = v;\n      },\n      onComplete: () => {\n        glide.current = null;\n        restoreSnap();\n      },\n    });\n  };\n\n  // A parent changing the value from outside glides there too.\n  useEffect(() => {\n    if (index !== current.current && index !== goal.current) glideTo(index);\n  });\n\n  const rows = useMemo(\n    () =>\n      options.map((option, i) => (\n        <div\n          key={option}\n          data-index={i}\n          className=\"flex h-10 shrink-0 snap-center items-center justify-center text-[22px] font-medium text-foreground tabular-nums opacity-0 backface-hidden\"\n        >\n          {option}\n        </div>\n      )),\n    [options],\n  );\n\n  return (\n    <div\n      ref={ref}\n      role=\"spinbutton\"\n      tabIndex={0}\n      aria-label={label}\n      aria-valuemin={0}\n      aria-valuemax={last}\n      aria-valuenow={index}\n      aria-valuetext={options[index]}\n      style={{ height: HEIGHT, paddingBlock: PAD }}\n      className=\"relative w-[72px] cursor-grab snap-y snap-mandatory overflow-y-auto overscroll-contain rounded-[12px] outline-hidden select-none [perspective:520px] [scrollbar-width:none] focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:cursor-grabbing [&::-webkit-scrollbar]:hidden\"\n      onWheel={interrupt}\n      onTouchStart={interrupt}\n      onPointerDown={(e) => {\n        // Touch and pen already scroll natively; only a mouse needs help.\n        if (e.pointerType !== \"mouse\" || e.button !== 0) return;\n        interrupt();\n        suppressClick.current = false;\n        drag.current = {\n          y: e.clientY,\n          top: e.currentTarget.scrollTop,\n          active: false,\n          samples: [{ y: e.clientY, t: e.timeStamp }],\n        };\n      }}\n      onPointerMove={(e) => {\n        const d = drag.current;\n        if (!d) return;\n        const dy = e.clientY - d.y;\n        if (!d.active) {\n          if (Math.abs(dy) < DRAG_SLOP) return;\n          d.active = true;\n          suppressClick.current = true;\n          e.currentTarget.setPointerCapture(e.pointerId);\n          e.currentTarget.style.scrollSnapType = \"none\";\n        }\n        e.currentTarget.scrollTop = d.top - dy;\n        d.samples.push({ y: e.clientY, t: e.timeStamp });\n        // Only the last 100ms say how fast the hand is moving now.\n        while (d.samples.length > 2 && e.timeStamp - d.samples[0].t > 100)\n          d.samples.shift();\n      }}\n      onPointerUp={(e) => {\n        const d = drag.current;\n        drag.current = null;\n        if (!d?.active) return;\n        const first = d.samples[0];\n        const end = d.samples[d.samples.length - 1];\n        const dt = (end.t - first.t) / 1000;\n        // Dragging down scrolls up, so the scroll velocity is inverted.\n        const velocity = dt > 0 ? -(end.y - first.y) / dt : 0;\n        const projected =\n          e.currentTarget.scrollTop +\n          ((velocity / 1000) * DECELERATION) / (1 - DECELERATION);\n        glideTo(Math.round(projected / ROW), velocity);\n      }}\n      onPointerCancel={() => {\n        drag.current = null;\n        restoreSnap();\n      }}\n      onClick={(e) => {\n        if (suppressClick.current) {\n          suppressClick.current = false;\n          return;\n        }\n        const row = (e.target as HTMLElement).closest<HTMLElement>(\"[data-index]\");\n        if (row) glideTo(Number(row.dataset.index));\n      }}\n      onKeyDown={(e) => {\n        const from = glide.current ? goal.current : current.current;\n        const next = {\n          ArrowUp: from - 1,\n          ArrowDown: from + 1,\n          PageUp: from - 5,\n          PageDown: from + 5,\n          Home: 0,\n          End: last,\n        }[e.key];\n        if (next === undefined) return;\n        e.preventDefault();\n        glideTo(next);\n      }}\n    >\n      {rows}\n    </div>\n  );\n});\n\nexport default function WheelPickerDemo() {\n  const [time, setTime] = useState<Time>({ hour: 7, minute: 30, period: \"AM\" });\n  return <WheelPicker value={time} onChange={setTime} />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/wheel-picker"}