# Number Field
A number typed, stepped or scrubbed by a person or agent.
Source page: https://dinachi.dev/docs/components/number-field

## Installation
```bash
npx @dinachi/cli@latest add number-field
```
Adds to your project:
- `components/ui/number-field/number-field.tsx`
- `components/ui/number-field/index.ts`
Installs:
- `@base-ui/react` ^1.9.0
- `lucide-react` ^0.552.0

## Usage
```tsx
import {
  NumberField,
  NumberFieldDecrement,
  NumberFieldGroup,
  NumberFieldIncrement,
  NumberFieldInput,
} from "@/components/ui/number-field"

export function Quantity() {
  return (
    <NumberField defaultValue={1} min={1} max={10}>
      <NumberFieldGroup>
        <NumberFieldDecrement />
        <NumberFieldInput aria-label="Quantity" />
        <NumberFieldIncrement />
      </NumberFieldGroup>
    </NumberField>
  )
}
```

## Anatomy
```tsx
<NumberField>
  <NumberFieldScrubArea>
    <NumberFieldScrubAreaCursor />
  </NumberFieldScrubArea>
  <NumberFieldGroup>
    <NumberFieldDecrement />
    <NumberFieldInput />
    <NumberFieldIncrement />
  </NumberFieldGroup>
</NumberField>
```
- `NumberField`: Holds the value, the range and the step.
- `NumberFieldGroup`: The bordered row of input and buttons.
- `NumberFieldInput`: The text input.
- `NumberFieldDecrement`: Steps the value down.
- `NumberFieldIncrement`: Steps the value up.
- `NumberFieldScrubArea`: Drag to change the value; often wraps a label.
- `NumberFieldScrubAreaCursor`: A custom cursor shown while scrubbing.

## Examples

### Default
An input between decrement and increment buttons.
```tsx
import { NumberField, NumberFieldGroup, NumberFieldInput, NumberFieldIncrement, NumberFieldDecrement } from '@/components/ui/number-field';

export function Example() {
  return (
    <NumberField defaultValue={5} className="w-[180px]">
      <NumberFieldGroup>
        <NumberFieldDecrement />
        <NumberFieldInput />
        <NumberFieldIncrement />
      </NumberFieldGroup>
    </NumberField>
  );
}
```

### Min and max
The value stays between 1 and 10.
```tsx
import { NumberField, NumberFieldGroup, NumberFieldInput, NumberFieldIncrement, NumberFieldDecrement } from '@/components/ui/number-field';

export function Example() {
  return (
    <div className="space-y-2">
      <label className="text-sm font-medium">Quantity (1-10)</label>
      <NumberField defaultValue={1} min={1} max={10} className="w-[180px]">
        <NumberFieldGroup>
          <NumberFieldDecrement />
          <NumberFieldInput />
          <NumberFieldIncrement />
        </NumberFieldGroup>
      </NumberField>
    </div>
  );
}
```

### Step
A price that steps by 0.01.
```tsx
import { NumberField, NumberFieldGroup, NumberFieldInput, NumberFieldIncrement, NumberFieldDecrement } from '@/components/ui/number-field';

export function Example() {
  return (
    <div className="space-y-2">
      <label className="text-sm font-medium">Price ($)</label>
      <NumberField defaultValue={9.99} step={0.01} min={0} className="w-[180px]">
        <NumberFieldGroup>
          <NumberFieldDecrement />
          <NumberFieldInput />
          <NumberFieldIncrement />
        </NumberFieldGroup>
      </NumberField>
    </div>
  );
}
```

## API reference
Props marked **agent** change what an agent reads or may do.

### NumberField
Holds the value, the range and the step.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `number \| null` | - | Controlled value. |
| `defaultValue` | `number \| null` | `null` | Starting value when uncontrolled. |
| `onValueChange` **agent** | `(value, details) => void` | - | Runs for people and agents. `details.cancel()` refuses the change. |
| `onValueCommitted` **agent** | `(value, details) => void` | - | Runs when a person commits, such as on blur, and after each accepted agent change. |
| `min` **agent** | `number` | - | Lowest value. Agent changes are clamped to it. |
| `max` **agent** | `number` | - | Highest value. Agent changes are clamped to it. |
| `step` **agent** | `number \| "any"` | `1` | How far one step moves. With "any" the agent steps by 1. |
| `smallStep` | `number` | `0.1` | The step while Alt is held. |
| `largeStep` | `number` | `10` | The step while Shift is held. |
| `format` | `Intl.NumberFormatOptions` | - | Formats the value in the input, for example as currency. |
| `locale` | `Intl.LocalesArgument` | - | The locale used to format and parse the value. |
| `allowWheelScrub` | `boolean` | `false` | Steps the value with the mouse wheel while the input is focused. |
| `snapOnStep` | `boolean` | `false` | Snaps stepped values to the nearest multiple of the step. |
| `disabled` **agent** | `boolean` | `false` | Blocks people and agents. |
| `readOnly` **agent** | `boolean` | `false` | Shows the value, refuses any change. |
| `name` | `string` | - | Submits the value with a form. |
| `required` | `boolean` | `false` | Must have a value before the form submits. |

