# 切换按钮

## 使用方法

`ToggleButton` 是一个带“按下 / 未按下”状态的按钮。它表示一个持续生效的选择，比如加粗、切换视图、收藏、开始录音，而不是一次性的动作。它复用 `Button` 的外观、尺寸和异步动作机制，只额外补上按下状态、`aria-pressed` 语义，以及按下时的图标与字重变化。

独立使用时，把按下状态绑到组件上即可：

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

const isPinned = shallowRef(false)
</script>

<template>
  <ToggleButton v-model:is-pressed="isPinned" label="Pin to top" />
</template>
```

点击时组件先发出 `pressedChange` 事件（携带下一个状态和原始的点击事件），再写入 `v-model:is-pressed`。回调里调用 `event.preventDefault()` 就表示这次切换由你自己处理，组件不会改写状态，也不会运行 `pressedChangeAction`。如果完全不绑定按下状态，按钮会自己管理它。

按下状态需要等待接口或路由时，用 `pressedChangeAction` 代替手写 loading 状态。动作执行期间按钮显示下一个状态和一个加载指示，并且仍然可以点击：后一次点击会反转上一次尚未完成的选择，而不是被丢掉。

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

const isShared = shallowRef(false)

async function shareWithTeam(next: boolean) {
  await api.setShared(boardId, next)
}
</script>

<template>
  <ToggleButton
    v-model:is-pressed="isShared"
    label="Share with team"
    :pressed-change-action="shareWithTeam"
  />
</template>
```

相关的开关应该放进 `ToggleButtonGroup`，让屏幕阅读器把它们读成一个整体：

```vue
<script setup lang="ts">
import { ToggleButton, ToggleButtonGroup } from '@astryx-vue/core/ToggleButton'
import { ref } from 'vue'

const view = ref<string | null | string[]>('board')
</script>

<template>
  <ToggleButtonGroup v-model:value="view" label="View mode">
    <ToggleButton value="list" label="List" />
    <ToggleButton value="board" label="Board" />
  </ToggleButtonGroup>
</template>
```

分组默认是单选：只有一个成员处于按下状态，再次点击当前项会取消选择（值为 `null`）。改成 `type="multiple"` 后每个成员各自开关，适合筛选器、列显示这类多选工具栏。分组的 `size` 会传给所有成员，成员自己设置 `size` 时以成员的为准；分组的 `isDisabled` 会禁用全部成员，而成员自己禁用自己时，分组无法把它重新启用。作为分组一员的按钮由分组决定按下状态，它自己的 `isPressed`、`pressedChange` 和 `pressedChangeAction` 都不再生效。

图标按钮请用 `isIconOnly`：按钮变成正方形，`label` 转为无障碍名称，鼠标悬停的文字提示由 `tooltip` 提供。按下时想换成实心图标，就把另一张图放进 `pressedIcon` 插槽；它留空时会退回 `icon`。

### 结构

- **图标**: 表示这个切换做什么的前导图标，比如收藏用的星，或加粗用的 B。
- **按下时的图标**: 按下时显示的另一枚图标，一般是默认图标的实心版，用来强化已经按下。
- **标签**: 可见文字或无障碍名称。只有图标的切换用它做 aria-label，并自动作为提示。
- **转圈**: pressedChangeAction 触发的异步操作期间，替换图标。

## 最佳实践

| 指引 | 实践 |
| --- | --- |
| 推荐 | 按下状态用一个实心或带颜色的图标表示，例如麦克风换成实心方块，让用户一眼看出当前状态。 |
| 推荐 | 按下与未按下时保持标签文字不变，让背景、字重和图标去表达状态的差别。 |
| 推荐 | 把相关的开关放进带 `label` 的 `ToggleButtonGroup`，屏幕阅读器才会把它们播报成一组。 |
| 推荐 | 需要请求后端时用 `pressedChangeAction`，按钮会自动显示按下预览和加载指示，不必自己维护 loading 状态。 |
| 避免 | 用它做一次性的动作，例如“提交”“删除”，那些是 `Button` 的职责。 |
| 避免 | 在同一个 `ToggleButtonGroup` 里混用普通 `Button`，组内只应该放 `ToggleButton`。 |
| 避免 | 用它表示需要长期保存的开关设置，这类语义应该交给 `Switch`。 |

## 示例

### 颜色

按下后图标带颜色。工具栏格式用强调色，反应按钮用各自的语义色。

