{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"ruler-slider","type":"registry:ui","title":"Ruler slider","description":"A tape of ticks that slides under a fixed needle. Drag it and let go: it keeps the speed you gave it, slows, and clicks into the nearest step while the number above rolls to the new value. For picking a measurement where the scale itself helps.","dependencies":["clsx","tailwind-merge"],"registryDependencies":["https://caliperui.site/r/styles.json"],"files":[{"path":"ui/animated-counter.tsx","type":"registry:ui","target":"components/ui/animated-counter.tsx","content":"\"use client\";\nimport {\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type CSSProperties,\n} from \"react\";\nimport { cn } from \"./lib/cn\";\nimport { cssMs } from \"./lib/motion-tokens\";\nimport \"./animated-counter.css\";\nfunction CounterDigit({\n  digit,\n  direction,\n  reveal,\n}: {\n  digit: number;\n  direction: \"up\" | \"down\" | \"none\";\n  reveal: boolean;\n}) {\n  const column = useRef<HTMLSpanElement>(null),\n    first = useRef(true);\n  useLayoutEffect(() => {\n    const element = column.current;\n    if (!element) return;\n    const animate = (initial = false) => {\n      const tokens = getComputedStyle(element),\n        height = element.parentElement!.getBoundingClientRect().height;\n      const transform = tokens.transform;\n      const offset =\n        transform === \"none\"\n          ? 20 + digit\n          : -new DOMMatrixReadOnly(transform).m42 / height;\n      const start = initial ? 20 : 20 + (((offset % 10) + 10) % 10);\n      let end = 20 + digit;\n      if (direction === \"up\" && end < start) end += 10;\n      if (direction === \"down\" && end > start) end -= 10;\n      element.getAnimations().forEach((animation) => animation.cancel());\n      element.style.transform = `translateY(-${(20 + digit) * 1.2}em)`;\n      if (\n        !matchMedia(\"(prefers-reduced-motion: reduce)\").matches &&\n        (initial || direction !== \"none\")\n      )\n        element.animate(\n          [\n            { transform: `translateY(-${start * 1.2}em)` },\n            { transform: `translateY(-${end * 1.2}em)` },\n          ],\n          {\n            duration: cssMs(tokens.getPropertyValue(\"--duration-deliberate\")),\n            easing: tokens.getPropertyValue(\"--ease-out\").trim(),\n          },\n        );\n    };\n    if (first.current) {\n      first.current = false;\n      element.style.transform = `translateY(-${(20 + digit) * 1.2}em)`;\n      if (reveal) {\n        const observer = new IntersectionObserver(\n          (entries) => {\n            if (entries[0].isIntersecting) {\n              animate(true);\n              observer.disconnect();\n            }\n          },\n          { threshold: 0.6 },\n        );\n        observer.observe(element.parentElement!);\n        return () => observer.disconnect();\n      }\n    } else animate();\n  }, [digit, direction, reveal]);\n  useEffect(() => {\n    const preference = matchMedia(\"(prefers-reduced-motion: reduce)\");\n    const cancel = () => {\n      if (preference.matches)\n        column.current\n          ?.getAnimations()\n          .forEach((animation) => animation.cancel());\n    };\n    preference.addEventListener(\"change\", cancel);\n    return () => preference.removeEventListener(\"change\", cancel);\n  }, []);\n  return (\n    <span\n      data-slot=\"counter-digit\"\n      className=\"inline-block h-[1.2em] w-[1ch] overflow-hidden\"\n    >\n      <span\n        ref={column}\n        className=\"block\"\n        style={\n          {\n            transform: \"translateY(calc(-1.2em * var(--counter-target)))\",\n            \"--counter-target\": 20 + digit,\n          } as CSSProperties\n        }\n      >\n        {Array.from({ length: 50 }, (_, i) => (\n          <span key={i} className=\"block h-[1.2em] leading-[1.2]\">\n            {i % 10}\n          </span>\n        ))}\n      </span>\n    </span>\n  );\n}\nexport function AnimatedCounter({\n  value,\n  label,\n  prefix = \"\",\n  suffix = \"\",\n  decimals = 0,\n  locale = \"en-US\",\n  animateOnView = false,\n  className,\n}: {\n  value: number;\n  label?: string;\n  prefix?: string;\n  suffix?: string;\n  decimals?: number;\n  locale?: string;\n  animateOnView?: boolean;\n  className?: string;\n}) {\n  const shell = useRef<HTMLSpanElement>(null),\n    content = useRef<HTMLSpanElement>(null);\n  useLayoutEffect(() => {\n    const measure = () => {\n      if (shell.current && content.current)\n        shell.current.style.width = `${content.current.offsetWidth}px`;\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    if (content.current) observer.observe(content.current);\n    return () => observer.disconnect();\n  }, []);\n  const [frame, setFrame] = useState({ value, prior: value });\n  if (!Object.is(frame.value, value)) setFrame({ value, prior: frame.value });\n  const direction =\n    value > frame.prior ? \"up\" : value < frame.prior ? \"down\" : \"none\";\n  const text = Number.isFinite(value)\n    ? new Intl.NumberFormat(locale, {\n        minimumFractionDigits: Math.max(0, Math.min(20, decimals)),\n        maximumFractionDigits: Math.max(0, Math.min(20, decimals)),\n      }).format(value)\n    : \"—\";\n  return (\n    <span\n      data-slot=\"animated-counter\"\n      className={cn(\"inline-flex flex-col min-w-0\", className)}\n    >\n      {label && (\n        <span className=\"mb-1 text-xs font-medium text-muted-foreground\">\n          {label}\n        </span>\n      )}\n      <span className=\"sr-only\">\n        {prefix}\n        {text}\n        {suffix}\n      </span>\n      <span\n        ref={shell}\n        data-slot=\"counter-shell\"\n        aria-hidden=\"true\"\n        className=\"relative inline-block h-[1.2em] overflow-hidden\"\n      >\n        <span\n          ref={content}\n          className=\"absolute right-0 inline-flex w-max items-center tabular-nums\"\n        >\n          {prefix}\n          {[...text].map((glyph, index) =>\n            /\\d/.test(glyph) ? (\n              <CounterDigit\n                key={`digit-${text.length - index}`}\n                digit={Number(glyph)}\n                direction={direction}\n                reveal={animateOnView}\n              />\n            ) : (\n              <span key={`separator-${text.length - index}`}>{glyph}</span>\n            ),\n          )}\n          {suffix}\n        </span>\n      </span>\n    </span>\n  );\n}\n"},{"path":"ui/lib/cn.ts","type":"registry:ui","target":"components/ui/lib/cn.ts","content":"import { clsx, type ClassValue } from \"clsx\";\nimport { extendTailwindMerge } from \"tailwind-merge\";\n\nconst twMerge = extendTailwindMerge({\n  extend: { theme: { radius: [\"control\", \"surface\", \"overlay\"], shadow: [\"overlay\"] } },\n});\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n"},{"path":"ui/lib/motion-tokens.ts","type":"registry:ui","target":"components/ui/lib/motion-tokens.ts","content":"/** Milliseconds from a CSS time such as \"280ms\" or \".28s\" (build tools may rewrite one as the other). */\nexport function cssMs(value: string) {\n  const text = value.trim();\n  const number = parseFloat(text);\n  if (!Number.isFinite(number)) return 0;\n  return text.endsWith(\"ms\") ? number : text.endsWith(\"s\") ? number * 1000 : number;\n}\n\n/** Reads a duration token (e.g. \"--duration-travel\") in milliseconds from an element; the tokens resolve to 0 under reduced motion. */\nexport function tokenMs(element: Element, name: string) {\n  return cssMs(getComputedStyle(element).getPropertyValue(name));\n}\n"},{"path":"ui/ruler-slider.tsx","type":"registry:ui","target":"components/ui/ruler-slider.tsx","content":"\"use client\";\nimport { useEffect, useRef, useState, type ComponentProps, type CSSProperties, type KeyboardEvent, type PointerEvent } from \"react\";\nimport { AnimatedCounter } from \"./animated-counter\";\nimport { cn } from \"./lib/cn\";\nimport \"./shared/styles-5.css\";\nimport \"./ruler-slider.css\";\n\nexport type RulerSliderProps = Omit<ComponentProps<\"div\">, \"defaultValue\" | \"onChange\"> & {\n  /** Names the value, e.g. \"Weight\". */\n  label: string;\n  value?: number;\n  defaultValue?: number;\n  onValueChange?: (value: number) => void;\n  min?: number;\n  max?: number;\n  step?: number;\n  /** A long, numbered tick every this many steps. */\n  majorEvery?: number;\n  /** Shown after the readout, such as \"kg\". */\n  unit?: string;\n  /** Pixels between ticks. */\n  gap?: number;\n};\n\nconst clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));\nconst decimalsOf = (step: number) => (String(step).split(\".\")[1] ?? \"\").length;\n\n/**\n * A tape of ticks that slides under a fixed needle. Drag it and let go: it keeps moving with the speed you gave it,\n * slows, and clicks into the nearest step while the readout rolls. Arrow keys step, Page keys jump a numbered tick,\n * Home and End go to the ends. Under reduced motion the tape lands without the glide.\n */\nexport function RulerSlider({ label, value, defaultValue, onValueChange, min = 0, max = 100, step = 1, majorEvery = 10, unit, gap = 10, className, style, ...props }: RulerSliderProps) {\n  const [own, setOwn] = useState(() => clamp(defaultValue ?? min, min, max));\n  const current = value ?? own;\n  const [pos, setPos] = useState<number | null>(null); // the tape's live position while dragged or gliding, in value units\n  const [detent, setDetent] = useState(0);\n  const drag = useRef<{ x: number; start: number; samples: [number, number][] } | null>(null);\n  const glide = useRef(0);\n  const last = useRef(current);\n  const decimals = decimalsOf(step);\n  const snap = (raw: number) => clamp(Math.round((raw - min) / step) * step + min, min, max);\n\n  const commit = (next: number) => {\n    const snapped = Number(snap(next).toFixed(decimals));\n    if (snapped === last.current) return;\n    last.current = snapped;\n    if (value === undefined) setOwn(snapped);\n    onValueChange?.(snapped);\n    setDetent((count) => count + 1);\n  };\n\n  useEffect(() => {\n    last.current = current;\n  }, [current]);\n  useEffect(() => () => cancelAnimationFrame(glide.current), []);\n\n  const down = (event: PointerEvent<HTMLDivElement>) => {\n    if (event.button !== 0) return;\n    cancelAnimationFrame(glide.current);\n    event.currentTarget.setPointerCapture(event.pointerId);\n    const start = pos ?? current;\n    drag.current = { x: event.clientX, start, samples: [[event.timeStamp, event.clientX]] };\n    setPos(start);\n  };\n  const move = (event: PointerEvent<HTMLDivElement>) => {\n    const active = drag.current;\n    if (!active) return;\n    // Rubber-band past the ends, so the limit is felt rather than hit.\n    const raw = active.start - ((event.clientX - active.x) / gap) * step;\n    const over = raw < min ? raw - min : raw > max ? raw - max : 0;\n    const next = raw - over + over * 0.3;\n    active.samples = [...active.samples.slice(-4), [event.timeStamp, event.clientX]];\n    setPos(next);\n    commit(next);\n  };\n  const up = () => {\n    const active = drag.current;\n    drag.current = null;\n    if (!active || pos === null) return;\n    const [[t0, x0], [t1, x1]] = [active.samples[0], active.samples[active.samples.length - 1]];\n    let velocity = t1 > t0 ? (-(x1 - x0) / gap) * step / (t1 - t0) : 0; // value units per ms\n    if (matchMedia(\"(prefers-reduced-motion: reduce)\").matches) velocity = 0;\n    let at = clamp(pos, min, max);\n    let then = -1;\n    const frame = (now: number) => {\n      const dt = then < 0 ? 16 : Math.min(32, now - then);\n      then = now;\n      at = clamp(at + velocity * dt, min, max);\n      velocity *= Math.pow(0.994, dt);\n      if (at === min || at === max) velocity = 0;\n      commit(at);\n      if (Math.abs(velocity) * gap / step > 0.02) {\n        setPos(at);\n        glide.current = requestAnimationFrame(frame);\n      } else setPos(null); // the snapped value takes over and the tape eases onto it\n    };\n    glide.current = requestAnimationFrame(frame);\n  };\n\n  const key = (event: KeyboardEvent<HTMLDivElement>) => {\n    const jumps: Record<string, number> = { ArrowRight: step, ArrowUp: step, ArrowLeft: -step, ArrowDown: -step, PageUp: step * majorEvery, PageDown: -step * majorEvery };\n    if (event.key in jumps) commit(current + jumps[event.key]);\n    else if (event.key === \"Home\") commit(min);\n    else if (event.key === \"End\") commit(max);\n    else return;\n    event.preventDefault();\n    cancelAnimationFrame(glide.current);\n    setPos(null);\n  };\n\n  const count = Math.round((max - min) / step) + 1;\n  const shown = pos ?? current;\n  const text = `${current.toFixed(decimals)}${unit ? ` ${unit}` : \"\"}`;\n\n  return (\n    <div data-slot=\"ruler-slider\" className={cn(\"grid gap-3\", className)} style={{ \"--rs-gap\": `${gap}px`, ...style } as CSSProperties} {...props}>\n      <div data-slot=\"rs-readout\" className=\"flex items-baseline justify-center gap-1.5\">\n        <AnimatedCounter value={current} decimals={decimals} className=\"text-3xl font-semibold tracking-tight\" />\n        {unit && <span className=\"text-sm text-muted-foreground\">{unit}</span>}\n      </div>\n      <div\n        role=\"slider\"\n        tabIndex={0}\n        aria-label={label}\n        aria-valuemin={min}\n        aria-valuemax={max}\n        aria-valuenow={current}\n        aria-valuetext={text}\n        data-slot=\"rs-window\"\n        data-dragging={pos !== null ? \"\" : undefined}\n        onPointerDown={down}\n        onPointerMove={move}\n        onPointerUp={up}\n        onPointerCancel={up}\n        onKeyDown={key}\n      >\n        {/* The fade sits on a still layer: a mask on the moving tape would travel with it. */}\n        <div data-slot=\"rs-fade\">\n          <div data-slot=\"rs-tape\" style={{ \"--rs-at\": (shown - min) / step } as CSSProperties}>\n            {Array.from({ length: count }, (_, i) => {\n              const major = i % majorEvery === 0;\n              const half = !major && majorEvery % 2 === 0 && i % (majorEvery / 2) === 0;\n              return (\n                <span key={i} data-slot=\"rs-tick\" data-major={major ? \"\" : undefined} data-half={half ? \"\" : undefined} style={{ \"--rs-i\": i } as CSSProperties}>\n                  {major && <span data-slot=\"rs-number\">{(min + i * step).toFixed(decimals)}</span>}\n                </span>\n              );\n            })}\n          </div>\n        </div>\n        <span key={detent} data-slot=\"rs-needle\" aria-hidden=\"true\" />\n      </div>\n    </div>\n  );\n}\n"},{"path":"ui/animated-counter.css","type":"registry:file","target":"components/ui/animated-counter.css","content":"/* animated-counter.tsx's styles; it imports this file. Edit freely. */\n@layer theme, base, components, utilities;\n\n@layer components {\n  [data-slot=\"counter-shell\"] {\n    transition: width var(--duration-deliberate) var(--ease-out);\n  }\n  @media (prefers-reduced-motion: reduce) {\n    [data-slot=\"counter-shell\"] {\n      transition: none;\n    }\n  }\n}\n"},{"path":"ui/shared/styles-5.css","type":"registry:file","target":"components/ui/shared/styles-5.css","content":"/* Shared by not-found-compass.tsx, rating.tsx, ruler-slider.tsx; each imports it. Edit freely. */\n@layer theme, base, components, utilities;\n\n@layer components {\n  [data-half=\"north\"] { fill: var(--foreground); }\n  [data-half=\"north-shade\"] { fill: color-mix(in oklab, var(--foreground) 70%, var(--background)); }\n  [data-half=\"south\"] { fill: var(--border); }\n}\n"},{"path":"ui/ruler-slider.css","type":"registry:file","target":"components/ui/ruler-slider.css","content":"/* ruler-slider.tsx's styles; it imports this file. Edit freely. */\n@layer theme, base, components, utilities;\n\n@layer components {\n  /* Ruler slider: the tape slides under a fixed needle; it follows the finger, then eases onto the step. */\n  [data-slot=\"ruler-slider\"] [data-slot=\"rs-window\"] { position: relative; height: 64px; overflow: hidden; border-radius: var(--radius-control); cursor: grab; touch-action: pan-y; outline: none; user-select: none; -webkit-user-select: none; }\n  [data-slot=\"ruler-slider\"] [data-slot=\"rs-window\"][data-dragging] { cursor: grabbing; }\n  [data-slot=\"ruler-slider\"] [data-slot=\"rs-window\"]:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }\n  [data-slot=\"ruler-slider\"] [data-slot=\"rs-fade\"] { position: absolute; inset: 0; overflow: hidden; mask-image: linear-gradient(90deg, transparent, #000 22%, #000 78%, transparent); }\n  [data-slot=\"ruler-slider\"] [data-slot=\"rs-tape\"] { position: absolute; inset: 0; translate: calc(var(--rs-at) * var(--rs-gap) * -1) 0; transition: translate var(--duration-deliberate) var(--ease-settle); }\n  [data-slot=\"ruler-slider\"] [data-dragging] [data-slot=\"rs-tape\"] { transition: none; }\n  [data-slot=\"ruler-slider\"] [data-slot=\"rs-tick\"] { position: absolute; top: 8px; left: calc(50% + var(--rs-i) * var(--rs-gap)); width: 1px; height: 10px; margin-left: -0.5px; background: var(--border-strong); }\n  [data-slot=\"ruler-slider\"] [data-slot=\"rs-tick\"][data-half] { height: 15px; }\n  [data-slot=\"ruler-slider\"] [data-slot=\"rs-tick\"][data-major] { width: 1.5px; height: 22px; margin-left: -0.75px; background: var(--muted-foreground); }\n  [data-slot=\"ruler-slider\"] [data-slot=\"rs-number\"] { position: absolute; top: 28px; left: 50%; translate: -50% 0; font-size: 12px; font-variant-numeric: tabular-nums; color: var(--muted-foreground); white-space: nowrap; }\n  [data-slot=\"ruler-slider\"] [data-slot=\"rs-needle\"] { position: absolute; top: 4px; left: 50%; width: 2px; height: 32px; margin-left: -1px; border-radius: 999px; background: var(--foreground); transform-origin: top; animation: rs-detent 240ms var(--ease-out); pointer-events: none; }\n  @media (pointer: coarse) { [data-slot=\"ruler-slider\"] [data-slot=\"rs-window\"] { height: 72px; } }\n  @media (prefers-reduced-motion: reduce) {\n    [data-slot=\"ruler-slider\"] [data-slot=\"rs-tape\"] { transition: none; }\n    [data-slot=\"ruler-slider\"] [data-slot=\"rs-needle\"] { animation: none; }\n  }\n  @keyframes rs-detent { from { scale: 1 1.2; } }\n}\n"}],"categories":["motion"],"meta":{"tier":"free","license":"MIT","family":"changing-values","docs":"/docs/components/ruler-slider"}}