Toggle
让按钮保持按下,或者把多个切换按钮组合在一起,共用一个值并支持方向键导航。
用切换按钮表示一个按压后会保持开启、直到再次按压才关闭的按钮,比如给文档标星或打开 Bold。把几个切换按钮放进一个切换按钮组,共用一个值,就像文本编辑器的格式按钮或视图切换器那样。
<script lang="ts">
import { StarIcon } from "@lucide/svelte"
import { Toggle, ToggleIcon } from "@ui-sdk/svelte/toggle"
</script>
<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>安装
npm install @ui-sdk/svelte @ui-sdk/core组合
用下面的组合构建一个 Toggle:
Toggle
└── ToggleIcon以及一个 ToggleGroup:
ToggleGroup
├── Toggle
│ └── ToggleIcon
└── Toggle
└── ToggleIconToggle 渲染一个原生按钮,用 aria-pressed 报告它的状态。ToggleIcon 是可选的:它容纳一个图标,并对屏幕阅读器隐藏。在分组里,给每个切换按钮一个 value;分组的值列出已按下的那些。
用法
导入部件并把它们组合起来:
<script lang="ts">
import { StarIcon } from "@lucide/svelte"
import { Toggle, ToggleIcon } from "@ui-sdk/svelte/toggle"
</script>
<Toggle aria-label="Star">
<ToggleIcon>
<StarIcon />
</ToggleIcon>
</Toggle>让标签在两种状态下保持一致:屏幕阅读器会播报按钮是否被按下。只有图标的切换按钮需要一个 aria-label,如上所示。设置 defaultPressed 让它一开始就是按下状态。切换按钮始终使用 type="button",所以按压它永远不会提交表单。
分组
把切换按钮放进同一个 @ui-sdk/svelte/toggle 入口的 ToggleGroup,共用一个值并支持方向键导航。给分组一个无障碍名称,给每个切换按钮一个 value。设置 multiple,让多个切换按钮可以同时保持按下。
<script lang="ts">
import { BoldIcon, ItalicIcon, UnderlineIcon } from "@lucide/svelte"
import { Toggle, ToggleGroup, ToggleIcon } from "@ui-sdk/svelte/toggle"
</script>
<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>分组持有哪些切换按钮被按下的状态,所以切换按钮自己的 pressed 和 defaultPressed 在分组里不生效。它的值始终是一个数组,按切换按钮在文档中的顺序排列。
单选
不设 multiple 时,按下一个切换按钮会取消其他按钮的按下状态。再次按压已按下的切换按钮会清除选择,除非你像这个对齐分组一样把 deselectable 设为 false。deselectable 不会替你选择初始值,所以要配合 defaultValue 使用。它只限制人们能做什么:控制器的 setValue([]) 仍然会清空分组。
<script lang="ts">
import {
TextAlignCenterIcon,
TextAlignEndIcon,
TextAlignStartIcon,
} from "@lucide/svelte"
import { Toggle, ToggleGroup, ToggleIcon } from "@ui-sdk/svelte/toggle"
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 },
]
</script>
<ToggleGroup
defaultValue={["start"]}
deselectable={false}
aria-label="Text alignment"
>
{#each alignments as item (item.value)}
<Toggle value={item.value} aria-label={item.label}>
<ToggleIcon mirror={item.mirror}>
<item.icon />
</ToggleIcon>
</Toggle>
{/each}
</ToggleGroup>Align start 和 Align end 上的 mirror 会在从右到左(RTL)的文本里翻转它们的图标。如果希望方向键移动时就选中选项,就改用 Radio;切换按钮组先移动焦点,再等待一次按压。
图标与标签
用 ToggleIcon 把图标放在标签旁边。图标对屏幕阅读器隐藏,所以只靠文字为按钮命名。
<Toggle>
<ToggleIcon>
<PinIcon />
</ToggleIcon>
Pin
</Toggle>禁用
在切换按钮或分组上设置 disabled 来阻止按压。禁用的切换按钮仍然可以一开始就是按下状态,包裹它的禁用 <fieldset> 也会禁用它。
<Toggle disabled defaultPressed>Pin</Toggle>单独一个禁用的切换按钮会离开 Tab 顺序。在分组里,禁用的切换按钮仍可用方向键到达,并报告 aria-disabled,但会忽略按压。
<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 说明它为什么不可用:
<Toggle disabled focusableWhenDisabled aria-describedby="pin-hint">Pin</Toggle>
<p id="pin-hint">Only owners can pin messages.</p>受控
绑定 bind:pressed,或传入 pressed 并处理 onPressedChange,由你自己持有状态。在 onPressedChange 里调用 details.cancel() 可以保持当前状态。createToggleController() 创建的控制器可以从任何地方按压切换按钮,比如键盘快捷键。每个挂载的切换按钮各建一个控制器。
<script lang="ts">
import { StarIcon } from "@lucide/svelte"
import {
createToggleController,
Toggle,
ToggleIcon,
} from "@ui-sdk/svelte/toggle"
let starred = $state(false)
const star = createToggleController()
</script>
<Toggle aria-label="Star" bind:pressed={starred} controller={star}>
<ToggleIcon>
<StarIcon />
</ToggleIcon>
</Toggle>
<button type="button" onclick={() => star.toggle()}>Toggle Star</button>onPressedChange 收到新状态和 details,它的 reason 是 "press" 或 "imperative"。
受控的分组
绑定 bind:value,或传入 value 并处理 onValueChange,由你自己持有分组的值,或在别处展示它。切换按钮自己的 onPressedChange 先于分组的运行,在任意一个里调用 details.cancel() 都会取消变更。createToggleGroupController() 创建的控制器可以从任何地方更改这个值:setValue([]) 会清空它。
<script lang="ts">
import {
createToggleGroupController,
Toggle,
ToggleGroup,
} from "@ui-sdk/svelte/toggle"
let formats = $state(["bold"])
const editor = createToggleGroupController()
</script>
<ToggleGroup
multiple
aria-label="Text formatting"
bind:value={formats}
controller={editor}
>
<Toggle value="bold">Bold</Toggle>
<Toggle value="italic">Italic</Toggle>
</ToggleGroup>
<button type="button" onclick={() => editor.setValue([])}
>Clear Formatting</button
>受控状态、取消和调试见状态与事件。
垂直
设置 orientation="vertical" 改用上、下方向键移动,而不是左、右方向键。分组和它的切换按钮会得到 data-orientation。
<ToggleGroup orientation="vertical" aria-label="Tool">...</ToggleGroup>循环
方向键会从最后一个切换按钮绕回第一个。把 loop 设为 false 可以停在两端。
<ToggleGroup multiple loop={false} aria-label="Text formatting">
...
</ToggleGroup>表单
切换按钮不提交值。表单里需要多选时用 Checkbox,单选时用 Radio。如果要在表单里保留切换按钮组,就自己把它的值复制到隐藏的输入框里。
自定义渲染
每个部件都接受一个 render 片段,它接收要展开的 props 和部件的状态。切换按钮的状态有 pressed,分组的状态有 value,即已按下的值。把部件的 props 留在按钮上,让它的 aria-pressed 和键盘行为保持连接。渲染约定见部件与组合。
<script lang="ts">
import { HeartIcon } from "@lucide/svelte"
import { Toggle, ToggleIcon } from "@ui-sdk/svelte/toggle"
</script>
<Toggle aria-label="Favorite">
{#snippet render({ props, state })}
<button {...props}>
<ToggleIcon>
<HeartIcon fill={state.pressed ? "currentColor" : "none"} />
</ToggleIcon>
</button>
{/snippet}
</Toggle>样式
用 data-pressed 为按下状态设置样式,用 data-disabled 表示不可用的切换按钮。带 ToggleIcon 的切换按钮会得到 data-has-icon,只要有一个切换按钮带图标,它所在的分组就会得到 data-has-icons,这有助于对齐图标和文字内容。data-orientation 告诉分组的切换按钮它朝哪个方向运行。
每个部件都有一个 data-slot,比如 toggle,它的状态属性列在数据属性下。
数据属性
Toggle
[data-slot="toggle"]
| 属性 | 含义 |
|---|---|
data-pressed | Present while pressed. |
data-disabled | Present when disabled, by its own prop or its group. |
data-orientation | horizontalverticalInside 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 | horizontalverticalWhich 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 参考
属性和回调与下面相同,都作为 Svelte props。pressed 和分组的 value 可以用 bind:pressed 和 bind:value 绑定。
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.reasonsays why, anddetails.cancel()stops it. Inside a group, it runs before the group'sonValueChange, 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
focusableWhenDisabledis set. Inside a group or a toolbar, it stays focusable witharia-disabled, so arrow keys still reach it. focusableWhenDisabled?boolean- Keeps a disabled toggle in the tab order with
aria-disabledinstead 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.reasonsays why, anddetails.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, thoughsetValue([])still clears it. Ignored withmultiple. 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.
状态
render 和 children 片段收到什么。
pressedboolean- Whether it's pressed. Inside a group, it follows the group's value.
disabledboolean- Whether it's disabled, by itself, its group or a fieldset around it.
在分组里,切换按钮的 disabled 包含分组的。分组:
valueT[]- The pressed toggles' values.
multipleboolean- Whether several toggles can be pressed at once.
disabledboolean- Whether the whole group is disabled, by its
disabledoption or a disabled fieldset around it. orientationToggleGroupOrientation- The group's
orientationoption, or"horizontal"when it's unset or invalid.
ToggleIcon:
mirrorboolean- Whether it flips in right-to-left text.
原因
details.reason 说明切换按钮为什么被按下或取消按下。
pressMouseEvent | KeyboardEvent- A single-element control was pressed: a checkbox, a switch or a toggle.
imperativenone- A controller or
apicall.
对分组来说,它说明已按下的切换按钮为什么发生了变化。
item-pressMouseEvent | KeyboardEvent- A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
imperativenone- A controller or
apicall.
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
multipleis 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 从不在挂载时运行。绑定的 pressed 或 value 只有在回调没有取消变更时才会更新。
| Prop | 所属部件 | 收到 |
|---|---|---|
bind:pressed | Toggle | 切换按钮是否被按下 |
onPressedChange | Toggle | (pressed, details):新状态,以及原因。在分组里,它先运行,并且可以取消分组的变更 |
bind:value | ToggleGroup | 已按下的切换按钮的值 |
onValueChange | ToggleGroup | (value, details):已按下的切换按钮的值,以及原因 |
无障碍
切换按钮遵循 WAI-ARIA 按钮模式里的切换按钮:一个带 aria-pressed 的原生按钮。分组遵循 WAI-ARIA 工具栏模式的键盘操作,只有一个 Tab 停靠点,切换按钮之间用方向键移动。它的角色是 group,不是 toolbar,所以可以放进 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.
运行于 React、Vue 和 web components。
在分组里:
- 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.
- Pressing toggles adds them to the value.
- A disabled toggle can't be pressed.
- A disabled group presses nothing.
- 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.
- With loop off, arrows stop at the ends.
- A vertical group moves with ArrowDown and ArrowUp.
- The group carries its orientation.
运行于 React、Vue 和 web components。