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

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

从 @ui-sdk/core 导入它们。把它们与 焦点与按键 搭配使用,在条目之间移动并选择它们。

选择条目

选择一个

把选中的键保存在 string[] 里,即使只能选择一个条目。在 api 中,把 createSelection 加到已有的游走焦点(roving focus)行为旁边:

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 回调使用与指南相同的 变更模式。

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

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

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

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

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

控制台
import * as React from "react"
import {
  createChange,
  createRovingFocus,
  createSelection,
  definePrimitive,
  selects,
  type ChangeDetails,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type PlansState = { value: string[]; focused: string | null }

type PlansOptions = {
  onValueChange?: (
    value: string[],
    details: ChangeDetails<"item-press">
  ) => void
  onContinue?: (plan: string) => void
}

const plans = definePrimitive({
  name: "plans",
  options: { onValueChange: "callback", onContinue: "callback" },
  state: (_options: PlansOptions): PlansState => ({ value: [], focused: null }),
  api: (context) => {
    const change = createChange(context)
    const roving = createRovingFocus<PlansState, { value: string }>(context, {
      slot: "plan",
      key: "focused",
      orientation: () => "vertical",
    })
    const selection = createSelection(context, {
      key: "value",
      set: (value, details) => change("value", value, details),
      order: () => roving.items().map((item) => item.key),
    })
    return {
      roving,
      selection,
      keydown(event: KeyboardEvent, el: HTMLElement, key: string) {
        if (event.key === " ") {
          event.preventDefault()
          selection.toggle(key, { reason: "item-press", event })
        } else if (event.key === "Enter" && selection.isSelected(key)) {
          context.options().onContinue?.(key)
        } else {
          roving.keydown(event, el)
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "listbox" }) }),
    plan: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        role: "option",
        "aria-selected": String(state.value.includes(part.key)),
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      on: {
        keydown: (event, { el, api, key }) => api.keydown(event, el!, key),
        pointerdown: (event, { api, key }) =>
          api.selection.choose(key, { reason: "item-press", event }),
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(plans, { root: "div", plan: "div" })

const Plans = parts.Root

const PlansPlan = parts.Plan

const options = [
  { name: "Free", price: "$0" },
  { name: "Pro", price: "$12 / month" },
  { name: "Team", price: "$30 / month" },
]

function Example() {
  const log = useLog()
  return (
    <Plans
      aria-label="Plan"
      onValueChange={(value: string[]) =>
        log(value.length ? `Chose ${value[0]}` : "Cleared the plan")
      }
      onContinue={(plan: string) => log(`Continuing with ${plan}`)}
    >
      {options.map(({ name, price }) => (
        <PlansPlan key={name} value={name}>
          {name}
          <span data-slot="hint">{price}</span>
        </PlansPlan>
      ))}
    </Plans>
  )
}

export { Example, plans, Plans, PlansPlan, type PlansOptions, type PlansState }
点击一个方案,或用方向键和 Space 选择一个。在已选中的方案上按 Space 会清除选择;按 Enter 带着它继续,控制台会记录每一步。

对于列表框(listbox),给根元素 role="listbox",给每个条目 role="option",并用 state.value.includes(key) 设置它的 aria-selected。保留 焦点与按键 里的焦点连接。

选择多个

把 multiple 加到选择选项里:

multiple: () => true,

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

import * as React from "react"
import {
  createChange,
  createRovingFocus,
  createSelection,
  definePrimitive,
  selects,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type ToppingsState = { value: string[]; focused: string | null }

const toppings = definePrimitive({
  name: "toppings",
  state: (): ToppingsState => ({ value: ["Cheese"], focused: null }),
  api: (context) => {
    const change = createChange(context)
    const roving = createRovingFocus<ToppingsState, { value: string }>(
      context,
      {
        slot: "topping",
        key: "focused",
        orientation: () => "horizontal",
      }
    )
    const selection = createSelection(context, {
      key: "value",
      set: (value, details) => change("value", value, details),
      order: () => roving.items().map((item) => item.key),
      multiple: () => true,
    })
    return {
      roving,
      selection,
      keydown(event: KeyboardEvent, el: HTMLElement, key: string) {
        if (event.key !== " ") {
          return roving.keydown(event, el)
        }
        event.preventDefault()
        selection.toggle(key, { reason: "item-press", event })
      },
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "listbox", "aria-multiselectable": "true" }),
    }),
    topping: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        role: "option",
        "aria-selected": String(state.value.includes(part.key)),
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      on: {
        keydown: (event, { el, api, key }) => api.keydown(event, el!, key),
        pointerdown: (event, { api, key }) =>
          api.selection.toggle(key, { reason: "item-press", event }),
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(toppings, { root: "div", topping: "div" })

const Toppings = parts.Root

const ToppingsTopping = parts.Topping

const names = ["Cheese", "Basil", "Olives", "Mushrooms", "Peppers"]

function Example() {
  return (
    <Toppings aria-label="Toppings">
      {names.map((name) => (
        <ToppingsTopping key={name} value={name}>
          {name}
        </ToppingsTopping>
      ))}
    </Toppings>
  )
}

export { Example, toppings, Toppings, ToppingsTopping, type ToppingsState }
点击配料来添加或移除。使用键盘时,用 Left 和 Right,然后按 Space。

范围与全选

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

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,使用已有焦点处理函数的返回值:

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 清除锚点:

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

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

控制台
import * as React from "react"
import {
  createChange,
  createRovingFocus,
  createSelection,
  definePrimitive,
  selects,
  type ChangeDetails,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type FilesState = { value: string[]; focused: string | null }

type FilesOptions = {
  replaceRanges?: boolean
  onValueChange?: (
    value: string[],
    details: ChangeDetails<"item-press" | "list-navigation">
  ) => void
}

const files = definePrimitive({
  name: "files",
  options: { replaceRanges: "boolean", onValueChange: "callback" },
  state: (_options: FilesOptions): FilesState => ({ value: [], focused: null }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const additive = () => !context.options().replaceRanges
    const roving = createRovingFocus<FilesState, { value: string }>(context, {
      slot: "file",
      key: "focused",
    })
    const selection = createSelection(context, {
      key: "value",
      set: (value, details) => change("value", value, details),
      order: () => roving.items().map((item) => item.key),
      multiple: () => true,
    })
    return {
      roving,
      keydown(event: KeyboardEvent, el: HTMLElement, key: string) {
        if ((event.metaKey || event.ctrlKey) && event.key === "a") {
          event.preventDefault()
          selection.toggleAll({ reason: "list-navigation", event })
        } else if (event.key === " ") {
          event.preventDefault()
          selection.toggle(key, { reason: "item-press", event })
        } else {
          const moved = roving.keydown(event, el)
          if (moved?.shift) {
            selection.extend(moved.key, {
              from: moved.from,
              additive: additive(),
              reason: "list-navigation",
              event,
            })
          }
        }
      },
      press(event: PointerEvent, key: string) {
        const why = { reason: "item-press" as const, event }
        if (event.shiftKey) {
          selection.extend(key, {
            ...why,
            from: store.get().focused,
            additive: additive(),
          })
        } else if (event.metaKey || event.ctrlKey) {
          selection.toggle(key, why)
        } else {
          selection.choose(key, why)
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "listbox", "aria-multiselectable": "true" }),
    }),
    file: slot<{ value: string }, { selected: boolean }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      state: (state, { key }) => ({ selected: state.value.includes(key) }),
      attrs: (state, part) => ({
        role: "option",
        "aria-selected": String(state.value.includes(part.key)),
        tabindex: part.api.roving.tabIndex(state, part),
        "data-selected": state.value.includes(part.key) ? "" : undefined,
      }),
      on: {
        keydown: (event, { el, api, key }) => api.keydown(event, el!, key),
        pointerdown: (event, { api, key }) => api.press(event, key),
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(files, { root: "div", file: "div" })

const Files = parts.Root

const FilesItem = parts.File

const names = [
  "notes.md",
  "budget.xlsx",
  "photo.jpg",
  "slides.key",
  "draft.docx",
  "logo.svg",
]

function Example() {
  const log = useLog()
  const [replace, setReplace] = React.useState(false)
  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <label data-slot="label">
          <input
            type="checkbox"
            checked={replace}
            onChange={(event) => setReplace(event.target.checked)}
          />
          Ranges replace the selection
        </label>
      </div>
      <Files
        aria-label="Files"
        replaceRanges={replace}
        onValueChange={(value: string[]) =>
          log(`${value.length} selected: ${value.join(", ") || "none"}`)
        }
      >
        {names.map((name) => (
          <FilesItem key={name} value={name}>
            {name}
          </FilesItem>
        ))}
      </Files>
    </div>
  )
}

export { Example, files, Files, FilesItem, type FilesOptions, type FilesState }
点击一个文件,然后按住 Shift 点击另一个来选择一个范围。按住 Control 或 Command 点击可以切换一个文件。勾选 Ranges replace the selection 进行比较。

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

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

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

无法选择的条目

用 selectable 跳过那些不应被选择、切换或加入范围的键:

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

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

import * as React from "react"
import {
  createChange,
  createRovingFocus,
  createSelection,
  definePrimitive,
  selects,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type MembersState = { value: string[]; focused: string | null }

type MembersOptions = {
  owners: string[]
}

const members = definePrimitive({
  name: "members",
  options: { owners: "list" },
  state: (options: MembersOptions): MembersState => ({
    value: [...options.owners],
    focused: null,
  }),
  api: (context) => {
    const change = createChange(context)
    const roving = createRovingFocus<MembersState, { value: string }>(context, {
      slot: "member",
      key: "focused",
    })
    const selection = createSelection(context, {
      key: "value",
      set: (value, details) => change("value", value, details),
      order: () => roving.items().map((item) => item.key),
      multiple: () => true,
      selectable: (key) => !context.options().owners.includes(key),
    })
    return {
      roving,
      selection,
      keydown(event: KeyboardEvent, el: HTMLElement, key: string) {
        if ((event.metaKey || event.ctrlKey) && event.key === "a") {
          event.preventDefault()
          selection.toggleAll({ reason: "list-navigation", event })
        } else if (event.key === " ") {
          event.preventDefault()
          selection.toggle(key, { reason: "item-press", event })
        } else {
          roving.keydown(event, el)
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "listbox", "aria-multiselectable": "true" }),
    }),
    member: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        role: "option",
        "aria-selected": String(state.value.includes(part.key)),
        tabindex: part.api.roving.tabIndex(state, part),
      }),
      on: {
        keydown: (event, { el, api, key }) => api.keydown(event, el!, key),
        pointerdown: (event, { api, key }) =>
          api.selection.toggle(key, { reason: "item-press", event }),
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(members, { root: "div", member: "div" })

const Members = parts.Root

const MembersMember = parts.Member

const names = [
  "Hollis Grant",
  "Inès Moreau",
  "Kofi Mensah",
  "Wren Takahashi",
  "Tomasz Wójcik",
]
const owners = ["Hollis Grant"]

function Example() {
  return (
    <Members owners={owners} aria-label="Members">
      {names.map((name) => (
        <MembersMember
          key={name}
          value={name}
          aria-disabled={owners.includes(name) || undefined}
        >
          {name}
          {owners.includes(name) && <span data-slot="hint">Owner</span>}
        </MembersMember>
      ))}
    </Members>
  )
}

export {
  Example,
  members,
  Members,
  MembersMember,
  type MembersOptions,
  type MembersState,
}
聚焦一个成员,按两次 Control 或 Command+A。Hollis Grant 保持选中,而其他成员先被选中,然后被清除。

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

矩形选择

画一个矩形

createLasso 选择被矩形触碰到的条目。在状态里先放 selected: string[] 和 lasso: LassoDraft | null,把 lasso 设为 null。把 lasso 加到原语的 live 字段里,实时状态 有相关说明。

在 api 里创建这个行为,并把它作为 lasso 返回:

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,这样绘制时不会滚动页面或选中文本。在指针落到它的空白处时开始:

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

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

lasso: slot({
  attrs: () => ({ "aria-hidden": "true" }),
  live: live((state, { api }) => ({ style: api.lasso.style(state) })),
}),
控制台
import * as React from "react"
import {
  createChange,
  createLasso,
  definePrimitive,
  live,
  type ChangeDetails,
  type LassoDraft,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type ShapesState = { selected: string[]; lasso: LassoDraft | null }

type ShapesOptions = {
  onSelectedChange?: (
    selected: string[],
    details: ChangeDetails<"lasso">
  ) => void
}

const shapes = definePrimitive({
  name: "shapes",
  options: { onSelectedChange: "callback" },
  state: (_options: ShapesOptions): ShapesState => ({
    selected: [],
    lasso: null,
  }),
  live: ["lasso"],
  api: (context) => {
    const change = createChange(context)
    return {
      lasso: createLasso<ShapesState>(context, {
        slot: "shape",
        draft: "lasso",
        selected: () => context.store.get().selected,
        set: (keys, details) => change("selected", keys, details),
      }),
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({
        style: "position:relative;touch-action:none;user-select:none",
      }),
      on: {
        pointerdown: (event, { el, api }) =>
          event.target === el && api.lasso.pointerdown(event, el!),
      },
    }),
    shape: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { key }) => ({
        "data-selected": state.selected.includes(key) ? "" : undefined,
      }),
      live: live<ShapesState, any, { value: string }>(
        (state, { key, api }) => ({
          "data-lassoed": api.lasso.touches(state, key) ? "" : undefined,
        })
      ),
    }),
    lasso: slot({
      attrs: () => ({ "aria-hidden": "true" }),
      live: live<ShapesState, any, {}>((state, { api }) => ({
        style: api.lasso.style(state),
      })),
    }),
  }),
})

const parts = createParts(shapes, { root: "div", shape: "div", lasso: "div" })

const Shapes = parts.Root

const ShapesItem = parts.Shape

const ShapesLasso = parts.Lasso

const items = [
  { key: "Circle", x: 24, y: 24, round: true },
  { key: "Square", x: 134, y: 36, round: false },
  { key: "Dot", x: 70, y: 130, round: true },
  { key: "Tile", x: 206, y: 116, round: false },
]

function Example() {
  const log = useLog()
  return (
    <Shapes
      aria-label="Shapes"
      onSelectedChange={(selected: string[]) =>
        log(`Selected: ${selected.join(", ") || "none"}`)
      }
    >
      {items.map((item) => (
        <ShapesItem
          key={item.key}
          value={item.key}
          data-shape={item.round ? "round" : undefined}
          style={{ left: item.x, top: item.y }}
        />
      ))}
      <ShapesLasso />
    </Shapes>
  )
}

export {
  Example,
  shapes,
  Shapes,
  ShapesItem,
  ShapesLasso,
  type ShapesOptions,
  type ShapesState,
}
从空白处拖动来选择形状;控制台会记录选择。按住 Shift 可以加入选择;在释放之前按 Escape 会取消矩形。

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

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

它跳过的条目

加上 selectable,把某些条目排除在矩形的命中范围之外;再加上 message,自定义屏幕阅读器的播报:

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

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

import * as React from "react"
import {
  createChange,
  createLasso,
  definePrimitive,
  live,
  type LassoDraft,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type PhotosState = { selected: string[]; lasso: LassoDraft | null }

type PhotosOptions = {
  locked: string[]
}

const photos = definePrimitive({
  name: "photos",
  options: { locked: "list" },
  state: (_options: PhotosOptions): PhotosState => ({
    selected: [],
    lasso: null,
  }),
  live: ["lasso"],
  api: (context) => {
    const change = createChange(context)
    return {
      lasso: createLasso<PhotosState>(context, {
        slot: "photo",
        draft: "lasso",
        selected: () => context.store.get().selected,
        set: (keys, details) => change("selected", keys, details),
        selectable: (key) => !context.options().locked.includes(key),
        message: (count) =>
          `${count} ${count === 1 ? "photo" : "photos"} selected`,
      }),
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({
        style: "position:relative;touch-action:none;user-select:none",
      }),
      on: {
        pointerdown: (event, { el, api }) =>
          event.target === el && api.lasso.pointerdown(event, el!),
      },
    }),
    photo: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { key }) => ({
        "data-selected": state.selected.includes(key) ? "" : undefined,
      }),
      live: live<PhotosState, any, { value: string }>(
        (state, { key, api }) => ({
          "data-lassoed": api.lasso.touches(state, key) ? "" : undefined,
        })
      ),
    }),
    lasso: slot({
      attrs: () => ({ "aria-hidden": "true" }),
      live: live<PhotosState, any, {}>((state, { api }) => ({
        style: api.lasso.style(state),
      })),
    }),
  }),
})

const parts = createParts(photos, { root: "div", photo: "div", lasso: "div" })

const Photos = parts.Root

const PhotosPhoto = parts.Photo

const PhotosLasso = parts.Lasso

const names = ["Beach", "Forest", "City", "Desert", "Lake", "Snow"]
const locked = ["City", "Lake"]

function Example() {
  return (
    <Photos locked={locked} aria-label="Photos">
      {names.map((name) => (
        <PhotosPhoto key={name} value={name}>
          {name}
          {locked.includes(name) && <span data-slot="badge">Locked</span>}
        </PhotosPhoto>
      ))}
      <PhotosLasso />
    </Photos>
  )
}

export {
  Example,
  photos,
  Photos,
  PhotosLasso,
  PhotosPhoto,
  type PhotosOptions,
  type PhotosState,
}
从空白处拖过照片。City 和 Lake 保持未选中;释放时屏幕阅读器会播报选中的数量。

单元格范围

选择一块

焦点与按键 展示了如何导航网格。当你还需要在单元格之间拖动、选择整行或整列,或复制一块内容时,加上 createCellRange。

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

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

从 api 返回 range,然后更新已有的单元格槽位:

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 让范围变更只到达加入或离开范围的单元格,以及沿移动边界的单元格。

import * as React from "react"
import {
  byCell,
  byCellRange,
  createCellRange,
  createGridFocus,
  definePrimitive,
  selects,
  type CellRange,
  type GridCell,
} from "@ui-sdk/core"
import { createParts, usePart, type PartProps } from "@ui-sdk/react/primitive"

type SheetState = { active: GridCell | null; range: CellRange | null }

type SheetOptions = { rows: number; cols: number }

type SheetSummaryState = {
  top: number
  left: number
  bottom: number
  right: number
}

const sheet = definePrimitive({
  name: "sheet",
  options: { rows: "number", cols: "number" },
  state: (_options: SheetOptions): SheetState => ({
    active: null,
    range: null,
  }),
  api: (context) => {
    const rows = () => context.options().rows
    const cols = () => context.options().cols
    const grid = createGridFocus<SheetState>(context, {
      key: "active",
      rows,
      cols,
    })
    return {
      grid,
      range: createCellRange<SheetState>(context, {
        key: "range",
        grid,
        rows,
        cols,
      }),
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({
        role: "grid",
        style: "user-select:none;touch-action:none",
      }),
    }),
    row: slot<{ id: string }>({
      props: { id: "string" },
      attrs: () => ({ role: "row" }),
    }),
    summary: slot<{}, SheetSummaryState>({
      state: (state, { api }) => {
        const bounds = state.active && api.range.bounds(state)
        return bounds ?? { top: -1, left: -1, bottom: -1, right: -1 }
      },
      attrs: () => ({ "aria-live": "polite" }),
    }),
    cell: slot<{ id: string; row: number; col: number }>({
      props: { row: "number", col: "number" },
      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),
    }),
  }),
})

