# ToggleGroup

> 共享 Button 的 pressed 操作组，支持单选、多选和键盘导航。

网页来源：/components/toggle-group

版本：@quirekit/ui 0.3.1；源码修订：d79a6b48d00e+worktree。此文档对应当前源码构建，接入方式以开始使用为准。

接入前置：[开始使用](/raw/components/getting-started.md)（Vue、样式、主题与图标 Provider）。

ToggleGroup 用共享 Button 表达一组状态操作。沿用当前 Ark 合同：单选输出 radiogroup / radio 与 `aria-checked`，多选输出 group 与 `aria-pressed`。
它支持独立操作的多选、可取消的单选以及自定义动作内容；Segmented 继续用于紧凑的互斥模式选择，Tabs 用于面板切换。

## 单选、多选与尺寸

`items` 使用稳定唯一的 value 和可读 label，可按项 disabled。`v-model` 始终是字符串数组；默认单选，`multiple` 开启独立多选。
单选接受零或一个不同值，传入多个不同值会明确报错；切换到单选前由宿主选择要保留的值。
`deselectable` 默认为 true，可再次按下当前项清空；设为 false 阻止单选项自行取消。

每项直接组合公共 Button。`size` 支持 xs / sm / md / lg / xl，默认 sm，选中使用同色 soft 外观；不会另造一套尺寸。
`item` 插槽提供 `{ item, pressed }`，替换图标或文字时仍保留 item.label 作为动作名称。

```vue
<QuireToggleGroup v-model="formats" :items="items" label="文字样式" multiple />
```

### 示例：toggle-group/basic

文件：`basic.vue`

```vue
<script setup lang="ts">
import { ref } from 'vue';
import type { QuireKitControlSize } from '@quirekit/ui';
import { QuireToggleGroup, QuireSelect, QuireSwitch } from '@quirekit/ui/vue';
const align = ref(['left']);
const format = ref(['bold']);
const readOnly = ref(false);
const disabled = ref(false);
const size = ref<QuireKitControlSize>('sm');
const sizes = ['xs', 'sm', 'md', 'lg', 'xl'].map(value => ({ value, label: value }));
const alignItems = [{ value: 'left', label: '左对齐' }, { value: 'center', label: '居中' }, { value: 'right', label: '右对齐' }];
const formatItems = [{ value: 'bold', label: '加粗' }, { value: 'italic', label: '斜体' }, { value: 'underline', label: '下划线', disabled: true }];
</script>
<template>
  <div class="grid gap-qk-group p-qk-surface" data-toggle-group-demo>
    <div class="flex flex-wrap items-center gap-4"><QuireSelect v-model="size" :items="sizes" label="切换组尺寸" class="w-24" /><QuireSwitch v-model:checked="readOnly" label="只读" /><QuireSwitch v-model:checked="disabled" label="禁用" /></div>
    <QuireToggleGroup v-model="align" :items="alignItems" label="对齐方式" :deselectable="false" :size="size" :read-only="readOnly" :disabled="disabled" />
    <QuireToggleGroup v-model="format" :items="formatItems" label="文字样式" multiple :size="size" :read-only="readOnly" :disabled="disabled" />
    <p class="text-qk-text-secondary" data-choice-value>{{ align.join('、') }} · {{ format.join('、') || '无样式' }}</p>
  </div>
</template>
```

## 键盘与组合

默认 rovingFocus 为 true：Tab 进入一个选项，方向键在启用项间移动，Space/Enter 改变按下状态；Home/End 与循环行为由同一 Ark 焦点模型持有。
`orientation` 支持 horizontal / vertical，`loopFocus` 控制端点循环。
`rovingFocus=false` 让各项使用普通 Tab 顺序，本组不再移动方向键焦点。当前 Ark 仍会消费这些按键事件，因此此选项不代表可以直接把方向键交给外层 Toolbar；已有漫游焦点的 Toolbar 暂不嵌套本组。

`readOnly` 保留焦点与模型、拒绝交互更新；按钮以 aria-disabled 表示当前不可修改，但不使用原生 disabled 移除焦点。
`disabled` 则退出交互与原生表单提交。分组没有自动全局快捷键。

## 状态、方向与五档尺寸

只读与禁用保留当前状态。纵向示例可使用上下方向键；五档并列便于比较尺寸，不需要反复打开选择器。

### 示例：toggle-group/states

文件：`states.vue`