```vue
<script setup lang="ts">
import { Icon } from '@astryx-vue/core/Icon'
import { Stack } from '@astryx-vue/core/Stack'
import { Text } from '@astryx-vue/core/Text'
import { ToggleButton } from '@astryx-vue/core/ToggleButton'
import { reactive } from 'vue'

const toolbar = reactive({ bold: true, italic: false, underline: true, strikethrough: false, link: false })
const reactions = reactive({ star: false, heart: false, bookmark: true, bell: false })

function toggleToolbar(key: keyof typeof toolbar) {
  toolbar[key] = !toolbar[key]
}
function toggleReaction(key: keyof typeof reactions) {
  reactions[key] = !reactions[key]
}
</script>

<template>
  <Stack direction="vertical" :gap="4">
    <Stack direction="vertical" :gap="1">
      <Text type="supporting" color="secondary">
        Toolbar
      </Text>
      <Stack direction="horizontal" :gap="1">
        <ToggleButton label="Bold" :is-pressed="toolbar.bold" is-icon-only @update:is-pressed="toggleToolbar('bold')">
          <template #icon>
            <Icon icon="i-heroicons-bold" color="secondary" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-bold" color="accent" />
          </template>
        </ToggleButton>
        <ToggleButton label="Italic" :is-pressed="toolbar.italic" is-icon-only @update:is-pressed="toggleToolbar('italic')">
          <template #icon>
            <Icon icon="i-heroicons-italic" color="secondary" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-italic" color="accent" />
          </template>
        </ToggleButton>
        <ToggleButton label="Underline" :is-pressed="toolbar.underline" is-icon-only @update:is-pressed="toggleToolbar('underline')">
          <template #icon>
            <Icon icon="i-heroicons-underline" color="secondary" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-underline" color="accent" />
          </template>
        </ToggleButton>
        <ToggleButton label="Strikethrough" :is-pressed="toolbar.strikethrough" is-icon-only @update:is-pressed="toggleToolbar('strikethrough')">
          <template #icon>
            <Icon icon="i-heroicons-strikethrough" color="secondary" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-strikethrough" color="accent" />
          </template>
        </ToggleButton>
        <ToggleButton label="Link" :is-pressed="toolbar.link" is-icon-only @update:is-pressed="toggleToolbar('link')">
          <template #icon>
            <Icon icon="i-heroicons-link" color="secondary" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-link" color="accent" />
          </template>
        </ToggleButton>
      </Stack>
    </Stack>
    <Stack direction="vertical" :gap="1">
      <Text type="supporting" color="secondary">
        Reactions
      </Text>
      <Stack direction="horizontal" :gap="1">
        <ToggleButton label="Star" :is-pressed="reactions.star" is-icon-only @update:is-pressed="toggleReaction('star')">
          <template #icon>
            <Icon icon="i-heroicons-star" color="secondary" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-star-solid" color="yellow" />
          </template>
        </ToggleButton>
        <ToggleButton label="Like" :is-pressed="reactions.heart" is-icon-only @update:is-pressed="toggleReaction('heart')">
          <template #icon>
            <Icon icon="i-heroicons-heart" color="secondary" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-heart-solid" color="red" />
          </template>
        </ToggleButton>
        <ToggleButton label="Save" :is-pressed="reactions.bookmark" is-icon-only @update:is-pressed="toggleReaction('bookmark')">
          <template #icon>
            <Icon icon="i-heroicons-bookmark" color="secondary" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-bookmark-solid" color="blue" />
          </template>
        </ToggleButton>
        <ToggleButton label="Follow" :is-pressed="reactions.bell" is-icon-only @update:is-pressed="toggleReaction('bell')">
          <template #icon>
            <Icon icon="i-heroicons-bell" color="secondary" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-bell-solid" color="accent" />
          </template>
        </ToggleButton>
      </Stack>
    </Stack>
  </Stack>
</template>
```

### 图标切换

纯图标开关在按下时从线框图标换成实心图标。适合收藏、书签或静音这类靠图标本身表达状态的操作。

