# Field

把表单控件连接到它的标签、描述和校验错误。

字段把表单控件连接到它的标签、描述和它显示的错误，并为你接好 `id`、`for` 和 `aria-describedby`。

```ts title="input.ts"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <ui-field>
        <ui-field-label>Username</ui-field-label>
        <ui-input>
          <input name="username" placeholder="hollis" autocomplete="username" />
        </ui-input>
        <ui-field-description>Choose a unique username for your account.</ui-field-description>
      </ui-field>
    </div>
  `
}

export { mount }
```

点击 Username 让输入框获得焦点，然后输入一个名字。

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

导入组件会定义每个字段部件，包括[字段集](https://ui-sdk.cn/docs/web-components/components/field#field-sets)。放在里面的控件也要导入。在服务器上，这个导入什么都不做。

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

## 组合
用下面的组合构建一个 `ui-field`：

```text
ui-field
├── ui-field-label
├── ui-input
├── ui-field-description
└── ui-field-error
```

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

<ui-field name="username">
  <ui-field-label>Username</ui-field-label>
  <ui-input>
    <input autocomplete="username" required />
  </ui-input>
  <ui-field-description>This is your public name.</ui-field-description>
  <ui-field-error></ui-field-error>
</ui-field>
```

控件可以是我们提供的组件，比如 `<ui-input>`、`<ui-textarea>` 或 `<ui-checkbox>`。字段会找到它里面的第一个，并写入 `id`、`aria-labelledby`、`aria-describedby` 和 `aria-invalid`。

标签为控件提供名称，描述和任何显示出来的错误则说明它。

把相关的字段归入一个[字段集](https://ui-sdk.cn/docs/web-components/components/field#field-sets)：

```html
<ui-field-set>
  <fieldset>
    <legend></legend>
    <ui-field-description></ui-field-description>
    <ui-field-group>
      <ui-field></ui-field>
      <ui-field></ui-field>
    </ui-field-group>
  </fieldset>
</ui-field-set>
```

## 控件
一行文本用 `<ui-input>`，更多内容用 `<ui-textarea>`，各自包住自己的原生元素：

```html
<ui-field>
  <ui-field-label>Feedback</ui-field-label>
  <ui-textarea>
    <textarea name="feedback"></textarea>
  </ui-textarea>
</ui-field>
```

对于我们不提供的控件，比如原生 `<select>`，直接把元素放进字段，它会以同样的方式连接。[智能体](/docs/agents)只能看到我们的组件，所以它无法填写未包装的元素：有我们的组件时就用我们的。

```html
<ui-field>
  <ui-field-label>Department</ui-field-label>
  <select name="department">
    <option value="design">Design</option>
    <option value="engineering">Engineering</option>
  </select>
</ui-field>
```

字段里的 [Checkbox](/docs/web-components/components/checkbox)、[Switch](/docs/web-components/components/switch) 或 [Radio Group](/docs/web-components/components/radio) 会使用字段的标签和描述。按压标签会切换复选框或开关。单选组会把字段的标签当作自己的名称，每个单选项则保留自己的标签：

```html
<ui-field>
  <ui-switch name="mfa"></ui-switch>
  <ui-field-label>Two-factor authentication</ui-field-label>
  <ui-field-description>Ask for a code when you sign in.</ui-field-description>
</ui-field>

<ui-field>
  <ui-field-label>Plan</ui-field-label>
  <ui-radio-group name="plan" default-value="monthly">
    <label>
      <ui-radio value="monthly"></ui-radio>
      Monthly
    </label>
    <label>
      <ui-radio value="yearly"></ui-radio>
      Yearly
    </label>
  </ui-radio-group>
</ui-field>
```

## 校验
使用原生约束，比如 `required`、`type="email"` 和 `pattern`。错误会在尝试提交后出现，并随值的变化而更新。第一个无效的控件会获得焦点。

把错误留空可显示浏览器的消息；要用自己的消息，就用 `match="valueMissing"` 和 `match="typeMismatch"`。加上错误部件后，页面里的这条消息会取代浏览器原生的校验气泡。

```ts title="validation.ts"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <form data-slot="stack">
      <ui-field name="email">
        <ui-field-label>Email</ui-field-label>
        <ui-input>
          <input type="email" required placeholder="hollis@example.com" />
        </ui-input>
        <ui-field-description>
          <span data-hide="valid">We'll send you a confirmation link.</span>
          <span data-show="valid">Looks good.</span>
        </ui-field-description>
        <ui-field-error match="valueMissing">Enter your email address.</ui-field-error>
        <ui-field-error match="typeMismatch">Enter an email address like hollis@example.com.</ui-field-error>
      </ui-field>
      <ui-field name="website">
        <ui-field-label>Website</ui-field-label>
        <ui-input>
          <input type="url" required placeholder="https://example.com" />
        </ui-input>
        <ui-field-error></ui-field-error>
      </ui-field>
      <button type="submit" data-variant="solid">Subscribe</button>
    </form>
  `
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    log(root, `Subscribed ${new FormData(form).get("email")}`)
  })
}