```vue
<script setup lang="ts">
import { QuireToggleGroup } from '@quirekit/ui/vue';
const items = [{ value: 'left', label: '左对齐' }, { value: 'center', label: '居中' }, { value: 'right', label: '右对齐' }];
</script>
<template>
  <div class="grid gap-qk-group p-qk-surface" data-toggle-states>
    <div class="grid gap-qk-inline"><span>只读</span><QuireToggleGroup label="只读对齐" :items="items" :default-value="['left']" read-only /></div>
    <div class="grid gap-qk-inline"><span>禁用</span><QuireToggleGroup label="禁用对齐" :items="items" :default-value="['center']" disabled /></div>
    <div class="grid gap-qk-inline"><span>纵向排列与方向键</span><QuireToggleGroup label="纵向对齐" :items="items" :default-value="['left']" orientation="vertical" /></div>
    <div v-for="size in (['xs', 'sm', 'md', 'lg', 'xl'] as const)" :key="size" class="flex flex-wrap items-center gap-4"><span>{{ size }}</span><QuireToggleGroup :label="`${size} 对齐`" :items="items" :size="size" :default-value="['left']" /></div>
  </div>
</template>
```

## Form 与提交

FormField 继续持有数组值与校验，ToggleGroup 不创建第二份字段注册。
提供 name 时，启用且按下的已知项用重复 name 的隐藏输入参与原生 FormData；readonly 保留，disabled 排除。
原生 reset 只恢复非受控初始值；受控模式由 Form/宿主重置。错误描述与 aria 属性传递给实际的 group 根节点。

### 示例：choice-groups/form

文件：`form.vue`

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { QuireForm, QuireFormField, QuireCheckboxGroup, QuireToggleGroup, QuireButton, QuireSwitch } from '@quirekit/ui/vue';
const readOnly = ref(false);
const disabled = ref(false);
const result = ref('尚未提交');
const items = [{ value: 'email', label: '邮件' }, { value: 'message', label: '站内消息' }];
const modes = [{ value: 'compact', label: '紧凑' }, { value: 'comfortable', label: '舒适' }];
/**
 * Narrows the form's generic field value to this public array contract.
 * @param value - Form-owned unknown field value.
 * @returns Valid string array for the control binding.
 */
function stringValues(value: unknown): string[] { return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []; }
/**
 * Records the validated host submission without a network side effect.
 * @param values - Current values owned by QuireForm.
 */
function save(values: Record<string, unknown>): void { result.value = JSON.stringify(values); }
</script>
<template>
  <div class="grid gap-qk-group p-qk-surface" data-choice-form-demo>
    <div class="flex flex-wrap gap-qk-surface"><QuireSwitch v-model:checked="readOnly" label="表单只读" /><QuireSwitch v-model:checked="disabled" label="表单禁用" /></div>
    <QuireForm validate-on="submit" :initial-values="{ channels: ['email'], density: ['compact'] }" :read-only="readOnly" :disabled="disabled" :on-submit="save">
      <QuireFormField v-slot="{ controlProps, value }" name="channels" label="接收通知" required required-message="至少选择一种通知方式">
        <QuireCheckboxGroup v-bind="controlProps" :model-value="stringValues(value)" :invalid="Boolean(controlProps.invalid)" :items="items" label="接收通知" hide-label orientation="horizontal" />
      </QuireFormField>
      <QuireFormField v-slot="{ controlProps, value }" name="density" label="显示密度" required>
        <QuireToggleGroup v-bind="controlProps" :model-value="stringValues(value)" :invalid="Boolean(controlProps.invalid)" :items="modes" label="显示密度" :deselectable="false" />
      </QuireFormField>
      <template #actions><QuireButton type="submit" variant="solid" color="primary" :disabled="disabled">保存偏好</QuireButton><QuireButton type="reset" variant="outline">重置</QuireButton></template>
    </QuireForm>
    <output class="text-qk-text-secondary" data-form-result>{{ result }}</output>
  </div>
</template>
```

## 网格选项

`columns` 将选项排成等宽网格，`variant="outline"` 为选项保留一致的边框宽度，选中时默认使用主色强调；设置 `color="neutral"` 使用中性色边框、文字和浅底色，适合主题配置等设置面板。可通过 `item` 插槽的 `pressed` 显示勾选标记。单选时设置 `:deselectable="false"` 保留一个选项；左右方向键按数据顺序切换。

### 示例：toggle-group/grid

文件：`grid.vue`

```vue
<script setup lang="ts">
import { QuireToggleGroup } from '@quirekit/ui/vue';
import { ref } from 'vue';
const value = ref(['precision']);
const items = [
  { value: 'precision', label: 'Precision' }, { value: 'ink', label: 'Ink' },
  { value: 'slate', label: 'Slate' }, { value: 'stone', label: 'Stone' }
];
</script>
<template>
  <div class="p-qk-surface">
    <QuireToggleGroup v-model="value" :items="items" label="中性色选项" :columns="2" variant="outline" color="neutral" :deselectable="false" />
  </div>
