# Animated Number Input for UI SDK (/docs/components/number-input)

Digits roll up or down as the value changes, and the buttons press in.

```tsx title="example.tsx"
import * as React from "react"

import { Field, FieldDescription, FieldLabel } from "@/components/keyframery/field"
import {
  NumberInput,
  NumberInputControl,
  NumberInputDecrement,
  NumberInputGroup,
  NumberInputIncrement,
  NumberInputScrubArea,
} from "@/components/keyframery/number-input"

/* Each digit is a column of 0 to 9 that rolls to its place. */
function Roll({ text }: { text: string }) {
  return (
    <span className="inline-flex h-[1.2em] overflow-hidden leading-[1.2em] tabular-nums">
      {text.split("").map((c, i) =>
        /\d/.test(c) ? (
          <span
            key={text.length - i}
            style={{ "--d": Number(c) } as React.CSSProperties}
            className="flex flex-col transition-[translate] duration-500 ease-spring [translate:0_calc(var(--d)*-1.2em)] motion-reduce:transition-none"
          >
            {Array.from({ length: 10 }, (_, d) => (
              <span key={d} className="h-[1.2em]">
                {d}
              </span>
            ))}
          </span>
        ) : (
          <span key={`${text.length - i}${c}`}>{c}</span>
        ),
      )}
    </span>
  )
}

const nightly = 142

export default function NumberInputDemo() {
  const [nights, setNights] = React.useState<number | null>(3)
  const [guests, setGuests] = React.useState<number | null>(2)
  const total = (nights ?? 0) * nightly

  return (
    <div className="flex w-[340px] flex-col gap-5">
      <div>
        <h3 className="text-[15px] font-semibold tracking-tight">Hollow Farm cottage</h3>
        <p className="mt-1 text-[13px] text-muted-foreground">Sleeps 4, €{nightly} a night</p>
      </div>
      <div className="grid grid-cols-2 gap-3">
        <Field>
          <NumberInput value={nights} onValueChange={(value) => setNights(value)} min={1} max={28}>
            <NumberInputScrubArea pixelsPerStep={6}>
              <FieldLabel>Nights</FieldLabel>
            </NumberInputScrubArea>
            <NumberInputGroup>
              <NumberInputDecrement aria-label="One night fewer" />
              <NumberInputControl />
              <NumberInputIncrement aria-label="One more night" />
            </NumberInputGroup>
          </NumberInput>
        </Field>
        <Field>
          <NumberInput value={guests} onValueChange={(value) => setGuests(value)} min={1} max={4}>
            <NumberInputScrubArea pixelsPerStep={10}>
              <FieldLabel>Guests</FieldLabel>
            </NumberInputScrubArea>
            <NumberInputGroup>
              <NumberInputDecrement aria-label="One guest fewer" />
              <NumberInputControl />
              <NumberInputIncrement aria-label="One more guest" />
            </NumberInputGroup>
          </NumberInput>
        </Field>
      </div>
      <Field disabled>
        <FieldLabel>Rooms</FieldLabel>
        <NumberInput defaultValue={1} disabled>
          <NumberInputGroup>
            <NumberInputDecrement aria-label="One room fewer" />
            <NumberInputControl />
            <NumberInputIncrement aria-label="One more room" />
          </NumberInputGroup>
        </NumberInput>
        <FieldDescription>The flat is booked as a whole.</FieldDescription>
      </Field>
      <div className="flex items-baseline justify-between border-t border-border pt-4 text-[13px]">
        <span className="inline-flex items-baseline gap-1 text-muted-foreground tabular-nums">
          <Roll text={String(nights ?? 0)} /> {nights === 1 ? "night" : "nights"} ·{" "}
          <Roll text={String(guests ?? 0)} /> {guests === 1 ? "guest" : "guests"}
        </span>
        <span className="text-[15px] font-semibold tracking-tight">
          <Roll text={`€${total.toLocaleString("en-GB")}`} />
        </span>
      </div>
    </div>
  )
}
```

## Installation [#installation]

```bash
npx shadcn@latest add @keyframery/number-input
```

This adds `components/keyframery/number-input.tsx` and its primitive, `components/keyframery/primitives/number-input.tsx`, to your project, and installs `@ui-sdk/react`. The motion tokens are added to your global CSS the first time you install a component.

## Usage [#usage]

```tsx
import {
  NumberInput,
  NumberInputControl,
  NumberInputDecrement,
  NumberInputGroup,
  NumberInputIncrement,
  NumberInputScrubArea,
  NumberInputScrubAreaCursor,
} from "@/components/keyframery/number-input"
```

