# Text Input

## Usage

`TextInput` accepts single-line text. The component includes `Field`.

```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="Email" type="email" auto-complete="email" />
</template>
```

For a custom control, use [Field](/en/components/field). Import the theme once in your app entry:

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

### Anatomy

- **Label**: Text that identifies the field. Always rendered for accessibility even when visually hidden.
- **Description**: Helper text between the label and the input that provides additional context or formatting hints.
- **Start icon**: A leading icon inside the input that hints at the expected content, like a magnifying glass for search.
- **Placeholder**: Hint text shown when the input is empty. Disappears on focus.
- **Clear button**: A trailing × button that resets the value and returns focus to the input.
- **Spinner**: Loading indicator that appears during async actions like server-side validation.
- **Status icon**: A trailing icon (error, warning, or success) that communicates validation state.

## Best practices

| Guidance | Practices |
| --- | --- |
| Do | Always provide a visible label so users know what the field is for. Only hide the label when surrounding context makes it obvious, like a search bar with a magnifying-glass icon. |
| Do | Use validation status with a message to explain what went wrong: "Email must include @" is better than just turning the border red. |
| Do | Size the input to match the expected content length so users can gauge how much to type: small for zip codes, medium for names, large for URLs. |
| Do | Add a clear button for search and filter inputs so users can quickly reset without selecting all text. |

## Examples

### Icon

Name, email, and password fields with a leading icon.

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

### Search

Search fields with a magnifying glass and a clear button.

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

### Sizes

Small, medium, and large fields.

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

### States

Error, warning, and success messages, plus status without a message, disabled, and loading.

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

### Status variant

The status message can sit against the field or float below it.

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

### Types

Description, password, email, tooltip, required, and optional fields.

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

## Styling the container and the control

`TextInput` has two parts you can style:

- **Container**: the `Field` box around the label, the control box, and the status message. Use `container-class` and `container-style`.
- **Control**: the box that paints the border and background and holds the icons and the clear button. Use `control-class` and `control-style`.

Each set stays on its own part. Neither set reaches the native `<input>`.

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

A `class` or `style` written directly on `` still lands on the control box and applies together with `control-class`. `id`, `data-*`, `aria-*`, and event listeners land on the native `<input>`.

Inside an `InputGroup`, and inside a `horizontal-labels` `FormLayout`, no container renders, so `container-*` has no effect and warns in development. To style an `InputGroup`, put the class on the `InputGroup` itself.

## Accessibility

A `label` is required. Screen readers rely on it to describe what the field is for, and a `placeholder` is only visible while the field is empty, so it cannot stand in for a label.

The component wires the label, description and status message together with ARIA attributes, so assistive technology reads them as one unit:

- `description` and `status.message` connect to `aria-describedby`.
- An error status sets `aria-invalid`.
- A required field sets `aria-required`.

`isRequired` renders the required indicator and sets the ARIA state. When you also need native browser validation — for example when you rely on form submission to block an incomplete field — pass `required` as well.

## Input methods

While an input method such as Pinyin or Kana is composing a candidate, the characters the user has typed are not final yet. The component tracks that distinction so a half-finished value never reaches your state:

- The component does not update `v-model` while a candidate is still being composed, and the field keeps showing the composing text.
- Once `compositionend` fires — the moment the user picks a candidate — the component writes the final text to `v-model`.
- Enter used to confirm a candidate does not emit `enter`. The event fires normally when the user presses Enter again to submit the form.

This keeps validation and submit logic built on `v-model` from reacting to partial input.