const parts = createParts(sheet, { root: "div", row: "div", summary: "p" })

const Sheet = parts.Root

const SheetRow = parts.Row

function SheetCell({
  row,
  col,
  ...props
}: { row: number; col: number } & PartProps<"div">) {
  return usePart(sheet, "cell", { id: `${row}:${col}`, row, col }, props, "div")
}

const SheetSummary = parts.Summary

const values = [
  [4, 8, 15, 16],
  [23, 42, 7, 1],
  [9, 3, 12, 5],
]

function Example() {
  return (
    <Sheet rows={3} cols={4} aria-label="Numbers">
      {values.map((row, r) => (
        <SheetRow key={r} id={String(r)}>
          {row.map((value, c) => (
            <SheetCell key={c} row={r} col={c}>
              {value}
            </SheetCell>
          ))}
        </SheetRow>
      ))}
      <SheetSummary>
        {({ top, left, bottom, right }) => {
          let total = 0
          for (let row = Math.max(top, 0); row <= bottom; row++) {
            for (let col = Math.max(left, 0); col <= right; col++) {
              total += values[row][col]
            }
          }
          return `Total: ${total}`
        }}
      </SheetSummary>
    </Sheet>
  )
}

export {
  Example,
  sheet,
  Sheet,
  SheetCell,
  SheetRow,
  SheetSummary,
  type SheetOptions,
  type SheetState,
  type SheetSummaryState,
}
在单元格之间拖动,或点击一个单元格并按住 Shift 配合方向键。总计会跟随选中的范围。

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

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

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