The parts and props are the same as UI SDK's Number Input. For every prop, see the [UI SDK number input reference](https://ui-sdk.dev/docs/components/number-input).

## What moves [#what-moves]

| Move      | What you see                                 |
| --------- | -------------------------------------------- |
| **Roll**  | Digits roll up or down as the value changes. |
| **Press** | The stepper buttons press in with a pop.     |

Timing and springiness follow the [motion style](/docs/motion-styles) you set, so this component moves like the rest of your app.

## Swap the import [#swap-the-import]

Already using UI SDK's number input with your own styles? Keep your markup and change one line. The primitive adds motion and nothing else.

```tsx
// Before
import { … } from "@ui-sdk/react/number-input"

// After: same parts, same props, now animated
import { … } from "@/components/keyframery/primitives/number-input"
```

## Parts [#parts]

The finished component exports 7 parts:

`NumberInput`, `NumberInputControl`, `NumberInputDecrement`, `NumberInputGroup`, `NumberInputIncrement`, `NumberInputScrubArea`, `NumberInputScrubAreaCursor`

## Accessibility [#accessibility]

Keyboard, focus and screen-reader behaviour come from UI SDK and are not changed. With reduced motion turned on, nothing in the number input moves: changes happen at once or with a short fade. More in [Accessibility](/docs/accessibility).

## Source [#source]

The code that lands in your project. It is yours to change.

**components/keyframery/number-input.tsx**

