# Segmented Control

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

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

```ts title="basic.ts"
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，然后用方向键在视图之间移动。上方的标签为控件提供名称，和任何字段一样。

## 安装
```bash
npm install @ui-sdk/web @ui-sdk/core
```

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

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

## 组合
用下面的组合构建一个 `ui-segmented-control`：

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

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

## 用法
导入部件并把它们组合起来：

```html
<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](/docs/web-components/components/field) 里，让它的标签为控件提供名称。没有 `default-value` 时，初始没有任何项被选中，Tab 会进入第一个启用的项。

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

```css
[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` 让同一份样式表能布局两个方向。

```ts title="vertical.ts"
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`。禁用的项无法聚焦，也无法选中，方向键会跳过它们。禁用的控件不提交任何内容。

```ts title="disabled.ts"
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")`。

```ts title="controlled.ts"
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。控制台会记录每次变更及其原因。

受控状态、取消和调试见[状态与事件](/docs/web-components/state-and-events)。

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

```ts title="form.ts"
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` 可以停在两端。

```html
<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`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/web-components/components/segmented-control#data-attributes)下。

### ui-segmented-control-indicator
- `--segmented-control-indicator-left`: Distance from the control's left edge to the checked item.
- `--segmented-control-indicator-right`: Distance from the control's right edge to the checked item.
- `--segmented-control-indicator-top`: Distance from the control's top edge to the checked item.
- `--segmented-control-indicator-bottom`: Distance from the control's bottom edge to the checked item.
- `--segmented-control-indicator-width`: Width of the checked item.
- `--segmented-control-indicator-height`: Height of the checked item.

## 数据属性
### ui-segmented-control
`[data-slot="segmented-control"]`

- `data-orientation` (`horizontal`, `vertical`): Which way the items run.
- `data-readonly`: Present when the control is read-only.
- `data-required`: Present when the control is required.
- `data-disabled`: Present when disabled, by its own prop, the control or a `<fieldset>`.

### ui-segmented-control-item
`[data-slot="segmented-control-item"]`

- `data-checked`: Present on the checked item.
- `data-readonly`: Present when the control is read-only.
- `data-required`: Present when the control is required.
- `data-unchecked`: Present on items that aren't checked.
- `data-disabled`: Present when disabled, by its own prop, the control or a `<fieldset>`.

### ui-segmented-control-indicator
`[data-slot="segmented-control-indicator"]`

- `data-orientation` (`horizontal`, `vertical`): Which way the items run.
- `data-activation-direction` (`none`)
- `data-visible`: Present 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
- `value` (`string`): 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.

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

- `value` (`string | null`): The checked item's value.
- `disabled` (`boolean`): Whether the segmented control is disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether it's read-only: arrow keys still move focus, but nothing changes the checked item.
- `required` (`boolean`): Whether a form won't submit until an item is checked.
- `orientation` (`SegmentedControlOrientation`): Which way the items run.

- `checked` (`boolean`): Whether this item is the control's value, which the indicator sits behind.
- `disabled` (`boolean`): Whether this item is disabled, by itself, the segmented control or a `<fieldset>`.
- `readOnly` (`boolean`): Whether the control is read-only, so pressing this item changes nothing.
- `required` (`boolean`): Whether a form won't submit until an item is checked.

- `value` (`string | null`): The checked item's value, which the indicator sits behind.
- `orientation` (`SegmentedControlOrientation`): Which way the items run.
- `direction` (`Direction`): Which way the checked item last moved on screen, `"none"` before it first moves.

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

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `list-navigation` (`KeyboardEvent`): Arrow, Home or End keys moved the selection, typing picked an item, or Ctrl or ⌘ with A selected every item of a listbox.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): 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, attribute | `ui-segmented-control` | 选中的值。属性设置起始值，且是实时的       |
| `api` property              | `ui-segmented-control` | [控制器](https://ui-sdk.cn/docs/web-components/components/segmented-control#controller)                      |
| `valuechange` event         | `ui-segmented-control` | `detail: { value, reason, event, source }` |

## 无障碍
分段控件是一个单选组，所以它遵循 [WAI-ARIA 单选按钮组模式](https://www.w3.org/WAI/ARIA/apg/patterns/radio/)，行为与共享同一 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.

Runs in React、Vue 和 web components.
