{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "slider",
  "type": "registry:ui",
  "title": "Slider",
  "description": "An accessible React slider for Next.js and Tailwind: one value or a range, with a thumb that grows into a pill showing its value as you reach for it.",
  "author": "FewTone <https://fewtone.com>",
  "dependencies": [
    "motion@^14.0.0"
  ],
  "registryDependencies": [
    "https://ui.fewtone.com/r/tokens.json",
    "https://ui.fewtone.com/r/motion.json",
    "https://ui.fewtone.com/r/number-ticker.json"
  ],
  "files": [
    {
      "path": "registry/fewtone/ui/slider.tsx",
      "type": "registry:ui",
      "content": "\"use client\";\n\nimport { NumberTicker } from \"@/components/ui/number-ticker\";\nimport { blur, duration, ease, spring } from \"@/lib/motion\";\nimport { cn } from \"@/lib/utils\";\nimport {\n  type AnimationPlaybackControls,\n  animate,\n  type MotionValue,\n  motion,\n  motionValue,\n  useMotionValue,\n  useReducedMotion,\n  useTransform,\n  useVelocity,\n} from \"motion/react\";\nimport {\n  type ComponentProps,\n  type KeyboardEvent,\n  type PointerEvent,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\n\n/*\n * Slider: one value or a range (owner, 2026-10-16), redesigned as the value thumb the owner chose in the Lab\n * (2026-10-22), ported from it exactly: the same drawing, sizes and timings. The WAI-ARIA slider pattern, our own\n * rather than Radix's, because Radix places its thumbs itself and they didn't move like the Lab's.\n * - A thin track and a small round thumb that, the moment you reach for it (the pointer over the slider, keyboard\n *   focus, a drag), grows into a pill with the value inside. The number is the thumb, so there's no tooltip to\n *   float or follow; back at rest it shrinks to a dot. The value flows as it changes (our Number Ticker), and a\n *   quick drag counts through the values.\n * - Motion (.agents/rules/motion.md):\n *   - Press the track and the thumb glides to the point on spring.snappy; the keys and outside changes glide the\n *     same way. Dragging follows the pointer exactly.\n *   - Moving, the pill stretches along the track with its speed (up to a quarter, full at 900px/s) and settles\n *     round when it stops.\n *   - The pill grows and shrinks on spring.snappy; its number comes through the blur (duration.base in,\n *     duration.fast out).\n *   - The track thickens from 4px to 6px while a thumb is open.\n * - Behaviour: each thumb is a `role=\"slider\"` with arrow keys (Shift for ten steps), Page Up/Down (ten steps),\n *   Home/End. A press on the track moves the nearest thumb there and focuses it; a range's thumbs can't cross.\n *   Vertical, right to left and inverted. With `name`, a hidden input per value submits it with a form.\n * - Nothing animates on first paint. With reduced motion the thumb jumps, doesn't stretch, the track keeps its\n *   thickness and the number only fades.\n */\n\n/** The thumb at rest, and grown into a pill (at least this wide; wider for a longer value), in px */\nconst DOT = 14;\nconst PILL = { width: 46, height: 26 };\n/** The room either side of the value in the pill, in px */\nconst PILL_PAD = 10;\n/** Moving, the pill stretches along the track by up to a quarter, full at this speed in px a second */\nconst STRETCH = 0.25;\nconst FULL_SPEED = 900;\n/** While a thumb is open, the track thickens from 4px to 6px */\nconst THICK = 1.5;\n/** Shift with an arrow, and Page Up/Down, move this many steps */\nconst BIG_STEP = 10;\n\n/** How the last focus came: the keyboard opens a thumb's pill on focus, a pointer doesn't */\nlet keyboardLast = false;\nlet listening = false;\nfunction watchModality() {\n  if (listening || typeof window === \"undefined\") return;\n  listening = true;\n  window.addEventListener(\"keydown\", () => (keyboardLast = true), true);\n  window.addEventListener(\"pointerdown\", () => (keyboardLast = false), true);\n}\n\nexport type SliderProps = Omit<ComponentProps<\"div\">, \"defaultValue\" | \"dir\" | \"onChange\"> & {\n  /** The values, when you control them: one number per thumb, two for a range */\n  value?: number[];\n  /** The values at first */\n  defaultValue?: number[];\n  /** Called on every change, while dragging too */\n  onValueChange?: (value: number[]) => void;\n  /** Called once a drag ends or a key changes the value */\n  onValueCommit?: (value: number[]) => void;\n  min?: number;\n  max?: number;\n  step?: number;\n  /** How many steps a range's thumbs keep apart */\n  minStepsBetweenThumbs?: number;\n  orientation?: \"horizontal\" | \"vertical\";\n  /** Right to left puts the lowest value on the right */\n  dir?: \"ltr\" | \"rtl\";\n  /** Puts the lowest value at the other end */\n  inverted?: boolean;\n  disabled?: boolean;\n  /** Submits the values with a form, through a hidden input per thumb */\n  name?: string;\n  form?: string;\n  /** Intl.NumberFormat options for the value in the thumb and for screen readers, for example { style: \"currency\", currency: \"USD\" } */\n  format?: Intl.NumberFormatOptions;\n  /** The locale to format in. en-US unless you pass one, so the server and the browser agree */\n  locale?: string;\n  /** A name for each thumb. Without it, a range's thumbs are named from aria-label: \"Price, minimum\". */\n  thumbLabels?: string[];\n};\n\n/**\n * Pick a value, or a range with two values, by dragging, pressing the track or with the keys. `value` and\n * `defaultValue` are arrays: one number for one thumb, two for a range. Name it with aria-label or\n * aria-labelledby; the name moves to the thumbs, which are the sliders screen readers see.\n */\nfunction Slider({\n  className,\n  value,\n  defaultValue,\n  onValueChange,\n  onValueCommit,\n  min = 0,\n  max = 100,\n  step = 1,\n  minStepsBetweenThumbs = 0,\n  orientation = \"horizontal\",\n  dir = \"ltr\",\n  inverted = false,\n  disabled = false,\n  name,\n  form,\n  format,\n  locale = \"en-US\",\n  thumbLabels,\n  \"aria-label\": ariaLabel,\n  \"aria-labelledby\": ariaLabelledby,\n  onPointerEnter,\n  onPointerLeave,\n  onPointerDown,\n  onPointerMove,\n  onPointerUp,\n  onPointerCancel,\n  ref,\n  ...props\n}: SliderProps) {\n  const [uncontrolled, setUncontrolled] = useState(defaultValue ?? [min]);\n  const values = value ?? uncontrolled;\n  const count = values.length;\n  const reduce = useReducedMotion() ?? false;\n  const vertical = orientation === \"vertical\";\n  // Drawn from the far end: vertical sliders grow upwards, right-to-left or inverted ones the other way\n  const flip = vertical ? !inverted : (dir === \"rtl\") !== inverted;\n  const thumbId = useId();\n  const formatKey = JSON.stringify(format ?? {});\n  // biome-ignore lint/correctness/useExhaustiveDependencies: format is compared through formatKey\n  const formatter = useMemo(() => new Intl.NumberFormat(locale, format), [locale, formatKey]);\n\n  const root = useRef<HTMLDivElement>(null);\n  const thumbs = useRef<(HTMLSpanElement | null)[]>([]);\n  // The track's length along its axis, as a motion value so the drawing always uses the latest measure\n  const size = useMotionValue(256);\n  const [hovered, setHovered] = useState(false);\n  const [focused, setFocused] = useState<{ index: number; keyboard: boolean } | null>(null);\n  // The thumb being moved by the pointer, and whether the pointer has moved since pressing (a drag)\n  const [active, setActive] = useState<{ index: number; dragging: boolean } | null>(null);\n\n  useEffect(watchModality, []);\n\n  useEffect(() => {\n    const node = root.current;\n    if (!node) return;\n    const measure = () => size.set(vertical ? node.offsetHeight : node.offsetWidth);\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, [size, vertical]);\n\n  const progressOf = (number: number) =>\n    max === min ? 0 : Math.min(1, Math.max(0, (number - min) / (max - min)));\n  const places = String(step).split(\".\")[1]?.length ?? 0;\n  const snap = (number: number) => Number((Math.round((number - min) / step) * step + min).toFixed(places));\n\n  /** Sets one thumb's value, inside the range and clear of its neighbours */\n  const setThumb = (index: number, wanted: number, commit = false) => {\n    const gap = minStepsBetweenThumbs * step;\n    const lower = index > 0 ? (values[index - 1] ?? min) + gap : min;\n    const upper = index < count - 1 ? (values[index + 1] ?? max) - gap : max;\n    const next = Math.min(upper, Math.max(lower, snap(Math.min(max, Math.max(min, wanted)))));\n    if (next === values[index]) {\n      if (commit) onValueCommit?.(values);\n      return;\n    }\n    const all = values.map((current, at) => (at === index ? next : current));\n    if (value === undefined) setUncontrolled(all);\n    onValueChange?.(all);\n    if (commit) onValueCommit?.(all);\n  };\n\n  // Where each thumb is drawn, 0 to 1 along the axis: it glides to a pressed point or a key's step on\n  // spring.snappy, and follows at once while dragged. Nothing moves on first paint.\n  // biome-ignore lint/correctness/useExhaustiveDependencies: one motion value per thumb, made when the count changes\n  const drawn = useMemo(() => values.map((current) => motionValue(progressOf(current))), [count]);\n  const glides = useRef(new Map<number, AnimationPlaybackControls>());\n  const progresses = values.map(progressOf);\n  const progressKey = progresses.join(\",\");\n  // biome-ignore lint/correctness/useExhaustiveDependencies: only a change of the values or the drag moves them\n  useEffect(() => {\n    progresses.forEach((target, index) => {\n      const mark = drawn[index];\n      if (!mark || mark.get() === target) return;\n      glides.current.get(index)?.stop();\n      if (reduce || (active?.index === index && active.dragging)) {\n        mark.jump(target);\n        return;\n      }\n      glides.current.set(index, animate(mark, target, spring.snappy));\n    });\n  }, [progressKey, active?.dragging, reduce, drawn]);\n  useEffect(() => {\n    const running = glides.current;\n    return () => {\n      for (const glide of running.values()) glide.stop();\n    };\n  }, []);\n\n  /** Where along the track (0 to 1, from the lowest value's end) the pointer is */\n  const fractionAt = (event: PointerEvent<HTMLElement>) => {\n    const box = event.currentTarget.getBoundingClientRect();\n    const length = vertical ? box.height : box.width;\n    if (length <= 0) return 0;\n    const along = vertical ? (event.clientY - box.top) / length : (event.clientX - box.left) / length;\n    const clamped = Math.min(1, Math.max(0, along));\n    return flip ? 1 - clamped : clamped;\n  };\n  const valueAt = (fraction: number) => min + fraction * (max - min);\n\n  const onKeyDown = (index: number) => (event: KeyboardEvent) => {\n    if (disabled) return;\n    const current = values[index] ?? min;\n    const big = step * BIG_STEP;\n    // Left and right follow the page's direction (and inverted); up and down always mean more and less\n    const forwards = (dir === \"rtl\") !== inverted ? -1 : 1;\n    const by = (amount: number) => (event.shiftKey ? big : step) * amount;\n    const moves: Record<string, number> = {\n      ArrowRight: by(vertical ? 1 : forwards),\n      ArrowLeft: by(vertical ? -1 : -forwards),\n      ArrowUp: by(1),\n      ArrowDown: by(-1),\n      PageUp: big,\n      PageDown: -big,\n    };\n    if (event.key in moves) setThumb(index, current + (moves[event.key] ?? 0), true);\n    else if (event.key === \"Home\") setThumb(index, min, true);\n    else if (event.key === \"End\") setThumb(index, max, true);\n    else return;\n    event.preventDefault();\n  };\n\n  /** Each thumb's accessible name, from thumbLabels or the slider's own name */\n  const nameOf = (index: number) => {\n    const own = thumbLabels?.[index];\n    if (own) return { \"aria-label\": own };\n    if (count === 1) return { \"aria-label\": ariaLabel, \"aria-labelledby\": ariaLabelledby };\n    const part = count === 2 ? (index === 0 ? \"minimum\" : \"maximum\") : `value ${index + 1} of ${count}`;\n    const id = `${thumbId}-${index}`;\n    // \"Price minimum\": the label's text, then the thumb's own part\n    if (ariaLabelledby) return { id, \"aria-label\": part, \"aria-labelledby\": `${ariaLabelledby} ${id}` };\n    if (ariaLabel) return { \"aria-label\": `${ariaLabel}, ${part}` };\n    return {};\n  };\n\n  const isOpen = (index: number) =>\n    !disabled &&\n    (hovered ||\n      (focused?.index === index && focused.keyboard) ||\n      (active?.index === index && active.dragging));\n  const anyOpen = values.some((_, index) => isOpen(index));\n\n  // The range: the whole track's fill, moved to the lower thumb and scaled to reach the upper one\n  const low = count > 1 ? drawn[0] : undefined;\n  const high = drawn[count - 1];\n  const zero = useMotionValue(0);\n  // In percent of the fill's own (full) length, so the server's HTML already draws it in place\n  const fillStart = useTransform(low ?? zero, (p) => `${(flip ? -1 : 1) * p * 100}%`);\n  const fillLength = useTransform([low ?? zero, high ?? zero], ([from = 0, to = 0]: number[]) =>\n    Math.max(0, to - from),\n  );\n\n  return (\n    <div\n      ref={(node) => {\n        root.current = node;\n        if (typeof ref === \"function\") ref(node);\n        else if (ref) ref.current = node;\n      }}\n      data-slot=\"slider\"\n      data-orientation={orientation}\n      data-disabled={disabled || undefined}\n      className={cn(\n        \"relative touch-none select-none\",\n        vertical ? \"h-full min-h-44 w-11\" : \"h-11 w-full\",\n        disabled ? \"cursor-not-allowed opacity-(--opacity-disabled)\" : \"cursor-pointer\",\n        className,\n      )}\n      onPointerEnter={(event) => {\n        onPointerEnter?.(event);\n        if (event.pointerType === \"mouse\") setHovered(true);\n      }}\n      onPointerLeave={(event) => {\n        onPointerLeave?.(event);\n        setHovered(false);\n      }}\n      onPointerDown={(event) => {\n        onPointerDown?.(event);\n        if (event.defaultPrevented || disabled || event.button !== 0) return;\n        event.currentTarget.setPointerCapture?.(event.pointerId);\n        const wanted = valueAt(fractionAt(event));\n        // The nearest thumb moves; between two equally near, the one on the side pressed\n        let index = 0;\n        values.forEach((current, at) => {\n          const best = Math.abs((values[index] ?? 0) - wanted);\n          const here = Math.abs(current - wanted);\n          if (here < best || (here === best && wanted > current)) index = at;\n        });\n        setActive({ index, dragging: false });\n        setThumb(index, wanted);\n        thumbs.current[index]?.focus({ preventScroll: true });\n        event.preventDefault();\n      }}\n      onPointerMove={(event) => {\n        onPointerMove?.(event);\n        if (!active) return;\n        if (!active.dragging) setActive({ index: active.index, dragging: true });\n        setThumb(active.index, valueAt(fractionAt(event)));\n      }}\n      onPointerUp={(event) => {\n        onPointerUp?.(event);\n        if (active) onValueCommit?.(values);\n        setActive(null);\n      }}\n      onPointerCancel={(event) => {\n        onPointerCancel?.(event);\n        setActive(null);\n      }}\n      {...props}\n    >\n      <motion.span\n        aria-hidden\n        data-slot=\"slider-track\"\n        className={cn(\n          \"absolute overflow-hidden rounded-full bg-muted\",\n          vertical ? \"inset-y-0 left-1/2 w-1 -translate-x-1/2\" : \"inset-x-0 top-1/2 h-1 -translate-y-1/2\",\n        )}\n        initial={false}\n        // Thicker while a thumb is open: the slider wakes under the hand\n        animate={\n          vertical ? { scaleX: anyOpen && !reduce ? THICK : 1 } : { scaleY: anyOpen && !reduce ? THICK : 1 }\n        }\n        transition={reduce ? { duration: 0 } : spring.snappy}\n      >\n        <motion.span\n          data-slot=\"slider-range\"\n          className={cn(\n            \"absolute inset-0 bg-primary\",\n            vertical ? (flip ? \"origin-bottom\" : \"origin-top\") : flip ? \"origin-right\" : \"origin-left\",\n          )}\n          style={vertical ? { y: fillStart, scaleY: fillLength } : { x: fillStart, scaleX: fillLength }}\n        />\n      </motion.span>\n      {values.map((thumbValue, index) => (\n        <Thumb\n          // biome-ignore lint/suspicious/noArrayIndexKey: a thumb is its place in the sorted values\n          key={index}\n          ref={(node) => {\n            thumbs.current[index] = node;\n          }}\n          value={thumbValue}\n          drawn={drawn[index] ?? zero}\n          size={size}\n          vertical={vertical}\n          flip={flip}\n          open={isOpen(index)}\n          disabled={disabled}\n          min={min}\n          max={max}\n          names={nameOf(index)}\n          valueText={format ? formatter.format(thumbValue) : undefined}\n          format={format}\n          locale={locale}\n          reduce={reduce}\n          onKeyDown={onKeyDown(index)}\n          onFocus={() => setFocused({ index, keyboard: keyboardLast })}\n          onBlur={() => setFocused((current) => (current?.index === index ? null : current))}\n        />\n      ))}\n      {name\n        ? values.map((current, index) => (\n            <input\n              // biome-ignore lint/suspicious/noArrayIndexKey: one input per thumb, in order\n              key={index}\n              type=\"hidden\"\n              name={count > 1 ? `${name}[]` : name}\n              form={form}\n              value={current}\n              disabled={disabled}\n            />\n          ))\n        : null}\n    </div>\n  );\n}\n\ntype ThumbProps = {\n  ref: (node: HTMLSpanElement | null) => void;\n  value: number;\n  drawn: MotionValue<number>;\n  size: MotionValue<number>;\n  vertical: boolean;\n  flip: boolean;\n  open: boolean;\n  disabled: boolean;\n  min: number;\n  max: number;\n  names: { id?: string; \"aria-label\"?: string; \"aria-labelledby\"?: string };\n  valueText?: string;\n  format?: Intl.NumberFormatOptions;\n  locale: string;\n  reduce: boolean;\n  onKeyDown: (event: KeyboardEvent) => void;\n  onFocus: () => void;\n  onBlur: () => void;\n};\n\n/** One thumb: a dot at rest, a pill with the value while it's reached for. It's the slider screen readers see. */\nfunction Thumb({\n  ref,\n  value,\n  drawn,\n  size,\n  vertical,\n  flip,\n  open,\n  disabled,\n  min,\n  max,\n  names,\n  valueText,\n  format,\n  locale,\n  reduce,\n  onKeyDown,\n  onFocus,\n  onBlur,\n}: ThumbProps) {\n  // Its centre sits at its value's point on the track, so it travels the whole length. Placed in percent of\n  // the slider, so it's in place from the server's HTML on, before anything is measured (a measured length\n  // drew it at a guess until the page woke up, owner 2026-10-22).\n  const at = useTransform(drawn, (p) => `${(flip ? 1 - p : p) * 100}%`);\n  // The faster it moves, the longer the pill (its speed in px a second, from the measured length); at rest,\n  // round again\n  const speed = useVelocity(drawn);\n  const stretch = useTransform([speed, size], ([velocity = 0, length = 0]: number[]) =>\n    reduce ? 1 : 1 + STRETCH * Math.min(1, Math.abs(velocity * length) / FULL_SPEED),\n  );\n  // The pill fits its value: as wide as the text plus its room, never narrower than the Lab's 46px, so a long\n  // value (\"51 hours\") never spills out (owner, 2026-10-22); a change of width glides on the same spring\n  const content = useRef<HTMLSpanElement>(null);\n  const [fit, setFit] = useState(0);\n  useLayoutEffect(() => {\n    const node = content.current;\n    if (!node) return;\n    const measure = () => setFit(node.offsetWidth);\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(node);\n    return () => observer.disconnect();\n  }, []);\n  const pill = { width: Math.max(PILL.width, fit + PILL_PAD * 2), height: PILL.height };\n\n  return (\n    <motion.span\n      ref={ref}\n      role=\"slider\"\n      tabIndex={disabled ? -1 : 0}\n      {...names}\n      aria-valuemin={min}\n      aria-valuemax={max}\n      aria-valuenow={value}\n      aria-valuetext={valueText}\n      aria-orientation={vertical ? \"vertical\" : \"horizontal\"}\n      aria-disabled={disabled || undefined}\n      data-slot=\"slider-thumb\"\n      data-open={open || undefined}\n      onKeyDown={onKeyDown}\n      onFocus={onFocus}\n      onBlur={onBlur}\n      className={cn(\n        \"absolute flex items-center justify-center overflow-hidden rounded-full bg-primary text-xs font-medium whitespace-nowrap text-primary-foreground tabular-nums\",\n        \"outline-ring focus-visible:outline-(length:--focus-ring-width) focus-visible:outline-offset-(--focus-ring-offset)\",\n        vertical ? \"left-1/2 -translate-x-1/2 -translate-y-1/2\" : \"top-1/2 -translate-x-1/2 -translate-y-1/2\",\n      )}\n      style={vertical ? { top: at, scaleY: stretch } : { left: at, scaleX: stretch }}\n      initial={false}\n      animate={open ? pill : { width: DOT, height: DOT }}\n      transition={reduce ? { duration: 0 } : spring.snappy}\n    >\n      <motion.span\n        ref={content}\n        aria-hidden\n        className=\"shrink-0\"\n        initial={false}\n        animate={\n          open\n            ? { opacity: 1, filter: blur.shown, scale: 1 }\n            : { opacity: 0, filter: reduce ? blur.shown : blur.hidden, scale: reduce ? 1 : 0.6 }\n        }\n        transition={\n          reduce\n            ? { duration: 0 }\n            : { duration: open ? duration.base : duration.fast, ease: open ? ease.out : ease.in }\n        }\n      >\n        {/* The value flows as it changes; nothing rolls when the pill first opens */}\n        <NumberTicker value={value} from={value} startOnView={false} format={format} locale={locale} />\n      </motion.span>\n    </motion.span>\n  );\n}\n\nexport { Slider };\n"
    }
  ],
  "categories": [
    "forms"
  ],
  "docs": "Usage and examples: https://ui.fewtone.com/components/slider"
}