```tsx
"use client"

/* Styled number input: the animated primitive plus the Keyframery look. */

import * as React from "react"

import {
  NumberInput as NumberInputRoot,
  NumberInputControl as NumberInputControlPrimitive,
  NumberInputDecrement as NumberInputDecrementPrimitive,
  NumberInputGroup as NumberInputGroupPrimitive,
  NumberInputIncrement as NumberInputIncrementPrimitive,
  NumberInputScrubArea as NumberInputScrubAreaPart,
  NumberInputScrubAreaCursor as NumberInputScrubAreaCursorPart,
  createNumberInputController,
} from "@/components/keyframery/primitives/number-input"
import { cn } from "@/lib/utils"

function NumberInput({ className, ...props }: React.ComponentProps<typeof NumberInputRoot>) {
  return <NumberInputRoot className={cn("flex min-w-0 flex-col gap-1.5", className)} {...props} />
}

/* The group is the field: two keys with the value between them. */
function NumberInputGroup({
  className,
  ...props
}: React.ComponentProps<typeof NumberInputGroupPrimitive>) {
  return (
    <NumberInputGroupPrimitive
      className={cn(
        "flex h-9 w-full min-w-0 items-center gap-1 rounded-[10px] bg-background p-1 text-[13px]",
        "outline-0 outline-ring",
        "[--field-line:rgb(0_0_0/0.09)] dark:[--field-line:rgb(255_255_255/0.1)]",
        "shadow-[0_0_0_1px_var(--field-line),0_1px_2px_rgb(0_0_0/0.05)] dark:shadow-[0_0_0_1px_var(--field-line)]",
        "hover:[--field-line:rgb(0_0_0/0.16)] dark:hover:[--field-line:rgb(255_255_255/0.18)]",
        "has-[input:focus-visible]:outline-[3px] has-[input:focus-visible]:outline-ring/30 has-[input:focus-visible]:[--field-line:var(--ring)] dark:has-[input:focus-visible]:[--field-line:var(--ring)]",
        "data-scrubbing:outline-[3px] data-scrubbing:outline-ring/30 data-scrubbing:[--field-line:var(--ring)] dark:data-scrubbing:[--field-line:var(--ring)]",
        "has-aria-invalid:outline-destructive has-aria-invalid:has-[input:focus-visible]:outline-destructive/30 has-aria-invalid:[--field-line:var(--destructive)] dark:has-aria-invalid:[--field-line:var(--destructive)]",
        "data-readonly:bg-muted/50",
        "data-disabled:cursor-not-allowed data-disabled:bg-muted data-disabled:[--field-line:rgb(0_0_0/0.06)] dark:data-disabled:[--field-line:rgb(255_255_255/0.06)]",
        className,
      )}
      {...props}
    />
  )
}

function NumberInputControl({
  className,
  ...props
}: React.ComponentProps<typeof NumberInputControlPrimitive>) {
  return (
    <NumberInputControlPrimitive
      className={cn(
        "h-full w-full min-w-0 flex-1 bg-transparent text-center text-[13px] font-medium text-foreground tabular-nums outline-none placeholder:text-muted-foreground/70",
        "data-disabled:cursor-not-allowed data-disabled:text-muted-foreground",
        className,
      )}
      {...props}
    />
  )
}

/* A small key. It goes flat at its bound or when the field is off. */
const stepKey = cn(
  "grid size-7 shrink-0 cursor-pointer place-items-center rounded-[7px] bg-background text-foreground outline-none select-none",
  "shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_1px_rgb(0_0_0/0.05),0_2px_4px_-2px_rgb(0_0_0/0.1)]",
  "dark:bg-accent dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07),inset_0_1px_0_rgb(255_255_255/0.08),0_2px_6px_-1px_rgb(0_0_0/0.6)]",
  "hover:bg-muted/60 dark:hover:bg-accent/80",
  "active:translate-y-px active:shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_0_1px_rgb(0_0_0/0.08)] dark:active:shadow-[0_0_0_1px_rgb(255_255_255/0.06),0_0_1px_rgb(0_0_0/0.6)]",
  "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
  "data-disabled:cursor-not-allowed data-disabled:translate-y-0 data-disabled:bg-transparent data-disabled:text-muted-foreground/50 data-disabled:shadow-none dark:data-disabled:bg-transparent dark:data-disabled:shadow-none",
  "[&_svg]:size-3.5 [&_svg]:shrink-0",
)

function StepIcon({ plus }: { plus?: boolean }) {
  return (
    <svg
      viewBox="0 0 16 16"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      <path d="M3.5 8h9" />
      {plus && <path d="M8 3.5v9" />}
    </svg>
  )
}

function NumberInputDecrement({
  className,
  children,
  ...props
}: React.ComponentProps<typeof NumberInputDecrementPrimitive>) {
  return (
    <NumberInputDecrementPrimitive className={cn(stepKey, className)} {...props}>
      {children ?? <StepIcon />}
    </NumberInputDecrementPrimitive>
  )
}

function NumberInputIncrement({
  className,
  children,
  ...props
}: React.ComponentProps<typeof NumberInputIncrementPrimitive>) {
  return (
    <NumberInputIncrementPrimitive className={cn(stepKey, className)} {...props}>
      {children ?? <StepIcon plus />}
    </NumberInputIncrementPrimitive>
  )
}

/* Drag it sideways to change the value. Usually wraps the label. */
function NumberInputScrubArea({
  className,
  ...props
}: React.ComponentProps<typeof NumberInputScrubAreaPart>) {
  return (
    <NumberInputScrubAreaPart
      className={cn(
        "w-fit cursor-ew-resize select-none data-[orientation=vertical]:cursor-ns-resize",
        "data-disabled:cursor-not-allowed data-readonly:cursor-default",
        className,
      )}
      {...props}
    />
  )
}

/* Drawn while the pointer is locked during a drag; the part places it with a translation. */
function NumberInputScrubAreaCursor({
  className,
  children,
  ...props
}: React.ComponentProps<typeof NumberInputScrubAreaCursorPart>) {
  return (
    <NumberInputScrubAreaCursorPart
      className={cn(
        "pointer-events-none -ms-2 -mt-2 size-4 text-foreground drop-shadow-[0_1px_1px_rgb(0_0_0/0.25)] [&_svg]:size-4",
        className,
      )}
      {...props}
    >
      {children ?? (
        <svg
          viewBox="0 0 16 16"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="M2 8h12M4.5 5.5 2 8l2.5 2.5M11.5 5.5 14 8l-2.5 2.5" />
        </svg>
      )}
    </NumberInputScrubAreaCursorPart>
  )
}

export {
  NumberInput,
  NumberInputControl,
  NumberInputDecrement,
  NumberInputGroup,
  NumberInputIncrement,
  NumberInputScrubArea,
  NumberInputScrubAreaCursor,
  createNumberInputController,
}
```

**components/keyframery/primitives/number-input.tsx**

