{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "wheel-picker",
  "title": "Wheel Picker",
  "description": "A scrolling wheel for one value out of a long ordered list: an hour, a minute, a year, a size. Several wheels side by side make a time picker.",
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "registry/default/wheel-picker/wheel-picker.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport type WheelPickerOption = {\n  value: string\n  label: string\n}\n\nexport type WheelPickerProps = Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"onChange\" | \"defaultValue\" | \"children\"\n> & {\n  options: readonly WheelPickerOption[]\n  value?: string\n  defaultValue?: string\n  onValueChange?: (value: string) => void\n  /** The accessible name, such as Hour or Shoe size. */\n  label: string\n  /** Runs past the last option back to the first, like the minutes on a clock. */\n  loop?: boolean\n  /** Rows on screen at once. Odd, so one sits in the middle. */\n  visibleCount?: number\n  itemHeight?: number\n  disabled?: boolean\n  /** Submits the chosen value with a form under this name. */\n  name?: string\n}\n\nexport type WheelPickerGroupProps = React.HTMLAttributes<HTMLDivElement> & {\n  /** The accessible name for the set, such as Start time. */\n  label: string\n  /** Shared by every wheel inside, so their rows line up. */\n  visibleCount?: number\n  itemHeight?: number\n}\n\ntype GroupContext = { visibleCount?: number; itemHeight?: number }\n\nconst WheelGroupContext = React.createContext<GroupContext | null>(null)\n\nconst SETTLE_DELAY = 120\nconst TYPEAHEAD_RESET = 700\n\nconst mod = (value: number, size: number) => ((value % size) + size) % size\n\nconst subscribeReducedMotion = (onChange: () => void) => {\n  const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n  query.addEventListener(\"change\", onChange)\n  return () => query.removeEventListener(\"change\", onChange)\n}\n\nconst readReducedMotion = () =>\n  window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches\n\n/**\n * A spinning list for one value out of a long ordered set: an hour, a year, a\n * shoe size. Scrolling is the browser's own, snapped to rows, so a flick on a\n * phone or a trackpad carries the momentum people expect.\n */\nexport function WheelPicker({\n  options,\n  value,\n  defaultValue,\n  onValueChange,\n  label,\n  loop = false,\n  visibleCount: visibleCountProp,\n  itemHeight: itemHeightProp,\n  disabled,\n  name,\n  className,\n  style,\n  ...rootProps\n}: WheelPickerProps) {\n  const group = React.useContext(WheelGroupContext)\n  const visibleCount = Math.max(\n    3,\n    (visibleCountProp ?? group?.visibleCount ?? 5) | 1\n  )\n  const itemHeight = itemHeightProp ?? group?.itemHeight ?? 36\n  const count = options.length\n\n  const [uncontrolled, setUncontrolled] = React.useState(\n    defaultValue ?? options[0]?.value\n  )\n  const selectedValue = value ?? uncontrolled\n  const selectedIndex = Math.max(\n    0,\n    options.findIndex((option) => option.value === selectedValue)\n  )\n  const selected = options[selectedIndex]\n\n  // Enough copies that a hard flick runs out of momentum before it runs out\n  // of rows; the wheel is quietly moved back to the middle copy once it rests.\n  const copies = loop && count > 0 ? Math.max(3, Math.ceil(90 / count)) | 1 : 1\n  const middle = Math.floor(copies / 2)\n  const rows = count * copies\n\n  const reduced = React.useSyncExternalStore(\n    subscribeReducedMotion,\n    readReducedMotion,\n    () => false\n  )\n\n  const scroller = React.useRef<HTMLDivElement>(null)\n  const items = React.useRef<(HTMLDivElement | null)[]>([])\n  const painted = React.useRef(new Set<number>())\n  const frame = React.useRef(0)\n  const settleTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null)\n  const touching = React.useRef(false)\n  const drag = React.useRef<{\n    startY: number\n    startTop: number\n    lastY: number\n    lastTime: number\n    velocity: number\n    moved: boolean\n  } | null>(null)\n  const suppressClick = React.useRef(false)\n  const typeahead = React.useRef({ text: \"\", time: 0 })\n\n  const paint = React.useCallback(() => {\n    const element = scroller.current\n    if (!element) return\n\n    const position = element.scrollTop / itemHeight\n    // The drum's radius is half the window, so the last visible row sits at\n    // ninety degrees and the wheel never shows its back.\n    const step = 2 / visibleCount\n    const radius = (visibleCount * itemHeight) / 2\n    const reach = Math.ceil(Math.PI / 2 / step) + 1\n    const first = Math.max(0, Math.floor(position) - reach)\n    const last = Math.min(rows - 1, Math.ceil(position) + reach)\n    const next = new Set<number>()\n\n    for (let index = first; index <= last; index++) {\n      const item = items.current[index]\n      if (!item) continue\n      next.add(index)\n\n      const offset = index - position\n      const distance = Math.abs(offset)\n\n      if (reduced) {\n        item.style.transform = \"\"\n        item.style.visibility = \"\"\n        item.style.opacity = String(Math.max(0.25, 1 - distance * 0.3))\n        continue\n      }\n\n      const angle = offset * step\n      if (Math.abs(angle) >= Math.PI / 2) {\n        item.style.visibility = \"hidden\"\n        continue\n      }\n\n      const lift = radius * Math.sin(angle) - offset * itemHeight\n      const depth = radius * (Math.cos(angle) - 1)\n      item.style.visibility = \"\"\n      item.style.opacity = String(Math.max(0.2, Math.cos(angle) ** 1.5))\n      item.style.transform = `translateY(${lift}px) translateZ(${depth}px) rotateX(${-angle}rad)`\n    }\n\n    for (const index of painted.current) {\n      if (next.has(index)) continue\n      const item = items.current[index]\n      if (item) item.style.visibility = \"hidden\"\n    }\n\n    painted.current = next\n  }, [itemHeight, reduced, rows, visibleCount])\n\n  const rowFor = React.useCallback(\n    (index: number) => (loop ? middle * count + index : index),\n    [count, loop, middle]\n  )\n\n  const scrollToRow = React.useCallback(\n    (row: number, behavior: ScrollBehavior) => {\n      scroller.current?.scrollTo({ top: row * itemHeight, behavior })\n      if (behavior === \"instant\") paint()\n    },\n    [itemHeight, paint]\n  )\n\n  const commit = (index: number) => {\n    const option = options[index]\n    if (!option || option.value === selectedValue) return\n    if (value === undefined) setUncontrolled(option.value)\n    onValueChange?.(option.value)\n  }\n\n  const settle = () => {\n    const element = scroller.current\n    if (!element || touching.current || drag.current || count === 0) return\n\n    element.style.scrollSnapType = \"\"\n    const row = Math.min(\n      rows - 1,\n      Math.max(0, Math.round(element.scrollTop / itemHeight))\n    )\n    const index = mod(row, count)\n\n    if (loop && row !== rowFor(index)) scrollToRow(rowFor(index), \"instant\")\n    commit(index)\n  }\n\n  const scheduleSettle = () => {\n    if (settleTimer.current) clearTimeout(settleTimer.current)\n    settleTimer.current = setTimeout(settle, SETTLE_DELAY)\n  }\n\n  React.useLayoutEffect(() => {\n    const element = scroller.current\n    if (!element || count === 0) return\n\n    const current = Math.round(element.scrollTop / itemHeight)\n    if (mod(current, count) !== selectedIndex || current >= rows) {\n      scrollToRow(rowFor(selectedIndex), \"instant\")\n    } else {\n      paint()\n    }\n  }, [count, itemHeight, paint, rowFor, rows, scrollToRow, selectedIndex])\n\n  React.useEffect(\n    () => () => {\n      cancelAnimationFrame(frame.current)\n      if (settleTimer.current) clearTimeout(settleTimer.current)\n    },\n    []\n  )\n\n  const moveTo = (index: number) => {\n    if (count === 0) return\n    scrollToRow(rowFor(index), \"instant\")\n    commit(index)\n  }\n\n  const findByText = (typed: string) => {\n    const now = Date.now()\n    const state = typeahead.current\n    state.text = now - state.time > TYPEAHEAD_RESET ? typed : state.text + typed\n    state.time = now\n\n    const query = state.text.toLowerCase()\n    const repeated = [...query].every((character) => character === query[0])\n    // Pressing the same letter again walks through everything that starts\n    // with it, the way a native select does.\n    const needle = repeated ? query[0]! : query\n    const start = repeated ? selectedIndex + 1 : selectedIndex\n\n    for (let offset = 0; offset < count; offset++) {\n      const index = mod(start + offset, count)\n      if (options[index]!.label.toLowerCase().startsWith(needle)) return index\n    }\n    return -1\n  }\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    if (disabled) return\n    const page = visibleCount\n    const moves: Record<string, number> = {\n      ArrowUp: selectedIndex - 1,\n      ArrowDown: selectedIndex + 1,\n      PageUp: selectedIndex - page,\n      PageDown: selectedIndex + page,\n      Home: 0,\n      End: count - 1,\n    }\n\n    if (event.key in moves) {\n      event.preventDefault()\n      const target = moves[event.key]!\n      const wraps = loop && event.key.startsWith(\"Arrow\")\n      moveTo(\n        wraps ? mod(target, count) : Math.min(count - 1, Math.max(0, target))\n      )\n      return\n    }\n\n    if (\n      event.key.length === 1 &&\n      event.key !== \" \" &&\n      !event.metaKey &&\n      !event.ctrlKey &&\n      !event.altKey\n    ) {\n      const index = findByText(event.key)\n      if (index >= 0) {\n        event.preventDefault()\n        moveTo(index)\n      }\n    }\n  }\n\n  const onPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {\n    suppressClick.current = false\n    if (disabled || event.pointerType !== \"mouse\" || event.button !== 0) return\n    const element = scroller.current\n    if (!element) return\n\n    drag.current = {\n      startY: event.clientY,\n      startTop: element.scrollTop,\n      lastY: event.clientY,\n      lastTime: event.timeStamp,\n      velocity: 0,\n      moved: false,\n    }\n  }\n\n  const onPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {\n    const state = drag.current\n    const element = scroller.current\n    if (!state || !element) return\n\n    const travelled = event.clientY - state.startY\n    if (!state.moved && Math.abs(travelled) < 4) return\n\n    if (!state.moved) {\n      state.moved = true\n      element.setPointerCapture(event.pointerId)\n      // Snapping would pull every assigned scrollTop back to a row, which\n      // turns a drag into a stutter. It comes back once the wheel rests.\n      element.style.scrollSnapType = \"none\"\n    }\n\n    const elapsed = Math.max(1, event.timeStamp - state.lastTime)\n    state.velocity = (event.clientY - state.lastY) / elapsed\n    state.lastY = event.clientY\n    state.lastTime = event.timeStamp\n    element.scrollTop = state.startTop - travelled\n  }\n\n  const onPointerEnd = (event: React.PointerEvent<HTMLDivElement>) => {\n    const state = drag.current\n    const element = scroller.current\n    drag.current = null\n    if (!state || !element || !state.moved) return\n\n    suppressClick.current = true\n    // A flick carries on a little, never more than one window of rows.\n    const reach = visibleCount * itemHeight\n    const held = event.timeStamp - state.lastTime > 80\n    const carry = held\n      ? 0\n      : Math.max(-reach, Math.min(reach, state.velocity * 120))\n    const thrown = element.scrollTop - carry\n    const row = Math.min(rows - 1, Math.max(0, Math.round(thrown / itemHeight)))\n    scrollToRow(row, reduced ? \"instant\" : \"smooth\")\n    scheduleSettle()\n  }\n\n  return (\n    <div\n      data-slot=\"wheel-picker\"\n      data-disabled={disabled ? \"\" : undefined}\n      className={cn(\n        \"has-[:focus-visible]:ring-ring relative min-w-14 rounded-md select-none has-[:focus-visible]:ring-2 data-disabled:opacity-50\",\n        group && \"flex-1\",\n        className\n      )}\n      style={{ height: visibleCount * itemHeight, ...style }}\n      {...rootProps}\n    >\n      {group ? null : (\n        <div\n          aria-hidden=\"true\"\n          data-slot=\"wheel-picker-band\"\n          className=\"bg-muted pointer-events-none absolute inset-x-0 top-1/2 -translate-y-1/2 rounded-md\"\n          style={{ height: itemHeight }}\n        />\n      )}\n\n      <div\n        ref={scroller}\n        role=\"spinbutton\"\n        tabIndex={disabled ? -1 : 0}\n        aria-label={label}\n        aria-valuemin={0}\n        aria-valuemax={Math.max(0, count - 1)}\n        aria-valuenow={selectedIndex}\n        aria-valuetext={selected?.label}\n        aria-disabled={disabled || undefined}\n        data-slot=\"wheel-picker-scroller\"\n        className={cn(\n          \"relative h-full snap-y snap-mandatory [scrollbar-width:none] overflow-y-scroll overscroll-contain outline-none [&::-webkit-scrollbar]:hidden\",\n          disabled ? \"pointer-events-none overflow-hidden\" : \"cursor-grab\"\n        )}\n        style={{\n          paddingBlock: ((visibleCount - 1) / 2) * itemHeight,\n          perspective: visibleCount * itemHeight * 3,\n          maskImage:\n            \"linear-gradient(to bottom, transparent, black 30%, black 70%, transparent)\",\n        }}\n        onKeyDown={onKeyDown}\n        onScroll={() => {\n          cancelAnimationFrame(frame.current)\n          frame.current = requestAnimationFrame(paint)\n          scheduleSettle()\n        }}\n        onTouchStart={() => {\n          touching.current = true\n        }}\n        onTouchEnd={() => {\n          touching.current = false\n          scheduleSettle()\n        }}\n        onTouchCancel={() => {\n          touching.current = false\n          scheduleSettle()\n        }}\n        onPointerDown={onPointerDown}\n        onPointerMove={onPointerMove}\n        onPointerUp={onPointerEnd}\n        onPointerCancel={onPointerEnd}\n      >\n        <div aria-hidden=\"true\">\n          {Array.from({ length: rows }, (_, row) => {\n            const option = options[row % count]!\n            return (\n              <div\n                key={row}\n                ref={(node) => {\n                  items.current[row] = node\n                }}\n                data-slot=\"wheel-picker-item\"\n                data-selected={row % count === selectedIndex ? \"\" : undefined}\n                className=\"text-foreground flex snap-center items-center justify-center px-3 text-base tabular-nums [backface-visibility:hidden] data-selected:font-semibold\"\n                style={{ height: itemHeight }}\n                onClick={() => {\n                  if (suppressClick.current || disabled) return\n                  scrollToRow(row, reduced ? \"instant\" : \"smooth\")\n                  scheduleSettle()\n                }}\n              >\n                {option.label}\n              </div>\n            )\n          })}\n        </div>\n      </div>\n\n      {name ? (\n        <input type=\"hidden\" name={name} value={selected?.value ?? \"\"} />\n      ) : null}\n    </div>\n  )\n}\n\n/**\n * Wheels side by side behind one selection band, for a value made of parts:\n * hours, minutes, and AM or PM. Left and right arrows move between them.\n */\nexport function WheelPickerGroup({\n  label,\n  visibleCount = 5,\n  itemHeight = 36,\n  className,\n  children,\n  onKeyDown,\n  ...rootProps\n}: WheelPickerGroupProps) {\n  const context = React.useMemo(\n    () => ({ visibleCount: Math.max(3, visibleCount | 1), itemHeight }),\n    [itemHeight, visibleCount]\n  )\n\n  return (\n    <WheelGroupContext.Provider value={context}>\n      <div\n        role=\"group\"\n        aria-label={label}\n        data-slot=\"wheel-picker-group\"\n        className={cn(\"relative flex items-stretch gap-1\", className)}\n        onKeyDown={(event) => {\n          onKeyDown?.(event)\n          if (event.defaultPrevented) return\n          if (event.key !== \"ArrowLeft\" && event.key !== \"ArrowRight\") return\n\n          const wheels = Array.from(\n            event.currentTarget.querySelectorAll<HTMLElement>(\n              '[role=\"spinbutton\"]:not([aria-disabled=\"true\"])'\n            )\n          )\n          const at = wheels.indexOf(event.target as HTMLElement)\n          if (at < 0) return\n\n          const next = wheels[at + (event.key === \"ArrowRight\" ? 1 : -1)]\n          if (next) {\n            event.preventDefault()\n            next.focus()\n          }\n        }}\n        {...rootProps}\n      >\n        <div\n          aria-hidden=\"true\"\n          data-slot=\"wheel-picker-band\"\n          className=\"bg-muted pointer-events-none absolute inset-x-0 top-1/2 -translate-y-1/2 rounded-md\"\n          style={{ height: context.itemHeight }}\n        />\n        {children}\n      </div>\n    </WheelGroupContext.Provider>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "categories": [
    "form",
    "input",
    "picker",
    "control"
  ],
  "type": "registry:ui"
}