# Switch

打开或关闭一项设置。

用开关表示一更改就立即生效的设置，比如 Airplane mode 或通知偏好。让它的标签在两种状态下保持一致：标签说明设置是什么，开关显示它是否开启。

```vue title="basic.vue"
<script setup lang="ts">
import { Switch, SwitchThumb } from "@ui-sdk/vue/switch"
</script>

<template>
  <label data-slot="label">
    Airplane mode
    <Switch>
      <SwitchThumb />
    </Switch>
  </label>
</template>
```

点击 Airplane mode，或聚焦开关后按 Space，把它打开或关闭。

## 安装
```bash
npm install @ui-sdk/vue @ui-sdk/core
```

## 组合
用下面的组合构建一个 `Switch`：

```text
Switch
└── SwitchThumb
```

把开关和它的文字包在一个 label 里。滑块手柄保持挂载并取得开关的状态，所以 CSS 可以让它从一端滑到另一端。

## 用法
导入部件并把它们组合起来：

```vue
<script setup lang="ts">
import { Switch, SwitchThumb } from "@ui-sdk/vue/switch"
</script>

<template>
  <label>
    Airplane mode
    <Switch>
      <SwitchThumb />
    </Switch>
  </label>
</template>
```

## 描述
设置需要更多说明时，用 `FieldLabel` 和 `FieldDescription`。字段会把标签和描述都连接到开关。

```vue title="description.vue"
<script setup lang="ts">
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
import { Switch, SwitchThumb } from "@ui-sdk/vue/switch"
</script>

<template>
  <Field>
    <div data-slot="stack">
      <FieldLabel>Weekly digest</FieldLabel>
      <FieldDescription>A summary of your week, every Monday.</FieldDescription>
    </div>
    <Switch>
      <SwitchThumb />
    </Switch>
  </Field>
</template>
```

点击 Weekly digest。字段把标签和描述连接到开关。

## 选择卡片
一项设置可以占满整张卡片。这里标签的 `::after` 覆盖整张卡片，所以点击卡片任意位置都会切换开关，`:has([data-checked])` 会标记已开启的卡片。

```vue title="choice-card.vue"
<script setup lang="ts">
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
import { Switch, SwitchThumb } from "@ui-sdk/vue/switch"

const settings = [
  {
    label: "Public profile",
    description: "Anyone can see your name and photo.",
    defaultChecked: false,
  },
  {
    label: "Show activity status",
    description: "Teammates can see when you're online.",
    defaultChecked: true,
  },
]
</script>

<template>
  <div data-slot="stack">
    <Field v-for="setting in settings" :key="setting.label" data-variant="card">
      <div data-slot="stack">
        <FieldLabel>{{ setting.label }}</FieldLabel>
        <FieldDescription>{{ setting.description }}</FieldDescription>
      </div>
      <Switch :default-checked="setting.defaultChecked">
        <SwitchThumb />
      </Switch>
    </Field>
  </div>
</template>
```

点击 Public profile 卡片的任意位置把它打开。每张卡片的开关各自保存自己的值。

## 禁用
`disabled` 阻止聚焦和更改，并让开关不参与表单提交。禁用的 `fieldset` 也一样。

```vue title="disabled.vue"
<script setup lang="ts">
import { Switch, SwitchThumb } from "@ui-sdk/vue/switch"
</script>

<template>
  <div data-slot="stack">
    <label data-slot="label">
      Product updates
      <Switch>
        <SwitchThumb />
      </Switch>
    </label>
    <label data-slot="label">
      Security alerts
      <Switch default-checked disabled>
        <SwitchThumb />
      </Switch>
    </label>
  </div>
</template>
```

Security alerts 始终开启，所以那个开关处于禁用状态。点击它不会改变状态，Tab 会跳过它。

## 只读
`read-only` 让开关保持可聚焦并参与表单提交，同时阻止用户更改它。用于在别处管理的设置。

```vue title="read-only.vue"
<script setup lang="ts">
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
import { Switch, SwitchThumb } from "@ui-sdk/vue/switch"
</script>

<template>
  <Field>
    <div data-slot="stack">
      <FieldLabel>Encrypt backups</FieldLabel>
      <FieldDescription
        >Your organization manages this setting.</FieldDescription
      >
    </div>
    <Switch name="encrypt" default-checked read-only>
      <SwitchThumb />
    </Switch>
  </Field>
</template>
```