```vue
<script setup lang="ts">
import { Icon } from '@astryx-vue/core/Icon'
import { Stack } from '@astryx-vue/core/Stack'
import { Text } from '@astryx-vue/core/Text'
import { ToggleButton } from '@astryx-vue/core/ToggleButton'
import { ref } from 'vue'

const isFavorited = ref(false)
const isBookmarked = ref(true)
const isMuted = ref(false)
</script>

<template>
  <Stack direction="vertical" :gap="4">
    <Text type="supporting" color="secondary">
      Outline → solid icon swap on press
    </Text>
    <Stack align="center" direction="horizontal" :gap="3">
      <ToggleButton label="Favorite" :is-pressed="isFavorited" is-icon-only @update:is-pressed="isFavorited = $event">
        <template #icon>
          <Icon icon="i-heroicons-star" />
        </template>
        <template #pressedIcon>
          <Icon icon="i-heroicons-star-solid" />
        </template>
      </ToggleButton>
      <ToggleButton label="Bookmark" :is-pressed="isBookmarked" is-icon-only @update:is-pressed="isBookmarked = $event">
        <template #icon>
          <Icon icon="i-heroicons-bookmark" />
        </template>
        <template #pressedIcon>
          <Icon icon="i-heroicons-bookmark-solid" />
        </template>
      </ToggleButton>
      <ToggleButton
        :label="isMuted ? 'Unmute notifications' : 'Mute notifications'"
        :is-pressed="isMuted"
        is-icon-only
        @update:is-pressed="isMuted = $event"
      >
        <template #icon>
          <Icon icon="i-heroicons-bell" />
        </template>
        <template #pressedIcon>
          <Icon icon="i-heroicons-bell-slash" />
        </template>
      </ToggleButton>
    </Stack>
  </Stack>
</template>
```

### 文字标签

带可见文字的开关，按下后字重会变化。图标单独说不清操作时使用。

```vue
<script setup lang="ts">
import { Icon } from '@astryx-vue/core/Icon'
import { Stack } from '@astryx-vue/core/Stack'
import { Text } from '@astryx-vue/core/Text'
import { ToggleButton, ToggleButtonGroup } from '@astryx-vue/core/ToggleButton'
import { ref } from 'vue'

const isVisible = ref(true)
const filters = ref<string[]>([])
</script>

<template>
  <Stack direction="vertical" :gap="4">
    <Stack direction="vertical" :gap="1">
      <Text type="supporting" color="secondary">
        Standalone with label and icon
      </Text>
      <Stack align="center" direction="horizontal" :gap="3">
        <ToggleButton
          label="Visible"
          :is-pressed="isVisible"
          @update:is-pressed="isVisible = $event"
        >
          <template #icon>
            <Icon :icon="isVisible ? 'i-heroicons-eye' : 'i-heroicons-eye-slash'" />
          </template>
          {{ isVisible ? 'Visible' : 'Hidden' }}
        </ToggleButton>
      </Stack>
    </Stack>
    <Stack direction="vertical" :gap="1">
      <Text type="supporting" color="secondary">
        Labeled group — filter toolbar
      </Text>
      <ToggleButtonGroup v-model:value="filters" type="multiple" label="Filters">
        <ToggleButton value="filter" label="Filter">
          <template #icon>
            <Icon icon="i-heroicons-funnel" />
          </template>
          Filter
        </ToggleButton>
        <ToggleButton value="nearby" label="Nearby">
          <template #icon>
            <Icon icon="i-heroicons-map-pin" />
          </template>
          Nearby
        </ToggleButton>
      </ToggleButtonGroup>
    </Stack>
  </Stack>
</template>
```

### 状态

独立开关的默认、按下、禁用和加载状态。

```vue
<script setup lang="ts">
import { Icon } from '@astryx-vue/core/Icon'
import { Stack } from '@astryx-vue/core/Stack'
import { Text } from '@astryx-vue/core/Text'
import { ToggleButton } from '@astryx-vue/core/ToggleButton'
</script>

<template>
  <Stack direction="vertical" :gap="4">
    <Stack direction="vertical" :gap="1">
      <Text type="supporting" color="secondary">
        Default
      </Text>
      <Stack align="center" direction="horizontal" :gap="3">
        <ToggleButton label="Favorite" :is-pressed="false">
          <template #icon>
            <Icon icon="i-heroicons-star" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-star-solid" />
          </template>
        </ToggleButton>
        <ToggleButton label="Favorite" :is-pressed="false" is-icon-only>
          <template #icon>
            <Icon icon="i-heroicons-star" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-star-solid" />
          </template>
        </ToggleButton>
      </Stack>
    </Stack>
    <Stack direction="vertical" :gap="1">
      <Text type="supporting" color="secondary">
        Pressed
      </Text>
      <Stack align="center" direction="horizontal" :gap="3">
        <ToggleButton label="Favorite" :is-pressed="true">
          <template #icon>
            <Icon icon="i-heroicons-star" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-star-solid" />
          </template>
        </ToggleButton>
        <ToggleButton label="Favorite" :is-pressed="true" is-icon-only>
          <template #icon>
            <Icon icon="i-heroicons-star" />
          </template>
          <template #pressedIcon>
            <Icon icon="i-heroicons-star-solid" />
          </template>
        </ToggleButton>
      </Stack>
    </Stack>
    <Stack direction="vertical" :gap="1">
      <Text type="supporting" color="secondary">
        Disabled
      </Text>
      <Stack align="center" direction="horizontal" :gap="3">
        <ToggleButton label="Favorite" :is-pressed="false" is-disabled>
          <template #icon>
            <Icon icon="i-heroicons-star" />
          </template>
        </ToggleButton>
        <ToggleButton label="Favorite" :is-pressed="false" is-icon-only is-disabled>
          <template #icon>
            <Icon icon="i-heroicons-star" />
          </template>
        </ToggleButton>
      </Stack>
    </Stack>
    <Stack direction="vertical" :gap="1">
      <Text type="supporting" color="secondary">
        Loading
      </Text>
      <Stack align="center" direction="horizontal" :gap="3">
        <ToggleButton label="Favorite" :is-pressed="false" is-loading>
          <template #icon>
            <Icon icon="i-heroicons-star" />
          </template>
        </ToggleButton>
        <ToggleButton label="Favorite" :is-pressed="false" is-icon-only is-loading>
          <template #icon>
            <Icon icon="i-heroicons-star" />
          </template>
        </ToggleButton>
      </Stack>
    </Stack>
  </Stack>
</template>
```