export { mount }
```

在邮箱为空或无效时点击 Subscribe，然后改正它来清除错误。

## 来自你的代码的错误
当服务器或表单库给出错误时，传入 `invalid`。`true` 会立即显示它。清除值即可回到浏览器的校验。

给这个错误单独的文本，并把 `match` 设为 `true`。`valueMissing` 这类具名匹配仍然指原生校验。`invalid="false"` 会隐藏字段的无效状态，但不会让无效的原生控件通过校验。

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

<script type="module">
  const field = document.querySelector("ui-field")
  const serverError = document.createElement("ui-field-error")
  serverError.setAttribute("match", "true")

  function showServerError(message) {
    serverError.textContent = message
    field.append(serverError)
    field.invalid = true
  }

  field.querySelector("input").addEventListener("input", () => {
    serverError.remove()
    field.invalid = undefined
  })
</script>
```

## 必填与禁用
必填控件会给每个部件标记 `data-required`，部件的状态里也有 `required`，所以只靠 CSS 就能让标签显示标记。

禁用的字段会禁用它的控件，并给每个部件标记 `data-disabled`，就像[禁用的字段集](https://ui-sdk.cn/docs/web-components/components/field#disabled-field-sets)对它里面的每个字段所做的那样。

## 字符计数
监听控件上的 `input`，并在描述里显示它的长度。在控件上设置 `maxlength`，让这个限制生效。

```html
<ui-field>
  <ui-field-label>Bio</ui-field-label>
  <ui-textarea>
    <textarea maxlength="280"></textarea>
  </ui-textarea>
  <ui-field-description>0 / 280</ui-field-description>
</ui-field>

<script type="module">
  const bio = document.querySelector("textarea")
  const count = document.querySelector("ui-field-description")
  bio.addEventListener("input", () => {
    count.textContent = `${bio.value.length} / 280`
  })
</script>
```

## 表单
控件用自己的 `name` 提交它的值；没有 `name` 时，就用字段的 `name`。重置会恢复控件的默认值，并隐藏校验错误。禁用的控件不会包含在提交的值里。共享的表单行为见[表单](/docs/web-components/forms)。

## 字段集
字段集把相关的字段归到一个图例（legend）下，并一起禁用它们。

```ts title="field-set.ts"
import "@ui-sdk/web/field"
import "@ui-sdk/web/input"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field-set>
      <fieldset>
        <legend>Address</legend>
        <ui-field-description>We need your address to deliver your order.</ui-field-description>
        <ui-field-group>
          <ui-field name="street">
            <ui-field-label>Street address</ui-field-label>
            <ui-input><input autocomplete="street-address" /></ui-input>
          </ui-field>
          <div data-slot="grid">
            <ui-field name="city">
              <ui-field-label>City</ui-field-label>
              <ui-input><input autocomplete="address-level2" /></ui-input>
            </ui-field>
            <ui-field name="postal-code">
              <ui-field-label>Postal code</ui-field-label>
              <ui-input><input autocomplete="postal-code" /></ui-input>
            </ui-field>
          </div>
        </ui-field-group>
      </fieldset>
    </ui-field-set>
  `
}

