在一行按钮里从几个选项中挑一个,指示器会滑向选中项。

用分段控件(segmented control)在几个视图或设置之间切换,比如 List 和 Grid。它像单选组一样工作,只有一个值和一个 Tab 停靠点,指示器会滑向选中的项。

import "@ui-sdk/web/field"
import "@ui-sdk/web/segmented-control"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>View</ui-field-label>
      <ui-segmented-control default-value="list">
        <ui-segmented-control-indicator></ui-segmented-control-indicator>
        <ui-segmented-control-item value="list">List</ui-segmented-control-item>
        <ui-segmented-control-item value="grid">Grid</ui-segmented-control-item>
        <ui-segmented-control-item value="board">Board</ui-segmented-control-item>
      </ui-segmented-control>
    </ui-field>
  `
}

export { mount }
选择 Grid,然后用方向键在视图之间移动。上方的标签为控件提供名称,和任何字段一样。

安装

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

导入组件;如果用到字段,也导入字段,以注册它们的元素。这个 import 在服务器上是安全的。

import "@ui-sdk/web/segmented-control"
import "@ui-sdk/web/field"

组合

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

ui-segmented-control
├── ui-segmented-control-indicator
├── ui-segmented-control-item
└── ui-segmented-control-item

给每一项一个 value。控件的值就是选中项的值,指示器位于该项后面。

用法

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

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

<ui-segmented-control aria-label="View" default-value="list">
  <ui-segmented-control-indicator></ui-segmented-control-indicator>
  <ui-segmented-control-item value="list">List</ui-segmented-control-item>
  <ui-segmented-control-item value="grid">Grid</ui-segmented-control-item>
</ui-segmented-control>

用 aria-label 给控件命名,或把它放进 Field 里,让它的标签为控件提供名称。没有 default-value 时,初始没有任何项被选中,Tab 会进入第一个启用的项。

指示器

ui-segmented-control-indicator 测量选中的项。把它放在控件内部,用它自己的 CSS 变量绘制滑向选中项的背景。项或控件的尺寸变化时,它会重新测量;没有选中任何项时,它没有盒子。有了位置之后,它会得到 data-visible。在此之前,比如在服务器上渲染、脚本还没运行的页面里,它的变量尚未设置,所以要在它 :not([data-visible]) 时隐藏它。

[data-slot="segmented-control"] {
  position: relative;
  display: inline-flex;
  isolation: isolate;
}

[data-slot="segmented-control-indicator"] {
  position: absolute;
  z-index: -1;
  top: var(--segmented-control-indicator-top);
  left: var(--segmented-control-indicator-left);
  width: var(--segmented-control-indicator-width);
  height: var(--segmented-control-indicator-height);
  transition-property: top, left, width, height;
  transition-duration: 200ms;

  &[data-activation-direction="none"] {
    transition: none;
  }
}

在 data-activation-direction 为 "none" 时跳过过渡,避免指示器第一次放置时滑入。之后它会说明选中项往哪个方向移动:left、right、up 或 down。

给它加上 follow-hover,它就会改为跟随指针下方的项,指针离开控件后再回到选中的项。它也会滑过禁用的项。

垂直

设置 orientation="vertical" 把各项堆叠起来。与任何单选组一样,两个轴上的方向键仍然在它们之间移动,每个部件上的 data-orientation 让同一份样式表能布局两个方向。

import "@ui-sdk/web/field"
import "@ui-sdk/web/segmented-control"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <ui-field>
      <ui-field-label>Vertical alignment</ui-field-label>
      <ui-segmented-control orientation="vertical" default-value="middle">
        <ui-segmented-control-indicator></ui-segmented-control-indicator>
        <ui-segmented-control-item value="top">Top</ui-segmented-control-item>
        <ui-segmented-control-item value="middle">Middle</ui-segmented-control-item>
        <ui-segmented-control-item value="bottom">Bottom</ui-segmented-control-item>
      </ui-segmented-control>
    </ui-field>
  `
}

