# Number Input

输入数字，按步进调整值，并按语言格式化显示。

把 Number Input 用于数量、价格和度量。它保留一个数值，同时显示格式化后的文本，并可以用键盘、步进按钮或拖动它的标签来调整这个值。

```ts title="basic.ts"
import "@ui-sdk/web/number-input"
import "@ui-sdk/web/field"
import { createElement, Minus, MoveHorizontal, Plus } from "lucide"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-number-input default-value="1" min="1">
        <ui-number-input-scrub-area pixels-per-step="4">
          <ui-field-label>Quantity</ui-field-label>
          <ui-number-input-scrub-area-cursor>
            ${createElement(MoveHorizontal, { "aria-hidden": "true" }).outerHTML}
          </ui-number-input-scrub-area-cursor>
        </ui-number-input-scrub-area>
        <ui-number-input-group>
          <ui-number-input-decrement>
            <button aria-label="Decrease">
              ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-number-input-decrement>
          <ui-number-input-control>
            <input />
          </ui-number-input-control>
          <ui-number-input-increment>
            <button aria-label="Increase">
              ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-number-input-increment>
        </ui-number-input-group>
      </ui-number-input>
    </ui-field>
  `
  root
    .querySelector("ui-number-input")!
    .addEventListener("valuecommit", (event) => {
      log(root, `Quantity ${event.detail.value ?? "empty"}`)
    })
}

export { mount }
```

横向拖动 Quantity 标签来调整数值，或者点击它来聚焦输入框。输入一个数字，按 ArrowUp 或 ArrowDown，或者按住一个步进按钮。每次变更提交后，控制台记录一次值。

## 安装
```bash
npm install @ui-sdk/web @ui-sdk/core
```

导入组件会定义它的元素。如果用到字段，也导入字段。在服务器上，导入什么都不做。

```ts
import "@ui-sdk/web/number-input"
import "@ui-sdk/web/field"
```

## 组合
用下面的组合构建 `ui-number-input`：

```text
ui-number-input
├── ui-number-input-scrub-area
│   └── ui-number-input-scrub-area-cursor
└── ui-number-input-group
    ├── ui-number-input-decrement
    │   └── button
    ├── ui-number-input-control
    │   └── input
    └── ui-number-input-increment
        └── button
```

`ui-number-input` 持有数值。`ui-number-input-group` 包住文本输入框和可选的步进按钮。`ui-number-input-control` 包住你自己的 `<input>`，`ui-number-input-decrement` 和 `ui-number-input-increment` 包住你自己的 `<button>`，它们改变值，并在按住时重复。把输入框样式和无障碍名称放在这些原生元素上。`ui-number-input-scrub-area` 是可选的，拖动它时会改变值。

输入的文字有效且在边界内时，输入会更新值。Enter 或失去焦点会提交它：文本被解析、限制在边界内、吸附到步进，然后格式化。空的输入框值为 `null`。

## 用法
导入部件并把它们组合起来：

```html
<script type="module">
  import "@ui-sdk/web/number-input"
</script>

<ui-number-input default-value="1" min="0">
  <ui-number-input-group>
    <ui-number-input-decrement
      ><button aria-label="Decrease">−</button></ui-number-input-decrement
    >
    <ui-number-input-control
      ><input aria-label="Quantity"
    /></ui-number-input-control>
    <ui-number-input-increment
      ><button aria-label="Increase">+</button></ui-number-input-increment
    >
  </ui-number-input-group>
</ui-number-input>
```

## 字段
把数字输入框包进 [Field](/docs/web-components/components/field)，给它一个可见的标签和描述。

```ts title="field.ts"
import "@ui-sdk/web/number-input"
import "@ui-sdk/web/field"
import { createElement, Minus, Plus } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Tickets</ui-field-label>
      <ui-number-input default-value="2" min="1">
        <ui-number-input-group>
          <ui-number-input-decrement>
            <button aria-label="Decrease">
              ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-number-input-decrement>
          <ui-number-input-control>
            <input />
          </ui-number-input-control>
          <ui-number-input-increment>
            <button aria-label="Increase">
              ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-number-input-increment>
        </ui-number-input-group>
      </ui-number-input>
      <ui-field-description>Each ticket admits one person to the workshop.</ui-field-description>
    </ui-field>
  `
}

export { mount }
```

点击 Tickets 来聚焦输入框，然后输入或步进它的值。屏幕阅读器会把描述和字段一起读出来。

## 最小值与最大值
用 `min` 和 `max` 设置边界。步进按钮到达边界时会禁用。输入的值超出边界时，会在提交时被限制到边界内。