按 Tab 到达 Encrypt backups。按 Space 或点击都不会改变它的开启状态。

## 受控
绑定 `v-model:checked`，或传入 `checked` 并处理 `@checked-change`，来自己持有值。`createSwitchController()` 创建的[控制器](https://ui-sdk.cn/docs/vue/components/switch#controller)可以从任何地方更改它，比如下面的 Toggle 按钮。共用的变更回调见[状态与事件](/docs/vue/state-and-events)。

```vue title="controlled.vue"
<script setup lang="ts">
import {
  createSwitchController,
  type SwitchCheckedChangeReason,
} from "@ui-sdk/core/switch"
import { Switch, SwitchThumb } from "@ui-sdk/vue/switch"
import { ref } from "vue"
import { useLog } from "./log"

const log = useLog()
const wifi = createSwitchController()
const checked = ref(true)

function onCheckedChange(
  next: boolean,
  details: { reason: SwitchCheckedChangeReason }
) {
  log(`${next ? "On" : "Off"} (${details.reason})`)
}
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <button type="button" @click="wifi.toggle()">Toggle</button>
    </div>
    <label data-slot="label">
      Wi-Fi
      <Switch
        v-model:checked="checked"
        :controller="wifi"
        @checked-change="onCheckedChange"
      >
        <SwitchThumb />
      </Switch>
    </label>
  </div>
</template>
```

关闭 Wi-Fi，或按 Toggle。控制台会记录每次变更及其原因。

## 表单
设置 `name`，让开关进入原生表单。开启的开关会提交它的 `value`，默认是 `"on"`；关闭的开关不提交任何内容。Reset 会把它恢复到 `default-checked`。把 `form` 设为表单的 id，就能从页面其他地方加入该表单。

```vue title="form.vue"
<script setup lang="ts">
import { FieldLegend, FieldSet } from "@ui-sdk/vue/field"
import { Switch, SwitchThumb } from "@ui-sdk/vue/switch"
import { useLog } from "./log"

const log = useLog()

function onSubmit(event: Event) {
  const entries = [...new FormData(event.currentTarget as HTMLFormElement)].map(
    ([name, value]) => `${name}=${value}`
  )
  log(entries.length ? `Submitted ${entries.join("&")}` : "Submitted nothing")
}
</script>

<template>
  <form data-slot="stack" @submit.prevent="onSubmit">
    <FieldSet>
      <FieldLegend>Email notifications</FieldLegend>
      <label data-slot="label">
        Product updates
        <Switch name="updates">
          <SwitchThumb />
        </Switch>
      </label>
      <label data-slot="label">
        Security alerts
        <Switch name="security" default-checked>
          <SwitchThumb />
        </Switch>
      </label>
      <label data-slot="label">
        Weekly digest
        <Switch name="digest" value="weekly" default-checked>
          <SwitchThumb />
        </Switch>
      </label>
    </FieldSet>
    <div data-slot="row">
      <button type="submit" data-variant="solid">Save</button>
      <button type="reset">Reset</button>
    </div>
  </form>
</template>
```

打开 Product updates 并按 Save。控制台会记录提交的值，Reset 会恢复默认值。

## 校验
`required` 会阻止提交，直到开关开启。在 [Field](/docs/vue/components/field) 中，`FieldError` 会在开关下方显示消息，并把它连接到开关。[表单与校验](/docs/vue/forms)涵盖了共用的字段行为。

```vue title="invalid.vue"
<script setup lang="ts">
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/vue/field"
import { Switch, SwitchThumb } from "@ui-sdk/vue/switch"
import { useLog } from "./log"

const log = useLog()

function onSubmit(event: Event) {
  log(
    `Submitted two-factor=${new FormData(event.currentTarget as HTMLFormElement).get("two-factor")}`
  )
}
</script>

<template>
  <form data-slot="stack" @submit.prevent="onSubmit">
    <Field>
      <div data-slot="row">
        <div data-slot="stack">
          <FieldLabel>Two-factor authentication</FieldLabel>
          <FieldDescription
            >Required for admins of this workspace.</FieldDescription
          >
        </div>
        <Switch name="two-factor" required>
          <SwitchThumb />
        </Switch>
      </div>
      <FieldError match="valueMissing">Turn this on to continue.</FieldError>
    </Field>
    <div data-slot="row">
      <button type="submit" data-variant="solid">Continue</button>
    </div>
  </form>
</template>
```

在开关关闭时按 Continue，查看错误。打开 Two-factor authentication 并继续；控制台会记录提交的值。

## 切换时保存
要在变更显示之前先保存，就在 `@checked-change` 里调用 `details.cancel()`，让当前值在保存期间保持不变。保存结束后，调用 `controller.setChecked(next, { reason: "imperative" })`，并在处理函数里放行这个原因，让保存的值生效。Agent 的变更也会上报 `"imperative"`，同时 `source` 为 `"agent"`，所以示例会检查 `source`，并像其他变更一样保存它。

示例在保存进行时忽略按压，并在滑块手柄里显示加载指示器。`aria-busy` 告诉辅助技术开关正忙；真正阻止另一次变更的是处理函数。

```vue title="async.vue"
<script setup lang="ts">
import { LoaderCircleIcon } from "@lucide/vue"
import type { ChangeSource } from "@ui-sdk/core"
import {
  createSwitchController,
  type SwitchCheckedChangeReason,
} from "@ui-sdk/core/switch"
import { Switch, SwitchThumb } from "@ui-sdk/vue/switch"
import { ref } from "vue"
import { useLog } from "./log"

const save = (_checked: boolean) =>
  new Promise((resolve) => setTimeout(resolve, 800))

const log = useLog()
const backups = createSwitchController()
const saving = ref(false)

function onCheckedChange(
  next: boolean,
  details: {
    reason: SwitchCheckedChangeReason
    source: ChangeSource
    cancel: () => void
  }
) {
  if (details.reason === "imperative" && details.source !== "agent") {
    return
  }
  details.cancel()
  if (saving.value) {
    return
  }
  saving.value = true
  log("Saving…")
  save(next).then(() => {
    backups.setChecked(next, { reason: "imperative" })
    saving.value = false
    log(`Saved: ${next ? "on" : "off"}`)
  })
}
</script>

<template>
  <label data-slot="label">
    Automatic backups
    <Switch
      :controller="backups"
      :aria-busy="saving"
      @checked-change="onCheckedChange"
    >
      <SwitchThumb>
        <LoaderCircleIcon
          v-if="saving"
          data-slot="spinner"
          aria-hidden="true"
        />
      </SwitchThumb>
    </Switch>
  </label>
</template>
```

打开 Automatic backups。保存期间滑块手柄会显示加载指示器，之后开关开启。

## 自定义渲染
开关和滑块手柄都接受 `render` 插槽，它接收要绑定的 props 和部件的状态。把部件的 props 留在元素上，让它的角色、标签和键盘行为保持连接。渲染约定见[部件与组合](/docs/vue/parts-and-composition)。

```vue title="render.vue"
<script setup lang="ts">
import { MoonIcon, SunIcon } from "@lucide/vue"
import { Switch, SwitchThumb } from "@ui-sdk/vue/switch"
</script>

<template>
  <label data-slot="label">
    Dark mode
    <Switch>
      <SwitchThumb>
        <template #render="{ props, state }">
          <span v-bind="props">
            <MoonIcon v-if="state.checked" aria-hidden="true" />
            <SunIcon v-else aria-hidden="true" />
          </span>
        </template>
      </SwitchThumb>
    </Switch>
  </label>
</template>
```

打开 Dark mode。滑块手柄根据它的状态渲染太阳或月亮。

## 样式
用 `data-checked` 和 `data-unchecked` 为开关和滑块手柄设置样式，用 `data-disabled`、`data-readonly` 和 `data-required` 表示其余状态。在无效的字段中，开关还会得到 `data-invalid` 和 `aria-invalid`；滑块手柄没有。在 `data-checked` 上用 `translate` 滑动滑块手柄，并在 `dir="rtl"` 下反向。

每个部件都有一个 `data-slot`，比如 `switch`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/vue/components/switch#data-attributes)下。

## 数据属性
### Switch
`[data-slot="switch"]`

- `data-checked`: Present while on.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-unchecked`: Present while off.
- `data-invalid`: Present while a `Field` around it shows as invalid. The thumb doesn't get it.

### SwitchThumb
`[data-slot="switch-thumb"]`

- `data-checked`: Present while on.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-unchecked`: Present while off.

## API 参考
属性和下面相同，回调是事件。

### Switch
- `checked?` (`boolean`): Whether it's checked. Pass it to control the checkbox.
- `defaultChecked?` (`boolean`): Whether it's checked at first, when uncontrolled. A form reset returns to it.
- `@checked-change` (`((checked: boolean, details: ChangeDetails<CheckboxCheckedChangeReason>) => void)`): Runs when a user or a form reset wants to change it. `details.reason` says why, and `details.cancel()` stops it.
- `disabled?` (`boolean`): Disables it like a native control: it can't be focused or changed, and isn't submitted.
- `readOnly?` (`boolean`): Keeps it focusable and submitted, but stops changes.
- `required?` (`boolean`): Blocks form submission until it's checked, with the browser's own message.
- `name?` (`string`): The name it submits under. Without one, it submits nothing.
- `value?` (`string`): What it submits while checked.
- `form?` (`string`): The id of a form to belong to, when it isn't inside that form.
- `controller?` (`{ toggle: (details?: Details) => boolean; getChecked: () => boolean; setChecked: (checked: boolean, details?: Details) => boolean; focus: () => void; }`): Toggles it from anywhere. Create one with `createSwitchController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### 状态
render 插槽和默认插槽收到什么。滑块手柄的状态 `SwitchThumbState` 相同。

- `checked` (`boolean`): Whether it's checked. False while indeterminate.
- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether it's read-only: it stays focusable and submitted, but presses don't change it.
- `required` (`boolean`): Whether a form won't submit until it's checked. Indeterminate doesn't count.

### 原因
`details.reason` 说明开关为什么打开或关闭。

- `press` (`MouseEvent | KeyboardEvent`): A single-element control was pressed: a checkbox, a switch or a toggle.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

### 控制器
用 `createSwitchController()` 创建一个，并作为 `controller` 传入。

每个写入方法都接受可选的 `{ reason, event }`，像按压一样运行变更回调，并在变更被取消时返回 `false`。

- `toggle(details?)` (`(details?: CheckboxChangeOptions | undefined) => boolean`): Turns it on, or off.
- `getChecked()` (`() => boolean`): Whether it's on.
- `setChecked(checked, details?)` (`(checked: boolean, details?: CheckboxChangeOptions | undefined) => boolean`): Turns it on or off, as a user would.
- `focus()` (`() => void`): Moves focus to it.

### 事件
事件先收到新状态，再收到详情。只有变更事件未被取消时，`v-model` 才会更新。

| 绑定              | 所属部件 | 收到                                               |
| ----------------- | -------- | -------------------------------------------------- |
| `v-model:checked` | `Switch` | 开关是否开启                                       |
| `@checked-change` | `Switch` | `(checked, details)`：新状态，以及[原因](https://ui-sdk.cn/docs/vue/components/switch#reasons) |

## 无障碍
开关遵循 [WAI-ARIA 开关模式](https://www.w3.org/WAI/ARIA/apg/patterns/switch/)。`Switch` 渲染一个带 `switch` 角色的按钮，以及一个参与表单的隐藏原生复选框。

### 键盘
| Key   | 作用                     |
| ----- | ------------------------ |
| Tab   | 移动到下一个开关         |
| Space | 打开或关闭它             |
| Enter | 提交它的表单，从不切换它 |

### 经过测试的行为
下面每一行都是一个自动化测试。

- Starts in its default state.
- Clicking toggles it.
- Clicking its label toggles it.
- Space toggles it.
- Enter submits the form and never toggles it.
- The thumb follows the state.

**The first input on a page**

- The first Space reports keyboard.

**On a touch screen**

- The first tap reports touch.

Runs in React、Vue 和 web components.

在表单中：

- The form submits every checked control's name and value.
- Unchecked controls submit nothing.
- A checkbox outside the form joins it with the form attribute.
- Required controls block submission.
- A form reset returns every control to its default.
- A reset returns to the default value, not to nothing.
- A disabled fieldset disables the controls inside it.
- A read-only control still submits.
- A user's change fires native input and change events on the form.

Runs in React、Vue 和 web components.

在模式基线之外：

**Enhancements**

- The first invalid control takes focus in document order.
- A later required field without an error part doesn't take focus from the first.

**Form-associated custom elements**

- Take part in the form with no hidden input. Web components only.
- Report validity like native controls. Web components only.
- Have live checked and value properties. Web components only.
- Are named by their labels. Web components only.

Runs in React、Vue 和 web components.

在每个经过测试的框架里，屏幕阅读器听到的内容相同，由虚拟屏幕阅读器录制：

- Announcements while checking boxes with a keyboard.
- Announcements while choosing a radio with a keyboard.

Runs in React、Vue 和 web components.