export { mount }
```

在地址字段之间移动。它们的图例和描述为这个分组命名。

`<ui-field-set>` 包住原生 `<fieldset>` 和它的 `<legend>`，并以 `display: contents` 显示，所以字段集在脚本运行之前就有了名称，也能被禁用。让图例保持为第一个子元素。图例不是原生 `<legend>` 时，用 `<ui-field-legend>`：它仍然通过 `aria-labelledby` 为字段集命名。

直接放在字段集里、不在任何 `<ui-field>` 之内的 `<ui-field-description>` 描述的是字段集，所以焦点进入时屏幕阅读器会读出它。`<ui-field-group>` 堆叠字段，没有角色也没有状态：为分组命名和禁用的都是字段集。

## 禁用字段集
禁用字段集会禁用它的控件和嵌套的字段集。表单提交时不会包含它们的值。

```html
<ui-field-set disabled>
  <fieldset>
    <legend>Billing address</legend>
    <ui-field name="billing-street">
      <ui-field-label>Street address</ui-field-label>
      <ui-input>
        <input autocomplete="billing street-address" />
      </ui-input>
    </ui-field>
  </fieldset>
</ui-field-set>
```

## 字段集里的分组
图例会为字段集里的[复选框组](https://ui-sdk.cn/docs/web-components/components/checkbox#group)或[单选组](/docs/web-components/components/radio)命名，所以分组不需要自己的标签。

```html
<ui-field-set>
  <fieldset>
    <legend>Notifications</legend>
    <ui-checkbox-group name="notify" default-value="mentions">
      <label>
        <ui-checkbox value="mentions"></ui-checkbox>
        Mentions
      </label>
      <label>
        <ui-checkbox value="follows"></ui-checkbox>
        New followers
      </label>
    </ui-checkbox-group>
  </fieldset>
