# Quantity stepper

> A number field with increment and decrement buttons that follow native bounds and step values.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/quantity-stepper`
- File: `src/components/haze/ui/quantity-stepper.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/button, @haze/input, @haze/utils
- Docs page: https://hazeui.com/ui/quantity-stepper

## Use when
- People adjust a small integer such as seat count
- A form needs both direct entry and tap targets for one-step changes

## Avoid when
- Users make coarse selections across a continuous range. Use slider.

## Alternatives
- [input](https://hazeui.com/ui/input.md)
- [slider](https://hazeui.com/ui/slider.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique control ID. Use it to associate a label with the input. |
| name | `string` | id | no | Form field name. |
| value | `number` | 1 | no | Initial quantity. |
| min | `number` | 0 | no | Smallest valid quantity. |
| max | `number` |  | no | Largest valid quantity. |
| step | `number` | 1 | no | Positive increment used by the input and buttons. |
| decrementLabel | `string` | "Decrease quantity" | no | Accessible name for the decrement button. |
| incrementLabel | `string` | "Increase quantity" | no | Accessible name for the increment button. |
| ...attributes | `HTML input attributes` |  | no | Additional attributes for the native input. |
| class | `string` |  | no | Additional classes on the wrapper. |

## Accessibility
- Supply a visible label for the numeric input.
- At a bound, the matching button announces its disabled state and retains keyboard focus.
- With JavaScript disabled, the native number field provides editing and validation.
- Key Up or Down: Step the value with focus on the field.
- Key Enter or Space: Activate the focused step button.

## Agent prompts

### Install and use

Install the Haze UI component "Quantity stepper" with `npx shadcn@latest add @haze/quantity-stepper`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/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 QuantityStepper from "@/components/haze/ui/quantity-stepper.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: https://hazeui.com/ui/quantity-stepper.md

### Customize with real content

Adapt the Haze quantity-stepper ui for our product. Replace the demo values of these props with our real content: id, name, value, min, max, step, decrementLabel, incrementLabel, ...attributes, class. Keep the layout, the heading level rules and these accessibility details: Supply a visible label for the numeric input. At a bound, the matching button announces its disabled state and retains keyboard focus. With JavaScript disabled, the native number field provides editing and validation. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using quantity-stepper, check it fits: use it when people adjust a small integer such as seat count; a form needs both direct entry and tap targets for one-step changes. Avoid it when users make coarse selections across a continuous range. use slider.. Alternatives: @haze/input, @haze/slider.

## Example requests that should lead here
- Add a labelled quantity stepper for one to ten workspace seats.

## Source

```astro
---
import { Minus, Plus } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Input from "./input.astro";
import Button from "./button.astro";

interface Props {
  id: string;
  name?: string;
  value?: number;
  min?: number;
  max?: number;
  step?: number;
  decrementLabel?: string;
  incrementLabel?: string;
  class?: string;
  [key: string]: unknown;
}

const {
  id, name = id, value = 1, min = 0, max, step = 1,
  decrementLabel = "Decrease quantity", incrementLabel = "Increase quantity",
  class: className, ...rest
} = Astro.props;

const stepButton = "hidden [[data-haze-quantity-stepper][data-enhanced]_&]:inline-flex active:scale-90 active:duration-100";
const increment = Number.isFinite(step) && step > 0 ? step : 1;
---

<div data-haze-quantity-stepper class={cn("flex w-full min-w-0 items-center gap-1.5", className)}>
  <Button size="icon" variant="outline" data-step="down" aria-label={decrementLabel} aria-controls={id} class={stepButton}>
    <Minus aria-hidden="true" />
  </Button>
  <Input {...rest} id={id} name={name} type="number" value={value} min={min} max={max} step={increment}
    class="text-center tabular-nums [[data-haze-quantity-stepper][data-enhanced]_&]:appearance-none [[data-haze-quantity-stepper][data-enhanced]_&]:[&::-webkit-inner-spin-button]:appearance-none [[data-haze-quantity-stepper][data-enhanced]_&]:[&::-webkit-outer-spin-button]:appearance-none" />
  <Button size="icon" variant="outline" data-step="up" aria-label={incrementLabel} aria-controls={id} class={stepButton}>
    <Plus aria-hidden="true" />
  </Button>
</div>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const input = root.querySelector<HTMLInputElement>("input[type=number]");
    const down = root.querySelector<HTMLButtonElement>('button[data-step="down"]');
    const up = root.querySelector<HTMLButtonElement>('button[data-step="up"]');
    if (!input || !down || !up) return;

    const sync = () => {
      const value = input.valueAsNumber;
      const locked = input.matches(":disabled") || input.readOnly;
      down.disabled = locked;
      up.disabled = locked;
      down.setAttribute("aria-disabled", String(input.min !== "" && value <= Number(input.min)));
      up.setAttribute("aria-disabled", String(input.max !== "" && value >= Number(input.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 stepOnce = (button: HTMLButtonElement) => {
      if (input.readOnly || input.matches(":disabled") || button.getAttribute("aria-disabled") === "true") return false;
      const before = input.value;
      if (button === down) input.stepDown();
      else input.stepUp();
      if (input.value === before) return false;
      nudge(button === down ? -1 : 1);
      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; };
    for (const button of [down, up]) {
      button.addEventListener("pointerdown", (ev) => {
        if (ev.button !== 0 || !ev.isPrimary || !stepOnce(button)) return;
        let repeats = 0;
        const tick = () => {
          if (!stepOnce(button)) { 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) stepOnce(button); });
    }
    input.addEventListener("input", sync);
    input.addEventListener("change", sync);
    input.form?.addEventListener("reset", () => queueMicrotask(sync));
    sync();
    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-quantity-stepper]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-quantity-stepper-listener")) {
    document.documentElement.setAttribute("data-haze-quantity-stepper-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
