# 表单字段

## 使用方法

`Field` 为控件补齐完整的字段结构，包括标签、补充说明、必填或可选提示和状态消息。它适合包装原生输入框、自研控件或第三方组件，让这些控件拥有与样式输入框一致的字段外观和无障碍关联。`TextInput` 已内置 `Field`，使用 `TextInput` 时直接传入字段属性即可，无需额外包裹。

下面的示例用 `Field` 包装一个原生滑块，通过默认插槽提供的关联 ID 把标签和说明挂到控件上：

```vue
<script setup lang="ts">
import { Field } from '@astryx-vue/core/Field'
import { shallowRef, useId } from 'vue'

const volume = shallowRef(50)
const inputId = `volume-${useId()}`
</script>

<template>
  <Field :input-id="inputId" label="Volume" description="Set playback volume.">
    <template #default="field">
      <input
        :id="field.inputId" v-model.number="volume" type="range"
        :aria-labelledby="field.labelId" :aria-describedby="field.describedBy"
      >
    </template>
  </Field>
</template>
```

### 结构

- **标签**: 标识字段的文字。为了无障碍始终渲染，也可以只在视觉上隐藏。
- **说明**: 标签和输入之间的辅助文字，说明该填什么。
- **控件插槽**: 还没有自己的字段外壳的自定义、原生或第三方控件。
- **状态消息**: 行内校验反馈，带上错误、警告或成功，以及一条消息。
- **可选或必填指示**: 标签旁边的徽章，表示字段是可选还是必填。
- **标签提示**: 标签末尾的信息图标，用提示说明这个字段。

## 最佳实践

| 指引 | 实践 |
| --- | --- |
| 推荐 | 包裹需要标签、辅助文字、必填或可选标识，或校验状态的自定义控件、原生输入框或第三方组件。 |
| 推荐 | 必须提供标签以保证无障碍，即使用 isLabelHidden 将其隐藏。 |
| 推荐 | 使用 inputID 和 descriptionID，将标签和描述通过 htmlFor 与 aria-describedby 关联到内部控件。 |
| 避免 | 在 TextInput、Typeahead、Select、DateInput 或 TextArea 等样式输入框外层嵌套 Field。这些组件已自带 Field 外壳。 |
| 避免 | 在滑块、开关或复选框等无边框控件上使用 attached 状态变体。应使用 detached，使消息不与控件重叠。 |
| 避免 | 在同一字段上同时设置 isOptional 和 isRequired。 |
| 避免 | 隐藏标签，又不提供其他方式让用户理解字段用途。 |

## 示例

### 必填和可选

必填的用户名，以及可选的备用邮箱。

```vue
<script setup lang="ts">
import { VStack } from '@astryx-vue/core/Stack'
import { TextInput } from '@astryx-vue/core/TextInput'
import { ref } from 'vue'

const username = ref('')
const email = ref('')
</script>

<template>
  <VStack :gap="4" width="100%" style="max-width: 320px">
    <TextInput v-model="username" label="Username" is-required placeholder="Enter your username" />
    <TextInput v-model="email" label="Backup email" is-optional placeholder="you@example.com" />
  </VStack>
</template>
```

### 校验状态

邮箱、用户名和 API 密钥上的错误、警告和成功。

```vue
<script setup lang="ts">
import { VStack } from '@astryx-vue/core/Stack'
import { TextInput } from '@astryx-vue/core/TextInput'
import { ref } from 'vue'

const email = ref('bad-email')
const username = ref('admin')
const apiKey = ref('sk-live-abc123')
</script>

<template>
  <VStack :gap="4" width="100%" style="max-width: 320px">
    <TextInput
      v-model="email"
      label="Email"
      description="Enter your work email"
      :status="{ type: 'error', message: 'Please enter a valid email address' }"
    />
    <TextInput
      v-model="username"
      label="Username"
      description="Choose a unique username"
      :status="{ type: 'warning', message: 'This username is reserved for administrators' }"
    />
    <TextInput
      v-model="apiKey"
      label="API Key"
      description="Paste your API key"
      :status="{ type: 'success', message: 'API key is valid and active' }"
    />
  </VStack>
</template>
```

### 说明文字

邮箱和密码标签下方的辅助说明。

