# Input

输入文本、添加清除按钮，并把值连接到表单或状态。

输入框是原生的文本框，用来输入姓名、邮箱地址或搜索词这样的短值。它可以在字段和表单里使用，并加上清除按钮、输入框周围的文字，以及变更原因。

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

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field name="website">
      <ui-field-label>Website</ui-field-label>
      <ui-input-group>
        <span>https://</span>
        <ui-input>
          <input placeholder="example.com" value="hollisgrant.com" />
        </ui-input>
        <ui-input-clear>
          <button type="button" aria-label="Clear website">
            ${createElement(X, { "aria-hidden": "true" }).outerHTML}
          </button>
        </ui-input-clear>
      </ui-input-group>
      <ui-field-description>Shown on your public profile.</ui-field-description>
    </ui-field>
  `
  root.querySelector("ui-input")!.addEventListener("valuechange", (event) => {
    const { value, reason } = event.detail
    log(root, `${value ? `“${value}”` : "Empty"} (${reason})`)
  })
}

export { mount }
```

修改 website，然后按 Clear website。文字被清除，焦点回到输入框，控制台记录原因。按 https:// 也会让输入框获得焦点。

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

导入组件会定义它的元素。在服务器上，导入什么也不做。

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

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

```text
ui-input
└── input

ui-input-group
├── ui-input
│   └── input
└── ui-input-clear
    └── button
```

`<ui-input>` 包住你自己的 `<input>`，所以把它的 type、placeholder、autocomplete 和其他原生属性放在 input 上。`<ui-input-group>` 在它周围放文字或按钮，`<ui-input-clear>` 包住一个把它清空的按钮。

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

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

<ui-input-group>
  <ui-input><input type="search" aria-label="Search" /></ui-input>
  <ui-input-clear
    ><button type="button" aria-label="Clear search"></button
  ></ui-input-clear>
</ui-input-group>
```

## 字段
把输入框包进 [Field](/docs/web-components/components/field)，给它一个可见的标签、描述和错误信息。输入框没有 `name` 时，字段也会提供自己的 `name`。

```html
<ui-field name="username">
  <ui-field-label>Username</ui-field-label>
  <ui-input><input autocomplete="username" /></ui-input>
  <ui-field-description
    >Choose a unique username for your account.</ui-field-description
  >
</ui-field>
```

## 禁用与只读
在原生 input 或它的字段上设置 `disabled`，阻止编辑，并把它移出 Tab 顺序和提交的值。`readonly` 的输入框仍然可以聚焦、选中和提交。

```html
<ui-field disabled>
  <ui-field-label>Email</ui-field-label>
  <ui-input><input type="email" value="hollis@example.com" /></ui-input>
</ui-field>

<ui-field>
  <ui-field-label>Profile URL</ui-field-label>
  <ui-input><input readonly value="example.com/hollis" /></ui-input>
</ui-field>
```

## 校验
使用 `required`、`type="email"` 和 `pattern` 这样的原生约束。提交尝试之后，字段会显示错误，并随值的变化更新它。对于应用自己判定的错误，设置字段的 `invalid` property；输入框会得到 `aria-invalid`。[Field](https://ui-sdk.cn/docs/web-components/components/field#validation) 介绍了错误部件和它们的匹配方式。

```html
<ui-field name="email">
  <ui-field-label>Email</ui-field-label>
  <ui-input><input type="email" required /></ui-input>
  <ui-field-error match="valueMissing"
    >Enter your email address.</ui-field-error
  >
  <ui-field-error match="true">That email is already in use.</ui-field-error>
</ui-field>
```

```ts
document.querySelector("ui-field")!.invalid = emailTaken ? true : undefined
```

## 输入框组
用 `<ui-input-group>` 在输入框周围放文字或按钮。按压组里的文字会让输入框获得焦点。这些文字是显示内容，不属于提交的值。

```html
<ui-input-group>
  <span>https://</span>
  <ui-input><input aria-label="Website" placeholder="example" /></ui-input>
  <span>.com</span>
</ui-input-group>
```

## 清除按钮
`<ui-input-clear>` 在有可清除的文字时显示。按压它的按钮会清空值，报告 `clear-press`，并把焦点还给输入框。`valuechange` 和原生 `input` 监听器也会收到这次变更。在有内容的输入框里按 Escape 也会以同样的方式清除它，所以包住它的对话框只会在输入框清空后才关闭。

```html
<ui-input-group>
  <ui-input><input type="search" aria-label="Search people" /></ui-input>
  <ui-input-clear>
    <button type="button" aria-label="Clear search">
      <svg aria-hidden="true">…</svg>
    </button>
  </ui-input-clear>
</ui-input-group>
```

## 受控
设置元素的 `value` property，并监听 `valuechange`，把文字保存在你自己的状态里。原生 `input` 事件仍然有效。

```ts
const input = document.querySelector("ui-input")!
input.value = "Hollis Grant"
input.addEventListener("valuechange", (event) => setName(event.detail.value))
```

受控状态的通用约定见[状态与事件](/docs/web-components/state-and-events)。Input 的[原因](https://ui-sdk.cn/docs/web-components/components/input#reasons)区分输入、清除、重置和控制器变更。

## 过滤输入的内容
在 `valuechange` 监听器里调用 `event.preventDefault()` 来拒绝一次变更。之前的文字和光标位置会恢复。

```html
<ui-input><input inputmode="numeric" maxlength="6" /></ui-input>
```

```ts
input.addEventListener("valuechange", (event) => {
  if (!/^\d*$/.test(event.detail.value)) event.preventDefault()
})
```

## 控制器
用元素的 `api` 处理输入框之外的动作。它的方法通过与输入相同的 `valuechange` 事件更新输入框。

```html
<ui-input><input aria-label="Message" /></ui-input>
<button type="button" data-action="reply">Quick Reply</button>
<button type="button" data-action="clear">Clear</button>
<button type="button" data-action="focus">Focus</button>
```

```ts
const message = document.querySelector("ui-input")!.api
document
  .querySelector('[data-action="reply"]')!
  .addEventListener("click", () => message.setValue("On my way!"))
