{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"detent-dial-input","type":"registry:component","title":"Detent Dial Input","description":"A number set by turning a CSS-3D dial: drag round it and it steps through detents, springing onto each while its copper marker ticks; a real slider with full keyboard control that submits in a form.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/detent-dial-input.tsx","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState, useSyncExternalStore } from \"react\";\nimport type { CSSProperties, KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from \"react\";\n\n/**\n * DetentDialInput — a number set by turning a dial.\n *\n * The kit's CSS-3D knob: drag round it and it steps through detents,\n * springing onto each while its copper marker ticks. A real slider: arrow\n * keys, Page Up and Down, Home and End, announced with its format;\n * controlled or not, and it submits in a form with `name`. No WebGL.\n *\n * Part of the Spatial 3D kit: a dark studio (#0a0a0d, panels #101114 and\n * #16171b, ink #f2f1ee) with anodised copper #ff7a3d only as light, and\n * one object in three finishes (titanium, ceramic, soft-touch polymer) under\n * one rig: key, fill and rim, soft shadows, occlusion and a softbox\n * reflection. Hanken Grotesk through var(--font-hanken) for display over\n * Geist. Respects prefers-reduced-motion. No dependencies beyond React.\n * Paste it as its own file: it repeats the kit's small helpers, which would\n * clash in one module. Load Hanken Grotesk with next/font (variable:\n * \"--font-hanken\") on a parent, or from Google Fonts or @fontsource.\n */\n\nconst SANS = 'var(--font-sans, \"Geist\", \"Inter\", ui-sans-serif, system-ui, sans-serif)';\n\nconst MONO = 'var(--font-mono, \"Geist Mono\", ui-monospace, \"SFMono-Regular\", Menlo, Consolas, monospace)';\n\nconst DISPLAY = 'var(--font-hanken, \"Hanken Grotesk\", var(--font-sans, \"Geist\"), ui-sans-serif, system-ui, sans-serif)';\n\n/** The dark studio the kit is set in. */\nconst ROOM = {\n  ground: \"#0a0a0d\",\n  panel: \"#101114\",\n  raised: \"#16171b\",\n  ink: \"rgba(242,241,238,0.92)\",\n  ink2: \"rgba(242,241,238,0.6)\",\n  ink3: \"rgba(242,241,238,0.38)\",\n  line: \"rgba(242,241,238,0.08)\",\n  line2: \"rgba(242,241,238,0.16)\",\n  copper: \"#ff7a3d\",\n} as const;\n\n/**\n * The three finishes the object can wear. `base` is the colour; the rest are\n * shader parameters: gloss (0-1), specular strength, rim, subsurface wrap, and\n * how metallic it is. `css` holds the colours the CSS-3D parts draw with.\n */\nexport const S3_FINISHES = {\n  titanium: {\n    label: \"Titanium\",\n    base: [0.725, 0.737, 0.761],\n    gloss: 0.62,\n    spec: 0.8,\n    rim: 0.3,\n    sss: 0,\n    metal: 1,\n    css: { face: \"#c9ccd2\", side: \"#8d9098\", edge: \"#e6e8ec\", shade: \"#5d6068\" },\n  },\n  ceramic: {\n    label: \"Ceramic\",\n    base: [0.925, 0.906, 0.867],\n    gloss: 0.4,\n    spec: 0.25,\n    rim: 0.18,\n    sss: 0.08,\n    metal: 0,\n    css: { face: \"#ece7dd\", side: \"#c9c2b5\", edge: \"#faf7f1\", shade: \"#9a9386\" },\n  },\n  polymer: {\n    label: \"Polymer\",\n    base: [0.106, 0.11, 0.125],\n    gloss: 0.3,\n    spec: 0.12,\n    rim: 0.22,\n    sss: 0,\n    metal: 0,\n    css: { face: \"#26272c\", side: \"#18191d\", edge: \"#3a3b41\", shade: \"#0e0f12\" },\n  },\n} as const;\n\nexport type S3Finish = keyof typeof S3_FINISHES;\n\nfunction own<T extends object>(map: T, key: string): key is Extract<keyof T, string> {\n  return Object.prototype.hasOwnProperty.call(map, key);\n}\n\nfunction finishOf(name: string) {\n  return own(S3_FINISHES, name) ? S3_FINISHES[name] : S3_FINISHES.titanium;\n}\n\nfunction clamp(v: number, lo: number, hi: number): number {\n  return v < lo ? lo : v > hi ? hi : v;\n}\n\nfunction subscribeMotion(cb: () => void) {\n  const m = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n  m.addEventListener(\"change\", cb);\n  return () => m.removeEventListener(\"change\", cb);\n}\n\n/** True when the visitor asked for reduced motion. False on the server. */\nfunction useReducedMotion(): boolean {\n  return useSyncExternalStore(\n    subscribeMotion,\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n/**\n * A spring for one number (stiffness 340, damping 26: a detent's snap,\n * settled in about 380ms). Returns the new value and velocity.\n */\nfunction spring(x: number, v: number, target: number, dt: number, k = 340, c = 26): [number, number] {\n  const steps = dt > 1 / 60 ? 2 : 1;\n  const h = dt / steps;\n  for (let i = 0; i < steps; i++) {\n    v += (k * (target - x) - c * v) * h;\n    x += v * h;\n  }\n  return [x, v];\n}\n\n// Each part carries only the CSS it needs, so any one of them works on its own.\n// Nothing is interpolated into these sheets; colours arrive as CSS variables.\n// revert-layer keeps an element's own rounded corners when a host page's focus rule flattens them.\nconst FOCUS_CSS = \".s3-scope :focus-visible,.s3-scope:focus-visible{outline:2px solid var(--s3-ring,#ff7a3d);outline-offset:3px;border-radius:revert-layer}\";\n\n/**\n * The dial in CSS 3D, for parts that ship no WebGL: nine knurled discs stacked\n * 2.2px apart form the ring's side, a finish-lit face and a dark glass cap sit\n * on top, and a copper marker turns with `angle`. Tilted in real perspective,\n * so its side and its shadow move as it turns toward you.\n */\nfunction CssDial({ finish = \"titanium\", angle = 0, size = 180, tiltX = 24, tiltY = -16, lit = false, ticks = 0 }: { finish?: S3Finish; angle?: number; size?: number; tiltX?: number; tiltY?: number; lit?: boolean; ticks?: number }) {\n  const c = finishOf(finish).css;\n  const layers = 9;\n  const turn = `rotate(${angle.toFixed(2)}deg)`;\n  return (\n    <div aria-hidden className=\"relative\" style={{ width: size, height: size, perspective: size * 4 }}>\n      <div className=\"absolute inset-0\" style={{ transformStyle: \"preserve-3d\", transform: `rotateX(${tiltX.toFixed(2)}deg) rotateY(${tiltY.toFixed(2)}deg)` }}>\n        <div className=\"absolute rounded-full\" style={{ inset: \"-9%\", transform: \"translateZ(-8px)\", background: `radial-gradient(circle at 40% 35%, ${ROOM.raised}, ${ROOM.panel} 60%, #07070a)`, boxShadow: \"0 30px 50px -20px rgba(0,0,0,0.8), inset 0 1px 0 rgba(242,241,238,0.06)\" }}>\n          {ticks > 0 ? (\n            <svg viewBox=\"-50 -50 100 100\" className=\"absolute inset-0 h-full w-full\">\n              {Array.from({ length: ticks }, (_, i) => {\n                const a = (i / ticks) * Math.PI * 2;\n                const r2 = i % 5 === 0 ? 41 : 43;\n                // Rounded, so the server and the browser draw the same numbers.\n                const at = (r: number) => [Number((Math.sin(a) * r).toFixed(2)), Number((-Math.cos(a) * r).toFixed(2))];\n                const [x1, y1] = at(45);\n                const [x2, y2] = at(r2);\n                return <line key={i} x1={x1} y1={y1} x2={x2} y2={y2} stroke={i % 5 === 0 ? \"rgba(242,241,238,0.5)\" : \"rgba(242,241,238,0.2)\"} strokeWidth={0.6} />;\n              })}\n            </svg>\n          ) : null}\n        </div>\n        {Array.from({ length: layers }, (_, i) => (\n          <div\n            key={i}\n            className=\"absolute rounded-full\"\n            style={{\n              inset: \"8%\",\n              transform: `translateZ(${(i * 2.2).toFixed(1)}px) ${turn}`,\n              background: `repeating-conic-gradient(${c.side} 0 3deg, ${i === layers - 1 ? c.edge : c.shade} 3deg 6deg)`,\n              filter: `brightness(${(0.72 + i * 0.035).toFixed(3)})`,\n            }}\n          />\n        ))}\n        <div\n          className=\"absolute rounded-full\"\n          style={{\n            inset: \"13%\",\n            transform: `translateZ(${(layers * 2.2).toFixed(1)}px) ${turn}`,\n            background: `radial-gradient(circle at 34% 28%, ${c.edge}, ${c.face} 42%, ${c.side} 100%)`,\n            boxShadow: `inset 0 0 0 1px ${c.edge}, inset 0 -6px 12px rgba(0,0,0,0.25)`,\n          }}\n        >\n          <div className=\"absolute rounded-full\" style={{ inset: \"12%\", background: \"radial-gradient(circle at 38% 30%, #2a2c33, #0d0e11 55%, #050507)\", boxShadow: \"inset 0 1px 1px rgba(255,255,255,0.14)\" }} />\n          <div\n            className=\"absolute rounded-full\"\n            style={{\n              width: \"7%\",\n              height: \"7%\",\n              left: \"46.5%\",\n              top: \"17%\",\n              background: ROOM.copper,\n              boxShadow: lit ? \"0 0 6px 1px rgba(255,122,61,0.95), 0 0 18px 3px rgba(255,122,61,0.5)\" : \"0 0 3px rgba(255,122,61,0.6)\",\n              transition: \"box-shadow 220ms\",\n            }}\n          />\n        </div>\n      </div>\n    </div>\n  );\n}\n\nexport type DetentDialInputProps = {\n  label: string;\n  min?: number;\n  max?: number;\n  step?: number;\n  value?: number;\n  defaultValue?: number;\n  onChange?: (value: number) => void;\n  /** How the value reads (a unit, a sign). */\n  format?: (value: number) => string;\n  /** Detents in one full turn of the dial. */\n  detents?: number;\n  finish?: S3Finish;\n  size?: number;\n  /** A form field name: the value is submitted in a hidden input. */\n  name?: string;\n  hint?: string;\n  className?: string;\n};\n\n/**\n * A number set by turning a dial. The dial is the kit's CSS-3D knob (knurled\n * discs under a glass cap); drag round it and it steps through detents (60 a\n * turn by default), springing onto each one (stiffness 340, damping 26) while\n * its copper marker ticks. It is a real slider: focus it and use the arrow\n * keys, Page Up and Down for ten steps, Home and End for the ends; the value is\n * announced with its format. Controlled or not; with `name` it submits in a\n * form.\n */\nexport function DetentDialInput({ label, min = 0, max = 100, step: stepProp = 1, value, defaultValue, onChange, format = (v) => String(v), detents = 60, finish = \"titanium\", size = 220, name, hint, className }: DetentDialInputProps) {\n  // A step of zero (or less) would divide by zero; one is the safe floor.\n  const step = stepProp > 0 ? stepProp : 1;\n  const [local, setLocal] = useState(clamp(defaultValue ?? min, min, max));\n  const v = clamp(value ?? local, min, max);\n  const [shown, setShown] = useState(0);\n  const [tick, setTick] = useState(false);\n  const anim = useRef({ x: 0, v: 0, raf: 0, last: 0 });\n  const drag = useRef<{ a0: number; v0: number } | null>(null);\n  const dialRef = useRef<HTMLDivElement>(null);\n  const reduced = useReducedMotion();\n  const labelId = useId();\n  const per = 360 / Math.max(6, detents);\n  const target = ((v - min) / step) * per;\n\n  const set = (next: number) => {\n    const n = clamp(Math.round((next - min) / step) * step + min, min, max);\n    const fixed = Number(n.toFixed(6));\n    if (fixed === v) return;\n    if (value === undefined) setLocal(fixed);\n    onChange?.(fixed);\n    setTick(true);\n  };\n\n  // The marker ticks for 120ms on every detent.\n  useEffect(() => {\n    if (!tick) return;\n    const id = window.setTimeout(() => setTick(false), 120);\n    return () => window.clearTimeout(id);\n  }, [tick]);\n\n  // The dial springs onto its detent.\n  useEffect(() => {\n    const t = anim.current;\n    if (reduced) {\n      t.x = target;\n      const id = requestAnimationFrame(() => setShown(target));\n      return () => cancelAnimationFrame(id);\n    }\n    const stepFrame = (now: number) => {\n      const dt = t.last ? Math.min(0.05, (now - t.last) / 1000) : 1 / 60;\n      t.last = now;\n      [t.x, t.v] = spring(t.x, t.v, target, dt);\n      setShown(t.x);\n      if (Math.abs(target - t.x) > 0.02 || Math.abs(t.v) > 0.02) t.raf = requestAnimationFrame(stepFrame);\n      else t.last = 0;\n    };\n    cancelAnimationFrame(t.raf);\n    t.raf = requestAnimationFrame(stepFrame);\n    return () => cancelAnimationFrame(t.raf);\n  }, [target, reduced]);\n\n  const angleAt = (e: ReactPointerEvent<HTMLElement>) => {\n    const r = e.currentTarget.getBoundingClientRect();\n    return (Math.atan2(e.clientX - (r.left + r.width / 2), -(e.clientY - (r.top + r.height / 2))) * 180) / Math.PI;\n  };\n  const onDown = (e: ReactPointerEvent<HTMLElement>) => {\n    drag.current = { a0: angleAt(e), v0: v };\n    e.currentTarget.setPointerCapture(e.pointerId);\n    e.currentTarget.focus();\n  };\n  const onMove = (e: ReactPointerEvent<HTMLElement>) => {\n    const d = drag.current;\n    if (!d) return;\n    let da = angleAt(e) - d.a0;\n    // Keep turning past the top: unwrap the angle so a full turn keeps counting.\n    if (da > 180) {\n      da -= 360;\n      d.a0 += 360;\n    } else if (da < -180) {\n      da += 360;\n      d.a0 -= 360;\n    }\n    set(d.v0 + (da / per) * step);\n  };\n  const onUp = () => {\n    drag.current = null;\n  };\n  const onKey = (e: ReactKeyboardEvent) => {\n    const map: Record<string, number> = { ArrowRight: step, ArrowUp: step, ArrowLeft: -step, ArrowDown: -step, PageUp: step * 10, PageDown: -step * 10 };\n    if (e.key in map) {\n      e.preventDefault();\n      set(v + map[e.key]);\n    } else if (e.key === \"Home\") {\n      e.preventDefault();\n      set(min);\n    } else if (e.key === \"End\") {\n      e.preventDefault();\n      set(max);\n    }\n  };\n\n  return (\n    <div className={\"s3-scope flex flex-col items-center gap-5 \" + (className ?? \"\")} style={{ color: ROOM.ink, \"--s3-ring\": ROOM.copper } as CSSProperties}>\n      <style>{FOCUS_CSS}</style>\n      <span id={labelId} className=\"text-[11px] uppercase tracking-[0.18em]\" style={{ fontFamily: MONO, color: ROOM.ink3 }}>\n        {label}\n      </span>\n      <div\n        ref={dialRef}\n        role=\"slider\"\n        tabIndex={0}\n        aria-labelledby={labelId}\n        aria-valuemin={min}\n        aria-valuemax={max}\n        aria-valuenow={v}\n        aria-valuetext={format(v)}\n        onPointerDown={onDown}\n        onPointerMove={onMove}\n        onPointerUp={onUp}\n        onPointerCancel={onUp}\n        onKeyDown={onKey}\n        className=\"cursor-grab touch-none rounded-full outline-none active:cursor-grabbing\"\n      >\n        <CssDial finish={finish} angle={shown} size={size} tiltX={18} tiltY={-10} lit={tick} ticks={Math.min(120, detents)} />\n      </div>\n      <span className=\"text-[44px] font-semibold leading-none tracking-[-0.02em] tabular-nums\" style={{ fontFamily: DISPLAY, color: \"#f2f1ee\" }}>\n        {format(v)}\n      </span>\n      {hint ? (\n        <span className=\"text-[13px]\" style={{ fontFamily: SANS, color: ROOM.ink3 }}>\n          {hint}\n        </span>\n      ) : null}\n      {name ? <input type=\"hidden\" name={name} value={v} /> : null}\n    </div>\n  );\n}\n","type":"registry:component","target":"components/viberdy/detent-dial-input.tsx"}],"meta":{"tier":"free","tags":["input","slider","dial","knob","3d","css 3d","form"],"href":"https://viberdy.dev/library/detent-dial-input","aiPrompt":"Build a React + Tailwind input, `DetentDialInput({ label, min, max, step, value, defaultValue, onChange, format, detents, finish, size, name, hint, className })`.\n\nUse the kit's CSS-3D dial (knurled discs under a glass cap, ticks = detents) as a role=slider element. The dial angle is ((value - min)/step) x (360/detents) degrees, followed by a spring (stiffness 340, damping 26). Dragging: on pointerdown remember the pointer's angle around the dial's centre and the value; on move, unwrap the angle change across the top and set value = start + (change / degrees per detent) x step, rounded to the step and clamped; the copper marker glows for 120ms on each change. Keys: arrows +-step, Page Up/Down +-10 steps, Home/End. The value in Hanken Grotesk 600 at 44px, a hint line, and a hidden input with name.\n\nSpatial 3D grammar: a dark studio, ground #0a0a0d (panels #101114, raised #16171b, ink #f2f1ee at 92/60/38%, hairlines at 8% and 16%), and one accent, anodised copper #ff7a3d, used only as light (a status arc, a detent marker, an active underglow), never as a fill. One object in three finishes, as material parameters: titanium (base #b9bcc2, gloss 0.62, specular 0.8, fully metallic), ceramic (#ece7dd, gloss 0.4, specular 0.25, a little subsurface wrap) and soft-touch polymer (#1b1c20, gloss 0.3, specular 0.12, the rim kept up so it holds against the ground). One rig for everything: a warm key from (0.55, 0.65, 0.42) at 1.15, a cool fill from (-0.4, -0.15, 0.55) at 0.3, a rim from behind at 0.65, soft shadows (k 16), five-tap occlusion and a studio reflection (a big softbox overhead left, a strip behind right), in linear light with a filmic curve and a 1/255 dither. Parts are blended with small smooth-min radii (8-15% of the smaller part) so the object reads as machined, not melted. Hanken Grotesk through var(--font-hanken, \"Hanken Grotesk\", ...) at 600-800 for display, Geist for reading, Geist Mono uppercase for readouts. Radii 24px panels, 20px cards, 14px controls, the dial full round. Motion: detent springs (stiffness 340, damping 26, ~380ms), orbit inertia that decays in ~270ms, an idle drift of 6 degrees a second on the page clock after 2.5s of stillness, hovers and presses in 90-420ms. Respect prefers-reduced-motion (a still three-quarter view you can still turn by hand; no drift, no scatter). No dependencies beyond React.","license":"https://viberdy.dev/license"}}