从代码中选择

同一个范围可以从按钮或其他控件改变。行和列的索引从零开始:

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) 清除范围。

import * as React from "react"
import {
  byCell,
  byCellRange,
  createCellRange,
  createChange,
  createGridFocus,
  definePrimitive,
  selects,
  type CellRange,
  type GridCell,
} from "@ui-sdk/core"
import { createParts, usePart, type PartProps } from "@ui-sdk/react/primitive"

type LedgerState = { active: GridCell | null; range: CellRange | null }

const values = [
  [4, 8, 15, 16],
  [23, 42, 7, 1],
  [9, 3, 12, 5],
]
const rows = values.length
const cols = values[0].length
const letters = "ABCD"

const nameOf = (row: number, col: number) => `${letters[col]}${row + 1}`

const shortcuts: Record<string, string> = {
  "column-b": "Column B",
  "rows-1-2": "Rows 1 and 2",
  block: "B2 to C3",
  all: "All",
}

const ledgerGrid = definePrimitive({
  name: "ledger-grid",
  state: (): LedgerState => ({ active: null, range: null }),
  api: (context) => {
    const change = createChange(context)
    const grid = createGridFocus<LedgerState>(context, {
      key: "active",
      rows: () => rows,
      cols: () => cols,
    })
    const range = createCellRange<LedgerState>(context, {
      key: "range",
      grid,
      rows: () => rows,
      cols: () => cols,
      set: (value, details) => change("range", value, details),
      message: ({ top, left, bottom, right }) =>
        `${nameOf(top, left)} to ${nameOf(bottom, right)} selected`,
    })
    return {
      grid,
      range,
      pick(shortcut: string) {
        if (shortcut === "column-b") {
          range.selectColumns(1)
        } else if (shortcut === "rows-1-2") {
          range.selectRows(0, 1)
        } else if (shortcut === "block") {
          range.select({ anchor: { row: 1, col: 1 }, end: { row: 2, col: 2 } })
        } else {
          range.selectAll()
        }
      },
    }
  },
  slots: (slot) => ({
    grid: slot({
      attrs: () => ({
        role: "grid",
        style: "user-select:none;touch-action:none",
      }),
    }),
    row: slot<{ id: string }>({
      props: { id: "string" },
      attrs: () => ({ role: "row" }),
    }),
    cell: slot<{ id: string; row: number; col: number }>({
      props: { row: "number", col: "number" },
      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),
    }),
    shortcut: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
      press: ({ api, key }) => api.pick(key),
    }),
    summary: slot<{}, { text: string }>({
      state: (state, { api }) => {
        const bounds = api.range.bounds(state)
        if (!bounds) {
          return { text: "Nothing selected" }
        }
        let big = 0
        for (let row = 0; row < rows; row++) {
          for (let col = 0; col < cols; col++) {
            if (
              api.range.contains(state, { row, col }) &&
              values[row][col] > 10
            ) {
              big++
            }
          }
        }
        const name = `${nameOf(bounds.top, bounds.left)}:${nameOf(bounds.bottom, bounds.right)}`
        return { text: `${name}, ${big} over 10` }
      },
    }),
  }),
})

