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

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

import "@ui-sdk/web/toggle"
import { createElement, Star } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="card">
      <div data-slot="stack">
        <h3>Q3 Roadmap</h3>
        <p data-slot="hint">Edited by Hollis Grant</p>
      </div>
      <ui-toggle>
        <button aria-label="Star">
          <ui-toggle-icon data-variant="fill">${createElement(Star, { "aria-hidden": "true" }).outerHTML}</ui-toggle-icon>
        </button>
      </ui-toggle>
    </div>
  `
}

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

安装

npm install @ui-sdk/web @ui-sdk/core

导入组件会定义它的元素。在服务器上,导入不做任何事。

import "@ui-sdk/web/toggle"

组合

用下面的组合构建一个 ui-toggle:

ui-toggle
└── button
    └── ui-toggle-icon

以及一个 ui-toggle-group:

ui-toggle-group
├── ui-toggle
│   └── button
│       └── ui-toggle-icon
└── ui-toggle
    └── button
        └── ui-toggle-icon

ui-toggle 包装一个原生按钮,用 aria-pressed 报告它的状态。ui-toggle-icon 是可选的:它容纳一个图标,并对屏幕阅读器隐藏。在分组里,给每个切换按钮一个 value;分组的值列出已按下的那些。

用法

导入部件并把它们组合起来:

<script type="module">
  import "@ui-sdk/web/toggle"
</script>

<ui-toggle>
  <button aria-label="Star">
    <ui-toggle-icon><svg aria-hidden="true">…</svg></ui-toggle-icon>
  </button>
</ui-toggle>

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

分组

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

import "@ui-sdk/web/toggle"
import { Bold, createElement, Italic, Underline } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-toggle-group multiple aria-label="Text formatting">
      <ui-toggle value="bold">
        <button aria-label="Bold">
          <ui-toggle-icon>${createElement(Bold, { "aria-hidden": "true" }).outerHTML}</ui-toggle-icon>
        </button>
      </ui-toggle>
      <ui-toggle value="italic">
        <button aria-label="Italic">
          <ui-toggle-icon>${createElement(Italic, { "aria-hidden": "true" }).outerHTML}</ui-toggle-icon>
        </button>
      </ui-toggle>
      <ui-toggle value="underline">
        <button aria-label="Underline">
          <ui-toggle-icon>${createElement(Underline, { "aria-hidden": "true" }).outerHTML}</ui-toggle-icon>
        </button>
      </ui-toggle>
    </ui-toggle-group>
  `
}

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

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

单选

不设 multiple 时,按下一个切换按钮会取消其他按钮的按下状态。再次按压已按下的切换按钮会清除选择,除非你像这个对齐分组一样设置 deselectable="false"。deselectable 不会替你选择初始值,所以要配合 default-value 使用。它只限制人们能做什么:元素的 api.setValue([]) 仍然会清空分组。

import "@ui-sdk/web/toggle"
import {
  createElement,
  TextAlignCenter,
  TextAlignEnd,
  TextAlignStart,
} from "lucide"

