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

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

import { Toggle, ToggleIcon } from "@ui-sdk/solid/toggle"

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">
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z" />
          </svg>
        </ToggleIcon>
      </Toggle>
    </div>
  )
}

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

安装

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

组合

用下面的组合构建一个 Toggle:

Toggle
└── ToggleIcon

以及一个 ToggleGroup:

ToggleGroup
├── Toggle
│   └── ToggleIcon
└── Toggle
    └── ToggleIcon

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

用法

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

import { Toggle, ToggleIcon } from "@ui-sdk/solid/toggle"

function Example() {
  return (
    <Toggle aria-label="Star">
      <ToggleIcon>
        <svg aria-hidden="true">…</svg>
      </ToggleIcon>
    </Toggle>
  )
}

export { Example }

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

分组

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

import { Toggle, ToggleGroup, ToggleIcon } from "@ui-sdk/solid/toggle"

function Example() {
  return (
    <ToggleGroup multiple aria-label="Text formatting">
      <Toggle value="bold" aria-label="Bold">
        <ToggleIcon>
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8" />
          </svg>
        </ToggleIcon>
      </Toggle>
      <Toggle value="italic" aria-label="Italic">
        <ToggleIcon>
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <line x1="19" x2="10" y1="4" y2="4" />
            <line x1="14" x2="5" y1="20" y2="20" />
            <line x1="15" x2="9" y1="4" y2="20" />
          </svg>
        </ToggleIcon>
      </Toggle>
      <Toggle value="underline" aria-label="Underline">
        <ToggleIcon>
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="M6 4v6a6 6 0 0 0 12 0V4" />
            <line x1="4" x2="20" y1="20" y2="20" />
          </svg>
        </ToggleIcon>
      </Toggle>
    </ToggleGroup>
  )
}

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

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

单选

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

import { Toggle, ToggleGroup, ToggleIcon } from "@ui-sdk/solid/toggle"
import { For } from "solid-js"

const icon = (markup: string) => () => (
  <svg
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
    innerHTML={markup}
  />
)
const TextAlignCenter = icon(
  '<path d="M21 5H3" /><path d="M17 12H7" /><path d="M19 19H5" />'
)
const TextAlignEnd = icon(
  '<path d="M21 5H3" /><path d="M21 12H9" /><path d="M21 19H7" />'
)
const TextAlignStart = icon(
  '<path d="M21 5H3" /><path d="M15 12H3" /><path d="M17 19H3" />'
)

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 Example() {
  return (
    <ToggleGroup
      defaultValue={["start"]}
      deselectable={false}
      aria-label="Text alignment"
    >
      <For each={alignments}>
        {(item) => (
          <Toggle value={item.value} aria-label={item.label}>
            <ToggleIcon mirror={item.mirror}>
              <item.icon />
            </ToggleIcon>
          </Toggle>
        )}
      </For>
    </ToggleGroup>
  )
}

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

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

图标与标签

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

<Toggle>
  <ToggleIcon>
    <svg aria-hidden="true">…</svg>
  </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>

受控

传入 pressed,并在 onPressedChange 里更新它。在回调里调用 details.cancel() 可以保持当前状态。createToggleController() 创建的控制器可以从任何地方按压切换按钮,比如键盘快捷键。每个挂载的切换按钮各建一个控制器。

import {
  createToggleController,
  Toggle,
  ToggleIcon,
} from "@ui-sdk/solid/toggle"
import { createSignal } from "solid-js"

function StarButton() {
  const [starred, setStarred] = createSignal(false)
  const star = createToggleController()

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

export { StarButton }

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

受控的分组

传入 value,并在 onValueChange 里更新它,由你自己持有分组的值,或在别处展示它。切换按钮自己的 onPressedChange 先于分组的运行,在任意一个里调用 details.cancel() 都会取消变更。createToggleGroupController() 创建的控制器可以从任何地方更改这个值:setValue([]) 会清空它。

import {
  createToggleGroupController,
  Toggle,
  ToggleGroup,
} from "@ui-sdk/solid/toggle"
import { createSignal } from "solid-js"

function Formatting() {
  const [formats, setFormats] = createSignal(["bold"])
  const editor = 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 }

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

垂直

设置 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 和键盘行为保持连接。渲染约定见部件与组合。

import { Toggle, ToggleIcon } from "@ui-sdk/solid/toggle"

function Example() {
  return (
    <Toggle
      aria-label="Favorite"
      render={(props, state) => (
        <button {...props}>
          <ToggleIcon>
            <svg
              viewBox="0 0 24 24"
              fill={state.pressed ? "currentColor" : "none"}
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5" />
            </svg>
          </ToggleIcon>
        </button>
      )}
    />
  )
}

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

样式

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

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

数据属性

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.

ToggleIcon

[data-slot="toggle-icon"]

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

ToggleGroup

[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 参考

属性和回调与下面相同,都作为 Solid 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.

状态

渲染函数和基于状态的 class、style 和 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 disabled option or a disabled fieldset around it.
orientationToggleGroupOrientation
The group's orientation option, 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 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 控制器

用 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所属部件收到
onPressedChangeToggle(pressed, details):新状态,以及原因。在分组里,它先运行,并且可以取消分组的变更
onValueChangeToggleGroup(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。

在分组里:

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。