Number Field
Unified numeric input with joined -/+ steppers, unit label, boundary clamping, and horizontal label scrubbing.
pnpm dlx shadcn@latest add @haze/number-field---
import { ArrowLeftRight, Minus, Plus } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Props {
id: string;
name?: string;
label?: string;
value?: number;
min?: number;
max?: number;
step?: number;
unit?: string;
/** Allows dragging the label horizontally to scrub values continuously (hold Shift for 10x step). */
scrub?: boolean;
size?: "sm" | "md" | "lg";
required?: boolean;
disabled?: boolean;
class?: string;
[key: string]: unknown;
}
const {
id,
name = id,
label = "Concurrency limit",
value = 12,
min = 0,
max = 1000,
step = 1,
unit,
scrub = true,
size = "md",
required = false,
disabled = false,
class: className,
...rest
} = Astro.props;
const safeStep = Number.isFinite(step) && step > 0 ? step : 1;
const heights = {
sm: "h-8 text-xs/5",
md: "h-10 text-sm/5",
lg: "h-11 text-sm/5",
};
const btnSizes = {
sm: "w-8",
md: "w-10",
lg: "w-11",
};
---
<div data-haze-number-field data-scrub={scrub ? "" : undefined} class={cn("grid min-w-0 gap-2", className)}>
<label
for={id}
data-nf-label
class={cn(
"inline-flex w-fit items-center gap-1.5 rounded-sm text-[0.8125rem]/5 font-medium text-foreground select-none",
scrub && "[[data-haze-number-field][data-enhanced]_&]:touch-pan-y [[data-haze-number-field][data-enhanced]_&]:cursor-ew-resize",
)}
>
{scrub && <ArrowLeftRight class="hidden size-3.5 text-muted-foreground [[data-haze-number-field][data-enhanced]_&]:inline-block" aria-hidden="true" />}
<span>{label}</span>
</label>
<div
class={cn(
"flex w-full min-w-0 items-stretch overflow-hidden rounded-lg border border-frame-input bg-field transition-[border-color,box-shadow] duration-150 ease-snappy hover:border-frame-foreground has-[:is(input,textarea):focus-visible]:border-ring has-[:is(input,textarea):focus-visible]:ring-3 has-[:is(input,textarea):focus-visible]:ring-ring/24",
"has-[:disabled]:cursor-not-allowed has-[:disabled]:bg-muted has-[:disabled]:opacity-50 has-[:disabled]:hover:border-frame-input",
"has-[[aria-invalid=true]]:border-destructive has-[[aria-invalid=true]:focus-visible]:ring-destructive/24",
heights[size],
)}
>
<button
type="button"
data-nf-dec
disabled={disabled}
aria-label={`Decrease ${label.toLowerCase()}`}
aria-controls={id}
class={cn(
"hidden shrink-0 cursor-pointer items-center justify-center border-r border-border text-muted-foreground transition-[color,background-color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground active:scale-90 active:bg-muted active:duration-100 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring aria-disabled:cursor-not-allowed aria-disabled:opacity-40 [[data-haze-number-field][data-enhanced]_&]:inline-flex",
btnSizes[size],
)}
>
<Minus class="size-3.5" aria-hidden="true" />
</button>
<div class="flex min-w-0 flex-1 items-center justify-center gap-1.5 px-2.5">
<input
{...rest}
id={id}
name={name}
type="number"
value={value}
min={min}
max={max}
step={safeStep}
required={required}
disabled={disabled}
aria-describedby={`${id}-hint`}
data-nf-input
class="h-full min-w-0 flex-1 border-0 bg-transparent text-center font-medium text-foreground tabular-nums outline-hidden disabled:cursor-not-allowed [[data-haze-number-field][data-enhanced]_&]:[appearance:textfield] [[data-haze-number-field][data-enhanced]_&]:[&::-webkit-inner-spin-button]:appearance-none [[data-haze-number-field][data-enhanced]_&]:[&::-webkit-outer-spin-button]:appearance-none"
/>
{unit && <span class="shrink-0 text-xs text-muted-foreground select-none">{unit}</span>}
</div>
<button
type="button"
data-nf-inc
disabled={disabled}
aria-label={`Increase ${label.toLowerCase()}`}
aria-controls={id}
class={cn(
"hidden shrink-0 cursor-pointer items-center justify-center border-l border-border text-muted-foreground transition-[color,background-color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground active:scale-90 active:bg-muted active:duration-100 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring aria-disabled:cursor-not-allowed aria-disabled:opacity-40 [[data-haze-number-field][data-enhanced]_&]:inline-flex",
btnSizes[size],
)}
>
<Plus class="size-3.5" aria-hidden="true" />
</button>
</div>
<p id={`${id}-hint`} class="text-xs/5 text-muted-foreground">
Range {min}–{max}{unit ? ` ${unit}` : ""}.<span data-nf-scrub-hint hidden> Drag label to scrub; hold Shift for 10× steps.</span>
</p>
</div>
<script>
function enhanceNumberFields() {
document.querySelectorAll<HTMLElement>("[data-haze-number-field]:not([data-enhanced])").forEach((root) => {
const input = root.querySelector<HTMLInputElement>("[data-nf-input]");
const label = root.querySelector<HTMLLabelElement>("[data-nf-label]");
const dec = root.querySelector<HTMLButtonElement>("[data-nf-dec]");
const inc = root.querySelector<HTMLButtonElement>("[data-nf-inc]");
const scrubHint = root.querySelector<HTMLElement>("[data-nf-scrub-hint]");
if (!input || !label || !dec || !inc) return;
const min = input.min !== "" ? Number(input.min) : -Infinity;
const max = input.max !== "" ? Number(input.max) : Infinity;
const step = Number(input.step) > 0 ? Number(input.step) : 1;
const decimals = (String(step).split(".")[1] ?? "").length;
const allowScrub = root.hasAttribute("data-scrub");
const formatVal = (n: number) => String(Number(Math.min(max, Math.max(min, n)).toFixed(Math.min(decimals + 4, 8))));
const sync = () => {
const cur = input.valueAsNumber;
const locked = input.disabled || input.readOnly;
dec.disabled = locked;
inc.disabled = locked;
dec.setAttribute("aria-disabled", String(Number.isFinite(min) && Number.isFinite(cur) && cur <= min));
inc.setAttribute("aria-disabled", String(Number.isFinite(max) && Number.isFinite(cur) && cur >= max));
};
const reduced = matchMedia("(prefers-reduced-motion: reduce)");
// The value lives only in the native input, so a 150 ms vertical nudge keeps editing, caret and screen readers untouched.
const nudge = (direction: number) => {
if (reduced.matches) return;
const easing = getComputedStyle(root).getPropertyValue("--ease-snappy").trim() || "ease";
input.animate([{ translate: `0 ${direction * 2}px` }, { translate: "0 0" }], { duration: 150, easing });
};
const stepBy = (delta: number) => {
if (input.disabled || input.readOnly) return false;
const base = Number.isFinite(input.valueAsNumber) ? input.valueAsNumber : (Number.isFinite(min) ? min : 0);
const next = formatVal(base + delta * step);
if (next === input.value) return false;
input.value = next;
nudge(Math.sign(delta));
sync();
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
return true;
};
// Press and hold: 400 ms delay, then every 80 ms, 40 ms after 10 repeats. Mouse/touch/pen only;
// keyboard Enter/Space arrives as a click with detail 0 and uses the browser's own key repeat.
let holdTimer = 0;
const stopHold = () => { clearTimeout(holdTimer); holdTimer = 0; };
const bindHold = (button: HTMLButtonElement, sign: number) => {
button.addEventListener("pointerdown", (ev) => {
if (ev.button !== 0 || !ev.isPrimary) return;
const mult = ev.shiftKey ? 10 : 1;
if (!stepBy(sign * mult)) return;
let repeats = 0;
const tick = () => {
if (!stepBy(sign * mult)) { stopHold(); return; }
repeats += 1;
holdTimer = window.setTimeout(tick, repeats >= 10 ? 40 : 80);
};
stopHold();
holdTimer = window.setTimeout(tick, 400);
});
for (const type of ["pointerup", "pointerleave", "pointercancel", "blur"]) button.addEventListener(type, stopHold);
button.addEventListener("click", (ev) => { if (ev.detail === 0) stepBy(sign * (ev.shiftKey ? 10 : 1)); });
};
bindHold(dec, -1);
bindHold(inc, 1);
if (allowScrub) {
let drag: { pointerId: number; startX: number; baseVal: number } | null = null;
label.addEventListener("pointerdown", (ev) => {
if (input.disabled || input.readOnly || ev.button !== 0 || !ev.isPrimary) return;
drag = {
pointerId: ev.pointerId,
startX: ev.clientX,
baseVal: Number.isFinite(input.valueAsNumber) ? input.valueAsNumber : (Number.isFinite(min) ? min : 0),
};
label.setPointerCapture(ev.pointerId);
});
label.addEventListener("pointermove", (ev) => {
if (!drag || drag.pointerId !== ev.pointerId) return;
const mult = ev.shiftKey ? 10 : 1;
const steps = Math.trunc((ev.clientX - drag.startX) / 4) * mult;
const next = formatVal(drag.baseVal + steps * step);
if (next === input.value) return;
input.value = next;
sync();
input.dispatchEvent(new Event("input", { bubbles: true }));
});
const endDrag = () => {
if (!drag) return;
drag = null;
input.dispatchEvent(new Event("change", { bubbles: true }));
};
label.addEventListener("pointerup", endDrag);
label.addEventListener("pointercancel", endDrag);
label.addEventListener("lostpointercapture", endDrag);
if (scrubHint) scrubHint.hidden = false;
}
input.addEventListener("blur", () => {
if (!Number.isFinite(input.valueAsNumber)) return;
const clamped = formatVal(input.valueAsNumber);
if (clamped !== input.value) {
input.value = clamped;
sync();
}
});
input.addEventListener("input", sync);
input.addEventListener("change", sync);
input.form?.addEventListener("reset", () => queueMicrotask(sync));
sync();
root.setAttribute("data-enhanced", "");
});
}
enhanceNumberFields();
if (!document.documentElement.hasAttribute("data-haze-number-field-listener")) {
document.documentElement.setAttribute("data-haze-number-field-listener", "");
document.addEventListener("astro:page-load", enhanceNumberFields);
}
</script>When to use
- Numeric settings where both precise typing and quick +/- adjustment help
- Design parameters or limits that benefit from dragging the label to scrub values
- Compact joined stepper bars in sm, md, or lg heights beside other form fields
When not to use
- Simple cart item quantity without label scrubbing; use quantity-stepper
- Continuous visual comparison between two bounds; use slider or range-slider
Installation
Add the Haze registry to components.json once, then install Number Field with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/number-fieldnpx shadcn@latest add @haze/number-fieldyarn dlx shadcn@latest add @haze/number-fieldbunx --bun shadcn@latest add @haze/number-fieldFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique id linking label, hint text, and stepper aria-controls. |
| name | string | – | Form submission name; defaults to id. |
| label | string | "Concurrency limit" | Visible label and optional pointer-drag scrub handle. |
| value | number | 12 | Initial numeric value. |
| min | number | 0 | Minimum allowed value. |
| max | number | 1000 | Maximum allowed value. |
| step | number | 1 | Increment step; holding Shift multiplies steps by 10. |
| unit | string | – | Optional unit suffix shown inside the center numeric cell. |
| scrub | boolean | true | Enables horizontal pointer dragging on the label. |
| size | "sm" | "md" | "lg" | "md" | Control height aligned with Haze inputs and buttons. |
| required | boolean | false | Marks the native input as required. |
| disabled | boolean | false | Disables typing, scrubbing, and stepper buttons. |
| class | string | – | Extra classes on the outer field wrapper. |
Keyboard interactions
- UpDown
- Step value inside the focused numeric input
- ShiftClick (-) or ShiftDrag
- Step by 10x the configured increment
Accessibility
- Stepper buttons expose aria-controls and aria-disabled at min/max bounds so focus stays stable during rapid clicks.
- Native <input type="number"> accepts keyboard typing and Up/Down arrows when scripts are off.
- Every scrub adjustment also accepts keyboard Arrow keys and direct number entry.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Number Field" with `npx shadcn@latest add @haze/number-field`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import NumberField from "@/components/haze/ui/number-field.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/number-field.md
Customize with real content
Adapt the Haze number-field ui for our product. Replace the demo values of these props with our real content: id, name, label, value, min, max, step, unit, scrub, size, required, disabled, class. Keep the layout, the heading level rules and these accessibility details: Stepper buttons expose aria-controls and aria-disabled at min/max bounds so focus stays stable during rapid clicks. Native <input type="number"> accepts keyboard typing and Up/Down arrows when scripts are off. Every scrub adjustment also accepts keyboard Arrow keys and direct number entry. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using number-field, check it fits: use it when numeric settings where both precise typing and quick +/- adjustment help; design parameters or limits that benefit from dragging the label to scrub values; compact joined stepper bars in sm, md, or lg heights beside other form fields. Avoid it when simple cart item quantity without label scrubbing; use quantity-stepper; continuous visual comparison between two bounds; use slider or range-slider. Alternatives: @haze/quantity-stepper, @haze/scrub-input, @haze/slider.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.