排序列表、嵌套树,或用指针或键盘在列表之间移动条目。

createReorder 排序列表和网格,createTreeReorder 移动行和子树,createTransfer 在列表之间移动条目。它们在移动过程中保留一份草稿,并在放下时通过你的变更提交它。用 bindDrag 为自定义拖动跟踪指针。

从 @ui-sdk/core 导入这些辅助函数。组合行为演示如何把行为接到原语(primitive)上。对于自由定位的条目,见拖动与调整大小。

指针拖动

跟随指针

bindDrag 跟随按压某个元素的指针。在指针处理函数里调用它,并保留它的清理函数,这样销毁原语时也会停止拖动:

let stop: (() => void) | undefined
context.onDestroy(() => stop?.())

return {
  pointerdown(event: PointerEvent, el: HTMLElement) {
    if (event.button !== 0) {
      return
    }
    stop?.()
    stop = bindDrag(el, event, {
      threshold: dragThreshold,
      cancelOnEscape: true,
      onMove: ({ x }) => resizeTo(x),
      onEnd: (_event, canceled) => (canceled ? restore() : commit()),
    })
  },
}

这里 resizeTo、restore 和 commit 是你自己的分隔条方法。bindDrag 只跟踪指针;每个位置意味着什么由你决定,键盘控制也由你添加。

import * as React from "react"
import {
  bindDrag,
  createChange,
  definePrimitive,
  dragThreshold,
  type ChangeDetails,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type SplitState = { size: number; draft: number | null }

type SplitOptions = {
  defaultSize?: number
  onSizeChange?: (
    size: number,
    details: ChangeDetails<"drag" | "keyboard">
  ) => void
}

const clamp = (size: number) => Math.round(Math.min(80, Math.max(20, size)))

const split = definePrimitive({
  name: "split",
  options: { defaultSize: "number", onSizeChange: "callback" },
  state: (options: SplitOptions): SplitState => ({
    size: options.defaultSize ?? 50,
    draft: null,
  }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    let stop: (() => void) | undefined
    context.onDestroy(() => stop?.())
    return {
      pointerdown(event: PointerEvent, el: HTMLElement) {
        const root = el.parentElement
        if (event.button !== 0 || !root) {
          return
        }
        stop?.()
        stop = bindDrag(el, event, {
          threshold: dragThreshold,
          cancelOnEscape: true,
          onMove: ({ x }) => {
            const box = root.getBoundingClientRect()
            store.set({ draft: clamp(((x - box.left) / box.width) * 100) })
          },
          onEnd: (end, canceled) => {
            const { draft } = store.get()
            stop = undefined
            store.set({ draft: null })
            if (!canceled && draft !== null) {
              change("size", draft, { reason: "drag", event: end })
            }
          },
        })
      },
      keydown(event: KeyboardEvent) {
        const by = { ArrowLeft: -5, ArrowRight: 5 }[event.key]
        if (!by) {
          return
        }
        event.preventDefault()
        change("size", clamp(store.get().size + by), {
          reason: "keyboard",
          event,
        })
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { size: number }>({
      state: (state) => ({ size: state.draft ?? state.size }),
      attrs: (state) => ({
        style: `--split:${state.draft ?? state.size}%`,
        "data-dragging": state.draft !== null ? "" : undefined,
      }),
    }),
    divider: slot({
      attrs: (state) => ({
        role: "separator",
        tabindex: "0",
        "aria-orientation": "vertical",
        "aria-valuenow": String(state.draft ?? state.size),
        "aria-valuemin": "20",
        "aria-valuemax": "80",
        style: "touch-action:none",
      }),
      on: {
        pointerdown: (event, { el, api }) => api.pointerdown(event, el!),
        keydown: (event, { api }) => api.keydown(event),
      },
    }),
  }),
})

const parts = createParts(split, { root: "div", divider: "div" })

const Split = parts.Root

const SplitDivider = parts.Divider

function Example() {
  return (
    <Split>
      <div data-slot="bind-pane">Files</div>
      <SplitDivider aria-label="Resize panes" />
      <div data-slot="bind-pane">Editor</div>
    </Split>
  )
}

export { Example }
拖动分隔条,或者聚焦它并使用 Left 和 Right。拖动过程中按 Escape 可以恢复宽度。

onMove 每帧最多运行一次。如果浏览器接管了指针,或者 Escape 取消了拖动,onEnd 会收到一个取消标志。返回的清理函数会停止跟踪,但不调用 onEnd。

dragThreshold 会等待移动几个像素后才开始 onMove。一次按压仍可能在低于该阈值时就结束,所以不要假设每个 onEnd 前面都有一次移动。当拖动应当优先于滚动时,给可拖动的表面设置 touch-action: none。

越过阈值收起

侧边栏会在最小宽度和最大宽度之间调整大小,也可以收起,但绝不会停在两者之间。当指针低于最小值时,让 scrubTo 来决定:给它两个吸附点,收起和最小值,各自覆盖一半的范围,并朝它们缓动:

import { scrubTo } from "@ui-sdk/core/number"

const collapse = { min: 0, max: minWidth, step: 1, snap: { points: [0, minWidth], threshold: minWidth / 2 } }

const widthAt = (pointer: number) =>
  pointer >= minWidth ? { value: Math.min(maxWidth, pointer), point: undefined } : scrubTo(pointer, collapse, { ease: true })

onMove: ({ x }) => {
  const { value, point } = widthAt(x - root.getBoundingClientRect().left)
  store.set({ draft: value, landing: point ?? null })
},
onEnd: () => commit(store.get().landing ?? store.get().draft),

当指针移到最小值以下时,侧边栏会跟随它,并朝更近的那个点加速,于是逐渐接近收起,而不会突然跳变。point 表示它最终会落到哪里,所以演示可以在松开之前就说明;朝另一个方向拖动时,它也会以同样的方式展开。

import * as React from "react"
import {
  bindDrag,
  createChange,
  definePrimitive,
  dragThreshold,
  type ChangeDetails,
} from "@ui-sdk/core"
import { scrubTo } from "@ui-sdk/core/number"
import { createParts } from "@ui-sdk/react/primitive"

type SidebarState = {
  width: number
  opened: number
  draft: number | null
  landing: number | null
}

type SidebarOptions = {
  defaultWidth?: number
  onWidthChange?: (
    width: number,
    details: ChangeDetails<"drag" | "keyboard">
  ) => void
}

const minWidth = 160
const maxWidth = 280

const collapse = {
  min: 0,
  max: minWidth,
  step: 1,
  snap: { points: [0, minWidth], threshold: minWidth / 2 },
}

const widthAt = (pointer: number) =>
  pointer >= minWidth
    ? { value: Math.min(maxWidth, Math.round(pointer)), point: undefined }
    : scrubTo(pointer, collapse, { ease: true })

const sidebar = definePrimitive({
  name: "sidebar",
  options: { defaultWidth: "number", onWidthChange: "callback" },
  state: (options: SidebarOptions): SidebarState => ({
    width: options.defaultWidth ?? 200,
    opened: options.defaultWidth || 200,
    draft: null,
    landing: null,
  }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const resize = (
      width: number,
      reason: "drag" | "keyboard",
      event: Event
    ) => {
      if (width) {
        store.set({ opened: width })
      }
      change("width", width, { reason, event })
    }
    let stop: (() => void) | undefined
    context.onDestroy(() => stop?.())
    return {
      pointerdown(event: PointerEvent, el: HTMLElement) {
        const root = el.parentElement
        if (event.button !== 0 || !root) {
          return
        }
        stop?.()
        stop = bindDrag(el, event, {
          threshold: dragThreshold,
          cancelOnEscape: true,
          onMove: ({ x }) => {
            const { value, point } = widthAt(
              x - root.getBoundingClientRect().left
            )
            store.set({ draft: value, landing: point ?? null })
          },
          onEnd: (end, canceled) => {
            const { draft, landing } = store.get()
            stop = undefined
            store.set({ draft: null, landing: null })
            if (!canceled && draft !== null) {
              resize(landing ?? draft, "drag", end)
            }
          },
        })
      },
      keydown(event: KeyboardEvent) {
        const { width, opened } = store.get()
        const next =
          event.key === "Enter"
            ? width
              ? 0
              : opened
            : event.key === "ArrowLeft"
              ? width - 16 < minWidth
                ? 0
                : width - 16
              : event.key === "ArrowRight"
                ? width
                  ? Math.min(maxWidth, width + 16)
                  : minWidth
                : undefined
        if (next === undefined) {
          return
        }
        event.preventDefault()
        resize(next, "keyboard", event)
      },
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: (state) => {
        const width = state.draft ?? state.width
        return {
          style: `--sidebar:${width}px`,
          "data-collapsed": width === 0 ? "" : undefined,
          "data-dragging": state.draft !== null ? "" : undefined,
          "data-landing":
            state.landing === null
              ? undefined
              : state.landing
                ? "open"
                : "collapsed",
        }
      },
    }),
    divider: slot({
      attrs: (state) => {
        const width = state.draft ?? state.width
        return {
          role: "separator",
          tabindex: "0",
          "aria-orientation": "vertical",
          "aria-valuenow": String(Math.round(width)),
          "aria-valuemin": "0",
          "aria-valuemax": String(maxWidth),
          "aria-valuetext": width ? `${Math.round(width)} pixels` : "Collapsed",
          style: "touch-action:none",
        }
      },
      on: {
        pointerdown: (event, { el, api }) => api.pointerdown(event, el!),
        keydown: (event, { api }) => api.keydown(event),
      },
    }),
  }),
})

