Number Input
SaveA number field with steppers, press-and-hold repeat, scrubbing on the label, and Intl formatting for currency, percent, and units, whose digits roll to each new value.
- Category
- Forms
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Number Input preview
$288 per month
Shift steps by $500
Installation
npx @shakenui/cli add number-inputReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add number-input --dry-runUsage
number-input-example.tsx
"use client";
import { useState } from "react";
import { NumberInput } from "@/components/shaken/ui/number-input";
const seatPrice = 24;
export default function NumberInputExample() {
const [seats, setSeats] = useState<number | null>(12);
return (
<div className="grid w-full max-w-md gap-x-4 gap-y-5 sm:grid-cols-2">
<NumberInput
label="Seats"
value={seats}
onValueChange={setSeats}
min={1}
max={500}
description={seats ? `${new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 }).format(seats * seatPrice)} per month` : "At least one seat"}
/>
<NumberInput
label="Monthly spend limit"
defaultValue={1200}
min={0}
step={50}
largeStep={500}
format={{ style: "currency", currency: "USD", maximumFractionDigits: 0 }}
description="Shift steps by $500"
/>
<NumberInput
label="Canary traffic"
defaultValue={0.25}
min={0}
max={1}
step={0.05}
largeStep={0.25}
format={{ style: "percent", maximumFractionDigits: 0 }}
/>
<NumberInput
label="Request timeout"
defaultValue={30}
min={1}
max={300}
step={5}
format={{ style: "unit", unit: "second", unitDisplay: "short" }}
/>
</div>
);
}States
Every state, rendered from local fixture data.
Number Input states
Your plan allows 8 parallel agents
Retries must be at least 1
API
| Prop | Type | Default | Description |
|---|---|---|---|
| value / defaultValue | number | null | — | The value, controlled or starting. null is an empty field. |
| onValueChange | (value, details) => void | — | Called on typing, stepping, scrubbing, and the wheel. |
| min / max | number | — | Bounds. The matching button disables at each bound. |
| step | number | 1 | Step for the buttons and arrow keys. |
| largeStep | number | 10 | Step with Shift held, and for Page Up and Page Down. |
| format | Intl.NumberFormatOptions | — | Display format, for example { style: "currency", currency: "USD" }, { style: "percent" }, or { style: "unit", unit: "second" }. |
| locale | Intl.LocalesArgument | — | Locale for formatting and parsing. |
| scrub | boolean | true | Drag horizontally on the label to change the value. |
| scrubSensitivity | number | 4 | Pixels of pointer travel per step while scrubbing. |
| label / description / error | ReactNode | — | Label, helper text, and an error that marks the field invalid. |
| disabled / readOnly | boolean | false | Blocks changes; both disable the steppers. |
Accessibility
- Built on Base UI NumberField: the input has inputmode set for numbers and its label points at it; Decrease and Increase are labeled buttons.
- Arrow keys step, Shift+Arrow and Page Up/Page Down step by largeStep, Alt+Arrow by the small step, and Home/End jump to min and max when set.
- Holding a stepper repeats. Scrubbing on the label is a pointer enhancement; the keyboard reaches every value without it.
- The rolling digits are an aria-hidden overlay on the real input, so screen readers and copy and paste always read the input's own text.
- Digits roll only for pointer-driven changes; keyboard steps update instantly, and with reduced motion preferred nothing rolls.
- Errors set aria-invalid and are linked with aria-describedby.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/ui/number-input.tsxnumber-input- npm packages: @base-ui/react@^1.9.0, motion@^14.14.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/number-input/0.1.0.json.
ui/number-input.tsxShowHide
ui/number-input.tsx
"use client";
import { NumberField } from "@base-ui/react/number-field";
import { AnimatePresence, motion, useReducedMotion, type Variants } from "motion/react";
import { type KeyboardEvent, type ReactNode, useId, useMemo, useRef, useState } from "react";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
type RootProps = NumberField.Root.Props;
type ChangeDetails = NumberField.Root.ChangeEventDetails;
export interface NumberInputProps
extends Omit<RootProps, "className" | "render" | "children" | "value" | "defaultValue" | "onValueChange" | "style"> {
/** Visible label. Drag on it horizontally to scrub the value. Pass `aria-label` instead when the label is shown elsewhere. */
label?: ReactNode;
/** Helper text below the field. */
description?: ReactNode;
/** Error message. Marks the field invalid and replaces the description. */
error?: ReactNode;
/** The value. Pass with `onValueChange` to control it. `null` is an empty field. */
value?: number | null;
/** The starting value when uncontrolled. */
defaultValue?: number | null;
/** Called on every change: typing, stepping, scrubbing, or the wheel. */
onValueChange?: (value: number | null, details: ChangeDetails | null) => void;
/** Lets the user drag horizontally on the label to change the value. */
scrub?: boolean;
/** Pixels of pointer travel per step while scrubbing. */
scrubSensitivity?: number;
/** Placeholder for an empty field. */
placeholder?: string;
/** Names the field for screen readers when there is no visible label. */
"aria-label"?: string;
/** Classes for the wrapping element. */
className?: string;
/** Classes for the bordered group that holds the buttons and the input. */
fieldClassName?: string;
}
const ease = [0.23, 1, 0.32, 1] as const;
// The outgoing digit leaves in the direction of travel and the new one arrives from the other side,
// like a counter wheel: going up, digits move up.
const digitVariants: Variants = {
enter: (direction: number) => ({ y: direction >= 0 ? "70%" : "-70%", opacity: 0, filter: "blur(2px)" }),
center: { y: "0%", opacity: 1, filter: "blur(0px)" },
exit: (direction: number) => ({ y: direction >= 0 ? "-70%" : "70%", opacity: 0, filter: "blur(2px)" }),
};
function RollingDigit({ digit, direction }: { digit: string; direction: number }) {
return (
<span className="relative inline-block">
<AnimatePresence initial={false} mode="popLayout" custom={direction}>
<motion.span
key={digit}
custom={direction}
variants={digitVariants}
initial="enter"
animate="center"
exit="exit"
transition={{ duration: 0.24, ease }}
className="inline-block"
>
{digit}
</motion.span>
</AnimatePresence>
</span>
);
}
/**
* Draws the formatted value over the input, one slot per character. Slots are keyed from the
* right so the ones digit stays put when the number grows a column.
*/
function RollingValue({ text, direction, animate }: { text: string; direction: number; animate: boolean }) {
const chars = Array.from(text);
return (
<span
aria-hidden="true"
className="pointer-events-none absolute inset-0 flex items-center justify-center overflow-hidden whitespace-pre"
>
{chars.map((char, index) => {
const key = chars.length - index;
if (animate && /\d/.test(char)) return <RollingDigit key={key} digit={char} direction={direction} />;
return <span key={key}>{char}</span>;
})}
</span>
);
}
function MinusIcon() {
return (
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none">
<path d="M4 8h8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
);
}
function PlusIcon() {
return (
<svg aria-hidden="true" viewBox="0 0 16 16" fill="none">
<path d="M8 4v8M4 8h8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
</svg>
);
}
const stepButton = cx(
"group/step flex h-full w-9 shrink-0 cursor-default items-center justify-center text-zinc-500 select-none dark:text-zinc-400",
"transition-colors duration-150 ease-out motion-reduce:transition-none",
"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
"data-[disabled]:pointer-events-none data-[disabled]:opacity-35",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
"[&_svg]:size-4 [&_svg]:transition-transform [&_svg]:duration-100 [&_svg]:ease-out motion-safe:active:[&_svg]:scale-[0.85] motion-reduce:[&_svg]:transition-none",
);
/**
* A number field with steppers. Hold a button to repeat, hold Shift for the large step, drag on
* the label to scrub, and use the arrow keys, Page Up and Page Down, Home and End. Values are
* formatted with `Intl.NumberFormat` (currency, percent, units), and digits roll to their new
* value when a step changes them.
*/
export function NumberInput({
label,
description,
error,
value: valueProp,
defaultValue = null,
onValueChange,
scrub = true,
scrubSensitivity = 4,
placeholder,
min,
max,
step = 1,
largeStep = 10,
format,
locale,
disabled,
readOnly,
id,
className,
fieldClassName,
"aria-label": ariaLabel,
...props
}: NumberInputProps) {
const generatedId = useId();
const inputId = id ?? generatedId;
const messageId = `${inputId}-message`;
const invalid = error != null && error !== false;
const message = invalid ? error : description;
const reduceMotion = useReducedMotion();
const [innerValue, setInnerValue] = useState<number | null>(defaultValue);
const controlled = valueProp !== undefined;
const value = controlled ? valueProp : innerValue;
// While the user is typing, the real input text shows. After a step, scrub, wheel, or blur, the
// rolling overlay takes over and the input text goes transparent underneath it.
const [editing, setEditing] = useState(false);
const [roll, setRoll] = useState<{ direction: number; animate: boolean }>({ direction: 1, animate: false });
const formatter = useMemo(() => new Intl.NumberFormat(locale, format), [locale, format]);
const text = value == null ? "" : formatter.format(value);
const lastValue = useRef(value);
lastValue.current = value;
function commit(next: number | null, details: ChangeDetails | null) {
const reason = details?.reason;
const typed = reason === "input-change" || reason === "input-paste" || reason === "input-clear";
setEditing(typed);
if (!typed) {
const previous = lastValue.current;
// Keyboard steps change instantly; only pointer-driven changes roll.
const pointerDriven = reason === "increment-press" || reason === "decrement-press" || reason === "scrub" || reason === "wheel";
setRoll({
direction: previous == null || next == null ? 1 : Math.sign(next - previous) || 1,
animate: pointerDriven && !reduceMotion,
});
}
if (!controlled) setInnerValue(next);
onValueChange?.(next, details);
}
// Page Up and Page Down step by `largeStep`, the same as Shift with the arrow keys. Re-dispatching
// as Shift+Arrow lets the field handle clamping, snapping, and any half-typed text.
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {
if (event.key !== "PageUp" && event.key !== "PageDown") return;
event.preventDefault();
if (disabled || readOnly) return;
event.currentTarget.dispatchEvent(
new window.KeyboardEvent("keydown", {
key: event.key === "PageUp" ? "ArrowUp" : "ArrowDown",
shiftKey: true,
bubbles: true,
cancelable: true,
}),
);
}
const atMin = min != null && value != null && value <= min;
const atMax = max != null && value != null && value >= max;
const showOverlay = !editing && text !== "";
const labelNode = label ? (
<label
htmlFor={inputId}
className={cx(
"text-sm font-medium text-zinc-900 transition-colors duration-150 ease-out select-none motion-reduce:transition-none dark:text-zinc-100",
scrub && !disabled && !readOnly && "cursor-ew-resize",
)}
>
{label}
</label>
) : null;
return (
<NumberField.Root
id={inputId}
value={value}
onValueChange={(next, details) => commit(next, details)}
min={min}
max={max}
step={step}
largeStep={largeStep}
format={format}
locale={locale}
disabled={disabled}
readOnly={readOnly}
className={cx("group/number grid w-full gap-1.5", className)}
{...props}
>
{labelNode && scrub && !disabled && !readOnly ? (
<NumberField.ScrubArea direction="horizontal" pixelSensitivity={scrubSensitivity} className="flex w-fit">
{labelNode}
<NumberField.ScrubAreaCursor className="drop-shadow-[0_1px_1px_rgb(0_0_0/0.25)]">
<svg aria-hidden="true" viewBox="0 0 24 16" fill="none" className="h-4 w-6 text-zinc-950 dark:text-white">
<path d="M7 4L3 8l4 4M17 4l4 4-4 4M3 8h18" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</NumberField.ScrubAreaCursor>
</NumberField.ScrubArea>
) : (
labelNode
)}
<NumberField.Group
className={cx(
"flex h-9 w-full items-stretch overflow-hidden rounded-lg border bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:bg-black dark:shadow-none",
"transition-[border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none",
invalid
? "border-red-500/60 focus-within:border-red-500 focus-within:ring-3 focus-within:ring-red-500/20"
: cx(
"border-zinc-950/15 hover:border-zinc-950/25 dark:border-white/15 dark:hover:border-white/25",
"focus-within:border-sky-500 focus-within:ring-3 focus-within:ring-sky-500/20 dark:focus-within:border-sky-500",
"group-data-[scrubbing]/number:border-sky-500 group-data-[scrubbing]/number:ring-3 group-data-[scrubbing]/number:ring-sky-500/20",
),
"group-data-[disabled]/number:cursor-not-allowed group-data-[disabled]/number:opacity-60",
fieldClassName,
)}
>
<NumberField.Decrement
aria-label="Decrease"
disabled={disabled || readOnly || atMin}
className={cx(stepButton, "border-r border-zinc-950/[0.07] dark:border-white/[0.08]")}
>
<MinusIcon />
</NumberField.Decrement>
<div className="relative min-w-0 flex-1 text-sm font-medium tabular-nums text-zinc-950 dark:text-white">
<NumberField.Input
aria-label={label ? undefined : ariaLabel}
aria-invalid={invalid || undefined}
aria-describedby={message ? messageId : undefined}
placeholder={placeholder}
onKeyDown={handleKeyDown}
onBlur={() => setEditing(false)}
className={cx(
"h-full w-full min-w-0 bg-transparent px-2 text-center outline-hidden placeholder:font-normal placeholder:text-zinc-400 disabled:cursor-not-allowed dark:placeholder:text-zinc-500",
"caret-zinc-950 dark:caret-white",
showOverlay && "text-transparent",
)}
/>
{showOverlay ? <RollingValue text={text} direction={roll.direction} animate={roll.animate} /> : null}
</div>
<NumberField.Increment
aria-label="Increase"
disabled={disabled || readOnly || atMax}
className={cx(stepButton, "border-l border-zinc-950/[0.07] dark:border-white/[0.08]")}
>
<PlusIcon />
</NumberField.Increment>
</NumberField.Group>
{message ? (
<p id={messageId} className={invalid ? "text-sm text-red-600 dark:text-red-400" : "text-sm text-zinc-500 dark:text-zinc-400"}>
{message}
</p>
) : null}
</NumberField.Root>
);
}