```ts title="min-max.ts"
import "@ui-sdk/web/number-input"
import "@ui-sdk/web/field"
import { createElement, Minus, Plus } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Guests</ui-field-label>
      <ui-number-input default-value="2" min="1" max="8">
        <ui-number-input-group>
          <ui-number-input-decrement>
            <button aria-label="Decrease">
              ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-number-input-decrement>
          <ui-number-input-control>
            <input />
          </ui-number-input-control>
          <ui-number-input-increment>
            <button aria-label="Increase">
              ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-number-input-increment>
        </ui-number-input-group>
      </ui-number-input>
      <ui-field-description>Tables seat between 1 and 8 guests.</ui-field-description>
    </ui-field>
  `
}

export { mount }
```

在 1 和 8 之间改变 Guests。输入 20 并按 Enter，它会被限制为 8。到达任一边界时，那个方向的步进按钮会被禁用。

## 步进与大步进
`step` 设置通常的增量，默认是 1。步进从 `min` 开始计算，没有设置最小值时从 0 开始。当步进落不到 `max` 上时，End 和增加按钮会停在它下方的最高步进位置，所以步进会让值保持在步进网格上，和 [Slider](https://ui-sdk.cn/docs/web-components/components/slider#step-and-bounds) 一样。Shift、Page Up 和 Page Down 使用 `large-step`，默认十个步进；Alt（Option）加方向键使用 `small-step`，即十分之一个步进。[键盘](https://ui-sdk.cn/docs/web-components/components/number-input#keyboard)列出了每个按键。

```ts title="step.ts"
import "@ui-sdk/web/number-input"
import "@ui-sdk/web/field"
import { createElement, Minus, Plus } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Hours</ui-field-label>
      <ui-number-input default-value="1.5" min="0" max="24" step="0.25" large-step="1" small-step="0.05">
        <ui-number-input-group>
          <ui-number-input-decrement>
            <button aria-label="Decrease">
              ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-number-input-decrement>
          <ui-number-input-control>
            <input />
          </ui-number-input-control>
          <ui-number-input-increment>
            <button aria-label="Increase">
              ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-number-input-increment>
        </ui-number-input-group>
      </ui-number-input>
      <ui-field-description>Logged in quarter hours.</ui-field-description>
    </ui-field>
  `
}

export { mount }
```

以 0.25 为步进调整 Hours。按住 Shift 移动 1，或者按住 Alt（Option）加方向键移动 0.05。Home 和 End 跳到 0 和 24。

## 格式化
通过 `format` 传入 `Intl.NumberFormat` 选项。输入框按这个格式显示和解析，同时保留数值。对于百分比，`0.15` 会显示为 `15%`，`step` 默认采用格式能显示的最小百分比：整数百分比是 `0.01`，两位小数是 `0.0001`。把 `format` 作为元素的 property 设置；它是一个对象。

```ts title="format.ts"
import "@ui-sdk/web/number-input"
import "@ui-sdk/web/field"
import { createElement, Minus, Plus } from "lucide"

const fields = [
  {
    label: "Price",
    defaultValue: 19.99,
    step: 0.01,
    format: { style: "currency", currency: "USD" },
  },
  {
    label: "Discount",
    defaultValue: 0.15,
    step: 0.01,
    format: { style: "percent" },
  },
  {
    label: "Weight",
    defaultValue: 2.5,
    step: 0.1,
    format: { style: "unit", unit: "kilogram" },
  },
] satisfies {
  label: string
  defaultValue: number
  step: number
  format: Intl.NumberFormatOptions
}[]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      ${fields
        .map(
          (field) => `
            <ui-field>
              <ui-field-label>${field.label}</ui-field-label>
              <ui-number-input default-value="${field.defaultValue}" step="${field.step}" min="0">
                <ui-number-input-group>
                  <ui-number-input-decrement>
                    <button aria-label="Decrease">
                      ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
                    </button>
                  </ui-number-input-decrement>
                  <ui-number-input-control>
                    <input />
                  </ui-number-input-control>
                  <ui-number-input-increment>
                    <button aria-label="Increase">
                      ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
                    </button>
                  </ui-number-input-increment>
                </ui-number-input-group>
              </ui-number-input>
            </ui-field>`
        )
        .join("")}
    </div>
  `
  root
    .querySelectorAll<HTMLElement & { format: Intl.NumberFormatOptions }>(
      "ui-number-input"
    )
    .forEach((el, index) => {
      el.format = fields[index].format
    })
}

export { mount }
```

编辑 Price、Discount 或 Weight，然后离开字段来格式化它。试着在 Price 里输入 5，或在 Discount 里输入 25%，然后使用步进按钮。

## 语言
设置 `locale` 来选择分隔符、货币符号和分组。不设置时，输入框在挂载后跟随页面的语言或浏览器的语言。没有提供 locale 时，服务端标记使用英语；如果首次渲染的结果很重要，请显式设置 locale。

```ts title="locale.ts"
import "@ui-sdk/web/number-input"
import "@ui-sdk/web/field"
import { createElement, Minus, Plus } from "lucide"

