{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"spring-slider","title":"Spring Slider","author":"CoDesign-Spa27","description":"A pill-track slider with a spring-driven fill and thumb, tick markers, and a tooltip that blurs in and out.","dependencies":["@number-flow/react","motion"],"files":[{"path":"components/ui-components/spring-slider.tsx","content":"\"use client\";\n\nimport NumberFlow from \"@number-flow/react\";\nimport {\n  AnimatePresence,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  useReducedMotion,\n  useSpring,\n  useTransform,\n} from \"motion/react\";\nimport {\n  type ComponentPropsWithoutRef,\n  type KeyboardEvent,\n  type ReactNode,\n  type PointerEvent as ReactPointerEvent,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport type SpringSliderProps = Omit<\n  ComponentPropsWithoutRef<\"div\">,\n  \"defaultValue\" | \"onChange\" | \"children\"\n> & {\n  defaultValue?: number;\n  disabled?: boolean;\n  /** Page Up / Page Down jump. Defaults to ten steps. */\n  largeStep?: number;\n  max?: number;\n  min?: number;\n  onValueChange?: (value: number) => void;\n  /** Tooltip body. Return anything; the default rolls the number with NumberFlow. */\n  renderTooltip?: (value: number) => ReactNode;\n  step?: number;\n  /** Dot count under the track. `false` hides them. */\n  ticks?: number | false;\n  value?: number;\n  /** Spoken value, when the number alone is not the point. */\n  valueText?: (value: number) => string;\n};\n\n/** Follows the pointer closely enough to feel direct. */\nconst DRAG_SPRING = { damping: 44, mass: 0.4, stiffness: 400 } as const;\n/** Carries visible overshoot, so a snap to a tick lands with weight. */\nconst SETTLE_SPRING = { damping: 26, mass: 0.5, stiffness: 200 } as const;\n/** Still a spring, so the same code path runs; just over before it is seen. */\nconst REDUCED_SPRING = { damping: 80, mass: 0.2, stiffness: 3000 } as const;\n\nconst TOOLTIP_EASE = [0.23, 1, 0.32, 1] as const;\n\nconst clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));\n\nexport function SpringSlider({\n  className,\n  defaultValue,\n  disabled = false,\n  largeStep,\n  max = 100,\n  min = 0,\n  onValueChange,\n  renderTooltip,\n  step = 1,\n  ticks,\n  value,\n  valueText,\n  ...props\n}: SpringSliderProps) {\n  const railRef = useRef<HTMLDivElement>(null);\n  const reduceMotion = useReducedMotion();\n  const labelId = useId();\n\n  const snap = useCallback(\n    (raw: number) => {\n      const steps = Math.round((raw - min) / step);\n      return clamp(Number((min + steps * step).toFixed(10)), min, max);\n    },\n    [max, min, step],\n  );\n\n  const [uncontrolled, setUncontrolled] = useState(() => snap(defaultValue ?? min));\n  const isControlled = value !== undefined;\n  const current = snap(isControlled ? value : uncontrolled);\n\n  const [isDragging, setIsDragging] = useState(false);\n  const [isPeeking, setIsPeeking] = useState(false);\n\n  // The thumb is a circle the height of the rail, so one measurement gives both\n  // its diameter and the distance it may travel.\n  const [rail, setRail] = useState({ size: 0, travel: 0 });\n\n  useLayoutEffect(() => {\n    const element = railRef.current;\n    if (!element) return;\n\n    const measure = () => {\n      const { height, width } = element.getBoundingClientRect();\n      setRail({ size: height, travel: Math.max(width - height, 0) });\n    };\n\n    const observer = new ResizeObserver(measure);\n    observer.observe(element);\n    measure();\n\n    return () => observer.disconnect();\n  }, []);\n\n  const target = useMotionValue(0);\n  const springConfig = reduceMotion ? REDUCED_SPRING : isDragging ? DRAG_SPRING : SETTLE_SPRING;\n  const offset = useSpring(target, springConfig);\n\n  const fraction = max === min ? 0 : (current - min) / (max - min);\n\n  useEffect(() => {\n    const next = fraction * rail.travel;\n    // Jump rather than spring the very first time, so the thumb does not fly in\n    // from zero on mount or after a resize.\n    if (offset.getPrevious() === undefined || rail.travel === 0) offset.jump(next);\n    target.set(next);\n  }, [fraction, rail.travel, offset, target]);\n\n  // The fill is a full-width pill slid left behind the track's own rounded clip,\n  // so its right cap tracks the thumb without a width or clip-path animation.\n  const fillTransform = useMotionTemplate`translateX(${useTransform(\n    offset,\n    (position) => position - rail.travel,\n  )}px)`;\n  const thumbTransform = useMotionTemplate`translateX(${offset}px)`;\n  const tooltipTransform = useMotionTemplate`translateX(calc(${useTransform(\n    offset,\n    (position) => position + rail.size / 2,\n  )}px - 50%))`;\n\n  const commit = useCallback(\n    (raw: number) => {\n      const next = snap(raw);\n      if (!isControlled) setUncontrolled(next);\n      if (next !== current) onValueChange?.(next);\n    },\n    [current, isControlled, onValueChange, snap],\n  );\n\n  const valueAtPointer = useCallback(\n    (clientX: number) => {\n      const element = railRef.current;\n      if (!element) return current;\n\n      const rect = element.getBoundingClientRect();\n      const usable = Math.max(rect.width - rect.height, 1);\n      // Measured from the thumb's centre, which starts half a thumb in.\n      const ratio = clamp((clientX - rect.left - rect.height / 2) / usable, 0, 1);\n      return min + ratio * (max - min);\n    },\n    [current, max, min],\n  );\n\n  const handlePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {\n    if (disabled || event.button !== 0) return;\n    event.currentTarget.setPointerCapture(event.pointerId);\n    event.currentTarget.focus();\n    setIsDragging(true);\n    commit(valueAtPointer(event.clientX));\n  };\n\n  const handlePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {\n    if (!isDragging || disabled) return;\n    commit(valueAtPointer(event.clientX));\n  };\n\n  const endDrag = (event: ReactPointerEvent<HTMLDivElement>) => {\n    if (!isDragging) return;\n    if (event.currentTarget.hasPointerCapture(event.pointerId)) {\n      event.currentTarget.releasePointerCapture(event.pointerId);\n    }\n    setIsDragging(false);\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    if (disabled) return;\n    const jump = largeStep ?? step * 10;\n\n    const next = {\n      ArrowDown: current - step,\n      ArrowLeft: current - step,\n      ArrowRight: current + step,\n      ArrowUp: current + step,\n      End: max,\n      Home: min,\n      PageDown: current - jump,\n      PageUp: current + jump,\n    }[event.key];\n\n    if (next === undefined) return;\n    event.preventDefault();\n    commit(next);\n  };\n\n  // Fraction digits follow the step, so a 0.25 step does not print as an integer.\n  const numberFormat = useMemo(() => {\n    const text = String(step);\n    const point = text.indexOf(\".\");\n    const digits = point === -1 ? 0 : Math.min(text.length - point - 1, 4);\n    return { maximumFractionDigits: digits, minimumFractionDigits: digits };\n  }, [step]);\n\n  const stepCount = Math.floor((max - min) / step) + 1;\n  const tickCount =\n    ticks === false ? 0 : (ticks ?? (stepCount >= 2 && stepCount <= 9 ? stepCount : 5));\n  const activeTick = tickCount > 1 ? Math.round(fraction * (tickCount - 1)) : 0;\n\n  const isTooltipOpen = !disabled && (isDragging || isPeeking);\n\n  return (\n    <div className={cn(\"w-full select-none\", disabled && \"opacity-50\", className)} {...props}>\n      <div className=\"relative\">\n        <AnimatePresence>\n          {isTooltipOpen ? (\n            <motion.div\n              animate={{ filter: \"blur(0px)\", opacity: 1, scale: 1, y: 0 }}\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute bottom-full left-0 z-10 mb-3 origin-bottom\"\n              exit={{\n                filter: reduceMotion ? \"blur(0px)\" : \"blur(6px)\",\n                opacity: 0,\n                scale: reduceMotion ? 1 : 0.92,\n                y: reduceMotion ? 0 : 8,\n              }}\n              initial={{\n                filter: reduceMotion ? \"blur(0px)\" : \"blur(6px)\",\n                opacity: 0,\n                scale: reduceMotion ? 1 : 0.92,\n                y: reduceMotion ? 0 : 8,\n              }}\n              style={{ transform: tooltipTransform }}\n              transition={{ duration: reduceMotion ? 0.12 : 0.24, ease: TOOLTIP_EASE }}\n            >\n              <div\n                className={cn(\n                  \"grid h-14 min-w-16 place-items-center rounded-[1.35rem] px-4\",\n                  \"bg-white text-[1.6rem] leading-none font-semibold text-neutral-700 tabular-nums\",\n                  \"shadow-[0_1px_2px_rgb(0_0_0/6%),0_10px_24px_-8px_rgb(0_0_0/18%)]\",\n                  \"dark:bg-[#242424] dark:text-neutral-100 dark:shadow-[0_1px_2px_rgb(0_0_0/40%),0_12px_28px_-8px_rgb(0_0_0/60%)]\",\n                )}\n              >\n                {renderTooltip ? (\n                  renderTooltip(current)\n                ) : (\n                  // NumberFlow reads the motion preference itself, and\n                  // `willChange` matters here: the value retargets on every\n                  // pointer move while dragging.\n                  <NumberFlow format={numberFormat} value={current} willChange />\n                )}\n              </div>\n            </motion.div>\n          ) : null}\n        </AnimatePresence>\n\n        <div\n          aria-disabled={disabled || undefined}\n          aria-labelledby={props[\"aria-label\"] ? undefined : labelId}\n          aria-orientation=\"horizontal\"\n          aria-valuemax={max}\n          aria-valuemin={min}\n          aria-valuenow={current}\n          aria-valuetext={valueText?.(current)}\n          className={cn(\n            \"relative h-16 w-full touch-none p-1 rounded-full outline-none\",\n            \"bg-white shadow-[inset_0_0_0_1px_rgb(0_0_0/5%),inset_0_2px_4px_rgb(0_0_0/6%)]\",\n            \"dark:bg-[#131313] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/8%),inset_0_2px_5px_rgb(0_0_0/50%)]\",\n            \"\",\n            disabled ? \"cursor-not-allowed\" : \"cursor-grab active:cursor-grabbing\",\n          )}\n          onKeyDown={handleKeyDown}\n          onPointerCancel={endDrag}\n          onPointerDown={handlePointerDown}\n          onPointerLeave={() => setIsPeeking(false)}\n          onPointerMove={handlePointerMove}\n          onPointerUp={endDrag}\n          onBlur={() => setIsPeeking(false)}\n          onFocus={(event) => {\n            if (event.currentTarget.matches(\":focus-visible\")) setIsPeeking(true);\n          }}\n          onPointerEnter={(event) => {\n            if (event.pointerType === \"mouse\") setIsPeeking(true);\n          }}\n          role=\"slider\"\n          tabIndex={disabled ? -1 : 0}\n        >\n          <div className=\"relative h-full w-full overflow-hidden rounded-full\" ref={railRef}>\n            <motion.div\n              aria-hidden=\"true\"\n              className={cn(\n                \"absolute inset-y-[0px] left-0 w-full rounded-full\",\n                \"bg-[linear-gradient(180deg,#fdf3ad_0%,#f9e37f_58%,#f6dc69_100%)]\",\n                \" \",\n              )}\n              style={{ transform: fillTransform }}\n            />\n\n            <motion.div\n              animate={{ scale: isDragging && !reduceMotion ? 1.04 : 1 }}\n              aria-hidden=\"true\"\n              className={cn(\n                \"absolute top-0 left-0 aspect-square h-full rounded-full\",\n                \"bg-[radial-gradient(120%_120%_at_50%_18%,#f8de55_0%,#f0cb1f_52%,#e3b70c_100%)]\",\n                \"shadow-[inset_0_1px_0_rgb(255_255_255/55%),0_2px_6px_rgb(190_150_0/38%),0_1px_2px_rgb(0_0_0/12%)]\",\n              )}\n              style={{ transform: thumbTransform }}\n              transition={SETTLE_SPRING}\n            />\n          </div>\n        </div>\n      </div>\n\n      {tickCount > 0 ? (\n        <div aria-hidden=\"true\" className=\"relative mt-3.5 h-1.5\">\n          {Array.from({ length: tickCount }, (_, index) => {\n            const tickFraction = tickCount === 1 ? 0 : index / (tickCount - 1);\n            return (\n              <motion.span\n                animate={{\n                  backgroundColor: index === activeTick ? \"#f0cb1f\" : \"#c9c9c9\",\n                  scale: index === activeTick ? 1.15 : 1,\n                }}\n                className=\"absolute top-0 left-0 block size-1.5 rounded-full\"\n                key={tickFraction}\n                style={{ x: rail.size / 2 + tickFraction * rail.travel - 3 }}\n                transition={{ duration: reduceMotion ? 0.1 : 0.22, ease: TOOLTIP_EASE }}\n              />\n            );\n          })}\n        </div>\n      ) : null}\n\n      <span className=\"sr-only\" id={labelId}>\n        Value\n      </span>\n    </div>\n  );\n}\n","type":"registry:ui"}],"categories":["input","form","animation"],"type":"registry:ui"}