{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"number-stepper","type":"registry:component","title":"Number stepper","description":"Rolls each digit the way the count moves, and speeds up the longer you hold.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/number-stepper.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useLayoutEffect, useRef, useState } from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// Short enough that a held button at full speed still reads as rolling\n// rather than a blur of overlapping digits.\nconst ROLL = { duration: 0.18, ease: EASE_OUT };\nconst SLIDE = { type: \"spring\", visualDuration: 0.2, bounce: 0 } as const;\n// Holding waits this long before repeating, so a click never double-steps.\nconst HOLD_DELAY = 400;\n// Repeats start at this interval and shrink by ACCELERATION each step,\n// down to FASTEST, so a long hold covers big ranges without overshooting\n// small ones.\nconst FIRST_REPEAT = 150;\nconst ACCELERATION = 0.85;\nconst FASTEST = 40;\n\ntype Direction = 1 | -1;\n\n// Updated during render from the previous value, so the roll direction is\n// known on the same frame as the new digits.\nfunction useDirection(value: number) {\n  const [previous, setPrevious] = useState(value);\n  const [direction, setDirection] = useState<Direction>(1);\n  if (value !== previous) {\n    setPrevious(value);\n    setDirection(value > previous ? 1 : -1);\n  }\n  return direction;\n}\n\nexport function RollingNumber({\n  value,\n  format = String,\n  className,\n}: {\n  value: number;\n  format?: (value: number) => string;\n  className?: string;\n}) {\n  const direction = useDirection(value);\n  const chars = [...format(value)];\n  return (\n    <span aria-hidden className={cn(\"relative inline-flex tabular-nums\", className)}>\n      <AnimatePresence mode=\"popLayout\" initial={false} custom={direction}>\n        {chars.map((char, i) => {\n          // Keyed by place from the right, so 9 to 10 keeps the ones column\n          // and only adds a tens column.\n          const place = chars.length - i;\n          const digit = /\\d/.test(char);\n          return (\n            <Place key={digit ? `d${place}` : `s${place}${char}`} digit={digit}>\n              {digit ? <Digit char={char} direction={direction} /> : char}\n            </Place>\n          );\n        })}\n      </AnimatePresence>\n    </span>\n  );\n}\n\nfunction Place({\n  digit,\n  children,\n}: {\n  digit: boolean;\n  children: React.ReactNode;\n}) {\n  const reduceMotion = useReducedMotion();\n  return (\n    <motion.span\n      layout={reduceMotion ? false : \"position\"}\n      initial={{ opacity: 0, filter: \"blur(4px)\" }}\n      animate={{ opacity: 1, filter: \"blur(0px)\" }}\n      exit={{ opacity: 0, filter: \"blur(0px)\", transition: { duration: 0.1 } }}\n      transition={{ ...ROLL, layout: SLIDE }}\n      className={cn(\"inline-grid\", digit && \"overflow-hidden\")}\n    >\n      {children}\n    </motion.span>\n  );\n}\n\nfunction Digit({ char, direction }: { char: string; direction: Direction }) {\n  const reduceMotion = useReducedMotion();\n  // Increasing rolls up: the new digit rises from below as the old one\n  // leaves through the top. Decreasing mirrors it.\n  const offset = (d: Direction) => (reduceMotion ? \"0%\" : `${d * 100}%`);\n  return (\n    <AnimatePresence initial={false} custom={direction}>\n      <motion.span\n        key={char}\n        custom={direction}\n        variants={{\n          enter: (d: Direction) => ({ y: offset(d), opacity: 0 }),\n          center: { y: \"0%\", opacity: 1 },\n          exit: (d: Direction) => ({ y: offset(-d as Direction), opacity: 0 }),\n        }}\n        initial=\"enter\"\n        animate=\"center\"\n        exit=\"exit\"\n        transition={ROLL}\n        // Every digit shares one cell, so the outgoing one never shifts layout.\n        className=\"col-start-1 row-start-1\"\n      >\n        {char}\n      </motion.span>\n    </AnimatePresence>\n  );\n}\n\nexport function NumberStepper({\n  label,\n  value,\n  onChange,\n  min = 0,\n  max = 99,\n  step = 1,\n  className,\n}: {\n  label: string;\n  value: number;\n  onChange: (value: number) => void;\n  min?: number;\n  max?: number;\n  step?: number;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const id = useId();\n  // Non-null only once the user types, so the rolling number stays in\n  // charge until then.\n  const [draft, setDraft] = useState<string | null>(null);\n  const valueRef = useRef<HTMLSpanElement>(null);\n  const bumpAnimation = useRef<Animation>(undefined);\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  // Held-button repeats fire faster than React re-renders can be counted\n  // on, so the latest value is tracked here too.\n  const latest = useRef({ value, onChange, min, max });\n\n  useLayoutEffect(() => {\n    latest.current = { value, onChange, min, max };\n  });\n\n  useEffect(\n    () => () => {\n      clearTimeout(timer.current);\n      bumpAnimation.current?.cancel();\n    },\n    [],\n  );\n\n  const bump = (direction: Direction) => {\n    const el = valueRef.current;\n    if (!el || reduceMotion) return;\n    bumpAnimation.current?.cancel();\n    // A 3px nudge toward the wall it hit: felt more than seen.\n    bumpAnimation.current = el.animate(\n      { translate: [\"0\", `${direction * 3}px`, \"0\"] },\n      { duration: 200, easing: \"cubic-bezier(0.23, 1, 0.32, 1)\" },\n    );\n  };\n\n  const setTo = (target: number, direction: Direction) => {\n    const now = latest.current;\n    const next = Math.min(Math.max(target, now.min), now.max);\n    // Asked for more than the limit allows, so it hit the wall.\n    if (next !== target) bump(direction);\n    if (next === now.value) return false;\n    latest.current = { ...now, value: next };\n    now.onChange(next);\n    return true;\n  };\n\n  const stepBy = (delta: number) =>\n    setTo(latest.current.value + delta, delta > 0 ? 1 : -1);\n\n  const stop = () => clearTimeout(timer.current);\n\n  const hold = (delta: number) => {\n    stop();\n    if (!stepBy(delta)) return;\n    let interval = FIRST_REPEAT;\n    const repeat = () => {\n      if (!stepBy(delta)) return;\n      interval = Math.max(FASTEST, interval * ACCELERATION);\n      timer.current = setTimeout(repeat, interval);\n    };\n    timer.current = setTimeout(repeat, HOLD_DELAY);\n  };\n\n  const commitDraft = () => {\n    if (draft === null) return;\n    const parsed = Number.parseInt(draft, 10);\n    setDraft(null);\n    if (Number.isNaN(parsed)) return;\n    setTo(parsed, parsed > value ? 1 : -1);\n  };\n\n  const button = (delta: number, atLimit: boolean, name: string, path: string) => (\n    <button\n      type=\"button\"\n      aria-label={`${name} ${label.toLowerCase()}`}\n      aria-controls={id}\n      // Stays focusable at the limit, so keyboard focus never drops to the\n      // page; a press there bumps the value instead.\n      aria-disabled={atLimit}\n      tabIndex={-1}\n      onPointerDown={(e) => {\n        if (e.button !== 0) return;\n        // Keeps focus where it was, so holding never steals it.\n        e.preventDefault();\n        hold(delta);\n      }}\n      onPointerUp={stop}\n      onPointerLeave={stop}\n      onPointerCancel={stop}\n      onContextMenu={(e) => e.preventDefault()}\n      // Pointer presses are handled above; this catches assistive tech.\n      onClick={(e) => {\n        if (e.detail === 0) stepBy(delta);\n      }}\n      className={cn(\n        \"flex size-9 shrink-0 touch-manipulation items-center justify-center rounded-full text-foreground outline-hidden select-none\",\n        \"transition-[scale,opacity,background-color] duration-150 ease-out hover:bg-foreground/[0.06] active:scale-[0.96] motion-reduce:transition-[opacity,background-color]\",\n        atLimit && \"opacity-35 hover:bg-transparent\",\n      )}\n    >\n      <svg\n        viewBox=\"0 0 16 16\"\n        aria-hidden\n        className=\"size-4\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth={1.5}\n        strokeLinecap=\"round\"\n      >\n        <path d={path} />\n      </svg>\n    </button>\n  );\n\n  const editing = draft !== null;\n\n  return (\n    // 22px radius around 4px padding keeps the 36px buttons concentric.\n    <div\n      className={cn(\n        \"inline-flex h-11 items-center rounded-full bg-muted p-1 shadow-raised outline-offset-2 outline-foreground has-[input:focus-visible]:outline-2 has-[input:focus-visible]:outline-solid\",\n        className,\n      )}\n    >\n      {button(-step, value <= min, \"Decrease\", \"M3.5 8h9\")}\n      <span ref={valueRef} className=\"relative grid w-12 place-items-center\">\n        <input\n          id={id}\n          role=\"spinbutton\"\n          aria-label={label}\n          aria-valuenow={value}\n          aria-valuemin={min}\n          aria-valuemax={max}\n          inputMode=\"numeric\"\n          autoComplete=\"off\"\n          value={draft ?? String(value)}\n          onChange={(e) => setDraft(e.target.value.replace(/\\D/g, \"\"))}\n          onFocus={(e) => e.currentTarget.select()}\n          onBlur={commitDraft}\n          onKeyDown={(e) => {\n            const delta: Record<string, number> = {\n              ArrowUp: step,\n              ArrowDown: -step,\n              PageUp: step * 10,\n              PageDown: -step * 10,\n            };\n            if (e.key in delta) {\n              e.preventDefault();\n              setDraft(null);\n              stepBy(delta[e.key]);\n            } else if (e.key === \"Home\" || e.key === \"End\") {\n              e.preventDefault();\n              setDraft(null);\n              setTo(e.key === \"Home\" ? min : max, e.key === \"Home\" ? -1 : 1);\n            } else if (e.key === \"Enter\") {\n              commitDraft();\n            } else if (e.key === \"Escape\") {\n              setDraft(null);\n            }\n          }}\n          // The text stays invisible until typing starts; the rolling copy\n          // above sits exactly on it.\n          className={cn(\n            \"col-start-1 row-start-1 w-full bg-transparent text-center text-[15px] font-medium tabular-nums caret-foreground outline-hidden\",\n            editing ? \"text-foreground\" : \"text-transparent\",\n          )}\n        />\n        {/* Hidden instantly once typing starts, never faded. */}\n        {!editing && (\n          <RollingNumber\n            value={value}\n            className=\"pointer-events-none col-start-1 row-start-1 text-[15px] font-medium text-foreground\"\n          />\n        )}\n      </span>\n      {button(step, value >= max, \"Increase\", \"M3.5 8h9M8 3.5v9\")}\n    </div>\n  );\n}\n\nconst ITEMS = [\n  { name: \"Linen shirt\", detail: \"Oat, M\", price: 48 },\n  { name: \"Canvas tote\", detail: \"Natural\", price: 24 },\n  { name: \"Wool socks\", detail: \"Charcoal, 2 pack\", price: 12.5 },\n];\n\nconst money = (v: number) =>\n  `$${v.toLocaleString(\"en-US\", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;\n\nexport default function NumberStepperDemo() {\n  const [quantities, setQuantities] = useState([1, 2, 3]);\n  const total = ITEMS.reduce((sum, item, i) => sum + item.price * quantities[i], 0);\n\n  return (\n    <div className=\"flex w-[min(420px,100%)] flex-col rounded-[20px] bg-muted p-2 shadow-raised\">\n      <ul className=\"flex flex-col\">\n        {ITEMS.map((item, i) => (\n          <li\n            key={item.name}\n            className=\"flex items-center gap-3 px-3 py-2.5 not-last:border-b not-last:border-border\"\n          >\n            <div className=\"flex min-w-0 flex-1 flex-col\">\n              <span className=\"truncate text-[15px] font-medium text-foreground\">\n                {item.name}\n              </span>\n              <span className=\"truncate text-sm text-muted-foreground\">\n                {item.detail} · {money(item.price)}\n              </span>\n            </div>\n            <NumberStepper\n              label={`${item.name} quantity`}\n              value={quantities[i]}\n              min={1}\n              max={20}\n              onChange={(next) =>\n                setQuantities((q) => q.map((n, j) => (j === i ? next : n)))\n              }\n              className=\"bg-background\"\n            />\n          </li>\n        ))}\n      </ul>\n      <div className=\"mt-1 flex items-center justify-between rounded-xl bg-background px-3 py-3 shadow-raised\">\n        <span className=\"text-sm text-muted-foreground\">Total</span>\n        <span className=\"text-lg font-semibold text-foreground\">\n          <span className=\"sr-only\">{money(total)}</span>\n          <RollingNumber value={total} format={money} />\n        </span>\n      </div>\n    </div>\n  );\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/number-stepper"}