```vue
<script setup lang="ts">
import { VStack } from '@astryx-vue/core/Stack'
import { TextInput } from '@astryx-vue/core/TextInput'
import { ref } from 'vue'

const email = ref('')
const password = ref('')
</script>

<template>
  <VStack :gap="4" width="100%" style="max-width: 320px">
    <TextInput
      v-model="email"
      label="Email"
      description="We'll send a confirmation link to this address"
      placeholder="you@example.com"
    />
    <TextInput
      v-model="password"
      label="Password"
      description="At least 8 characters with one uppercase letter"
      placeholder="Create a password"
    />
  </VStack>
</template>
```

## 关联 ID

默认插槽提供以下参数：

- `inputId`：控件 ID。
- `labelId`：标签 ID。
- `descriptionId`：说明 ID。
- `statusId`：状态消息 ID。
- `describedBy`：说明与状态消息的 ID 列表。

1. 将 `inputId` 传给控件的 `id`。
2. 将 `labelId` 传给控件的 `aria-labelledby`。
3. 将 `describedBy` 传给控件的 `aria-describedby`。

`Field` 不会自动修改插槽中的控件。

## 分组标签

1. 为 `Field` 设置 `isGroupLabel`。
2. 将 `labelId` 传给分组的 `aria-labelledby`。

隐藏标签时，界面必须提供说明字段用途的上下文。

## 使用范围

应用负责以下行为：

- 校验控件的值。
- 提交表单。
- 禁用控件。

## Field Props

| 名称 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `label` | `string` | 必需 | 字段的可见标签；即使视觉上隐藏，也仍作为控件的无障碍名称。 |
| `isLabelHidden` | `boolean` | false | 在视觉上隐藏标签和说明，但保留它们与控件的无障碍关联。 |
| `description` | `string` | — | 显示在标签下方、控件上方的补充说明。 |
| `isDisabled` | `boolean` | false | 禁用状态。Field 和 FieldLabel 只调整标签样式，控件本身由使用方禁用。 |
| `isOptional` | `boolean` | false | 显示“可选”提示；与 `isRequired` 同时设置时优先。 |
| `isRequired` | `boolean` | false | 显示“必填”提示；在 `TextInput` 中还会同时设置 `aria-required`。 |
| `labelIcon` | `IconName \| Component` | — | 显示在标签前的 Vue 图标组件；`labelIcon` 插槽优先于该属性。 |
| `labelTooltip` | `string` | — | 标签旁的信息按钮，提示内容支持悬停、键盘聚焦和点击查看。 |
| `optionalLabel` | `string` | Optional | “可选”提示的本地化文字。 |
| `requiredLabel` | `string` | Required | “必填”提示的本地化文字。 |
| `inputId` | `string` | 必需 | 被标记控件的 ID，必须与内部控件的 `id` 一致。 |
| `labelId` | `string` | {inputId}-label | 标签自身的 ID；作为分组标签时，由分组容器通过 `aria-labelledby` 引用。 |
| `descriptionId` | `string` | {inputId}-description | 说明文字的 ID，控件通过 `aria-describedby` 引用它。 |
| `isGroupLabel` | `boolean` | false | 为 `radiogroup` 等分组输出 `span` 而不是 `label`，避免把分组当作单个控件。 |
| `status` | `FieldStatusInput` | — | 字段状态，包含状态类型、可选的消息文本和自定义 `messageId`。 |
| `statusVariant` | `'attached' \| 'detached' \| 'tooltip'` | attached | `tooltip` 隐藏行内消息框，但保留描述与屏幕阅读器播报，提示按钮由内部控件自行提供。 |
| `width` | `number \| string` | auto | 整个字段的宽度，传入数字时按像素处理。 |

## FieldLabel Props