## TextInput Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `modelValue` | `string` | Required | Input value, normally bound with v-model. |
| `label` | `string` | Required | Visible label. Still names the control when visually hidden. |
| `isLabelHidden` | `boolean` | false | Visually hides the label and description without removing accessible associations. |
| `description` | `string` | — | Helper text between the label and control. |
| `isDisabled` | `boolean` | false | Disables the input. Disabled values are excluded from form submission. |
| `isOptional` | `boolean` | false | Shows an optional indicator and takes precedence over isRequired. |
| `isRequired` | `boolean` | false | Shows a required indicator; TextInput also sets aria-required. |
| `labelIcon` | `Component` | — | Vue icon component before the label. The labelIcon slot takes precedence. |
| `labelTooltip` | `string` | — | Info button beside the label, available on hover, keyboard focus and click. |
| `optionalLabel` | `string` | Optional | Localized optional indicator. |
| `requiredLabel` | `string` | Required | Localized required indicator. |
| `id` | `string` | Generated | Native input ID. Label and description associations update together. |
| `type` | `'text' \| 'password' \| 'email'` | text | Single-line input type. Use a textarea for multiline content. |
| `size` | `'sm' \| 'md' \| 'lg'` | md | Neutral heights are 28, 32 and 36px respectively. |
| `isReadOnly` | `boolean` | false | Prevents editing, but remains focusable, undimmed and included in form submission. |
| `disabledMessage` | `string` | — | Disabled reason. Uses aria-disabled and readonly to preserve focus, while blocking edits and excluding the field from submission. |
| `startIcon` | `Component` | — | Decorative leading icon component. The icon slot takes precedence. |
| `status` | `TextInputStatus` | — | Error, warning or success, optionally with message and messageId. Error sets aria-invalid. |
| `statusVariant` | `'attached' \| 'detached' \| 'tooltip'` | attached | Attached, detached or an icon tooltip. All variants describe the input accessibly. |
| `changeAction` | `(value: string, event: TextInputChangeEvent) => void \| Promise<void>` | — | Runs after a value change. A returned Promise automatically drives pending state. |
| `isLoading` | `boolean` | false | External loading state, combined with pending actions without disabling editing. |
| `placeholder` | `string` | — | Empty-value hint. Does not replace the label. |
| `width` | `number \| string` | auto | Width of the whole field. Numbers are pixels, CSS strings are used unchanged. |
| `hasClear` | `boolean` | false | Shows a clear button for nonempty editable values and restores input focus after clearing. |
| `hasAutoFocus` | `boolean` | false | Focuses the native input after mounting. |
| `htmlName` | `string` | — | Native name, taking precedence over a forwarded name and removed when disabled. |
| `autoComplete` | `string` | — | Forwarded unchanged to native autocomplete. |
| `clearLabel` | `string` | Clear {label} | Accessible name of the clear button. It includes the field label by default. The tooltip only says “Clear”. |
| `loadingLabel` | `string` | Loading | Localized loading-indicator name. |
| `containerClass` | `string \| object \| array` | — | Class for the field container: the Field box around the label, control box, and status message. Has no effect, and warns in development, where no Field box renders (inside InputGroup and in a horizontal-labels FormLayout). |
| `containerStyle` | `StyleValue` | — | Inline style for the field container. Same targeting as containerClass. |
| `controlClass` | `string \| object \| array` | — | Class for the control box: the element that paints the border and background and holds the icons and clear button. Never reaches the native input. |
| `controlStyle` | `StyleValue` | — | Inline style for the control box. |

## Status type

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

## TextInput Slots

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `icon` | `() => VNode[]` | — | Decorative leading icon, overriding startIcon. Keep interactive controls out of this slot. |
| `end` | `() => VNode[]` | — | Trailing content, including buttons. Consumers provide accessible names. |
| `labelIcon` | `() => VNode[]` | — | Decorative label icon, overriding the labelIcon prop. |

