# NumberField

A controlled input for a number, with stepper buttons, locale formatting and an area to drag across.

- Page: https://www.effectcn.com/components/number-field
- Kind: Headless component with parts
- File: `src/ui/number-field.ts`
- Built on: `NumberField` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/number-field.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/number-field.ts`

```ts
import type { Component } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import type { InputElement, NumberField } from "@effect/ui-kit"
import { cn } from "#lib/cn"

/** What the kit's `NumberField` hands its `view` closure. */
export type NumberFieldParts = Component.Headless.Parts<typeof NumberField>

interface ClassOption {
  readonly class?: string | undefined
}

const stepper =
  "relative shrink-0 text-muted-foreground transition-colors duration-150 hover:bg-accent hover:text-foreground active:bg-foreground/10 " +
  "data-[disabled]:cursor-not-allowed data-[disabled]:bg-transparent data-[disabled]:text-muted-foreground/40 " +
  "before:absolute before:top-1/2 before:left-1/2"

const bar = "before:h-[1.5px] before:w-2.5 before:-translate-1/2 before:rounded-full before:bg-current"

const chevron = "before:size-[5px] before:-translate-x-1/2 before:border-t-[1.5px] before:border-l-[1.5px] before:border-current"

const groups = {
  default: "",
  stacked: "[&>input]:border-l-0 [&>input]:text-left"
} as const

export type NumberFieldVariant = keyof typeof groups

/** The root. Pass `element: field.root(h.div)` when the number field is a `Field`. */
export const NumberFieldRoot = <Msg>(
  h: Html.H<Msg>,
  numberField: NumberFieldParts,
  options: ClassOption & { readonly element?: ReturnType<Html.H<Msg>["div"]["attr"]> | undefined } = {}
) =>
  numberField.root(
    (options.element ?? h.div).class(cn("inline-flex flex-col items-start gap-1.5", options.class))
  )

/** A `<label>`. Point its `for` at the input's id, or draw `field.label` instead. */
export const NumberFieldLabel = <Msg>(h: Html.H<Msg>, numberField: NumberFieldParts, options: ClassOption = {}) =>
  h.label
    .class(cn("text-[13px] font-medium data-[disabled]:opacity-50", options.class))
    .attr("data-disabled", numberField.disabled ? "" : undefined)

/**
 * The bordered box around the input and the buttons. `stacked` is for an
 * input followed by `NumberFieldSteppers`.
 */
export const NumberFieldGroup = <Msg>(
  h: Html.H<Msg>,
  numberField: NumberFieldParts,
  options: ClassOption & { readonly variant?: NumberFieldVariant | undefined } = {}
) =>
  numberField.group(
    h.div.class(cn(
      "inline-flex h-8.5 items-stretch rounded-md border border-input bg-background shadow-sm",
      "transition-[border-color,box-shadow] duration-150 focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/20",
      "has-[input[aria-invalid=true]]:border-destructive data-[disabled]:opacity-50",
      groups[options.variant ?? "default"],
      options.class
    ))
  )

/** The text input. Pass `element: field.control(h.input)` in a `Field`, or `h.input.attr("id", ...)` for a label. */
export const NumberFieldInput = <Msg>(
  h: Html.H<Msg>,
  numberField: NumberFieldParts,
  options: ClassOption & { readonly element?: InputElement<Msg> | undefined } = {}
) =>
  numberField.input(
    (options.element ?? h.input).class(cn(
      "w-22 min-w-0 border-0 border-x border-input bg-transparent px-2.5 text-center text-[13px] text-foreground tabular-nums outline-none",
      "data-[disabled]:cursor-not-allowed data-[readonly]:text-muted-foreground",
      options.class
    ))
  )

/** The minus button, drawn with a bar. */
export const NumberFieldDecrement = <Msg>(h: Html.H<Msg>, numberField: NumberFieldParts, options: ClassOption = {}) =>
  numberField.decrement({
    element: h.button.class(cn(stepper, bar, "w-8 rounded-l-[calc(var(--radius-md)-1px)]", options.class))
  })