```tsx
"use client"

/* Animated drop-in for `@ui-sdk/react/number-input`: same parts, same props. Swap the import and keep
   your code. This file adds motion only. Colours, radii, shadows and spacing stay yours. */

import {
  NumberInputControl as NumberInputControlPart,
  NumberInputDecrement as NumberInputDecrementPart,
  NumberInputGroup as NumberInputGroupPart,
  NumberInputIncrement as NumberInputIncrementPart,
} from "@ui-sdk/react/number-input"
import * as React from "react"

import { cn } from "@/lib/utils"

export * from "@ui-sdk/react/number-input"

/* The group is usually the field's box: its focus ring is the outline, which closes in from
   10px out on a spring, easing from its resting colour to its focus colour. Give it width and colour with `has-[input:focus-visible]:outline-…`. */
function NumberInputGroup({ className, ...props }: React.ComponentProps<typeof NumberInputGroupPart>) {
  return (
    <NumberInputGroupPart
      className={cn(
        "outline-offset-[10px] has-[input:focus-visible]:outline-offset-0 data-scrubbing:outline-offset-0",
        "[transition:outline-offset_calc(160ms*var(--kf-speed,1))_var(--ease-house),outline-width_calc(160ms*var(--kf-speed,1))_var(--ease-house),outline-color_0s_linear_calc(160ms*var(--kf-speed,1)),box-shadow_calc(150ms*var(--kf-speed,1))_var(--ease-house),background-color_calc(150ms*var(--kf-speed,1))_var(--ease-house)] has-[input:focus-visible]:[transition:outline-offset_calc(900ms*var(--kf-speed,1))_var(--ease-spring),outline-width_calc(900ms*var(--kf-speed,1))_var(--ease-spring),outline-color_calc(700ms*var(--kf-speed,1))_var(--ease-house),box-shadow_calc(150ms*var(--kf-speed,1))_var(--ease-house),background-color_calc(150ms*var(--kf-speed,1))_var(--ease-house)] data-scrubbing:[transition:outline-offset_calc(900ms*var(--kf-speed,1))_var(--ease-spring),outline-width_calc(900ms*var(--kf-speed,1))_var(--ease-spring),outline-color_calc(700ms*var(--kf-speed,1))_var(--ease-house),box-shadow_calc(150ms*var(--kf-speed,1))_var(--ease-house),background-color_calc(150ms*var(--kf-speed,1))_var(--ease-house)]",
        "motion-reduce:[transition:none]!",
        className,
      )}
      {...props}
    />
  )
}

/* While a stepper is held, the value leans 3px toward it, and springs back on release. */
function NumberInputControl({
  className,
  ...props
}: React.ComponentProps<typeof NumberInputControlPart>) {
  return (
    <NumberInputControlPart
      className={cn(
        "transition-[translate] duration-[calc(300ms*var(--kf-speed,1))] ease-pop motion-reduce:transition-none!",
        "in-[[data-slot=number-input-group]:has([data-slot=number-input-increment]:not([data-disabled]):active)]:translate-x-[3px]",
        "in-[[data-slot=number-input-group]:has([data-slot=number-input-decrement]:not([data-disabled]):active)]:-translate-x-[3px]",
        className,
      )}
      {...props}
    />
  )
}

/* Steppers press deep and spring back with a pop. */
const stepperMotion =
  "[transition:scale_calc(280ms*var(--kf-speed,1))_var(--ease-pop),translate_calc(280ms*var(--kf-speed,1))_var(--ease-pop),box-shadow_calc(120ms*var(--kf-speed,1))_var(--ease-house),background-color_calc(120ms*var(--kf-speed,1))_var(--ease-house),color_calc(120ms*var(--kf-speed,1))_var(--ease-house),opacity_calc(120ms*var(--kf-speed,1))_var(--ease-house)] " +
  "active:scale-[0.84] data-disabled:active:scale-100 motion-reduce:[transition:none]!"

function NumberInputDecrement({
  className,
  ...props
}: React.ComponentProps<typeof NumberInputDecrementPart>) {
  return <NumberInputDecrementPart className={cn(stepperMotion, className)} {...props} />
}

function NumberInputIncrement({
  className,
  ...props
}: React.ComponentProps<typeof NumberInputIncrementPart>) {
  return <NumberInputIncrementPart className={cn(stepperMotion, className)} {...props} />
}

export { NumberInputControl, NumberInputDecrement, NumberInputGroup, NumberInputIncrement }
```

## Questions

### How does the animated Number Input for UI SDK move?

Roll: Digits roll up or down as the value changes. Press: The stepper buttons press in with a pop.

### Do I need Motion or Framer Motion for the animated Number Input?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### Can I keep my own styling and only take the motion?

Yes. Import from `@/components/keyframery/primitives/number-input` instead. It has the same parts and props as `@ui-sdk/react/number-input` and adds motion only.

### What happens to the Number Input when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