### NumberFieldGroup
The bordered row of input and buttons.

Takes the props of the element it renders.

### NumberFieldInput
The text input.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `aria-label` **agent** | `string` | - | Names the field without a label element. The agent reads it too. |

### NumberFieldDecrement
Steps the value down.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode` | `<Minus />` | Replaces the icon. |

### NumberFieldIncrement
Steps the value up.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode` | `<Plus />` | Replaces the icon. |

### NumberFieldScrubArea
Drag to change the value; often wraps a label.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `direction` | `"horizontal" \| "vertical"` | `"horizontal"` | Which way the pointer moves to scrub. |
| `pixelSensitivity` | `number` | `2` | Pixels the pointer moves per step. |

### NumberFieldScrubAreaCursor
A custom cursor shown while scrubbing.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode` | - | The cursor icon. |

## Agent
Inside an `AgentProvider`, Number Field appears in `agent.snapshot()` as `number`.
Reads:
- `label`: The input's label or aria-label.
- `value`: The current number, or nothing while empty.
- `min / max`: The range, when set.
- `step`: The step size. 1 when step is "any".
- `disabled`: True when the field is blocked.
Actions:
- `setValue(42)`: Sets the value, clamped to min and max. A string that is not a number fails.
- `increment(3)`: Steps up by that many steps, 1 if omitted. An empty field steps from min, or 0.
- `decrement(3)`: Steps down the same way.
An agent's change runs through `onValueChange` like anyone's. `isAgentChange(details)` is true for it; `details.cancel()` refuses it and the agent is told the app refused. An accepted change also runs `onValueCommitted`. A disabled or `readOnly` field refuses on its own.
```ts
await agent.act({
  steps: [{ ref: "number", action: "increment", args: [3] }],
})
```

## Accessibility
- The input is a text field described as a "Number field", with a numeric inputmode.
- Name every field with a label element or aria-label on `NumberFieldInput`. The agent reads it too.
- The step buttons are hidden from the agent, which steps through the field.
### Keyboard
| Keys | Does |
| --- | --- |
| `↑` / `↓` | Steps the value up or down |
| `Shift` / `↑` | Steps by `largeStep`, with ↓ to go down |
| `Alt` / `↑` | Steps by `smallStep`, with ↓ to go down |
| `Home` | Sets the value to min, when set |
| `End` | Sets the value to max, when set |

## Source
`components/ui/number-field/number-field.tsx`
```tsx
"use client"

import * as React from "react"
import { NumberField as NumberFieldPrimitive } from "@base-ui/react/number-field"
import { Minus, Plus } from "lucide-react"
import { cn } from "@/lib/utils"
import { agentRound, changeAsAgent, createAgentChangeDetails, useAgentControl, useAgentState, useHasAgent, useMergedRef } from "@/components/ui/agent"

type NumberFieldProps = React.ComponentPropsWithoutRef<typeof NumberFieldPrimitive.Root>

const NumberFieldAgentContext = React.createContext<React.MutableRefObject<HTMLInputElement | null> | null>(null)

const clamp = (n: number, min = -Infinity, max = Infinity) => Math.min(max, Math.max(min, n))

function toNumber(value: unknown): number | string {
  const n = typeof value === "number" ? value : Number(String(value ?? "").trim() || NaN)
  return Number.isFinite(n) ? n : `"${String(value)}" is not a number.`
}

// Base UI also takes "any", which has no size to step by, so the agent steps by 1.
const stepOf = ({ step }: NumberFieldProps) => (typeof step === "number" ? step : 1)

/** The agent's actions, each clamped to min and max the way Base UI clamps a person's. */
function numberActions(props: NumberFieldProps, value: number | null, set: (next: number) => string | undefined) {
  const { min, max, readOnly } = props
  const step = stepOf(props)
  const to = (next: unknown, from = 0, scale = 1) => {
    if (readOnly) return "The number field is read-only."
    const n = toNumber(next)
    return typeof n === "string" ? n : set(clamp(agentRound(from + n * scale, from, scale, n), min, max))
  }
  const from = value ?? min ?? 0
  return {
    setValue: (next: unknown) => to(next),
    increment: (steps: unknown = 1) => to(steps, from, step),
    decrement: (steps: unknown = 1) => to(steps, from, -step),
  }
}

/**
 * Base UI's root, holding its own value so an agent can set it the way a parent would.
 * `onValueChange` sees the agent's changes first and can cancel them.
 */
const NumberField = React.forwardRef<HTMLDivElement, NumberFieldProps>(
  ({ value: valueProp, defaultValue = null, onValueChange, ...props }, ref) => {
    type Details = NumberFieldPrimitive.Root.ChangeEventDetails
    const [value, changeValue] = useAgentState<number | null, Details>(valueProp, defaultValue, onValueChange)
    const input = React.useRef<HTMLInputElement | null>(null)

    useAgentControl(() => ({
      kind: "number" as const,
      element: input.current,
      value: value ?? undefined,
      min: props.min,
      max: props.max,
      step: stepOf(props),
      disabled: props.disabled,
      // An agent's change is whole at once, so it is committed too, as a person's is on blur.
      actions: numberActions(
        props,
        value,
        (next) => changeAsAgent(changeValue, next) ?? void props.onValueCommitted?.(next, createAgentChangeDetails("none"))
      ),
    }))

    return (
      <NumberFieldAgentContext.Provider value={useHasAgent() ? input : null}>
        <NumberFieldPrimitive.Root ref={ref} data-slot="number-field" {...props} value={value} onValueChange={changeValue} />
      </NumberFieldAgentContext.Provider>
    )
  }
)
NumberField.displayName = "NumberField"