/** The plus button, drawn with two bars. */
export const NumberFieldIncrement = <Msg>(h: Html.H<Msg>, numberField: NumberFieldParts, options: ClassOption = {}) =>
  numberField.increment({
    element: h.button.class(cn(
      stepper,
      bar,
      "w-8 rounded-r-[calc(var(--radius-md)-1px)]",
      "after:absolute after:top-1/2 after:left-1/2 after:h-[1.5px] after:w-2.5 after:-translate-1/2 after:rotate-90 after:rounded-full after:bg-current",
      options.class
    ))
  })

/** Both buttons in a column of chevrons, for the end of a `stacked` group. */
export const NumberFieldSteppers = <Msg>(h: Html.H<Msg>, numberField: NumberFieldParts, options: ClassOption = {}) =>
  h.div.class(cn("flex w-6 flex-col", options.class)).children(
    numberField.increment({
      element: h.button.class(cn(
        stepper,
        chevron,
        "flex-1 rounded-tr-[calc(var(--radius-md)-1px)] border-b border-input before:-translate-y-1/4 before:rotate-45"
      ))
    }),
    numberField.decrement({
      element: h.button.class(cn(
        stepper,
        chevron,
        "flex-1 rounded-br-[calc(var(--radius-md)-1px)] before:-translate-y-3/4 before:rotate-225"
      ))
    })
  )

/** The two-headed arrow the scrub area and its cursor show. */
export const NumberFieldScrubIcon = <Msg>(h: Html.H<Msg>) =>
  h.el("svg")
    .attrs({
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      "stroke-width": "2",
      "stroke-linecap": "round",
      "stroke-linejoin": "round",
      "aria-hidden": "true"
    })
    .children(h.el("path").attr("d", "M8 8l-4 4 4 4M16 8l4 4-4 4M4 12h16"))

/** An area that changes the value when it is dragged across. Put the label inside it. */
export const NumberFieldScrubArea = <Msg>(
  h: Html.H<Msg>,
  numberField: NumberFieldParts,
  options: ClassOption & { readonly direction?: "horizontal" | "vertical" | undefined } = {}
) =>
  numberField.scrubArea({
    element: h.span.class(cn(
      "inline-flex cursor-ew-resize items-center gap-1.5 data-[disabled]:cursor-default data-[disabled]:opacity-50",
      "[&_label]:cursor-[inherit] [&_svg]:size-[13px] [&_svg]:text-muted-foreground",
      options.class
    )),
    direction: options.direction
  })

/**
 * Stands in for the pointer while a drag holds the pointer lock, and is
 * `undefined` otherwise. It is a popover, so its browser defaults are cleared.
 */
export const NumberFieldScrubAreaCursor = <Msg>(h: Html.H<Msg>, numberField: NumberFieldParts, options: ClassOption = {}) =>
  numberField.scrubAreaCursor(
    h.span.class(cn(
      "size-5.5 overflow-visible border-0 bg-transparent p-0 text-foreground [&_svg]:size-5.5 [&_svg]:text-foreground",
      options.class
    ))
  )?.children(NumberFieldScrubIcon(h))
```

```ts
import { NumberFieldRoot, NumberFieldLabel, NumberFieldGroup, NumberFieldInput, NumberFieldDecrement, NumberFieldIncrement, NumberFieldSteppers, NumberFieldScrubIcon, NumberFieldScrubArea, NumberFieldScrubAreaCursor } from "#ui/number-field"
```

## Usage

Type a number, press a button or hold it, or use the arrow keys.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { NumberField } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  NumberFieldDecrement,
  NumberFieldGroup,
  NumberFieldIncrement,
  NumberFieldInput,
  NumberFieldRoot
} from "#ui/number-field"

const NumberFieldBasicMessage = UiSchema.TaggedEnum({
  UpdatedNumberField: { value: Schema.NullOr(Schema.Number) }
})

export const NumberFieldBasic = Html.component({
  name: "NumberFieldBasic",
  model: Schema.Struct({ quantity: Schema.NullOr(Schema.Number) }),
  message: NumberFieldBasicMessage
}).make({
  init: () => ({ quantity: 3 }),
  update: {
    UpdatedNumberField: ($, { value }) => $.evolve({ quantity: value })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      NumberField(h, {
        props: { value: model.quantity, name: "quantity" },
        onEmit: {
          Updated: ({ value }) => NumberFieldBasicMessage.UpdatedNumberField({ value }),
          Committed: () => undefined
        },
        view: (numberField) =>
          NumberFieldRoot(h, numberField).children(
            NumberFieldGroup(h, numberField).children(
              NumberFieldDecrement(h, numberField),
              NumberFieldInput(h, numberField).attr("aria-label", "Quantity"),
              NumberFieldIncrement(h, numberField)
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(
        model.quantity === null ? "The field is empty" : `In the Model: ${model.quantity}`
      )
    )
})
```

