# Toggle

让按钮保持按下，或者把多个切换按钮组合在一起，共用一个值并支持方向键导航。

用切换按钮表示一个按压后会保持开启、直到再次按压才关闭的按钮，比如给文档标星或打开 Bold。把几个切换按钮放进一个切换按钮组，共用一个值，就像文本编辑器的格式按钮或视图切换器那样。

```tsx title="basic.tsx"
import { Toggle, ToggleIcon } from "@ui-sdk/react/toggle"
import { StarIcon } from "lucide-react"

function Example() {
  return (
    <div data-slot="card">
      <div data-slot="stack">
        <h3>Q3 Roadmap</h3>
        <p data-slot="hint">Edited by Hollis Grant</p>
      </div>
      <Toggle aria-label="Star">
        <ToggleIcon data-variant="fill">
          <StarIcon />
        </ToggleIcon>
      </Toggle>
    </div>
  )
}

export { Example }
```

按 Q3 Roadmap 旁边的星标，或聚焦它后按 Enter 或 Space。按下时它会填充，无障碍名称始终是 Star。

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

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

```text
Toggle
└── ToggleIcon
```

以及一个 `ToggleGroup`：

```text
ToggleGroup
├── Toggle
│   └── ToggleIcon
└── Toggle
    └── ToggleIcon
```

`Toggle` 渲染一个原生按钮，用 `aria-pressed` 报告它的状态。`ToggleIcon` 是可选的：它容纳一个图标，并对屏幕阅读器隐藏。在分组里，给每个切换按钮一个 `value`；分组的值列出已按下的那些。

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

```tsx
import { Toggle, ToggleIcon } from "@ui-sdk/react/toggle"
import { StarIcon } from "lucide-react"

function Example() {
  return (
    <Toggle aria-label="Star">
      <ToggleIcon>
        <StarIcon />
      </ToggleIcon>
    </Toggle>
  )
}

export { Example }
```

让标签在两种状态下保持一致：屏幕阅读器会播报按钮是否被按下。只有图标的切换按钮需要一个 `aria-label`，如上所示。设置 `defaultPressed` 让它一开始就是按下状态。切换按钮始终使用 `type="button"`，所以按压它永远不会提交表单。

## 分组
把切换按钮放进同一个 `@ui-sdk/react/toggle` 入口的 `ToggleGroup`，共用一个值并支持方向键导航。给分组一个无障碍名称，给每个切换按钮一个 `value`。设置 `multiple`，让多个切换按钮可以同时保持按下。

```tsx title="group.tsx"
import { Toggle, ToggleGroup, ToggleIcon } from "@ui-sdk/react/toggle"
import { BoldIcon, ItalicIcon, UnderlineIcon } from "lucide-react"

function Example() {
  return (
    <ToggleGroup multiple aria-label="Text formatting">
      <Toggle value="bold" aria-label="Bold">
        <ToggleIcon>
          <BoldIcon />
        </ToggleIcon>
      </Toggle>
      <Toggle value="italic" aria-label="Italic">
        <ToggleIcon>
          <ItalicIcon />
        </ToggleIcon>
      </Toggle>
      <Toggle value="underline" aria-label="Underline">
        <ToggleIcon>
          <UnderlineIcon />
        </ToggleIcon>
      </Toggle>
    </ToggleGroup>
  )
}

export { Example }
```

按 Bold 和 Italic，让两个都保持按下。左、右方向键移动焦点，不会改变任何一个。

分组持有哪些切换按钮被按下的状态，所以切换按钮自己的 `pressed` 和 `defaultPressed` 在分组里不生效。它的值始终是一个数组，按切换按钮在文档中的顺序排列。

## 单选
不设 `multiple` 时，按下一个切换按钮会取消其他按钮的按下状态。再次按压已按下的切换按钮会清除选择，除非你像这个对齐分组一样把 `deselectable` 设为 `false`。`deselectable` 不会替你选择初始值，所以要配合 `defaultValue` 使用。它只限制人们能做什么：控制器的 `setValue([])` 仍然会清空分组。