const fields = [
  {
    label: "Preis",
    locale: "de-DE",
    defaultValue: 1234.5,
    step: 0.01,
    format: { style: "currency", currency: "EUR" },
  },
  {
    label: "Budget",
    locale: "en-IN",
    defaultValue: 1234567,
    step: 1000,
    format: { style: "currency", currency: "INR", maximumFractionDigits: 0 },
  },
] satisfies {
  label: string
  locale: string
  defaultValue: number
  step: number
  format: Intl.NumberFormatOptions
}[]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      ${fields
        .map(
          (field) => `
            <ui-field>
              <ui-field-label>${field.label}</ui-field-label>
              <ui-number-input default-value="${field.defaultValue}" step="${field.step}" locale="${field.locale}" min="0">
                <ui-number-input-group>
                  <ui-number-input-decrement>
                    <button aria-label="Decrease">
                      ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
                    </button>
                  </ui-number-input-decrement>
                  <ui-number-input-control>
                    <input />
                  </ui-number-input-control>
                  <ui-number-input-increment>
                    <button aria-label="Increase">
                      ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
                    </button>
                  </ui-number-input-increment>
                </ui-number-input-group>
              </ui-number-input>
              <ui-field-description>Formatted for ${field.locale}.</ui-field-description>
            </ui-field>`
        )
        .join("")}
    </div>
  `
  root
    .querySelectorAll<HTMLElement & { format: Intl.NumberFormatOptions }>(
      "ui-number-input"
    )
    .forEach((el, index) => {
      el.format = fields[index].format
    })
}

export { mount }
```

用逗号作小数点来编辑 Preis，或者步进 Budget 看看印度式的数字分组。显示和接受的格式都跟随每个字段的 locale。

## 鼠标滚轮
设置 `wheel`，让输入框获得焦点时可以用鼠标滚轮步进。它默认关闭。

```ts title="wheel.ts"
import "@ui-sdk/web/number-input"
import "@ui-sdk/web/field"
import { createElement, Minus, Plus } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Font size</ui-field-label>
      <ui-number-input default-value="16" min="8" max="72" wheel>
        <ui-number-input-group>
          <ui-number-input-decrement>
            <button aria-label="Decrease">
              ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-number-input-decrement>
          <ui-number-input-control>
            <input />
          </ui-number-input-control>
          <ui-number-input-increment>
            <button aria-label="Increase">
              ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-number-input-increment>
        </ui-number-input-group>
      </ui-number-input>
      <ui-field-description>Focus the input, then scroll over it.</ui-field-description>
    </ui-field>
  `
}

export { mount }
```

聚焦 Font size 并在它上面滚动来改变值。把焦点移开再滚动一次，值保持不变。

## 拖动区域
`ui-number-input-scrub-area` 在你拖动它时改变值。手柄可以是数字输入框里的任何元素：第一个示例里的标签，或者组里的字母或图标，就像设计工具那样。向右和向上会增大值。`orientation` 选择轴，`pixels-per-step` 控制指针每步移动多远。Shift 和 Alt（Option）使用大步进和小步进。

```ts title="scrub.ts"
import "@ui-sdk/web/number-input"
import { createElement, MoveHorizontal } from "lucide"
import { log } from "./log"

const fields = [
  { label: "X position", handle: "X", defaultValue: 120 },
  { label: "Y position", handle: "Y", defaultValue: 48 },
  { label: "Width", handle: "W", defaultValue: 320, min: 0 },
  { label: "Height", handle: "H", defaultValue: 240, min: 0 },
]

function mount(root: HTMLElement) {
  const title = `frame-${crypto.randomUUID()}`
  root.innerHTML = `
    <div data-slot="card" role="group" aria-labelledby="${title}">
      <h3 id="${title}">Frame</h3>
      <div data-slot="grid">
        ${fields
          .map(
            ({ label, handle, defaultValue, min }) => `
              <ui-number-input default-value="${defaultValue}"${min === undefined ? "" : ` min="${min}"`}>
                <ui-number-input-group>
                  <ui-number-input-scrub-area pixels-per-step="1">
                    <span aria-hidden="true">${handle}</span>
                    <ui-number-input-scrub-area-cursor>
                      ${createElement(MoveHorizontal, { "aria-hidden": "true" }).outerHTML}
                    </ui-number-input-scrub-area-cursor>
                  </ui-number-input-scrub-area>
                  <ui-number-input-control>
                    <input aria-label="${label}" />
                  </ui-number-input-control>
                </ui-number-input-group>
              </ui-number-input>
            `
          )
          .join("")}
      </div>
    </div>
  `
  root.querySelectorAll("ui-number-input").forEach((field, index) => {
    field.addEventListener("valuecommit", (event) => {
      log(root, `${fields[index].label} ${event.detail.value ?? "empty"}`)
    })
  })
}