| 名称 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `label` | `string` | 必需 | 可见标签。隐藏时仍为控件提供名称。 |
| `isLabelHidden` | `boolean` | false | 视觉上隐藏标签和说明，保留无障碍关联。 |
| `description` | `string` | — | 标签下方、控件上方的补充说明。 |
| `isDisabled` | `boolean` | false | 禁用状态。Field/FieldLabel 只改变标签样式，控件由使用方禁用。 |
| `isOptional` | `boolean` | false | 显示可选提示。与 isRequired 同时设置时优先。 |
| `isRequired` | `boolean` | false | 显示必填提示。TextInput 同时设置 aria-required。 |
| `labelIcon` | `IconName \| Component` | — | 标签前的 Vue 图标组件。labelIcon 插槽优先。 |
| `labelTooltip` | `string` | — | 标签旁的信息按钮，支持悬停、键盘聚焦和点击。 |
| `optionalLabel` | `string` | Optional | 可选提示的本地化文字。 |
| `requiredLabel` | `string` | Required | 必填提示的本地化文字。 |
| `inputId` | `string` | 必需 | 被标记控件的 ID。必须与控件 id 相同。 |
| `labelId` | `string` | {inputId}-label | 标签自身 ID。分组使用 aria-labelledby 引用。 |
| `descriptionId` | `string` | {inputId}-description | 说明 ID。控件通过 aria-describedby 引用。 |
| `isGroupLabel` | `boolean` | false | 为 radiogroup 等分组输出 span，避免把分组当作单个控件。 |

## FieldStatus Props

| 名称 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `type` | `'error' \| 'warning' \| 'success'` | 必需 | 状态语义与配色。 |
| `message` | `string` | 必需 | 状态文字。空字符串不显示消息框。 |
| `variant` | `'attached' \| 'detached'` | attached | attached 与有边框的控件重叠。detached 适合滑块、开关等。 |
| `isVisuallyHidden` | `boolean` | false | 只保留无障碍描述和播报，用于控件自行提供 tooltip 的场景。 |

## 插槽

Field 的 default 为必需插槽，接收以下参数：

```ts
interface FieldSlotProps {
  inputId: string
  labelId: string
  descriptionId?: string
  statusId?: string
  describedBy?: string
}
```

- `Field` 和 `FieldLabel` 提供 `labelIcon` 插槽。
- `labelIcon` 插槽覆盖同名属性。
- 图标只作装饰用途。
- `FieldStatus` 不提供插槽。文字通过 `message` 传入。

## 状态消息

```ts
interface FieldStatusInput {
  type: 'error' | 'warning' | 'success'
  message?: string
  messageId?: string
}
```

### 播报规则

- `error` 使用 `aria-live="assertive"` 区域。
- `warning` 使用 `aria-live="polite"` 区域。
- `success` 使用 `aria-live="polite"` 区域。
- 消息变化时，组件重新播报消息。
- 消息为空时，组件清空播报区域。
- 视觉消息不重复设置 `aria-live`。

### 消息布局

- `attached`：消息紧贴控件。必须放在 `Field` 内有边框的控件下方。
- `detached`：消息与控件分离。消息包含状态图标。
- `Field` 的 `tooltip` 模式：隐藏文字仍用于描述和播报。内部控件负责提供提示按钮。

独立使用 `FieldStatus` 时，使用 `detached`。

## 事件

这三个组件不声明自定义事件。

## 模板引用

每个组件都公开 `element`：

| 组件 | 元素 |
| --- | --- |
| `Field` | 字段根 `div`。 |
| `FieldLabel` | 标签元素或分组 `span`。 |
| `FieldStatus` | 视觉消息元素。 |

挂载前，`element` 为 `null`。
没有消息时，`FieldStatus.element` 为 `null`。

## 原生属性

| 组件 | 属性接收位置 |
| --- | --- |
| `Field` | 字段根元素。 |
| `FieldLabel` | 标签组。 |
| `FieldStatus` | 消息元素。 |

以下内容必须直接传给内部控件：

- `name`。
- `required`。
- `disabled`。
- 控件事件监听器。

## 导入

```ts
import type { FieldProps, FieldSlotProps, FieldStatusInput } from '@astryx-vue/core/Field'
import { Field, FieldLabel } from '@astryx-vue/core/Field'
import { FieldStatus } from '@astryx-vue/core/FieldStatus'
import '@astryx-vue/themes/neutral.css'
```

## 主题

- `--astryx-spacing-1`：字段内容间距。
- `--astryx-spacing-2`：分离状态消息的内边距。
- `--astryx-radius-element`：状态消息圆角。
- `--astryx-color-text-secondary`：辅助文字颜色。
- `--astryx-text-label-size`：标签字号。
- `--astryx-text-supporting-size`：说明与状态消息字号。

状态颜色与 `TextInput` 共用变量。完整列表见 [TextInput 校验状态](/components/text-input/props#校验状态)。
