Skip to content
Molecules

Number input

A stepper that repeats while held.

Installation

  1. Run the CLI

    Run pnpm dlx asta-ui@latest init once, then this. The file lands in components/astabyte/ and the colour tokens go into your CSS.

    $ pnpm dlx asta-ui@latest add number-input

    Or with the shadcn CLI: pnpm dlx shadcn@latest add https://ui.astabyte.com/r/number-input.json

  2. Or install the package

    Don’t want the file? Import from asta-ui/number-input and update with pnpm update asta-ui. Add the stylesheet once. More.

    $ pnpm add asta-ui
    import { NumberInput } from "asta-ui/number-input";
  3. Or copy it by hand

    Copy this file. Keep the paths, or fix the @/ imports. Then add the tokens from globals.css.

    "use client";
    
    import { useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
    
    const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
    
    export interface NumberInputProps {
      value?: number;
      defaultValue?: number;
      onChange?: (value: number) => void;
      min?: number;
      max?: number;
      step?: number;
      label?: string;
      /** Submits the value with a form through a hidden input. */
      name?: string;
      /** Text after the number, e.g. "seats" or "kg". */
      suffix?: ReactNode;
      size?: "sm" | "md";
      className?: string;
    }
    
    /** One digit as a vertical strip of 0–9 that rolls to its new position. */
    function Digit({ d }: { d: number }) {
      return (
        <span className="relative inline-block h-[1.25em] w-[0.62em] overflow-hidden">
          <span
            className="absolute inset-x-0 top-0 flex flex-col transition-transform duration-500 ease-[cubic-bezier(.16,1,.3,1)] motion-reduce:transition-none"
            style={{ transform: `translateY(${-d * 1.25}em)` }}
          >
            {Array.from({ length: 10 }, (_, i) => (
              <span key={i} className="flex h-[1.25em] items-center justify-center">
                {i}
              </span>
            ))}
          </span>
        </span>
      );
    }
    
    /**
     * A stepper. Hold − or + and it repeats, faster the longer you hold. Arrow keys step, Page Up/Down step by
     * ten, Home/End jump to min/max, and typing digits enters a value.
     */
    export function NumberInput({ value, defaultValue = 0, onChange, min = 0, max = 999, step = 1, label, name, suffix, size = "md", className }: NumberInputProps) {
      const [inner, setInner] = useState(defaultValue);
      const current = value ?? inner;
      const latest = useRef(current);
      const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
      const typed = useRef({ text: "", at: 0 });
      const [bump, setBump] = useState<"min" | "max" | null>(null);
    
      useEffect(() => {
        latest.current = current;
      }, [current]);
    
      const set = (v: number) => {
        const next = Math.min(max, Math.max(min, v));
        if (next === latest.current) {
          // Already at a limit: nudge to say so.
          setBump(v < min ? "min" : v > max ? "max" : null);
          setTimeout(() => setBump(null), 260);
          return false;
        }
        latest.current = next;
        if (value === undefined) setInner(next);
        onChange?.(next);
        return true;
      };
    
      const stop = () => {
        if (timer.current) clearTimeout(timer.current);
        timer.current = null;
      };
    
      useEffect(() => () => {
        if (timer.current) clearTimeout(timer.current);
      }, []);
    
      const hold = (dir: 1 | -1) => {
        stop();
        set(latest.current + dir * step);
        let delay = 380;
        const tick = () => {
          if (!set(latest.current + dir * step)) return stop();
          delay = Math.max(40, delay * 0.82);
          timer.current = setTimeout(tick, delay);
        };
        timer.current = setTimeout(tick, delay);
      };
    
      const onKey = (e: KeyboardEvent) => {
        if (e.key === "ArrowUp" || e.key === "ArrowRight") set(current + step);
        else if (e.key === "ArrowDown" || e.key === "ArrowLeft") set(current - step);
        else if (e.key === "PageUp") set(current + step * 10);
        else if (e.key === "PageDown") set(current - step * 10);
        else if (e.key === "Home") set(min);
        else if (e.key === "End") set(max);
        else if (/^[0-9]$/.test(e.key)) {
          const now = e.timeStamp;
          const text = (now - typed.current.at > 900 ? "" : typed.current.text) + e.key;
          typed.current = { text, at: now };
          set(Number(text));
        } else return;
        e.preventDefault();
      };
    
      const digits = String(Math.abs(Math.round(current))).split("").map(Number);
      const big = size === "md";
    
      const btn = (dir: 1 | -1) => {
        const off = dir === 1 ? current >= max : current <= min;
        return (
          <button
            type="button"
            tabIndex={-1}
            aria-label={dir === 1 ? "Increase" : "Decrease"}
            disabled={off}
            onPointerDown={(e) => {
              if (e.button !== 0) return;
              e.currentTarget.setPointerCapture(e.pointerId);
              hold(dir);
            }}
            onPointerUp={stop}
            onPointerCancel={stop}
            onLostPointerCapture={stop}
            onContextMenu={(e) => e.preventDefault()}
            className={cx(
              "flex shrink-0 select-none items-center justify-center rounded-md text-ink-2 outline-none transition-[background-color,transform,opacity] duration-150 [touch-action:manipulation] hover:bg-paper-2 hover:text-ink active:scale-90 disabled:opacity-30 disabled:hover:bg-transparent",
              big ? "h-8 w-8" : "h-6 w-6",
            )}
          >
            <svg viewBox="0 0 24 24" className="h-3.5 w-3.5" fill="none" stroke="currentColor" strokeWidth="2.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
              {dir === 1 ? <path d="M12 5v14M5 12h14" /> : <path d="M5 12h14" />}
            </svg>
          </button>
        );
      };
    
      return (
        <div
          className={cx(
            "inline-flex items-center gap-1 bg-paper shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_14%,transparent)]",
            big ? "h-12 rounded-[10px] px-2" : "h-8 rounded-full px-1",
            className,
          )}
        >
          {btn(-1)}
          <div
            role="spinbutton"
            tabIndex={0}
            aria-label={label}
            aria-valuenow={current}
            aria-valuemin={min}
            aria-valuemax={max}
            onKeyDown={onKey}
            className={cx(
              "flex min-w-[3.5em] items-center justify-center gap-1.5 rounded-lg px-1 font-medium tabular-nums tracking-[-0.02em] text-ink outline-none transition-transform duration-200 focus-visible:ring-2 focus-visible:ring-brand/50",
              big ? "text-[20px]" : "text-[14px]",
              bump === "max" && "-translate-y-0.5",
              bump === "min" && "translate-y-0.5",
            )}
          >
            <span className="inline-flex">
              {current < 0 && "−"}
              {digits.map((d, i) => (
                <Digit key={digits.length - i} d={d} />
              ))}
            </span>
            {suffix && <span className={cx("font-normal text-mute", big ? "text-[13px]" : "text-[12px]")}>{suffix}</span>}
          </div>
          {btn(1)}
          {name && <input type="hidden" name={name} value={current} />}
        </div>
      );
    }
    
    export default NumberInput;
    
  4. Or ask your AI agent

    Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.

    Add the Astabyte UI Number input component to my project.
    
    A stepper that repeats while held.
    It includes: hold to repeat, min/max, keys.
    
    Install it:
    ```sh
    pnpm dlx asta-ui@latest add number-input --radix
    ```
    Or with the shadcn CLI:
    ```sh
    pnpm dlx shadcn@latest add https://ui.astabyte.com/r/number-input.json
    ```
    If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4).
    
    Import it like this:
    ```tsx
    import { NumberInput } from "@/components/astabyte/number-input";
    ```
    
    Usage example and props: https://ui.astabyte.com/number-input
    Full catalogue for context: https://ui.astabyte.com/llms.txt
    
    Rules:
    - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS.
    - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback.
    - Keep keyboard, focus and ARIA behaviour.
    - Use fake data and fake brand names in examples.
    
    Use it to: [describe where it goes and what it should do]
  5. Or use plain HTML + CSS

    Not on React? Use it from Django, Rails, Laravel, Go html/template, htmx or a static page. Load asta.css and asta.js once (the head.html tab), then paste the markup. The ui.astabyte.com/cdn link is temporary: pin a version from jsDelivr for production. More in HTML + CSS.

    <!-- Needs asta.js for the steppers and rolling digits. -->
    <form style="display:flex;flex-direction:column;align-items:flex-start;gap:16px"><div style="display:flex;flex-wrap:wrap;align-items:flex-start;gap:24px"><div data-asta-number data-min="1" data-max="120" data-step="1" class="asta-number-input"><button type="button" tabindex="-1" aria-label="Decrease" data-asta-number-step="-1" class="asta-number-input-step"><svg viewBox="0 0 16 16"  fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M3.5 8h9"></path></svg></button><div role="spinbutton" tabindex="0" id="seats" aria-label="Seats" aria-valuenow="9" aria-valuemin="1" aria-valuemax="120" data-asta-number-view class="asta-number-input-view"><span class="asta-number-input-digits" data-asta-number-digits><span class="asta-number-input-digit" data-asta-digit><span class="asta-number-input-reel" style="transform:translateY(-11.25em);"><span >0</span><span >1</span><span >2</span><span >3</span><span >4</span><span >5</span><span >6</span><span >7</span><span >8</span><span >9</span></span></span></span> </div><button type="button" tabindex="-1" aria-label="Increase" data-asta-number-step="1" class="asta-number-input-step"><svg viewBox="0 0 16 16"  fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M8 3.5v9M3.5 8h9"></path></svg></button> <input type="hidden" name="seats" value="9" data-asta-number-input></div><div data-asta-number data-min="1" data-max="14" data-step="1" class="asta-number-input asta-number-input-sm"><button type="button" tabindex="-1" aria-label="Decrease" data-asta-number-step="-1" class="asta-number-input-step"><svg viewBox="0 0 16 16"  fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M3.5 8h9"></path></svg></button><div role="spinbutton" tabindex="0" id="nights" aria-label="Nights" aria-valuenow="2" aria-valuemin="1" aria-valuemax="14" data-asta-number-view class="asta-number-input-view"><span class="asta-number-input-digits" data-asta-number-digits><span class="asta-number-input-digit" data-asta-digit><span class="asta-number-input-reel" style="transform:translateY(-2.50em);"><span >0</span><span >1</span><span >2</span><span >3</span><span >4</span><span >5</span><span >6</span><span >7</span><span >8</span><span >9</span></span></span></span> <span class="asta-number-input-suffix">nights</span></div><button type="button" tabindex="-1" aria-label="Increase" data-asta-number-step="1" class="asta-number-input-step"><svg viewBox="0 0 16 16"  fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" aria-hidden="true"><path d="M8 3.5v9M3.5 8h9"></path></svg></button> <input type="hidden" name="nights" value="2" data-asta-number-input></div></div></form>