const parts = createParts(sidebar, { root: "div", divider: "div" })

const Sidebar = parts.Root

const SidebarDivider = parts.Divider

function Example() {
  return (
    <Sidebar defaultWidth={160}>
      <nav aria-label="Files" data-slot="sidebar-nav">
        <ul>
          {["README.md", "package.json", "src", "tests"].map((file) => (
            <li key={file}>{file}</li>
          ))}
        </ul>
      </nav>
      <SidebarDivider aria-label="Resize sidebar" />
      <div data-slot="sidebar-hint">
        <span data-show="open">Drag the divider left to collapse</span>
        <span data-show="collapsed">Drag right a bit to open</span>
        <span data-show="landing-collapsed">Release to collapse</span>
        <span data-show="landing-open">Release to open at {minWidth}px</span>
      </div>
    </Sidebar>
  )
}

export { Example }
把分隔条拖到侧边栏最小值以下:它会朝收起或回到最小值的方向缓动,并说明松手后会发生哪一种。聚焦分隔条后可以使用 Left、Right 和 Enter。

不受限制地拖动

对于拖动调节器(scrubber),指针锁定让用户能一直拖动,越过屏幕边缘。读取移动的距离,而不是指针的位置:

bindDrag(el, event, {
  threshold: dragThreshold,
  lock: true,
  onStart: () => !context.options().locked,
  onMove: ({ movementX, event }) => {
    change("value", context.store.get().value + movementX / 2, {
      reason: "drag",
      event,
    })
  },
  onEnd: () => {},
})

当移动达到阈值时,onStart 会运行。返回 false 会停止跟踪,但不调用 onEnd。如果浏览器无法锁定指针,跟踪会继续使用指针捕获。

import * as React from "react"
import {
  bindDrag,
  createChange,
  definePrimitive,
  dragThreshold,
  type ChangeDetails,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/react/checkbox"
import { CheckIcon } from "lucide-react"

type ScrubState = { value: number }

type ScrubOptions = {
  locked?: boolean
  onValueChange?: (
    value: number,
    details: ChangeDetails<"drag" | "keyboard">
  ) => void
}

const clamp = (value: number) => Math.round(Math.min(100, Math.max(0, value)))

const scrub = definePrimitive({
  name: "scrub",
  options: { locked: "boolean", onValueChange: "callback" },
  state: (_options: ScrubOptions): ScrubState => ({ value: 50 }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    let stop: (() => void) | undefined
    context.onDestroy(() => stop?.())
    return {
      pointerdown(event: PointerEvent, el: HTMLElement) {
        stop?.()
        stop = bindDrag(el, event, {
          threshold: dragThreshold,
          lock: true,
          onStart: () => !context.options().locked,
          onMove: ({ movementX, event }) =>
            change("value", clamp(store.get().value + movementX / 2), {
              reason: "drag",
              event,
            }),
          onEnd: () => (stop = undefined),
        })
      },
      keydown(event: KeyboardEvent) {
        const by = { ArrowRight: 1, ArrowUp: 1, ArrowLeft: -1, ArrowDown: -1 }[
          event.key
        ]
        if (!by) {
          return
        }
        event.preventDefault()
        change("value", clamp(store.get().value + by), {
          reason: "keyboard",
          event,
        })
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, ScrubState>({
      state: (state) => ({ value: state.value }),
      attrs: (state) => ({
        role: "slider",
        tabindex: "0",
        "aria-valuemin": "0",
        "aria-valuemax": "100",
        "aria-valuenow": String(state.value),
        style: "touch-action:none;user-select:none;cursor:ew-resize",
      }),
      on: {
        pointerdown: (event, { el, api }) => api.pointerdown(event, el!),
        keydown: (event, { api }) => api.keydown(event),
      },
    }),
  }),
})

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

const Scrub = parts.Root

function Example() {
  const [locked, setLocked] = React.useState(false)
  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <label data-slot="label">
          <Checkbox
            checked={locked}
            onCheckedChange={(next) => setLocked(next === true)}
          >
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
          Locked
        </label>
      </div>
      <Scrub aria-label="Opacity" locked={locked}>
        {({ value }) => (
          <>
            <span data-slot="hint">Opacity</span>
            <span>{value}%</span>
          </>
        )}
      </Scrub>
    </div>
  )
}

export { Example }
把 Opacity 标签向左或向右拖动。指针锁定可用时,光标会隐藏,这样你可以一直拖。勾选 Locked 可以阻止拖动。

传给 onMove 的采样对象会被复用。在回调期间读取 x、y、movementX、movementY、locked 和 event,不要把这个对象留到以后再用。

重新排序

排序列表

把已提交的顺序保存在一个 string[] 里,并另起一个 ReorderDraft | null 字段,初始值为 null。在 api 里把它们接到 createReorder:

const change = createChange(context)
const reorder = createReorder(context, {
  slot: "item",
  key: "value",
  draft: "moving",
  set: (value, details) => change("value", value, details),
})

从 api 返回 reorder。用 reorder.order(state) 渲染条目,它在移动过程中读取草稿,其他时候读取已提交的值。顺序变化时,保持每个条目的键稳定。

条目的槽位会先运行重排处理函数,再运行已有的游走焦点处理函数。这样,在有人拿起条目之前,方向键仍然可以移动焦点:

on: {
  keydown: (event, { el, api, key }) =>
    api.reorder.keydown(event, key) || api.roving.keydown(event, el!),
  pointerdown: (event, { api, key }) => api.reorder.pointerdown(event, key),
},
bind: (el, part) => {
  const cleanups = [part.api.roving.bind(el, part), part.api.reorder.bind(el, part)]
  return () => cleanups.forEach((cleanup) => cleanup())
},
import * as React from "react"
import {
  createChange,
  createReorder,
  createRovingFocus,
  definePrimitive,
  type ChangeDetails,
  type ReorderDraft,
  type ReorderReason,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type RankingState = {
  value: string[]
  focused: string | null
  moving: ReorderDraft | null
}

type RankingOptions = {
  defaultValue: string[]
  onValueChange?: (
    value: string[],
    details: ChangeDetails<ReorderReason>
  ) => void
}

const ranking = definePrimitive({
  name: "ranking",
  options: { defaultValue: "list", onValueChange: "callback" },
  state: (options: RankingOptions): RankingState => ({
    value: options.defaultValue,
    focused: null,
    moving: null,
  }),
  api: (context) => {
    const change = createChange(context)
    return {
      roving: createRovingFocus<RankingState, { value: string }>(context, {
        slot: "item",
        key: "focused",
      }),
      reorder: createReorder<RankingState>(context, {
        slot: "item",
        key: "value",
        draft: "moving",
        label: (key) => key,
        set: (value, details) => change("value", value, details),
      }),
    }
  },
  slots: (slot) => ({
    root: slot<{}, { order: string[] }>({
      state: (state, { api }) => ({ order: api.reorder.order(state) }),
      attrs: () => ({
        role: "listbox",
        "aria-roledescription": "sortable list",
      }),
    }),
    item: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        role: "option",
        "aria-roledescription": "sortable item",
        "aria-selected": String(state.moving?.key === part.key),
        tabindex: part.api.roving.tabIndex(state, part),
        "data-grabbed": state.moving?.key === part.key ? "" : undefined,
        style: "touch-action:none;user-select:none",
      }),
      on: {
        keydown: (event, { el, api, key }) =>
          api.reorder.keydown(event, key) || api.roving.keydown(event, el!),
        pointerdown: (event, { api, key }) =>
          api.reorder.pointerdown(event, key),
      },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.reorder.bind(el, part),
        ]
        return () => cleanups.forEach((cleanup) => cleanup())
      },
    }),
  }),
})

const parts = createParts(ranking, { root: "div", item: "div" })

const Ranking = parts.Root

const RankingItem = parts.Item