export { mount }
选择 Bottom,然后按上方向键。指示器沿着这一列向下跟随。

禁用

在控件或单个项上设置 disabled。禁用的项无法聚焦,也无法选中,方向键会跳过它们。禁用的控件不提交任何内容。

import "@ui-sdk/web/segmented-control"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="stack">
      <ui-segmented-control aria-label="Theme" default-value="system" disabled>
        <ui-segmented-control-indicator></ui-segmented-control-indicator>
        <ui-segmented-control-item value="light">Light</ui-segmented-control-item>
        <ui-segmented-control-item value="dark">Dark</ui-segmented-control-item>
        <ui-segmented-control-item value="system">System</ui-segmented-control-item>
      </ui-segmented-control>
      <ui-segmented-control aria-label="Billing period" default-value="monthly">
        <ui-segmented-control-indicator></ui-segmented-control-indicator>
        <ui-segmented-control-item value="monthly">Monthly</ui-segmented-control-item>
        <ui-segmented-control-item value="yearly">Yearly</ui-segmented-control-item>
        <ui-segmented-control-item value="lifetime" disabled>Lifetime</ui-segmented-control-item>
      </ui-segmented-control>
    </div>
  `
}

export { mount }
Theme 控件已禁用。在 Billing period 中,Lifetime 已禁用,所以方向键会在 Monthly 和 Yearly 之间移动。

受控

监听 valuechange 获取每次变更及其原因。调用 event.preventDefault() 可以保持当前值。元素的 api property 有相同的方法,比如下面 Show Month 按钮用的 api.setValue("month")。

控制台
import "@ui-sdk/web/segmented-control"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div>
      <div data-slot="controls">
        <button type="button">Show Month</button>
      </div>
      <ui-segmented-control aria-label="Range" default-value="week">
        <ui-segmented-control-indicator></ui-segmented-control-indicator>
        <ui-segmented-control-item value="day">Day</ui-segmented-control-item>
        <ui-segmented-control-item value="week">Week</ui-segmented-control-item>
        <ui-segmented-control-item value="month">Month</ui-segmented-control-item>
      </ui-segmented-control>
    </div>
  `
  const range = root.querySelector("ui-segmented-control")!
  range.addEventListener("valuechange", (event) => {
    const { value, reason } = event.detail
    log(root, `value: ${value} (${reason})`)
  })
  root
    .querySelector('[data-slot="controls"] button')!
    .addEventListener("click", () => range.api.setValue("month"))
}

export { mount }
选择 Day,然后按 Show Month。控制台会记录每次变更及其原因。

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

表单

控件通过 ElementInternals 参与表单。设置 name 以提交选中的值;没有 name 或没有选中的项时,不提交任何内容。required 会阻止提交,直到做出选择;form 设为表单的 id,就能从页面其他地方加入该表单;重置会恢复到 default-value。

控制台
import "@ui-sdk/web/field"
import "@ui-sdk/web/segmented-control"
import { log } from "./log"

function mount(root: HTMLElement) {
  root.innerHTML = `
    <form data-slot="stack">
      <ui-field>
        <ui-field-label>Theme</ui-field-label>
        <ui-segmented-control name="theme" required default-value="system">
          <ui-segmented-control-indicator></ui-segmented-control-indicator>
          <ui-segmented-control-item value="light">Light</ui-segmented-control-item>
          <ui-segmented-control-item value="dark">Dark</ui-segmented-control-item>
          <ui-segmented-control-item value="system">System</ui-segmented-control-item>
        </ui-segmented-control>
        <ui-field-description>System follows your device's setting.</ui-field-description>
      </ui-field>
      <ui-field>
        <ui-field-label>Density</ui-field-label>
        <ui-segmented-control name="density" default-value="comfortable">
          <ui-segmented-control-indicator></ui-segmented-control-indicator>
          <ui-segmented-control-item value="compact">Compact</ui-segmented-control-item>
          <ui-segmented-control-item value="comfortable">Comfortable</ui-segmented-control-item>
        </ui-segmented-control>
      </ui-field>
      <div data-slot="row">
        <button type="submit" data-variant="solid">Save</button>
        <button type="reset">Reset</button>
      </div>
    </form>
  `
  const form = root.querySelector("form")!
  form.addEventListener("submit", (event) => {
    event.preventDefault()
    const data = new FormData(form)
    log(
      root,
      `Saved theme=${data.get("theme")}, density=${data.get("density")}`
    )
  })
}