const parts = createParts(ledgerGrid, {
  grid: "div",
  row: "div",
  shortcut: "button",
  summary: "p",
})

const LedgerGrid = parts.Root

const LedgerGridGrid = parts.Grid

const LedgerGridRow = parts.Row

function LedgerGridCell({
  row,
  col,
  ...props
}: { row: number; col: number } & PartProps<"div">) {
  return usePart(
    ledgerGrid,
    "cell",
    { id: `${row}:${col}`, row, col },
    props,
    "div"
  )
}

const LedgerGridShortcut = parts.Shortcut

const LedgerGridSummary = parts.Summary

function Example() {
  return (
    <LedgerGrid>
      <div data-slot="stack">
        <div data-slot="controls">
          {Object.entries(shortcuts).map(([value, label]) => (
            <LedgerGridShortcut data-size="sm" key={value} value={value}>
              {label}
            </LedgerGridShortcut>
          ))}
        </div>
        <LedgerGridGrid aria-label="Ledger">
          {values.map((row, r) => (
            <LedgerGridRow key={r} id={String(r)}>
              {row.map((value, c) => (
                <LedgerGridCell key={c} row={r} col={c}>
                  {value}
                </LedgerGridCell>
              ))}
            </LedgerGridRow>
          ))}
        </LedgerGridGrid>
        <LedgerGridSummary data-summary>{({ text }) => text}</LedgerGridSummary>
      </div>
    </LedgerGrid>
  )
}