## TextInput Events

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `update:modelValue` | `value: string` | — | v-model update, before change and changeAction. |
| `change` | `value: string, event: TextInputChangeEvent` | — | Emitted after each committed edit or clear. event.preventDefault() skips changeAction without undoing the model update. |
| `enter` | `event: KeyboardEvent` | — | Enter outside IME composition. Canceled keydown events suppress it. |
| `keydown` | `event: KeyboardEvent` | — | Native keyboard event. PreventDefault() can suppress enter. |
| `clear` | `event: MouseEvent` | — | Clear-button activation. Still emits update:modelValue and change and runs an uncanceled action. |
| `actionError` | `error: unknown, value: string, event: TextInputChangeEvent` | — | Emitted after a synchronous throw or Promise rejection. Pending is cleaned automatically. |

## TextInputChangeEvent

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

- Native `input` events are usually not cancelable.
- `change` supplies a cancelable component event.
- `event.detail.value` contains the new value.
- `event.detail.originalEvent` contains the original event.
- `changeAction` and `actionError` receive the same component event.

The original event type depends on the action:

| Action | Type |
| --- | --- |
| Enter text | `InputEvent` |
| Confirm input method composition | `CompositionEvent` |
| Click the clear button | `MouseEvent` |

## Async actions

`changeAction` receives the new value and component event. Returning a Promise displays a loading indicator.

- **Editing**: the input remains editable while saving. Clearing the value also runs `changeAction`.
- **Loading**: `aria-busy` stays `true` while any action is unfinished. It clears after all actions settle, including rejected actions.
- **Value updates**: new values from the parent take precedence over temporary display values.
- **Concurrent saves**: cancel older requests or check request versions in your application to prevent stale results from overwriting newer values.
- **Errors**: handle `@action-error` to show a message. To roll back, update the value bound with `v-model`.

## Template refs

Template refs expose these properties and methods:

- `element: HTMLInputElement | null`: the native input element, or `null` before mounting.
- `focus(options?: FocusOptions)`: focuses the input.
- `blur()`: removes focus from the input.
- `select()`: selects all input text.

## Native attributes

- `maxlength`, `minlength`, `pattern`, `required`, `form`, `aria-*`, `data-*` and native event listeners are forwarded to the native `input`.
- `class` and `style` apply to the control box and combine with `controlClass` and `controlStyle`. Use `containerClass` and `containerStyle` for the Field container. `width` applies to the whole `Field`.
- The component manages `value`, `type`, `disabled`, `readonly`, `autofocus` and core ARIA state. Use the corresponding component props.
- `aria-describedby` and `aria-labelledby` merge with the component's internal association IDs.

### Disabled and read-only states

- **Disabled without a reason**: native `disabled` prevents editing, focus and submission of the field.
- **Disabled with `disabledMessage`**: `aria-disabled` and `readonly` preserve focus so the reason can be discovered. The component removes `name` and blocks edits and clearing.
- **Read-only**: the input remains focusable, allows copying and is included in `FormData`.
- Disabled takes precedence when both states are set.

## Theme

Add a class to the component to override theme variables:

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

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

### Appearance and size

- `--astryx-input-background`: input background color.
- `--astryx-input-border`: default border color.
- `--astryx-input-focus`: focus border color when no validation status is set.
- `--astryx-radius-element`: input corner radius.
- `--astryx-input-height-sm`: small height; Neutral defaults to `28px`.
- `--astryx-input-height-md`: medium height; Neutral defaults to `32px`.
- `--astryx-input-height-lg`: large height; Neutral defaults to `36px`.

### Validation states

Each state provides three variables for the border and icon, message text, and message background:

- **Error**: `--astryx-input-error`, `--astryx-input-error-foreground`, `--astryx-input-error-background`.
- **Warning**: `--astryx-input-warning`, `--astryx-input-warning-foreground`, `--astryx-input-warning-background`.
- **Success**: `--astryx-input-success`, `--astryx-input-success-foreground`, `--astryx-input-success-background`.

Override status variables on a parent containing the whole field to style both the input and its status message.

### Color mode

- Neutral selects its colors from CSS `color-scheme`.
- Set `data-astryx-color-mode="light"` on the root element or theme container to use light mode.
- Set `data-astryx-color-mode="dark"` to use dark mode.