const alignments = [
  { value: "start", label: "Align start", icon: TextAlignStart, mirror: true },
  {
    value: "center",
    label: "Align center",
    icon: TextAlignCenter,
    mirror: false,
  },
  { value: "end", label: "Align end", icon: TextAlignEnd, mirror: true },
]

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-toggle-group default-value="start" deselectable="false" aria-label="Text alignment">
      ${alignments
        .map(
          (item) => `
            <ui-toggle value="${item.value}">
              <button aria-label="${item.label}">
                <ui-toggle-icon${item.mirror ? " mirror" : ""}>${createElement(item.icon, { "aria-hidden": "true" }).outerHTML}</ui-toggle-icon>
              </button>
            </ui-toggle>
          `
        )
        .join("")}
    </ui-toggle-group>
  `
}

export { mount }
按 Align center 代替 Align start,然后再按一次 Align center。始终有一个对齐方式保持按下。

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

图标与标签

用 ui-toggle-icon 把图标放在标签旁边。图标对屏幕阅读器隐藏,所以只靠文字为按钮命名。

<ui-toggle>
  <button>
    <ui-toggle-icon><svg aria-hidden="true">…</svg></ui-toggle-icon>
    Pin
  </button>
</ui-toggle>

禁用

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

<ui-toggle disabled default-pressed>
  <button>Pin</button>
</ui-toggle>

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

<ui-toggle-group multiple aria-label="Text formatting">
  <ui-toggle value="bold"><button>Bold</button></ui-toggle>
  <ui-toggle value="italic"><button>Italic</button></ui-toggle>
  <ui-toggle value="underline" disabled><button>Underline</button></ui-toggle>
</ui-toggle-group>

禁用时仍可聚焦

设置 focusable-when-disabled 让禁用的切换按钮仍可聚焦。它使用 aria-disabled,并且仍然忽略按压。用 aria-describedby 说明它为什么不可用:

<ui-toggle disabled focusable-when-disabled>
  <button aria-describedby="pin-hint">Pin</button>
</ui-toggle>
<p id="pin-hint">Only owners can pin messages.</p>

受控

读取或设置元素的 pressed property,并监听 pressedchange。设置这个 property 会安静地提交,就像原生输入框的 value。在监听器里调用 event.preventDefault() 可以保持当前状态。元素的 api 可以从任何地方按压切换按钮,比如键盘快捷键。

<ui-toggle>
  <button aria-label="Star">
    <ui-toggle-icon><svg aria-hidden="true">…</svg></ui-toggle-icon>
  </button>
</ui-toggle>
<button type="button" id="toggle-star">Toggle Star</button>

<script type="module">
  import "@ui-sdk/web/toggle"

  let starred = false
  const star = document.querySelector("ui-toggle")
  star.pressed = starred
  star.addEventListener(
    "pressedchange",
    (event) => (starred = event.detail.value)
  )
  document
    .querySelector("#toggle-star")
    .addEventListener("click", () => star.api.toggle())
</script>

event.detail 用 value 保存新状态,并带有一个 reason,值为 "press" 或 "imperative"。

受控的分组

读取或设置分组元素的 value property,并监听 valuechange,由你自己持有分组的值,或在别处展示它。切换按钮的 pressedchange 先于分组的 valuechange 触发,在任意一个上调用 event.preventDefault() 都会取消变更。元素的 api 可以从任何地方更改这个值:api.setValue([]) 会清空它。

<ui-toggle-group multiple aria-label="Text formatting">
  <ui-toggle value="bold"><button>Bold</button></ui-toggle>
  <ui-toggle value="italic"><button>Italic</button></ui-toggle>
</ui-toggle-group>
<button type="button" id="clear-formatting">Clear Formatting</button>

<script type="module">
  import "@ui-sdk/web/toggle"

  let formats = ["bold"]
  const editor = document.querySelector("ui-toggle-group")
  editor.value = formats
  editor.addEventListener(
    "valuechange",
    (event) => (formats = event.detail.value)
  )
  document
    .querySelector("#clear-formatting")
    .addEventListener("click", () => editor.api.setValue([]))
</script>

受控状态、取消和调试见状态与事件。

垂直

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

<ui-toggle-group orientation="vertical" aria-label="Tool">
  ...
</ui-toggle-group>

循环

方向键会从最后一个切换按钮绕回第一个。设置 loop="false" 可以停在两端。

<ui-toggle-group multiple loop="false" aria-label="Text formatting">
  ...
</ui-toggle-group>

表单

切换按钮不提交值。表单里需要多选时用 Checkbox,单选时用 Radio。如果要在表单里保留切换按钮组,就自己把它的值复制到隐藏的输入框里。

自定义渲染

元素没有渲染函数。ui-toggle 包装你自己的 <button>,所以把任何内容放进去,并从元素读取状态:切换按钮的 pressed property,或分组的 value,即已按下的值。把按钮留在 ui-toggle 里面,让它的 aria-pressed 和键盘行为保持连接。这里一个 pressedchange 监听器设置心形的 fill。渲染约定见部件与组合。

import "@ui-sdk/web/toggle"
import { createElement, Heart } from "lucide"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-toggle>
      <button aria-label="Favorite">
        <ui-toggle-icon>${createElement(Heart, { "aria-hidden": "true" }).outerHTML}</ui-toggle-icon>
      </button>
    </ui-toggle>
  `
  const favorite = root.querySelector("ui-toggle")!
  const heart = root.querySelector("svg")!
  const render = (pressed: boolean) =>
    heart.setAttribute("fill", pressed ? "currentColor" : "none")
  render(favorite.pressed)
  favorite.addEventListener("pressedchange", (event) =>
    render(event.detail.value)
  )
}

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