</ui-field-set>
```

## 自定义渲染
控件是你自己的元素，所以想渲染什么都行。部件没有渲染函数：用部件的数据属性来显示和隐藏内容，比如 Tailwind 里的 `in-data-invalid:inline`。空的 `<ui-field-error>` 会用当前问题的消息填充自己。

## 自定义控件
Web Components 没有 Hook：字段自己找到它的控件。它会取里面的第一个原生 `<input>`、`<select>` 或 `<textarea>`，或第一个带控件角色的元素，比如 `role="checkbox"`、`"switch"`、`"radiogroup"`、`"combobox"`、`"slider"`、`"spinbutton"`、`"textbox"` 或 `"listbox"`。它会写入该元素的 `id`、`aria-labelledby`、`aria-describedby`、`aria-invalid`、`disabled` 和数据属性，元素没有 `name` 时还会写入字段的 `name`。

所以，你自己的自定义元素只要带有这些角色之一，就会加入字段。字段只从原生 input、select、textarea 和我们自己的元素读取有效性，所以你的元素要通过里面的一个原生 input 来提交和校验，并带上自己的 `name`。

想用我们的控件所用的原语（primitive）从零构建控件，请参阅[原语](/docs/core/kernel/define-a-primitive)。

## 样式
校验用 `data-invalid` 和 `data-valid`，其余用 `data-focused`、`data-required` 和 `data-disabled`。字段的每个部件都会拿到相同的属性，所以标签可以随控件一起变红。

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

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

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### `<ui-field-label>`
`[data-slot="field-label"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

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

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### `<ui-field-description>`
`[data-slot="field-description"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### `<ui-field-error>`
`[data-slot="field-error"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### `<fieldset>`
`<ui-field-group>` 有 `data-slot="field-group"`，没有状态属性。

`[data-slot="field-set"]`

- `data-disabled`: Present when the field set is disabled, by its own prop or a `<fieldset>` around it.

### `<legend>`
`[data-slot="field-legend"]`

- `data-disabled`: Present when the field set is disabled, by its own prop or a `<fieldset>` around it.

### `<ui-field-description>` 在 `<ui-field-set>` 里
`[data-slot="field-description"]`

- `data-disabled`: Present when the field set is disabled, by its own prop or a `<fieldset>` around it.

## API 参考
props 是 kebab 命名的属性。不带值的 `invalid` 是 `true`，`invalid="false"` 是 `false`。`invalid` 也是一个 property，`undefined` 会把它留给属性，没有属性时则留给浏览器。

字段没有变更事件。从部件的数据属性里读取它的状态。加上 `debug` 属性可以记录每次状态变化及其原因。

### Field
- `name?` (`string`): The name the control submits under, when the control doesn't set its own.
- `disabled?` (`boolean`): Disables the control, and marks every part.
- `invalid?` (`boolean`): Whether the field shows as invalid, when your code decides, like a form library or an error from the server. `true` shows its errors now, `false` shows none whatever the browser thinks. Leave it out to show the browser's own validation once a submit finds the field invalid.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### FieldError
- `match?` (`boolean | ValidityKey`): When this error shows. `true` shows it always and `false` never. A validity flag, like `"valueMissing"`, shows it only for that problem of the browser's own validation. Without it, any problem shows it.

### FieldSet
- `disabled?` (`boolean`): Disables every control inside it, except those in its legend, and leaves them out of the form.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### 状态
- `disabled` (`boolean`): Whether the field is disabled, by itself or by a `<fieldset>`.
- `required` (`boolean`): Whether the control is required, read from its `required` or `aria-required`.
- `focused` (`boolean`): Whether focus is inside the control.
- `invalid` (`boolean`): Whether the field shows as invalid: `invalid` when you pass it, else the browser's validation once shown.
- `valid` (`boolean`): Whether the browser's validation passes, once shown. Always false while you pass `invalid`.

- `disabled` (`boolean`): Whether the field is disabled, by itself or by a `<fieldset>`.
- `required` (`boolean`): Whether the control is required, read from its `required` or `aria-required`.
- `focused` (`boolean`): Whether focus is inside the control.
- `invalid` (`boolean`): Whether the field shows as invalid: `invalid` when you pass it, else the browser's validation once shown.
- `valid` (`boolean`): Whether the browser's validation passes, once shown. Always false while you pass `invalid`.
- `message` (`string`): The browser's message for the current problem. Children you pass show instead.

`<ui-field-description>` 会收到字段的状态；当它描述字段集时，只收到 `disabled`。

- `disabled` (`boolean`): Whether the field set is disabled, by itself or by a field set around it. Whether the field is disabled, by itself or by a `<fieldset>`.
- `required` (`boolean | undefined`): Whether the control is required, read from its `required` or `aria-required`.
- `focused` (`boolean | undefined`): Whether focus is inside the control.
- `invalid` (`boolean | undefined`): Whether the field shows as invalid: `invalid` when you pass it, else the browser's validation once shown.
- `valid` (`boolean | undefined`): Whether the browser's validation passes, once shown. Always false while you pass `invalid`.

字段集的每个部件都会收到相同的状态。

- `disabled` (`boolean`): Whether the field set is disabled, by itself or by a field set around it.

## 无障碍
标签通过 `aria-labelledby` 为控件提供名称，控件能接受原生 `<label for>` 时还会同时用它。描述和任何显示出来的错误通过 `aria-describedby` 描述它，无效的控件带有 `aria-invalid`。下面的测试覆盖这些关联和键盘行为。

**Labelling**

- The label names the control.
- The description describes the control.
- Clicking the label of a text field focuses it.

**A label wrapping a field**

- Names the control inside it.
- Checks its control when clicked anywhere.
- Keeps the field's description on its control.
- Names a control that renders after it.
- Keeps the part's data-slot.
- Warns in development only when a label outside a field labels nothing.
- A description and an error outside a field keep their data-slot. Web components only.
- A hidden error outside a field stays hidden whatever display its class gives. Web components only.
- An error outside a field follows its match. Web components only.
- An error outside a field shows a child that arrives after it. Web components only.

**Errors**

- Stay hidden until the form tries to submit.
- Show the browser's message when they have no text of their own.
- Count another library's form-associated element inside the field.
- Describe the control while they show.
- Update as the value changes once shown.
- Update as state set from script changes the value once shown. Web components only.
- A field marked invalid shows its error right away.
- A field marked valid never shows the browser's errors.
- A form reset hides them again.
- Errors in the page replace the browser's message, and the first invalid control takes focus.

Runs in React、Vue 和 web components.

在字段集里：

- The legend names the group.
- A disabled field set disables the controls inside and leaves them out of the form.
- Enabling it again restores the controls.
- A field set disabled from the start disables its required fields.
- Fields in a disabled field set mark their parts disabled.

**Enhancements**

- The description describes the group.

Runs in React、Vue 和 web components.

在表单里：

- The form submits every checked control's name and value.
- Unchecked controls submit nothing.
- A checkbox outside the form joins it with the form attribute.
- Required controls block submission.
- A form reset returns every control to its default.
- A reset returns to the default value, not to nothing.
- A disabled fieldset disables the controls inside it.
- A read-only control still submits.
- A user's change fires native input and change events on the form.

Runs in React、Vue 和 web components.