function Example() {
  return (
    <Ranking
      aria-label="Favorite seasons"
      defaultValue={["Spring", "Summer", "Autumn", "Winter"]}
    >
      {({ order }) =>
        order.map((season, index) => (
          <RankingItem key={season} value={season}>
            <span data-slot="hint">{index + 1}</span>
            {season}
          </RankingItem>
        ))
      }
    </Ranking>
  )
}

export { Example }
拖动一个季节来给它排名。使用键盘时,聚焦其中一个,按 Space 或 Enter,用方向键移动,再按 Space 或 Enter 放下。Escape 取消。

Home 和 End 把拿起的条目移到任意一端。Tab 取消移动,并继续在页面中移动焦点。变更会报告 drag 或 move-key,屏幕阅读器会听到拿起、移动和放下。

这个演示使用由 option 组成的 listbox,为可排序列表和条目设置 aria-roledescription,并为拿起的条目设置 aria-selected。给每个条目一个 aria-describedby,指向键盘操作说明。对于带嵌套控件的条目,使用列表并单独提供一个拖动手柄按钮,把处理函数放在那个手柄上。

拖动过程中,core 会把 --drag-x 和 --drag-y 写到绑定的条目上。用它们让条目保持在指针下方,并用 state.moving?.key === key 派生出 data-grabbed 属性:

[data-slot="sortable-list-item"] {
  touch-action: none;
  user-select: none;
}
[data-slot="sortable-list-item"][data-grabbed] {
  transform: translate(var(--drag-x, 0), var(--drag-y, 0));
  position: relative;
  z-index: 1;
}

网格

默认方向是纵向。对于会换行成多行的条目,加上 orientation: () => "grid":

orientation: () => "grid",
import * as React from "react"
import {
  createChange,
  createReorder,
  createRovingFocus,
  definePrimitive,
  spatialMove,
  type ReorderDraft,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type AlbumState = {
  value: string[]
  focused: string | null
  moving: ReorderDraft | null
}

const album = definePrimitive({
  name: "album",
  state: (): AlbumState => ({
    value: [
      "Dawn",
      "Dune",
      "Fern",
      "Fjord",
      "Glacier",
      "Harbor",
      "Mesa",
      "Reef",
    ],
    focused: null,
    moving: null,
  }),
  api: (context) => {
    const change = createChange(context)
    return {
      roving: createRovingFocus<AlbumState, { value: string }>(context, {
        slot: "photo",
        key: "focused",
        move: spatialMove(),
      }),
      reorder: createReorder<AlbumState>(context, {
        slot: "photo",
        key: "value",
        draft: "moving",
        set: (value, details) => change("value", value, details),
        orientation: () => "grid",
      }),
    }
  },
  slots: (slot) => ({
    root: slot<{}, { order: string[] }>({
      state: (state, { api }) => ({ order: api.reorder.order(state) }),
      attrs: () => ({
        role: "listbox",
        "aria-roledescription": "sortable grid",
      }),
    }),
    photo: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        role: "option",
        "aria-roledescription": "sortable item",
        "aria-selected": String(state.moving?.key === part.key),
        tabindex: part.api.roving.tabIndex(state, part),
        "data-grabbed": state.moving?.key === part.key ? "" : undefined,
        style: "touch-action:none;user-select:none",
      }),
      on: {
        keydown: (event, { el, api, key }) =>
          api.reorder.keydown(event, key) || api.roving.keydown(event, el!),
        pointerdown: (event, { api, key }) =>
          api.reorder.pointerdown(event, key),
      },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.reorder.bind(el, part),
        ]
        return () => cleanups.forEach((cleanup) => cleanup())
      },
    }),
  }),
})

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

const Album = parts.Root

const AlbumPhoto = parts.Photo

function Example() {
  return (
    <Album aria-label="Album">
      {({ order }) =>
        order.map((photo) => (
          <AlbumPhoto key={photo} value={photo}>
            {photo}
          </AlbumPhoto>
        ))
      }
    </Album>
  )
}

export { Example }
把照片拖到新位置,或者按 Space 拿起它。Left 和 Right 移动一个位置;Up 和 Down 在行之间移动。Space 放下它。

对于单行横向排列,使用 "horizontal",给它的游走焦点设置相同的方向,并在列表框上设置 aria-orientation="horizontal"。

一次移动多个

group 回调让选中的一组条目一起移动。把它加到重排选项里:

group: (key) => {
  const { selected } = context.store.get()
  return selected.includes(key) ? selected : [key]
},

分组在拖动开始时确定,保持列表的顺序,并把已禁用的条目留在原处。reorder.moving(state, key) 标识分组里的每个条目;reorder.dragging(state, key) 还要求这是一次指针拖动。

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

type BacklogState = {
  value: string[]
  selected: string[]
  focused: string | null
  moving: ReorderDraft | null
}

const backlog = definePrimitive({
  name: "backlog",
  state: (): BacklogState => ({
    value: [
      "Login page",
      "Search",
      "Dark mode",
      "Exports",
      "Billing",
      "Onboarding",
    ],
    selected: [],
    focused: null,
    moving: null,
  }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    return {
      roving: createRovingFocus<BacklogState, { value: string }>(context, {
        slot: "task",
        key: "focused",
      }),
      reorder: createReorder<BacklogState>(context, {
        slot: "task",
        key: "value",
        draft: "moving",
        set: (value, details) => change("value", value, details),
        group: (key) => {
          const { selected } = store.get()
          return selected.includes(key) ? selected : [key]
        },
      }),
      tick(key: string) {
        const { selected } = store.get()
        store.set({
          selected: selected.includes(key)
            ? selected.filter((other) => other !== key)
            : [...selected, key],
        })
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { order: string[] }>({
      state: (state, { api }) => ({ order: api.reorder.order(state) }),
      attrs: () => ({ role: "list" }),
    }),
    task: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        role: "listitem",
        tabindex: part.api.roving.tabIndex(state, part),
        "data-moving": part.api.reorder.moving(state, part.key)
          ? ""
          : undefined,
        "data-dragging": part.api.reorder.dragging(state, part.key)
          ? ""
          : undefined,
        style: "touch-action:none;user-select:none",
      }),
      on: {
        keydown: (event, { el, api, key }) =>
          api.reorder.keydown(event, key) || api.roving.keydown(event, el!),
        pointerdown: (event, { api, key }) =>
          api.reorder.pointerdown(event, key),
      },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.reorder.bind(el, part),
        ]
        return () => cleanups.forEach((cleanup) => cleanup())
      },
    }),
    tick: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        type: "button",
        role: "checkbox",
        "aria-checked": String(state.selected.includes(part.key)),
        "aria-label": `Select ${part.key}`,
        tabindex: "-1",
      }),
      on: {
        pointerdown: (event) => event.preventDefault(),
        click: (_event, { api, key }) => api.tick(key),
      },
    }),
  }),
})

const parts = createParts(backlog, { root: "div", task: "div", tick: "button" })

const Backlog = parts.Root

const BacklogTask = parts.Task

const BacklogTick = parts.Tick

function Example() {
  return (
    <Backlog aria-label="Backlog">
      {({ order }) =>
        order.map((task) => (
          <BacklogTask key={task} value={task}>
            <BacklogTick value={task} />
            {task}
          </BacklogTask>
        ))
      }
    </Backlog>
  )
}

export { Example }
勾选几个任务,然后拖动其中一个已勾选的任务。你也可以聚焦一个已勾选的任务,用 Space 和方向键移动整个分组。

已经用 preventDefault() 处理过的指针事件不会启动重排。这样,复选框可以处理自己的按压,而不会同时拿起条目。

拖动时显示副本

对于可滚动的列表,被平移的条目可能会被裁剪。加上 preview: true,在页面之上拖动一份副本:

preview: true,
createAutoScroll: { edge: 40, speed: 12 },
import * as React from "react"
import {
  createChange,
  createReorder,
  createRovingFocus,
  definePrimitive,
  type ReorderDraft,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type QueueState = {
  value: string[]
  focused: string | null
  moving: ReorderDraft | null
}

const songs = Array.from(
  { length: 16 },
  (_, index) => `Track ${String(index + 1).padStart(2, "0")}`
)

const queue = definePrimitive({
  name: "queue",
  state: (): QueueState => ({ value: songs, focused: null, moving: null }),
  api: (context) => {
    const change = createChange(context)
    return {
      roving: createRovingFocus<QueueState, { value: string }>(context, {
        slot: "song",
        key: "focused",
      }),
      reorder: createReorder<QueueState>(context, {
        slot: "song",
        key: "value",
        draft: "moving",
        set: (value, details) => change("value", value, details),
        preview: true,
        createAutoScroll: { edge: 40, speed: 12 },
      }),
    }
  },
  slots: (slot) => ({
    root: slot<{}, { order: string[] }>({
      state: (state, { api }) => ({ order: api.reorder.order(state) }),
      attrs: () => ({
        role: "listbox",
        "aria-roledescription": "sortable list",
      }),
    }),
    song: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        role: "option",
        "aria-roledescription": "sortable item",
        "aria-selected": String(state.moving?.key === part.key),
        tabindex: part.api.roving.tabIndex(state, part),
        "data-dragging": part.api.reorder.dragging(state, part.key)
          ? ""
          : undefined,
        style: "touch-action:none;user-select:none",
      }),
      on: {
        keydown: (event, { el, api, key }) =>
          api.reorder.keydown(event, key) || api.roving.keydown(event, el!),
        pointerdown: (event, { api, key }) =>
          api.reorder.pointerdown(event, key),
      },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.reorder.bind(el, part),
        ]
        return () => cleanups.forEach((cleanup) => cleanup())
      },
    }),
  }),
})

