# Switch

## Usage

`Switch` toggles a single boolean state.

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

const enabled = shallowRef(false)
</script>

<template>
  <Switch v-model="enabled" label="Notifications" />
</template>
```

### Anatomy

- **Field**: Container arranging the switch, label, and feedback.
- **Track**: Pill-shaped surface that shows the off or on state.
- **Thumb**: Indicator that moves across the track when state changes.
- **Label**: Text identifying the setting controlled by the switch.
- **Description**: Helper text below the label.
- **Spinner**: Loading indicator shown inside the thumb while busy.
- **Status message**: Error, warning, or success message below the switch.

## Best practices

| Guidance | Practices |
| --- | --- |
| Do | Use for settings that apply immediately; the toggle should take effect without a separate save action. |
| Do | Pair with a clear, concise label that describes the setting being controlled. |
| Don't | Use for options that require a form submission to take effect; use a checkbox instead. |
| Don't | Wrap a disabled switch in Tooltip to explain why it is disabled; disabled controls swallow the hover events the wrapper needs. Use the disabledMessage prop instead. |

## Examples

### Disabled

A disabled switch with a label and a description, for a feature that is not available yet.

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

const enabled = shallowRef(false)
</script>

<template>
  <Switch v-model="enabled" label="Premium feature" description="Upgrade to enable this option" is-disabled />
</template>
```

### Settings panel

Several settings in one card, each one a switch.

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

const notifications = shallowRef(false)
const darkMode = shallowRef(true)
const autoSave = shallowRef(false)
</script>

<template>
  <Card width="100%" style="max-width: 300px">
    <VStack :gap="4">
      <Switch v-model="notifications" label="Enable notifications" />
      <Switch v-model="darkMode" label="Dark mode" />
      <Switch v-model="autoSave" label="Auto-save" />
    </VStack>
  </Card>
</template>
```

### With description

A line under the label says what turning the switch on will do.

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

const enabled = shallowRef(false)
</script>

<template>
  <Switch v-model="enabled" label="Dark mode" description="Switch to a darker color scheme." />
</template>
```

### With status

Error, warning, and success messages under the switch.

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

const terms = shallowRef(false)
const sharing = shallowRef(true)
const twoFactor = shallowRef(true)
</script>

<template>
  <VStack :gap="6" width="100%" style="max-width: 400px">
    <Switch
      v-model="terms"
      label="Accept terms and conditions"
      is-required
      :status="{ type: 'error', message: 'You must accept the terms to continue' }"
    />
    <Switch
      v-model="sharing"
      label="Share usage data"
      description="Help us improve by sharing anonymous usage statistics"
      :status="{ type: 'warning', message: 'This data may be shared with partners' }"
    />
    <Switch
      v-model="twoFactor"
      label="Two-factor authentication"
      :status="{ type: 'success', message: 'Your account is now more secure' }"
    />
  </VStack>
</template>
```

## Keyboard interactions

`Switch` is built on a native checkbox, so its keyboard behaviour follows the browser's defaults and every action is reachable without a mouse. With focus on the switch, these keys apply:

- Tab moves focus to the switch.
- Space toggles the checked state.
- Escape closes the disabled-reason tooltip.

The disabled-reason tooltip only appears when the switch is disabled and a `disabledMessage` is provided, so Escape has an effect only in that case.

## Usage notes

Use a switch for a two-state option that takes effect right away, such as turning notifications on or off. If an option only applies once the form is submitted, use a checkbox instead; otherwise users may assume the switch has already saved the change.

`isRequired` only shows the required indicator and sets `aria-required`; it does not perform validation or block form submission.

## Switch Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `v-model` | `boolean` | — | Required. Current switch state. |
| `label` | `string` | — | Required. Accessible name of the control. |
| `id` | `string` | — | ID of the native input. Auto-generated when omitted. |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Switch size. |
| `width` | `number \| string` | — | Component width. Numbers are treated as px. |
| `description` | `string` | — | Description shown below the label. |
| `isLabelHidden` | `boolean` | `false` | Hide the visual label while keeping the accessible name. |
| `isDisabled` | `boolean` | `false` | Prevent changes. |
| `disabledMessage` | `string` | — | Reason for disabling. The control stays focusable when this is provided. |
| `isReadOnly` | `boolean` | `false` | Prevent changes. The value is still submitted. |
| `isLoading` | `boolean` | `false` | Show loading state and block repeated toggles. |
| `loadingLabel` | `string` | Current locale | Text announced while the switch is busy. Defaults to the active locale: Loading in English, 加载中 in Chinese. |
| `isRequired` | `boolean` | `false` | Show required indicator and enable native required validation. |
| `isOptional` | `boolean` | `false` | Show optional indicator. Takes precedence over isRequired. |
| `optionalLabel` | `string` | `'Optional'` | Text for the optional indicator. |
| `requiredLabel` | `string` | `'Required'` | Text for the required indicator. |
| `htmlName` | `string` | — | Form field name. Takes precedence over native name. |
| `form` | `string` | — | ID of the associated form. |
| `status` | `FieldStatusInput` | — | Status type, message, and message ID. |
| `statusVariant` | `'attached' \| 'detached' \| 'tooltip'` | `'detached'` | Where to display the status message. |
| `changeAction` | `SwitchChangeAction` | — | Action run after toggling. Supports Promise. |
| `hasAutoFocus` | `boolean` | `false` | Focus the input after mount. |
| `labelIcon` | `Component` | — | Decorative icon before the label. |
| `labelTooltip` | `string` | — | Tooltip shown next to the label. |

## Status

`status` has these fields:

- `type`: `'error'`, `'warning'`, or `'success'`.
- `message`: message text.
- `messageId`: message ID.

The default `statusVariant` is `detached`, so the message appears below the switch.

## Events

- `update:modelValue(value)`: emitted after the user toggles.
- `change(value, event)`: fired after the model updates.
- `actionError(error, value, event)`: emitted when the async action rejects or throws.

`event` is a cancellable `SwitchChangeEvent`.
`event.detail.originalEvent` keeps the native event.
Calling `event.preventDefault()` inside `change` skips `changeAction`.
It does not roll back the model update.

## Async action

`changeAction(value, event)` receives the new value and the component event.

- The component shows a loading state while the Promise is pending.
- Repeated toggles are blocked until the Promise settles.
- The parent-bound value takes precedence over any temporary display value.
- The component clears the loading state after success or failure.
- Failed actions do not roll back the value written to `v-model`.
- Use `@action-error` to display failures.
- Roll back in application code when needed.

## Slots

- `labelIcon`: decorative icon before the label. Overrides the `labelIcon` prop.

## Template ref

- `element`: `HTMLInputElement | null`.
- `focus(options?: FocusOptions)`: focus the input.
- `blur()`: remove focus from the input.

## Native attributes

`class` and `style` are applied to the outer wrapper.
Unrecognized native attributes and listeners are forwarded to the `input`.
The component manages `checked`, `type`, `role`, and core ARIA states.

## Accessibility

### Track and thumb

- Criterion: 1.4.11 Non-text Contrast
- Check: 3:1
- States: Rest, Hover, Pointer down

The on and off tracks must each have at least 3:1 contrast with the surface behind them, and the thumb with its track. For Hover and Pointer down, measure the final colors after the tint and the pressed overlay are applied.