export {
  Example,
  ledgerGrid,
  LedgerGrid,
  LedgerGridCell,
  LedgerGridGrid,
  LedgerGridRow,
  LedgerGridShortcut,
  LedgerGridSummary,
  type LedgerState,
}
用按钮选择一列、几行、一块或整个网格。摘要会说明范围并统计大于 10 的值。

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

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

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 的作用和在 网格焦点 里一样。

复制与粘贴

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

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 把剪贴板文本转换成行:

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

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

控制台
import * as React from "react"
import {
  byCell,
  byCellRange,
  cellsToText,
  createCellRange,
  createGridFocus,
  definePrimitive,
  selects,
  textToCells,
  type CellRange,
  type GridCell,
} from "@ui-sdk/core"
import { createParts, usePart, type PartProps } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type PricesOptions = { onCopy?: (text: string) => void }

type PricesState = {
  active: GridCell | null
  range: CellRange | null
  cells: string[][]
}

const start = [
  ["Tea", "3", "12"],
  ["Coffee", "4", "9"],
  ["Cake", "5", "4"],
  ["", "", ""],
]
const rows = start.length
const cols = start[0].length

const prices = definePrimitive({
  name: "prices",
  options: { onCopy: "callback" },
  state: (_options: PricesOptions): PricesState => ({
    active: null,
    range: null,
    cells: start,
  }),
  api: (context) => {
    const { store } = context
    const grid = createGridFocus<PricesState>(context, {
      key: "active",
      rows: () => rows,
      cols: () => cols,
    })
    const range = createCellRange<PricesState>(context, {
      key: "range",
      grid,
      rows: () => rows,
      cols: () => cols,
    })
    return {
      grid,
      range,
      copy(event: ClipboardEvent) {
        const state = store.get()
        const text = range.text(state, ({ row, col }) => state.cells[row][col])
        event.preventDefault()
        event.clipboardData?.setData("text/plain", text)
        context.options().onCopy?.(text)
      },
      paste(event: ClipboardEvent) {
        const state = store.get()
        const bounds = range.bounds(state)
        if (!bounds) {
          return
        }
        event.preventDefault()
        const pasted = textToCells(
          event.clipboardData?.getData("text/plain") ?? ""
        )
        const cells = state.cells.map((row) => [...row])
        pasted.forEach((values, r) =>
          values.forEach((value, c) => {
            const row = bounds.top + r
            const col = bounds.left + c
            if (row < rows && col < cols) {
              cells[row][col] = value
            }
          })
        )
        store.set({ cells })
      },
      copyAll() {
        const text = cellsToText(store.get().cells)
        context.options().onCopy?.(text)
        navigator.clipboard?.writeText(text).catch(() => {})
      },
    }
  },
  slots: (slot) => ({
    root: slot({}),
    grid: slot({
      attrs: () => ({
        role: "grid",
        style: "user-select:none;touch-action:none",
      }),
      on: {
        copy: (event, { api }) => api.copy(event as ClipboardEvent),
        paste: (event, { api }) => api.paste(event as ClipboardEvent),
      },
    }),
    row: slot<{ id: string }>({
      props: { id: "string" },
      attrs: () => ({ role: "row" }),
    }),
    cell: slot<{ id: string; row: number; col: number }, { text: string }>({
      props: { row: "number", col: "number" },
      selects: selects({ active: byCell, range: byCellRange }),
      state: (state, { props }) => ({
        text: state.cells[props.row][props.col],
      }),
      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),
    }),
    copyAll: slot({
      attrs: () => ({ type: "button" }),
      press: ({ api }) => api.copyAll(),
    }),
  }),
})

