# Stepper

> A capsule with minus and plus buttons around a number that rolls when it changes, for quantities and counts.

Docs: https://plumbago.ochotzas.com/components/stepper

## Installation

```sh
npx plumbago add stepper
```

This copies `components/ui/stepper.tsx` into your project, along with `cn`, `count-change`, and installs `@base-ui/react`.

## Usage

```tsx
import { Stepper } from "@/components/ui/stepper"

<Stepper label="Guests" defaultValue={2} min={1} max={12} />
```

## Examples

### Preview

```tsx
import { Stepper } from "@/components/ui/stepper"

export default function StepperDemo() {
  return <Stepper label="Guests" defaultValue={2} min={1} max={12} />
}
```

### Inside an island

```tsx
import { Island, ListRow, ListRowText, ListRowTitle } from "@/components/ui/island"
import { Stepper } from "@/components/ui/stepper"

export default function StepperInsideAnIsland() {
  return (
    <Island variant="list" className="w-full max-w-md">
      <ListRow>
        <ListRowText>
          <ListRowTitle>Portions</ListRowTitle>
        </ListRowText>
        <Stepper label="Portions" defaultValue={4} min={1} max={20} />
      </ListRow>
      <ListRow>
        <ListRowText>
          <ListRowTitle>Prep time</ListRowTitle>
        </ListRowText>
        <Stepper label="Prep time" defaultValue={25} min={5} max={120} step={5} format={{ style: "unit", unit: "minute" }} />
      </ListRow>
      <ListRow>
        <ListRowText>
          <ListRowTitle>Chillies</ListRowTitle>
        </ListRowText>
        <Stepper label="Chillies" defaultValue={2} min={0} max={5} />
      </ListRow>
    </Island>
  )
}
```

### With format

```tsx
import { Stepper } from "@/components/ui/stepper"

export default function StepperWithFormat() {
  return (
    <Stepper
      label="Deposit"
      defaultValue={50}
      min={0}
      max={500}
      step={10}
      locale="en-IE"
      format={{ style: "currency", currency: "EUR", maximumFractionDigits: 0 }}
    />
  )
}
```

### At a bound

```tsx
import { Stepper } from "@/components/ui/stepper"

export default function StepperAtABound() {
  return <Stepper label="Guests" defaultValue={1} min={1} max={12} />
}
```

### Disabled

```tsx
import { Stepper } from "@/components/ui/stepper"

export default function StepperDisabled() {
  return <Stepper label="Guests" defaultValue={6} min={1} max={12} disabled />
}
```

## Built on Base UI

Stepper wraps these Base UI parts and keeps their props:

- [Number field](https://base-ui.com/react/components/number-field)

## Source

```tsx
import { NumberField } from "@base-ui/react/number-field"
import { cn } from "@/lib/cn"
import { CountSlot } from "@/lib/count-change"
import { type ComponentProps, type KeyboardEvent, useRef, useState } from "react"

export type StepperProps = Omit<ComponentProps<typeof NumberField.Root>, "className" | "children"> & {
  label: string
  className?: string
}

const buttonStyle = cn(
  "relative inline-flex h-8 w-9 shrink-0 cursor-pointer items-center justify-center rounded-full text-ink select-none [-webkit-tap-highlight-color:transparent]",
  "transition-control after:absolute after:-inset-x-1 after:-inset-y-1.5 after:content-['']",
  "hover:not-data-disabled:bg-press active:not-data-disabled:scale-press active:not-data-disabled:duration-[90ms]",
  "data-disabled:cursor-default data-disabled:text-ink-3 [&_svg]:size-[18px] [&_svg]:shrink-0",
)

const steppingKeys = new Set(["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End"])

export function Stepper({ label, value, defaultValue, onValueChange, format, locale, className, ...props }: StepperProps) {
  const [uncontrolledValue, setUncontrolledValue] = useState<number | null>(defaultValue ?? null)
  const current = value !== undefined ? value : uncontrolledValue
  const shown = current === null ? "" : new Intl.NumberFormat(locale, format).format(current)
  const [editing, setEditing] = useState(false)
  const [ringVisible, setRingVisible] = useState(false)
  const focusFromButtonRef = useRef(false)

  function handleInputKeyDown(event: KeyboardEvent<HTMLInputElement>) {
    const typesText = event.key.length === 1 || event.key === "Backspace" || event.key === "Delete"
    if (typesText && !event.metaKey && !event.ctrlKey) setEditing(true)
    if (event.key === "Enter" || steppingKeys.has(event.key)) setEditing(false)
    setRingVisible(true)
  }

  return (
    <NumberField.Root
      data-slot="stepper"
      value={value}
      defaultValue={defaultValue}
      format={format}
      locale={locale}
      onValueChange={(next, details) => {
        setUncontrolledValue(next)
        onValueChange?.(next, details)
      }}
      className={cn("inline-flex shrink-0", className)}
      {...props}
    >
      <NumberField.Group
        data-slot="stepper-group"
        data-ring={ringVisible ? "" : undefined}
        onPointerDownCapture={(event) => {
          const pressesButton = event.target instanceof Element && event.target.closest("button") !== null
          focusFromButtonRef.current = pressesButton
          if (pressesButton) setEditing(false)
        }}
        className="inline-flex h-9 items-center rounded-full bg-fill-secondary px-0.5 data-ring:ring-2 data-ring:ring-accent"
      >
        <NumberField.Decrement data-slot="stepper-decrement" aria-label={`Decrease ${label}`} className={buttonStyle}>
          <svg viewBox="0 0 20 20" aria-hidden="true" className="fill-none stroke-current" strokeWidth="1.75" strokeLinecap="round">
            <path d="M5 10h10" />
          </svg>
        </NumberField.Decrement>
        <span data-slot="stepper-value" data-editing={editing ? "" : undefined} className="group/value relative inline-grid min-w-8 place-items-center">
          <NumberField.Input
            aria-label={label}
            onFocus={() => {
              setRingVisible(!focusFromButtonRef.current)
              focusFromButtonRef.current = false
            }}
            onBlur={() => {
              setEditing(false)
              setRingVisible(false)
            }}
            onPointerDown={() => {
              setEditing(true)
              setRingVisible(true)
            }}
            onKeyDown={handleInputKeyDown}
            className="w-full min-w-0 bg-transparent p-0 text-center text-body font-medium text-transparent caret-transparent tabular-nums outline-none group-data-editing/value:text-ink group-data-editing/value:caret-ink disabled:cursor-default disabled:opacity-40"
            style={{ width: `${Math.max(shown.length, 2)}ch` }}
          />
          <span
            aria-hidden="true"
            className="pointer-events-none absolute inset-0 grid place-items-center text-body font-medium tabular-nums group-data-editing/value:invisible group-has-disabled/value:opacity-40"
          >
            {current === null ? <span className="text-ink-3">–</span> : <CountSlot text={shown} value={current} />}
          </span>
        </span>
        <NumberField.Increment data-slot="stepper-increment" aria-label={`Increase ${label}`} className={buttonStyle}>
          <svg viewBox="0 0 20 20" aria-hidden="true" className="fill-none stroke-current" strokeWidth="1.75" strokeLinecap="round">
            <path d="M5 10h10M10 5v10" />
          </svg>
        </NumberField.Increment>
      </NumberField.Group>
    </NumberField.Root>
  )
}
```