</template>
```

## API

### QuireToggleGroup

#### Props

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| items | 是 | — | Ordered choices with stable unique values. |
| label | 是 | — | Accessible name for the entire group. |
| modelValue | 否 | — | Controlled values, owned by the host. |
| defaultValue | 否 | — | Initial non-controlled selection. |
| size | 否 | "sm" | Shared action/choice density. |
| orientation | 否 | "horizontal" | Visual and keyboard arrangement. |
| columns | 否 | — | Optional equal-width columns; horizontal arrow keys retain item order. |
| variant | 否 | "ghost" | Action appearance; outline retains border geometry and adds a soft fill when selected. |
| color | 否 | "primary" | Selected outline color; defaults to primary. Ghost actions remain neutral. |
| disabled | 否 | false | Disable all options and native submission. |
| readOnly | 否 | false | Preserve focus and values while rejecting interactive changes. |
| name | 否 | — | Repeated native form field name. |
| form | 否 | — | External native form association. |
| invalid | 否 | false | Expose validation failure supplied by the owning field. |
| multiple | 否 | false | Allow several independent pressed values; false by default. |
| deselectable | 否 | true | Allow clearing a single selection by pressing it again. |
| rovingFocus | 否 | true | Use group arrow-key navigation; false uses individual Tab stops, not outer-toolbar delegation. |
| loopFocus | 否 | true | Loop at the first and last enabled actions. |

**items**

```ts
readonly QuireKitToggleGroupItem[]
```

```ts
readonly ({
  /** Stable unique action value. */
  value: string;
  /** Accessible action name, retained for custom icon content. */
  label: string;
  /** Prevent this action from changing state. */
  disabled?: boolean | undefined;
})[]
```

**label**

```ts
string
```

**modelValue**

```ts
readonly string[] | undefined
```

```ts
undefined | readonly (string)[]
```

**defaultValue**

```ts
readonly string[] | undefined
```

```ts
undefined | readonly (string)[]
```

**size**

```ts
QuireKitControlSize | undefined
```

```ts
undefined | "xs" | "sm" | "md" | "lg" | "xl"
```

**orientation**

```ts
"vertical" | "horizontal" | undefined
```

```ts
undefined | "vertical" | "horizontal"
```

**columns**

```ts
number | undefined
```

```ts
undefined | number
```

**variant**

```ts
"outline" | "ghost" | undefined
```

```ts
undefined | "outline" | "ghost"
```

**color**

```ts
"neutral" | "primary" | undefined
```

```ts
undefined | "neutral" | "primary"
```

**disabled**

```ts
boolean | undefined
```

**readOnly**

```ts
boolean | undefined
```

**name**

```ts
string | undefined
```

```ts
undefined | string
```

**form**

```ts
string | undefined
```

```ts
undefined | string
```

**invalid**

```ts
boolean | undefined
```

**multiple**

```ts
boolean | undefined
```

**deselectable**

```ts
boolean | undefined
```

**rovingFocus**

```ts
boolean | undefined
```

**loopFocus**

```ts
boolean | undefined
```

#### Events

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| update\:modelValue | 否 | — |  |

**update:modelValue**

```ts
[value: string[]]
```

#### Slots

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| item | 否 | — | Replace visible action content, retaining its accessible label and pressed behavior. |

**item**

```ts
{ item: QuireKitToggleGroupItem; pressed: boolean; }
```

```ts
{
  item: {
    /** Stable unique action value. */
    value: string;
    /** Accessible action name, retained for custom icon content. */
    label: string;
    /** Prevent this action from changing state. */
    disabled?: boolean | undefined;
  };
  pressed: boolean;
}
```

#### 公开实例成员

无。

#### 相关类型

```ts
type QuireKitToggleGroupItem = {
  /** Stable unique action value. */
  value: string;
  /** Accessible action name, retained for custom icon content. */
  label: string;
  /** Prevent this action from changing state. */
  disabled?: boolean | undefined;
};
```
