# 文本输入框

## 使用方法

`TextInput`（单行文本输入框）供用户输入一行简短文字，例如电子邮箱、姓名、搜索词或密码等。它内置了 `Field` 组件，会自动把标签文字、辅助说明以及校验报错信息与输入框关联在一起。平时只需配合 `v-model` 绑定输入值即可：

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

const email = shallowRef('')
</script>

<template>
  <TextInput v-model="email" label="邮箱" type="email" auto-complete="email" />
</template>
```

**什么时候用：**
- 需要用户输入较短的一行文字时（如登录账号、联系方式、单行搜索）。

**什么时候不要用：**
- 需要输入文章、留言或详细备注等多行长篇内容时，请改用多行文本域 [TextArea](/components/text-area)。
- 需要用户从预设列表中挑选已有选项时，请改用 [Selector](/components/selector) 或下拉菜单。
- 需要完全自定义输入控件的外壳与结构时，可以直接使用底层原子组件 [Field](/components/field)。

主题只需在整个应用的主入口（如 `main.ts`）引入一次：

```ts
import '@astryx-vue/themes/neutral.css'
```

### 结构

- **标签**: 标识字段的文字。即使视觉上隐藏，为了无障碍也始终渲染。
- **说明**: 标签和输入之间的辅助文字，补充语境或格式。
- **起始图标**: 输入框里的前导图标，暗示期望的内容，比如搜索用的放大镜。
- **占位**: 输入为空时的提示文字。聚焦后消失。
- **清除按钮**: 尾部的 × 按钮，清空值并把焦点交回输入。
- **转圈**: 服务端校验这类异步操作进行时出现的加载指示。
- **状态图标**: 尾部图标，表示错误、警告或成功，用来传达校验状态。

## 最佳实践

| 指引 | 实践 |
| --- | --- |
| 推荐 | 必须提供可见的标签，让用户知道该字段的用途。只有上下文已经明确时才隐藏标签，例如带放大镜图标的搜索框。 |
| 推荐 | 使用带消息的校验状态，说明出了什么问题。“邮箱必须包含 @” 比仅把边框变红更清楚。 |
| 推荐 | 输入框尺寸要与预期内容长度相符，让用户判断该输入多少内容。邮编用 small，姓名用 medium，URL 用 large。 |
| 推荐 | 为搜索和筛选输入框添加清除按钮，让用户无需全选文字即可快速重置。 |

## 示例

### 图标

姓名、邮箱和密码字段，前面各有一个图标。

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

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

<template>
  <div style="width: 300px; max-width: 100%">
    <VStack :gap="3">
      <TextInput v-model="name" label="Full name" placeholder="Sarah Chen">
        <template #icon>
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z" />
          </svg>
        </template>
      </TextInput>
      <TextInput v-model="email" type="email" label="Email" placeholder="sarah@company.com">
        <template #icon>
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 0 1-2.25 2.25h-15a2.25 2.25 0 0 1-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25m19.5 0v.243a2.25 2.25 0 0 1-1.07 1.916l-7.5 4.615a2.25 2.25 0 0 1-2.36 0L3.32 8.91a2.25 2.25 0 0 1-1.07-1.916V6.75" />
          </svg>
        </template>
      </TextInput>
      <TextInput v-model="password" type="password" label="Password" placeholder="Enter your password">
        <template #icon>
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" d="M16.5 10.5V6.75a4.5 4.5 0 1 0-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 0 0 2.25-2.25v-6.75a2.25 2.25 0 0 0-2.25-2.25H6.75a2.25 2.25 0 0 0-2.25 2.25v6.75a2.25 2.25 0 0 0 2.25 2.25Z" />
          </svg>
        </template>
      </TextInput>
    </VStack>
  </div>
</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 query = ref('')
const filter = ref('design systems')
</script>

<template>
  <div style="width: 300px; max-width: 100%">
    <VStack :gap="3">
      <TextInput v-model="query" label="Search field" placeholder="Search projects…" has-clear>
        <template #icon>
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z" />
          </svg>
        </template>
      </TextInput>
      <TextInput v-model="filter" label="Search field with value" placeholder="Filter…" has-clear>
        <template #icon>
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" d="m21 21-5.197-5.197m0 0A7.5 7.5 0 1 0 5.196 5.196a7.5 7.5 0 0 0 10.607 10.607Z" />
          </svg>
        </template>
      </TextInput>
    </VStack>
  </div>
</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 sm = ref('')
const md = ref('')
const lg = ref('')
</script>

<template>
  <div style="width: 300px; max-width: 100%">
    <VStack :gap="3">
      <TextInput v-model="sm" label="Small" placeholder="Enter a value" size="sm" />
      <TextInput v-model="md" label="Medium" placeholder="Enter a value" size="md" />
      <TextInput v-model="lg" label="Large" placeholder="Enter a value" size="lg" />
    </VStack>
  </div>
</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 error = ref('sarah@')
const warning = ref('sarah_chen')
const success = ref('https://sarahchen.dev')
const errorOnly = ref('test')
const disabled = ref('')
const loading = ref('sarahc')
</script>

<template>
  <div style="width: 300px; max-width: 100%">
    <VStack :gap="3">
      <TextInput
        v-model="error"
        label="Error message"
        placeholder="Enter a value"
        :status="{ type: 'error', message: 'Please enter a valid email address.' }"
      />
      <TextInput
        v-model="warning"
        label="Warning message"
        placeholder="Enter a value"
        :status="{ type: 'warning', message: 'This username is already taken — try adding a number.' }"
      />
      <TextInput
        v-model="success"
        label="Success message"
        placeholder="Enter a value"
        :status="{ type: 'success', message: 'URL is valid and reachable.' }"
      />
      <TextInput
        v-model="errorOnly"
        label="Status without message"
        placeholder="Enter a value"
        :status="{ type: 'error' }"
      />
      <TextInput v-model="disabled" label="Disabled field" placeholder="Enter a value" is-disabled />
      <TextInput v-model="loading" label="Loading field" is-loading />
    </VStack>
  </div>
</template>
```