const parts = createParts(queue, { root: "div", song: "div" })

const Queue = parts.Root

const QueueSong = parts.Song

function Example() {
  return (
    <Queue aria-label="Queue">
      {({ order }) =>
        order.map((song) => (
          <QueueSong key={song} value={song}>
            {song}
          </QueueSong>
        ))
      }
    </Queue>
  )
}

export { Example }
拖动一首曲目,并把它停在播放列表的顶部或底部边缘附近来滚动。它的占位符会显示它将落到哪里。

原条目会留在拟定的顺序里。使用分组时,副本还会获得 data-drag-count 和 --drag-count,用于显示数量徽标。自动滚动会随预览一起启用;用 createAutoScroll: false 关掉它。

用代码移动

对于立即发生的变更,比如菜单的 Move to Top 操作,使用 move:

reorder.move("Serve", 0)

对于一次只走一步的控件,使用 grab(key)、moveTo(index) 和 drop() 或 cancel()。moveTo 在移除正在移动的分组后剩下的条目之间计算位置。

import * as React from "react"
import {
  createChange,
  createReorder,
  createRovingFocus,
  definePrimitive,
  type ReorderDraft,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { ArrowDownIcon, ArrowUpIcon } from "lucide-react"

type RecipeState = {
  value: string[]
  focused: string | null
  moving: ReorderDraft | null
}

const recipe = definePrimitive({
  name: "recipe",
  state: (): RecipeState => ({
    value: ["Boil water", "Add pasta", "Make the sauce", "Drain", "Serve"],
    focused: "Boil water",
    moving: null,
  }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const reorder = createReorder<RecipeState>(context, {
      slot: "step",
      key: "value",
      draft: "moving",
      set: (value, details) => change("value", value, details),
    })
    return {
      roving: createRovingFocus<RecipeState, { value: string }>(context, {
        slot: "step",
        key: "focused",
      }),
      reorder,
      act(action: string) {
        const { focused, moving } = store.get()
        if (action === "grab" && focused) {
          reorder.grab(focused)
        } else if (moving && (action === "up" || action === "down")) {
          const index = moving.order.indexOf(moving.key)
          reorder.moveTo(index + (action === "up" ? -1 : 1))
        } else if (action === "drop") {
          reorder.drop()
        } else if (action === "cancel") {
          reorder.cancel()
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { order: string[] }>({
      state: (state, { api }) => ({ order: api.reorder.order(state) }),
    }),
    list: slot({
      attrs: () => ({
        role: "listbox",
        "aria-roledescription": "sortable list",
      }),
    }),
    step: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        role: "option",
        "aria-roledescription": "sortable item",
        "aria-selected": String(state.moving?.key === part.key),
        tabindex: part.api.roving.tabIndex(state, part),
        "data-grabbed": state.moving?.key === part.key ? "" : undefined,
        style: "touch-action:none;user-select:none",
      }),
      on: {
        keydown: (event, { el, api, key }) =>
          api.reorder.keydown(event, key) || api.roving.keydown(event, el!),
        pointerdown: (event, { api, key }) =>
          api.reorder.pointerdown(event, key),
      },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.reorder.bind(el, part),
        ]
        return () => cleanups.forEach((cleanup) => cleanup())
      },
    }),
    toTop: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (_state, part) => ({
        type: "button",
        tabindex: "-1",
        "aria-label": `Move ${part.key} to top`,
      }),
      on: { pointerdown: (event) => event.preventDefault() },
      press: ({ api, key }) => api.reorder.move(key, 0),
    }),
    action: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        type: "button",
        disabled: (part.key === "grab") === !!state.moving ? "" : undefined,
      }),
      on: { pointerdown: (event) => event.preventDefault() },
      press: ({ api, key }) => api.act(key),
    }),
  }),
})

const parts = createParts(recipe, {
  root: "div",
  list: "div",
  step: "div",
  toTop: "button",
  action: "button",
})

const Recipe = parts.Root

const RecipeList = parts.List

const RecipeStep = parts.Step

const RecipeToTop = parts.ToTop

const RecipeAction = parts.Action

function Example() {
  return (
    <Recipe>
      {({ order }) => (
        <>
          <div data-slot="controls">
            <RecipeAction data-size="sm" value="grab">
              Pick Up
            </RecipeAction>
            <RecipeAction data-size="sm" value="up" aria-label="Move up">
              <ArrowUpIcon aria-hidden="true" />
            </RecipeAction>
            <RecipeAction data-size="sm" value="down" aria-label="Move down">
              <ArrowDownIcon aria-hidden="true" />
            </RecipeAction>
            <RecipeAction data-size="sm" value="drop">
              Drop
            </RecipeAction>
            <RecipeAction data-size="sm" value="cancel">
              Cancel
            </RecipeAction>
          </div>
          <RecipeList aria-label="Recipe">
            {order.map((step) => (
              <RecipeStep key={step} value={step}>
                {step}
                <RecipeToTop value={step}>
                  <ArrowUpIcon aria-hidden="true" />
                  Top
                </RecipeToTop>
              </RecipeStep>
            ))}
          </RecipeList>
        </>
      )}
    </Recipe>
  )
}

export { Example }
使用 Top 立即移动一个食谱步骤。工具栏会拿起聚焦的步骤,移动它,然后放下或取消。

立即移动会报告 imperative;拿起和放下控件遵循与键盘相同的草稿。

播报什么

当条目的可见文本包含的内容多于它的名称时,使用 label。自定义 message 可以只替换一条播报,其余仍用默认值:

disabled: (item) => item.key === context.options().pinned,
label: (key) => titles[key],
message: (message) =>
  message.type === "move" ? `${message.label}, track ${message.position}.` : reorderMessage(message),
import * as React from "react"
import {
  createChange,
  createReorder,
  createRovingFocus,
  definePrimitive,
  reorderMessage,
  type ReorderDraft,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type TracksState = {
  value: string[]
  focused: string | null
  moving: ReorderDraft | null
}

type TracksOptions = {
  pinned: string
}

const titles: Record<string, string> = {
  intro: "Intro",
  tides: "Tides",
  ember: "Ember",
  static: "Static",
}

const tracks = definePrimitive({
  name: "tracks",
  options: { pinned: "string" },
  state: (_options: TracksOptions): TracksState => ({
    value: ["intro", "tides", "ember", "static"],
    focused: null,
    moving: null,
  }),
  api: (context) => {
    const change = createChange(context)
    return {
      roving: createRovingFocus<TracksState, { value: string }>(context, {
        slot: "track",
        key: "focused",
      }),
      reorder: createReorder<TracksState, { value: string }>(context, {
        slot: "track",
        key: "value",
        draft: "moving",
        set: (value, details) => change("value", value, details),
        disabled: (item) => item.key === context.options().pinned,
        label: (key) => titles[key],
        message: (message) =>
          message.type === "move"
            ? `${message.label}, track ${message.position}.`
            : reorderMessage(message),
      }),
    }
  },
  slots: (slot) => ({
    root: slot<{}, { order: string[] }>({
      state: (state, { api }) => ({ order: api.reorder.order(state) }),
      attrs: () => ({
        role: "listbox",
        "aria-roledescription": "sortable list",
      }),
    }),
    track: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        role: "option",
        "aria-roledescription": "sortable item",
        "aria-selected": String(state.moving?.key === part.key),
        tabindex: part.api.roving.tabIndex(state, part),
        "data-grabbed": state.moving?.key === part.key ? "" : undefined,
        style: "touch-action:none;user-select:none",
      }),
      on: {
        keydown: (event, { el, api, key }) =>
          api.reorder.keydown(event, key) || api.roving.keydown(event, el!),
        pointerdown: (event, { api, key }) =>
          api.reorder.pointerdown(event, key),
      },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.reorder.bind(el, part),
        ]
        return () => cleanups.forEach((cleanup) => cleanup())
      },
    }),
  }),
})