export { mount }
```

横向拖动 X、Y、W 或 H 字母来改变那个值。按住 Shift 使用更大的步进，或按住 Alt（Option）使用更小的步进。拖动结束时，控制台记录每个值。

指针锁定可用时，拖动可以一直继续，越过屏幕边缘。`ui-number-input-scrub-area-cursor` 在锁定时绘制一个替代光标。光标用一个内联位移放进文档 body 中；用负外边距让图标居中。

要把拖动区域放在数字输入框之外，比如放在工具栏里的图标上，把拖动区域的 `for` 属性设为数字输入框的 `id`。多个拖动区域可以控制同一个字段。

## 禁用
在组件或包住它的 fieldset 上设置 `disabled`，阻止聚焦、变更和表单提交。

```html
<ui-field>
  <ui-field-label>Quantity</ui-field-label>
  <ui-number-input default-value="3" disabled>
    <ui-number-input-group>
      <ui-number-input-decrement
        ><button aria-label="Decrease">−</button></ui-number-input-decrement
      >
      <ui-number-input-control><input /></ui-number-input-control>
      <ui-number-input-increment
        ><button aria-label="Increase">+</button></ui-number-input-increment
      >
    </ui-number-input-group>
  </ui-number-input>
  <ui-field-description
    >Sold out. You can't change the quantity.</ui-field-description
  >
</ui-field>
```

要在某一个步进按钮上设置 `disabled`，可以放在它的元素上，比如 `<ui-number-input-increment disabled>`，也可以放在它里面的 `<button>` 上，这样只关闭那个方向。另一个按钮仍然可以步进。

## 只读
设置 `read-only`，让值保持可聚焦、仍包含在表单数据中，同时阻止编辑和步进。

```html
<ui-field>
  <ui-field-label>Seats included</ui-field-label>
  <ui-number-input default-value="5" read-only>
    <ui-number-input-group>
      <ui-number-input-decrement
        ><button aria-label="Decrease">−</button></ui-number-input-decrement
      >
      <ui-number-input-control><input /></ui-number-input-control>
      <ui-number-input-increment
        ><button aria-label="Increase">+</button></ui-number-input-increment
      >
    </ui-number-input-group>
  </ui-number-input>
  <ui-field-description>Set by your plan.</ui-field-description>
</ui-field>
```

## 校验
用 `required` 阻止空值。Field 把它的错误与输入框关联，并在一次不成功的提交后把它标记为无效。这里，Age 为空时选择 **Continue**，会显示 “Enter your age.”。

```html
<form>
  <ui-field>
    <ui-field-label>Age</ui-field-label>
    <ui-number-input name="age" required min="18" max="120">
      <ui-number-input-group>
        <ui-number-input-decrement
          ><button aria-label="Decrease">−</button></ui-number-input-decrement
        >
        <ui-number-input-control><input /></ui-number-input-control>
        <ui-number-input-increment
          ><button aria-label="Increase">+</button></ui-number-input-increment
        >
      </ui-number-input-group>
    </ui-number-input>
    <ui-field-error match="valueMissing">Enter your age.</ui-field-error>
  </ui-field>
  <button type="submit">Continue</button>
</form>
```

## 受控
设置元素的 `value` property，并监听 `valuechange`。交互进行中时，`valuechange` 报告有效的变更。`valuecommit` 在输入的文字被提交、步进按键或按钮松开，或拖动结束时触发。用提交事件来做交互结束后才该做的事。

```ts title="controlled.ts"
import "@ui-sdk/web/number-input"
import "@ui-sdk/web/field"
import { createElement, Minus, Plus } from "lucide"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" data-value="4">Reset to 4</button>
        <button type="button" data-value="">Clear</button>
      </div>
      <ui-field>
        <ui-field-label>Servings</ui-field-label>
        <ui-number-input default-value="4" min="1" max="12">
          <ui-number-input-group>
            <ui-number-input-decrement>
              <button aria-label="Decrease">
                ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
              </button>
            </ui-number-input-decrement>
            <ui-number-input-control>
              <input />
            </ui-number-input-control>
            <ui-number-input-increment>
              <button aria-label="Increase">
                ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
              </button>
            </ui-number-input-increment>
          </ui-number-input-group>
        </ui-number-input>
      </ui-field>
    </div>
  `
  const field = root.querySelector("ui-number-input")!
  field.addEventListener("valuechange", (event) => {
    log(root, `Value ${event.detail.value ?? "empty"} (${event.detail.reason})`)
  })
  field.addEventListener("valuecommit", (event) => {
    log(
      root,
      `Committed ${event.detail.value ?? "empty"} (${event.detail.reason})`
    )
  })
  root.querySelectorAll<HTMLButtonElement>("[data-value]").forEach((button) => {
    button.addEventListener("click", () => {
      field.value = button.dataset.value ? Number(button.dataset.value) : null
    })
  })
}

export { mount }
```