### 状态位置

状态说明可以贴在字段上，也可以浮在字段下方。

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

const attached = ref('sarah@')
const detached = ref('sarah@')
</script>

<template>
  <div style="width: 640px; max-width: 100%">
    <HStack :gap="5">
      <VStack :gap="2">
        <Text type="label">
          attached (default)
        </Text>
        <TextInput
          v-model="attached"
          label="Email"
          placeholder="you@example.com"
          status-variant="attached"
          :status="{ type: 'error', message: 'Please enter a valid email address.' }"
        />
        <Text type="supporting">
          Message overlaps directly below the input.
        </Text>
      </VStack>
      <VStack :gap="2">
        <Text type="label">
          detached
        </Text>
        <TextInput
          v-model="detached"
          label="Email"
          placeholder="you@example.com"
          status-variant="detached"
          :status="{ type: 'error', message: 'Please enter a valid email address.' }"
        />
        <Text type="supporting">
          Message floats below as a separate element with spacing.
        </Text>
      </VStack>
    </HStack>
  </div>
</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 described = ref('')
const password = ref('hunter42')
const email = ref('sarah@example.com')
const tooltip = ref('')
const required = ref('')
const optional = ref('')
</script>

<template>
  <div style="width: 300px; max-width: 100%">
    <VStack :gap="3">
      <TextInput
        v-model="described"
        label="Default field"
        placeholder="Enter your email"
        description="Descriptions can be used to provide additional information about a field."
      />
      <TextInput v-model="password" type="password" label="Password field" placeholder="Enter a value" />
      <TextInput v-model="email" type="email" label="Email field" placeholder="Enter a value" />
      <TextInput
        v-model="tooltip"
        label="Field tooltip"
        placeholder="Enter your API key"
        label-tooltip="Your unique API key for authentication. Keep this secret!"
      />
      <TextInput v-model="required" label="Required field" placeholder="Enter your username" is-required />
      <TextInput v-model="optional" label="Optional field" placeholder="Enter your nickname" is-optional />
    </VStack>
  </div>