const parts = createParts(tracks, { root: "div", track: "div" })

const Tracks = parts.Root

const TracksTrack = parts.Track

const lengths: Record<string, string> = {
  intro: "0:48",
  tides: "3:12",
  ember: "4:05",
  static: "2:37",
}

function Example() {
  return (
    <Tracks pinned="intro" aria-label="Tracks">
      {({ order }) =>
        order.map((track) => (
          <TracksTrack key={track} value={track}>
            {titles[track]}
            <span data-slot="hint">
              {track === "intro" ? "Pinned" : lengths[track]}
            </span>
          </TracksTrack>
        ))
      }
    </Tracks>
  )
}

export { Example }
用 Space 拿起未固定的曲目,并用方向键移动它。屏幕阅读器会播报曲目编号。已固定的曲目不能被拿起,但其他曲目可以越过它移动。

disabled 阻止拿起;但它不会保留条目的位置。播报是即时(assertive)的,一轮中的多个变更可能作为最新消息一起播报。

重新排序树

排序与嵌套

树使用一个扁平的 { key, depth } 行数组,按阅读顺序排列。移动父级会移动它的整个子树。把 moving 的初始值设为 null,类型为 TreeReorderDraft | null:

const tree = createTreeReorder(context, {
  key: "rows",
  draft: "moving",
  set: (value, details) => change("rows", value, details),
  indent: () => 20,
  preview: true,
})

渲染 tree.rows(state),按 depth 缩进,并用 tree.bind(el, key) 绑定每个渲染出的行。也要保留游走焦点的绑定。和可排序列表一样,在焦点处理函数之前调用 tree.keydown(event, key),在按压时调用 tree.pointerdown(event, key)。

import * as React from "react"
import {
  createChange,
  createRovingFocus,
  createTreeReorder,
  css,
  definePrimitive,
  type ChangeDetails,
  type TreeReorderDraft,
  type TreeReorderReason,
  type TreeReorderRow,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type PagesState = {
  rows: TreeReorderRow[]
  focused: string | null
  moving: TreeReorderDraft | null
}

type PagesOptions = {
  defaultRows: TreeReorderRow[]
  onRowsChange?: (
    rows: TreeReorderRow[],
    details: ChangeDetails<TreeReorderReason>
  ) => void
}

const pages = definePrimitive({
  name: "pages",
  options: { defaultRows: "value", onRowsChange: "callback" },
  state: (options: PagesOptions): PagesState => ({
    rows: options.defaultRows,
    focused: null,
    moving: null,
  }),
  api: (context) => {
    const change = createChange(context)
    return {
      roving: createRovingFocus<PagesState, { value: string }>(context, {
        slot: "row",
        key: "focused",
      }),
      tree: createTreeReorder<PagesState>(context, {
        key: "rows",
        draft: "moving",
        set: (value, details) => change("rows", value, details),
        indent: () => 20,
        preview: true,
      }),
    }
  },
  slots: (slot) => ({
    root: slot<{}, { rows: TreeReorderRow[] }>({
      state: (state, { api }) => ({ rows: api.tree.rows(state) }),
      attrs: () => ({ role: "tree" }),
    }),
    row: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => {
        const depth =
          part.api.tree.rows(state).find((row) => row.key === part.key)
            ?.depth ?? 0
        return {
          role: "treeitem",
          "aria-level": String(depth + 1),
          tabindex: part.api.roving.tabIndex(state, part),
          "data-moving": part.api.tree.moving(state, part.key) ? "" : undefined,
          style: css({
            "--depth": String(depth),
            "touch-action": "none",
            "user-select": "none",
          }),
        }
      },
      on: {
        keydown: (event, { el, api, key }) =>
          api.tree.keydown(event, key) || api.roving.keydown(event, el!),
        pointerdown: (event, { api, key }) => api.tree.pointerdown(event, key),
      },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.tree.bind(el, part.key),
        ]
        return () => cleanups.forEach((cleanup) => cleanup())
      },
    }),
  }),
})

const parts = createParts(pages, { root: "div", row: "div" })

const Pages = parts.Root

const PagesRow = parts.Row

const outline = [
  { key: "Guides", depth: 0 },
  { key: "Install", depth: 1 },
  { key: "Forms", depth: 1 },
  { key: "Reference", depth: 0 },
  { key: "Hooks", depth: 1 },
  { key: "Changelog", depth: 0 },
]

function Example() {
  return (
    <Pages aria-label="Pages" defaultRows={outline}>
      {({ rows }) =>
        rows.map((row) => (
          <PagesRow key={row.key} value={row.key}>
            {row.key}
          </PagesRow>
        ))
      }
    </Pages>
  )
}

export { Example }
把大纲行向上或向下拖动,横向拖动可以改变它的深度。使用键盘时,按 Space 拿起它,用 Up 和 Down 放置,用 Left 和 Right 改变它的层级。

indent 是一级的水平距离,默认 24 像素。关闭的子树可以留在数据里,而它们的行不挂载;指针命中会跳过这些隐藏的行。

一次移动不会改变相邻行的父级。深度受插入点周围行的限制。set 的详情包括 key、parent(根节点处为 null),以及在该父级子节点中从 0 开始的 index;当你的应用存储的是嵌套树时,这很有用。

限制与用代码移动

加上最大深度和拿起规则:

maxDepth: () => 1,
disabled: (key) => key === "Inbox",

深度从 0 开始,所以这里允许两层。限制包括正在移动的行及其后代。

import * as React from "react"
import {
  createChange,
  createRovingFocus,
  createTreeReorder,
  css,
  definePrimitive,
  subtreeEnd,
  treeReorderMessage,
  type TreeReorderDraft,
  type TreeReorderRow,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import {
  ArrowLeftIcon,
  ArrowRightIcon,
  FolderIcon,
  InboxIcon,
} from "lucide-react"

type FoldersState = {
  rows: TreeReorderRow[]
  focused: string | null
  moving: TreeReorderDraft | null
}

const counts: Record<string, number> = {
  Inbox: 12,
  Work: 4,
  Reports: 2,
  Drafts: 1,
  Personal: 7,
  Travel: 3,
}

const folders = definePrimitive({
  name: "folders",
  state: (): FoldersState => ({
    rows: [
      { key: "Inbox", depth: 0 },
      { key: "Work", depth: 0 },
      { key: "Reports", depth: 1 },
      { key: "Drafts", depth: 1 },
      { key: "Personal", depth: 0 },
      { key: "Travel", depth: 1 },
    ],
    focused: null,
    moving: null,
  }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const tree = createTreeReorder<FoldersState>(context, {
      key: "rows",
      draft: "moving",
      set: (value, details) => change("rows", value, details),
      indent: () => 16,
      maxDepth: () => 1,
      disabled: (key) => key === "Inbox",
      label: (key) => key,
      message: (message) =>
        message.type === "drop"
          ? `${message.label} moved, level ${message.level}.`
          : treeReorderMessage(message),
    })
    return {
      roving: createRovingFocus<FoldersState, { value: string }>(context, {
        slot: "row",
        key: "focused",
      }),
      tree,
      shift(key: string, by: number) {
        const rows = store.get().rows
        const index = rows.findIndex((row) => row.key === key)
        const after = rows[subtreeEnd(rows, index)]?.key ?? null
        tree.move(key, after, rows[index].depth + by)
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { rows: TreeReorderRow[] }>({
      state: (state, { api }) => ({ rows: api.tree.rows(state) }),
      attrs: () => ({ role: "tree" }),
    }),
    row: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => {
        const rows = part.api.tree.rows(state)
        const index = rows.findIndex((row) => row.key === part.key)
        return {
          role: "treeitem",
          "aria-level": String(rows[index].depth + 1),
          tabindex: part.api.roving.tabIndex(state, part),
          "data-moving": part.api.tree.moving(state, part.key) ? "" : undefined,
          "data-dragging": part.api.tree.dragging(state, part.key)
            ? ""
            : undefined,
          "data-parent": subtreeEnd(rows, index) > index + 1 ? "" : undefined,
          style: css({
            "--depth": String(rows[index].depth),
            "touch-action": "none",
            "user-select": "none",
          }),
        }
      },
      on: {
        keydown: (event, { el, api, key }) =>
          api.tree.keydown(event, key) || api.roving.keydown(event, el!),
        pointerdown: (event, { api, key }) => api.tree.pointerdown(event, key),
      },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.tree.bind(el, part.key),
        ]
        return () => cleanups.forEach((cleanup) => cleanup())
      },
    }),
    indent: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (_state, part) => ({
        type: "button",
        tabindex: "-1",
        "aria-label": `Indent ${part.key}`,
      }),
      on: { pointerdown: (event) => event.preventDefault() },
      press: ({ api, key }) => api.shift(key, 1),
    }),
    outdent: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (_state, part) => ({
        type: "button",
        tabindex: "-1",
        "aria-label": `Outdent ${part.key}`,
      }),
      on: { pointerdown: (event) => event.preventDefault() },
      press: ({ api, key }) => api.shift(key, -1),
    }),
  }),
})