按住 Servings 的步进按钮。值每变化一次，控制台记录一次，松开时再记录一行 Committed。Clear 把值设为 null，Reset 恢复到 4。

共享的状态约定见[状态与事件](/docs/web-components/state-and-events)，Number Input 特有的原因见[原因](https://ui-sdk.cn/docs/web-components/components/number-input#reasons)。

## 控制器
用元素的 `api` property 从其他控件改变或聚焦输入框。`increment()` 和 `decrement()` 步进值；传入 `{ large: true }` 使用大步进。`setValue()`、`getValue()` 和 `focus()` 负责直接更新和读取。

```ts title="controller.ts"
import "@ui-sdk/web/number-input"
import "@ui-sdk/web/field"
import { createElement, Minus, Plus } from "lucide"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" data-action="out">Zoom Out</button>
        <button type="button" data-action="in">Zoom In</button>
        <button type="button" data-action="reset">Actual Size</button>
        <button type="button" data-action="read">Read</button>
        <button type="button" data-action="focus">Focus</button>
      </div>
      <ui-field>
        <ui-field-label>Zoom</ui-field-label>
        <ui-number-input default-value="100" min="10" max="400" step="10">
          <ui-number-input-group>
            <ui-number-input-decrement>
              <button aria-label="Decrease">
                ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
              </button>
            </ui-number-input-decrement>
            <ui-number-input-control>
              <input />
            </ui-number-input-control>
            <ui-number-input-increment>
              <button aria-label="Increase">
                ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
              </button>
            </ui-number-input-increment>
          </ui-number-input-group>
        </ui-number-input>
      </ui-field>
    </div>
  `
  const field = root.querySelector("ui-number-input")!
  field.format = { style: "unit", unit: "percent" }
  field.addEventListener("valuechange", (event) => {
    log(root, `Zoom ${event.detail.value ?? "empty"}% (${event.detail.reason})`)
  })
  const zoom = field.api
  const actions: Record<string, () => void> = {
    out: () => zoom.decrement({ large: true }),
    in: () => zoom.increment({ large: true }),
    reset: () => zoom.setValue(100),
    read: () => log(root, `Zoom is ${zoom.getValue()}%`),
    focus: () => zoom.focus(),
  }
  root
    .querySelectorAll<HTMLButtonElement>("[data-action]")
    .forEach((button) => {
      button.addEventListener("click", () => actions[button.dataset.action!]())
    })
}

export { mount }
```

按 Zoom In 和 Zoom Out 每次移动 100%，再按 Actual Size 恢复到 100%。Read 记录当前值，Focus 把焦点移进字段。

[控制器](/docs/web-components/controllers)介绍了创建和共享控制器。

## 表单
这个元素与表单关联，并以 `name` 提交纯数值。格式化不会改变表单数据：显示为 $4.50 的金额仍然提交 `4.5`。空值提交空字符串。

```ts title="form.ts"
import "@ui-sdk/web/number-input"
import "@ui-sdk/web/field"
import { createElement, Minus, Plus } from "lucide"
import { log } from "./log"

let count = 0

function mount(root: HTMLElement) {
  const formId = `order-${++count}`
  root.innerHTML = `
    <div data-slot="stack">
      <form data-slot="stack" id="${formId}">
        <ui-field>
          <ui-field-label>Quantity</ui-field-label>
          <ui-number-input name="quantity" default-value="2" min="1">
            <ui-number-input-group>
              <ui-number-input-decrement>
                <button aria-label="Decrease">
                  ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
                </button>
              </ui-number-input-decrement>
              <ui-number-input-control>
                <input />
              </ui-number-input-control>
              <ui-number-input-increment>
                <button aria-label="Increase">
                  ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
                </button>
              </ui-number-input-increment>
            </ui-number-input-group>
          </ui-number-input>
        </ui-field>
        <ui-field>
          <ui-field-label>Tip</ui-field-label>
          <ui-number-input name="tip" default-value="4.5" min="0" step="0.5">
            <ui-number-input-group>
              <ui-number-input-decrement>
                <button aria-label="Decrease">
                  ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
                </button>
              </ui-number-input-decrement>
              <ui-number-input-control>
                <input />
              </ui-number-input-control>
              <ui-number-input-increment>
                <button aria-label="Increase">
                  ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
                </button>
              </ui-number-input-increment>
            </ui-number-input-group>
          </ui-number-input>
        </ui-field>
      </form>
      <ui-field>
        <ui-field-label>Gift cards</ui-field-label>
        <ui-number-input name="gift-cards" form="${formId}" default-value="0" min="0">
          <ui-number-input-group>
            <ui-number-input-decrement>
              <button aria-label="Decrease">
                ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
              </button>
            </ui-number-input-decrement>
            <ui-number-input-control>
              <input />
            </ui-number-input-control>
            <ui-number-input-increment>
              <button aria-label="Increase">
                ${createElement(Plus, { "aria-hidden": "true" }).outerHTML}
              </button>
            </ui-number-input-increment>
          </ui-number-input-group>
        </ui-number-input>
      </ui-field>
      <div data-slot="row">
        <button type="reset" form="${formId}">Reset</button>
        <button type="submit" form="${formId}" data-variant="solid">Save</button>
      </div>
    </div>
  `
  const [, tip] = root.querySelectorAll("ui-number-input")
  tip.format = { style: "currency", currency: "USD" }
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    const data = [...new FormData(form)].map(
      ([name, value]) => `${name}=${value}`
    )
    log(root, `Submitted ${data.join(", ")}`)
  })
}

