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

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

<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  SegmentedControl,
  SegmentedControlIndicator,
  SegmentedControlItem,
} from "@ui-sdk/vue/segmented-control"
</script>

<template>
  <Field>
    <FieldLabel>View</FieldLabel>
    <SegmentedControl default-value="list">
      <SegmentedControlIndicator />
      <SegmentedControlItem value="list">List</SegmentedControlItem>
      <SegmentedControlItem value="grid">Grid</SegmentedControlItem>
      <SegmentedControlItem value="board">Board</SegmentedControlItem>
    </SegmentedControl>
  </Field>
</template>
选择 Grid,然后用方向键在视图之间移动。上方的标签为控件提供名称,和任何字段一样。

安装

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

组合

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

SegmentedControl
├── SegmentedControlIndicator
├── SegmentedControlItem
└── SegmentedControlItem

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

用法

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

<script setup lang="ts">
import {
  SegmentedControl,
  SegmentedControlIndicator,
  SegmentedControlItem,
} from "@ui-sdk/vue/segmented-control"
</script>

<template>
  <SegmentedControl aria-label="View" default-value="list">
    <SegmentedControlIndicator />
    <SegmentedControlItem value="list">List</SegmentedControlItem>
    <SegmentedControlItem value="grid">Grid</SegmentedControlItem>
  </SegmentedControl>
</template>

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

指示器

SegmentedControlIndicator 测量选中的项。把它放在控件内部,用它自己的 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 让同一份样式表能布局两个方向。

<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  SegmentedControl,
  SegmentedControlIndicator,
  SegmentedControlItem,
} from "@ui-sdk/vue/segmented-control"
</script>

<template>
  <Field>
    <FieldLabel>Vertical alignment</FieldLabel>
    <SegmentedControl orientation="vertical" default-value="middle">
      <SegmentedControlIndicator />
      <SegmentedControlItem value="top">Top</SegmentedControlItem>
      <SegmentedControlItem value="middle">Middle</SegmentedControlItem>
      <SegmentedControlItem value="bottom">Bottom</SegmentedControlItem>
    </SegmentedControl>
  </Field>
</template>
选择 Bottom,然后按上方向键。指示器沿着这一列向下跟随。

禁用

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

<script setup lang="ts">
import {
  SegmentedControl,
  SegmentedControlIndicator,
  SegmentedControlItem,
} from "@ui-sdk/vue/segmented-control"
</script>

<template>
  <div data-slot="stack">
    <SegmentedControl aria-label="Theme" default-value="system" disabled>
      <SegmentedControlIndicator />
      <SegmentedControlItem value="light">Light</SegmentedControlItem>
      <SegmentedControlItem value="dark">Dark</SegmentedControlItem>
      <SegmentedControlItem value="system">System</SegmentedControlItem>
    </SegmentedControl>
    <SegmentedControl aria-label="Billing period" default-value="monthly">
      <SegmentedControlIndicator />
      <SegmentedControlItem value="monthly">Monthly</SegmentedControlItem>
      <SegmentedControlItem value="yearly">Yearly</SegmentedControlItem>
      <SegmentedControlItem value="lifetime" disabled
        >Lifetime</SegmentedControlItem
      >
    </SegmentedControl>
  </div>
</template>
Theme 控件已禁用。在 Billing period 中,Lifetime 已禁用,所以方向键会在 Monthly 和 Yearly 之间移动。

受控

用 v-model:value 绑定值,用 @value-change 拿到原因。在监听器里调用 details.cancel() 可以保持当前值。createSegmentedControlController() 创建的控制器可以从任何地方选中一个项,比如下面的 Show Month 按钮。每个挂载的控件各建一个控制器。

控制台
<script setup lang="ts">
import {
  createSegmentedControlController,
  SegmentedControl,
  SegmentedControlIndicator,
  SegmentedControlItem,
} from "@ui-sdk/vue/segmented-control"
import { ref } from "vue"
import { useLog } from "./log"

const log = useLog()
const range = createSegmentedControlController()
const value = ref<string | null>("week")
</script>

