{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"rotary-dial","type":"registry:component","title":"Rotary dial","description":"Drag a hole to the finger stop and each digit lands as the disc unwinds.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/rotary-dial.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { animate, motion, useMotionValue } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// Everything is drawn in a 280 unit square; pointer math scales into it.\nconst SIZE = 280;\nconst C = SIZE / 2;\nconst HOLE_RING = 98;\nconst HOLE_R = 19;\n// A little larger than the hole so a finger landing on its rim still catches.\nconst HIT_R = 24;\nconst DISC_R = 128;\nconst CARD_R = 52;\n\n// Angles are compass degrees: 0 at twelve o'clock, growing clockwise.\n// Holes sit 30deg apart with 1 at two o'clock and 0 near five, leaving the\n// gap at the bottom right where the finger stop lives.\nconst HOOK = 126;\n// A hole is blocked by the hook once its centre gets this close: its own\n// angular radius plus room for a fingertip.\nconst BLOCKED = HOOK - 22;\n// How far a finger can overshoot the stop or the rest position before the\n// disc stops caring where the pointer went.\nconst SLACK = 90;\n// Letting go this close to the stop still counts, like a real dial's give.\nconst STOP_TOLERANCE = 4;\n// A governor holds a real dial's return to about ten pulses a second. Slower\n// than other UI on purpose: the steady unwind is the feel of the object, and\n// even 0 comes home in under a second.\nconst RETURN_SPEED = 360;\n// Nearly linear with softened ends, so the disc neither lurches off the stop\n// nor thumps into rest. No overshoot: governors don't bounce.\nconst RETURN_EASE = [0.1, 0.04, 0.9, 0.96] as const;\n// A hand winding the disc: quick to get going, easing into the stop.\nconst WIND_EASE = [0.45, 0, 0.25, 1] as const;\n// Held against the stop for a beat before letting go, as a finger would.\nconst HOLD_MS = 70;\nconst EASE_OUT = \"cubic-bezier(0.23, 1, 0.32, 1)\";\n\nconst DIGITS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];\n\nfunction rest(digit: number) {\n  const k = digit === 0 ? 10 : digit;\n  return 60 - 30 * (k - 1);\n}\n\nfunction travel(digit: number) {\n  return BLOCKED - rest(digit);\n}\n\nfunction polar(radius: number, degrees: number) {\n  const a = (degrees * Math.PI) / 180;\n  return [C + radius * Math.sin(a), C - radius * Math.cos(a)] as const;\n}\n\nfunction compass(x: number, y: number) {\n  return (Math.atan2(x - C, C - y) * 180) / Math.PI;\n}\n\nfunction clamp(v: number, lo: number, hi: number) {\n  return Math.min(Math.max(v, lo), hi);\n}\n\nfunction circle(cx: number, cy: number, r: number) {\n  return `M${cx - r} ${cy}a${r} ${r} 0 1 0 ${r * 2} 0a${r} ${r} 0 1 0 ${-r * 2} 0Z`;\n}\n\n// One path with the holes cut by evenodd, so the disc is a single layer.\nconst DISC_PATH = [\n  circle(C, C, DISC_R),\n  circle(C, C, CARD_R + 4),\n  ...DIGITS.map((d) => {\n    const [x, y] = polar(HOLE_RING, rest(d));\n    return circle(x, y, HOLE_R);\n  }),\n].join(\"\");\n\n// The dial is a physical object, so it keeps its materials in both themes:\n// black bakelite over an ivory number plate. The plate dims a little in\n// dark mode so it doesn't glare.\nconst BAKELITE = \"oklch(0.19 0.004 60)\";\nconst BAKELITE_LIT = \"oklch(0.3 0.004 60)\";\nconst PLATE = \"light-dark(oklch(0.965 0.01 85), oklch(0.86 0.012 85))\";\nconst PLATE_INK = \"oklch(0.24 0.01 60)\";\n\nconst HOOK_FROM = polar(HOLE_RING + 8, HOOK);\nconst HOOK_TO = polar(C - 3, HOOK);\n\ntype Phase = \"idle\" | \"drag\" | \"out\" | \"back\";\ntype Grab = {\n  id: number;\n  digit: number;\n  last: number;\n  raw: number;\n  moved: number;\n  atStop: boolean;\n};\n\nexport function RotaryDial({\n  value,\n  onChange,\n  label,\n  maxLength = 10,\n  groups = [3, 3, 4],\n  autoFocus = false,\n  className,\n}: {\n  value: string;\n  onChange: (value: string) => void;\n  label: string;\n  maxLength?: number;\n  /** Digit group sizes in the readout, e.g. [3, 3, 4] for a phone number. */\n  groups?: number[];\n  autoFocus?: boolean;\n  className?: string;\n}) {\n  const id = useId();\n  // SVG ids can't hold the colons useId may produce.\n  const gid = `rd${id.replace(/[^a-zA-Z0-9_-]/g, \"\")}`;\n  const reduceMotion = useReducedMotion();\n  const rotation = useMotionValue(0);\n  const dialRef = useRef<HTMLDivElement>(null);\n  const stopRef = useRef<HTMLDivElement>(null);\n\n  const phase = useRef<Phase>(\"idle\");\n  const active = useRef<number | null>(null);\n  const queue = useRef<number[]>([]);\n  const grab = useRef<Grab | null>(null);\n  const anim = useRef<ReturnType<typeof animate> | null>(null);\n  const hold = useRef<ReturnType<typeof setTimeout>>(undefined);\n\n  // Animation callbacks outlive the render that started them, so they read\n  // the latest props through refs.\n  const valueRef = useRef(value);\n  const onChangeRef = useRef(onChange);\n  const reduceRef = useRef(reduceMotion);\n  useEffect(() => {\n    valueRef.current = value;\n    onChangeRef.current = onChange;\n    reduceRef.current = reduceMotion;\n  });\n\n  useEffect(() => {\n    if (autoFocus) dialRef.current?.focus({ preventScroll: true });\n  }, [autoFocus]);\n\n  useEffect(\n    () => () => {\n      anim.current?.stop();\n      clearTimeout(hold.current);\n    },\n    [],\n  );\n\n  const commit = (digit: number) => {\n    if (valueRef.current.length >= maxLength) return;\n    const next = valueRef.current + digit;\n    valueRef.current = next;\n    onChangeRef.current(next);\n  };\n\n  const inFlight = () =>\n    (phase.current === \"out\" || phase.current === \"back\") && active.current !== null ? 1 : 0;\n  const room = () => maxLength - valueRef.current.length - queue.current.length - inFlight();\n\n  const halt = () => {\n    anim.current?.stop();\n    anim.current = null;\n    clearTimeout(hold.current);\n  };\n\n  const bumpStop = () => {\n    if (reduceRef.current) return;\n    stopRef.current?.animate(\n      [{ transform: \"rotate(0deg)\" }, { transform: \"rotate(1.5deg)\" }, { transform: \"rotate(0deg)\" }],\n      { duration: 180, easing: EASE_OUT },\n    );\n  };\n\n  const settle = () => {\n    phase.current = \"idle\";\n    active.current = null;\n    const next = queue.current.shift();\n    if (next !== undefined) windOut(next);\n  };\n\n  const unwind = (digit: number | null) => {\n    phase.current = \"back\";\n    active.current = digit;\n    const from = rotation.get();\n    const done = () => {\n      anim.current = null;\n      if (digit !== null) commit(digit);\n      settle();\n    };\n    if (reduceRef.current || from < 0.5) {\n      rotation.jump(0);\n      done();\n      return;\n    }\n    anim.current = animate(rotation, 0, {\n      duration: from / RETURN_SPEED,\n      ease: RETURN_EASE,\n      onComplete: done,\n    });\n  };\n\n  // Typed digits and tapped holes take exactly the path a finger would.\n  const windOut = (digit: number) => {\n    phase.current = \"out\";\n    active.current = digit;\n    if (reduceRef.current) {\n      rotation.jump(0);\n      commit(digit);\n      settle();\n      return;\n    }\n    const to = travel(digit);\n    anim.current = animate(rotation, to, {\n      duration: 0.16 + (to - rotation.get()) / 1100,\n      ease: WIND_EASE,\n      onComplete: () => {\n        bumpStop();\n        hold.current = setTimeout(() => unwind(digit), HOLD_MS);\n      },\n    });\n  };\n\n  // Grabbing the disc mid-flight lands everything already dialed or typed,\n  // so a quick finger never loses a digit.\n  const flush = () => {\n    const was = phase.current;\n    halt();\n    if ((was === \"out\" || was === \"back\") && active.current !== null) commit(active.current);\n    for (const d of queue.current) commit(d);\n    queue.current = [];\n    phase.current = \"idle\";\n    active.current = null;\n  };\n\n  const enqueue = (digit: number) => {\n    if (room() <= 0) return;\n    queue.current.push(digit);\n    if (phase.current === \"idle\") settle();\n  };\n\n  const erase = () => {\n    // A digit still waiting its turn is the newest, so it goes first.\n    if (queue.current.length) {\n      queue.current.pop();\n      return;\n    }\n    if (!valueRef.current) return;\n    const next = valueRef.current.slice(0, -1);\n    valueRef.current = next;\n    onChangeRef.current(next);\n  };\n\n  const local = (e: React.PointerEvent<HTMLElement>) => {\n    const box = e.currentTarget.getBoundingClientRect();\n    const scale = SIZE / box.width;\n    return [(e.clientX - box.left) * scale, (e.clientY - box.top) * scale] as const;\n  };\n\n  const holeAt = (x: number, y: number, r: number) => {\n    for (const d of DIGITS) {\n      // Holes already wound past their own stop are out of reach.\n      if (r > travel(d) + 0.5) continue;\n      const [hx, hy] = polar(HOLE_RING, rest(d) + r);\n      if (Math.hypot(x - hx, y - hy) <= HIT_R) return d;\n    }\n    return null;\n  };\n\n  const onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (e.button !== 0 || grab.current) return;\n    const [x, y] = local(e);\n    const digit = holeAt(x, y, rotation.get());\n    if (digit === null) return;\n    flush();\n    e.currentTarget.setPointerCapture(e.pointerId);\n    phase.current = \"drag\";\n    active.current = digit;\n    grab.current = {\n      id: e.pointerId,\n      digit,\n      last: compass(x, y),\n      raw: rotation.get(),\n      moved: 0,\n      atStop: false,\n    };\n  };\n\n  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {\n    const g = grab.current;\n    if (!g || e.pointerId !== g.id) return;\n    const [x, y] = local(e);\n    const angle = compass(x, y);\n    // Unwrap across the +-180 seam so a pull through six o'clock is smooth.\n    let delta = angle - g.last;\n    if (delta > 180) delta -= 360;\n    if (delta < -180) delta += 360;\n    g.last = angle;\n    g.moved += Math.abs(delta);\n    const t = travel(g.digit);\n    g.raw = clamp(g.raw + delta, -SLACK, t + SLACK);\n    const r = clamp(g.raw, 0, t);\n    rotation.set(r);\n    const atStop = r >= t;\n    if (atStop && !g.atStop) bumpStop();\n    g.atStop = atStop;\n  };\n\n  const release = (e: React.PointerEvent<HTMLDivElement>, cancelled: boolean) => {\n    const g = grab.current;\n    if (!g || e.pointerId !== g.id) return;\n    grab.current = null;\n    const fits = room() > 0;\n    // A tap on a hole dials it for you.\n    if (!cancelled && g.moved < 2 && fits) {\n      windOut(g.digit);\n      return;\n    }\n    const reached = rotation.get() >= travel(g.digit) - STOP_TOLERANCE;\n    unwind(!cancelled && reached && fits ? g.digit : null);\n  };\n\n  const groupStarts = new Set<number>();\n  groups.reduce((at, size) => {\n    groupStarts.add(at);\n    return at + size;\n  }, 0);\n\n  return (\n    <div className={cn(\"flex w-[340px] max-w-full flex-col items-center gap-7\", className)}>\n      <div className=\"flex w-full flex-col gap-1.5\">\n        <span id={`${id}-label`} className=\"px-1 text-sm text-muted-foreground\">\n          {label}\n        </span>\n        <div className=\"flex h-14 items-center gap-2 rounded-2xl bg-muted pr-2 pl-4 shadow-raised\">\n          <output\n            aria-labelledby={`${id}-label`}\n            aria-live=\"polite\"\n            className=\"flex min-w-0 flex-1 items-baseline overflow-hidden font-mono text-2xl tabular-nums\"\n          >\n            {value ? (\n              value.split(\"\").map((digit, i) => (\n                <motion.span\n                  key={i}\n                  initial={{ opacity: 0, filter: \"blur(4px)\", y: reduceMotion ? 0 : 6 }}\n                  animate={{ opacity: 1, filter: \"blur(0px)\", y: 0 }}\n                  transition={{ duration: 0.2, ease: [0.23, 1, 0.32, 1] }}\n                  className={cn(\"inline-block\", i > 0 && groupStarts.has(i) && \"ml-[0.45em]\")}\n                >\n                  {digit}\n                </motion.span>\n              ))\n            ) : (\n              <span className=\"font-sans text-base text-muted-foreground\">Dial a number</span>\n            )}\n          </output>\n          <button\n            type=\"button\"\n            aria-label=\"Delete last digit\"\n            disabled={!value}\n            onClick={erase}\n            className=\"flex size-10 shrink-0 items-center justify-center rounded-xl text-muted-foreground outline-hidden transition-[scale,color,opacity] duration-150 ease-out hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] disabled:pointer-events-none disabled:opacity-40\"\n          >\n            <svg\n              viewBox=\"0 0 24 24\"\n              className=\"size-5\"\n              fill=\"none\"\n              stroke=\"currentColor\"\n              strokeWidth={1.5}\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              aria-hidden\n            >\n              <path d=\"M9 5h10a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-6-7Z\" />\n              <path d=\"m11.5 9.5 5 5M16.5 9.5l-5 5\" />\n            </svg>\n          </button>\n        </div>\n      </div>\n\n      <div\n        ref={dialRef}\n        role=\"group\"\n        tabIndex={0}\n        aria-label={`${label} dial`}\n        aria-describedby={`${id}-hint`}\n        aria-keyshortcuts=\"0 1 2 3 4 5 6 7 8 9 Backspace\"\n        className=\"relative aspect-square w-[280px] max-w-full cursor-grab touch-none rounded-full shadow-[0_12px_28px_-10px_oklch(0_0_0/0.35),0_2px_4px_oklch(0_0_0/0.12)] outline-hidden select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-4 focus-visible:outline-foreground active:cursor-grabbing\"\n        onPointerDown={onPointerDown}\n        onPointerMove={onPointerMove}\n        onPointerUp={(e) => release(e, false)}\n        onPointerCancel={(e) => release(e, true)}\n        onKeyDown={(e) => {\n          if (e.metaKey || e.ctrlKey || e.altKey) return;\n          if (/^\\d$/.test(e.key)) {\n            e.preventDefault();\n            if (!e.repeat && !grab.current) enqueue(Number(e.key));\n          } else if (e.key === \"Backspace\" || e.key === \"Delete\") {\n            e.preventDefault();\n            erase();\n          }\n        }}\n      >\n        <span id={`${id}-hint`} className=\"sr-only\">\n          Type digits to dial them. Backspace deletes.\n        </span>\n        <svg viewBox={`0 0 ${SIZE} ${SIZE}`} className=\"absolute inset-0 size-full\" aria-hidden>\n          <defs>\n            {/* Concentric light, so it stays put while the disc turns: the\n                bakelite is darkest near the hub and catches a band of light\n                toward its rolled rim. */}\n            <radialGradient id={`${gid}-disc`} cx=\"50%\" cy=\"50%\" r=\"50%\">\n              <stop offset=\"0.42\" stopColor={BAKELITE} />\n              <stop offset=\"0.86\" stopColor={BAKELITE_LIT} />\n              <stop offset=\"0.93\" stopColor={BAKELITE} />\n            </radialGradient>\n            <linearGradient id={`${gid}-chrome`} x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\">\n              <stop offset=\"0\" stopColor=\"oklch(0.94 0 0)\" />\n              <stop offset=\"0.5\" stopColor=\"oklch(0.62 0 0)\" />\n              <stop offset=\"1\" stopColor=\"oklch(0.8 0 0)\" />\n            </linearGradient>\n          </defs>\n          {/* The number plate stays put; its digits show through the holes. */}\n          <circle cx={C} cy={C} r={C - 1} style={{ fill: PLATE }} stroke=\"oklch(0 0 0 / 0.12)\" />\n          {DIGITS.map((d) => {\n            const [x, y] = polar(HOLE_RING, rest(d));\n            return (\n              <text\n                key={d}\n                x={x}\n                y={y}\n                dy=\"0.36em\"\n                textAnchor=\"middle\"\n                fill={PLATE_INK}\n                className=\"text-lg font-semibold tabular-nums\"\n              >\n                {d}\n              </text>\n            );\n          })}\n        </svg>\n\n        <motion.div className=\"absolute inset-0\" style={{ rotate: rotation }}>\n          <svg viewBox={`0 0 ${SIZE} ${SIZE}`} className=\"size-full\" aria-hidden>\n            {/* A soft shadow the disc casts on the plate. */}\n            <path\n              d={DISC_PATH}\n              fillRule=\"evenodd\"\n              fill=\"oklch(0 0 0 / 0.18)\"\n              transform=\"translate(0 1.5)\"\n            />\n            <path d={DISC_PATH} fillRule=\"evenodd\" fill={`url(#${gid}-disc)`} />\n            {/* Moulded lips on the rim and every hole catch the light. */}\n            <circle cx={C} cy={C} r={DISC_R - 0.75} fill=\"none\" stroke=\"oklch(1 0 0 / 0.16)\" strokeWidth={1.5} />\n            {DIGITS.map((d) => {\n              const [x, y] = polar(HOLE_RING, rest(d));\n              return (\n                <circle key={d} cx={x} cy={y} r={HOLE_R + 0.75} fill=\"none\" stroke=\"oklch(1 0 0 / 0.2)\" strokeWidth={1.5} />\n              );\n            })}\n          </svg>\n        </motion.div>\n\n        <div ref={stopRef} className=\"pointer-events-none absolute inset-0\">\n          <svg viewBox={`0 0 ${SIZE} ${SIZE}`} className=\"size-full\" aria-hidden>\n            {/* A plated steel finger stop, screwed to the plate at its outer\n                end, with a collar of plate colour between it and the disc. */}\n            <line\n              x1={HOOK_FROM[0]}\n              y1={HOOK_FROM[1]}\n              x2={HOOK_TO[0]}\n              y2={HOOK_TO[1]}\n              strokeWidth={12}\n              strokeLinecap=\"round\"\n              style={{ stroke: PLATE }}\n            />\n            <line\n              x1={HOOK_FROM[0]}\n              y1={HOOK_FROM[1]}\n              x2={HOOK_TO[0]}\n              y2={HOOK_TO[1]}\n              strokeWidth={7}\n              strokeLinecap=\"round\"\n              stroke={`url(#${gid}-chrome)`}\n            />\n            <circle cx={HOOK_TO[0]} cy={HOOK_TO[1]} r={2} fill=\"oklch(0.45 0 0)\" />\n          </svg>\n        </div>\n\n        <svg\n          viewBox={`0 0 ${SIZE} ${SIZE}`}\n          className=\"pointer-events-none absolute inset-0 size-full\"\n          aria-hidden\n        >\n          {/* The centre card, printed on the same stock as the plate, under\n              a clear bezel. */}\n          <circle cx={C} cy={C} r={CARD_R} style={{ fill: PLATE }} stroke=\"oklch(0 0 0 / 0.25)\" strokeWidth={1.5} />\n          <circle cx={C} cy={C} r={CARD_R - 5} fill=\"none\" stroke={PLATE_INK} strokeOpacity={0.25} />\n          <text x={C} y={C - 4} textAnchor=\"middle\" fill={PLATE_INK} fillOpacity={0.7} className=\"text-xs\">\n            Pull a hole\n          </text>\n          <text x={C} y={C + 12} textAnchor=\"middle\" fill={PLATE_INK} fillOpacity={0.7} className=\"text-xs\">\n            to the stop\n          </text>\n        </svg>\n      </div>\n    </div>\n  );\n}\n\nexport default function RotaryDialDemo() {\n  const [value, setValue] = useState(\"\");\n  return <RotaryDial label=\"Phone number\" value={value} onChange={setValue} autoFocus />;\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":["objects"],"docs":"From ui lab: https://lab.xevrion.dev/lab/rotary-dial"}