export { mount }
选择 Dark 和 Compact,然后按 Save。控制台会记录两个值,Reset 会把每个控件恢复到它的默认值。

只读

设置 read-only 可以保留值,同时仍让人聚焦各个项。方向键只移动焦点,不选中任何项,值仍会随表单提交。

循环

方向键会从最后一个项绕回第一个。把 loop 设为 false 可以停在两端。

<ui-segmented-control aria-label="View" default-value="list" loop="false">
  ...
</ui-segmented-control>

样式

部件没有样式。用 data-checked 和 data-unchecked 表示选中的项,用 data-disabled、data-readonly 和 data-required 表示其余状态。data-orientation 在控件和指示器上。

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

ui-segmented-control-indicator

变量内容
--segmented-control-indicator-leftDistance from the control's left edge to the checked item.
--segmented-control-indicator-rightDistance from the control's right edge to the checked item.
--segmented-control-indicator-topDistance from the control's top edge to the checked item.
--segmented-control-indicator-bottomDistance from the control's bottom edge to the checked item.
--segmented-control-indicator-widthWidth of the checked item.
--segmented-control-indicator-heightHeight of the checked item.

数据属性

ui-segmented-control

[data-slot="segmented-control"]

属性含义
data-orientationhorizontalverticalWhich way the items run.
data-readonlyPresent when the control is read-only.
data-requiredPresent when the control is required.
data-disabledPresent when disabled, by its own prop, the control or a <fieldset>.

ui-segmented-control-item

[data-slot="segmented-control-item"]

属性含义
data-checkedPresent on the checked item.
data-readonlyPresent when the control is read-only.
data-requiredPresent when the control is required.
data-uncheckedPresent on items that aren't checked.
data-disabledPresent when disabled, by its own prop, the control or a <fieldset>.

ui-segmented-control-indicator

[data-slot="segmented-control-indicator"]

属性含义
data-orientationhorizontalverticalWhich way the items run.
data-activation-directionnone
data-visiblePresent once the indicator has a position. Its variables are unset until then.

API 参考

props 是以 kebab case 写成的属性,比如 default-value 和 read-only:"false" 表示 false,所以 loop="false" 会关闭循环。value 是实时的 property 和属性。回调是 DOM 事件。

ui-segmented-control

value?T | null
The checked item's value. Pass it to control the segmented control. null checks nothing.
defaultValue?T | null
The item checked at first, when uncontrolled. A form reset returns to it.
valuechange event
Runs when a user or a form reset wants to change the value. details.reason says why, and details.cancel() stops it.
disabled?boolean
Disables every item: they can't be focused or changed, and the value isn't submitted.
readOnly?boolean
Keeps the items focusable and the value submitted, but stops changes.
required?boolean
Blocks form submission until an item is checked, with the browser's own message.
name?string
The name the value submits under. Without one, the segmented control submits nothing.
form?string
The id of a form to belong to, when the segmented control isn't inside that form.
loop?boolean
Whether arrow keys wrap from the last item to the first.
orientation?SegmentedControlOrientation
Which way the items run, for styling and for screen readers. Arrow keys on both axes move between items either way, as in any radio group.
controller?{ getValue: () => T | null; setValue: (value: T | null, details?: SegmentedControlChangeOptions) => boolean; focus: () => void; }
Checks items from anywhere. Create one with createSegmentedControlController().
debug?boolean
Logs every state change with its reason to the console, in development builds.

ui-segmented-control-item