```tsx title="group-single.tsx"
import { Toggle, ToggleGroup, ToggleIcon } from "@ui-sdk/react/toggle"
import {
  TextAlignCenterIcon,
  TextAlignEndIcon,
  TextAlignStartIcon,
} from "lucide-react"

const alignments = [
  {
    value: "start",
    label: "Align start",
    icon: TextAlignStartIcon,
    mirror: true,
  },
  {
    value: "center",
    label: "Align center",
    icon: TextAlignCenterIcon,
    mirror: false,
  },
  { value: "end", label: "Align end", icon: TextAlignEndIcon, mirror: true },
]

function Example() {
  return (
    <ToggleGroup
      defaultValue={["start"]}
      deselectable={false}
      aria-label="Text alignment"
    >
      {alignments.map((item) => (
        <Toggle key={item.value} value={item.value} aria-label={item.label}>
          <ToggleIcon mirror={item.mirror}>
            <item.icon />
          </ToggleIcon>
        </Toggle>
      ))}
    </ToggleGroup>
  )
}

export { Example }
```

按 Align center 代替 Align start，然后再按一次 Align center。始终有一个对齐方式保持按下。

Align start 和 Align end 上的 `mirror` 会在从右到左（RTL）的文本里翻转它们的图标。如果希望方向键移动时就选中选项，就改用 [Radio](/docs/react/components/radio)；切换按钮组先移动焦点，再等待一次按压。

## 图标与标签
用 `ToggleIcon` 把图标放在标签旁边。图标对屏幕阅读器隐藏，所以只靠文字为按钮命名。

```tsx
<Toggle>
  <ToggleIcon>
    <PinIcon />
  </ToggleIcon>
  Pin
</Toggle>
```

## 禁用
在切换按钮或分组上设置 `disabled` 来阻止按压。禁用的切换按钮仍然可以一开始就是按下状态，包裹它的禁用 `<fieldset>` 也会禁用它。

```tsx
<Toggle disabled defaultPressed>
  Pin
</Toggle>
```

单独一个禁用的切换按钮会离开 Tab 顺序。在分组里，禁用的切换按钮仍可用方向键到达，并报告 `aria-disabled`，但会忽略按压。

```tsx
<ToggleGroup multiple aria-label="Text formatting">
  <Toggle value="bold">Bold</Toggle>
  <Toggle value="italic">Italic</Toggle>
  <Toggle value="underline" disabled>
    Underline
  </Toggle>
</ToggleGroup>
```

## 禁用时仍可聚焦
设置 `focusableWhenDisabled` 让禁用的切换按钮仍可聚焦。它使用 `aria-disabled`，并且仍然忽略按压。用 `aria-describedby` 说明它为什么不可用：

```tsx
<Toggle disabled focusableWhenDisabled aria-describedby="pin-hint">
  Pin
</Toggle>
<p id="pin-hint">Only owners can pin messages.</p>
```