const parts = createParts(folders, {
  root: "div",
  row: "div",
  indent: "button",
  outdent: "button",
})

const Folders = parts.Root

const FoldersRow = parts.Row

const FoldersIndent = parts.Indent

const FoldersOutdent = parts.Outdent

function Example() {
  return (
    <Folders aria-label="Folders">
      {({ rows }) =>
        rows.map((row) => (
          <FoldersRow key={row.key} value={row.key}>
            {row.key === "Inbox" ? (
              <InboxIcon aria-hidden="true" />
            ) : (
              <FolderIcon aria-hidden="true" />
            )}
            <span>{row.key}</span>
            <span data-slot="hint">{counts[row.key]}</span>
            {row.key !== "Inbox" && (
              <>
                <FoldersOutdent value={row.key}>
                  <ArrowLeftIcon aria-hidden="true" />
                </FoldersOutdent>
                <FoldersIndent value={row.key}>
                  <ArrowRightIcon aria-hidden="true" />
                </FoldersIndent>
              </>
            )}
          </FoldersRow>
        ))
      }
    </Folders>
  )
}

export { Example }
使用文件夹的箭头按钮,把它连同内容一起缩进或取消缩进。树允许两层,Inbox 不能被拿起。

tree.move(key, before, depth) 把子树移到另一行之前;当 before 为 null 时,移到末尾。它会使用最接近且合适的深度。subtreeEnd(rows, index) 返回子树之后的第一个索引,有助于计算插入位置。

对于分步移动,使用 grab、place,然后 drop 或 cancel。moving(state, key) 包括后代;dragging 还会检查移动是否来自指针。像列表那样自定义 label 和 message,默认文案由 treeReorderMessage 提供。

在列表之间移动

两个列表

把各个列表一起存成一个 Record<string, string[]>,并让条目键在所有列表之间唯一。为移动添加一个 TransferDraft | null 字段:

const transfer = createTransfer(context, {
  key: "lists",
  draft: "moving",
  set: (value, details) => change("lists", value, details),
})

从 transfer.lists(state) 渲染。用 bindList(el, key) 绑定列表元素,用 bindItem(el, key) 绑定条目元素,并从槽位返回它们的清理函数。保留已有的焦点绑定,并在它的按键处理函数之前运行 transfer.keydown(event, key)。按压时调用 transfer.pointerdown(event, key)。

import * as React from "react"
import {
  createChange,
  createRovingFocus,
  createTransfer,
  definePrimitive,
  spatialMove,
  type ChangeDetails,
  type TransferDraft,
  type TransferLists,
  type TransferReason,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

const names: Record<string, string> = { closet: "Closet", bag: "Bag" }

type PackingState = {
  lists: TransferLists
  focused: string | null
  moving: TransferDraft | null
}

type PackingOptions = {
  defaultLists: TransferLists
  onListsChange?: (
    lists: TransferLists,
    details: ChangeDetails<TransferReason>
  ) => void
}

const packing = definePrimitive({
  name: "packing",
  options: { defaultLists: "value", onListsChange: "callback" },
  state: (options: PackingOptions): PackingState => ({
    lists: options.defaultLists,
    focused: null,
    moving: null,
  }),
  api: (context) => {
    const change = createChange(context)
    return {
      roving: createRovingFocus<PackingState, { value: string }>(context, {
        slot: "item",
        key: "focused",
        move: spatialMove(),
      }),
      transfer: createTransfer<PackingState>(context, {
        key: "lists",
        draft: "moving",
        set: (value, details) => change("lists", value, details),
      }),
    }
  },
  slots: (slot) => ({
    root: slot<{}, { lists: TransferLists }>({
      state: (state, { api }) => ({ lists: api.transfer.lists(state) }),
    }),
    list: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ role: "listbox" }),
      bind: (el, { api, key }) => api.transfer.bindList(el, key),
    }),
    item: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        role: "option",
        "aria-selected": String(state.moving?.key === part.key),
        tabindex: part.api.roving.tabIndex(state, part),
        "data-dragging": part.api.transfer.dragging(state, part.key)
          ? ""
          : undefined,
        style: "touch-action:none;user-select:none",
      }),
      on: {
        keydown: (event, { el, api, key }) =>
          api.transfer.keydown(event, key) || api.roving.keydown(event, el!),
        pointerdown: (event, { api, key }) =>
          api.transfer.pointerdown(event, key),
      },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.transfer.bindItem(el, part.key),
        ]
        return () => cleanups.forEach((cleanup) => cleanup())
      },
    }),
  }),
})

const parts = createParts(packing, { root: "div", list: "div", item: "div" })

const Packing = parts.Root

const PackingList = parts.List

const PackingItem = parts.Item

function Example() {
  return (
    <Packing
      defaultLists={{
        closet: ["Jacket", "Boots", "Scarf"],
        bag: ["Passport", "Charger"],
      }}
    >
      {({ lists }) =>
        Object.entries(lists).map(([list, items]) => (
          <div key={list} data-slot="transfer-lane">
            <span data-slot="transfer-label">{names[list]}</span>
            <PackingList value={list} aria-label={names[list]}>
              {items.map((item) => (
                <PackingItem key={item} value={item}>
                  {item}
                </PackingItem>
              ))}
            </PackingList>
          </div>
        ))
      }
    </Packing>
  )
}

export { Example }
在打包清单之间拖动条目。使用键盘时,按 Space 拿起它,用 Left 和 Right 切换列表,用 Up 和 Down 放置,然后按 Space 放下。

移动使用一份被拖动的副本,并在靠近边缘时自动滚动。moving(state, key) 标识拿起的条目,而 dragging(state, key) 标识一次指针拖动。set 的详情包括条目的 key、它的 from 和 to 列表,以及它的新 index。

带规则的看板

用 accepts 拒绝某个目标,用 order 选择键盘在列表之间的行进顺序:

order: () => ["todo", "doing", "done"],
accepts: (key, list) =>
  list !== "doing" || context.store.get().lists.doing.filter((card) => card !== key).length < 2,
disabled: (key) => key === "Billing",
listLabel: (list) => columns[list],
import * as React from "react"
import {
  createChange,
  createRovingFocus,
  createTransfer,
  definePrimitive,
  spatialMove,
  transferMessage,
  type TransferDraft,
  type TransferLists,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { CheckIcon } from "lucide-react"

type BoardState = {
  lists: TransferLists
  focused: string | null
  moving: TransferDraft | null
}

const columns: Record<string, string> = {
  todo: "To do",
  doing: "Doing",
  done: "Done",
}
const blocked = "Billing"
const tags: Record<string, string> = {
  Search: "Feature",
  Billing: "Blocked",
  Login: "Bug",
  Docs: "Chore",
  Icons: "Design",
}

const board = definePrimitive({
  name: "board",
  state: (): BoardState => ({
    lists: {
      done: ["Icons"],
      todo: ["Search", "Billing", "Login"],
      doing: ["Docs"],
    },
    focused: null,
    moving: null,
  }),
  api: (context) => {
    const change = createChange(context)
    return {
      roving: createRovingFocus<BoardState, { value: string }>(context, {
        slot: "card",
        key: "focused",
        move: spatialMove(),
      }),
      transfer: createTransfer<BoardState>(context, {
        key: "lists",
        draft: "moving",
        set: (value, details) => change("lists", value, details),
        order: () => ["todo", "doing", "done"],
        accepts: (key, list) =>
          list !== "doing" ||
          context.store.get().lists.doing.filter((card) => card !== key)
            .length < 2,
        disabled: (key) => key === blocked,
        label: (key) => key,
        listLabel: (list) => columns[list],
        message: (message) =>
          message.type === "drop"
            ? `${message.label} is in ${message.list} now.`
            : transferMessage(message),
        createAutoScroll: false,
      }),
    }
  },
  slots: (slot) => ({
    root: slot<{}, { lists: TransferLists }>({
      state: (state, { api }) => ({ lists: api.transfer.lists(state) }),
    }),
    column: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ role: "listbox" }),
      bind: (el, { api, key }) => api.transfer.bindList(el, key),
    }),
    card: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        role: "option",
        "aria-selected": String(part.api.transfer.moving(state, part.key)),
        "aria-disabled": part.key === blocked ? "true" : undefined,
        tabindex: part.api.roving.tabIndex(state, part),
        "data-dragging": part.api.transfer.dragging(state, part.key)
          ? ""
          : undefined,
        style: "touch-action:none;user-select:none",
      }),
      on: {
        keydown: (event, { el, api, key }) =>
          api.transfer.keydown(event, key) || api.roving.keydown(event, el!),
        pointerdown: (event, { api, key }) =>
          api.transfer.pointerdown(event, key),
      },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.transfer.bindItem(el, part.key),
        ]
        return () => cleanups.forEach((cleanup) => cleanup())
      },
    }),
    finish: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (_state, part) => ({
        type: "button",
        tabindex: "-1",
        "aria-label": `Move ${part.key} to Done`,
      }),
      on: { pointerdown: (event) => event.preventDefault() },
      press: ({ api, key }) => api.transfer.move(key, "done", 0),
    }),
  }),
})