## Examples

### Min, max and step

Typed values and steps stay within the range, and a button at its bound is disabled.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { NumberField } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  NumberFieldDecrement,
  NumberFieldGroup,
  NumberFieldIncrement,
  NumberFieldInput,
  NumberFieldLabel,
  NumberFieldRoot
} from "#ui/number-field"

const NumberFieldRangeMessage = UiSchema.TaggedEnum({
  UpdatedNumberField: { value: Schema.NullOr(Schema.Number) }
})

export const NumberFieldRange = Html.component({
  name: "NumberFieldRange",
  model: Schema.Struct({ guests: Schema.NullOr(Schema.Number) }),
  message: NumberFieldRangeMessage
}).make({
  init: () => ({ guests: 2 }),
  update: {
    UpdatedNumberField: ($, { value }) => $.evolve({ guests: value })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      NumberField(h, {
        props: { value: model.guests, min: 1, max: 8, step: 1, largeStep: 4, name: "guests" },
        onEmit: {
          Updated: ({ value }) => NumberFieldRangeMessage.UpdatedNumberField({ value }),
          Committed: () => undefined
        },
        view: (numberField) =>
          NumberFieldRoot(h, numberField).children(
            NumberFieldLabel(h, numberField).attr("for", "number-field-guests").children("Guests"),
            NumberFieldGroup(h, numberField).children(
              NumberFieldDecrement(h, numberField),
              NumberFieldInput(h, numberField, { element: h.input.attr("id", "number-field-guests") }),
              NumberFieldIncrement(h, numberField)
            )
          )
      }),
      h.p.class("max-w-70 text-center text-xs text-muted-foreground").children(
        "1 to 8. Home and End jump to the bounds, and Shift with an arrow moves by 4."
      )
    )
})
```

### Currency, percent and unit

The format prop takes the options of Intl.NumberFormat, and the value stays a plain number.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { NumberField } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  NumberFieldDecrement,
  NumberFieldGroup,
  NumberFieldIncrement,
  NumberFieldInput,
  NumberFieldLabel,
  NumberFieldRoot
} from "#ui/number-field"

const names = ["price", "discount", "weight"] as const

const NumberFieldFormatMessage = UiSchema.TaggedEnum({
  UpdatedNumberField: { name: Schema.Literals(names), value: Schema.NullOr(Schema.Number) }
})

const fields = {
  price: {
    label: "Price",
    props: { min: 0, step: 1, smallStep: 0.01, format: { style: "currency", currency: "EUR" } }
  },
  discount: {
    label: "Discount",
    props: { min: 0, max: 1, step: 0.01, largeStep: 0.1, format: { style: "percent" } }
  },
  weight: {
    label: "Weight",
    props: { min: 0, step: 0.5, format: { style: "unit", unit: "kilogram", maximumFractionDigits: 1 } }
  }
} as const

export const NumberFieldFormat = Html.component({
  name: "NumberFieldFormat",
  model: Schema.Struct({
    price: Schema.NullOr(Schema.Number),
    discount: Schema.NullOr(Schema.Number),
    weight: Schema.NullOr(Schema.Number)
  }),
  message: NumberFieldFormatMessage
}).make({
  init: () => ({ price: 1249.5, discount: 0.15, weight: 2.5 }),
  update: {
    UpdatedNumberField: ($, { name, value }) => $.evolve({ [name]: value })
  },
  view: (h, model) =>
    h.div.class("flex flex-wrap items-start justify-center gap-5").children(
      names.map((name) =>
        NumberField(h, {
          key: name,
          // The locale is fixed so the server and the browser write the number the same way.
          props: { ...fields[name].props, value: model[name], name, locale: "en-IE" },
          onEmit: {
            Updated: ({ value }) => NumberFieldFormatMessage.UpdatedNumberField({ name, value }),
            Committed: () => undefined
          },
          view: (numberField) =>
            NumberFieldRoot(h, numberField).children(
              NumberFieldLabel(h, numberField).attr("for", `number-field-${name}`).children(
                fields[name].label
              ),
              NumberFieldGroup(h, numberField).children(
                NumberFieldDecrement(h, numberField),
                NumberFieldInput(h, numberField, { element: h.input.attr("id", `number-field-${name}`) }),
                NumberFieldIncrement(h, numberField)
              ),
              h.span.class("text-xs text-muted-foreground tabular-nums").children(`value: ${model[name] ?? "null"}`)
            )
        })
      )
    )
})
```