export { mount }
```

改变 Quantity 或 Tip 并按 Save：控制台记录纯数值。Gift cards 通过它的表单 id 属于同一个表单。Reset 恢复默认值。

设置 `form`，把输入框和页面其他位置的一个表单关联起来。表单重置会恢复默认值，并报告 `reset` 原因。

## 自定义渲染
元素没有渲染函数。输入框和步进按钮是你自己的元素，所以直接改它们，并从它们的数据属性或 `valuechange` 事件读取状态。这里一个 `valuechange` 监听器给减少按钮加了 tooltip，并在值到达边界后在增加按钮上显示 Max。

```ts title="render.ts"
import "@ui-sdk/web/number-input"
import "@ui-sdk/web/field"
import { createElement, Minus, Plus } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Temperature</ui-field-label>
      <ui-number-input default-value="-2" min="-20" max="40">
        <ui-number-input-group>
          <ui-number-input-decrement>
            <button aria-label="Colder">
              ${createElement(Minus, { "aria-hidden": "true" }).outerHTML}
            </button>
          </ui-number-input-decrement>
          <ui-number-input-control>
            <input />
          </ui-number-input-control>
          <ui-number-input-increment>
            <button aria-label="Warmer"></button>
          </ui-number-input-increment>
        </ui-number-input-group>
      </ui-number-input>
    </ui-field>
  `
  const field = root.querySelector("ui-number-input")!
  field.format = { style: "unit", unit: "celsius" }
  const colder = root.querySelector<HTMLButtonElement>('[aria-label="Colder"]')!
  const warmer = root.querySelector<HTMLButtonElement>('[aria-label="Warmer"]')!
  const plus = createElement(Plus, { "aria-hidden": "true" }).outerHTML
  const show = (value: number | null) => {
    colder.title = value === -20 ? "As cold as it goes" : "Colder"
    warmer.innerHTML = value === 40 ? "<span>Max</span>" : plus
  }
  field.addEventListener("valuechange", (event) => show(event.detail.value))
  show(field.value)
}

export { mount }
```

在 Temperature 里按 End 跳到 40°C。增加按钮显示 Max；悬停减少按钮可以看到它的 tooltip。