<template>
  <div>
    <div data-slot="controls">
      <button type="button" @click="range.setValue('month')">Show Month</button>
    </div>
    <SegmentedControl
      v-model:value="value"
      aria-label="Range"
      :controller="range"
      @value-change="
        (next, details) => log(`value: ${next} (${details.reason})`)
      "
    >
      <SegmentedControlIndicator />
      <SegmentedControlItem value="day">Day</SegmentedControlItem>
      <SegmentedControlItem value="week">Week</SegmentedControlItem>
      <SegmentedControlItem value="month">Month</SegmentedControlItem>
    </SegmentedControl>
  </div>
</template>
选择 Day,然后按 Show Month。控制台会记录每次变更及其原因。

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

表单

每个项渲染一个隐藏的原生单选按钮,所以控件会参与表单。设置 name 以提交选中的值;没有 name 或没有选中的项时,不提交任何内容。required 会阻止提交,直到做出选择;form 设为表单的 id,就能从页面其他地方加入该表单;重置会恢复到 default-value。

控制台
<script setup lang="ts">
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
import {
  SegmentedControl,
  SegmentedControlIndicator,
  SegmentedControlItem,
} from "@ui-sdk/vue/segmented-control"
import { useLog } from "./log"

const log = useLog()

function submit(event: Event) {
  const data = new FormData(event.currentTarget as HTMLFormElement)
  log(`Saved theme=${data.get("theme")}, density=${data.get("density")}`)
}
</script>

<template>
  <form data-slot="stack" @submit.prevent="submit">
    <Field>
      <FieldLabel>Theme</FieldLabel>
      <SegmentedControl name="theme" required default-value="system">
        <SegmentedControlIndicator />
        <SegmentedControlItem value="light">Light</SegmentedControlItem>
        <SegmentedControlItem value="dark">Dark</SegmentedControlItem>
        <SegmentedControlItem value="system">System</SegmentedControlItem>
      </SegmentedControl>
      <FieldDescription>System follows your device's setting.</FieldDescription>
    </Field>
    <Field>
      <FieldLabel>Density</FieldLabel>
      <SegmentedControl name="density" default-value="comfortable">
        <SegmentedControlIndicator />
        <SegmentedControlItem value="compact">Compact</SegmentedControlItem>
        <SegmentedControlItem value="comfortable"
          >Comfortable</SegmentedControlItem
        >
      </SegmentedControl>
    </Field>
    <div data-slot="row">
      <button type="submit" data-variant="solid">Save</button>
      <button type="reset">Reset</button>
    </div>
  </form>
</template>
选择 Dark 和 Compact,然后按 Save。控制台会记录两个值,Reset 会把每个控件恢复到它的默认值。

只读

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

循环

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

<SegmentedControl aria-label="View" default-value="list" :loop="false">
  ...
</SegmentedControl>

样式

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

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

SegmentedControlIndicator

变量内容
--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.

数据属性

SegmentedControl

[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>.

SegmentedControlItem

[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>.

SegmentedControlIndicator

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

属性与下面相同。onValueChange 是 v-model:value,或用于拿到原因的 @value-change。

SegmentedControl

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.
@value-change((value: T | null, details: ChangeDetails<SegmentedControlValueChangeReason>) => void)
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.

SegmentedControlItem

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.

SegmentedControlIndicator

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.

原因

details.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.

控制器

用 createSegmentedControlController() 创建一个,并作为 controller 传入。

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

事件

事件先收到新值,再收到详情。v-model 只在变更事件没有被取消时更新。

绑定所属部件收到
v-model:valueSegmentedControl选中的值
@value-changeSegmentedControl(value, details):选中的值,以及原因

无障碍

分段控件是一个单选组,所以它遵循 WAI-ARIA 单选按钮组模式,行为与共享同一 name 的原生单选按钮一致。每个 SegmentedControlItem 渲染一个带 radio 角色的按钮,以及一个参与表单的隐藏原生单选按钮。指示器不带语义,屏幕阅读器会跳过它。

键盘

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。