# Switch

打开或关闭一项设置。

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

```tsx title="basic.tsx"
import { Switch, SwitchThumb } from "@ui-sdk/react/switch"

function Example() {
  return (
    <label data-slot="label">
      Airplane mode
      <Switch>
        <SwitchThumb />
      </Switch>
    </label>
  )
}

export { Example }
```

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

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

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

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

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

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

```tsx
import { Switch, SwitchThumb } from "@ui-sdk/react/switch"

function Example() {
  return (
    <label>
      Airplane mode
      <Switch>
        <SwitchThumb />
      </Switch>
    </label>
  )
}

export { Example }
```

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

```tsx title="description.tsx"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/react/field"
import { Switch, SwitchThumb } from "@ui-sdk/react/switch"

function Example() {
  return (
    <Field>
      <div data-slot="stack">
        <FieldLabel>Weekly digest</FieldLabel>
        <FieldDescription>
          A summary of your week, every Monday.
        </FieldDescription>
      </div>
      <Switch>
        <SwitchThumb />
      </Switch>
    </Field>
  )
}

export { Example }
```

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

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

```tsx title="choice-card.tsx"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/react/field"
import { Switch, SwitchThumb } from "@ui-sdk/react/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,
  },
]

function Example() {
  return (
    <div data-slot="stack">
      {settings.map((setting) => (
        <Field key={setting.label} data-variant="card">
          <div data-slot="stack">
            <FieldLabel>{setting.label}</FieldLabel>
            <FieldDescription>{setting.description}</FieldDescription>
          </div>
          <Switch defaultChecked={setting.defaultChecked}>
            <SwitchThumb />
          </Switch>
        </Field>
      ))}
    </div>
  )
}

export { Example }
```

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

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

```tsx title="disabled.tsx"
import { Switch, SwitchThumb } from "@ui-sdk/react/switch"

function Example() {
  return (
    <div data-slot="stack">
      <label data-slot="label">
        Product updates
        <Switch>
          <SwitchThumb />
        </Switch>
      </label>
      <label data-slot="label">
        Security alerts
        <Switch defaultChecked disabled>
          <SwitchThumb />
        </Switch>
      </label>
    </div>
  )
}

export { Example }
```

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

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

```tsx title="read-only.tsx"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/react/field"
import { Switch, SwitchThumb } from "@ui-sdk/react/switch"

function Example() {
  return (
    <Field>
      <div data-slot="stack">
        <FieldLabel>Encrypt backups</FieldLabel>
        <FieldDescription>
          Your organization manages this setting.
        </FieldDescription>
      </div>
      <Switch name="encrypt" defaultChecked readOnly>
        <SwitchThumb />
      </Switch>
    </Field>
  )
}

export { Example }
```

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

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

```tsx title="controlled.tsx"
"use client"

import * as React from "react"
import { createSwitchController } from "@ui-sdk/core/switch"
import { Switch, SwitchThumb } from "@ui-sdk/react/switch"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [wifi] = React.useState(() => createSwitchController())
  const [checked, setChecked] = React.useState(true)

  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button type="button" onClick={() => wifi.toggle()}>
          Toggle
        </button>
      </div>
      <label data-slot="label">
        Wi-Fi
        <Switch
          checked={checked}
          onCheckedChange={(next, details) => {
            setChecked(next)
            log(`${next ? "On" : "Off"} (${details.reason})`)
          }}
          controller={wifi}
        >
          <SwitchThumb />
        </Switch>
      </label>
    </div>
  )
}

export { Example }
```

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

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

```tsx title="form.tsx"
"use client"

import { FieldLegend, FieldSet } from "@ui-sdk/react/field"
import { Switch, SwitchThumb } from "@ui-sdk/react/switch"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <form
      data-slot="stack"
      onSubmit={(event) => {
        event.preventDefault()
        const entries = [...new FormData(event.currentTarget)].map(
          ([name, value]) => `${name}=${value}`
        )
        log(
          entries.length
            ? `Submitted ${entries.join("&")}`
            : "Submitted nothing"
        )
      }}
    >
      <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" defaultChecked>
            <SwitchThumb />
          </Switch>
        </label>
        <label data-slot="label">
          Weekly digest
          <Switch name="digest" value="weekly" defaultChecked>
            <SwitchThumb />
          </Switch>
        </label>
      </FieldSet>
      <div data-slot="row">
        <button type="submit" data-variant="solid">
          Save
        </button>
        <button type="reset">Reset</button>
      </div>
    </form>
  )
}

export { Example }
```

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

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

```tsx title="invalid.tsx"
"use client"

import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/react/field"
import { Switch, SwitchThumb } from "@ui-sdk/react/switch"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <form
      data-slot="stack"
      onSubmit={(event) => {
        event.preventDefault()
        log(
          `Submitted two-factor=${new FormData(event.currentTarget).get("two-factor")}`
        )
      }}
    >
      <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>
  )
}

export { Example }
```

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

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

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

```tsx title="async.tsx"
"use client"

import * as React from "react"
import { createSwitchController } from "@ui-sdk/core/switch"
import { Switch, SwitchThumb } from "@ui-sdk/react/switch"
import { LoaderCircleIcon } from "lucide-react"
import { useLog } from "./log"

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

function Example() {
  const log = useLog()
  const [backups] = React.useState(() => createSwitchController())
  const [saving, setSaving] = React.useState(false)
  const pending = React.useRef(false)

  return (
    <label data-slot="label">
      Automatic backups
      <Switch
        controller={backups}
        aria-busy={saving}
        onCheckedChange={(next, details) => {
          if (details.reason === "imperative" && details.source !== "agent") {
            return
          }
          details.cancel()
          if (pending.current) {
            return
          }
          pending.current = true
          setSaving(true)
          log("Saving…")
          save(next).then(() => {
            pending.current = false
            backups.setChecked(next, { reason: "imperative" })
            setSaving(false)
            log(`Saved: ${next ? "on" : "off"}`)
          })
        }}
      >
        <SwitchThumb>
          {saving && (
            <LoaderCircleIcon data-slot="spinner" aria-hidden="true" />
          )}
        </SwitchThumb>
      </Switch>
    </label>
  )
}

export { Example }
```

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

## 自定义渲染
开关和滑块手柄都接受 `render`。传入一个元素，它的 props 会与部件的 props 合并；或传入一个函数，它接收 props 和部件的状态。把部件的 props 留在元素上，让它的角色、标签和键盘行为保持连接。渲染约定见[部件与组合](/docs/react/parts-and-composition)。

```tsx title="render.tsx"
import { Switch, SwitchThumb } from "@ui-sdk/react/switch"
import { MoonIcon, SunIcon } from "lucide-react"

function Example() {
  return (
    <label data-slot="label">
      Dark mode
      <Switch>
        <SwitchThumb
          render={(props, state) => (
            <span {...props}>
              {state.checked ? (
                <MoonIcon aria-hidden="true" />
              ) : (
                <SunIcon aria-hidden="true" />
              )}
            </span>
          )}
        />
      </Switch>
    </label>
  )
}

export { Example }
```

打开 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/react/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 参考
属性和回调与下面相同，都作为 React props。

### 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.
- `onCheckedChange?` (`((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.

### 状态
渲染函数、基于状态的类名和槽位收到什么。滑块手柄的状态 `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.

### 事件
回调先收到新状态，再收到详情。

| Prop              | 所属部件 | 收到                                               |
| ----------------- | -------- | -------------------------------------------------- |
| `onCheckedChange` | `Switch` | `(checked, details)`：新状态，以及[原因](https://ui-sdk.cn/docs/react/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.