</template>
```

## 给外壳和本体加样式

`TextInput` 有两个可以加样式的部件：

- **外壳**：`Field` 那一层，包着标签、输入框和状态消息。用 `container-class` 和 `container-style`。
- **本体**：画边框和背景、里面装着图标和清除按钮的那个盒子。用 `control-class` 和 `control-style`。

两组属性各落各的位置，不会改道，也不会落到原生 `<input>` 上。

```vue
<TextInput
  v-model="name"
  label="姓名"
  container-class="my-field"
  :control-style="{ borderRadius: '12px' }"
/>
```

直接写在 `` 上的 `class` 和 `style` 仍然落在本体上，和 `control-class` 一起生效。`id`、`data-*`、`aria-*` 和事件监听则落在原生 `<input>` 上。

在 `InputGroup` 里，以及横向标签的 `FormLayout` 里，字段没有外壳，`container-*` 不生效，开发环境会给出警告。要给 `InputGroup` 加样式，请直接写在 `InputGroup` 上。

## 无障碍

`label` 是必填项。屏幕阅读器靠它说明这个字段是做什么的；`placeholder` 只在输入框为空时可见，用户一开始输入就消失，不能用它代替标签。

标签、说明和状态消息由组件通过 ARIA 属性串联起来，辅助技术能把它们当成一个整体读出：

- `description` 与 `status.message` 关联到 `aria-describedby`。
- 出错时自动设置 `aria-invalid`。
- 字段必填时自动设置 `aria-required`。

`isRequired` 负责显示必填提示并设置 ARIA 状态。如果还需要浏览器原生的必填校验——例如依赖表单提交来拦截未填写的字段——再额外传入 `required`。

## 中文输入法

拼音、注音这类输入法在用户敲下字母时，文字还处在候选状态，选定候选词之后才算真正输入完成。组件会区分「正在组合」和「已经输入」，避免把半成品当成最终值：

- 候选词尚未确定时，组件不更新 `v-model`，输入框里显示的仍是组合中的文字。
- `compositionend` 触发后，也就是用户选定候选词的那一刻，组件才把最终文字同步到 `v-model`。
- 用 Enter 选定候选词不会触发 `enter` 事件；用户再次按下 Enter 提交表单时，`enter` 才正常触发。

这样，依赖 `v-model` 的校验和提交逻辑就不会在用户输入到一半时被提前打断。

## TextInput Props

| 名称 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `modelValue` | `string` | 必需 | 输入框的当前值，一般通过 v-model 绑定。 |
| `label` | `string` | 必需 | 字段的可见标签。即使被隐藏，也会作为控件的名称提供给辅助技术。 |
| `isLabelHidden` | `boolean` | false | 在视觉上隐藏标签与说明，同时保留它们与控件的无障碍关联。 |
| `description` | `string` | — | 显示在标签下方、控件上方的补充说明文字。 |
| `isDisabled` | `boolean` | false | 禁用输入框。被禁用的字段不参与表单提交。 |
| `isOptional` | `boolean` | false | 显示“可选”提示。与 isRequired 同时设置时，isOptional 优先。 |
| `isRequired` | `boolean` | false | 显示“必填”提示，组件同时会设置 aria-required。 |
| `labelIcon` | `Component` | — | 显示在标签前的图标组件。与 labelIcon 插槽同时使用时，插槽优先。 |
| `labelTooltip` | `string` | — | 在标签旁显示信息按钮，悬停、键盘聚焦或点击都可以查看提示。 |
| `optionalLabel` | `string` | Optional | “可选”提示的显示文字，用于本地化。 |
| `requiredLabel` | `string` | Required | “必填”提示的显示文字，用于本地化。 |
| `id` | `string` | 自动生成 | 原生 input 的 ID。设置后会同步更新标签与说明的关联。 |
| `type` | `'text' \| 'password' \| 'email'` | text | 输入框类型。多行内容请改用 TextArea。 |
| `size` | `'sm' \| 'md' \| 'lg'` | md | 输入框高度。Neutral 主题下三档分别为 28、32、36px。 |
| `isReadOnly` | `boolean` | false | 内容不可编辑，但输入框保留焦点、正常显示，值仍会参与表单提交。 |
| `disabledMessage` | `string` | — | 说明禁用原因。设置后改用 aria-disabled 与 readonly 保留焦点，方便用户查看原因；字段仍不可修改，也不会随表单提交。 |
| `startIcon` | `Component` | — | 显示在输入框前端的装饰图标。与 icon 插槽同时使用时，插槽优先。 |
| `status` | `TextInputStatus` | — | 设置 error、warning 或 success 校验状态，可附带 message 和 messageId。错误状态会设置 aria-invalid。 |
| `statusVariant` | `'attached' \| 'detached' \| 'tooltip'` | attached | 状态消息的展示方式：紧贴控件、分离显示，或收进图标提示。三种方式均与输入框保持关联。 |
| `changeAction` | `(value: string, event: TextInputChangeEvent) => void \| Promise<void>` | — | 在值变化后执行的动作。返回 Promise 时，组件会显示加载状态。 |
| `isLoading` | `boolean` | false | 手动控制加载状态。存在未完成的异步操作时也会显示加载，期间输入框仍可编辑。 |
| `placeholder` | `string` | — | 输入为空时显示的提示文字，不能替代 label。 |
| `width` | `number \| string` | auto | 整个字段的宽度。数字按像素处理，CSS 字符串按原样使用。 |
| `hasClear` | `boolean` | false | 在有内容且可编辑时显示清除按钮，点击清除后焦点会回到输入框。 |
| `hasAutoFocus` | `boolean` | false | 组件挂载后自动聚焦原生 input。 |
| `htmlName` | `string` | — | 原生 input 的 name 属性，优先于通过原生属性传入的 name。字段禁用时会被移除。 |
| `autoComplete` | `string` | — | 原样透传给原生 input 的 autocomplete 属性。 |
| `clearLabel` | `string` | Clear {label} | 清除按钮的读屏名称，默认带字段名。悬停或键盘聚焦时，提示只说「清除」。 |
| `loadingLabel` | `string` | Loading | 加载指示器的无障碍名称，用于本地化。 |
| `containerClass` | `string \| object \| array` | — | 加到字段外壳（Field 那一层，包着标签、输入框和状态消息）的 class。在 InputGroup 和横向标签的 FormLayout 里没有外壳，此时不生效，开发环境会警告。 |
| `containerStyle` | `StyleValue` | — | 加到字段外壳的行内样式。落点规则同 containerClass。 |
| `controlClass` | `string \| object \| array` | — | 加到输入框本体（画边框和背景、装着图标和清除按钮的盒子）的 class。不会落到原生 input 上。 |
| `controlStyle` | `StyleValue` | — | 加到输入框本体的行内样式。 |

## 状态类型

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

## TextInput 插槽

| 名称 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `icon` | `() => VNode[]` | — | 前端装饰图标，覆盖 startIcon。避免放入可交互控件。 |
| `end` | `() => VNode[]` | — | 尾部内容，可以放按钮。使用方负责其无障碍名称。 |
| `labelIcon` | `() => VNode[]` | — | 标签前的装饰图标，覆盖 labelIcon 属性。 |

## TextInput 事件

| 名称 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `update:modelValue` | `value: string` | — | v-model 更新。先于 change 与 changeAction。 |
| `change` | `value: string, event: TextInputChangeEvent` | — | 每次有效修改与清除后触发。event.preventDefault() 只阻止 changeAction，不撤回 v-model 更新。 |
| `enter` | `event: KeyboardEvent` | — | 非输入法提交的 Enter。keydown 被取消时不触发。 |
| `keydown` | `event: KeyboardEvent` | — | 原生按键事件。调用 preventDefault() 可阻止 enter。 |
| `clear` | `event: MouseEvent` | — | 清除按钮被激活后触发。仍会发出 update:modelValue 和 change，并运行未取消的 action。 |
| `actionError` | `error: unknown, value: string, event: TextInputChangeEvent` | — | 同步异常或 Promise 拒绝后触发。组件自动清除该操作的加载状态。 |

## TextInputChangeEvent

```ts
type TextInputChangeEvent = CustomEvent<{
  value: string
  originalEvent: Event
}>
```

- 原生 `input` 事件通常无法取消。
- `change` 提供可以取消的组件事件。
- `event.detail.value` 保存修改后的值。
- `event.detail.originalEvent` 保存原始事件。
- `changeAction` 和 `actionError` 接收同一个组件事件。

原始事件的类型取决于操作：

| 操作 | 类型 |
| --- | --- |
| 输入文字 | `InputEvent` |
| 提交输入法候选词 | `CompositionEvent` |
| 点击清除按钮 | `MouseEvent` |

## 异步操作

`changeAction` 接收修改后的值和组件事件。返回 Promise 时，组件会显示加载状态。

- **输入**：保存期间仍可编辑。清除内容也会运行 `changeAction`。
- **加载状态**：存在未完成的操作时，`aria-busy` 为 `true`。所有操作结束后清除加载状态，失败的操作也会计入。
- **值更新**：父组件传入的新值优先于组件临时显示的值。
- **并发保存**：由应用取消旧请求或检查请求序号，避免过期结果覆盖新值。
- **失败处理**：通过 `@action-error` 展示错误。需要回滚时，由应用更新 `v-model` 绑定值。

## 模板引用

模板引用公开以下属性和方法：

- `element: HTMLInputElement | null`：原生输入元素。挂载前为 `null`。
- `focus(options?: FocusOptions)`：聚焦输入框。
- `blur()`：移除输入框焦点。
- `select()`：选中全部输入内容。

## 原生属性

- `maxlength`、`minlength`、`pattern`、`required`、`form`、`aria-*`、`data-*` 和原生事件监听器传入原生 `input`。
- `class` 和 `style` 作用于输入框本体，和 `controlClass`、`controlStyle` 一起生效；给外壳加样式用 `containerClass`、`containerStyle`。`width` 作用于整个 `Field`。
- `value`、`type`、`disabled`、`readonly`、`autofocus` 与核心 ARIA 状态由组件管理，请使用对应的组件属性。
- `aria-describedby` 和 `aria-labelledby` 会与组件内部的关联 ID 合并。

### 禁用与只读

- **禁用且无原因说明**：使用原生 `disabled`，无法编辑、聚焦或提交该字段。
- **禁用且有 `disabledMessage`**：使用 `aria-disabled` 和 `readonly` 保留焦点，以便查看原因。同时移除 `name`，阻止修改和清除。
- **只读**：保留焦点，允许复制，值仍包含在 `FormData` 中。
- 同时设置禁用和只读时，禁用优先。

## 主题

为组件添加类名，即可覆盖主题变量：

```vue
<TextInput v-model="email" class="my-input" label="邮箱" />
```

```css
.my-input {
  --astryx-input-focus: #10b981;
  --astryx-radius-element: 8px;
}
```

### 外观与尺寸

- `--astryx-input-background`：输入框背景色。
- `--astryx-input-border`：默认边框色。
- `--astryx-input-focus`：无校验状态时的焦点边框色。
- `--astryx-radius-element`：输入框圆角。
- `--astryx-input-height-sm`：小尺寸高度，Neutral 默认 `28px`。
- `--astryx-input-height-md`：中尺寸高度，Neutral 默认 `32px`。
- `--astryx-input-height-lg`：大尺寸高度，Neutral 默认 `36px`。

### 校验状态

每种状态提供三个变量，分别控制边框与图标、消息文字、消息背景：

- **错误**：`--astryx-input-error`、`--astryx-input-error-foreground`、`--astryx-input-error-background`。
- **警告**：`--astryx-input-warning`、`--astryx-input-warning-foreground`、`--astryx-input-warning-background`。
- **成功**：`--astryx-input-success`、`--astryx-input-success-foreground`、`--astryx-input-success-background`。

在包含整个字段的父元素上覆盖状态变量，可同时调整输入框和状态消息。

### 明暗模式

- Neutral 根据 CSS `color-scheme` 自动选择配色。
- 在根元素或主题容器上设置 `data-astryx-color-mode="light"`，可固定使用浅色模式。
- 设置 `data-astryx-color-mode="dark"`，可固定使用暗色模式。
