# Input

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

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

```tsx title="basic.tsx"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/react/field"
import { Input, InputClear, InputGroup } from "@ui-sdk/react/input"
import { XIcon } from "lucide-react"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Field name="website">
      <FieldLabel>Website</FieldLabel>
      <InputGroup>
        <span>https://</span>
        <Input
          placeholder="example.com"
          defaultValue="hollisgrant.com"
          onValueChange={(value, details) =>
            log(`${value ? `“${value}”` : "Empty"} (${details.reason})`)
          }
        />
        <InputClear aria-label="Clear website">
          <XIcon aria-hidden="true" />
        </InputClear>
      </InputGroup>
      <FieldDescription>Shown on your public profile.</FieldDescription>
    </Field>
  )
}

export { Example }
```

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

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

## 组合
用下面的组合构建 `Input` 或 `InputGroup`：

```text
Input

InputGroup
├── Input
└── InputClear
```

`Input` 渲染一个原生 `<input>`。直接传它的 type、placeholder、autocomplete 和其他原生属性。`InputGroup` 在它周围放文字或按钮，`InputClear` 把它清空。

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

```tsx
import { Input, InputClear, InputGroup } from "@ui-sdk/react/input"

function Example() {
  return (
    <InputGroup>
      <Input type="search" aria-label="Search" />
      <InputClear aria-label="Clear search" />
    </InputGroup>
  )
}

export { Example }
```

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

```tsx
<Field name="username">
  <FieldLabel>Username</FieldLabel>
  <Input autoComplete="username" />
  <FieldDescription>
    Choose a unique username for your account.
  </FieldDescription>
</Field>
```

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

```tsx
<Field disabled>
  <FieldLabel>Email</FieldLabel>
  <Input type="email" defaultValue="hollis@example.com" />
</Field>

<Field>
  <FieldLabel>Profile URL</FieldLabel>
  <Input readOnly value="example.com/hollis" />
</Field>
```

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

```tsx
<Field name="email" invalid={emailTaken ? true : undefined}>
  <FieldLabel>Email</FieldLabel>
  <Input type="email" required />
  <FieldError match="valueMissing">Enter your email address.</FieldError>
  <FieldError match>That email is already in use.</FieldError>
</Field>
```

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

```tsx
<InputGroup>
  <span>https://</span>
  <Input aria-label="Website" placeholder="example" />
  <span>.com</span>
</InputGroup>
```

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

```tsx
<InputGroup>
  <Input type="search" aria-label="Search people" />
  <InputClear aria-label="Clear search">
    <XIcon aria-hidden="true" />
  </InputClear>
</InputGroup>
```

## 受控
传 `value` 和 `onValueChange` 来受控输入框。原生 `onChange` 仍然有效。

```tsx
const [name, setName] = React.useState("Hollis Grant")

<Input value={name} onValueChange={(value) => setName(value)} />
```

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

## 过滤输入的内容
在值变更回调里调用 `details.cancel()` 来拒绝一次变更。之前的文字和光标位置会恢复。

```tsx
<Input
  inputMode="numeric"
  maxLength={6}
  onValueChange={(value, details) => {
    if (!/^\d*$/.test(value)) details.cancel()
  }}
/>
```

## 控制器
用 `createInputController()` 处理输入框之外的动作。它的方法通过与输入相同的变更回调更新输入框。

```tsx
const [message] = React.useState(createInputController)

<Input controller={message} aria-label="Message" />
<button onClick={() => message.setValue("On my way!")}>Quick Reply</button>
<button onClick={() => message.clear()}>Clear</button>
<button onClick={() => message.focus()}>Focus</button>
```

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

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

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

## 数据属性
### 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.

### InputGroup
`[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.

### InputClear
`[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 参考
Props 与下面相同，作为 React props，再加上所有原生 input prop。

### Input
- `value?` (`string`): The value, for a controlled field.
- `defaultValue?` (`string`): The value it starts with. A form reset returns here.
- `onValueChange?` (`((value: string, details: ChangeDetails<InputValueChangeReason>) => void)`): 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.

`InputGroup` 和 `InputClear` 会收到组内输入框的状态。

- `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.

### 控制器
用 `createInputController()` 创建一个，并作为 `controller` 传入。

- `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.