const parts = createParts(prices, {
  root: "div",
  grid: "div",
  row: "div",
  copyAll: "button",
})

const Prices = parts.Root

const PricesGrid = parts.Grid

const PricesRow = parts.Row

function PricesCell({
  row,
  col,
  ...props
}: { row: number; col: number } & PartProps<"div", { text: string }>) {
  return usePart(
    prices,
    "cell",
    { id: `${row}:${col}`, row, col },
    props,
    "div"
  )
}

const PricesCopyAll = parts.CopyAll

function Example() {
  const log = useLog()
  return (
    <Prices onCopy={(text: string) => log(`Copied ${JSON.stringify(text)}`)}>
      <div data-slot="stack">
        <div data-slot="controls">
          <PricesCopyAll data-size="sm">Copy Whole Sheet</PricesCopyAll>
        </div>
        <PricesGrid aria-label="Prices">
          {start.map((cells, r) => (
            <PricesRow key={r} id={String(r)}>
              {cells.map((_, c) => (
                <PricesCell key={c} row={r} col={c}>
                  {({ text }) => text}
                </PricesCell>
              ))}
            </PricesRow>
          ))}
        </PricesGrid>
      </div>
    </Prices>
  )
}

export {
  Example,
  prices,
  Prices,
  PricesCell,
  PricesCopyAll,
  PricesGrid,
  PricesRow,
  type PricesOptions,
  type PricesState,
}
选择单元格,用 Control 或 Command+C 复制。点击目标单元格,用 Control 或 Command+V 粘贴。

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