Usage

The demo above, as code.

"use client";

import { useState } from "react";
import { NumberInput } from "@/components/astabyte/number-input";

export default function NumberInputDemo() {
  const [seats, setSeats] = useState(8);

  return (
    <div className="flex min-h-[420px] w-full items-center justify-center p-6 sm:p-10">
      <div className="flex w-full max-w-sm flex-col gap-8">
        <div className="flex items-center justify-between gap-4 rounded-xl bg-paper-2 p-4 pl-5">
          <div>
            <p className="text-[14px] font-medium tracking-[-0.01em] text-ink">Seats</p>
            <p className="mt-0.5 text-[13px] tabular-nums text-mute">${seats * 12}/month</p>
          </div>
          <NumberInput label="Seats" value={seats} onChange={setSeats} min={1} max={250} />
        </div>
        <div className="flex items-center justify-between gap-4 px-1">
          <p className="text-[14px] text-ink-2">Quantity</p>
          <NumberInput label="Quantity" size="sm" defaultValue={1} min={1} max={10} />
        </div>
        <div className="flex items-center justify-between gap-4 px-1">
          <p className="text-[14px] text-ink-2">Weight</p>
          <NumberInput label="Weight" size="sm" defaultValue={20} step={5} max={300} suffix="kg" />
        </div>
        <p className="text-center text-[12.5px] text-mute">Hold − or + to repeat. Arrows, Page Up/Down and digits work too.</p>
      </div>
    </div>
  );
}