Scrub number
A number field you scrub by dragging its label: Shift for ten times faster, Alt for a tenth. Click the number to type, and the digits roll as it changes.
npx shadcn@latest add https://captain-ui.vercel.app/r/scrub-number.jsonBatch run
Runs
Each
Temperature
Timeout
s
Budget for the batch
$44.40
24 runs × $1.85
Drag any label sideways to scrub its number, or click the number to type.
"use client";
// Captain UI · Scrub number, MIT. Drag the label to scrub (Shift ×10, Alt ×0.1), or click the number and type. Digits roll as it changes.
import { AnimatePresence, animate, motion, useMotionValue, useReducedMotion } from "motion/react";
import { useId, useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode } from "react";
import { EASE, SPRING, SPRING_RELEASE, clamp, cx, rubber } from "@/registry/captain/ui/captain";
type ScrubNumberProps = {
value?: number;
defaultValue?: number;
onValueChange?: (value: number) => void;
min?: number;
max?: number;
step?: number;
/** Pixels of drag per step. */
pixelsPerStep?: number;
/** The drag handle and the field's name. */
label: ReactNode;
prefix?: string;
unit?: string;
/** Formats the number (without prefix or unit). Defaults to grouped digits at the step's precision. */
format?: (value: number) => string;
disabled?: boolean;
className?: string;
};
const places = (n: number) => {
const s = String(n);
if (s.includes("e-")) return Number(s.split("e-")[1]);
return (s.split(".")[1] ?? "").length;
};
const round = (v: number, q: number) => Number((Math.round(v / q) * q).toFixed(places(q)));
export function ScrubNumber({
value,
defaultValue = 0,
onValueChange,
min = -Infinity,
max = Infinity,
step = 1,
pixelsPerStep = 2,
label,
prefix = "",
unit,
format,
disabled,
className,
}: ScrubNumberProps) {
const [inner, setInner] = useState(defaultValue);
const v = value ?? inner;
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState("");
const [scrubbing, setScrubbing] = useState(false);
const input = useRef<HTMLInputElement>(null);
const nudge = useMotionValue(0);
const reduce = useReducedMotion();
const id = useId();
const live = useRef(v);
live.current = v;
const s = useRef<{ id: number; last: number; cur: number; over: number; moved: number; x: number } | null>(null);
const dp = Math.max(places(step), places(v));
const show = (n: number) =>
format ? format(n) : n.toLocaleString("en-GB", { minimumFractionDigits: places(step), maximumFractionDigits: Math.max(places(step), Math.min(dp, 6)) });
const set = (n: number) => {
const next = clamp(n, min, max);
if (next === live.current) return;
live.current = next;
if (value === undefined) setInner(next);
onValueChange?.(next);
};
const down = (e: PointerEvent<HTMLSpanElement>) => {
if (disabled || e.button !== 0) return;
e.preventDefault();
e.currentTarget.setPointerCapture(e.pointerId);
s.current = { id: e.pointerId, last: e.clientX, cur: live.current, over: 0, moved: 0, x: e.clientX };
};
const move = (e: PointerEvent<HTMLSpanElement>) => {
const d = s.current;
if (!d || d.id !== e.pointerId) return;
const dx = e.clientX - d.last;
d.last = e.clientX;
d.moved = Math.max(d.moved, Math.abs(e.clientX - d.x));
if (d.moved < 3) return;
if (!scrubbing) {
setScrubbing(true);
document.documentElement.style.cursor = "ew-resize";
}
const mult = e.shiftKey ? 10 : e.altKey ? 0.1 : 1;
const q = step * mult;
const per = q / pixelsPerStep;
// Spend any stored overshoot first, so turning back responds at once.
let px = dx;
if (d.over !== 0 && Math.sign(px) !== Math.sign(d.over)) {
const used = Math.sign(px) * Math.min(Math.abs(px), Math.abs(d.over));
d.over += used;
px -= used;
}
let raw = d.cur + px * per;
if (raw > max) {
d.over += (raw - max) / per;
raw = max;
} else if (raw < min) {
d.over += (raw - min) / per;
raw = min;
}
d.cur = raw;
nudge.set(rubber(d.over, 10));
set(round(raw, q));
};
const up = (e: PointerEvent<HTMLSpanElement>) => {
const d = s.current;
if (!d || d.id !== e.pointerId) return;
s.current = null;
document.documentElement.style.cursor = "";
if (scrubbing) setScrubbing(false);
animate(nudge, 0, reduce ? { duration: 0 } : SPRING_RELEASE);
if (d.moved < 3) input.current?.focus();
};
const parse = (t: string) => {
const n = Number(t.replace(/[^0-9.\-]/g, ""));
return Number.isFinite(n) && t.trim() !== "" ? n : null;
};
const begin = () => {
setDraft(show(v).replace(/,/g, ""));
setEditing(true);
requestAnimationFrame(() => input.current?.select());
};
const finish = (keep: boolean) => {
if (keep) {
const n = parse(draft);
if (n !== null) set(n);
}
setEditing(false);
};
const key = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
e.preventDefault();
finish(true);
input.current?.blur();
} else if (e.key === "Escape") {
e.preventDefault();
finish(false);
input.current?.blur();
} else if (e.key === "ArrowUp" || e.key === "ArrowDown") {
e.preventDefault();
const q = step * (e.shiftKey ? 10 : e.altKey ? 0.1 : 1);
const base = editing ? parse(draft) ?? v : v;
const n = clamp(round(base + (e.key === "ArrowUp" ? q : -q), q), min, max);
set(n);
if (editing) {
setDraft(String(n));
requestAnimationFrame(() => input.current?.select());
}
}
};
const text = show(v);
return (
<div
className={cx(
"well relative flex h-9 items-center rounded-inner pr-2.5 transition-colors duration-150",
disabled && "opacity-45",
className,
)}
>
<span aria-hidden className={cx("raised pointer-events-none absolute inset-0 rounded-[inherit] transition-opacity duration-150 ease-snap", editing ? "opacity-100" : "opacity-0")} />
<span
id={id}
onPointerDown={down}
onPointerMove={move}
onPointerUp={up}
onPointerCancel={up}
className={cx(
"relative z-10 flex h-full shrink-0 touch-pan-y items-center rounded-l-inner pr-3 pl-2.5 text-[13px] whitespace-nowrap select-none",
"transition-colors duration-150 before:absolute before:-inset-y-1 before:inset-x-0 before:content-['']",
"after:absolute after:inset-[3px] after:-z-10 after:rounded-[6px] after:bg-press after:opacity-0 after:transition-opacity after:duration-150 after:content-['']",
disabled ? "cursor-not-allowed text-ink-3" : "cursor-ew-resize text-ink-2 hover:text-ink",
scrubbing && "text-ink after:opacity-100",
)}
>
{label}
</span>
<motion.div className="relative z-10 flex h-full min-w-0 flex-1 items-center" style={{ x: nudge }}>
<input
ref={input}
type="text"
inputMode="decimal"
role="spinbutton"
aria-labelledby={id}
aria-valuenow={v}
aria-valuemin={Number.isFinite(min) ? min : undefined}
aria-valuemax={Number.isFinite(max) ? max : undefined}
aria-valuetext={`${prefix}${text}${unit ? ` ${unit}` : ""}`}
disabled={disabled}
value={editing ? draft : `${prefix}${text}`}
onFocus={begin}
onBlur={() => editing && finish(true)}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={key}
className={cx(
"tnum h-full w-full min-w-0 bg-transparent text-right text-[14px] outline-none",
editing ? "text-ink caret-accent" : "cursor-text text-transparent caret-transparent selection:bg-transparent",
)}
spellCheck={false}
autoComplete="off"
/>
{!editing ? (
<span aria-hidden className="tnum pointer-events-none absolute inset-y-0 right-0 flex items-center text-[14px] text-ink">
<Roll text={`${prefix}${text}`} reduce={!!reduce} />
</span>
) : null}
</motion.div>
{unit ? <span className="relative z-10 pl-1.5 text-[13px] text-ink-3 select-none">{unit}</span> : null}
</div>
);
}
/** Each digit is a 0–9 column that slides to its value; other characters sit still. Keys count from the right so units stay put. Sized in em, so it takes the parent's font size. */
export function Roll({ text, reduce = false }: { text: string; reduce?: boolean }) {
const chars = [...text];
return (
<span className="flex h-[1.25em] overflow-hidden leading-[1.25em]">
<AnimatePresence initial={false} mode="popLayout">
{chars.map((c, i) => {
const k = chars.length - i;
const d = c >= "0" && c <= "9" ? Number(c) : -1;
return (
<motion.span
key={`${k}-${d < 0 ? c : "d"}`}
layout="position"
initial={{ opacity: 0, y: reduce ? 0 : 6 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: reduce ? 0 : -6 }}
transition={{ duration: 0.18, ease: EASE }}
className="relative block h-[1.25em]"
>
{d < 0 ? (
<span className="block">{c}</span>
) : (
<motion.span
className="flex flex-col"
initial={false}
animate={{ y: `${-d * 10}%` }}
transition={reduce ? { duration: 0 } : SPRING}
>
{"0123456789".split("").map((n) => (
<span key={n} className="block h-[1.25em]">
{n}
</span>
))}
</motion.span>
)}
</motion.span>
);
})}
</AnimatePresence>
</span>
);
}Usage
import { ScrubNumber } from "@/components/ui/scrub-number"
<ScrubNumber label="Timeout" defaultValue={90} min={5} max={600} step={5} unit="s" />Props
| Prop | Type | Default | What it does |
|---|---|---|---|
| value | number | Controlled value. | |
| defaultValue | number | 0 | Initial value when uncontrolled. |
| onValueChange | (value: number) => void | Called while scrubbing, on arrow keys and when typing is committed. | |
| label | ReactNode | The field's name and its drag handle. | |
| min / max | number | -∞ / ∞ | Past a limit the number leans like rubber and springs back. |
| step | number | 1 | One step per pixelsPerStep of drag, and per arrow key. |
| pixelsPerStep | number | 2 | How far to drag for one step. |
| prefix / unit | string | Shown before and after the number, e.g. $ and s. | |
| format | (value: number) => string | Formats the number. Defaults to grouped digits at the step's precision. | |
| disabled | boolean | Dims and ignores input. |
Keyboard
- ↑ ↓
- One step
- Shift + ↑ ↓
- Ten steps
- Alt + ↑ ↓
- A tenth of a step
- Enter
- Commit what you typed
- Escape
- Discard what you typed
Accessibility
- The field is a real text input with role=spinbutton, aria-valuenow and its limits.
- The label names the input, so scrubbing is optional: arrows and typing do the same.
- The rolling digits are decorative and hidden from screen readers.