# 选择

选择条目、扩展选择，或框选一片形状或单元格。

`createSelection` 选择条目的键并扩展范围，`createLasso` 用画出的矩形选择条目，`createCellRange` 选择一块网格单元格。

从 `@ui-sdk/core` 导入它们。把它们与 [焦点与按键](/docs/core/behaviors/focus) 搭配使用，在条目之间移动并选择它们。

## 选择条目
### 选择一个
把选中的键保存在 `string[]` 里，即使只能选择一个条目。在 `api` 中，把 `createSelection` 加到已有的游走焦点（roving focus）行为旁边：

```ts
const change = createChange(context)
const selection = createSelection(context, {
  key: "value",
  set: (value, details) => change("value", value, details),
  order: () => roving.items().map((item) => item.key),
})
```

让 `value` 从 `[]` 开始，并从 `api` 返回 `selection`。`set` 回调使用与指南相同的 [变更模式](https://ui-sdk.cn/docs/core/kernel/handle-changes#changes)。

这个行为提供了一些方法，供你从事件处理函数中调用。例如，一次指针按压可以选择一个条目：

```ts
pointerdown: (event, { api, key }) => api.selection.choose(key, { reason: "item-press", event }),
```

`choose` 选中那个条目。`toggle` 还允许用户清除选择。把这一分支加到已有的 Space 按键处理函数里：

```ts
if (event.key === " ") {
  event.preventDefault()
  selection.toggle(key, { reason: "item-press", event })
}
```

这个方案选择器两者都用。`selection.isSelected(key)` 让它的 Enter 处理函数在继续之前检查是否已选中某个方案。

点击一个方案，或用方向键和 Space 选择一个。在已选中的方案上按 Space 会清除选择；按 Enter 带着它继续，控制台会记录每一步。

对于列表框（listbox），给根元素 `role="listbox"`，给每个条目 `role="option"`，并用 `state.value.includes(key)` 设置它的 `aria-selected`。保留 [焦点与按键](https://ui-sdk.cn/docs/core/behaviors/focus#roving-focus) 里的焦点连接。

### 选择多个
把 `multiple` 加到选择选项里：

```ts
multiple: () => true,
```

现在 `toggle` 在保留其他条目的同时添加或移除一个条目。指针按压和 Space 都用它，就像这个配料选择器。允许多选的列表框还需要在根元素上设置 `aria-multiselectable="true"`。

点击配料来添加或移除。使用键盘时，用 Left 和 Right，然后按 Space。

### 范围与全选
`extend` 从锚点选择到另一个条目。锚点是在不按 Shift 的情况下最近选择或切换的条目。下面三次调用给文件列表提供它惯常的指针交互：

```ts
press(event: PointerEvent, key: string) {
  const details = { reason: "item-press" as const, event }
  if (event.shiftKey) {
    selection.extend(key, { ...details, from: context.store.get().focused })
  } else if (event.metaKey || event.ctrlKey) {
    selection.toggle(key, details)
  } else {
    selection.choose(key, details)
  }
},
```

对于配合方向键的 Shift，使用已有焦点处理函数的返回值：

```ts
const moved = roving.keydown(event, el)
if (moved?.shift) {
  selection.extend(moved.key, {
    from: moved.from,
    reason: "list-navigation",
    event,
  })
}
```

还没有锚点时，`from` 提供起点。`selection.anchor()` 返回当前锚点的键。

当方向键只移动焦点而不选择时，比如在带复选框列的表格里，让锚点跟着焦点移动，这样下一次 Shift 范围就从那里开始。`setAnchor` 保持选择不变，`null` 清除锚点：

```ts
const moved = roving.keydown(event, el)
if (moved && !moved.shift) {
  selection.setAnchor(moved.key)
}
```

范围会保留设置锚点时已选中的内容，然后加入锚点与目标之间的条目。传入 `additive: false` 可以只选择该范围。从外部提供一个不同的选择会让下一次范围从头开始。

点击一个文件，然后按住 Shift 点击另一个来选择一个范围。按住 Control 或 Command 点击可以切换一个文件。勾选 Ranges replace the selection 进行比较。

在多选模式下，`toggleAll` 选择 `order` 里所有可用的键，如果它们已经全部选中则清除。在阻止浏览器默认动作之后，从你的 Control 或 Command+A 处理函数中调用它：

```ts
selection.toggleAll({ reason: "list-navigation", event })
```

`order` 决定范围和全选能到达哪些条目。对于虚拟化列表，传入完整的键列表，包括尚未渲染的条目。

### 无法选择的条目
用 `selectable` 跳过那些不应被选择、切换或加入范围的键：

```ts
selectable: (key) => !context.options().owners.includes(key),
```

在这个成员列表里，所有者一开始就是选中的。演示使用 `toggle` 和 `toggleAll`，它们不会动这些所有者。

聚焦一个成员，按两次 Control 或 Command+A。Hollis Grant 保持选中，而其他成员先被选中，然后被清除。

这并不会把条目固定在选择里：`choose` 和带 `additive: false` 的范围可以替换整个值。如果某些键必须始终保持选中，请在你的 `set` 回调里强制这一点。

## 矩形选择
### 画一个矩形
`createLasso` 选择被矩形触碰到的条目。在状态里先放 `selected: string[]` 和 `lasso: LassoDraft | null`，把 `lasso` 设为 `null`。把 `lasso` 加到原语的 `live` 字段里，[实时状态](https://ui-sdk.cn/docs/core/kernel/handle-changes#live-state) 有相关说明。

在 `api` 里创建这个行为，并把它作为 `lasso` 返回：

```ts
const lasso = createLasso(context, {
  slot: "shape",
  draft: "lasso",
  selected: () => context.store.get().selected,
  set: (keys, details) => change("selected", keys, details),
})
```

给绘制表面设置 `position: relative`、`touch-action: none` 和 `user-select: none`，这样绘制时不会滚动页面或选中文本。在指针落到它的空白处时开始：

```ts
pointerdown: (event, { el, api }) => {
  if (el && event.target === el) {
    api.lasso.pointerdown(event, el)
  }
},
```

让矩形部件保持渲染。没有拖动时，它的 `style` 会把它隐藏：

```ts
lasso: slot({
  attrs: () => ({ "aria-hidden": "true" }),
  live: live((state, { api }) => ({ style: api.lasso.style(state) })),
}),
```

从空白处拖动来选择形状；控制台会记录选择。按住 Shift 可以加入选择；在释放之前按 Escape 会取消矩形。

`lasso.touches(state, key)` 告诉你哪些条目属于预览选择。按住 Shift 时，这包括拖动之前已经选中的条目。用它来提供 `data-lassoed` 高亮。

选择只改变一次，在指针释放时，原因为 `"lasso"`。Escape 取消拖动并保留之前的选择。

### 它跳过的条目
加上 `selectable`，把某些条目排除在矩形的命中范围之外；再加上 `message`，自定义屏幕阅读器的播报：

```ts
selectable: (key) => !context.options().locked.includes(key),
message: (count) => `${count} ${count === 1 ? "photo" : "photos"} selected`,
```

播报在选择请求被接受之后运行。

从空白处拖过照片。City 和 Lake 保持未选中；释放时屏幕阅读器会播报选中的数量。

## 单元格范围
### 选择一块
[焦点与按键](https://ui-sdk.cn/docs/core/behaviors/focus#grids) 展示了如何导航网格。当你还需要在单元格之间拖动、选择整行或整列，或复制一块内容时，加上 `createCellRange`。

在状态里保留 `range: CellRange | null` 字段，初始值为 `null`。传入已有的网格行为及其行数和列数：

```ts
const range = createCellRange(context, {
  key: "range",
  grid,
  rows: () => 4,
  cols: () => 5,
})
```

从 `api` 返回 `range`，然后更新已有的单元格槽位：

```ts
selects: selects({ active: byCell, range: byCellRange }),
attrs: (state, { props, api }) => ({
  role: "gridcell",
  tabindex: api.grid.tabIndex(state, props),
  ...api.range.cellAttrs(state, props),
}),
on: {
  keydown: (event, { api }) => api.range.keydown(event),
  pointerdown: (event, { api, props }) => api.range.pointerdown(event, props),
},
bind: (el, { api, props }) => api.range.bind(el, props),
```

`range.bind` 还会绑定网格焦点，`range.keydown` 把普通的导航转发给网格。同一个事件不需要同时调用两个行为。`byCellRange` 让范围变更只到达加入或离开范围的单元格，以及沿移动边界的单元格。

在单元格之间拖动，或点击一个单元格并按住 Shift 配合方向键。总计会跟随选中的范围。

范围扩大时，焦点停留在活动单元格上。不带 Shift 的移动会清除范围。这个行为还处理这些快捷键：

| 按键          | 动作               |
| ------------- | ------------------ |
| Shift+Space   | 选择范围所在的行。 |
| Control+Space | 选择范围所在的列。 |
| Control+A     | 选择每个单元格。   |
| Escape        | 清除范围。         |

`cellAttrs` 用 `aria-selected`、`data-selected` 和 `data-range-edge` 标记显式范围。最后一项列出单元格位于范围的哪些边上，比如 `"top left"`，所以你可以用 `[data-range-edge~="top"]` 画出轮廓。

### 从代码中选择
同一个范围可以从按钮或其他控件改变。行和列的索引从零开始：

```ts
range.selectColumns(1)
range.selectRows(0, 1)
range.select({ anchor: { row: 1, col: 1 }, end: { row: 2, col: 2 } })
range.selectAll()
range.select(null)
```

这些调用改变范围而不移动焦点。`select(null)` 清除范围。

用按钮选择一列、几行、一块或整个网格。摘要会说明范围并统计大于 10 的值。

`range.bounds(state)` 给出包含端点的 `top`、`left`、`bottom` 和 `right` 索引。没有显式范围时，它回退到活动单元格；如果没有活动单元格，则返回 `null`。当你需要汇总或统计单元格时，`range.contains(state, cell)` 使用同样的规则。

默认情况下，范围变更直接写入状态。要通过 `createChange` 上报它们，加上 `set`。你还可以自定义键盘选择之后屏幕阅读器听到的内容：

```ts
set: (value, details) => change("range", value, details),
message: ({ top, left, bottom, right }) =>
  `Rows ${top + 1} to ${bottom + 1}, columns ${left + 1} to ${right + 1} selected`,
```

对于尚未渲染的行，`reveal` 的作用和在 [网格焦点](https://ui-sdk.cn/docs/core/behaviors/focus#rows-that-arent-rendered) 里一样。

### 复制与粘贴
`range.text(state, read)` 把选中的单元格读成以制表符分隔的文本。从网格的 `copy` 处理函数中调用它：

```ts
copy(event: ClipboardEvent) {
  const state = context.store.get()
  const text = range.text(state, ({ row, col }) => state.cells[row][col])
  event.preventDefault()
  event.clipboardData?.setData("text/plain", text)
},
```

在 `paste` 处理函数里，`textToCells` 把剪贴板文本转换成行：

```ts
const rows = textToCells(event.clipboardData?.getData("text/plain") ?? "")
```

你的处理函数阻止默认粘贴，并从选择范围的左上角单元格开始，把这些值写进状态。到网格边缘就停止。演示的 Code 标签页显示了完整的处理函数。

选择单元格，用 Control 或 Command+C 复制。点击目标单元格，用 Control 或 Command+V 粘贴。

`cellsToText(rows)` 反方向工作。用它复制整张表，即使只选中了其中一部分。

## API 参考
### 条目选择选项
- `key` (`Key`): The state key that holds the selected keys, a `string[]`. Example: [Choose One](https://ui-sdk.cn/docs/core/behaviors/selection#choose-one).
- `set` (`(value: string[], details: Why<Reason>) => boolean`): Asks for a new selection and returns whether it went through. Pass the primitive's change, so `on<Key>Change`, `cancel()` and controlled values work: `set: (value, details) => change("value", value, details)`. Example: [Choose One](https://ui-sdk.cn/docs/core/behaviors/selection#choose-one).
- `order` (`() => readonly string[]`): Every key in list order, for ranges and select all, like the visible items' keys. Example: [Choose One](https://ui-sdk.cn/docs/core/behaviors/selection#choose-one).
- `multiple?` (`(() => boolean)`): Whether more than one item can be selected. Defaults to `false`. Example: [Choose Many](https://ui-sdk.cn/docs/core/behaviors/selection#choose-many).
- `selectable?` (`((key: string) => boolean)`): Whether a key can be chosen, toggled, or added to a range. Replacing the selection can still remove it. Defaults to every item. Example: [Items That Can't Be Selected](https://ui-sdk.cn/docs/core/behaviors/selection#items-that-cant-be-selected).

### 矩形选择选项
- `slot` (`string`): The slot whose parts the rectangle selects. Example: [Draw a Rectangle](https://ui-sdk.cn/docs/core/behaviors/selection#draw-a-rectangle).
- `draft` (`keyof State & string`): The state key that holds the `LassoDraft` while one is drawn. Start it at `null`, and list it in `live`. Example: [Draw a Rectangle](https://ui-sdk.cn/docs/core/behaviors/selection#draw-a-rectangle).
- `selected` (`() => string[]`): The selection now, which Shift adds to. Example: [Draw a Rectangle](https://ui-sdk.cn/docs/core/behaviors/selection#draw-a-rectangle).
- `set` (`(keys: string[], details: { reason: "lasso"; event?: Event; }) => boolean`): Asks for a new selection. Pass the primitive's change. Example: [Draw a Rectangle](https://ui-sdk.cn/docs/core/behaviors/selection#draw-a-rectangle).
- `selectable?` (`((key: string) => boolean)`): Whether an item can be selected. Defaults to every item. Example: [Items It Skips](https://ui-sdk.cn/docs/core/behaviors/selection#items-it-skips).
- `message?` (`((count: number) => string)`): What screen readers hear when the rectangle lifts. Defaults to English. Example: [Items It Skips](https://ui-sdk.cn/docs/core/behaviors/selection#items-it-skips).

### 单元格范围选项
- `key` (`keyof State & string`): The state key that holds the `CellRange`, or `null` when only the active cell is selected. Example: [Select a Block](https://ui-sdk.cn/docs/core/behaviors/selection#select-a-block).
- `grid` (`object`): The grid's focus, which keeps the active cell. Example: [Select a Block](https://ui-sdk.cn/docs/core/behaviors/selection#select-a-block).
- `rows` (`() => number`): How many rows the range can reach. Example: [Select a Block](https://ui-sdk.cn/docs/core/behaviors/selection#select-a-block).
- `cols` (`() => number`): How many columns. Example: [Select a Block](https://ui-sdk.cn/docs/core/behaviors/selection#select-a-block).
- `reveal?` (`((cell: GridCell) => void)`): Shows a cell the range grows to that may not be rendered, like `createGridFocus`'s `reveal`. Example: [Rows That Aren't Rendered](https://ui-sdk.cn/docs/core/behaviors/focus#rows-that-arent-rendered).
- `set?` (`((range: CellRange | null, details: { reason: CellRangeReason; event?: Event; }) => boolean)`): Asks for a new range and returns whether it went through. Defaults to writing the state; pass the primitive's change to report it. Example: [Selecting from Code](https://ui-sdk.cn/docs/core/behaviors/selection#selecting-from-code).
- `message?` (`((bounds: CellBounds) => string)`): What screen readers hear after the range changes from the keyboard. Defaults to English. Example: [Selecting from Code](https://ui-sdk.cn/docs/core/behaviors/selection#selecting-from-code).