## 受控
传入 `pressed`，并在 `onPressedChange` 里更新它。在回调里调用 `details.cancel()` 可以保持当前状态。`createToggleController()` 创建的[控制器](https://ui-sdk.cn/docs/react/components/toggle#toggle-controller)可以从任何地方按压切换按钮，比如键盘快捷键。每个挂载的切换按钮各建一个控制器。

```tsx
"use client"

import * as React from "react"
import {
  createToggleController,
  Toggle,
  ToggleIcon,
} from "@ui-sdk/react/toggle"
import { StarIcon } from "lucide-react"

function StarButton() {
  const [starred, setStarred] = React.useState(false)
  const [star] = React.useState(createToggleController)

  return (
    <>
      <Toggle
        aria-label="Star"
        pressed={starred}
        onPressedChange={setStarred}
        controller={star}
      >
        <ToggleIcon>
          <StarIcon />
        </ToggleIcon>
      </Toggle>
      <button type="button" onClick={() => star.toggle()}>
        Toggle Star
      </button>
    </>
  )
}

export { StarButton }
```

回调收到新状态和 `details`，它的 `reason` 是 `"press"` 或 `"imperative"`。

## 受控的分组
传入 `value`，并在 `onValueChange` 里更新它，由你自己持有分组的值，或在别处展示它。切换按钮自己的 `onPressedChange` 先于分组的运行，在任意一个里调用 `details.cancel()` 都会取消变更。`createToggleGroupController()` 创建的[控制器](https://ui-sdk.cn/docs/react/components/toggle#togglegroup-controller)可以从任何地方更改这个值：`setValue([])` 会清空它。

```tsx
"use client"

import * as React from "react"
import {
  createToggleGroupController,
  Toggle,
  ToggleGroup,
} from "@ui-sdk/react/toggle"

function Formatting() {
  const [formats, setFormats] = React.useState(["bold"])
  const [editor] = React.useState(createToggleGroupController)

  return (
    <>
      <ToggleGroup
        multiple
        aria-label="Text formatting"
        value={formats}
        onValueChange={setFormats}
        controller={editor}
      >
        <Toggle value="bold">Bold</Toggle>
        <Toggle value="italic">Italic</Toggle>
      </ToggleGroup>
      <button type="button" onClick={() => editor.setValue([])}>
        Clear Formatting
      </button>
    </>
  )
}

export { Formatting }
```

受控状态、取消和调试见[状态与事件](/docs/react/state-and-events)。

## 垂直
设置 `orientation="vertical"` 改用上、下方向键移动，而不是左、右方向键。分组和它的切换按钮会得到 `data-orientation`。

```tsx
<ToggleGroup orientation="vertical" aria-label="Tool">
  ...
</ToggleGroup>
```

## 循环
方向键会从最后一个切换按钮绕回第一个。把 `loop` 设为 `false` 可以停在两端。

```tsx
<ToggleGroup multiple loop={false} aria-label="Text formatting">
  ...
</ToggleGroup>
```

## 表单
切换按钮不提交值。表单里需要多选时用 [Checkbox](/docs/react/components/checkbox)，单选时用 [Radio](/docs/react/components/radio)。如果要在表单里保留切换按钮组，就自己把它的值复制到隐藏的输入框里。

## 自定义渲染
每个部件都接受 `render`。传入一个元素，它的 props 会与部件的 props 合并；或传入一个函数，它接收 props 和部件的状态。切换按钮的状态有 `pressed`，分组的状态有 `value`，即已按下的值。把部件的 props 留在按钮上，让它的 `aria-pressed` 和键盘行为保持连接。渲染约定见[部件与组合](/docs/react/parts-and-composition)。

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

import { Toggle, ToggleIcon } from "@ui-sdk/react/toggle"
import { HeartIcon } from "lucide-react"

function Example() {
  return (
    <Toggle
      aria-label="Favorite"
      render={(props, state) => (
        <button {...props}>
          <ToggleIcon>
            <HeartIcon fill={state.pressed ? "currentColor" : "none"} />
          </ToggleIcon>
        </button>
      )}
    />
  )
}

export { Example }
```

按 Favorite。心形会根据切换按钮的按下状态渲染成实心或空心。

## 样式
用 `data-pressed` 为按下状态设置样式，用 `data-disabled` 表示不可用的切换按钮。带 `ToggleIcon` 的切换按钮会得到 `data-has-icon`，只要有一个切换按钮带图标，它所在的分组就会得到 `data-has-icons`，这有助于对齐图标和文字内容。`data-orientation` 告诉分组的切换按钮它朝哪个方向运行。

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

## 数据属性
### Toggle
`[data-slot="toggle"]`

- `data-pressed`: Present while pressed.
- `data-disabled`: Present when disabled, by its own prop or its group.
- `data-orientation` (`horizontal`, `vertical`): Inside a group, the group's orientation.
- `data-has-icon`: Present while the toggle holds an icon part.

### ToggleIcon
`[data-slot="toggle-icon"]`

- `data-mirror`: Present on an icon that flips in right-to-left text, with `mirror`.

### ToggleGroup
`[data-slot="toggle-group"]`

- `data-orientation` (`horizontal`, `vertical`): Which arrow keys move between toggles.
- `data-disabled`: Present when the whole group is disabled.
- `data-has-icons`: Present while any toggle inside holds an icon part, so toggles without one can line up.

## API 参考
属性和回调与下面相同，都作为 React props。

### Toggle
- `pressed?` (`boolean`): Whether it's pressed. Pass it to control the toggle. Inside a group, the group's value decides.
- `defaultPressed?` (`boolean`): Whether it's pressed at first, when uncontrolled.
- `onPressedChange?` (`((pressed: boolean, details: ChangeDetails<TogglePressedChangeReason>) => void)`): Runs when a press wants to change it. `details.reason` says why, and `details.cancel()` stops it. Inside a group, it runs before the group's `onValueChange`, and canceling it cancels the group's change too.
- `value?` (`string`): Identifies the toggle inside a group, whose value lists the pressed toggles' values. Defaults to a generated id.
- `disabled?` (`boolean`): Stops presses. Alone, the toggle is natively disabled, unless `focusableWhenDisabled` is set. Inside a group or a toolbar, it stays focusable with `aria-disabled`, so arrow keys still reach it.
- `focusableWhenDisabled?` (`boolean`): Keeps a disabled toggle in the tab order with `aria-disabled` instead of the native attribute. Toggles in a group or a toolbar always are.
- `controller?` (`{ isPressed: () => boolean; setPressed: (pressed: boolean, options?: ToggleChangeOptions) => boolean; toggle: (options?: ToggleChangeOptions) => boolean; focus: () => void; }`): Presses it from anywhere. Create one with `createToggleController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### ToggleIcon
- `mirror?` (`boolean`): Flips the icon horizontally in right-to-left text, for icons that point a way, like arrows and chevrons. Icons that picture a thing, like a clock or a check, stay as they are.

### ToggleGroup
- `value?` (`T[]`): The pressed toggles' values. Pass it to control the group.
- `defaultValue?` (`T[]`): The toggles pressed at first, when uncontrolled.
- `onValueChange?` (`((value: T[], details: ChangeDetails<ToggleGroupValueChangeReason>) => void)`): Runs when a toggle wants to be pressed or unpressed. `details.reason` says why, and `details.cancel()` stops it.
- `multiple?` (`boolean`): Whether several toggles can be pressed at once. Otherwise pressing one unpresses the others.
- `deselectable?` (`boolean`): Whether the pressed toggle can be unpressed when only one may be pressed. With `false`, one toggle stays pressed once any is, though `setValue([])` still clears it. Ignored with `multiple`.
- `disabled?` (`boolean`): Stops every toggle from being pressed. They stay focusable with `aria-disabled`, so the group keeps its tab stop and stays discoverable.
- `orientation?` (`ToggleGroupOrientation`): Which arrow keys move between toggles: left and right, or up and down.
- `loop?` (`boolean`): Whether arrow keys wrap from the last toggle to the first.
- `controller?` (`object`): Presses toggles from anywhere. Create one with `createToggleGroupController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### 状态
渲染函数、基于状态的类名和槽位收到什么。

- `pressed` (`boolean`): Whether it's pressed. Inside a group, it follows the group's value.
- `disabled` (`boolean`): Whether it's disabled, by itself, its group or a fieldset around it.

在分组里，切换按钮的 `disabled` 包含分组的。分组：

- `value` (`T[]`): The pressed toggles' values.
- `multiple` (`boolean`): Whether several toggles can be pressed at once.
- `disabled` (`boolean`): Whether the whole group is disabled, by its `disabled` option or a disabled fieldset around it.
- `orientation` (`ToggleGroupOrientation`): The group's `orientation` option, or `"horizontal"` when it's unset or invalid.

`ToggleIcon`：

- `mirror` (`boolean`): Whether it flips in right-to-left text.

### 原因
`details.reason` 说明切换按钮为什么被按下或取消按下。

- `press` (`MouseEvent | KeyboardEvent`): A single-element control was pressed: a checkbox, a switch or a toggle.
- `imperative` (`none`): A controller or `api` call.

对分组来说，它说明已按下的切换按钮为什么发生了变化。

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `imperative` (`none`): A controller or `api` call.

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

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

- `isPressed()` (`() => boolean`): Whether it's pressed. Inside a group, it follows the group's value.
- `setPressed(pressed, options?)` (`(pressed: boolean, options?: ToggleChangeOptions | undefined) => boolean`): Presses or unpresses it, as a user would. A disabled toggle ignores it. Returns false when canceled.
- `toggle(options?)` (`(options?: ToggleChangeOptions | undefined) => boolean`): Presses it, or unpresses it.
- `focus()` (`() => void`): Moves focus to it.

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

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

- `getValue()` (`() => T[]`): The pressed toggles' values, in the order they appear.
- `setValue(value, options?)` (`(value: T[], options?: ToggleGroupChangeOptions | undefined) => boolean`): Sets the pressed toggles. Only the first counts unless `multiple` is set. Returns false when canceled.
- `isPressed(value)` (`(value: T) => boolean`): Whether a toggle is pressed.
- `toggle(value, options?)` (`(value: T, options?: ToggleGroupChangeOptions | undefined) => boolean`): Presses a toggle, or unpresses a pressed one, as a user would. Disabled toggles and `deselectable={false}` refuse it.
- `focus(value?)` (`(value?: T | undefined) => void`): Moves focus to a toggle, or to the one that holds the group's tab stop.

### 事件
回调先收到新状态或值，再收到详情。`onValueChange` 从不在挂载时运行。

| Prop              | 所属部件      | 收到                                                                                           |
| ----------------- | ------------- | ---------------------------------------------------------------------------------------------- |
| `onPressedChange` | `Toggle`      | `(pressed, details)`：新状态，以及[原因](https://ui-sdk.cn/docs/react/components/toggle#reasons)。在分组里，它先运行，并且可以取消分组的变更 |
| `onValueChange`   | `ToggleGroup` | `(value, details)`：已按下的切换按钮的值，以及[原因](https://ui-sdk.cn/docs/react/components/toggle#reasons)                                 |

## 无障碍
切换按钮遵循 [WAI-ARIA 按钮模式](https://www.w3.org/WAI/ARIA/apg/patterns/button/)里的切换按钮：一个带 `aria-pressed` 的原生按钮。分组遵循 [WAI-ARIA 工具栏模式](https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/)的键盘操作，只有一个 Tab 停靠点，切换按钮之间用方向键移动。它的角色是 `group`，不是 `toolbar`，所以可以放进 [Toolbar](/docs/react/components/toolbar)；也不是 `radiogroup`，因为它的切换按钮是按钮。

### 键盘
分组是一个 Tab 停靠点。Tab 首次进入时停在第一个启用的已按下切换按钮上，没有的话停在第一个启用的切换按钮上；之后再进入时停在最后聚焦的那个。

| Key          | 作用                                 |
| ------------ | ------------------------------------ |
| Enter, Space | 按下或取消按下获得焦点的切换按钮     |
| Tab          | 进入或离开分组                       |
| Left, Right  | 在水平分组里移动焦点，从右到左时互换 |
| Up, Down     | 在垂直分组里移动焦点                 |
| Home, End    | 把焦点移到第一个或最后一个切换按钮   |

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

- A toggle starts unpressed.
- Clicking a toggle presses it, and clicking again unpresses it.
- Space presses a focused toggle.
- Enter presses a focused toggle.
- A toggle can start pressed.
- A change can be cancelled.
- A toggle keeps its name when it's pressed.

Runs in React、Vue 和 web components.

在分组里：

**One pressed at a time**

- The group is named and its default toggle is pressed.
- Pressing a toggle unpresses the others.
- Pressing the pressed toggle unpresses it.
- A change can be cancelled.

**Several pressed at once**

- Pressing toggles adds them to the value.
- A disabled toggle can't be pressed.
- A disabled group presses nothing.

**Keyboard**

- Tab moves into the group once, and out of it.
- Only one toggle in a group is a tab stop.
- ArrowRight and ArrowLeft move focus without pressing.
- Focus wraps at both ends.
- Home and End move to the first and last toggles.
- ArrowUp and ArrowDown do nothing in a horizontal group.
- Space presses the focused toggle.
- Enter presses the focused toggle.
- Tab returns to the toggle focused last.
- The group itself is never a tab stop.
- Keys pressed without waiting still land.
- Arrow keys with a modifier are left to the browser.

**Options**

- With loop off, arrows stop at the ends.
- A vertical group moves with ArrowDown and ArrowUp.
- The group carries its orientation.

Runs in React、Vue 和 web components.
