NumberField unstable
A controlled input for a number, with stepper buttons and an area to drag
across. Pass the current value as value, a number or null for an
empty field, and store the one Updated carries. Your view supplies the
markup; the component formats and parses the text for a locale, steps the
value from the keyboard, the buttons, the wheel and a drag, and adds the
ARIA and data attributes. It is a headless component, because it keeps the
text being typed and the press or drag under way.
Anatomy
| Part | Element |
|---|---|
root |
any element that can contain an <input>, around every other part |
group |
any element, role="group", around the input and the buttons |
input |
<input>, the text field |
decrement |
<button> |
increment |
<button> |
scrubArea |
any element, dragged across to change the value |
scrubAreaCursor |
any element inside the scrub area, shown during a drag |
root, group, input and scrubAreaCursor each take the consumer's
builder and return it, so the consumer goes on chaining and adds children
with .children(...). The others take an options object and return its
element:
decrement({ element, disabled })andincrement({ element, disabled }):disabledmakes that one button unavailable.scrubArea({ element, direction, pixelSensitivity, teleportDistance }):directionis"horizontal"by default, or"vertical".pixelSensitivity,2by default, is how many pixels the pointer moves before the value changes.teleportDistanceis how far the cursor goes from the scrub area before it comes back in on the other side. Without it the cursor wraps at the edges of the viewport.
root adds a visually hidden <input type="number"> after the
children you chain, which holds the form value. scrubAreaCursor returns
undefined unless a drag holds the pointer lock, so write
numberField.scrubAreaCursor(h.span)?.children(icon).
The parts also return value, inputValue, the text the input shows,
disabled, readOnly, required and scrubbing, for markup that
depends on them.
The kit sets no look. A button and the scrub area get user-select: none
and the scrub area touch-action: none. The cursor is a popover, so it
sits in the top layer, and it gets position: fixed, its inset,
margin: 0, pointer-events: none and the transform that moves it.
A browser also gives a popover a border, padding, a background and
overflow: auto, so reset those on the cursor.
Naming
Name the input with a <label for>, an aria-label, or a Field: draw
it with numberField.input(field.control(h.input)) and pass
disabled: field.disabled. The input keeps the id its builder has, the
field's or your own, and gets a generated one otherwise. Each button
points at it with aria-controls. The buttons default to aria-label
"Decrease" and "Increase"; set aria-label on each builder to override
or localize them.
Data attributes
On every part, each present with an empty value or absent:
data-disabled: on a button, also while the value is at that button's bound or the button hasdisableddata-readonlydata-requireddata-scrubbing: a drag on a scrub area is under way
A Field's data attributes, such as data-invalid and data-touched, go
on its own parts and on the input field.control decorates.
Keyboard
On the input:
- ArrowUp and ArrowDown add
stepand take it away - Shift with an arrow moves by
largeStep, and Alt bysmallStep - Home and End go to
minandmax, when they are set
Only the characters the locale and the format can show may be typed: its
digits, separators, signs, and the currency or unit. A second sign or
decimal separator is refused unless the selection replaces the first.
Digits of the Arabic-Indic, Persian, fullwidth and Han systems are read
too, and so are a typed percent or permille sign. Pasted text goes in at
the caret without the characters that may not be typed, and is dropped
unless the text then reads as a number. The buttons have
tabindex="-1", as the arrows do their job from the input.
The input's keydown handler cancels the default of the stepping keys
and of a character that may not be typed, so the input gets every
keydown while it has focus, and an ancestor's keydown handler never
sees them. To handle them, add a keydown handler to the input's
builder.
Pointer
A press on a button steps once, and holding it repeats the step after 400 ms, every 60 ms, until the release or the bound. A mouse press also moves focus to the input. A tap steps once, and a touch that scrolls the page steps nothing.
A drag across a scrub area steps the value by the pixels moved times the
step, with Shift and Alt as on the keyboard. A mouse or pen drag asks for
the pointer lock, so it can go on past the edge of the screen, and
scrubAreaCursor stands in for the pointer the lock hides. The browser
may show a notice for the lock. Touch, WebKit and a refused lock drag
without it, and then no cursor is drawn.
With allowWheelScrub, the wheel over the focused input steps the value.
Events
Updated reports each value the user asks for: while typing, once the
text reads as a number, and for each step. Committed reports the value
once the user is done: when the input loses focus, after each key and
wheel turn, and when a button or a drag is released. Both carry a
reason. To refuse a change, don't store it: the typed text stays until
the input loses focus, and then it shows the stored value again.
While typing, the input shows the text as typed, and the value is kept
within min and max unless allowOutOfRange is set. When the input
loses focus it shows the value, formatted. Text that doesn't read as a
number is dropped then.
Forms
The hidden input submits the value as a plain number under name, to
the form around the root or the one form names. It carries min, max,
step and required, so the browser refuses to submit a value outside
the range, or off the step, that allowOutOfRange or the consumer let in.
Pass step: "any" to submit any fraction. A disabled field submits
nothing.
The server formats with its own default locale, which may differ from the
browser's. Pass locale when the field is rendered on a server.
Example A price in euros whose value lives in the consumer's Model
import { UiSchema } from "effect/ui"import { Html, HtmlServer } from "effect/ui/html"import { Field, NumberField } from "effect/ui/kit"import { Effect, Schema } from "effect"
const CartMessage = UiSchema.TaggedEnum({ UpdatedPrice: { value: Schema.NullOr(Schema.Number) } })
const Cart = Html.component({ name: "Cart", model: Schema.Struct({ price: Schema.NullOr(Schema.Number) }), message: CartMessage}).make({ init: () => ({ price: 1234.5 }), update: { UpdatedPrice: ($, { value }) => $.evolve({ price: value }) }, view: (h, model) => Field(h, { view: (field) => NumberField(h, { props: { value: model.price, min: 0, name: "price", locale: "de-DE", format: { style: "currency", currency: "EUR" }, disabled: field.disabled }, onEmit: { Updated: ({ value }) => CartMessage.UpdatedPrice({ value }), Committed: () => undefined }, view: (numberField) => numberField.root(field.root(h.div)).children( numberField.scrubArea({ element: h.span }).children( field.label(h.label).children("Price"), numberField.scrubAreaCursor(h.span)?.children("โ") ), numberField.group(h.div).children( numberField.decrement({ element: h.button }).children("-"), numberField.input(field.control(h.input.class("amount"))), numberField.increment({ element: h.button }).children("+") ) ) }) })})
// The input shows the price as the locale writes it, and the hidden input holds the number.const { html } = await Effect.runPromise(HtmlServer.renderToHtml(Cart, {}))const input = /<input class="amount" id="([^"]+)"[^>]*>/.exec(html)if (input === null || !html.includes('<label for="' + input[1] + '"')) throw new Error("the input isn't labelled")if (!/value="1\.234,50\sโฌ"/.test(input[0])) throw new Error("the input doesn't show the formatted price")if (!/<input[^>]*type="number"[^>]*name="price"[^>]*value="1234.5"/.test(html)) throw new Error("no form value")Components
NumberField
unstableA headless number field. Call it with the consumer's h, the props, and
a view closure that draws the root and, inside it, the input and the
parts it needs of the group, the buttons and the scrub area.
Details
The parts also return value, inputValue, disabled, readOnly,
required and scrubbing, for markup that depends on them.
The field's own attributes win over the ones the consumer set on the builder before the part, including the ones a state leaves absent:
- every part: the data attributes
group:roleinput:id,type,inputmode,form,required,readonly,disabledandvaluedecrementandincrement:type,tabindex,aria-controls,aria-disabled, anddisabled, which they remove: an unavailable button stays focusable, so a press that reaches the bound isn't lostscrubArea:rolescrubAreaCursor:id,aria-hiddenandpopover
The styles the buttons, the scrub area and the cursor need are added to
the consumer's style, after it. The input's autocomplete,
autocorrect and spellcheck, and a button's aria-label, are
written only when the builder has none.
The input handles input, blur and keydown on a layer of its own, so
the consumer's handlers for them, and a Field's, still run.
History restore saves nothing of it: after Back, forward or a reload it
starts from init.
Signature
declare const NumberField: Headless<{ readonly allowOutOfRange?: boolean; readonly allowWheelScrub?: boolean; readonly disabled?: boolean; readonly form?: string; readonly format?: { readonly compactDisplay?: "short" | "long"; readonly currency?: string; readonly currencyDisplay?: "symbol" | "name" | "code" | "narrowSymbol"; readonly currencySign?: "standard" | "accounting"; readonly localeMatcher?: "lookup" | "best fit"; readonly maximumFractionDigits?: number; readonly maximumSignificantDigits?: number; readonly minimumFractionDigits?: number; readonly minimumIntegerDigits?: number; readonly minimumSignificantDigits?: number; readonly notation?: "standard" | "scientific" | "engineering" | "compact"; readonly numberingSystem?: string; readonly roundingIncrement?: number; readonly roundingMode?: "ceil" | "floor" | "expand" | "trunc" | "halfCeil" | "halfFloor" | "halfExpand" | "halfTrunc" | "halfEven"; readonly roundingPriority?: "auto" | "morePrecision" | "lessPrecision"; readonly signDisplay?: "auto" | "always" | "never" | "exceptZero" | "negative"; readonly style?: "decimal" | "percent" | "currency" | "unit"; readonly trailingZeroDisplay?: "auto" | "stripIfInteger"; readonly unit?: string; readonly unitDisplay?: "short" | "long" | "narrow"; readonly useGrouping?: boolean | "true" | "false" | "auto" | "always" | "min2"; }; readonly largeStep?: number; readonly locale?: string | readonly Array<string>; readonly max?: number; readonly min?: number; readonly name?: string; readonly readOnly?: boolean; readonly required?: boolean; readonly smallStep?: number; readonly snapOnStep?: boolean; readonly step?: number | "any"; readonly value: number | null;}, { readonly _tag: "Committed"; readonly reason: "keyboard" | "input-clear" | "wheel" | "input-blur" | "increment-press" | "decrement-press" | "scrub"; readonly value: number | null;} | { readonly _tag: "Updated"; readonly direction?: 1 | -1; readonly reason: "none" | "keyboard" | "input-change" | "input-clear" | "wheel" | "input-paste" | "input-blur" | "increment-press" | "decrement-press" | "scrub"; readonly value: number | null;}, { decrement: <B extends PartTarget<"button">>(__namedParameters: { readonly disabled?: boolean; readonly element: B; }) => ReturnType<B["attr"]> & Pick<Part<"button", [direction: -1 | 1, own: boolean], never>, "~R">; disabled: boolean; group: Part<string, [], never>; increment: <B extends PartTarget<"button">>(__namedParameters: { readonly disabled?: boolean; readonly element: B; }) => ReturnType<B["attr"]> & Pick<Part<"button", [direction: -1 | 1, own: boolean], never>, "~R">; input: <B extends PartTarget<"input">>(element: B) => ReturnType<B["attr"]> & Pick<Part<"input", [id: string], never>, "~R">; inputValue: string; readOnly: boolean; required: boolean; root: Part<string, [], never>; scrubArea: <B extends PartTarget<string>>(__namedParameters: { readonly direction?: "horizontal" | "vertical"; readonly element: B; readonly pixelSensitivity?: number; readonly teleportDistance?: number; }) => ReturnType<B["attr"]> & Pick<Part<string, [vertical: boolean, pixelSensitivity: number, teleportDistance: number], never>, "~R">; scrubAreaCursor: <B extends PartTarget<string>>(element: B) => ReturnType<B["attr"]> | undefined & Pick<Part<string, [], never>, "~R">; scrubbing: boolean; value: number | null;}, never, never, never, never, never, never, { readonly cursor: boolean; readonly focus: number; readonly ios: boolean; readonly pending: boolean; readonly scrubbing: boolean; readonly text: string | null;}, { readonly _tag: "FocusedFormInput";} | { readonly _tag: "BlurredInput"; readonly disabled: boolean;} | { readonly _tag: "Autofilled"; readonly value: string;} | { readonly _tag: "PressedKey"; readonly alt: boolean; readonly key: string; readonly shift: boolean;} | { readonly _tag: "UpdatedInput"; readonly value: string;} | { readonly _tag: "PastedText"; readonly value: string;} | { readonly _tag: "TurnedWheel"; readonly alt: boolean; readonly direction: -1 | 1; readonly shift: boolean;} | { readonly _tag: "DetectedIOS";} | { readonly _tag: "PressedStepper"; readonly alt: boolean; readonly direction: -1 | 1; readonly focus: boolean; readonly shift: boolean;} | { readonly _tag: "HeldStepper"; readonly alt: boolean; readonly direction: -1 | 1; readonly shift: boolean;} | { readonly _tag: "ReleasedStepper"; readonly direction: -1 | 1;} | { readonly _tag: "ClickedStepper"; readonly alt: boolean; readonly direction: -1 | 1; readonly shift: boolean;} | { readonly _tag: "StartedScrub"; readonly focus: boolean;} | { readonly _tag: "ChangedPointerLock"; readonly locked: boolean;} | { readonly _tag: "MovedScrub"; readonly alt: boolean; readonly amount: number; readonly shift: boolean;} | { readonly _tag: "EndedScrub"; readonly commit: boolean;}, QueryEntries<{}, {}>>Models
Why a NumberField asks to change its value.
Signature
type NumberFieldChangeReason = typeof NumberFieldChangeReason.TypeWhat ended the change a NumberField commits.
Signature
type NumberFieldCommitReason = typeof NumberFieldCommitReason.TypeWhat a NumberField emits.
Signature
type NumberFieldEvents = typeof NumberFieldEvents.TypeHow a NumberField writes its number.
Signature
type NumberFieldFormat = typeof NumberFieldFormat.TypeThe props of a NumberField.
Signature
type NumberFieldProps = typeof NumberFieldProps.TypeSchemas
NumberFieldChangeReason
unstableWhy a NumberField asks to change its value.
Details
"input-change": the text was typed into"input-clear": the text was emptied"input-paste": text was pasted"input-blur": the input lost focus, and the value was rounded to the format or brought within the range"keyboard": an arrow key, Home or End"increment-press"and"decrement-press": a button"wheel": the wheel over the input"scrub": a drag across a scrub area"none": the browser filled the form value in
Signature
declare const NumberFieldChangeReason: Literals<readonly ["input-change", "input-clear", "input-paste", "input-blur", "keyboard", "increment-press", "decrement-press", "wheel", "scrub", "none"]>NumberFieldCommitReason
unstableWhat ended the change a NumberField commits: the input losing focus
with a value or without one, a key, the release of a button, a wheel
turn, or the release of a drag.
Signature
declare const NumberFieldCommitReason: Literals<readonly ["input-blur", "input-clear", "keyboard", "increment-press", "decrement-press", "wheel", "scrub"]>NumberFieldEvents
unstableWhat a NumberField emits.
Details
Updated: asks forvalueto bevalue. A step also carries itsdirection,1up or-1down.Committed: reports that the user is done changing the value, andvalueis the one they left.
Signature
declare const NumberFieldEvents: TaggedEnum<{ Committed: TaggedStruct<"Committed", { readonly reason: Literals<readonly ["input-blur", "input-clear", "keyboard", "increment-press", "decrement-press", "wheel", "scrub"]>; readonly value: NullOr<Number>; }>; Updated: TaggedStruct<"Updated", { readonly direction: optional<Literals<readonly [-1, 1]>>; readonly reason: Literals<readonly ["input-change", "input-clear", "input-paste", "input-blur", "keyboard", "increment-press", "decrement-press", "wheel", "scrub", "none"]>; readonly value: NullOr<Number>; }>;}>NumberFieldFormat
unstableHow a NumberField writes its number: the options of
Intl.NumberFormat, such as { style: "currency", currency: "EUR" }.
Details
The input shows the value in this format and reads what is typed by it.
notation: "compact" shows a value such as 1.2K, which can't be read
back, so its suffix can't be typed.
Signature
declare const NumberFieldFormat: Struct<{ readonly compactDisplay: optional<Literals<readonly ["short", "long"]>>; readonly currency: optional<String>; readonly currencyDisplay: optional<Literals<readonly ["code", "symbol", "narrowSymbol", "name"]>>; readonly currencySign: optional<Literals<readonly ["standard", "accounting"]>>; readonly localeMatcher: optional<Literals<readonly ["lookup", "best fit"]>>; readonly maximumFractionDigits: optional<Number>; readonly maximumSignificantDigits: optional<Number>; readonly minimumFractionDigits: optional<Number>; readonly minimumIntegerDigits: optional<Number>; readonly minimumSignificantDigits: optional<Number>; readonly notation: optional<Literals<readonly ["standard", "scientific", "engineering", "compact"]>>; readonly numberingSystem: optional<String>; readonly roundingIncrement: optional<Number>; readonly roundingMode: optional<Literals<readonly ["ceil", "floor", "expand", "trunc", "halfCeil", "halfFloor", "halfExpand", "halfTrunc", "halfEven"]>>; readonly roundingPriority: optional<Literals<readonly ["auto", "morePrecision", "lessPrecision"]>>; readonly signDisplay: optional<Literals<readonly ["auto", "never", "always", "exceptZero", "negative"]>>; readonly style: optional<Literals<readonly ["decimal", "percent", "currency", "unit"]>>; readonly trailingZeroDisplay: optional<Literals<readonly ["auto", "stripIfInteger"]>>; readonly unit: optional<String>; readonly unitDisplay: optional<Literals<readonly ["short", "long", "narrow"]>>; readonly useGrouping: optional<Union<readonly [Boolean, Literals<readonly ["always", "auto", "min2", "true", "false"]>]>>;}>NumberFieldProps
unstableProps for the number field's value, its range, its steps and its format.
Details
value: the number, ornullfor an empty field.minandmax: the range. Typed values and steps are kept within it.step: what an arrow key, a button, the wheel and a dragged pixel change the value by,1by default."any"steps by1and lets the form submit any fraction.smallStep: the step while Alt is held,0.1by default.largeStep: the step while Shift is held,10by default.snapOnStep: a step lands on a multiple of the step frommin, or from0without one.allowOutOfRange: a typed value may be outsideminandmax, for the form's own validation to report. Steps still stay within them.allowWheelScrub: the wheel over the focused input steps the value.format: the options ofIntl.NumberFormat.locale: the locale to format and parse with, the runtime's default when left out.disabled: disables the input, makes the buttons unavailable, and the field emits and submits nothing.readOnly: the value can be read and focused, not changed.required: the form needs a value.name: the name the value is submitted under.form: the id of the form that submits it, when the field isn't inside one.
Signature
declare const NumberFieldProps: Struct<{ readonly allowOutOfRange: optional<Boolean>; readonly allowWheelScrub: optional<Boolean>; readonly disabled: optional<Boolean>; readonly form: optional<String>; readonly format: optional<Struct<{ readonly compactDisplay: optional<Literals<readonly ["short", "long"]>>; readonly currency: optional<String>; readonly currencyDisplay: optional<Literals<readonly ["code", "symbol", "narrowSymbol", "name"]>>; readonly currencySign: optional<Literals<readonly ["standard", "accounting"]>>; readonly localeMatcher: optional<Literals<readonly ["lookup", "best fit"]>>; readonly maximumFractionDigits: optional<Number>; readonly maximumSignificantDigits: optional<Number>; readonly minimumFractionDigits: optional<Number>; readonly minimumIntegerDigits: optional<Number>; readonly minimumSignificantDigits: optional<Number>; readonly notation: optional<Literals<readonly ["standard", "scientific", "engineering", "compact"]>>; readonly numberingSystem: optional<String>; readonly roundingIncrement: optional<Number>; readonly roundingMode: optional<Literals<readonly ["ceil", "floor", "expand", "trunc", "halfCeil", "halfFloor", "halfExpand", "halfTrunc", "halfEven"]>>; readonly roundingPriority: optional<Literals<readonly ["auto", "morePrecision", "lessPrecision"]>>; readonly signDisplay: optional<Literals<readonly ["auto", "never", "always", "exceptZero", "negative"]>>; readonly style: optional<Literals<readonly ["decimal", "percent", "currency", "unit"]>>; readonly trailingZeroDisplay: optional<Literals<readonly ["auto", "stripIfInteger"]>>; readonly unit: optional<String>; readonly unitDisplay: optional<Literals<readonly ["short", "long", "narrow"]>>; readonly useGrouping: optional<Union<readonly [Boolean, Literals<readonly ["always", "auto", "min2", "true", "false"]>]>>; }>>; readonly largeStep: optional<Number>; readonly locale: optional<Union<readonly [String, $Array<String>]>>; readonly max: optional<Number>; readonly min: optional<Number>; readonly name: optional<String>; readonly readOnly: optional<Boolean>; readonly required: optional<Boolean>; readonly smallStep: optional<Number>; readonly snapOnStep: optional<Boolean>; readonly step: optional<Union<readonly [Number, Literal<"any">]>>; readonly value: NullOr<Number>;}>