valuestring
What the value becomes when this item is checked.
disabled?boolean
Skips the item, like a disabled native radio: arrow keys pass it and it can't be focused or checked.

ui-segmented-control-indicator

followHover?boolean
Whether it follows the item under the pointer, and goes back to the checked one when the pointer leaves the control.

状态

相同的状态会以数据属性的形式显示在每个元素上。

valuestring | null
The checked item's value.
disabledboolean
Whether the segmented control is disabled, by itself or by a <fieldset>.
readOnlyboolean
Whether it's read-only: arrow keys still move focus, but nothing changes the checked item.
requiredboolean
Whether a form won't submit until an item is checked.
orientationSegmentedControlOrientation
Which way the items run.
checkedboolean
Whether this item is the control's value, which the indicator sits behind.
disabledboolean
Whether this item is disabled, by itself, the segmented control or a <fieldset>.
readOnlyboolean
Whether the control is read-only, so pressing this item changes nothing.
requiredboolean
Whether a form won't submit until an item is checked.
valuestring | null
The checked item's value, which the indicator sits behind.
orientationSegmentedControlOrientation
Which way the items run.
directionDirection
Which way the checked item last moved on screen, "none" before it first moves.

原因

event.detail.reason 说明选中的值为什么改变。

item-pressMouseEvent | KeyboardEvent
A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
list-navigationKeyboardEvent
Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
resetnone
A form reset.
restorenone
The browser restored state, like after going back, or a saved value was read back from storage.
imperativenone
A controller or api call.

控制器

元素的 api property 有相同的方法。value property 读取并设置选中的值。

每个写入方法都接受可选的 { reason, event },像按压一样触发变更事件,并在变更被取消时返回 false。

getValue()() => T | null
The checked item's value.
setValue(value, details?)(value: T | null, details?: SegmentedControlChangeOptions | undefined) => boolean
Checks an item, as a user would. Disabled items and read-only controls ignore it.
focus()() => void
Moves focus to the checked item, or the first one.

事件

事件在各自的元素上触发,不冒泡,新值在 event.detail.value 中,reason 和 event 在它旁边。调用 preventDefault() 会取消变更。

成员所属部件说明
value property, attributeui-segmented-control选中的值。属性设置起始值,且是实时的
api propertyui-segmented-control控制器
valuechange eventui-segmented-controldetail: { value, reason, event, source }

无障碍

分段控件是一个单选组,所以它遵循 WAI-ARIA 单选按钮组模式,行为与共享同一 name 的原生单选按钮一致。ui-segmented-control-item 本身就是控件,带有 radio 角色,分段控件通过 ElementInternals 参与表单,不需要隐藏输入。指示器不带语义,屏幕阅读器会跳过它。

键盘

Key作用
Tab进入控件,停在选中的项或第一个启用的项上
方向键移到下一个或上一个项并选中它,跳过禁用的那些
Space选中当前聚焦的项
Enter提交它的表单

经过测试的行为

下面每一行都是一个自动化测试。

Selection
  • The default item is checked, and only that one.
  • Clicking an item checks it and says why.
  • Clicking a disabled item does nothing.
  • A change can be cancelled.
  • A controller checks an item.
Keyboard
  • Tab lands on the checked item, and the next Tab leaves.
  • Arrow keys on both axes check the next item, skip disabled ones and wrap.
Orientation
  • A segmented control is horizontal unless it says otherwise.
  • A vertical segmented control reports it.
Indicator
  • With followHover, the indicator follows the hovered item and goes back when the pointer leaves.
  • The indicator covers the checked item.
  • The indicator follows the checked item.
  • The indicator says which way the checked item moved, and none at first.
  • The indicator covers the checked item in a vertical control.
  • The indicator matches items with fractional widths exactly.
  • A scaled ancestor doesn't move the indicator off fractional items.
  • With nothing checked, the indicator has no box.
Forms
  • The checked value submits under the control's name.
  • A form reset checks the default item again.
  • A disabled control submits nothing, and its items can't be focused or checked.

运行于 React、Vue 和 web components。