const parts = createParts(board, {
  root: "div",
  column: "div",
  card: "div",
  finish: "button",
})

const Board = parts.Root

const BoardColumn = parts.Column

const BoardCard = parts.Card

const BoardFinish = parts.Finish

function Example() {
  return (
    <Board>
      {({ lists }) =>
        Object.keys(columns).map((list) => (
          <div key={list} data-slot="transfer-lane">
            <span data-slot="transfer-label">
              {columns[list]}
              {list === "doing" && <span>Max 2</span>}
            </span>
            <BoardColumn value={list} aria-label={columns[list]}>
              {lists[list].map((card) => (
                <BoardCard key={card} value={card}>
                  {card}
                  <div data-slot="transfer-meta">
                    {tags[card]}
                    {list !== "done" && card !== blocked && (
                      <BoardFinish value={card}>
                        <CheckIcon aria-hidden="true" />
                      </BoardFinish>
                    )}
                  </div>
                </BoardCard>
              ))}
            </BoardColumn>
          </div>
        ))
      }
    </Board>
  )
}

export { Example }
在列之间移动卡片。Doing 最多容纳两张卡片,Billing 不能被拿起,卡片上的勾选会把它直接移到 Done。

transfer.move("Search", "done", 0) 会立即移动。对于分步移动,使用 grab、moveTo(list, index),然后 drop 或 cancel。

label 为条目命名,listLabel 为目标命名,message 自定义播报,默认由 transferMessage 提供。对于不需要边缘滚动的看板,设置 createAutoScroll: false。

拖动副本

对于你自己的拖动,bindDragPreview 会创建一个跟随指针的元素副本。原元素留在原处:

const preview = bindDragPreview(el, { x: event.clientX, y: event.clientY })

在拖动的 onMove 里调用 preview.move(x, y)。在 onEnd 和任何提前清理中调用 preview.remove()。你可以通过 preview.el 给副本设置样式,例如在有效目标上方切换 data-over 属性。

import * as React from "react"
import {
  bindDrag,
  bindDragPreview,
  createChange,
  definePrimitive,
  dragThreshold,
  type ChangeDetails,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type TaggerState = { value: string[]; over: boolean }

type TaggerOptions = {
  onValueChange?: (
    value: string[],
    details: ChangeDetails<"drag" | "item-press">
  ) => void
}

const tagger = definePrimitive({
  name: "tagger",
  options: { onValueChange: "callback" },
  state: (_options: TaggerOptions): TaggerState => ({ value: [], over: false }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const add = (
      tag: string,
      details: { reason: "drag" | "item-press"; event?: Event }
    ) =>
      !store.get().value.includes(tag) &&
      change("value", [...store.get().value, tag], details)
    let stop: (() => void) | undefined
    context.onDestroy(() => stop?.())
    return {
      pointerdown(event: PointerEvent, el: HTMLElement, tag: string) {
        if (event.button !== 0) {
          return
        }
        const note = context.element("note")
        let preview: ReturnType<typeof bindDragPreview> | undefined
        const isOver = (x: number, y: number) => {
          const box = note?.getBoundingClientRect()
          return (
            !!box &&
            x >= box.left &&
            x <= box.right &&
            y >= box.top &&
            y <= box.bottom
          )
        }
        stop?.()
        stop = bindDrag(el, event, {
          threshold: dragThreshold,
          cancelOnEscape: true,
          onStart: () => {
            preview = bindDragPreview(el, {
              x: event.clientX,
              y: event.clientY,
            })
          },
          onMove: ({ x, y }) => {
            const over = isOver(x, y)
            preview?.move(x, y)
            preview?.el.toggleAttribute("data-over", over)
            store.set({ over })
          },
          onEnd: (end, canceled) => {
            const { over } = store.get()
            preview?.remove()
            stop = undefined
            store.set({ over: false })
            if (preview && over && !canceled) {
              add(tag, { reason: "drag", event: end })
            }
          },
        })
      },
      keydown(event: KeyboardEvent, tag: string) {
        if (event.key !== "Enter") {
          return
        }
        event.preventDefault()
        add(tag, { reason: "item-press", event })
      },
    }
  },
  slots: (slot) => ({
    tag: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({
        type: "button",
        style: "touch-action:none;user-select:none",
      }),
      on: {
        pointerdown: (event, { el, api, key }) =>
          api.pointerdown(event, el!, key),
        keydown: (event, { api, key }) => api.keydown(event, key),
      },
    }),
    note: slot<{}, { tags: string[] }>({
      state: (state) => ({ tags: state.value }),
      attrs: (state) => ({ "data-over": state.over ? "" : undefined }),
    }),
  }),
})

const parts = createParts(tagger, { tag: "button", note: "div" })

const Tagger = parts.Root

const TaggerTag = parts.Tag

const TaggerNote = parts.Note

function Example() {
  return (
    <Tagger>
      <div data-slot="stack">
        <div data-slot="row">
          {["Urgent", "Design", "Later"].map((tag) => (
            <TaggerTag data-size="sm" key={tag} value={tag}>
              {tag}
            </TaggerTag>
          ))}
        </div>
        <TaggerNote aria-label="Note">
          {({ tags }) => (
            <>
              <span data-slot="label">Launch plan</span>
              <div data-slot="row">
                {tags.length ? (
                  tags.map((tag) => (
                    <span key={tag} data-slot="badge">
                      {tag}
                    </span>
                  ))
                ) : (
                  <span data-slot="hint">Drag a tag here.</span>
                )}
              </div>
            </>
          )}
        </TaggerNote>
      </div>
    </Tagger>
  )
}

export { Example }
把标签拖到便签上,当副本高亮时松开。你也可以聚焦一个标签并按 Enter 添加它。

副本在创建时保留元素的外观;它不会渲染之后框架的更新。它带有 data-drag-preview,移除了 ID,并且对辅助技术和指针命中隐藏。它在可用时使用顶层,否则回退到固定定位。

拖动时滚动

自定义拖动可以用 createAutoScroll 在指针附近滚动。为这次拖动创建它,每次移动时调用 update(x, y),并在每次退出时调用 stop():

const scroll = createAutoScroll({
  edge: 48,
  speed: 16,
  ignore: () => preview.el,
  onScroll: findChapter,
})
控制台
import * as React from "react"
import {
  bindDrag,
  bindDragPreview,
  createAutoScroll,
  createChange,
  definePrimitive,
  dragThreshold,
  type ChangeDetails,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { BookmarkIcon } from "lucide-react"
import { useLog } from "./log"

type BookState = { bookmark: string | null; over: string | null }

type BookOptions = {
  onBookmarkChange?: (
    bookmark: string | null,
    details: ChangeDetails<"drag">
  ) => void
}

const book = definePrimitive({
  name: "book",
  options: { onBookmarkChange: "callback" },
  state: (_options: BookOptions): BookState => ({ bookmark: null, over: null }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    let stop: (() => void) | undefined
    context.onDestroy(() => stop?.())
    return {
      pointerdown(event: PointerEvent, el: HTMLElement) {
        if (event.button !== 0) {
          return
        }
        let preview: ReturnType<typeof bindDragPreview> | undefined
        let pointer = { x: event.clientX, y: event.clientY }
        const findChapter = () => {
          const hit = document
            .elementFromPoint(pointer.x, pointer.y)
            ?.closest<HTMLElement>("[data-chapter]")
          store.set({ over: hit?.dataset.chapter ?? null })
        }
        const scroll = createAutoScroll({
          edge: 48,
          speed: 16,
          ignore: () => preview?.el,
          onScroll: findChapter,
        })
        stop?.()
        stop = bindDrag(el, event, {
          threshold: dragThreshold,
          cancelOnEscape: true,
          onStart: () => {
            preview = bindDragPreview(el, pointer)
          },
          onMove: ({ x, y }) => {
            pointer = { x, y }
            preview?.move(x, y)
            scroll.update(x, y)
            findChapter()
          },
          onEnd: (end, canceled) => {
            const { over } = store.get()
            scroll.stop()
            preview?.remove()
            stop = undefined
            store.set({ over: null })
            if (preview && over && !canceled) {
              change("bookmark", over, { reason: "drag", event: end })
            }
          },
        })
      },
    }
  },
  slots: (slot) => ({
    bookmark: slot({
      attrs: () => ({
        type: "button",
        style: "touch-action:none;user-select:none",
      }),
      on: { pointerdown: (event, { el, api }) => api.pointerdown(event, el!) },
    }),
    chapters: slot({ attrs: () => ({ role: "list" }) }),
    chapter: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => ({
        role: "listitem",
        "data-chapter": part.key,
        "data-over": state.over === part.key ? "" : undefined,
        "data-bookmarked": state.bookmark === part.key ? "" : undefined,
      }),
    }),
  }),
})