## ToggleButton Props

| 名称 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `label` | `string` | 必需 | 按钮的无障碍名称。有默认插槽内容时它是无障碍名称，纯图标模式下同时是 `aria-label`；两者都没有时它是可见文字。 |
| `isPressed` | `boolean` | `false` | 是否处于按下状态，用 `v-model:is-pressed` 绑定。不绑定该属性时按钮自己管理按下状态，初始为未按下。放入 ToggleButtonGroup 后由分组接管，该属性失效。 |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | 按钮尺寸。留空时沿用所在分组的 size，分组也没有则回退到 `md`。 |
| `elevation` | `'none' \| 'low' \| 'med' \| 'high'` | `'none'` | 静止状态下的阴影强度，用于悬浮样式的切换按钮，取值与 Button 一致。放入分组后每个成员仍保留自己的阴影。 |
| `isDisabled` | `boolean` | `false` | 是否禁用。分组的 isDisabled 会禁用全部成员；成员自己禁用自己时，启用中的分组不会把它重新启用。禁用时标记 `aria-disabled`，不用原生 disabled，按钮仍可获得焦点。 |
| `isLoading` | `boolean` | `false` | 是否显示加载状态。同时设置 `aria-busy`，内容隐藏并显示转圈指示。 |
| `isIconOnly` | `boolean` | `false` | 渲染为正方形纯图标按钮，用 label 作为无障碍名称，不渲染标签文字和占位元素。 |
| `pressedChangeAction` | `(isPressed: boolean) => void \| Promise<void>` | - | 由接口或路由支撑的切换动作。在 `click` 和 `pressedChange` 之后执行，其中任一回调阻止了默认行为就不执行；执行期间按钮显示下一个状态和加载指示，并允许再次点击来反转尚未完成的选择。分组中带 value 的成员会忽略它。 |
| `tooltip` | `string` | - | 悬停和键盘聚焦时显示的文字提示，纯图标按钮常用它补足含义。 |
| `value` | `string` | - | 在 ToggleButtonGroup 中标识自己的值，分组用它判断按下状态；独立使用时不参与表单提交。 |

## ToggleButtonGroup Props

| 名称 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `label` | `string` | 必需 | 分组的无障碍名称，渲染为 `role="group"` 容器上的 `aria-label`。 |
| `type` | `'single' \| 'multiple'` | `'single'` | 选择模式。`single` 只允许一个成员按下，再次点击当前项会取消选择；`multiple` 允许多个成员同时按下。 |
| `value` | `string \| null \| string[]` | `null` | 当前选中的值，用 `v-model:value` 绑定。单选模式是字符串或 `null`，多选模式是字符串数组（默认空数组）。 |
| `orientation` | `'horizontal' \| 'vertical'` | `'horizontal'` | 成员的排列方向。垂直时成员拉伸为整行宽度。 |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | 成员继承的默认尺寸，成员自己设置 `size` 时以成员为准。 |
| `isDisabled` | `boolean` | `false` | 是否禁用全部成员。成员自己设置 `isDisabled` 时同样保持禁用。 |

## 事件

