{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "number-stepper",
  "type": "registry:ui",
  "title": "Number Stepper",
  "description": "A number with a button either side to take one away or add one, that can also be typed: a spin button.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/cn",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/number-stepper.tsx",
      "type": "registry:ui",
      "target": "components/ui/number-stepper.tsx",
      "content": "\"use client\";\n/**\n * @name number-stepper\n * @category ui\n * @description A number with a button either side to take one away or add one, that can also be typed: a spin button.\n * @when A small whole number that is usually changed by a step or two: people in a party, a quantity, nights. For a number where the rough position matters use slider; for a free number (a price, a year) use input with type=\"number\". Name it with a Label (pass the same `id`) or `aria-label`.\n * @example\n * <Label htmlFor=\"adults\">Adults</Label>\n * <NumberStepper id=\"adults\" defaultValue={2} min={1} max={12} />\n *\n * // Controlled, with its own parts and translated button names\n * <NumberStepper value={nights} onValueChange={setNights} min={1} aria-label=\"Nights\">\n *   <NumberStepperDecrement aria-label=\"One night fewer\" />\n *   <NumberStepperInput />\n *   <NumberStepperIncrement aria-label=\"One night more\" />\n * </NumberStepper>\n */\nimport { Minus, Plus } from \"lucide-react\";\nimport { createContext, use, useEffect, useId, useRef, useState, type ComponentProps, type KeyboardEvent, type PointerEvent, type ReactNode } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\ntype StepperContextValue = {\n  inputId: string;\n  value: number;\n  min: number;\n  max: number;\n  step: number;\n  largeStep: number;\n  disabled: boolean;\n  readOnly: boolean;\n  name: string | undefined;\n  format: (value: number) => string;\n  valueText: ((value: number) => string) | undefined;\n  labelProps: { \"aria-label\"?: string | undefined; \"aria-labelledby\"?: string | undefined; \"aria-describedby\"?: string | undefined; \"aria-invalid\"?: ComponentProps<\"input\">[\"aria-invalid\"] };\n  /** Sets the value, clamped to the range and snapped to the step. */\n  commit: (next: number) => void;\n};\n\nconst StepperContext = createContext<StepperContextValue | null>(null);\n\nfunction useStepper(part: string): StepperContextValue {\n  const context = use(StepperContext);\n  if (!context) throw new Error(`<${part}> must be used inside <NumberStepper>.`);\n  return context;\n}\n\n/** The number of decimal places a step has, so that 0.1 + 0.2 is shown as 0.3. */\nfunction decimals(step: number): number {\n  const text = String(step);\n  const point = text.indexOf(\".\");\n  return point === -1 ? 0 : text.length - point - 1;\n}\n\nexport type NumberStepperProps = Omit<ComponentProps<\"div\">, \"defaultValue\" | \"onChange\"> & {\n  /** The controlled value. */\n  value?: number;\n  /** The starting value when uncontrolled. Default: `min`, or 0. */\n  defaultValue?: number;\n  onValueChange?: (value: number) => void;\n  min?: number;\n  max?: number;\n  /** What one press or one arrow key adds or takes away. Default 1. */\n  step?: number;\n  /** What Page Up and Page Down add or take away. Default ten steps. */\n  largeStep?: number;\n  disabled?: boolean;\n  readOnly?: boolean;\n  /** The field's name in a form: the value is submitted with it. */\n  name?: string;\n  /** How the number is shown in the field. Default: the plain number. */\n  format?: (value: number) => string;\n  /** What a screen reader says for a value when the number alone is not enough (\"3 adults\"). */\n  valueText?: (value: number) => string;\n  /** The parts, when the default three (decrement, input, increment) are not what is wanted. */\n  children?: ReactNode;\n};\n\n/**\n * The spin button pattern: Up and Down arrows change the value by a step, Page Up and Page Down by a large\n * step, Home and End go to the limits (when there are any). The buttons are for pointers and touch, and are\n * kept out of the Tab order because the arrow keys already do their work. `id`, `aria-label`,\n * `aria-labelledby`, `aria-describedby` and `aria-invalid` go to the field itself.\n */\nexport function NumberStepper({\n  className,\n  id,\n  value,\n  defaultValue,\n  onValueChange,\n  min = Number.NEGATIVE_INFINITY,\n  max = Number.POSITIVE_INFINITY,\n  step = 1,\n  largeStep,\n  disabled = false,\n  readOnly = false,\n  name,\n  format = String,\n  valueText,\n  children,\n  \"aria-label\": ariaLabel,\n  \"aria-labelledby\": ariaLabelledBy,\n  \"aria-describedby\": ariaDescribedBy,\n  \"aria-invalid\": ariaInvalid,\n  ...props\n}: NumberStepperProps) {\n  const ownId = useId();\n  const [current, setCurrent] = useControllableState({ value, defaultValue: defaultValue ?? (Number.isFinite(min) ? min : 0), onChange: onValueChange });\n  const places = decimals(step);\n  const commit = (next: number): void => {\n    if (Number.isNaN(next)) return;\n    setCurrent(Number(Math.min(max, Math.max(min, next)).toFixed(places)));\n  };\n\n  return (\n    <StepperContext\n      value={{\n        inputId: id ?? ownId,\n        value: current,\n        min,\n        max,\n        step,\n        largeStep: largeStep ?? step * 10,\n        disabled,\n        readOnly,\n        name,\n        format,\n        valueText,\n        labelProps: { \"aria-label\": ariaLabel, \"aria-labelledby\": ariaLabelledBy, \"aria-describedby\": ariaDescribedBy, \"aria-invalid\": ariaInvalid },\n        commit,\n      }}\n    >\n      <div\n        data-slot=\"number-stepper\"\n        data-disabled={disabled ? \"\" : undefined}\n        className={cn(\n          \"inline-flex h-control w-fit max-w-full items-stretch rounded-control border border-input bg-background text-sm text-foreground has-[input:focus-visible]:outline-2 has-[input:focus-visible]:outline-offset-2 has-[input:focus-visible]:outline-ring has-[input[aria-invalid=true]]:border-destructive data-[disabled]:opacity-50\",\n          className,\n        )}\n        {...props}\n      >\n        {children ?? (\n          <>\n            <NumberStepperDecrement />\n            <NumberStepperInput />\n            <NumberStepperIncrement />\n          </>\n        )}\n      </div>\n    </StepperContext>\n  );\n}\n\nexport type NumberStepperInputProps = Omit<ComponentProps<\"input\">, \"value\" | \"defaultValue\" | \"type\" | \"min\" | \"max\" | \"step\">;\n\n/** The field. It shows the formatted value, takes typing, and commits what was typed on Enter or on leaving. */\nexport function NumberStepperInput({ className, onKeyDown, onBlur, ...props }: NumberStepperInputProps) {\n  const context = useStepper(\"NumberStepperInput\");\n  const { value, min, max, step, largeStep, commit } = context;\n  /** What is being typed, until it is committed. null: the field shows the value. */\n  const [draft, setDraft] = useState<string | null>(null);\n\n  const commitDraft = (): void => {\n    if (draft === null) return;\n    const typed = Number(draft.trim().replace(\",\", \".\"));\n    if (draft.trim() !== \"\" && !Number.isNaN(typed)) commit(typed);\n    setDraft(null);\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>): void => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented || context.readOnly) return;\n    const base = draft === null ? value : Number(draft.replace(\",\", \".\")) || value;\n    const moves: Record<string, number | undefined> = {\n      ArrowUp: base + step,\n      ArrowDown: base - step,\n      PageUp: base + largeStep,\n      PageDown: base - largeStep,\n      Home: Number.isFinite(min) ? min : undefined,\n      End: Number.isFinite(max) ? max : undefined,\n    };\n    const next = moves[event.key];\n    if (next !== undefined) {\n      event.preventDefault();\n      setDraft(null);\n      commit(next);\n    } else if (event.key === \"Enter\") {\n      commitDraft();\n    }\n  };\n\n  return (\n    <>\n      <input\n        data-slot=\"number-stepper-input\"\n        id={context.inputId}\n        role=\"spinbutton\"\n        type=\"text\"\n        inputMode={decimals(step) > 0 ? \"decimal\" : \"numeric\"}\n        autoComplete=\"off\"\n        aria-valuenow={value}\n        aria-valuemin={Number.isFinite(min) ? min : undefined}\n        aria-valuemax={Number.isFinite(max) ? max : undefined}\n        aria-valuetext={context.valueText?.(value)}\n        disabled={context.disabled}\n        readOnly={context.readOnly}\n        value={draft ?? context.format(value)}\n        onChange={(event) => setDraft(event.target.value)}\n        onKeyDown={handleKeyDown}\n        onBlur={(event) => {\n          commitDraft();\n          onBlur?.(event);\n        }}\n        className={cn(\"w-12 min-w-0 flex-1 bg-transparent px-1 text-center tabular-nums outline-none disabled:pointer-events-none\", className)}\n        {...context.labelProps}\n        {...props}\n      />\n      {context.name ? <input type=\"hidden\" name={context.name} value={value} disabled={context.disabled} /> : null}\n    </>\n  );\n}\n\n/** How long a button is held before it starts repeating, and how fast it repeats, in milliseconds. */\nconst HOLD_DELAY = 400;\nconst HOLD_EVERY = 80;\n\ntype StepButtonProps = ComponentProps<\"button\"> & { direction: -1 | 1 };\n\nfunction StepButton({ direction, className, children, onPointerDown, onClick, ...props }: StepButtonProps) {\n  const context = useStepper(direction === 1 ? \"NumberStepperIncrement\" : \"NumberStepperDecrement\");\n  const { value, step, min, max, commit } = context;\n  const atLimit = direction === 1 ? value >= max : value <= min;\n  const blocked = context.disabled || context.readOnly || atLimit;\n\n  // While the button is held the value keeps changing, so the repeat reads the latest one.\n  const latest = useRef({ value, commit });\n  useEffect(() => {\n    latest.current = { value, commit };\n  });\n  const timers = useRef<{ delay?: number; repeat?: number }>({});\n  const stop = (): void => {\n    window.clearTimeout(timers.current.delay);\n    window.clearInterval(timers.current.repeat);\n    timers.current = {};\n  };\n  useEffect(() => stop, []);\n  useEffect(() => {\n    if (blocked) stop();\n  }, [blocked]);\n\n  const stepOnce = (): void => latest.current.commit(latest.current.value + direction * step);\n\n  const handlePointerDown = (event: PointerEvent<HTMLButtonElement>): void => {\n    onPointerDown?.(event);\n    if (event.defaultPrevented || event.button !== 0 || blocked) return;\n    stepOnce();\n    stop();\n    timers.current.delay = window.setTimeout(() => {\n      timers.current.repeat = window.setInterval(stepOnce, HOLD_EVERY);\n    }, HOLD_DELAY);\n  };\n\n  return (\n    <button\n      type=\"button\"\n      tabIndex={-1}\n      aria-controls={context.inputId}\n      disabled={blocked}\n      onPointerDown={handlePointerDown}\n      onPointerUp={stop}\n      onPointerLeave={stop}\n      onPointerCancel={stop}\n      onClick={(event) => {\n        onClick?.(event);\n        // A pointer press has already stepped on the way down. This is the click of a keyboard or a screen reader.\n        if (!event.defaultPrevented && event.detail === 0) stepOnce();\n      }}\n      className={cn(\n        \"inline-flex aspect-square h-full shrink-0 touch-manipulation items-center justify-center text-muted-foreground transition-[background-color,color,opacity] duration-instant ease-out select-none first:rounded-s-control last:rounded-e-control hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-40 motion-reduce:transition-none [&_svg]:size-4\",\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </button>\n  );\n}\n\nexport type NumberStepperButtonProps = Omit<ComponentProps<\"button\">, \"type\">;\n\n/** Takes one step away. Hold it to keep going. Its name (\"Decrease\") is an `aria-label`: translate it with the interface. */\nexport function NumberStepperDecrement({ children, \"aria-label\": ariaLabel = \"Decrease\", ...props }: NumberStepperButtonProps) {\n  return (\n    <StepButton data-slot=\"number-stepper-decrement\" direction={-1} aria-label={ariaLabel} {...props}>\n      {children ?? <Minus aria-hidden=\"true\" strokeWidth={1.5} />}\n    </StepButton>\n  );\n}\n\n/** Adds one step. Hold it to keep going. Its name (\"Increase\") is an `aria-label`: translate it with the interface. */\nexport function NumberStepperIncrement({ children, \"aria-label\": ariaLabel = \"Increase\", ...props }: NumberStepperButtonProps) {\n  return (\n    <StepButton data-slot=\"number-stepper-increment\" direction={1} aria-label={ariaLabel} {...props}>\n      {children ?? <Plus aria-hidden=\"true\" strokeWidth={1.5} />}\n    </StepButton>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "A small whole number that is usually changed by a step or two: people in a party, a quantity, nights. For a number where the rough position matters use slider; for a free number (a price, a year) use input with type=\"number\". Name it with a Label (pass the same `id`) or `aria-label`.",
    "example": "<Label htmlFor=\"adults\">Adults</Label>\n<NumberStepper id=\"adults\" defaultValue={2} min={1} max={12} />\n\n// Controlled, with its own parts and translated button names\n<NumberStepper value={nights} onValueChange={setNights} min={1} aria-label=\"Nights\">\n  <NumberStepperDecrement aria-label=\"One night fewer\" />\n  <NumberStepperInput />\n  <NumberStepperIncrement aria-label=\"One night more\" />\n</NumberStepper>",
    "client": true
  }
}