样式

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

每个部件都有一个 data-slot,比如 toggle,它的状态属性列在数据属性下。切换按钮的属性落在它的按钮上。

数据属性

<ui-toggle>

[data-slot="toggle"]

属性含义
data-pressedPresent while pressed.
data-disabledPresent when disabled, by its own prop or its group.
data-orientationhorizontalverticalInside a group, the group's orientation.
data-has-iconPresent while the toggle holds an icon part.

<ui-toggle-icon>

[data-slot="toggle-icon"]

属性含义
data-mirrorPresent on an icon that flips in right-to-left text, with mirror.

<ui-toggle-group>

[data-slot="toggle-group"]

属性含义
data-orientationhorizontalverticalWhich arrow keys move between toggles.
data-disabledPresent when the whole group is disabled.
data-has-iconsPresent while any toggle inside holds an icon part, so toggles without one can line up.

API 参考

属性以 kebab case 写成,比如 default-pressed 和 focusable-when-disabled:"false" 表示 false,如 deselectable="false" 和 loop="false"。分组的 value 和 default-value 接受逗号分隔的值,比如 default-value="bold,italic"。pressed 是实时的 property 和属性。回调是 DOM 事件。元素没有 controller 属性:它的 api property 就是控制器。

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.
pressedchange event
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 valuechange, 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.
valuechange event
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.

状态

相同的状态会作为数据属性显示在每个按钮和分组上。

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 disabled option or a disabled fieldset around it.
orientationToggleGroupOrientation
The group's orientation option, or "horizontal" when it's unset or invalid.

ui-toggle-icon:

mirrorboolean
Whether it flips in right-to-left text.

原因

event.detail.reason 说明切换按钮为什么被按下或取消按下。

pressMouseEvent | KeyboardEvent
A single-element control was pressed: a checkbox, a switch or a toggle.
imperativenone
A controller or api call.

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

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 api call.

Toggle 控制器

元素的 api property 有相同的方法。pressed property 读取和设置状态。

每个写入方法都接受可选的 { 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 控制器

元素的 api property 有相同的方法。value property 读取和设置已按下的切换按钮。

每个写入方法都接受可选的 { reason, event },像按压一样触发 valuechange,并在变更被取消时返回 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.

事件

事件在各自的元素上触发,不会冒泡,新状态或值在 event.detail.value 里,reason、event 和 source 在旁边。调用 preventDefault() 会取消变更。valuechange 从不在连接时触发。

成员所属部件说明
pressed property, attributeui-toggle切换按钮是否被按下。属性设置起始值,且是实时的
api propertyui-toggle控制器
pressedchange eventui-toggledetail: { value: pressed, reason, event, source }。在分组里,它先于分组的 valuechange 触发,并且可以取消它
value propertyui-toggle-group已按下的切换按钮的值。设置它会按下切换按钮
api propertyui-toggle-group控制器
valuechange eventui-toggle-groupdetail: { value, reason, event, source }

无障碍

切换按钮遵循 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。

在分组里:

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.

运行于 React、Vue 和 web components。