# Segmented Control

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

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

```tsx title="basic.tsx"
"use client"

import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
  SegmentedControl,
  SegmentedControlIndicator,
  SegmentedControlItem,
} from "@ui-sdk/react/segmented-control"

function Example() {
  return (
    <Field>
      <FieldLabel>View</FieldLabel>
      <SegmentedControl defaultValue="list">
        <SegmentedControlIndicator />
        <SegmentedControlItem value="list">List</SegmentedControlItem>
        <SegmentedControlItem value="grid">Grid</SegmentedControlItem>
        <SegmentedControlItem value="board">Board</SegmentedControlItem>
      </SegmentedControl>
    </Field>
  )
}

export { Example }
```

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

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

## 组合
用下面的组合构建一个 `SegmentedControl`：

```text
SegmentedControl
├── SegmentedControlIndicator
├── SegmentedControlItem
└── SegmentedControlItem
```

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

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

```tsx
import {
  SegmentedControl,
  SegmentedControlIndicator,
  SegmentedControlItem,
} from "@ui-sdk/react/segmented-control"

function Example() {
  return (
    <SegmentedControl aria-label="View" defaultValue="list">
      <SegmentedControlIndicator />
      <SegmentedControlItem value="list">List</SegmentedControlItem>
      <SegmentedControlItem value="grid">Grid</SegmentedControlItem>
    </SegmentedControl>
  )
}

export { Example }
```

用 `aria-label` 给控件命名，或把它放进 [Field](/docs/react/components/field) 里，让它的标签为控件提供名称。没有 `defaultValue` 时，初始没有任何项被选中，Tab 会进入第一个启用的项。

## 指示器
`SegmentedControlIndicator` 测量选中的项。把它放在控件内部，用它自己的 [CSS 变量](https://ui-sdk.cn/docs/react/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`。

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

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

```tsx title="vertical.tsx"
"use client"

import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
  SegmentedControl,
  SegmentedControlIndicator,
  SegmentedControlItem,
} from "@ui-sdk/react/segmented-control"

function Example() {
  return (
    <Field>
      <FieldLabel>Vertical alignment</FieldLabel>
      <SegmentedControl orientation="vertical" defaultValue="middle">
        <SegmentedControlIndicator />
        <SegmentedControlItem value="top">Top</SegmentedControlItem>
        <SegmentedControlItem value="middle">Middle</SegmentedControlItem>
        <SegmentedControlItem value="bottom">Bottom</SegmentedControlItem>
      </SegmentedControl>
    </Field>
  )
}

export { Example }
```

选择 Bottom，然后按上方向键。指示器沿着这一列向下跟随。

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

```tsx title="disabled.tsx"
"use client"

import {
  SegmentedControl,
  SegmentedControlIndicator,
  SegmentedControlItem,
} from "@ui-sdk/react/segmented-control"

function Example() {
  return (
    <div data-slot="stack">
      <SegmentedControl aria-label="Theme" defaultValue="system" disabled>
        <SegmentedControlIndicator />
        <SegmentedControlItem value="light">Light</SegmentedControlItem>
        <SegmentedControlItem value="dark">Dark</SegmentedControlItem>
        <SegmentedControlItem value="system">System</SegmentedControlItem>
      </SegmentedControl>
      <SegmentedControl aria-label="Billing period" defaultValue="monthly">
        <SegmentedControlIndicator />
        <SegmentedControlItem value="monthly">Monthly</SegmentedControlItem>
        <SegmentedControlItem value="yearly">Yearly</SegmentedControlItem>
        <SegmentedControlItem value="lifetime" disabled>
          Lifetime
        </SegmentedControlItem>
      </SegmentedControl>
    </div>
  )
}

export { Example }
```

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

## 受控
传入 `value`，并在 `onValueChange` 里更新它。在回调里调用 `details.cancel()` 可以保持当前值。`createSegmentedControlController()` 创建的[控制器](https://ui-sdk.cn/docs/react/components/segmented-control#controller)可以从任何地方选中一个项，比如下面的 Show Month 按钮。每个挂载的控件各建一个控制器。

```tsx title="controlled.tsx"
"use client"

import {
  createSegmentedControlController,
  SegmentedControl,
  SegmentedControlIndicator,
  SegmentedControlItem,
} from "@ui-sdk/react/segmented-control"
import * as React from "react"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [range] = React.useState(() => createSegmentedControlController())
  const [value, setValue] = React.useState<string | null>("week")

  return (
    <div>
      <div data-slot="controls">
        <button type="button" onClick={() => range.setValue("month")}>
          Show Month
        </button>
      </div>
      <SegmentedControl
        aria-label="Range"
        value={value}
        onValueChange={(next, details) => {
          setValue(next)
          log(`value: ${next} (${details.reason})`)
        }}
        controller={range}
      >
        <SegmentedControlIndicator />
        <SegmentedControlItem value="day">Day</SegmentedControlItem>
        <SegmentedControlItem value="week">Week</SegmentedControlItem>
        <SegmentedControlItem value="month">Month</SegmentedControlItem>
      </SegmentedControl>
    </div>
  )
}

export { Example }
```

选择 Day，然后按 Show Month。控制台会记录每次变更及其原因。

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

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

```tsx title="form.tsx"
"use client"

import { Field, FieldDescription, FieldLabel } from "@ui-sdk/react/field"
import {
  SegmentedControl,
  SegmentedControlIndicator,
  SegmentedControlItem,
} from "@ui-sdk/react/segmented-control"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <form
      data-slot="stack"
      onSubmit={(event) => {
        event.preventDefault()
        const data = new FormData(event.currentTarget)
        log(`Saved theme=${data.get("theme")}, density=${data.get("density")}`)
      }}
    >
      <Field>
        <FieldLabel>Theme</FieldLabel>
        <SegmentedControl name="theme" required defaultValue="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" defaultValue="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>
  )
}

export { Example }
```

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

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

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

```tsx
<SegmentedControl aria-label="View" defaultValue="list" loop={false}>
  ...
</SegmentedControl>
```

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

每个部件都有一个 `data-slot`，比如 `segmented-control-item`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/react/components/segmented-control#data-attributes)下。

### SegmentedControlIndicator
- `--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.

## 数据属性
### SegmentedControl
`[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>`.

### SegmentedControlItem
`[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>`.

### SegmentedControlIndicator
`[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 参考
属性和回调与下面相同，以 React props 的形式提供。

### 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.
- `onValueChange?` (`((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
- `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.

### SegmentedControlIndicator
- `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.

### 原因
`details.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.

### 控制器
用 `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.

### 事件
回调先收到新值，再收到详情。

| Prop            | 所属部件           | 收到                                               |
| --------------- | ------------------ | -------------------------------------------------- |
| `onValueChange` | `SegmentedControl` | `(value, details)`：选中的值，以及[原因](https://ui-sdk.cn/docs/react/components/segmented-control#reasons) |

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

Runs in React、Vue 和 web components.