const NumberFieldGroup = React.forwardRef<
  React.ComponentRef<typeof NumberFieldPrimitive.Group>,
  React.ComponentPropsWithoutRef<typeof NumberFieldPrimitive.Group>
>(({ className, ...props }, ref) => (
  <NumberFieldPrimitive.Group
    ref={ref}
    data-slot="number-field-group"
    className={cn(
      "inline-flex h-10 w-full items-stretch overflow-hidden rounded-md border border-input bg-background",
      className
    )}
    {...props}
  />
))
NumberFieldGroup.displayName = "NumberFieldGroup"

const NumberFieldInput = React.forwardRef<
  React.ComponentRef<typeof NumberFieldPrimitive.Input>,
  React.ComponentPropsWithoutRef<typeof NumberFieldPrimitive.Input>
>(({ className, ...props }, ref) => (
  <NumberFieldPrimitive.Input
    ref={useMergedRef(ref, React.useContext(NumberFieldAgentContext))}
    data-slot="number-field-input"
    className={cn(
      "w-full bg-transparent px-3 text-sm outline-none placeholder:text-muted-foreground",
      "disabled:cursor-not-allowed disabled:opacity-50",
      className
    )}
    {...props}
  />
))
NumberFieldInput.displayName = "NumberFieldInput"

const NumberFieldIncrement = React.forwardRef<
  React.ComponentRef<typeof NumberFieldPrimitive.Increment>,
  React.ComponentPropsWithoutRef<typeof NumberFieldPrimitive.Increment>
>(({ className, children, ...props }, ref) => (
  <NumberFieldPrimitive.Increment
    ref={ref}
    data-slot="number-field-increment"
    data-agent-part={useHasAgent() ? "" : undefined}
    className={cn(
      "inline-flex h-full items-center justify-center border-l border-input px-3 text-muted-foreground transition-colors",
      "hover:bg-accent hover:text-accent-foreground",
      "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
      "disabled:pointer-events-none disabled:opacity-50",
      className
    )}
    {...props}
  >
    {children ?? <Plus className="h-4 w-4" />}
  </NumberFieldPrimitive.Increment>
))
NumberFieldIncrement.displayName = "NumberFieldIncrement"

const NumberFieldDecrement = React.forwardRef<
  React.ComponentRef<typeof NumberFieldPrimitive.Decrement>,
  React.ComponentPropsWithoutRef<typeof NumberFieldPrimitive.Decrement>
>(({ className, children, ...props }, ref) => (
  <NumberFieldPrimitive.Decrement
    ref={ref}
    data-slot="number-field-decrement"
    data-agent-part={useHasAgent() ? "" : undefined}
    className={cn(
      "inline-flex h-full items-center justify-center border-r border-input px-3 text-muted-foreground transition-colors",
      "hover:bg-accent hover:text-accent-foreground",
      "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
      "disabled:pointer-events-none disabled:opacity-50",
      className
    )}
    {...props}
  >
    {children ?? <Minus className="h-4 w-4" />}
  </NumberFieldPrimitive.Decrement>
))
NumberFieldDecrement.displayName = "NumberFieldDecrement"

const NumberFieldScrubArea = React.forwardRef<
  React.ComponentRef<typeof NumberFieldPrimitive.ScrubArea>,
  React.ComponentPropsWithoutRef<typeof NumberFieldPrimitive.ScrubArea>
>(({ className, ...props }, ref) => (
  <NumberFieldPrimitive.ScrubArea
    ref={ref}
    data-slot="number-field-scrub-area"
    className={cn("cursor-ew-resize", className)}
    {...props}
  />
))
NumberFieldScrubArea.displayName = "NumberFieldScrubArea"

const NumberFieldScrubAreaCursor = React.forwardRef<
  React.ComponentRef<typeof NumberFieldPrimitive.ScrubAreaCursor>,
  React.ComponentPropsWithoutRef<typeof NumberFieldPrimitive.ScrubAreaCursor>
>(({ className, ...props }, ref) => (
  <NumberFieldPrimitive.ScrubAreaCursor
    ref={ref}
    data-slot="number-field-scrub-area-cursor"
    className={cn("text-muted-foreground", className)}
    {...props}
  />
))
NumberFieldScrubAreaCursor.displayName = "NumberFieldScrubAreaCursor"

export type { NumberFieldProps }

export {
  NumberField,
  NumberFieldGroup,
  NumberFieldInput,
  NumberFieldIncrement,
  NumberFieldDecrement,
  NumberFieldScrubArea,
  NumberFieldScrubAreaCursor,
}
```