每个部件的状态列在[状态](https://ui-sdk.cn/docs/web-components/components/number-input#state)下。

## 样式
把组样式化为字段的盒子，并给里面的输入框和步进按钮设置样式。步进按钮上的 `data-disabled` 也表示它已到达边界，拖动改变值时 `data-scrubbing` 标记每个部件。在 Field 内部，原生输入框会收到 `data-invalid` 这样的校验属性。使用逻辑间距，让布局跟随周围的方向。

每个部件都有一个 `data-slot`，比如 `number-input-group`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/web-components/components/number-input#data-attributes)下。

## 数据属性
### `<ui-number-input>`
`[data-slot="number-input"]`

- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-scrubbing`: Present while a drag on the scrub area changes the value.

### `<ui-number-input-scrub-area>`
`[data-slot="number-input-scrub-area"]`

- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-orientation` (`horizontal`, `vertical`): Which way to drag.
- `data-scrubbing`: Present while a drag on the scrub area changes the value.

### `<ui-number-input-scrub-area-cursor>`
`[data-slot="number-input-scrub-area-cursor"]`

- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-scrubbing`: Present while a drag on the scrub area changes the value.

### `<ui-number-input-group>`
`[data-slot="number-input-group"]`

- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-scrubbing`: Present while a drag on the scrub area changes the value.

### `<ui-number-input-decrement>`
`[data-slot="number-input-decrement"]`

- `data-disabled`: Present when the button can't step: it or the field is disabled, the field is read-only, or the value is at `min`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-at-bound`
- `data-scrubbing`: Present while a drag on the scrub area changes the value.

### `<ui-number-input-control>`
`[data-slot="number-input-control"]`

- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-scrubbing`: Present while a drag on the scrub area changes the value.

### `<ui-number-input-increment>`
`[data-slot="number-input-increment"]`

- `data-disabled`: Present when the button can't step: it or the field is disabled, the field is read-only, or the value is at `max`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-scrubbing`: Present while a drag on the scrub area changes the value.

## API 参考
Props 是以 kebab 命名写成的属性，比如 `default-value`、`large-step` 和 `read-only`。`format` 和 `controller` 是 property。回调是 DOM 事件。

### NumberInput
- `value?` (`number | null`): The value, or null for an empty field. Pass it to control the field.
- `defaultValue?` (`number | null`): The value at first, when uncontrolled. A form reset returns to it.
- `valuechange event`: Runs when the value changes: as a typed number becomes valid, and on every step. `details.cancel()` stops it.
- `valuecommit event`: Runs once an interaction that changed the value ends: typing is committed, a key or a button is released, or a scrub ends. For saving.
- `min?` (`number`): The lowest value. Typed values below it are raised to it when committed.
- `max?` (`number`): The highest value. Typed values above it are lowered to it when committed.
- `step?` (`number`): How far one step moves. Committed values snap to steps from `min`, or from 0 without one.
- `largeStep?` (`number`): How far Page Up, Page Down, and Shift with an arrow key, a button, the wheel or a scrub move.
- `smallStep?` (`number`): How far Alt (Option on a Mac) with an arrow key, the wheel or a scrub moves, for fine changes. Values it reaches snap to it rather than to `step`.
- `format?` (`Intl.NumberFormatOptions`): How the value shows: `Intl.NumberFormat` options, like `{ style: "currency", currency: "USD" }`. Typing accepts the same format in the locale, and percents are fractions: 50% is 0.5.
- `locale?` (`string`): The locale for formatting and reading typed numbers. Defaults to the page's `lang`, or the browser's language without one, once the page is interactive. Server markup uses English until then, so it never disagrees with the client.
- `wheel?` (`boolean`): Lets the mouse wheel step the value while the input has focus.
- `disabled?` (`boolean`): Disables it like a native control: it can't be focused or changed, and isn't submitted.
- `readOnly?` (`boolean`): Keeps it focusable and submitted, but stops changes.
- `required?` (`boolean`): Blocks form submission while it's empty, with the browser's own message.
- `name?` (`string`): The name it submits under. The number is submitted as is, like `1234.5`, never formatted.
- `form?` (`string`): The id of a form to belong to, when it isn't inside that form.
- `controller?` (`object`): Steps it from anywhere. Create one with `createNumberInputController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### NumberInputScrubArea
- `orientation?` (`"horizontal" | "vertical"`): Which way to drag: right and up increase.
- `pixelsPerStep?` (`number`): How far the pointer moves for one step, in CSS pixels.
- `controller?` (`object`): Connects a scrub area outside the number input, like an icon in a toolbar, to the number input with this controller. Inside it, it connects on its own. Web components use `for="<number input id>"` instead.

### NumberInputIncrement 和 NumberInputDecrement
- `disabled?` (`boolean`): Turns off this button alone. Pressing, clicking or holding it doesn't step.

### 状态
同样的状态会在每个元素上显示为数据属性。

- `value` (`number | null`): The value, or null when empty.
- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether it's read-only: it stays focusable and submitted, but typing, steps and scrubs don't change it.
- `required` (`boolean`): Whether a form won't submit while it's empty.
- `scrubbing` (`boolean`): Whether a scrub is moving the value.

按钮的状态 `NumberInputButtonState` 说明该按钮能否步进，以及值是否到达它那一侧的边界，而不只是字段被禁用：

- `value` (`number | null`): The value, or null when empty.
- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`. Whether the button can't step, because it or the field is disabled, the field is read-only, or the value is at its bound.
- `readOnly` (`boolean`): Whether it's read-only: it stays focusable and submitted, but typing, steps and scrubs don't change it.
- `required` (`boolean`): Whether a form won't submit while it's empty.
- `scrubbing` (`boolean`): Whether a scrub is moving the value.
- `atBound` (`boolean`): Whether the value is at the bound this button steps toward, like the maximum for the increment.

### 原因
`event.detail.reason` 说明值为什么变化。

- `input-change` (`Event`): Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
- `input-commit` (`KeyboardEvent | FocusEvent`): Enter, or leaving a number input, committed what was typed: a number input parses, clamps and snaps it to the step, and an autocomplete closes its suggestions on it.
- `step-key` (`KeyboardEvent`): Arrow, Page Up, Page Down, Home or End stepped a slider or a number input.
- `increment-press` (`PointerEvent | MouseEvent`): A number input's increment button was pressed, or held.
- `decrement-press` (`PointerEvent | MouseEvent`): A number input's decrement button was pressed, or held.
- `wheel` (`WheelEvent`): The mouse wheel stepped a focused number input.
- `scrub` (`PointerEvent`): A drag on a number input's scrub area.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

### 控制器
元素的 `api` property 有同样的方法。`value` property 读取和设置值。

每个写入方法都接受可选的 `{ reason, event }`，像一次按压那样触发变更事件，并在变更被取消时返回 `false`。

- `getValue()` (`() => number | null`): The value, or null when the field is empty.
- `setValue(value, options?)` (`(value: number | null, options?: NumberInputChangeOptions | undefined) => boolean`): Sets the value, as a user would. It's clamped and snapped to the step.
- `increment(options?)` (`(options?: (NumberInputChangeOptions & { large?: boolean | undefined; }) | undefined) => boolean`): Steps the value up, by `largeStep` with `{ large: true }`.
- `decrement(options?)` (`(options?: (NumberInputChangeOptions & { large?: boolean | undefined; }) | undefined) => boolean`): Steps the value down, by `largeStep` with `{ large: true }`.
- `focus()` (`() => void`): Moves focus to the input.

### 事件
事件在各自的元素上触发，不冒泡，值在 `event.detail.value` 里，`reason` 和 `event` 在它旁边。在 `valuechange` 上调用 `preventDefault()` 会取消变更。

| 成员                        | 所属              | 说明                                                   |
| --------------------------- | ----------------- | ------------------------------------------------------ |
| `value` property, attribute | `ui-number-input` | 值，为空时是 null。空的 attribute 表示空值             |
| `format` property           | `ui-number-input` | `Intl.NumberFormat` 选项                               |
| `api` property              | `ui-number-input` | [控制器](https://ui-sdk.cn/docs/web-components/components/number-input#controller)                                  |
| `valuechange` event         | `ui-number-input` | `detail: { value, reason, event, source }`，值变化时   |
| `valuecommit` event         | `ui-number-input` | `detail: { value, reason, event, source }`，交互结束时 |

## 无障碍
在原生文本输入框上遵循 [WAI-ARIA spinbutton 模式](https://www.w3.org/WAI/ARIA/apg/patterns/spinbutton/)的键盘模型，所以普通的文本编辑也能用。给输入框一个 FieldLabel 或 `aria-label`，并给两个步进按钮命名。每个按钮都用 `aria-controls` 指向输入框。

### 键盘
| 输入                                       | 增量                               |
| ------------------------------------------ | ---------------------------------- |
| ArrowUp、ArrowDown 或一个步进按钮          | `step`，默认是 1。                 |
| Shift 加方向键或按钮；Page Up 或 Page Down | `large-step`，默认十个步进。       |
| Alt（Option）加方向键                      | `small-step`，默认十分之一个步进。 |
| Home 或 End                                | 最小值或最大值，如果设置了。       |

Enter 提交输入的文字。步进按钮不在 Tab 顺序里，因为获得焦点的输入框可以通过方向键给出同样的步进。

### 经过测试的行为
下面每一行都是一个自动化测试。

**Keyboard**

- Starts with its default value, formatted.
- ArrowUp and ArrowDown step the value.
- Full-width digits from an input method commit as a number.
- Shift with an arrow key steps by the large step.
- Home and End go to the minimum and the maximum.
- Stepping stops at the bounds.
- Steps keep cents exact.
- The buttons aren't in the tab order.

**Typing**

- Typing a number changes the value.
- A typed value above the maximum is lowered when focus leaves.
- Typed text in the format is read and formatted when focus leaves.
- Typing sends change only once the text is committed.
- Letters can't be typed.
- Arrow keys step from what's typed.
- Text that isn't a number goes back to the value when focus leaves.
- The value commits when focus leaves.

**Buttons**

- The increment and decrement buttons step the value.
- A button at its bound is disabled and marked data-at-bound.
- Holding a button repeats the step.
- A press commits when the button is released.
- A disabled button is marked disabled.
- A disabled button doesn't step when clicked or held, and the other still does.
- <button disabled> inside a step button element stays disabled past a bound. Web components only.
- A button disabled while it's held stops repeating.

**State and forms**

- Submits the number as is, not formatted.
- A disabled field can't be focused or changed.
- A read-only field can be focused, but not changed.
- A required empty field blocks the form.
- The mouse wheel does nothing unless turned on.
- The mouse wheel steps a focused field when turned on.
- A canceled change keeps the value.
- A controlled field follows its value.
- Reads and writes the locale's format.

Runs in React、Vue 和 web components.

模式之外：

- Page Up and Page Down step by the large step.
- A form reset returns every field to its default.
- A typed value snaps to the step when focus leaves.
- Enter commits and formats what's typed.
- Holding an arrow key commits once, when the key comes up.
- A field with cents asks for a decimal keypad.
- A scrub steps by distance, whatever the speed.
- A scrub that doesn't move commits nothing.

Runs in React、Vue 和 web components.

在每个经过测试的框架里，屏幕阅读器听到的内容相同，由虚拟屏幕阅读器记录：

- Announcements while moving to a number input with a keyboard.

Runs in React、Vue 和 web components.