API 参考

条目选择选项

keyKey
The state key that holds the selected keys, a string[].
示例: 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).
示例: Choose One
order() => readonly string[]
Every key in list order, for ranges and select all, like the visible items' keys.
示例: Choose One
multiple?(() => boolean)
Whether more than one item can be selected. Defaults to false.
示例: 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.
示例: Items That Can't Be Selected

矩形选择选项

slotstring
The slot whose parts the rectangle selects.
示例: Draw a Rectangle
draftkeyof State & string
The state key that holds the LassoDraft while one is drawn. Start it at null, and list it in live.
示例: Draw a Rectangle
selected() => string[]
The selection now, which Shift adds to.
示例: Draw a Rectangle
set(keys: string[], details: { reason: "lasso"; event?: Event; }) => boolean
Asks for a new selection. Pass the primitive's change.
示例: Draw a Rectangle
selectable?((key: string) => boolean)
Whether an item can be selected. Defaults to every item.
示例: Items It Skips
message?((count: number) => string)
What screen readers hear when the rectangle lifts. Defaults to English.
示例: Items It Skips

单元格范围选项

keykeyof State & string
The state key that holds the CellRange, or null when only the active cell is selected.
示例: Select a Block
gridobject
The grid's focus, which keeps the active cell.
示例: Select a Block
rows() => number
How many rows the range can reach.
示例: Select a Block
cols() => number
How many columns.
示例: Select a Block
reveal?((cell: GridCell) => void)
Shows a cell the range grows to that may not be rendered, like createGridFocus's reveal.
示例: Rows That Aren't 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.
示例: Selecting from Code
message?((bounds: CellBounds) => string)
What screen readers hear after the range changes from the keyboard. Defaults to English.
示例: Selecting from Code