| 名称 | 载荷 | 说明 |
| --- | --- | --- |
| `pressedChange` | `(isPressed: boolean, event: MouseEvent)` | 点击要求切换到的状态和原始的点击事件。在回调里调用 `event.preventDefault()` 表示这次切换由你处理，组件不改写状态，也跳过 `pressedChangeAction`。 |
| `update:isPressed` | `(isPressed: boolean)` | 供 `v-model:is-pressed` 使用。回调阻止默认行为时不会发出。 |
| `click` | `(event: MouseEvent)` | 原始的点击事件。独立按钮上它最先发出，早于 `pressedChange` 和 `pressedChangeAction`；在这里调用 `event.preventDefault()` 会取消这次切换，两者都不会执行。分组里带 value 的成员则在分组完成切换后才发出。按钮被禁用时不会发出。 |
| `change` | `(value: string \| null \| string[])` | 分组的选择结果：单选模式是字符串或 `null`，多选模式是数组。 |

## 插槽

| 名称 | 说明 |
| --- | --- |
| `default` | 可见内容，会取代 label 作为可见文字，无障碍名称仍然取自 label。留空时渲染 label。 |
| `icon` | 标签前的装饰图标；纯图标模式下它是唯一内容。把图标类放进一个有尺寸的元素，例如 `<span class="i-carbon-filter" style="width: 16px; height: 16px" />`，以匹配按钮的图标盒子。 |
| `pressedIcon` | 按下时显示的图标，通常换成一枚实心图标。留空时退回 `icon`。图形的颜色由元素自己决定，所以要传入已经着色的元素，例如 `<span class="i-carbon-stop-filled" style="color: var(--astryx-icon-error-foreground)" />`。 |

ToggleButtonGroup 通过默认插槽接收 ToggleButton：

| 名称 | 说明 |
| --- | --- |
| `default` | 组内的 ToggleButton 成员，每个成员都需要自己的 `value`。 |

## 键盘

| 按键 | 行为 |
| --- | --- |
| `Tab` | 依次聚焦每一个可用的切换按钮；分组不会把成员合并成单个 tab 停靠点。 |
| `Enter` / `Space` | 切换当前焦点所在的按钮，与点击等价。 |

分组本身不拦截方向键：每个成员都是独立的 tab 停靠点，`Tab` 逐个经过，方向键不会在成员之间移动焦点（这一点与 `ButtonGroup` 不同）。禁用的成员同样是 Tab 停靠点（标记为 `aria-disabled`），只是不响应激活。

## 模板引用

`ToggleButton` 公开以下内容：

- `element`：`HTMLButtonElement | HTMLAnchorElement | HTMLElement | null`。
- `focus(options?: FocusOptions)`：聚焦按钮。
- `blur()`：移除按钮焦点。

## 原生属性

根元素为 `<button type="button">`。

以下内容传入根元素：

- HTML 属性。
- `aria-*` 属性。
- `data-*` 属性。
- `class`。
- `style`。
- 原生事件监听器。

`aria-pressed` 由组件根据按下状态设置，`data-pressed`、`data-variant="ghost"` 和 `data-size` 供主题选择器使用，不要覆盖。`aria-label` 在纯图标模式下取自 `label`。

## 无障碍

### 文字

- 准则: 1.4.3 Contrast (Minimum)
- 要求: 4.5:1
- 适用状态: Unselected, Selected, Hover, Pointer down

选中和未选中时，文字和按钮底都要至少 4.5:1。悬停和按下，量的是叠层加上去之后的最终底色。

### 代替文字的图标或转圈弧线

- 准则: 1.4.11 Non-text Contrast
- 要求: 3:1
- 适用状态: Icon only, Loading

只有图标的 ToggleButton，图标和按钮底至少 3:1。转动的那截弧线也要达到 3:1。图标旁边已经有可见文字时，图标不用单独量。

### 选中指示

- 准则: 1.4.11 Non-text Contrast
- 要求: 3:1 if relied upon
- 适用状态: Selected

只有使用者必须靠选中底才能分出选中和未选中时，这块底才要达到 3:1。字重或换过的图标也可以表示选中。

### 看得出的控件边界

- 准则: 1.4.11 Non-text Contrast
- 要求: 3:1 if needed
- 适用状态: Rest

只有使用者必须靠这条边才看得出这是控件时，边才需要 3:1。看得见的文字或图标也可以把控件标出来。

### 键盘焦点指示

- 准则: 1.4.11 Non-text Contrast
- 要求: 3:1
- 适用状态: Focus visible

焦点轮廓和按钮周围至少 3:1。选中和未选中都要量。

### 禁用外观

- 准则: 1.4.3 and 1.4.11 exceptions
- 要求: Not required
- 适用状态: Disabled

禁用的控件不用达到这些对比度。