document
  .querySelector('[data-action="clear"]')!
  .addEventListener("click", () => message.clear())
document
  .querySelector('[data-action="focus"]')!
  .addEventListener("click", () => message.focus())
```

[控制器](/docs/web-components/controllers)介绍了元素的 `api`。

## 密码与文件
用 [Password Input](/docs/web-components/components/password-input) 显示和隐藏密码。原生文件输入框可以用 `type="file"`；需要拖放、预览和校验时，用 [File Input](/docs/web-components/components/file-input)。

## 样式
每个部件都有一个 `data-slot`，比如 `input-group`，并通过[数据属性](https://ui-sdk.cn/docs/web-components/components/input#data-attributes)下列出的属性显示状态。在输入框上使用 `data-filled`、`data-disabled`、`data-readonly` 和 `data-required`，在字段内部还会用到字段的校验和焦点属性。要为组设置焦点环，请给 `:has(input:focus-visible)` 写样式，这样组里获得焦点的按钮会保留自己的焦点环。

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

- `data-filled`: Present while the field holds any text.
- `data-disabled`: Present when the field is disabled, by its own prop or its Field.
- `data-readonly`: Present when the field is read-only.
- `data-required`: Present when the field is required.

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

- `data-filled`: Present while the field in the group holds any text.
- `data-disabled`: Present while the field in the group is disabled, by itself or a `<fieldset>`.
- `data-readonly`: Present while the field in the group is read-only.

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

- `data-filled`: Present while the field in the group holds any text.
- `data-disabled`: Present while the field in the group is disabled, by itself or a `<fieldset>`.
- `data-readonly`: Present while the field in the group is read-only.

## API 参考
把原生属性放在 `<input>` 上，其中 `value` 是默认值。`<ui-input>` 元素的 `value` property 读写文字，它的 `api` 带有控制器的方法。`onValueChange` 是 `valuechange` 事件，它不冒泡：`event.detail` 里有 `value` 和 `reason`，`preventDefault()` 会取消这次变更。

### Input
- `value?` (`string`): The value, for a controlled field.
- `defaultValue?` (`string`): The value it starts with. A form reset returns here.
- `valuechange event`: Called when the user changes the value: typing (`"input-change"`), a Clear part (`"clear-press"`), a form reset (`"reset"`) or a controller (`"imperative"`). `details.cancel()` keeps the value as it was.
- `controller?` (`object`): Reads and writes the field from anywhere. Create one with `createInputController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

- `disabled?` (`boolean`): Disables the field.
- `readOnly?` (`boolean`): Makes the field read-only.
- `required?` (`boolean`): Makes the field required.

### InputGroup
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### InputClear
包住一个 `<button>`，清空它所在组里的输入框并让它获得焦点。只有存在可清除的文字时它才显示。

### 状态
- `filled` (`boolean`): Whether the field holds any text.
- `disabled` (`boolean`): Whether the field is disabled.
- `readOnly` (`boolean`): Whether the field is read-only.
- `required` (`boolean`): Whether the field is required.

`<ui-input-group>` 和 `<ui-input-clear>` 会收到组内输入框的状态。

- `filled` (`boolean`): Whether the field in the group holds any text.
- `disabled` (`boolean`): Whether the field in the group is disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether the field in the group is read-only.

### 原因
- `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.
- `clear-press` (`MouseEvent | KeyboardEvent`): A Clear part was pressed, like on an input, a select or a combobox.
- `reset` (`none`): A form reset.
- `imperative` (`none`): A controller or `api` call.

### 控制器
`<ui-input>` 元素的 `api` property 包含这些方法。

- `getValue()` (`() => string`): The current value.
- `setValue(value, options?)` (`(value: string, options?: ChangeOptions<InputValueChangeReason> | undefined) => boolean`): Sets the value as if the user typed it, so `input` fires. Returns false when the change was canceled or nothing changed.
- `clear(options?)` (`(options?: ChangeOptions<InputValueChangeReason> | undefined) => boolean`): Empties the field, as if the user deleted the text, so `input` fires. Returns false when the change was canceled or nothing changed.
- `focus()` (`() => void`): Moves focus to the field.

## 无障碍
给输入框一个可见的字段标签或 `aria-label`，并给清除按钮一个无障碍名称。原生输入框保留标准的文本编辑、选择、自动完成和表单行为。

- The label names the input and the description describes it.
- Clicking the label focuses the input.
- An invalid input is marked once the form tries to submit.
- Data-filled follows the text.
- An input group's clear button shows only while there's text.
- <ui-input>'s value property writes the field quietly, and its api reports. Web components only.

**Enhancements**

- Changes report their reason: typing, then a reset.
- A canceled change keeps the text as it was.
- A canceled change keeps a controlled input's text as it was.
- A canceled change waits for an IME to finish before the text goes back.
- A controlled input keeps every keystroke.
- A required input marks its label required.

**Input group**

- The clear button empties the field, reports why, and returns focus.
- Escape empties a filled field first, and a dialog around it hears the next one.
- Pressing the group's text focuses its field.
- The clear button hides while its field is disabled.

Runs in React、Vue 和 web components.
