---
title: "数字字段"
description: "让用户把数字当作数字来输入——按所在区域设置的写法键入，或者用按键或按钮步进；数字被限制在范围之内，单位就在旁边——它是表单中一个完整的字段，由一个字段和一个数字输入框组成。"
url: "https://tanrei.chnotchy.com/zh-cn/components/number-field/"
last_updated: 2026-10-23T21:17:12.000Z
---

# 数字字段

> 让用户把数字当作数字来输入——按所在区域设置的写法键入，或者用按键或按钮步进；数字被限制在范围之内，单位就在旁边——它是表单中一个完整的字段，由一个字段和一个数字输入框组成。

## 概览

当产品要把一个数字当作数字来读取时，使用数字字段：数量、尺寸、百分比、金额。用户按所在区域设置的写法键入它，或者用方向键、字段末尾的两个按钮来步进。这个字段的绘制方式和尺寸，与相同变体、相同尺寸的文本字段一致。

**组成部分**是一个[字段](https://tanrei.chnotchy.com/zh-cn/components/field/)和一个[数字输入框](https://tanrei.chnotchy.com/zh-cn/components/number-input/)。字段是框架：标签、必填或选填标记、帮助文本和错误。数字输入框是控件：方框、数字、它的单位和两个步进按钮。数字字段自己什么都不绘制，也没有令牌：它的每个属性都是这两者之一的属性，原样交给它们。

数字字段已经是一个字段：它绝不放进[字段](https://tanrei.chnotchy.com/zh-cn/components/field/)里。标签在别处的地方——滑块旁边、表格的单元格里——单独使用[数字输入框](https://tanrei.chnotchy.com/zh-cn/components/number-input/)。

它是一个块，放在哪里就和那里一样宽，它的方框会把它填满。它没有自己的宽度：想要窄一些的字段，就把它放进窄一些的地方。

在 Web 上它是 `<tanrei-number-field>`。其他平台尚未实现。

### 用法

`value` 是一个数字；字段里没有数字时是 `null`。它在用户**确认**时改变——焦点离开字段、按下 Enter，或者步进——而不是每按一次键就改变。用户键入期间，文本归用户所有：不拒绝任何内容，不改写格式，不限制到范围之内，也不取整。这期间文本读作什么数字，由 `input` 带出。

**Web**

```html
<form>
  <tanrei-number-field name="quantity" label="数量" value="1" min="1" max="99"
    required required-text="必填" invalid-text="请输入数字。" increment-label="增加" decrement-label="减少"></tanrei-number-field>
</form>

<!-- 带单位，步长为 0.25，没有上限。 -->
<tanrei-number-field id="radius" label="圆角半径" value="8" min="0" step="0.25" suffix-text="px" increment-label="增加" decrement-label="减少"></tanrei-number-field>

<!-- 金额：前面是符号，后面是代码，始终保留两位小数。 -->
<tanrei-number-field label="金额" value="120" prefix-text="$" suffix-text="USD"
  min-fraction-digits="2" max-fraction-digits="2" increment-label="增加" decrement-label="减少"></tanrei-number-field>

<script type="module">
  import '@tanrei/web/components/number-field';

  const radius = document.querySelector('#radius');
  // 一次确认改变了值。value 已经是新的值：一个数字，或者 null。
  radius.addEventListener('change', () => save(radius.value));
  // 用户正在键入或步进：文本读作的数字，没有限制到范围之内，也没有取整；不是数字时为 null。
  radius.addEventListener('input', (e) => preview(e.detail.value));
  // 确认了一段不是数字的文本。字段保留这段文本，并显示 invalidText：
  // detail.text 就是这段文字，没有给字段提供时为空。
  radius.addEventListener('entryerror', (e) => console.log(e.detail.reason, e.detail.text));
</script>
```

**React**

```tsx
import { NumberField } from '@tanrei/react';

<NumberField label="圆角半径" value={radius} min={0} step={0.25} suffixText="px"
  incrementLabel="增加" decrementLabel="减少"
  onChange={(event) => setRadius(event.currentTarget.value)} />
```

### 下一层

用它的两个成员手写出来的同一个字段，画面是一样的，对辅助技术来说也是同一个微调按钮（spin button），名称、描述和状态都相同：

```html
<tanrei-field label="数量" required required-text="必填"
  supporting-text="每笔订单最多 99 件。">
  <tanrei-number-input name="quantity" min="1" max="99" invalid-text="请输入数字。"
    increment-label="增加" decrement-label="减少"></tanrei-number-input>
</tanrei-field>
```

需要数字字段没有提供的排布方式时，就往下走一层：

| 你需要 | 使用 |
| --- | --- |
| 标签、方框、帮助文本和错误 | 数字字段 |
| 在框架里面、方框的旁边或下方放你自己的东西 | 一个[字段](https://tanrei.chnotchy.com/zh-cn/components/field/)，里面放一个[数字输入框](https://tanrei.chnotchy.com/zh-cn/components/number-input/)和你自己的元素 |
| 只要方框，放在位于别处的标签之下：滑块旁边、表格的单元格、工具栏 | 单独的[数字输入框](https://tanrei.chnotchy.com/zh-cn/components/number-input/)，由它自己的 `label` 命名 |

到了下一层，变的是各样东西写在哪里。`name`、`value`、范围和单位写在数字输入框上，这时它就是表单遇到的那个控件，它的事件也在它上面监听。`label`、`error`、`disabled` 和必填与否仍然写在字段上，由字段传给控件：不要设置输入框自己的那几个。数字字段做的事，没有一件是手写的字段和数字输入框做不到的。

## 规格

### 字段

| 部件 | 它是什么 |
| --- | --- |
| 标签 | 属于字段：位于容器上方（`stacked`）。在 `filled` 和 `outlined` 中由数字输入框绘制，浮在方框里面，字段不绘制标签行。它就是无障碍名称，无论它是画出来的，还是用 `labelHidden` 隐藏的 |
| 必填和选填标记 | 属于字段，位于标签之后：`required` 时是“必填”小标签、星号，或者什么都不画；`optional` 时是“选填”小标签。浮动标签带的是星号 |
| 输入框 | 属于数字输入框：以文本形式呈现的数字。编辑期间是用户键入的内容；其余时候是已确认的数字，按区域设置的写法显示。只有一行，放不下时滚动 |
| 前缀、后缀 | 属于数字输入框：数字前后的固定文本，例如货币符号或单位。它们属于方框，绝不属于值 |
| 步进按钮 | 属于数字输入框：末尾的两个按钮，第一个减小，第二个增大。把 `steppers` 设为 false 就不绘制它们 |
| 辅助文本 | 属于字段：一行帮助文本。字段处于错误状态时，错误文本取代它的位置（设计系统两者都保留时，绘制在它的下方）：`error` 为 true 时是 `errorText`，文本不是数字时是 `invalidText`。无论有没有步进按钮，它都从方框的文本内边距处开始，到那里结束 |

三种变体，以及 `small`（32）、`medium`（40）和 `large`（56）三种尺寸，都是文本字段的。默认系统只提供 `stacked`。

数字字段没有自己的令牌。它的方框读取[数字输入框的令牌](https://tanrei.chnotchy.com/zh-cn/components/number-input/#%E8%A7%84%E6%A0%BC)，它的各行读取[字段的令牌](https://tanrei.chnotchy.com/zh-cn/components/field/#%E8%A7%84%E6%A0%BC)，两个步进按钮读取[按钮的令牌](https://tanrei.chnotchy.com/zh-cn/components/button/#%E8%A7%84%E6%A0%BC)，无论这些令牌设置在哪里。要改动某一个实例，就在它上面设置成员的令牌：`style="--tanrei-comp-field-label-gap: 0.75rem"`。

两个步进按钮是并排的 medium 尺寸 text 按钮。在默认系统下，它们占去字段宽度中的 88，每一个都是完整的触摸目标。它们绝不会画得更小，也绝不上下叠放：一行里容不下它们时，就把它们关掉。按键仍然可以步进。

### 值和文本

| 何时 | 发生什么 |
| --- | --- |
| 用户键入、粘贴或听写 | 什么都不改。`input` 带出文本读作的数字，或者 `null` |
| 焦点离开，或者按下 Enter | 文本被确认：低于 `min` 时提高到 `min`，高于 `max` 时降低到 `max`，按 `maxFractionDigits` 取整，成为值，并按区域设置的写法写回。值有变化时触发 `change` |
| 文本为空 | 值变为 `null` |
| 文本不是数字 | 文本保留。值变为 `null`，字段进入错误状态并显示 `invalidText`——没有 `invalidText` 时显示它的 `errorText`——同时触发 `entryerror` |
| 产品设置 `value` | 无论之前键入了什么，都显示这个数字。不触发任何事件，这个数字也不会按 `min` 和 `max` 修正 |

已确认的数字用区域设置的数字和小数分隔符书写，小数位数在 `minFractionDigits` 和 `maxFractionDigits` 之间，不带分组分隔符——这样显示出来的内容可以原样再键入一遍。

文本按字段的 `locale` 宽松地解读；`locale` 为空时，按页面的语言解读：

- 数字两侧和数字内部的空格会被忽略。
- 数字之前的连字符减号、减号或加号是正负号。
- ASCII 数字、区域设置自己的数字和全角数字都算数字。
- 数字之间的区域设置分组分隔符会被忽略：在英语中，`1,234.50` 读作 1234.5。
- 键入或粘贴进来的前缀和后缀会被忽略：`12 px` 读作 12。
- 字母、指数、两个分隔符，或者单独一个正负号，都不是数字。

字段绝不在两种区域设置之间猜测。在以逗号为小数分隔符的德语中，`1.500` 读作 1500，`1.5` 读作 15。

数字和它的单位是连成一体书写的。前缀写在数字之前，后缀写在数字之后，方向按单位自身所用文字的书写方向，与页面的方向无关。所以“44 px”“$ 120 USD”和“40 %”在阿拉伯语或希伯来语的页面里，读起来与在英语页面里一样；用阿拉伯字母或希伯来字母写的单位，则位于数字的左侧。步进按钮和标签跟随页面。`align="end"` 让数字紧靠它的单位：单位用拉丁字母或符号书写时，在两种方向下都靠右。要让拉丁字母的货币代码位于数字的左侧，就让后缀以一个从右到左标记（U+200F）开头。

### 步进

| 输入 | 发生什么 |
| --- | --- |
| 上方向键、下方向键 | 按 `step` 步进 |
| Page Up、Page Down | 按 `step` 的十倍步进 |
| 按下步进按钮 | 步进一次。按住不放时会重复：半秒之后开始，先是每秒十次，然后每秒二十次 |
| Home、End、左方向键、右方向键 | 在文本中移动插入点 |
| 滚轮、拖动 | 什么都不发生。页面照常滚动 |

一次步进会走到步长网格上的下一个数字，网格从 `min` 算起（没有 `min` 时从零算起）：步长为 5 时，12 向上步进到 15，向下步进到 10。它按十进制计算，所以 0.2 步进 0.1 得到 0.3。空的字段会步进到范围允许的、离零最近的数字。

`step` 说明一步走多远。它不限制可以键入什么：步长为 5 时，键入的 12 仍然是 12。只接受某些数字时，请校验值并设置 `error`。

### 与滑块搭配

放在滑块旁边、与滑块共用一个行标题的数字，只要方框就够了：用[数字输入框](https://tanrei.chnotchy.com/zh-cn/components/number-input/#%E4%B8%8E%E6%BB%91%E5%9D%97%E6%90%AD%E9%85%8D)，由它自己的 `label` 命名。示例在它的页面上。

- Category: Text inputs
- Level: composed
- Listing: default
- Built from: Field, Number input
- Page: https://tanrei.chnotchy.com/components/number-field/
- Spec: https://github.com/chnotchy/tanrei/blob/main/specs/number-field.spec.json

### Availability

| Design system | Has it | Notes |
| --- | --- | --- |
| Tanrei (`tanrei`) | Yes | Variants left out: `filled`, `outlined`. |
| Cupertino (Apple HIG-inspired) (`cupertino`) | Yes | — |
| M3 Expressive-like (Material 3 Expressive-inspired) (`m3-expressive-like`) | Yes | — |
| M3-like (Material 3-inspired) (`m3-like`) | Yes | — |

### Platforms

- Web: the element `<tanrei-number-field>`, registered by importing `@tanrei/web` (or only its own module, `@tanrei/web/components/number-field`).
- React: `NumberField` from `@tanrei/react`.

| Platform | Name | Status |
| --- | --- | --- |
| Web | `tanrei-number-field` | lagging |
| SwiftUI | `TanreiNumberField` | planned |
| Jetpack Compose | `TanreiNumberField` | planned |
| Flutter | `TanreiNumberField` | planned |
| React Native | `NumberField` | planned |

Names a platform gives in its own idiom:

| Spec | Web | SwiftUI | Jetpack Compose | Flutter | React Native |
| --- | --- | --- | --- | --- | --- |
| `label` (prop) | `label` | `label` | `label` | `labelText` | `label` |
| `labelHidden` (prop) | `labelHidden` | `labelsHidden` | `labelHidden` | `labelHidden` | `labelHidden` |
| `placeholder` (prop) | `placeholder` | `prompt` | `placeholder` | `hintText` | `placeholder` |
| `supportingText` (prop) | `supportingText` | `supportingText` | `supportingText` | `helperText` | `supportingText` |
| `error` (prop) | `error` | `error` | `isError` | `isError` | `error` |
| `disabled` (prop) | `disabled` | `disabled` | `enabled` | `enabled` | `disabled` |
| `required` (prop) | `required` | `isRequired` | `required` | `required` | `required` |
| `optional` (prop) | `optional` | `isOptional` | `optional` | `optional` | `optional` |
| `min` (prop) | `min` | `in` | `min` | `min` | `min` |
| `max` (prop) | `max` | `in` | `max` | `max` | `max` |
| `steppers` (prop) | `noSteppers` | `steppers` | `steppers` | `steppers` | `steppers` |
| `incrementLabel` (prop) | `incrementLabel` | `incrementLabel` | `incrementContentDescription` | `incrementSemanticLabel` | `incrementAccessibilityLabel` |
| `decrementLabel` (prop) | `decrementLabel` | `decrementLabel` | `decrementContentDescription` | `decrementSemanticLabel` | `decrementAccessibilityLabel` |
| `prefixText` (prop) | `prefixText` | `prefix` | `prefix` | `prefixText` | `prefix` |
| `suffixText` (prop) | `suffixText` | `suffix` | `suffix` | `suffixText` | `suffix` |
| `valueText` (prop) | `valueText` | `valueText` | `stateDescription` | `semanticValue` | `valueText` |
| `input` (event) | `input` | `onInput` | `onInput` | `onInput` | `onInput` |
| `change` (event) | `change` | `value` | `onValueChange` | `onChanged` | `onValueChange` |
| `action` (event) | `action` | `onSubmit` | `keyboardActions` | `onSubmitted` | `onSubmitEditing` |
| `entryError` (event) | `entryerror` | `onEntryError` | `onEntryError` | `onEntryError` | `onEntryError` |

Statuses: `planned` — In the inventory. Nothing shippable exists yet. `lagging` — An implementation of an earlier spec exists; it has not caught up with the current one. `alpha` — Implemented with tests. The API may still change. `beta` — Feature complete and at parity. Only fixes are expected. `stable` — Covered by semantic versioning. `deprecated` — Still shipped; scheduled for removal.

### Anatomy

- `field`: The Field: the label row with its glyph and its requirement mark, and the supporting row with the help and the error text. In a look whose input floats the label it draws no label row.
- `number-input`: The number input, as the Field's one control: the box, the number in it, the prefix and the suffix, the two steppers, and the label that floats in the box in the looks that float one.

### Props

| Prop | Type | Default | Web attribute | Description |
| --- | --- | --- | --- | --- |
| `variant` | `enum`: `stacked`, `filled`, `outlined` | `"stacked"` | `variant` | The text input's three looks, so that a number input is drawn as the text inputs beside it: stacked is a filled box that shows focus and error with a line inside its edge and draws no label — the label of the Field that frames it stands above it; filled and outlined float the label inside the box. Use one style per form. A design system may leave some out (the Tanrei system ships stacked only) or add values. (From Number input.) |
| `size` | `enum`: `small`, `medium`, `large` | `"medium"` | `size` | Minimum height of the container: stacked 32 / 40 / 56, as tall as a Button of the same size, so that the box and a Button side by side in one row stand as tall as each other; filled and outlined 40 / 48 / 56, which hold the label that floats inside them. These are the text input's three sizes, small for a bar, a toolbar or a dense row of controls. The hit area always meets the minimum target. A design system may add values. (From Number input.) |
| `value` | `number` | — | `value` | The committed number, or null (the platform's absent value) while the field holds none. It changes when the person commits — focus leaves, the action key, a step — not on every keystroke; input carries what is being typed. (From Number input.) |
| `label` | `string` | `""` | `label` | Names the control, visibly and to assistive technology. Required, unless the control names itself (a checkbox or a switch with its own label): then leave it empty and the field adds only help and an error. (From Field: Names the number input. In a filled or outlined look the input draws it, floating in its box, and the Field draws no label row (FLD-25, NMI-8).) |
| `labelHidden` | `boolean` | `false` | `label-hidden` | Does not draw the label, which stays the accessible name. For a control whose visible label is elsewhere (a table column, a toolbar). (From Field: Hides the label wherever it would be drawn: the Field's row, or the input's floating label (FLD-25). Where no message is shown either, the bare number input, named by its own label, is that control without a frame.) |
| `placeholder` | `string` | `""` | `placeholder` | A hint shown while the input is empty and the label is not in the input line. Never a replacement for a name. (From Number input.) |
| `supportingText` | `string` | `""` | `supporting-text` | Help shown below the control and given to assistive technology as the control's description. While the field is in error it gives way to errorText, unless the design system keeps both (comp.field.error-text.placement append). (From Field.) |
| `errorText` | `string` | `""` | `error-text` | Shown while error is true, in supportingText's place — or below it, which then stays, where the design system's comp.field.error-text.placement is append: what is wrong and how to put it right, in words. (From Field.) |
| `error` | `boolean` | `false` | `error` | Puts the field in the error condition: the error text is drawn, the control is exposed as invalid and, where it has an error condition of its own, drawn in it. What a value means is the product's to validate; the field never sets this itself. (From Field: The Field puts its number input in the input's own error condition (FLD-8, NMI-10); the steppers stay as they are.) |
| `disabled` | `boolean` | `false` | `disabled` | Disables the control and draws the frame as disabled. Disable a framed control here, not on the control, so that its label follows. (From Field: The Field disables its number input, and with it both steppers (FLD-14, NMI-32); the number field is then left out of its form (NUM-48).) |
| `readOnly` | `boolean` | `false` | `readonly` | The number can be focused, selected and copied, but not changed: no key steps it and no stepper is drawn. (From Number input.) |
| `required` | `boolean` | `false` | `required` | What the form asks of the control: true exposes it as required and draws the required mark beside the label. It never validates: a missing answer is the product's to report with error. (From Field: The Field exposes its number input as required (FLD-10, NMI-12).) |
| `optional` | `boolean` | `false` | `optional` | Draws the optional tag after the label and adds optionalText to the control's description, because assistive technology has no state for it. Ignored while required is true: a control is never both. (From Field.) |
| `requiredMark` | `enum`: `auto`, `tag`, `asterisk`, `none` | `"auto"` | `required-mark` | How this control shows that it is required: tag is a small filled Tag with requiredText, asterisk is "*" after the label, none draws nothing and keeps the semantics. Auto takes comp.field.requirement.mark, which follows sys.behavior.requirement-mark, the system's one answer. Ignored unless required is true. (From Field.) |
| `requiredText` | `string` | `""` | `required-text` | The text of the required tag, in the product's language ("Required", "必須"). The product's: Tanrei has no word for it. Empty reads the product's words; with neither, FLD-24 says what is drawn. (From Field.) |
| `optionalText` | `string` | `""` | `optional-text` | The text of the optional tag, in the product's language ("Optional", "任意"); also read to assistive technology as part of the description. The product's: Tanrei has no word for it. Empty reads the product's words. (From Field.) |
| `min` | `number` | — | `min` | The lowest number a commit keeps; a lower one is raised to it. Null for no limit. It is also where the steps are counted from. (From Number input.) |
| `max` | `number` | — | `max` | The highest number a commit keeps; a higher one is lowered to it. Null for no limit. (From Number input.) |
| `step` | `number` | `1` | `step` | How far Up Arrow, Down Arrow and a stepper move the number; Page Up and Page Down move ten times as far. It does not limit what may be typed. (From Number input.) |
| `steppers` | `boolean` | `true` | — | Draws the two stepper buttons at the end of the field. False for a field in a row too narrow for them, or beside a slider that does their work; the keys still step. (From Number input.) |
| `incrementLabel` | `string` | `""` | `increment-label` | The accessible name of the stepper that steps up, in the product's language ("Increase"). The product's: Tanrei has no word for it. Empty reads the product's words. Required while the steppers are shown. (From Number input.) |
| `decrementLabel` | `string` | `""` | `decrement-label` | The accessible name of the stepper that steps down, in the product's language ("Decrease"). The product's: Tanrei has no word for it. Empty reads the product's words. Required while the steppers are shown. (From Number input.) |
| `prefixText` | `string` | `""` | `prefix-text` | Fixed text before the number, not part of the value: a currency sign ("$", "¥"). (From Number input.) |
| `suffixText` | `string` | `""` | `suffix-text` | Fixed text after the number, not part of the value: the unit ("px", "ms", "%", "kg"). Read to assistive technology with the number. (From Number input.) |
| `valueText` | `string` | `""` | `value-text` | The value as words ("12 pixels", "3 stars"), given to assistive technology in place of the number with its prefix and suffix. The same text a Slider beside the field takes as its valueText. (From Number input.) |
| `align` | `enum`: `start`, `end` | `"start"` | `align` | Where the number stands in the input: at the start, as the text of every other field, or at the end, for a number in a column of numbers whose digits should line up. (From Number input.) |
| `minFractionDigits` | `number` | `0` | `min-fraction-digits` | The fewest digits shown after the decimal separator; zeros fill them (2 for an amount of money: "12.00"). (From Number input.) |
| `maxFractionDigits` | `number` | `3` | `max-fraction-digits` | The most digits kept after the decimal separator: a commit rounds to it. 0 makes the field hold whole numbers and asks for a keyboard without a separator. (From Number input.) |
| `locale` | `string` | `""` | `locale` | A BCP 47 language tag ("en-US", "de-DE", "ar-EG") for how the number is shown and read: its digits and its decimal separator. Empty uses the platform's current locale. The value itself is a number in every locale. (From Number input.) |
| `invalidText` | `string` | `""` | `invalid-text` | The words for an input committed with a text that is not a number ("Enter a number"): given to the Field that frames it, which shows them as its error text and, while they are empty, shows its own errorText (NMI-21, FLD-28). (From Number input: Shown by the Field, in its supporting row (FLD-28).) |

### Events

| Event | Description |
| --- | --- |
| `input` | The person changed the text, or a step changed the value; carries the number the text reads as — not clamped, not rounded — or the empty value while it reads as none. Emitted for every change, not when the product sets value. What a Slider beside the field follows. (From Number input.) |
| `change` | A commit changed the value: focus left the field, the action key was pressed, a key or a stepper stepped it, or a held stepper was released; carries the value. (From Number input.) |
| `action` | The person pressed the keyboard's action key (Enter, Return, Done). (From Number input.) |
| `entryError` | The person committed a text that is not a number; carries the reason (invalid) and invalidText, the words the input has for it. The entry error itself is shown by the Field that frames the input (NMI-21). (From Number input.) |

### Slots

| Slot | Description |
| --- | --- |
| `label-icon` | A glyph before the label. (From Field.) |

### States

`enabled`, `disabled`, `hovered`, `focused`, `error`

### Accessibility

- Role: `spinbutton`
- Labeling: The number field adds nothing to what its members expose and coordinates nothing: the Field gives the number input its name, its description and its required, invalid and disabled states (FLD-8, FLD-10, FLD-11, FLD-14), and the number input carries them on its own element with its value, its limits and its value text (NMI-12, NMI-34). Assistive technology meets one spin button named by label and two buttons that are no focus stops, exactly as it meets a Field around a number input written by hand.
- Minimum target size: yes

| Keys | Action |
| --- | --- |
| Every key | The number input's (its accessibility block; NMI-20, NMI-23). The number field handles no key and adds no focus stop (NUM-49). |

- One level down is the same thing: a Field with a number input in it. Every fixture has that pair as its twin, and the accessibility tree of the two is the same (NUM-47).
- On the web the two members stand in the number field's own shadow root, so the form meets the number field and not the input (NUM-48); focus passes through to the input (NUM-49).
- Two levels down, for a number whose label is elsewhere and that shows no message, is the number input alone, named by its own label: beside a slider under one row title, in a table, in a toolbar.

### Behaviour

Requirements in EARS form, each with its stable id.

- **NUM-47** THE number field SHALL be a Field that frames one number input, and nothing else. It SHALL give label, labelHidden, supportingText, errorText, error, disabled, required, optional, requiredMark, requiredText and optionalText to its Field and every other prop to its number input, each unchanged; SHALL hold the label-icon slot for its Field; and SHALL emit its number input's events as its own, each once. THE number field SHALL be as wide as the place it stands in, and its number input SHALL fill it: it is a block with no width of its own, as its Field is (FLD-1), around a control that fills the width it is given (NMI-36). It SHALL draw no part of its own, hold no state of its own and have no token of its own: what it shows, how it behaves and what it exposes to assistive technology SHALL be exactly what that Field and that number input do when a product places the one in the other (FLD-1 to FLD-28; NMI-1 to NMI-46) — the label row and its requirement mark (FLD-2 to FLD-6), or the label that floats in the box with the Field's row left out (FLD-25, NMI-7, NMI-8); the supporting row and the error (FLD-7 to FLD-9, FLD-26); the name, the description and the states (FLD-10, FLD-11, FLD-14, NMI-12, NMI-32); a text that is not a number shown as an error in the Field's row, in the input's words (FLD-28, NMI-21); and the two steppers, which are the number input's Buttons and stand inside its box (NMI-25).
- **NUM-48** WHERE the platform has forms (the web) THE number field SHALL be the one control the form sees: it SHALL take name, submit its number input's value as that input submits it — a decimal number with ASCII digits and a period, or an empty string WHILE it holds none (NMI-35) — reset to the value it was first given, restore it on navigation, report to the form's constraint validation exactly what its number input would report there (a missing value WHILE required is true and it holds none, NMI-12; a bad input WHILE an entry error lasts, NMI-21), and be left out WHILE disabled is true or a disabled group of the form holds it; its number input and its Field SHALL take no part in the form themselves. WHEN the action key asks for the form's submission (NMI-20) the form asked SHALL be the number field's own.
- **NUM-49** WHEN the number field is given focus — by the product, by a press on any part of it that FLD-12 or NMI-14 gives to the input, or by a form that reports its validity — THE number field SHALL pass the focus to its number input and SHALL add no stop to the focus order: it has one stop, its input, and the steppers are none (NMI-25). A press on a stepper SHALL step and move no focus, in the number field as in the bare input (NMI-26). WHILE focus is inside it THE number field SHALL count as focused for its Field (FLD-13).
- **NUM-50** IF the number field is placed in a Field THE number field SHALL in debug builds report that it is a field already and that the bare control is the number input, and both SHALL still render (FLD-15). WHILE it stands in a field group THE number field SHALL follow that group's disabled, through its own Field, and take nothing else from the group (FGR-14).
- **NUM-51** THE number field SHALL have no words of its own and SHALL read none: requiredText and optionalText are read by its Field (FLD-24), incrementLabel and decrementLabel by its number input (NMI-44), each from the instance's prop and then from the product's words.
- **NUM-52** WHERE the platform has ARIA attributes (the web), WHEN the product sets an aria- attribute on the host, by the attribute or by the ARIA property that reflects it, THE number field SHALL move it to the data-aria- attribute of the same name, so that the host is no second node with its name, description or state, and SHALL expose it on the element that carries its role — an id reference by the elements it names in the host's tree or a tree around it, an error message as part of the description while the number field is invalid — except those the number field owns (aria-label, aria-labelledby, aria-disabled), which it SHALL move and not expose: its name is label (NUM-47). WHEN the product removes the aria- attribute or its data-aria- twin, or sets the ARIA property that reflects it (ariaLabel, ariaDescribedByElements…) to null, THE number field SHALL take it off that element. WHEN the product sets an aria- attribute the number field owns THE number field SHALL report it in debug builds.

### Tokens

As written in the token documents (DTCG): an alias in braces names the token it takes its value from, which each design system resolves. On the web each token is a CSS custom property: `--tanrei` and the name after `tanrei`, joined by hyphens (`tanrei.comp.field.…` → `--tanrei-comp-field-…`).

#### `tanrei.comp.field`

| Token | Type | Value |
| --- | --- | --- |
| `comp.field.label.typescale` | `typography` | `{tanrei.sys.typescale.label}` |
| `comp.field.label.gap` | `dimension` | `{tanrei.sys.space.space100}` |
| `comp.field.label-icon.size` | `dimension` | `{tanrei.sys.icon.small}` |
| `comp.field.label-icon.gap` | `dimension` | `{tanrei.sys.space.space100}` |
| `comp.field.requirement.mark` | `number` | `{tanrei.sys.behavior.requirement-mark}` |
| `comp.field.requirement.gap` | `dimension` | `{tanrei.sys.space.space100}` |
| `comp.field.requirement.asterisk-gap` | `dimension` | `{tanrei.sys.space.space25}` |
| `comp.field.supporting-text.typescale` | `typography` | `{tanrei.sys.typescale.label-small}` |
| `comp.field.supporting-text.gap` | `dimension` | `{tanrei.sys.space.space50}` |
| `comp.field.counter.gap` | `dimension` | `{tanrei.sys.space.space200}` |
| `comp.field.motion.state-duration` | `duration` | `{tanrei.sys.motion.role.state.default}` |
| `comp.field.motion.state-easing` | `cubicBezier` | `{tanrei.sys.motion.easing.state}` |
| `comp.field.standard.label.color` | `color` | `{tanrei.sys.color.on-surface}` |
| `comp.field.standard.label-icon.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.supporting-text.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.counter.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.required-asterisk.color` | `color` | `{tanrei.sys.color.primary}` |
| `comp.field.standard.error.label.color` | `color` | `{tanrei.sys.color.on-surface}` |
| `comp.field.standard.error.label-icon.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.error.supporting-text.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.error.counter.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.error.required-asterisk.color` | `color` | `{tanrei.sys.color.primary}` |
| `comp.field.standard.error.value-text.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.value-text.color` | `color` | `{tanrei.sys.color.on-surface-variant}` |
| `comp.field.standard.error-text.color` | `color` | `{tanrei.sys.color.error}` |
| `comp.field.value-text.typescale` | `typography` | `{tanrei.sys.typescale.label}` |
| `comp.field.value-text.gap` | `dimension` | `{tanrei.sys.space.space200}` |
| `comp.field.error-text.gap` | `dimension` | `{tanrei.sys.space.space50}` |
| `comp.field.error-text.placement` | `number` | `0` |

Per-state tokens, valued by the design system's pattern rules (not written by hand):

- `comp.field.<variant>.<state>.<property>` for the variants `standard`, the states `focused`, `disabled` and the properties `label.color`, `label-icon.color`, `supporting-text.color`, `required-asterisk.color`, `error.label.color`, `error.label-icon.color`, `error.supporting-text.color`, `error.required-asterisk.color`, `counter.color`, `error.counter.color`, `value-text.color`, `error.value-text.color`, `error-text.color`.

### Web 上绘制方式的不同之处

- 这个元素的 shadow root 里有一个 `<tanrei-field>`，其中放着一个 `<tanrei-number-input>`。导入数字字段，两者也随之完成定义。
- 数字字段是与表单关联的元素，也是它的表单遇到的唯一控件。它接受 `name`，无论区域设置显示成什么样，都以普通的十进制数字（`12.5`）提交它的值。重置时回到 `value` 属性（attribute）的值；在 `required` 且没有数字时报告缺少值，在文本不是数字时报告输入有误。
- 它是一个块，和它所在的地方一样宽。在不给宽度的地方，长标签会让它比自己的方框更宽：这时请给它一个宽度。
- 部件就是成员的部件，沿用它们自己的名称：来自字段的 `label`、`label-icon`、`requirement-label` 和 `supporting-text`；来自数字输入框的 `container`、`outline`、`active-indicator`、`input`、`prefix`、`suffix` 和 `stepper`。`label` 和 `requirement-label` 指向两者中画出来的那一个；`field-label` 和 `number-input-label` 只指向其中一个。两个成员本身是部件 `field` 和 `number-input`。
- `entryerror` 的 `detail.text` 是输入框的 `invalidText`，没有提供时为空。detail 的类型是数字输入框的：`TanreiNumberInputInputDetail` 和 `TanreiNumberInputEntryErrorDetail`。
- `steppers` 对应含义相反的属性（attribute）`no-steppers`，`readOnly` 对应 `readonly`。
- `input` 是带有 `detail.value` 的 CustomEvent。`change` 和 `action` 是普通事件：从元素上读取 `value`。除非 `action` 被取消，否则随后会请求表单提交。
- 没有 `locale` 时，字段读取最近的 `lang` 属性（attribute），其次是浏览器的语言。
- 除了区域设置的分隔符之外，只要该区域设置不用句点分组，句点也读作小数分隔符。
- 翻页键与滑块一样，在步长自己的网格上走十步：步长为 2 时，在 42 上按 Page Up 得到 62，再按一次得到 82。
- 在 iOS 和 iPadOS 上，可以键入负数时，字段会请求完整键盘，因为那里的小数键盘没有减号。
- 在元素定义之前，它没有尺寸。请预留高度。

## 指南

### 数字字段、文本字段还是滑块

| 方面 | 数字字段 | 文本字段 | 滑块 |
| --- | --- | --- | --- |
| 里面是什么 | 一个数字 | 任意文本 | 某个范围内的一个数字 |
| 选择方式 | 键入或步进 | 键入 | 拖动 |
| 适合 | 已经知道的值 | 不是数量的数字串 | 凭感觉选出的值 |

邮政编码、卡号、电话号码和一次性验证码都由数字组成，但不是数量：没有人会给邮政编码加一。它们请使用[文本字段](https://tanrei.chnotchy.com/zh-cn/components/text-field/)。

### 推荐

- 写一个标签，说明计数的是什么，并让它在表单中保持可见。
- 把单位放进 `suffixText`，把货币符号放进 `prefixText`。
- 后缀读出来不合适时，提供 `valueText`：`×` 用“1.5 倍”。
- 编写 `invalidText` 时要说明该键入什么：“请输入数字。”
- 整数把 `maxFractionDigits` 设为 0。这样键盘上就没有分隔符。
- 给出 `incrementLabel` 和 `decrementLabel`：写在字段上，或者用 `setWords()` 为整个产品只给一次。Tanrei 不自带任何文字：没有名称的步进按钮仍然会绘制，用指针按下时仍然步进，但不提供给辅助技术，因为在那里微调按钮自己就能步进。

### 避免

- 不要把数字字段用于不是数量的数字串。
- 不要在 `input` 时保存。每按一次键它都会触发；`change` 才带有已确认的值。
- 不要指望 `min` 和 `max` 修正你自己设置的值。它们作用于用户确认的内容。
- 不要把选择单位的控件放进字段里面。在旁边放一个[下拉选择框](https://tanrei.chnotchy.com/zh-cn/components/select/)。
- 不要把数字字段放进字段。它已经是一个字段；字段框住的控件是[数字输入框](https://tanrei.chnotchy.com/zh-cn/components/number-input/)。
- 不要为了把方框放在你自己的标签下面而隐藏数字字段的标签。请使用数字输入框。

## 无障碍

### 组件负责的部分

- 输入框是一个微调按钮（spin button）。它的名称是 `label`，无论是画出来的还是隐藏的，绝不是占位符。
- 它的值是已确认的数字，它的范围是 `min` 和 `max`。
- 显示出来的辅助文本或错误文本是它的描述；字段为选填时，还会加上 `optionalText`。
- `error` 为 true 或文本不是数字时，它暴露为无效；设置了 `required` 时，暴露为必填；只读时，暴露为只读。
- 字段获得焦点期间出现的错误，会以礼貌（polite）的方式朗读一次——文本不是数字时也一样。
- 步进按钮是由 `decrementLabel` 和 `incrementLabel` 命名的按钮；没有人命名的那一个对辅助技术隐藏。它们不在焦点顺序中，因为方向键在输入框里就能步进；通过触摸浏览的用户仍然能找到它们。
- 按下步进按钮不会移动焦点，所以不会唤起屏幕键盘。
- 输入法正在组合输入时，字段不解读任何内容，也不处理任何按键。
- 滚轮绝不会改变数字。
- 字段的点击区域满足最小目标，每个步进按钮都是完整的目标。
- 文本放大到 200% 时，标签和帮助文本会换行。数字保持在一行里，并且可以滚动。
- 当一行放不下并排的数字和步进按钮时（例如在窄窗口中把文本放大到 200%，并带有前缀和较长后缀），步进按钮会移到数字下方单独的一行，位于方框的末端。它们绝不会被隐藏，因为在触摸屏上它们是步进的唯一方式。
- 在强制颜色模式下，字段会多出一道边线，错误靠文字和无效状态来表达。
- 在从右到左的布局中，步进按钮和标签会镜像：步进按钮位于左端。数字和它的单位按单位自身所用文字的写法书写：用拉丁字母或符号写的单位位于数字之后，从左到右书写；用页面的文字写的单位位于数字的左侧。朗读的内容不变。

Web 上的已知差距：

- Chromium 读出数字时不带单位：它从输入框里的文本取得值文本，而略过字段指定的那一个。单位重要时，请在标签里写明。
- 在元素定义之前，什么都不绘制。

### 需要你做的事

- 为每个数字字段提供 `label`。
- 在字段上编写 `invalidText`。`requiredText`、`optionalText`、`incrementLabel` 和 `decrementLabel` 可以写在字段上，也可以用 `setWords()` 为整个产品只给一次。Tanrei 不自带任何文字；缺少的文字会在开发时报告。参见[产品的文字](https://tanrei.chnotchy.com/zh-cn/foundations/words/)。
- 自己校验值，设置 `error`，并编写说明如何改正这个数字的 `errorText`。
- 给滑块和它旁边的数字输入框相同的名称。