const parts = createParts(book, {
  bookmark: "button",
  chapters: "div",
  chapter: "div",
})

const Book = parts.Root

const BookBookmark = parts.Bookmark

const BookChapters = parts.Chapters

const BookChapter = parts.Chapter

const chapters = Array.from(
  { length: 24 },
  (_, index) => `Chapter ${index + 1}`
)

function Example() {
  const log = useLog()
  return (
    <Book
      onBookmarkChange={(bookmark) =>
        log(bookmark ? `Bookmarked ${bookmark}` : "Removed the bookmark")
      }
    >
      <div data-slot="stack">
        <BookBookmark data-size="sm">
          <BookmarkIcon aria-hidden="true" />
          Bookmark
        </BookBookmark>
        <BookChapters aria-label="Chapters">
          {chapters.map((chapter) => (
            <BookChapter key={chapter} value={chapter}>
              {chapter}
            </BookChapter>
          ))}
        </BookChapters>
      </div>
    </Book>
  )
}

export { Example }
把书签拖到章节列表的顶部或底部边缘附近。保持在那里继续按住即可滚动,然后在某一章上松开。

edge 是开始滚动的距离,单位为像素;speed 是每帧的最大像素数。辅助函数会找到指针下方最近的滚动容器,并以页面的纵向滚动作为回退。ignore 会跳过某个元素,比如被拖动的副本。onScroll 让你在内容从静止的指针下方移过后重新找到目标。

保持焦点与草稿

排序行为已经会保留焦点,并在受控值赶上之前保持已提交的草稿可见。如果你要构建自己的拖动,在移动已聚焦的元素之后使用 keepFocus,在把草稿交给它的所有者时使用 settleDraft。

API 参考

选项表格会链接回介绍它们的示例。

onMove(sample: PointerSample) => void
At most once per frame, with the latest position and the movement since the last call.
示例: Follow a Pointer
onEnd(event: PointerEvent, canceled: boolean) => void
The pointer lifted, or the browser took it over, like for a scroll. A move still pending runs first, so the last position is never lost.
示例: Follow a Pointer
threshold?number
How far, in CSS pixels, the pointer moves along either axis before moves are reported, so a press that barely moves stays a click. Defaults to 0.
示例: Follow a Pointer
onStart?((event: PointerEvent) => boolean | void)
Runs once, on the first move past threshold, before its onMove. Return false to stop following the pointer, like when a drag can't start.
示例: Dragging Without Limits
lock?boolean
Locks the pointer once it has moved past dragThreshold, so it can travel without limit, like a scrub, while a plain click never hides the cursor. Falls back to capture where the browser refuses, as Safari does.
示例: Dragging Without Limits
cancelOnEscape?boolean
Ends the gesture as canceled when Escape is pressed once it has started, and keeps that press from reaching anything else, like a popup around it. onEnd gets the last pointer event. Defaults to false.
示例: Follow a Pointer
slotstring
The slot whose parts are the items. Each joins in the slot's bind with reorder.bind(el, part).
示例: Sort a List
keykeyof State & string
The state key that holds the order, a string[] of item keys.
示例: Sort a List
draftkeyof State & string
The state key that holds the ReorderDraft while an item moves. Start it at null.
示例: Sort a List
set(value: string[], details: { reason: ReorderReason; event?: Event; }) => boolean
Asks for a new order 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).
示例: Sort a List
orientation?(() => ReorderOrientation)
Whether the items run top to bottom, along a line, or wrap in rows like a grid of photos, which picks the arrows and how a drag finds its place. Defaults to "vertical".
示例: Grids
group?((key: string) => string[])
The keys that move with the one picked up, like the selection when it holds it. Defaults to that one key.
示例: Several at Once
preview?boolean
Drags a copy of the item above the page while the item itself shows where it would drop, so a list that scrolls neither clips it nor grows under it. A drag near a scroller's edge scrolls it. Defaults to false.
示例: A Copy While Dragging
createAutoScroll?false | Omit<AutoScrollOptions, "ignore" | "onScroll">
How a drag with preview near a scroller's edge scrolls it, or false not to.
示例: A Copy While Dragging
disabled?((item: { key: string; props: Props; }) => boolean)
Whether an item can't be picked up. It still moves aside for others.
示例: What's Read Out
label?((key: string) => string | undefined)
The name screen readers hear for an item. Return undefined for the default, its text.
示例: What's Read Out
message?((message: ReorderMessage) => string)
The text screen readers hear for each step. Defaults to English.
示例: What's Read Out
keykeyof State & string
The state key that holds the rows, a TreeReorderRow[] in reading order.
示例: Sort and Nest
draftkeyof State & string
The state key that holds the TreeReorderDraft while an item moves. Start it at null.
示例: Sort and Nest
set(value: TreeReorderRow[], details: { reason: TreeReorderReason; event?: Event; key: string; } & TreePlace) => boolean
Asks for the new rows and returns whether they went through. Pass the primitive's change: set: (value, details) => change("rows", value, details). details says which item moved and where to.
示例: Sort and Nest
indent?(() => number)
How far a drag goes sideways for each level, in CSS pixels. Defaults to 24.
示例: Sort and Nest
maxDepth?(() => number)
The deepest an item and the rows under it can go, from 0. Defaults to no limit.
示例: Limits and Moving from Code
disabled?((key: string) => boolean)
Whether an item can't be picked up. It still moves aside for others.
示例: Limits and Moving from Code
label?((key: string) => string | undefined)
The name screen readers hear for an item. Defaults to its text.
示例: Limits and Moving from Code
message?((message: TreeReorderMessage) => string)
The text screen readers hear for each step. Defaults to English.
示例: Limits and Moving from Code
preview?boolean
Drags a copy of the row above the page while the rows show where it would drop. Defaults to false.
示例: Sort and Nest
createAutoScroll?false | Omit<AutoScrollOptions, "ignore" | "onScroll">
How a drag with preview near a scroller's edge scrolls it, or false not to.
示例: Sort and Nest
keykeyof State & string
The state key that holds every list, a TransferLists.
示例: Two Lists
draftkeyof State & string
The state key that holds the TransferDraft while an item moves. Start it at null.
示例: Two Lists
set(value: TransferLists, details: { reason: TransferReason; event?: Event; key: string; from: string; to: string; index: number; }) => boolean
Asks for the new lists and returns whether they went through. Pass the primitive's change: set: (value, details) => change("lists", value, details). details says what moved, from where to where.
示例: Two Lists
order?(() => string[])
The lists in the order Left and Right go through them. Defaults to the order of the value's keys.
示例: A Board with Rules
accepts?((key: string, list: string) => boolean)
Whether a list takes an item, like a column at its limit. Lists that don't are skipped.
示例: A Board with Rules
disabled?((key: string) => boolean)
Whether an item can't be picked up.
示例: A Board with Rules
label?((key: string) => string | undefined)
The name screen readers hear for an item. Defaults to its text.
示例: A Board with Rules
listLabel?((list: string) => string | undefined)
The name screen readers hear for a list. Defaults to its key.
示例: A Board with Rules
message?((message: TransferMessage) => string)
The text screen readers hear for each step. Defaults to English.
示例: A Board with Rules
createAutoScroll?false | Omit<AutoScrollOptions, "ignore" | "onScroll">
How a drag near a scroller's edge scrolls it, or false not to.
示例: A Board with Rules
edge?number
How far in from an edge scrolling starts, in pixels.
示例: Scrolling While Dragging
speed?number
The fastest it scrolls, in pixels per frame, with the pointer at the edge.
示例: Scrolling While Dragging
onScroll?(() => void)
Runs after each frame that scrolled, so a drag can find its target again under a pointer that didn't move.
示例: Scrolling While Dragging
ignore?(() => Element | null | undefined)
The element being dragged, which sits under the pointer, so the scrollers under it are found instead of its own.
示例: Scrolling While Dragging