# 开关

## 使用方法

`Switch` 用于切换单个布尔状态。

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

### 结构

- **字段**: 排列开关、标签和反馈的容器。
- **轨道**: 表示关或开的胶囊形表面。
- **拇指**: 状态变化时沿轨道移动的指示。
- **标签**: 说明开关控制的是哪一项设置的文字。
- **说明**: 标签下面的辅助文字。
- **转圈**: 忙碌时显示在拇指里的加载指示。
- **状态消息**: 开关下面的错误、警告或成功提示。

## 最佳实践

| 指引 | 实践 |
| --- | --- |
| 推荐 | 用于立即生效的设置。切换后应直接生效，无需单独的保存操作。 |
| 推荐 | 搭配清晰、简洁的标签，说明所控制的设置。 |
| 避免 | 需要提交表单才能生效的选项使用开关。应改用复选框。 |
| 避免 | 用 Tooltip 包裹禁用的开关来解释禁用原因。禁用的控件会吞掉包裹层需要的悬停事件。应改用 disabledMessage 属性。 |

## 示例

### 禁用

禁用的开关带上标签和说明，用来表示还没开放的功能。

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

### 设置面板

几项设置放在同一张卡片里，每一项是一个开关。

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

### 带说明

标签下面再写一行说明，交代打开之后会发生什么。

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

### 校验状态

error、warning、success 三种校验结果，写在开关下面。

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

## 键盘操作

开关在底层是一个原生复选框，键盘行为沿用浏览器自带的规则，用户不用鼠标也能完成切换。焦点落在开关上之后，可以使用以下按键：

- 按 Tab 把焦点移到开关上。
- 按 Space 切换选中状态。
- 按 Escape 关闭禁用原因提示。

「禁用原因提示」只在开关被禁用、并且传入了 `disabledMessage` 时才会出现，所以 Escape 也只在那种情况下有效。

## 使用建议

开关适合「改完立即生效」的二元选项，例如打开或关闭通知。如果一个选项要等提交表单才算确认，就应该改用复选框，否则用户会误以为开关已经保存了这次修改。

`isRequired` 只负责显示必填提示并设置 `aria-required`，不执行校验，也不会阻止表单提交。

## 属性

| 属性 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `v-model` | `boolean` | — | 必需。当前开关状态。 |
| `label` | `string` | — | 必需。控件的无障碍名称。 |
| `id` | `string` | — | 原生输入元素的 ID。省略时自动生成。 |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | 开关尺寸。 |
| `width` | `number \| string` | — | 组件宽度。数字按 px 处理。 |
| `description` | `string` | — | 标签下方的说明。 |
| `isLabelHidden` | `boolean` | `false` | 隐藏标签的视觉显示。保留无障碍名称。 |
| `isDisabled` | `boolean` | `false` | 阻止修改。 |
| `disabledMessage` | `string` | — | 禁用原因。提供原因时，禁用控件仍可聚焦。 |
| `isReadOnly` | `boolean` | `false` | 阻止修改。值仍参与表单提交。 |
| `isLoading` | `boolean` | `false` | 显示加载状态。阻止重复切换。 |
| `loadingLabel` | `string` | 跟随当前语言 | 忙碌时读屏念的文字。不传时用当前语言，英文是 Loading，中文是加载中。 |
| `isRequired` | `boolean` | `false` | 显示必填提示。启用原生必填校验。 |
| `isOptional` | `boolean` | `false` | 显示可选提示。优先于 isRequired。 |
| `optionalLabel` | `string` | `'Optional'` | 可选提示文本。 |
| `requiredLabel` | `string` | `'Required'` | 必填提示文本。 |
| `htmlName` | `string` | — | 表单字段名。优先于原生 name。 |
| `form` | `string` | — | 关联表单的 ID。 |
| `status` | `FieldStatusInput` | — | 状态类型、消息和消息 ID。 |
| `statusVariant` | `'attached' \| 'detached' \| 'tooltip'` | `'detached'` | 状态消息的显示位置。 |
| `changeAction` | `SwitchChangeAction` | — | 切换后执行的操作。支持 Promise。 |
| `hasAutoFocus` | `boolean` | `false` | 挂载后聚焦输入元素。 |
| `labelIcon` | `Component` | — | 标签前的装饰图标。 |
| `labelTooltip` | `string` | — | 标签旁的信息按钮提示。 |

## 状态消息

`status` 包含以下字段：

- `type`：`error`、`warning` 或 `success`。
- `message`：消息文本。
- `messageId`：消息 ID。

默认 `statusVariant` 为 `detached`，消息显示在开关下方。

## 事件

- `update:modelValue(value)`：用户切换后发出布尔值。
- `change(value, event)`：模型更新后触发。
- `actionError(error, value, event)`：异步操作拒绝或同步抛出错误时触发。

`event` 是可取消的 `SwitchChangeEvent`。
`event.detail.originalEvent` 保留原生事件。
在 `change` 中调用 `event.preventDefault()` 可跳过 `changeAction`。
此操作不会撤销模型更新。

## 异步操作

`changeAction(value, event)` 接收新值和组件事件。

- 操作返回 Promise 时，组件显示加载状态。
- 操作完成前，组件阻止重复切换。
- 父组件的新值优先于临时显示值。
- Promise 成功或失败后，组件清除加载状态。
- 失败时，组件不会撤销写入 `v-model` 的值。
- 使用 `@action-error` 显示失败信息。
- 需要回滚时，由业务层更新绑定值。

## 插槽

- `labelIcon`：标签前的装饰图标。优先于 `labelIcon` 属性。

## 模板引用

- `element`：`HTMLInputElement | null`。
- `focus(options?: FocusOptions)`：聚焦输入元素。
- `blur()`：移除输入焦点。

## 原生属性

`class` 和 `style` 应用于组件外层。
未声明的原生属性和事件传入 `input`。
组件管理 `checked`、`type`、`role` 和核心 ARIA 状态。

## 无障碍

### 轨道和圆点

- 准则: 1.4.11 Non-text Contrast
- 要求: 3:1
- 适用状态: Rest, Hover, Pointer down

打开和关闭的轨道各自要和后面的表面至少 3:1，圆点也要和它所在的轨道至少 3:1。悬停和按下，量的是着色和按下叠层加上去之后的最终颜色。
