Slider
Grab anywhere on the track and it follows your finger 1:1. Pull past an end and the track squashes like rubber; let go and it springs to the nearest step.
npx shadcn@latest add https://captain-ui.vercel.app/r/slider.jsonAgents in parallel4 agents
Spend cap per run$12.50
Agents may merge09:00 to 17:30
Worst case today: $50.00 if all 4 hit the cap.
"use client";
// Captain UI · Slider, MIT. Grab anywhere on the track and it follows 1:1; pull past an end and the track squashes like rubber.
import { animate, motion, useMotionValue, useReducedMotion, useTransform, type AnimationPlaybackControls } from "motion/react";
import { useEffect, useId, useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode } from "react";
import { SPRING, SPRING_RELEASE, clamp, cx, rubber, useIsoLayoutEffect } from "@/registry/captain/ui/captain";
type SliderProps = {
/** One value, or two for a range. Controlled. */
value?: number[];
defaultValue?: number[];
/** Called as the value steps, while dragging and from the keyboard. */
onValueChange?: (value: number[]) => void;
/** Called once when a drag or key press ends. */
onValueCommit?: (value: number[]) => void;
min?: number;
max?: number;
step?: number;
/** Range only: the closest the two thumbs may get, in steps. */
minStepsBetweenThumbs?: number;
/** Marks every step on the track (up to 40 of them). */
ticks?: boolean;
label?: ReactNode;
/** Formats the readout and aria-valuetext. */
format?: (value: number) => string;
/** Accessible names for the thumbs, e.g. ["Start", "End"]. */
thumbLabels?: string[];
"aria-label"?: string;
disabled?: boolean;
className?: string;
};
const R = 11; // thumb half-size
const OVER = 22; // how far the rubber band can stretch, px
const THUMB = "shadow-[0_1px_1px_rgba(17,18,20,.12),0_2px_6px_rgba(17,18,20,.14),inset_0_-1px_0_rgba(17,18,20,.05)]";
export function Slider({
value,
defaultValue,
onValueChange,
onValueCommit,
min = 0,
max = 100,
step = 1,
minStepsBetweenThumbs = 0,
ticks = false,
label,
format = String,
thumbLabels,
disabled,
className,
...rest
}: SliderProps) {
const [inner, setInner] = useState<number[]>(defaultValue ?? [min]);
const values = value ?? inner;
const range = values.length > 1;
const span = max - min || 1;
const decimals = (String(step).split(".")[1] ?? "").length;
const frac = (v: number) => (v - min) / span;
const snap = (v: number) => Number(clamp(Math.round((v - min) / step) * step + min, min, max).toFixed(decimals));
const gap = (minStepsBetweenThumbs * step) / span;
const v0 = values[0] ?? min;
const f0 = useMotionValue(frac(v0));
const f1 = useMotionValue(frac(values[1] ?? v0));
const fOf = (i: number) => (i === 1 ? f1 : f0);
const at = (list: number[], i: number) => list[i] ?? list[0] ?? min;
const end = range ? f1 : f0;
const rail = useRef<HTMLDivElement>(null);
const thumbs = useRef<Array<HTMLDivElement | null>>([]);
const width = useRef(260);
const live = useRef(values);
live.current = values;
const reduce = useReducedMotion();
const tap = useRef<AnimationPlaybackControls | null>(null);
const drag = useRef<{ id: number; i: number; x: number; from: number; t: number; last: number; v: number } | null>(null);
const [active, setActive] = useState<number | null>(null);
// Programmatic focus from a press would light :focus-visible, so keyboard focus is tracked by hand.
const [kb, setKb] = useState<number | null>(null);
const labelId = useId();
useIsoLayoutEffect(() => {
const el = rail.current;
if (!el) return;
const ro = new ResizeObserver(() => (width.current = el.clientWidth || width.current));
ro.observe(el);
return () => ro.disconnect();
}, []);
const key = values.join(",");
useEffect(() => {
if (drag.current) return;
live.current.slice(0, 2).forEach((v, i) => animate(fOf(i), frac(v), reduce ? { duration: 0 } : SPRING));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, min, max, reduce]);
// Past an end the rail stretches toward the finger and thins, anchored at the far end.
const over = (a: number, b: number) => Math.max(0, -a) + Math.max(0, b - 1);
const scaleX = useTransform([f0, end], ([a = 0, b = 0]: number[]) => 1 + over(a, b));
const scaleY = useTransform([f0, end], ([a = 0, b = 0]: number[]) => 1 - Math.min(0.4, ((over(a, b) * width.current) / OVER) * 0.4));
const originX = useTransform(f0, (a) => (a < 0 ? 1 : 0));
const fillX = useTransform(f0, (a) => `${range ? clamp(a, 0, 1) * 100 : 0}%`);
const fillS = useTransform([f0, end], ([a = 0, b = 0]: number[]) => (range ? clamp(b, 0, 1) - clamp(a, 0, 1) : clamp(a, 0, 1)));
const x0 = useTransform(f0, (a) => `${a * 100}%`);
const x1 = useTransform(f1, (a) => `${a * 100}%`);
const commit = (next: number[]) => {
if (next.every((v, i) => v === live.current[i])) return;
live.current = next;
if (value === undefined) setInner(next);
onValueChange?.(next);
};
const bounds = (i: number) => ({
lo: range && i === 1 ? f0.get() + gap : 0,
hi: range && i === 0 ? f1.get() - gap : 1,
});
const place = (i: number, f: number) => {
const next = [...live.current];
next[i] = snap(min + clamp(f, 0, 1) * span);
commit(next);
};
const down = (e: PointerEvent<HTMLDivElement>) => {
if (disabled || e.button !== 0 || !rail.current) return;
const r = rail.current.getBoundingClientRect();
width.current = r.width;
const p = (e.clientX - r.left) / r.width;
const hit = (e.target as HTMLElement).closest<HTMLElement>("[data-thumb]");
let i = 0;
if (hit) i = Number(hit.dataset.thumb);
else if (range) {
const a = f0.get();
const b = f1.get();
i = p <= a ? 0 : p >= b ? 1 : p - a < b - p ? 0 : 1;
}
e.currentTarget.setPointerCapture(e.pointerId);
setKb(null);
thumbs.current[i]?.focus({ preventScroll: true });
let from = fOf(i).get();
if (!hit) {
const { lo, hi } = bounds(i);
from = clamp(p, lo, hi);
tap.current = animate(fOf(i), from, reduce ? { duration: 0 } : { type: "spring", stiffness: 900, damping: 60 });
place(i, from);
}
drag.current = { id: e.pointerId, i, x: e.clientX, from, t: performance.now(), last: e.clientX, v: 0 };
setActive(i);
};
const move = (e: PointerEvent<HTMLDivElement>) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
if (Math.abs(e.clientX - d.x) < 1) return;
tap.current?.stop();
const W = width.current;
const raw = d.from + (e.clientX - d.x) / W;
const { lo, hi } = bounds(d.i);
let f = clamp(raw, lo, hi);
if (raw < lo && lo <= 0) f = rubber((raw - lo) * W, OVER) / W;
if (raw > hi && hi >= 1) f = 1 + rubber((raw - hi) * W, OVER) / W;
fOf(d.i).set(f);
place(d.i, f);
const now = performance.now();
d.v = ((e.clientX - d.last) / Math.max(1, now - d.t)) * 1000;
d.t = now;
d.last = e.clientX;
};
const up = (e: PointerEvent<HTMLDivElement>) => {
const d = drag.current;
if (!d || d.id !== e.pointerId) return;
drag.current = null;
setActive(null);
const v = clamp(d.v, -900, 900) / width.current;
animate(fOf(d.i), frac(at(live.current, d.i)), reduce ? { duration: 0 } : { ...SPRING_RELEASE, velocity: v });
onValueCommit?.(live.current);
};
const onKey = (i: number) => (e: KeyboardEvent<HTMLDivElement>) => {
if (disabled) return;
setKb(i);
const big = Math.max(step, Math.round(span / 10 / step) * step);
const lo = range && i === 1 ? at(values, 0) + minStepsBetweenThumbs * step : min;
const hi = range && i === 0 ? at(values, 1) - minStepsBetweenThumbs * step : max;
let v = at(values, i);
if (e.key === "ArrowRight" || e.key === "ArrowUp") v += e.shiftKey ? big : step;
else if (e.key === "ArrowLeft" || e.key === "ArrowDown") v -= e.shiftKey ? big : step;
else if (e.key === "PageUp") v += big;
else if (e.key === "PageDown") v -= big;
else if (e.key === "Home") v = lo;
else if (e.key === "End") v = hi;
else return;
e.preventDefault();
const next = [...values];
next[i] = snap(clamp(v, lo, hi));
commit(next);
onValueCommit?.(next);
};
const count = Math.round(span / step);
const marks = ticks && count <= 40 ? Array.from({ length: count - 1 }, (_, k) => (k + 1) / count) : [];
const lowF = range ? frac(v0) : 0;
const highF = frac(at(values, values.length - 1));
return (
<div className={cx("w-full select-none", disabled && "opacity-45", className)}>
{label ? (
<div className="flex items-baseline justify-between gap-4 text-[13px]">
<span id={labelId} className="text-ink-2">
{label}
</span>
<span className="tnum text-ink">{values.map(format).join(" to ")}</span>
</div>
) : null}
<div
className={cx("relative h-11 touch-none px-[11px]", disabled ? "cursor-not-allowed" : "cursor-pointer")}
onPointerDown={down}
onPointerMove={move}
onPointerUp={up}
onPointerCancel={up}
>
<div ref={rail} className="relative h-full">
<motion.div
className="well absolute inset-x-0 top-1/2 -mt-1 h-2 overflow-hidden rounded-[4px]"
style={{ scaleX, scaleY, originX }}
>
<motion.div className="absolute inset-y-0 left-0 w-full origin-left bg-primary" style={{ x: fillX, scaleX: fillS }} />
{marks.map((m) => {
const on = m >= lowF - 1e-9 && m <= highF + 1e-9;
return (
<span
key={m}
className={cx("absolute top-1/2 -mt-[2px] -ml-px h-1 w-0.5 rounded-[1px] transition-colors duration-150", on ? "bg-primary-ink/45" : "bg-ink/20")}
style={{ left: `${m * 100}%` }}
/>
);
})}
</motion.div>
{values.slice(0, 2).map((v, i) => (
<motion.div key={i} className="pointer-events-none absolute inset-0" style={{ x: i === 0 ? x0 : x1 }}>
<div
ref={(el) => {
thumbs.current[i] = el;
}}
data-thumb={i}
role="slider"
tabIndex={disabled ? -1 : 0}
aria-valuemin={range && i === 1 ? v0 : min}
aria-valuemax={range && i === 0 ? at(values, 1) : max}
aria-valuenow={v}
aria-valuetext={format(v)}
aria-orientation="horizontal"
aria-disabled={disabled || undefined}
aria-label={thumbLabels?.[i] ?? (label ? undefined : rest["aria-label"])}
aria-labelledby={!thumbLabels?.[i] && label ? labelId : undefined}
data-active={active === i || undefined}
onKeyDown={onKey(i)}
onKeyUp={(e) => e.key === "Tab" && setKb(i)}
onBlur={() => setKb(null)}
className={cx(
"pointer-events-auto absolute top-1/2 left-0 grid place-items-center rounded-[7px] bg-white transition-[scale,box-shadow] duration-150 ease-snap data-[active]:scale-110",
THUMB,
"data-[active]:shadow-[0_1px_1px_rgba(17,18,20,.12),0_4px_10px_rgba(17,18,20,.16),inset_0_-1px_0_rgba(17,18,20,.05)]",
)}
style={{ width: R * 2, height: R * 2, marginLeft: -R, marginTop: -R }}
>
<span className={cx("w-0.5 rounded-[1px] transition-[background-color,height] duration-150", kb === i ? "h-2.5 bg-accent" : "h-2 bg-[rgba(17,18,20,.16)]")} />
</div>
</motion.div>
))}
</div>
</div>
</div>
);
}Usage
import { Slider } from "@/components/ui/slider"
<Slider label="Spend cap per run" defaultValue={[12.5]} max={50} step={2.5} format={(v) => `$${v.toFixed(2)}`} />
<Slider label="Agents may merge" defaultValue={[9, 17.5]} min={6} max={22} step={0.5} />Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| value | number[] | Controlled. One value, or two for a range. | |
| defaultValue | number[] | [min] | Initial value when uncontrolled. |
| onValueChange | (value: number[]) => void | Called each time the value steps. | |
| onValueCommit | (value: number[]) => void | Called when a drag or key press ends. | |
| min / max / step | number | 0 / 100 / 1 | The scale. Decimal steps are kept exact. |
| minStepsBetweenThumbs | number | 0 | Range only: how close the thumbs may get. |
| ticks | boolean | false | Marks each step on the track, up to 40. |
| label | ReactNode | Shown above the track with the live readout. | |
| format | (value: number) => string | String | Formats the readout and aria-valuetext. |
| thumbLabels | string[] | Names for each thumb, read by screen readers. | |
| disabled | boolean | Dims and ignores input. |
Keyboard
- ← →
- One step
- Shift + ← →
- Ten steps
- Page Up / Down
- Ten steps
- Home / End
- Minimum / maximum
Accessibility
- Each thumb is role=slider with aria-valuenow, aria-valuetext and its own bounds.
- Range thumbs cannot cross; their min and max follow each other.
- Pressing the track focuses the thumb it moves, so the keyboard carries on from there.