### Scrub area

A label that changes the value when it is dragged across.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { NumberField } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  NumberFieldDecrement,
  NumberFieldGroup,
  NumberFieldIncrement,
  NumberFieldInput,
  NumberFieldLabel,
  NumberFieldRoot,
  NumberFieldScrubArea,
  NumberFieldScrubAreaCursor,
  NumberFieldScrubIcon
} from "#ui/number-field"

const NumberFieldScrubMessage = UiSchema.TaggedEnum({
  UpdatedNumberField: { value: Schema.NullOr(Schema.Number) }
})

export const NumberFieldScrub = Html.component({
  name: "NumberFieldScrub",
  model: Schema.Struct({ rotation: Schema.NullOr(Schema.Number) }),
  message: NumberFieldScrubMessage
}).make({
  init: () => ({ rotation: 45 }),
  update: {
    UpdatedNumberField: ($, { value }) => $.evolve({ rotation: value })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      NumberField(h, {
        props: {
          value: model.rotation,
          min: -180,
          max: 180,
          allowWheelScrub: true,
          format: { style: "unit", unit: "degree" },
          locale: "en-US",
          name: "rotation"
        },
        onEmit: {
          Updated: ({ value }) => NumberFieldScrubMessage.UpdatedNumberField({ value }),
          Committed: () => undefined
        },
        view: (numberField) =>
          NumberFieldRoot(h, numberField).children(
            NumberFieldScrubArea(h, numberField).children(
              NumberFieldLabel(h, numberField).attr("for", "number-field-rotation").children("Rotation"),
              NumberFieldScrubIcon(h),
              // Drawn only while a drag holds the pointer lock, in place of the hidden pointer.
              NumberFieldScrubAreaCursor(h, numberField)
            ),
            NumberFieldGroup(h, numberField).children(
              NumberFieldDecrement(h, numberField),
              NumberFieldInput(h, numberField, { element: h.input.attr("id", "number-field-rotation") }),
              NumberFieldIncrement(h, numberField)
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground").children(
        "Drag across the label, or turn the wheel over the focused input."
      )
    )
})
```

### Stacked steppers in a field

Both buttons in a column, inside a Field that reports an empty value.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Field, NumberField } from "@effect/ui-kit"
import { Schema } from "effect"
import { FieldDescription, FieldError, FieldLabel } from "#ui/field"
import { NumberFieldGroup, NumberFieldInput, NumberFieldRoot, NumberFieldSteppers } from "#ui/number-field"

const NumberFieldStackedMessage = UiSchema.TaggedEnum({
  UpdatedNumberField: { value: Schema.NullOr(Schema.Number) }
})

export const NumberFieldStacked = Html.component({
  name: "NumberFieldStacked",
  model: Schema.Struct({ seats: Schema.NullOr(Schema.Number) }),
  message: NumberFieldStackedMessage
}).make({
  init: () => ({ seats: 5 }),
  update: {
    UpdatedNumberField: ($, { value }) => $.evolve({ seats: value })
  },
  view: (h, model) =>
    Field(h, {
      props: { described: true, invalid: model.seats === null },
      view: (field) =>
        NumberField(h, {
          props: { value: model.seats, min: 1, max: 50, required: true, name: "seats", disabled: field.disabled },
          onEmit: {
            Updated: ({ value }) => NumberFieldStackedMessage.UpdatedNumberField({ value }),
            Committed: () => undefined
          },
          view: (numberField) =>
            NumberFieldRoot(h, numberField, { element: field.root(h.div) }).children(
              FieldLabel(h, field).children("Seats"),
              NumberFieldGroup(h, numberField, { variant: "stacked" }).children(
                NumberFieldInput(h, numberField, { element: field.control(h.input) }),
                NumberFieldSteppers(h, numberField)
              ),
              FieldDescription(h, field).children(
                model.seats === null ? "" : `$${model.seats * 12} per month`
              ),
              FieldError(h, field)?.children("Enter how many seats you need")
            )
        })
    })
})
```

### Disabled and read-only

A read-only field keeps focus and selection, and changes nothing.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { NumberField } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  NumberFieldDecrement,
  NumberFieldGroup,
  NumberFieldIncrement,
  NumberFieldInput,
  NumberFieldLabel,
  NumberFieldRoot
} from "#ui/number-field"

const NumberFieldStatesMessage = UiSchema.TaggedEnum({
  UpdatedNumberField: { value: Schema.NullOr(Schema.Number) }
})

const states = [
  { key: "disabled", label: "Disabled", props: { disabled: true } },
  { key: "readonly", label: "Read-only", props: { readOnly: true } }
] as const

export const NumberFieldStates = Html.component({
  name: "NumberFieldStates",
  model: Schema.Struct({ value: Schema.NullOr(Schema.Number) }),
  message: NumberFieldStatesMessage
}).make({
  init: () => ({ value: 12 }),
  update: {
    UpdatedNumberField: ($, { value }) => $.evolve({ value })
  },
  view: (h, model) =>
    h.div.class("flex flex-wrap items-center justify-center gap-5").children(
      states.map(({ key, label, props }) =>
        NumberField(h, {
          key,
          props: { ...props, value: model.value },
          onEmit: {
            Updated: ({ value }) => NumberFieldStatesMessage.UpdatedNumberField({ value }),
            Committed: () => undefined
          },
          view: (numberField) =>
            NumberFieldRoot(h, numberField).children(
              NumberFieldLabel(h, numberField).attr("for", `number-field-${key}`).children(label),
              NumberFieldGroup(h, numberField).children(
                NumberFieldDecrement(h, numberField),
                NumberFieldInput(h, numberField, { element: h.input.attr("id", `number-field-${key}`) }),
                NumberFieldIncrement(h, numberField)
              )
            )
        })
      )
    )
})
```

## Anatomy

The parts the `view` closure receives. Apply each one to an element of your own.

| Part | Description |
| --- | --- |
| `root` | Any element around every other part. Adds the hidden input that holds the form value. |
| `group` | Any element, role="group", around the input and the buttons. |
| `input` | The <input> that shows the formatted text. |
| `decrement / increment` | decrement({ element, disabled }): a <button> that steps once, and repeats while held. |
| `scrubArea` | scrubArea({ element, direction, pixelSensitivity }): any element, dragged across to change the value. |
| `scrubAreaCursor` | Any element inside the scrub area. Returns undefined unless a drag holds the pointer lock. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `value` | `number \| null` | The number, or null for an empty field. |
| `min / max` | `number` | The range. Typed values and steps are kept within it. |
| `step` | `number \| "any"` | What an arrow key, a button, the wheel and a dragged pixel change the value by. 1 by default. |
| `smallStep / largeStep` | `number` | The step while Alt or Shift is held. 0.1 and 10 by default. |
| `format` | `Intl.NumberFormatOptions` | How the number is written and read, such as { style: "currency", currency: "EUR" }. |
| `locale` | `string \| string[]` | The locale to format and parse with. Pass it when rendering on a server. |
| `allowWheelScrub` | `boolean` | The wheel over the focused input steps the value. |
| `allowOutOfRange` | `boolean` | A typed value may be outside min and max, for your own validation to report. |
| `disabled / readOnly / required` | `boolean` | The state of the field. |
| `name` | `string` | The name the hidden input submits the plain number under. |

### Events

| Event | Description |
| --- | --- |
| `Updated` | { value, reason, direction? }: each value the user asks for, while typing and for each step. |
| `Committed` | { value, reason }: the value once the user is done: on blur, after a key, and when a button or a drag is released. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-disabled` | On every part. On a button, also while the value is at that button's bound. |
| `data-readonly` | The field is read-only. |
| `data-required` | The field is required. |
| `data-scrubbing` | A drag on a scrub area is under way. |

## Related components

- [Field](https://www.effectcn.com/components/field.md): Groups a control with its label, description and error, and reports whether it is invalid, touched or focused on each of them.
