移动和调整对象的大小,显示滑动操作,按压并按住,选取点,绘制范围,并预览选项。

createMove 移动对象,createResize 改变它们的边界,createSwipeActions 露出行背后的操作,bindHold 响应持续按住的按压,bindRepeat 在按钮被按住期间持续步进。createArea 选取二维值,createSpans 编辑轨道上的范围,createPreview 让人在选定之前试用一个值。

从 @ui-sdk/core 导入这些辅助函数。当辅助函数需要 set 回调时,把它接到你的变更上。要把条目排序,见拖放。

在二维中移动

放置任意对象

把位置保存在 Record<string, MovePoint> 里,并另起一个 MoveDraft | null 字段,初始值为 null。在 api 里把它们接到 createMove:

const change = createChange(context)
const move = createMove(context, {
  key: "positions",
  draft: "moving",
  set: (value, details) => change("positions", value, details),
  step: () => 4,
  bounds: () => ({ minX: 0, minY: 0, maxX: 264, maxY: 144 }),
})

从 api 返回 move。定位槽位使用已提交的坐标作为基础位置。把 moving 加到原语的 live 字段里,并让实时槽位绑定写入拖动偏移:

attrs: (state, { key }) => ({
  style: css({
    position: "absolute",
    left: `${state.positions[key].x}px`,
    top: `${state.positions[key].y}px`,
    "touch-action": "none",
  }),
}),
live: live((state, { api, key }) => ({
  "data-dragging": api.move.dragging(state, key) ? "" : undefined,
  style: api.move.style(state, key),
})),
on: {
  keydown: (event, { api, key }) => api.move.keydown(event, key),
  pointerdown: (event, { el, api, key }) => api.move.pointerdown(event, key, el!),
},

在一个已定位的容器里,把这个槽位渲染成可获得焦点、带有无障碍名称的元素。实时绑定会更新 translate、--move-x 和 --move-y,而不必为每次指针移动触发框架渲染。

控制台
import * as React from "react"
import {
  createChange,
  createMove,
  createRovingFocus,
  css,
  definePrimitive,
  live,
  spatialMove,
  type ChangeDetails,
  type MoveDraft,
  type MovePoint,
  type MoveReason,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

const emoji: Record<string, string> = {
  Cactus: "🌵",
  Lemon: "🍋",
  Rocket: "🚀",
}

type StickersState = {
  positions: Record<string, MovePoint>
  focused: string | null
  moving: MoveDraft | null
}

type StickersOptions = {
  defaultPositions: Record<string, MovePoint>
  onPositionsChange?: (
    positions: Record<string, MovePoint>,
    details: ChangeDetails<MoveReason>
  ) => void
}

const stickers = definePrimitive({
  name: "stickers",
  options: { defaultPositions: "value", onPositionsChange: "callback" },
  state: (options: StickersOptions): StickersState => ({
    positions: options.defaultPositions,
    focused: null,
    moving: null,
  }),
  live: ["moving"],
  api: (context) => {
    const change = createChange(context)
    return {
      roving: createRovingFocus<StickersState, { value: string }>(context, {
        slot: "sticker",
        key: "focused",
        move: spatialMove(),
      }),
      move: createMove<StickersState>(context, {
        key: "positions",
        draft: "moving",
        set: (value, details) => change("positions", value, details),
        step: () => 4,
        bounds: () => ({ minX: 0, minY: 0, maxX: 216, maxY: 120 }),
      }),
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({ role: "group", style: "position:relative" }),
    }),
    sticker: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => {
        const at = state.positions[part.key] ?? { x: 0, y: 0 }
        return {
          tabindex: part.api.roving.tabIndex(state, part),
          style: css({
            position: "absolute",
            left: `${at.x}px`,
            top: `${at.y}px`,
            "touch-action": "none",
          }),
        }
      },
      live: live<StickersState, any, { value: string }>(
        (state, { api, key }) => ({
          "data-dragging": api.move.dragging(state, key) ? "" : undefined,
          style: api.move.style(state, key),
        })
      ),
      on: {
        keydown: (event, { el, api, key }) =>
          api.move.keydown(event, key) || api.roving.keydown(event, el!),
        pointerdown: (event, { el, api, key }) =>
          api.move.pointerdown(event, key, el!),
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

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

const Stickers = parts.Root

const StickersItem = parts.Sticker

function Example() {
  const log = useLog()
  const positions = React.useRef<Record<string, MovePoint>>({
    Cactus: { x: 24, y: 28 },
    Lemon: { x: 108, y: 96 },
    Rocket: { x: 192, y: 20 },
  })
  return (
    <Stickers
      aria-label="Stickers"
      defaultPositions={positions.current}
      onPositionsChange={(next, details) => {
        for (const [sticker, at] of Object.entries(next)) {
          const was = positions.current[sticker]
          if (was.x !== at.x || was.y !== at.y) {
            log(`${sticker} moved to ${at.x}, ${at.y} (${details.reason})`)
          }
        }
        positions.current = next
      }}
    >
      {Object.keys(positions.current).map((sticker) => (
        <StickersItem key={sticker} value={sticker} aria-label={sticker}>
          {emoji[sticker]}
        </StickersItem>
      ))}
    </Stickers>
  )
}

export { Example }
拖动一张贴纸,或者聚焦它并按 Alt 加方向键移动 4 像素。加上 Shift 会移动十倍的距离。拖动过程中按 Escape 会把它放回原处。

step 是放下的位置所落到的网格,也是 Alt 加方向键移动的距离;Shift 会按 largeStep 移动,默认是十步。bounds 限制已提交的坐标;拖动预览在松开之前可以超出这些坐标。放下会报告 drag,键盘微移会报告 move-key,屏幕阅读器会听到新的位置。

一次移动多个

加上 group,让选中的一组一起移动:

group: (key) => {
  const { selected } = context.store.get()
  return selected.includes(key) ? selected : [key]
},
step: () => 20,
disabled: (key) => key === "ship",
label: (key) => titles[key],

step 设置网格以及 Alt 加方向键的距离,默认为 1。disabled 阻止指针和键盘移动,并把该条目从正在移动的分组中移除。

控制台
import * as React from "react"
import {
  createChange,
  createMove,
  createRovingFocus,
  css,
  definePrimitive,
  live,
  spatialMove,
  type MoveDraft,
  type MovePoint,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { PinIcon } from "lucide-react"
import { useLog } from "./log"

type BoardState = {
  positions: Record<string, MovePoint>
  selected: string[]
  focused: string | null
  moving: MoveDraft | null
}

const titles: Record<string, string> = {
  plan: "Plan",
  draft: "Draft",
  ship: "Ship",
}

const board = definePrimitive({
  name: "notes",
  options: { defaultPositions: "value", onPositionsChange: "callback" },
  state: (options: {
    defaultPositions: Record<string, MovePoint>
    onPositionsChange?: (positions: Record<string, MovePoint>) => void
  }): BoardState => ({
    positions: options.defaultPositions,
    selected: [],
    focused: null,
    moving: null,
  }),
  live: ["moving"],
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const move = createMove<BoardState>(context, {
      key: "positions",
      draft: "moving",
      set: (value, details) => change("positions", value, details),
      group: (key) =>
        store.get().selected.includes(key) ? store.get().selected : [key],
      step: () => 20,
      bounds: () => ({ minX: 0, minY: 0, maxX: 180, maxY: 140 }),
      disabled: (key) => key === "ship",
      label: (key) => titles[key],
      message: ({ keys, label, at }) =>
        keys.length > 1
          ? `Moved ${keys.length} notes.`
          : `${label} is at ${at.x}, ${at.y}.`,
    })
    return {
      roving: createRovingFocus<BoardState, { value: string }>(context, {
        slot: "note",
        key: "focused",
        move: spatialMove(),
      }),
      move,
      select(key: string, add: boolean) {
        const { selected } = store.get()
        if (add) {
          store.set({
            selected: selected.includes(key)
              ? selected.filter((other) => other !== key)
              : [...selected, key],
          })
        } else if (!selected.includes(key)) {
          store.set({ selected: [key] })
        }
      },
      clear: () => store.set({ selected: [] }),
    }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({
        role: "listbox",
        "aria-multiselectable": "true",
        "aria-roledescription": "board",
        style: "position:relative",
      }),
      on: {
        pointerdown: (event, { el, api }) => event.target === el && api.clear(),
      },
    }),
    note: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, part) => {
        const at = state.positions[part.key]
        return {
          role: "option",
          "aria-selected": String(state.selected.includes(part.key)),
          "aria-disabled": part.key === "ship" ? "true" : undefined,
          tabindex: part.api.roving.tabIndex(state, part),
          style: css({
            position: "absolute",
            left: `${at.x}px`,
            top: `${at.y}px`,
            "touch-action": "none",
          }),
        }
      },
      live: live<BoardState, any, { value: string }>((state, { api, key }) => ({
        "data-dragging": api.move.dragging(state, key) ? "" : undefined,
        style: api.move.style(state, key),
      })),
      on: {
        keydown: (event, { el, api, key }) => {
          if (event.key === " ") {
            event.preventDefault()
            return api.select(key, true)
          }
          api.move.keydown(event, key) || api.roving.keydown(event, el!)
        },
        pointerdown: (event, { el, api, key }) => {
          api.select(key, event.shiftKey)
          api.move.pointerdown(event, key, el!)
        },
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

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

const Board = parts.Root

const BoardNote = parts.Note

function Example() {
  const log = useLog()
  const positions = React.useRef<Record<string, MovePoint>>({
    plan: { x: 20, y: 20 },
    draft: { x: 100, y: 60 },
    ship: { x: 180, y: 120 },
  })
  return (
    <Board
      aria-label="Notes"
      defaultPositions={positions.current}
      onPositionsChange={(next) => {
        for (const [key, at] of Object.entries(next)) {
          const was = positions.current[key]
          if (was.x !== at.x || was.y !== at.y) {
            log(`${titles[key]} moved to ${at.x}, ${at.y}`)
          }
        }
        positions.current = next
      }}
    >
      {Object.entries(titles).map(([key, title]) => (
        <BoardNote key={key} value={key}>
          {title}
          {key === "ship" && <PinIcon aria-hidden="true" />}
        </BoardNote>
      ))}
    </Board>
  )
}

export { Example }
点击便签将其选中,或按住 Shift 点击以加入一个。拖动已选中的便签来移动整个分组。Alt 加方向键会把它微移 20 像素;固定的便签留在原处。

在 pointerdown 时先选择,再调用 move.pointerdown。当按压的便签已经在选择中时,保持选择不变。演示把它和空间焦点结合起来,所以普通方向键可以在便签之间移动。

label 提供播报用的名称。message 可以用移动的 keys、第一个条目的 label 以及它新的 at 点来自定义句子。moveMessage 提供默认文案。

缩放与用代码移动

在缩放过的画布上,告诉行为多少个屏幕像素代表一个单位:

scale: () => context.store.get().zoom,

指针距离会除以这个缩放比例。用代码发起的移动仍然使用画布自己的单位:

move.moveTo("circle", { x: 100, y: 60 })
move.moveBy(["circle"], 10, 0)
控制台
import * as React from "react"
import {
  createChange,
  createMove,
  css,
  definePrimitive,
  live,
  type MoveDraft,
  type MovePoint,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type CanvasState = {
  positions: Record<string, MovePoint>
  zoom: number
  moving: MoveDraft | null
}

type CanvasOptions = {
  zoom?: number
  onPositionsChange?: (positions: Record<string, MovePoint>) => void
}

const canvas = definePrimitive({
  name: "canvas",
  options: { zoom: "number", onPositionsChange: "callback" },
  state: (options: CanvasOptions): CanvasState => ({
    positions: { circle: { x: 40, y: 40 }, square: { x: 168, y: 88 } },
    zoom: options.zoom ?? 1,
    moving: null,
  }),
  sync: (options) => ({ zoom: options.zoom ?? 1 }),
  live: ["moving"],
  api: (context) => {
    const change = createChange(context)
    const move = createMove<CanvasState>(context, {
      key: "positions",
      draft: "moving",
      set: (value, details) => change("positions", value, details),
      scale: () => context.store.get().zoom,
      bounds: () => ({ minX: 0, minY: 0, maxX: 224, maxY: 128 }),
    })
    return {
      move,
      act(action: string) {
        if (action === "center") {
          move.moveTo("circle", { x: 112, y: 64 })
        } else if (action === "nudge") {
          move.moveBy(["circle"], 10, 0)
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "group" }) }),
    surface: slot({
      attrs: (state) => ({
        style: css({
          position: "relative",
          width: "272px",
          height: "176px",
          transform: `scale(${state.zoom})`,
          "transform-origin": "0 0",
        }),
      }),
    }),
    shape: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { key }) => {
        const at = state.positions[key]
        return {
          tabindex: "0",
          style: css({
            position: "absolute",
            left: `${at.x}px`,
            top: `${at.y}px`,
            "touch-action": "none",
          }),
        }
      },
      live: live<CanvasState, any, { value: string }>(
        (state, { api, key }) => ({
          style: api.move.style(state, key),
        })
      ),
      on: {
        keydown: (event, { api, key }) => api.move.keydown(event, key),
        pointerdown: (event, { el, api, key }) =>
          api.move.pointerdown(event, key, el!),
      },
    }),
    action: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
      press: ({ api, key }) => api.act(key),
    }),
  }),
})

const parts = createParts(canvas, {
  root: "div",
  surface: "div",
  shape: "div",
  action: "button",
})

const Canvas = parts.Root

const CanvasSurface = parts.Surface

const CanvasShape = parts.Shape

const CanvasAction = parts.Action

function Example() {
  const log = useLog()
  const [zoom, setZoom] = React.useState(1)
  return (
    <Canvas
      aria-label="Canvas"
      zoom={zoom}
      onPositionsChange={({ circle, square }) =>
        log(
          `Circle at ${circle.x}, ${circle.y} · Square at ${square.x}, ${square.y}`
        )
      }
    >
      <div data-slot="controls">
        {[0.5, 1, 1.5].map((option) => (
          <button
            key={option}
            type="button"
            data-variant="ghost"
            data-size="sm"
            aria-pressed={zoom === option}
            onClick={() => setZoom(option)}
          >
            {option * 100}%
          </button>
        ))}
        <CanvasAction value="center" data-size="sm">
          Center
        </CanvasAction>
        <CanvasAction value="nudge" data-size="sm">
          Nudge
        </CanvasAction>
      </div>
      <div data-slot="move-area">
        <CanvasSurface>
          <CanvasShape value="circle" aria-label="Circle" data-shape="round" />
          <CanvasShape value="square" aria-label="Square" />
        </CanvasSurface>
      </div>
    </Canvas>
  )
}

export { Example }
改变缩放,然后拖动形状。用按钮在不拖动的情况下移动圆形。

两个方法都会报告 imperative 并应用 bounds。它们不会应用拖动的网格,也不会过滤已禁用的键,所以如有需要,在调用它们之前先检查这些应用规则。

调整盒子大小

盒子上的手柄

一个盒子有 { x, y, width, height }。把盒子保存在状态里,另起一个 ResizeDraft | null 字段并初始化为 null,然后在 api 里添加 createResize:

const resize = createResize(context, {
  boxes: (state) => state.boxes,
  draft: "draft",
  set: (value, details) => change("boxes", value, details),
  min: () => ({ width: 60, height: 40 }),
  bounds: () => ({ left: 0, top: 0, right: 320, bottom: 200 }),
  step: () => 4,
})

盒子槽位用 boxStyle 读取已提交的尺寸。把 draft 列进原语的 live 字段,然后通过实时绑定应用 resize.style:

box: slot({
  attrs: (state, { api }) => ({ style: api.resize.boxStyle(state, "frame") }),
  live: live((state, { api }) => ({ style: api.resize.style(state, "frame") })),
  on: {
    pointerdown: (event, { el, api }) => api.resize.pointerdown(event, "frame", "move", el!),
  },
}),

把盒子绝对定位,并给每个手柄自己的 ID。手柄使用罗盘方向名:n、e、s、w、ne、nw、se 和 sw。盒子本身使用 move。

把手柄渲染成按钮,名称例如 “Resize bottom right”。它们的槽位调用 resize.handleAttrs(handle) 来处理光标和触摸行为,调用 resize.pointerdown(event, key, handle, el) 来处理拖动,调用 resize.keydown(event, key, handle) 来处理方向键。

控制台
import * as React from "react"
import {
  createChange,
  createResize,
  definePrimitive,
  live,
  type ChangeDetails,
  type ResizeBox,
  type ResizeDraft,
  type ResizeHandle,
  type ResizeReason,
} from "@ui-sdk/core"
import { usePart, usePrimitive, type PartProps } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type FrameState = {
  boxes: Record<string, ResizeBox>
  draft: ResizeDraft | null
}

type FrameOptions = {
  defaultBox: ResizeBox
  onBoxesChange?: (
    boxes: Record<string, ResizeBox>,
    details: ChangeDetails<ResizeReason>
  ) => void
}

const frame = definePrimitive({
  name: "frame",
  options: { defaultBox: "value", onBoxesChange: "callback" },
  state: (options: FrameOptions): FrameState => ({
    boxes: { frame: options.defaultBox },
    draft: null,
  }),
  live: ["draft"],
  api: (context) => {
    const change = createChange(context)
    return {
      resize: createResize<FrameState>(context, {
        boxes: (state) => state.boxes,
        draft: "draft",
        set: (value, details) => change("boxes", value, details),
        min: () => ({ width: 60, height: 40 }),
        bounds: () => ({ left: 0, top: 0, right: 272, bottom: 176 }),
        step: () => 4,
      }),
    }
  },
  slots: (slot) => ({
    box: slot({
      attrs: (state, { api }) => ({
        style: `${api.resize.boxStyle(state, "frame")};touch-action:none`,
      }),
      live: live<FrameState, any, {}>((state, { api }) => ({
        style: api.resize.style(state, "frame"),
      })),
      on: {
        pointerdown: (event, { el, api }) =>
          api.resize.pointerdown(event, "frame", "move", el!),
      },
    }),
    handle: slot<{ id: string; handle: ResizeHandle }>({
      props: { handle: "string" },
      attrs: (_state, { props, api }) => api.resize.handleAttrs(props.handle),
      on: {
        pointerdown: (event, { el, api, props }) =>
          api.resize.pointerdown(event, "frame", props.handle, el!),
        keydown: (event, { api, props }) =>
          api.resize.keydown(event, "frame", props.handle),
      },
    }),
  }),
})

function Frame({
  defaultBox,
  onBoxesChange,
  ...props
}: FrameOptions & PartProps<"div">) {
  const handle = usePrimitive(frame, { defaultBox, onBoxesChange })
  return usePart(handle, "box", {}, props, "div")
}

function FrameHandle({
  handle,
  ...props
}: { handle: ResizeHandle } & PartProps<"button">) {
  return usePart(
    frame,
    "handle",
    { id: handle, handle },
    { type: "button", ...props },
    "button"
  )
}

const handles: Partial<Record<ResizeHandle, string>> = {
  nw: "top left",
  n: "top",
  ne: "top right",
  e: "right",
  se: "bottom right",
  s: "bottom",
  sw: "bottom left",
  w: "left",
}

function Example() {
  const log = useLog()
  return (
    <div data-slot="resize-stage">
      <Frame
        aria-label="Frame"
        defaultBox={{ x: 68, y: 40, width: 136, height: 96 }}
        onBoxesChange={({ frame }, details) =>
          log(
            `${frame.width} × ${frame.height} at ${frame.x}, ${frame.y} (${details.reason})`
          )
        }
      >
        {(Object.keys(handles) as ResizeHandle[]).map((name) => (
          <FrameHandle
            key={name}
            handle={name}
            aria-label={`Resize ${handles[name]}`}
          />
        ))}
      </Frame>
    </div>
  )
}

export { Example }
拖动手柄调整框架大小,或拖动框架移动它。聚焦一个手柄并使用方向键;加上 Shift 可以走更大的步长。Escape 取消拖动。

handleAttrs 不提供标签,也不让元素可获得焦点。按钮负责这些。方向键按 step 移动一条边,也就是放下的盒子所落到的网格,或者加上 Shift 时按 largeStep 移动,默认十步;边上的手柄沿自己的轴响应。变更会报告 drag 或 resize-key。

保持形状

在调整大小的选项里设置宽高比和尺寸限制:

aspect: () => (context.store.get().locked ? 16 / 9 : undefined),
min: () => ({ width: 96, height: 54 }),
max: () => ({ width: 256, height: 144 }),
largeStep: () => 16,
控制台
import * as React from "react"
import {
  createChange,
  createResize,
  definePrimitive,
  live,
  type ResizeBox,
  type ResizeDraft,
  type ResizeHandle,
} from "@ui-sdk/core"
import { usePart, usePrimitive, type PartProps } from "@ui-sdk/react/primitive"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/react/checkbox"
import { CheckIcon, PlayIcon } from "lucide-react"
import { useLog } from "./log"

type VideoState = {
  boxes: Record<string, ResizeBox>
  locked: boolean
  draft: ResizeDraft | null
}

type VideoOptions = {
  locked?: boolean
  onBoxesChange?: (boxes: Record<string, ResizeBox>) => void
}

const video = definePrimitive({
  name: "video",
  options: { locked: "boolean", onBoxesChange: "callback" },
  state: (options: VideoOptions): VideoState => ({
    boxes: { video: { x: 56, y: 43, width: 160, height: 90 } },
    locked: options.locked ?? true,
    draft: null,
  }),
  sync: (options) => ({ locked: options.locked ?? true }),
  live: ["draft"],
  api: (context) => {
    const change = createChange(context)
    return {
      resize: createResize<VideoState>(context, {
        boxes: (state) => state.boxes,
        draft: "draft",
        set: (value, details) => change("boxes", value, details),
        aspect: () => (context.store.get().locked ? 16 / 9 : undefined),
        min: () => ({ width: 96, height: 54 }),
        max: () => ({ width: 256, height: 144 }),
        bounds: () => ({ left: 0, top: 0, right: 272, bottom: 176 }),
        largeStep: () => 16,
      }),
    }
  },
  slots: (slot) => ({
    box: slot({
      attrs: (state, { api }) => ({
        style: `${api.resize.boxStyle(state, "video")};touch-action:none`,
      }),
      live: live<VideoState, any, {}>((state, { api }) => ({
        style: api.resize.style(state, "video"),
      })),
      on: {
        pointerdown: (event, { el, api }) =>
          api.resize.pointerdown(event, "video", "move", el!),
      },
    }),
    handle: slot<{ id: string; handle: ResizeHandle }>({
      props: { handle: "string" },
      attrs: (_state, { props, api }) => api.resize.handleAttrs(props.handle),
      on: {
        pointerdown: (event, { el, api, props }) =>
          api.resize.pointerdown(event, "video", props.handle, el!),
        keydown: (event, { api, props }) =>
          api.resize.keydown(event, "video", props.handle),
      },
    }),
  }),
})

function Video({
  locked,
  onBoxesChange,
  ...props
}: VideoOptions & PartProps<"div">) {
  const handle = usePrimitive(video, { locked, onBoxesChange })
  return usePart(handle, "box", {}, props, "div")
}

function VideoHandle({
  handle,
  ...props
}: { handle: ResizeHandle } & PartProps<"button">) {
  return usePart(
    video,
    "handle",
    { id: handle, handle },
    { type: "button", ...props },
    "button"
  )
}

const places: Partial<Record<ResizeHandle, string>> = {
  nw: "top left",
  ne: "top right",
  e: "right",
  se: "bottom right",
  sw: "bottom left",
  w: "left",
}

function Example() {
  const log = useLog()
  const [locked, setLocked] = React.useState(true)
  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>
          Keep 16:9
        </label>
      </div>
      <div data-slot="resize-stage">
        <Video
          aria-label="Video"
          locked={locked}
          onBoxesChange={({ video }) =>
            log(`${Math.round(video.width)} × ${Math.round(video.height)}`)
          }
        >
          <PlayIcon aria-hidden="true" />
          {(Object.keys(places) as ResizeHandle[]).map((name) => (
            <VideoHandle
              key={name}
              handle={name}
              aria-label={`Resize ${places[name]}`}
            />
          ))}
        </Video>
      </div>
    </div>
  )
}

export { Example }
在勾选 16:9 时调整视频框架的大小。取消勾选即可自由调整,或在拖动角时按住 Shift,以保持框架起始时的比例。

aspect 是宽度除以高度。角会跟随移动得更远的那条边;边上的手柄围绕中心调整另一个维度。min 和 max 限制尺寸,而 bounds 描述周围的区域。这里 largeStep 让 Shift 加方向键移动 16 像素,而普通方向键仍然移动 1。

多个盒子,以及用代码操作

同一个行为可以管理多个盒子。为缩放过的桌面加上 scale,为用户不应移动或调整大小的盒子加上 disabled:

scale: () => 0.75,
disabled: (key) => key === "notes",
label: (key) => titles[key],
import * as React from "react"
import {
  createChange,
  createResize,
  css,
  definePrimitive,
  type ResizeBox,
  type ResizeDraft,
} from "@ui-sdk/core"
import { createParts, usePart, type PartProps } from "@ui-sdk/react/primitive"
import { LockIcon } from "lucide-react"

type DesktopState = {
  windows: Record<string, ResizeBox>
  draft: ResizeDraft | null
}

const titles: Record<string, string> = { mail: "Mail", notes: "Notes" }

const desktop = definePrimitive({
  name: "desktop",
  state: (): DesktopState => ({
    windows: {
      mail: { x: 20, y: 20, width: 160, height: 100 },
      notes: { x: 200, y: 100, width: 140, height: 100 },
    },
    draft: null,
  }),
  api: (context) => {
    const change = createChange(context)
    const resize = createResize<DesktopState>(context, {
      boxes: (state) => state.windows,
      draft: "draft",
      set: (value, details) => change("windows", value, details),
      min: () => ({ width: 100, height: 60 }),
      bounds: () => ({ left: 0, top: 0, right: 360, bottom: 220 }),
      scale: () => 0.75,
      disabled: (key) => key === "notes",
      label: (key) => titles[key],
      message: ({ label, handle, box }) =>
        handle === "move"
          ? `${label} moved.`
          : `${label} is ${box.width} by ${box.height}.`,
    })
    return {
      resize,
      act(action: string) {
        if (action === "maximize") {
          resize.resizeTo("mail", { x: 0, y: 0, width: 360, height: 220 })
        } else if (action === "grow") {
          resize.resizeBy("mail", "se", 40, 40)
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { mail: ResizeBox | null }>({
      state: (state, { api }) => ({ mail: api.resize.box(state, "mail") }),
    }),
    screen: slot({
      attrs: () => ({
        style: css({
          position: "relative",
          width: "360px",
          height: "220px",
          transform: "scale(0.75)",
          "transform-origin": "0 0",
        }),
      }),
    }),
    window: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { api, key }) => ({
        role: "group",
        "aria-label": titles[key],
        "aria-disabled": key === "notes" ? "true" : undefined,
        "data-resizing": api.resize.dragging(state, key),
        style: `${api.resize.boxStyle(state, key)};${api.resize.style(state, key) ?? ""};touch-action:none`,
      }),
      on: {
        pointerdown: (event, { el, api, key }) =>
          api.resize.pointerdown(event, key, "move", el!),
      },
    }),
    corner: slot<{ id: string; box: string }>({
      props: { box: "string" },
      attrs: (_state, { api }) => api.resize.handleAttrs("se"),
      on: {
        pointerdown: (event, { el, api, props }) =>
          api.resize.pointerdown(event, props.box, "se", el!),
      },
    }),
    action: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
      press: ({ api, key }) => api.act(key),
    }),
  }),
})

const parts = createParts(desktop, {
  root: "div",
  screen: "div",
  window: "div",
  action: "button",
})

const Desktop = parts.Root

const DesktopScreen = parts.Screen

const DesktopWindow = parts.Window

function DesktopCorner({ box, ...props }: { box: string } & PartProps<"div">) {
  return usePart(desktop, "corner", { id: `${box}-se`, box }, props, "div")
}

const DesktopAction = parts.Action

function Example() {
  return (
    <Desktop>
      {({ mail }) => (
        <>
          <div data-slot="controls">
            <DesktopAction data-size="sm" value="maximize">
              Maximize
            </DesktopAction>
            <DesktopAction data-size="sm" value="grow">
              Grow
            </DesktopAction>
          </div>
          <div data-slot="resize-stage">
            <DesktopScreen>
              {Object.entries(titles).map(([key, title]) => (
                <DesktopWindow key={key} value={key}>
                  <div data-slot="resize-titlebar">
                    {title}
                    {key === "mail" ? (
                      <span data-slot="hint">
                        {Math.round(mail!.width)} × {Math.round(mail!.height)}
                      </span>
                    ) : (
                      <LockIcon aria-hidden="true" />
                    )}
                  </div>
                  <DesktopCorner box={key} />
                </DesktopWindow>
              ))}
            </DesktopScreen>
          </div>
        </>
      )}
    </Desktop>
  )
}

export { Example }
在缩放过的桌面上移动或调整 Mail 的大小。Notes 已锁定。Maximize 会设置 Mail 的盒子,Grow 会从右下角把它放大。

有两种用代码更改盒子的方式:

resize.resizeTo("mail", { x: 0, y: 0, width: 400, height: 240 })
resize.resizeBy("mail", "se", 40, 40)

resizeBy 会应用手柄的尺寸限制和禁用规则。resizeTo 直接写入提供的盒子,所以尺寸和权限由你自己校验。两者都会报告 imperative。

要渲染实时尺寸标签,就把草稿排除在 live 之外,并读取 resize.box(state, key)。它在拖动过程中返回草稿盒子,其他时候返回已提交的盒子。dragging(state, key) 返回活动的手柄。label 和 message 自定义播报,默认由 resizeMessage 提供。

把行滑到一旁

行背后的操作

createSwipeActions 一次只保持一行打开。把 open 初始化为 SwipeOpen | null,把 swiping 初始化为 SwipeDraft | null,两者都是 null:

const swipe = createSwipeActions(context, {
  key: "open",
  draft: "swiping",
})

每一行都有会移动的内容,覆盖在 start 或 end 一侧的操作之上。用 bindRow(el, key) 绑定行,用 bindActions(el, rowKey, side) 绑定每个操作组。从槽位返回这些清理函数。

把 swiping 放进 live。内容槽位把 transform 和实时属性结合起来:

attrs: () => ({ style: css({ transform: "translateX(var(--swipe-x, 0px))" }) }),
live: live((state, { api, key }) => api.swipe.contentAttrs(state, key)),

在行上调用 swipe.pointerdown(event, key, el) 和 swipe.keydown(event, key)。给它 position: relative、overflow: hidden 和 touch-action: pan-y。操作槽位用 swipe.actionsAttrs(state, rowKey, side) 让隐藏的操作变为不可交互(inert)。

import * as React from "react"
import {
  createRovingFocus,
  createSwipeActions,
  css,
  definePrimitive,
  live,
  selects,
  type SwipeDraft,
  type SwipeOpen,
  type SwipeSide,
} from "@ui-sdk/core"
import { createParts, usePart, type PartProps } from "@ui-sdk/react/primitive"

type RowsState = {
  open: SwipeOpen | null
  swiping: SwipeDraft | null
  focused: string | null
}

const rows = definePrimitive({
  name: "rows",
  state: (): RowsState => ({ open: null, swiping: null, focused: null }),
  live: ["swiping"],
  api: (context) => ({
    roving: createRovingFocus<RowsState, { value: string }>(context, {
      slot: "row",
      key: "focused",
    }),
    swipe: createSwipeActions<RowsState>(context, {
      key: "open",
      draft: "swiping",
    }),
  }),
  slots: (slot) => ({
    root: slot({ attrs: () => ({ role: "list" }) }),
    row: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        role: "listitem",
        tabindex: part.api.roving.tabIndex(state, part),
        "data-open": state.open?.key === part.key ? state.open.side : undefined,
        style: css({
          position: "relative",
          overflow: "hidden",
          "touch-action": "pan-y",
        }),
      }),
      on: {
        pointerdown: (event, { el, api, key }) =>
          api.swipe.pointerdown(event, key, el!),
        keydown: (event, { el, api, key }) =>
          api.swipe.keydown(event, key) ||
          (event.target === el && api.roving.keydown(event, el!)),
      },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.swipe.bindRow(el, part.key),
        ]
        return () => cleanups.forEach((cleanup) => cleanup())
      },
    }),
    content: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({
        style: css({
          position: "relative",
          "z-index": "1",
          transform: "translateX(var(--swipe-x, 0px))",
        }),
      }),
      live: live<RowsState, any, { value: string }>((state, { api, key }) =>
        api.swipe.contentAttrs(state, key)
      ),
    }),
    actions: slot<{ id: string; row: string; side: SwipeSide }>({
      props: { row: "string", side: "string" },
      attrs: (state, { props, api }) => ({
        ...api.swipe.actionsAttrs(state, props.row, props.side),
        style: css({
          position: "absolute",
          top: "0",
          bottom: "0",
          [props.side === "start" ? "inset-inline-start" : "inset-inline-end"]:
            "0",
          display: "flex",
        }),
      }),
      bind: (el, { props, api }) =>
        api.swipe.bindActions(el, props.row, props.side),
    }),
  }),
})

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

const Rows = parts.Root

const RowsItem = parts.Row

const RowsContent = parts.Content

function RowsActions({
  row,
  side,
  ...props
}: { row: string; side: SwipeSide } & PartProps<"div">) {
  return usePart(
    rows,
    "actions",
    { id: `${row}-${side}`, row, side },
    props,
    "div"
  )
}

function Example() {
  const [items, setItems] = React.useState([
    "Team lunch on Friday",
    "Your invoice is ready",
    "New comment on the docs",
  ])
  return (
    <Rows aria-label="Messages">
      {items.map((item) => (
        <RowsItem key={item} value={item}>
          <RowsContent value={item}>{item}</RowsContent>
          <RowsActions row={item} side="end">
            <button
              type="button"
              tabIndex={-1}
              data-variant="destructive"
              onClick={() =>
                setItems((current) => current.filter((other) => other !== item))
              }
            >
              Delete
            </button>
          </RowsActions>
        </RowsItem>
      ))}
    </Rows>
  )
}

export { Example }
向左滑动一条消息,露出 Delete。使用键盘时,聚焦一行并按 Left 到达它的操作,然后按 Escape 关闭。

滑动会等待横向移动,这样纵向滚动仍然可用。超过操作宽度的一半再松开,就会保持打开;快速轻扫可以更早地打开或关闭。操作的宽度来自你的布局。

start 操作会在朝行的末端滑动时出现,在英文中是从左到右。在从右到左的布局中方向相反。contentAttrs 提供 --swipe-x、data-swipe 和 data-swiping,因此你可以在指针移动时禁用过渡。

完整滑动

加上 onFullSwipe,在用户滑动得足够远时执行操作。回调会完成实际工作;辅助函数不会替你点击操作按钮:

onFullSwipe: (key, side) => {
  context.options().onAction?.(key, side)
  return true
},
fullSwipe: () => 0.5,
disabled: (key) => key === context.options().pinned,

返回操作是否被接受。fullSwipe 是行宽的一个比例,默认 0.6。当松开就会触发操作时,内容会获得 data-full。

控制台
import * as React from "react"
import {
  createRovingFocus,
  createSwipeActions,
  css,
  definePrimitive,
  live,
  selects,
  type SwipeDraft,
  type SwipeOpen,
  type SwipeSide,
} from "@ui-sdk/core"
import { createParts, usePart, type PartProps } from "@ui-sdk/react/primitive"
import { PinIcon } from "lucide-react"
import { useLog } from "./log"

type MailboxState = {
  open: SwipeOpen | null
  swiping: SwipeDraft | null
  focused: string | null
}

type MailboxOptions = {
  pinned?: string
  first?: string
  onAction?: (key: string, side: SwipeSide) => void
}

const mailbox = definePrimitive({
  name: "mailbox",
  options: { pinned: "string", first: "string", onAction: "callback" },
  state: (_options: MailboxOptions): MailboxState => ({
    open: null,
    swiping: null,
    focused: null,
  }),
  live: ["swiping"],
  api: (context) => {
    const swipe = createSwipeActions<MailboxState>(context, {
      key: "open",
      draft: "swiping",
      onFullSwipe: (key, side) => {
        context.options().onAction?.(key, side)
        return true
      },
      fullSwipe: () => 0.5,
      disabled: (key) => key === context.options().pinned,
    })
    return {
      roving: createRovingFocus<MailboxState, { value: string }>(context, {
        slot: "row",
        key: "focused",
      }),
      swipe,
      act(action: string) {
        const first = context.options().first
        if (action === "peek" && first) {
          swipe.show(first, "end")
        } else if (action === "close") {
          swipe.close()
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot({}),
    list: slot({ attrs: () => ({ role: "list" }) }),
    row: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        role: "listitem",
        tabindex: part.api.roving.tabIndex(state, part),
        "data-open": state.open?.key === part.key ? state.open.side : undefined,
        style: css({
          position: "relative",
          overflow: "hidden",
          "touch-action": "pan-y",
        }),
      }),
      on: {
        pointerdown: (event, { el, api, key }) =>
          api.swipe.pointerdown(event, key, el!),
        keydown: (event, { el, api, key }) =>
          api.swipe.keydown(event, key) ||
          (event.target === el && api.roving.keydown(event, el!)),
      },
      bind: (el, part) => {
        const cleanups = [
          part.api.roving.bind(el, part),
          part.api.swipe.bindRow(el, part.key),
        ]
        return () => cleanups.forEach((cleanup) => cleanup())
      },
    }),
    content: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({
        style: css({
          position: "relative",
          "z-index": "1",
          transform: "translateX(var(--swipe-x, 0px))",
        }),
      }),
      live: live<MailboxState, any, { value: string }>((state, { api, key }) =>
        api.swipe.contentAttrs(state, key)
      ),
    }),
    actions: slot<{ id: string; row: string; side: SwipeSide }>({
      props: { row: "string", side: "string" },
      attrs: (state, { props, api }) => ({
        ...api.swipe.actionsAttrs(state, props.row, props.side),
        style: css({
          position: "absolute",
          top: "0",
          bottom: "0",
          [props.side === "start" ? "inset-inline-start" : "inset-inline-end"]:
            "0",
          display: "flex",
        }),
      }),
      bind: (el, { props, api }) =>
        api.swipe.bindActions(el, props.row, props.side),
    }),
    action: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
      press: ({ api, key }) => api.act(key),
    }),
  }),
})

const parts = createParts(mailbox, {
  root: "div",
  list: "div",
  row: "div",
  content: "div",
  action: "button",
})

const Mailbox = parts.Root

const MailboxList = parts.List

const MailboxRow = parts.Row

const MailboxContent = parts.Content

const MailboxAction = parts.Action

function MailboxActions({
  row,
  side,
  ...props
}: { row: string; side: SwipeSide } & PartProps<"div">) {
  return usePart(
    mailbox,
    "actions",
    { id: `${row}-${side}`, row, side },
    props,
    "div"
  )
}

function Example() {
  const log = useLog()
  const [messages, setMessages] = React.useState([
    "Welcome to Acme",
    "Flight to Lisbon",
    "Weekly digest",
  ])
  const [read, setRead] = React.useState<string[]>([])
  const toggleRead = (message: string) => {
    log(
      `${read.includes(message) ? "Marked unread" : "Marked read"}: ${message}`
    )
    setRead((current) =>
      current.includes(message)
        ? current.filter((other) => other !== message)
        : [...current, message]
    )
  }
  const archive = (message: string) => {
    log(`Archived: ${message}`)
    setMessages((current) => current.filter((other) => other !== message))
  }
  return (
    <Mailbox
      pinned="Welcome to Acme"
      first={messages[1]}
      onAction={(key: string, side: SwipeSide) =>
        side === "start" ? toggleRead(key) : archive(key)
      }
    >
      <div data-slot="controls">
        <MailboxAction data-size="sm" value="peek">
          Peek
        </MailboxAction>
        <MailboxAction data-size="sm" value="close">
          Close
        </MailboxAction>
      </div>
      <MailboxList aria-label="Mailbox">
        {messages.map((message) => (
          <MailboxRow key={message} value={message}>
            <MailboxContent value={message}>
              {message}
              {message === "Welcome to Acme" ? (
                <PinIcon aria-hidden="true" />
              ) : (
                read.includes(message) && <span data-slot="hint">Read</span>
              )}
            </MailboxContent>
            <MailboxActions row={message} side="start">
              <button
                type="button"
                tabIndex={-1}
                data-variant="solid"
                onClick={() => toggleRead(message)}
              >
                {read.includes(message) ? "Unread" : "Read"}
              </button>
            </MailboxActions>
            <MailboxActions row={message} side="end">
              <button
                type="button"
                tabIndex={-1}
                onClick={() => archive(message)}
              >
                Archive
              </button>
            </MailboxActions>
          </MailboxRow>
        ))}
      </MailboxList>
    </Mailbox>
  )
}

export { Example }
向右滑动把消息标为已读,向左滑动将其归档。超过行宽的一半后,松开即可执行操作。固定的消息保持关闭;Peek 和 Close 用代码控制操作。

swipe.show(key, "end", { focus: true }) 打开一行并聚焦它的第一个操作。swipe.close({ focus: true }) 关闭它并把焦点送回行。省略 focus 就让焦点留在原处。swipe.open() 读取打开的行。

拖动关闭

一条 toast 或卡片被拖动得足够远时,会在松开时关闭。给 scrubTo 一个位于 0 的吸附点:在阈值之内,它的结果带有那个 point,所以 toast 会弹回;超过阈值后,就没有可返回的点。每次移动都询问一次,这样 toast 才能显示松开后会发生什么:

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

const keeps = { min: -width, max: width, step: 1, snap: { points: [0], threshold: width * 0.3 } }

onMove: ({ x }) => {
  moved = x - startX
  setOffset(moved)
  setDismissing(scrubTo(moved, keeps).point === undefined)
},
onEnd: () => (scrubTo(moved, keeps).point === undefined ? dismiss(Math.sign(moved)) : setOffset(0)),

给 data-dismissing 设置样式,让变更在松开之前就清楚可见,像 iOS 那样:这里 toast 背后的层会变红,并显示 “Release to dismiss”。拖回阈值以内就会恢复。为键盘在每条 toast 里保留一个 Dismiss 按钮。

import * as React from "react"
import { bindDrag, dragThreshold } from "@ui-sdk/core"
import { scrubTo } from "@ui-sdk/core/number"
import { XIcon } from "lucide-react"

const initial = [
  { id: 1, title: "Event created", body: "Design review, Friday at 10:00" },
  { id: 2, title: "Invite sent", body: "Inès Moreau can now edit" },
  { id: 3, title: "Upload finished", body: "launch-video.mp4 is ready" },
]

type Toast = (typeof initial)[number]

function SwipeToast({
  toast,
  onDismiss,
}: {
  toast: Toast
  onDismiss: () => void
}) {
  const [offset, setOffset] = React.useState(0)
  const [dragging, setDragging] = React.useState(false)
  const [dismissing, setDismissing] = React.useState(false)
  const stop = React.useRef<(() => void) | undefined>(undefined)
  React.useEffect(() => () => stop.current?.(), [])

  const dismiss = (side: number, width: number) => {
    setOffset(side * width)
    setTimeout(onDismiss, 200)
  }

  const pointerdown = (event: React.PointerEvent<HTMLDivElement>) => {
    if (event.button !== 0 || (event.target as Element).closest("button")) {
      return
    }
    const width = event.currentTarget.offsetWidth
    const keeps = {
      min: -width,
      max: width,
      step: 1,
      snap: { points: [0], threshold: width * 0.3 },
    }
    const startX = event.clientX
    let moved = 0
    stop.current?.()
    stop.current = bindDrag(event.currentTarget, event.nativeEvent, {
      threshold: dragThreshold,
      cancelOnEscape: true,
      onStart: () => setDragging(true),
      onMove: ({ x }) => {
        moved = x - startX
        setOffset(moved)
        setDismissing(scrubTo(moved, keeps).point === undefined)
      },
      onEnd: (_end, canceled) => {
        stop.current = undefined
        setDragging(false)
        setDismissing(false)
        if (!canceled && scrubTo(moved, keeps).point === undefined) {
          dismiss(Math.sign(moved), width)
        } else {
          setOffset(0)
        }
      },
    })
  }

  return (
    <li data-slot="dismiss-item">
      <div
        aria-hidden
        data-slot="dismiss-layer"
        data-side={offset < 0 ? "end" : "start"}
        data-dismissing={dismissing || undefined}
        hidden={!dragging}
      >
        {dismissing ? "Release to dismiss" : "Dismiss"}
      </div>
      <div
        data-slot="dismiss-toast"
        data-dragging={dragging || undefined}
        onPointerDown={pointerdown}
        style={{ "--dismiss-x": `${offset}px` } as React.CSSProperties}
      >
        <div data-slot="stack">
          <span>{toast.title}</span>
          <span data-slot="hint">{toast.body}</span>
        </div>
        <button
          type="button"
          data-variant="ghost"
          data-size="sm"
          aria-label={`Dismiss ${toast.title}`}
          onClick={(event) =>
            dismiss(1, event.currentTarget.parentElement!.offsetWidth)
          }
        >
          <XIcon aria-hidden="true" />
        </button>
      </div>
    </li>
  )
}

function Example() {
  const [toasts, setToasts] = React.useState(initial)
  return (
    <div data-slot="stack">
      <div data-slot="controls">
        <button
          type="button"
          onClick={() => setToasts(initial)}
          disabled={toasts.length === initial.length}
        >
          Show All
        </button>
      </div>
      <ul data-slot="dismiss-list" aria-label="Notifications">
        {toasts.map((toast) => (
          <SwipeToast
            key={toast.id}
            toast={toast}
            onDismiss={() =>
              setToasts((current) =>
                current.filter((candidate) => candidate.id !== toast.id)
              )
            }
          />
        ))}
      </ul>
    </div>
  )
}

export { Example }
把 toast 向侧面拖动:超过它宽度的三分之一后,背后的层会变红,松开就会关闭它。拖回来,或按 Escape,可以保留它。

按压并按住

按住确认

当一次按压持续超过 delay(默认 500 毫秒)时,bindHold 会运行 onHold。给它一个按钮,并保留它的清理函数:

import { bindHold } from "@ui-sdk/core"

const unbind = bindHold(button, {
  delay: 1500,
  onHold: () => deleteProject(),
})

它适用于鼠标、手指、触控笔,以及按钮获得焦点时的 Space 或 Enter。按压期间,按钮带有 data-holding;按住之后,再带有 data-held。--hold-delay 保存这个延迟,所以 CSS 可以在完全相同的时间内填充按钮:

[data-holding] .fill {
  transform: scaleX(1);
  transition: transform var(--hold-delay) linear;
}
控制台
import * as React from "react"
import { bindHold } from "@ui-sdk/core"
import { useLog } from "./log"

export function Example() {
  const button = React.useRef<HTMLButtonElement>(null)
  const hint = React.useId()
  const [deleted, setDeleted] = React.useState(false)
  const log = useLog()

  React.useEffect(() => {
    if (deleted) {
      return
    }
    return bindHold(button.current!, {
      delay: 1500,
      onHold: () => setDeleted(true),
      onEnd: ({ held, canceled }) => {
        if (!held) {
          log(canceled ? "Canceled" : "Released before it filled")
        }
      },
    })
  }, [deleted, log])

  if (deleted) {
    return (
      <div data-slot="row">
        <span>Launch site deleted.</span>
        <button
          type="button"
          data-variant="ghost"
          onClick={() => setDeleted(false)}
        >
          Restore
        </button>
      </div>
    )
  }

  return (
    <div data-slot="stack">
      <button
        ref={button}
        type="button"
        data-slot="hold-button"
        data-variant="destructive"
        aria-describedby={hint}
      >
        <span data-slot="hold-fill" aria-hidden />
        Delete Project
      </button>
      <span id={hint} data-slot="hint">
        Press and hold to delete
      </span>
    </div>
  )
}
按住 Delete Project,直到它填满。过早松开则不会删除任何内容。使用键盘时,聚焦它并按住 Space。

按压结束后,onEnd 会带着 held 和 canceled 运行。在按住之前指针移动超过 tolerance 像素(默认 10)、手指开始滚动、按下 Escape,或焦点离开按钮或窗口时,按压会被取消。被取消的按压不会点击,Escape 也不会到达按钮周围的对话框或浮层。在按钮的标签或描述里说明它需要按住,就像这里的提示那样。

按住时重复

bindRepeat 在按钮被按下时步进一次,然后在按住期间持续步进,像步进器的按钮、滚动箭头或遥控器的音量键那样。告诉它一步要做什么:

import { bindRepeat } from "@ui-sdk/core"

const unbind = bindRepeat(button, {
  repeat: 80,
  onStep: () => zoomBy(5),
})

在 delay 之后(默认 400 毫秒),onStep 每隔 repeat 毫秒再次运行(默认 60),直到按压结束。从 onStep 返回 false 可以停止重复,比如到达边界时。count 表示这是本次按压的第几步,从 1 开始;按压结束后,onEnd 会收到总数。

你不需要点击处理函数。鼠标或按键在按下时就步进,随后的点击不会再次步进。手指或触控笔在抬起时步进,或者在按住之后步进,所以在按钮上开始的滚动永远不会步进。没有按压支撑的点击,比如屏幕阅读器发出的点击,会步进一次。

import * as React from "react"
import { bindRepeat } from "@ui-sdk/core"
import { MinusIcon, PlusIcon } from "lucide-react"

const min = 25
const max = 400

function ZoomButton({
  label,
  disabled,
  onStep,
  children,
}: {
  label: string
  disabled: boolean
  onStep: () => boolean
  children: React.ReactNode
}) {
  const button = React.useRef<HTMLButtonElement>(null)
  const step = React.useEffectEvent(onStep)

  React.useEffect(
    () => bindRepeat(button.current!, { repeat: 80, onStep: () => step() }),
    []
  )

  return (
    <button
      ref={button}
      type="button"
      data-variant="outline"
      aria-label={label}
      disabled={disabled}
    >
      {children}
    </button>
  )
}

export function Example() {
  const [zoom, setZoom] = React.useState(100)

  const zoomBy = (amount: number) => {
    const next = Math.min(Math.max(zoom + amount, min), max)
    setZoom(next)
    return next > min && next < max
  }

  return (
    <div data-slot="row">
      <ZoomButton
        label="Zoom Out"
        disabled={zoom === min}
        onStep={() => zoomBy(-5)}
      >
        <MinusIcon aria-hidden />
      </ZoomButton>
      <output aria-live="polite" data-slot="hold-zoom">
        {zoom}%
      </output>
      <ZoomButton
        label="Zoom In"
        disabled={zoom === max}
        onStep={() => zoomBy(5)}
      >
        <PlusIcon aria-hidden />
      </ZoomButton>
    </div>
  )
}
按一次 Zoom In 增加 5%。按住它,缩放会持续上升,直到你松开或达到 400%。按住时滑出按钮,它会等到你回来。

按住期间,只要指针离开按钮,重复就会等待,指针回来时再继续,就像滚动条的箭头那样。短按 Space 或 Enter 会步进一次;按住时,它们会以和指针相同的节奏重复,无论键盘重复按键有多快。传入 keys: [] 把按键交给浏览器,它发送的每次点击都会步进一次。松开、浏览器取消、Escape,或焦点离开按钮或窗口,都会结束这次按压。

bindRepeat 构建在 bindHold 之上,所以按钮在按压期间带有 data-holding,开始重复后带有 data-held。bindHold 也接受 repeat,用于那种要等到按压被按住之后才第一次运行的操作。

按压开始时,onPress 会运行,input 会被设为 mouse、touch、pen 或 keyboard。返回 false 可以忽略它,比如一个只在触摸时长按打开的上下文菜单区域,因为鼠标有右键。传入 disabled 可以拒绝按压,并阻止按住重复。当手指或触控笔按压时,浏览器自带的长按菜单和 iOS 的 callout 会保持关闭。清理函数会停止正在进行的按压,但不调用 onEnd。

二维值

面板上的一个点

createArea 把一个表面映射为两个值。从状态里读取这个点,并把每次变更写回去:

const area = createArea(context, {
  value: (state) => ({ x: state.mix.warmth, y: state.mix.energy }),
  set: (value, details) =>
    change("mix", { warmth: value.x, energy: value.y }, details),
  x: () => ({ min: 0, max: 100, step: 1, label: "Warmth" }),
  y: () => ({ min: 0, max: 100, step: 1, label: "Energy" }),
})

表面负责开始指针跟踪;滑块手柄提供键盘控制和滑块属性:

pad: slot({
  on: { pointerdown: (event, { el, api }) => api.area.pointerdown(event, el!) },
}),
thumb: slot({
  attrs: (state, { api }) => ({ ...api.area.thumbAttrs(state), style: api.area.thumbStyle(state) }),
  on: { keydown: (event, { api }) => api.area.keydown(event) },
}),

让表面定位,并设置 touch-action: none。滑块手柄的位置相对于它。和移动草稿不同,这个选择器在整个手势期间都会调用 set,使用滑块报告的原因:按压时是 track-press,移动时是 drag,按键时是 step-key。

控制台
import * as React from "react"
import {
  createArea,
  createChange,
  definePrimitive,
  type AreaReason,
  type ChangeDetails,
} from "@ui-sdk/core"
import {
  createParts,
  usePart,
  usePrimitive,
  type PartProps,
} from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type Mix = { warmth: number; energy: number }

type MixerState = { mix: Mix }

type MixerOptions = {
  defaultMix: Mix
  onMixChange?: (mix: Mix, details: ChangeDetails<AreaReason>) => void
}

const mixer = definePrimitive({
  name: "mixer",
  options: { defaultMix: "value", onMixChange: "callback" },
  state: (options: MixerOptions): MixerState => ({ mix: options.defaultMix }),
  api: (context) => {
    const change = createChange(context)
    return {
      area: createArea<MixerState>(context, {
        value: (state) => ({ x: state.mix.warmth, y: state.mix.energy }),
        set: (value, details) =>
          change("mix", { warmth: value.x, energy: value.y }, details),
        x: () => ({ min: 0, max: 100, step: 1, label: "Warmth" }),
        y: () => ({ min: 0, max: 100, step: 1, label: "Energy" }),
      }),
    }
  },
  slots: (slot) => ({
    pad: slot({
      attrs: () => ({
        style: "position:relative;touch-action:none;user-select:none",
      }),
      on: {
        pointerdown: (event, { el, api }) => api.area.pointerdown(event, el!),
      },
    }),
    thumb: slot({
      attrs: (state, { api }) => ({
        ...api.area.thumbAttrs(state),
        style: api.area.thumbStyle(state),
      }),
      on: { keydown: (event, { api }) => api.area.keydown(event) },
    }),
  }),
})

const parts = createParts(mixer, { thumb: "div" })

function Mixer({
  defaultMix,
  onMixChange,
  ...props
}: MixerOptions & PartProps<"div">) {
  const handle = usePrimitive(mixer, { defaultMix, onMixChange })
  return usePart(handle, "pad", {}, props, "div")
}

const MixerThumb = parts.Thumb

function Example() {
  const log = useLog()
  return (
    <Mixer
      defaultMix={{ warmth: 30, energy: 70 }}
      onMixChange={(mix, details) =>
        log(`Warmth ${mix.warmth}, energy ${mix.energy} (${details.reason})`)
      }
    >
      <span data-slot="mixer-axis" data-axis="y" aria-hidden="true">
        Energy
      </span>
      <span data-slot="mixer-axis" data-axis="x" aria-hidden="true">
        Warmth
      </span>
      <MixerThumb aria-label="Mix" />
    </Mixer>
  )
}

export { Example }
在面板上点击或拖动来改变 warmth 和 energy。聚焦滑块手柄并使用方向键,加 Shift 可以走更大的步长。

每个轴默认是 0–1,步长为 0.01。y 轴从下到上,x 跟随文字方向。方向键移动一步,Shift 移动十步,Page Up 和 Page Down 把 y 移动其范围的十分之一,Home 和 End 则到达 x 的两端。

thumbAttrs 暴露一个滑块,其值文本描述两个轴。thumbStyle 设置它的百分比位置以及 --area-x 和 --area-y 的比例。

播报什么,以及何时落定

用 valueText 提供可读的描述,用 onCommit 做应当等到手势结束才执行的工作:

valueText: ({ x, y }) => `${x}% saturation, ${y}% brightness`,
onCommit: (value) => context.options().onColorCommit?.(value),
disabled: () => context.store.get().locked,
控制台
import * as React from "react"
import {
  createArea,
  createChange,
  definePrimitive,
  type AreaValue,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/react/checkbox"
import { CheckIcon } from "lucide-react"
import { useLog } from "./log"

type ColorState = { color: AreaValue; locked: boolean }

type ColorOptions = {
  locked?: boolean
  onColorChange?: (color: AreaValue) => void
  onColorCommit?: (color: AreaValue) => void
}

const color = definePrimitive({
  name: "color",
  options: {
    locked: "boolean",
    onColorChange: "callback",
    onColorCommit: "callback",
  },
  state: (options: ColorOptions): ColorState => ({
    color: { x: 60, y: 80 },
    locked: !!options.locked,
  }),
  sync: (options) => ({ locked: !!options.locked }),
  api: (context) => {
    const change = createChange(context)
    const area = createArea<ColorState>(context, {
      value: (state) => state.color,
      set: (value, details) => change("color", value, details),
      x: () => ({ min: 0, max: 100, step: 1, label: "Saturation" }),
      y: () => ({ min: 0, max: 100, step: 1, label: "Brightness" }),
      valueText: ({ x, y }) => `${x}% saturation, ${y}% brightness`,
      onCommit: (value) => context.options().onColorCommit?.(value),
      disabled: () => context.store.get().locked,
    })
    return { area }
  },
  slots: (slot) => ({
    root: slot<{}, { swatch: string }>({
      state: (state, { api }) => {
        const { x, y } = api.area.fractions(state)
        const lightness = y * (1 - x / 2)
        const saturation =
          lightness === 0 || lightness === 1
            ? 0
            : (y - lightness) / Math.min(lightness, 1 - lightness)
        return {
          swatch: `hsl(210 ${Math.round(saturation * 100)}% ${Math.round(lightness * 100)}%)`,
        }
      },
    }),
    square: slot({
      attrs: () => ({
        style: "position:relative;touch-action:none;user-select:none",
      }),
      on: {
        pointerdown: (event, { el, api }) => api.area.pointerdown(event, el!),
      },
    }),
    thumb: slot({
      attrs: (state, { api }) => ({
        ...api.area.thumbAttrs(state),
        style: api.area.thumbStyle(state),
      }),
      on: { keydown: (event, { api }) => api.area.keydown(event) },
    }),
    reset: slot({
      attrs: () => ({ type: "button" }),
      press: ({ api }) => api.area.set({ x: 60, y: 80 }),
    }),
  }),
})

const parts = createParts(color, {
  root: "div",
  square: "div",
  thumb: "div",
  reset: "button",
})

const ColorPicker = parts.Root

const ColorSquare = parts.Square

const ColorThumb = parts.Thumb

const ColorReset = parts.Reset

function Example() {
  const log = useLog()
  const [locked, setLocked] = React.useState(false)
  return (
    <ColorPicker
      locked={locked}
      onColorCommit={({ x, y }) =>
        log(`Saved ${x}% saturation, ${y}% brightness`)
      }
    >
      {({ swatch }) => (
        <>
          <div data-slot="controls">
            <ColorReset data-size="sm">Reset</ColorReset>
            <label data-slot="label">
              <Checkbox
                checked={locked}
                onCheckedChange={(next) => setLocked(next === true)}
              >
                <CheckboxIndicator>
                  <CheckIcon aria-hidden="true" />
                </CheckboxIndicator>
              </Checkbox>
              Lock
            </label>
          </div>
          <ColorSquare>
            <ColorThumb aria-label="Color" />
          </ColorSquare>
          <span data-slot="swatch" style={{ background: swatch }} />
        </>
      )}
    </ColorPicker>
  )
}

export { Example }
拖动来调整饱和度和亮度。色块会立即跟随;保存的值会在松开后或键盘变更后记录到控制台。Lock 会禁用选择器,Reset 用代码设置它的值。

onCommit 在指针跟踪结束时或键盘变更成功后运行。disabled 阻止用户输入,并把滑块手柄从 Tab 顺序中移除。

area.set({ x: 60, y: 80 }) 会以 imperative 原因吸附并钳制一个程序化值。它在禁用时仍然有效,也不会调用 onCommit。area.fractions(state) 给出每个值在其轴内的位置,对渐变或色块很有用。

轨道上的范围

时间轴上的预订

一个 Span 有 id、track,以及以你的单位表示的 start 和 end 值。对于会议室预订,这些单位可以是从午夜起算的分钟数。把预订保存在数组里,并另起一个 SpansDraft<Booking> | null 字段,初始值为 null:

type Booking = Span & { title: string }
type RoomsState = { bookings: Booking[]; draft: SpansDraft<Booking> | null }

let booked = 0
const spans = createSpans<RoomsState, Booking>(context, {
  key: "bookings",
  draft: "draft",
  set: (value, details) => change("bookings", value, details),
  axis: "x",
  min: () => 9 * 60,
  max: () => 17 * 60,
  step: () => 30,
  overlap: false,
  create: (span) => ({ ...span, id: `booking-${++booked}`, title: "New" }),
})

渲染 spans.spans(state),这样拖动期间会显示草稿。放下时会把数组提交一次,详情里带有受影响的 id 和 action。

用 bindTrack(el, key) 绑定轨道,用 bindSpan(el, id) 绑定预订。轨道上的按压调用 trackPointerdown(event, key);预订上的按压调用 spanPointerdown(event, id)。给预订内部的调整大小手柄加上 data-span-edge="start" 或 "end"。

import * as React from "react"
import {
  createChange,
  createSpans,
  definePrimitive,
  type ChangeDetails,
  type Span,
  type SpansDraft,
  type SpansReason,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type Booking = Span & { title: string }

type RoomsState = { bookings: Booking[]; draft: SpansDraft<Booking> | null }

type RoomsOptions = {
  defaultBookings: Booking[]
  onBookingsChange?: (
    bookings: Booking[],
    details: ChangeDetails<SpansReason>
  ) => void
}

const hour = (minutes: number) =>
  `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}`

let booked = 0

const rooms = definePrimitive({
  name: "rooms",
  options: { defaultBookings: "value", onBookingsChange: "callback" },
  state: (options: RoomsOptions): RoomsState => ({
    bookings: options.defaultBookings,
    draft: null,
  }),
  api: (context) => {
    const change = createChange(context)
    return {
      spans: createSpans<RoomsState, Booking>(context, {
        key: "bookings",
        draft: "draft",
        set: (value, details) => change("bookings", value, details),
        axis: "x",
        min: () => 9 * 60,
        max: () => 17 * 60,
        step: () => 30,
        overlap: false,
        create: (span) => ({
          ...span,
          id: `booking-${++booked}`,
          title: "New",
        }),
        label: (booking) =>
          `${booking.title}, ${booking.track}, ${hour(booking.start)} to ${hour(booking.end)}`,
      }),
    }
  },
  slots: (slot) => ({
    root: slot<{}, { bookings: Booking[] }>({
      state: (state, { api }) => ({ bookings: api.spans.spans(state) }),
    }),
    room: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({
        role: "group",
        style: "position:relative;touch-action:none;user-select:none",
      }),
      on: {
        pointerdown: (event, { api, key }) =>
          api.spans.trackPointerdown(event, key),
      },
      bind: (el, { api, key }) => api.spans.bindTrack(el, key),
    }),
    booking: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { api, key }) => {
        const booking = api.spans.spans(state).find((other) => other.id === key)
        return {
          tabindex: "0",
          "aria-label": booking
            ? `${booking.title}, ${booking.track}, ${hour(booking.start)} to ${hour(booking.end)}`
            : undefined,
          ...api.spans.spanAttrs(state, key),
          style: booking ? api.spans.spanStyle(booking) : undefined,
        }
      },
      on: {
        pointerdown: (event, { api, key }) =>
          api.spans.spanPointerdown(event, key),
        keydown: (event, { api, key }) => api.spans.keydown(event, key),
      },
      bind: (el, { api, key }) => api.spans.bindSpan(el, key),
    }),
  }),
})

const parts = createParts(rooms, { root: "div", room: "div", booking: "div" })

const Rooms = parts.Root

const RoomsRoom = parts.Room

const RoomsBooking = parts.Booking

function Example() {
  return (
    <Rooms
      defaultBookings={[
        {
          id: "standup",
          track: "Atlas",
          start: 9 * 60 + 30,
          end: 11 * 60,
          title: "Standup",
        },
        {
          id: "review",
          track: "Birch",
          start: 13 * 60,
          end: 15 * 60,
          title: "Review",
        },
      ]}
    >
      {({ bookings }) => (
        <>
          <div data-slot="spans-lane">
            <span data-slot="spans-label" />
            <div data-slot="spans-axis" aria-hidden="true">
              <span>9:00</span>
              <span>13:00</span>
              <span>17:00</span>
            </div>
          </div>
          {["Atlas", "Birch"].map((room) => (
            <div key={room} data-slot="spans-lane">
              <span data-slot="spans-label">{room}</span>
              <RoomsRoom value={room} aria-label={room}>
                {bookings
                  .filter((booking) => booking.track === room)
                  .map((booking) => (
                    <RoomsBooking key={booking.id} value={booking.id}>
                      {booking.title}
                      <span data-span-edge="end" />
                    </RoomsBooking>
                  ))}
              </RoomsRoom>
            </div>
          ))}
        </>
      )}
    </Rooms>
  )
}

export { Example }
在空白处拖动来预订房间。拖动预订可以移动它,拖动它的末端可以调整大小。值会吸附到半小时,预订之间不能重叠。

用 spanStyle(booking) 定位预订,用 spanAttrs(state, id) 获取 data-span-id 以及绘制、拖动或调整大小的状态。能否获得焦点以及无障碍名称由你自己提供;label(booking) 提供播报中使用的名称。给轨道和可拖动的范围设置 touch-action: none。

在预订上调用 keydown(event, id)。沿轨道的方向键移动它;配合 Shift 时移动它的末端。跨轨道的方向键更换房间,Delete 或 Backspace 删除它。每次按键都会立即提交。

create 提供新预订的 ID 和数据。没有它时,空轨道不会创建预订。overlap: false 会拒绝与同一轨道上另一个范围重叠的提议范围。

向下排列的日期

轨道默认纵向排列。为日历加上持续时间限制、点击持续时间和显式的轨道顺序:

minSize: () => 60,
maxSize: () => 180,
size: () => 60,
tracks: () => ["Mon", "Tue", "Wed"],
createAutoScroll: { edge: 32 },
控制台
import * as React from "react"
import {
  createChange,
  createSpans,
  css,
  definePrimitive,
  stackSpans,
  type Span,
  type SpanAction,
  type SpansDraft,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type Plan = Span & { title: string }

type WeekState = {
  plans: Plan[]
  draft: SpansDraft<Plan> | null
  hover: number | null
}

const time = (minutes: number) =>
  `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}`

let made = 0

const week = definePrimitive({
  name: "week",
  options: { onHover: "callback" },
  state: (_options: {
    onHover?: (day: string, minutes: number) => void
  }): WeekState => ({
    plans: [
      { id: "gym", track: "Mon", start: 9 * 60, end: 10 * 60, title: "Gym" },
      {
        id: "call",
        track: "Mon",
        start: 9 * 60 + 30,
        end: 11 * 60,
        title: "Call",
      },
      {
        id: "lunch",
        track: "Tue",
        start: 12 * 60,
        end: 13 * 60,
        title: "Lunch",
      },
    ],
    draft: null,
    hover: null,
  }),
  api: (context) => {
    const change = createChange(context)
    const spans = createSpans<WeekState, Plan>(context, {
      key: "plans",
      draft: "draft",
      set: (value, details) => change("plans", value, details),
      min: () => 8 * 60,
      max: () => 14 * 60,
      step: () => 30,
      minSize: () => 60,
      maxSize: () => 180,
      size: () => 60,
      tracks: () => ["Mon", "Tue", "Wed"],
      create: (span) => ({ ...span, id: `plan-${++made}`, title: "New" }),
      label: (plan) =>
        `${plan.title}, ${plan.track} ${time(plan.start)} to ${time(plan.end)}`,
      createAutoScroll: { edge: 32 },
    })
    return {
      spans,
      hover: (track: string | null, event?: PointerEvent) => {
        const hover =
          track && event
            ? spans.valueAt(track, event.clientX, event.clientY)
            : null
        if (hover === context.store.get().hover) {
          return
        }
        context.store.set({ hover })
        if (track && hover !== null) {
          context.options().onHover?.(track, hover)
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot({}),
    day: slot<{ value: string }, { plans: Plan[] }>({
      props: { value: "string" },
      state: (state, { api, key }) => ({
        plans: api.spans.spansOn(state, key),
      }),
      attrs: () => ({
        role: "group",
        style: "position:relative;touch-action:none;user-select:none",
      }),
      on: {
        pointerdown: (event, { api, key }) =>
          api.spans.trackPointerdown(event, key),
        pointermove: (event, { api, key }) => api.hover(key, event),
        pointerleave: (_event, { api }) => api.hover(null),
      },
      bind: (el, { api, key }) => api.spans.bindTrack(el, key),
    }),
    plan: slot<
      { value: string },
      { plan: Plan; action: SpanAction | undefined }
    >({
      props: { value: "string" },
      present: (state, { api, key }) =>
        api.spans.spans(state).some((plan) => plan.id === key),
      state: (state, { api, key }) => ({
        plan: api.spans.spans(state).find((plan) => plan.id === key)!,
        action: api.spans.action(state, key),
      }),
      attrs: (state, { api, key }) => {
        const plans = api.spans.spans(state)
        const plan = plans.find((other) => other.id === key)!
        const lanes = stackSpans(
          plans.filter((other) => other.track === plan.track)
        )
        return {
          tabindex: "0",
          "aria-label": `${plan.title}, ${plan.track} ${time(plan.start)} to ${time(plan.end)}`,
          ...api.spans.spanAttrs(state, key),
          style: api.spans.spanStyle(plan, lanes.get(key)),
        }
      },
      on: {
        pointerdown: (event, { api, key }) =>
          api.spans.spanPointerdown(event, key),
        keydown: (event, { api, key }) => api.spans.keydown(event, key),
      },
      bind: (el, { api, key }) => api.spans.bindSpan(el, key),
    }),
    edge: slot<{ edge: "start" | "end" }>({
      props: { edge: "string" },
      attrs: (_state, { props }) => ({
        "data-span-edge": props.edge,
        style: css({
          position: "absolute",
          left: "0",
          right: "0",
          height: "6px",
          cursor: "ns-resize",
        }),
      }),
    }),
  }),
})

const parts = createParts(week, {
  root: "div",
  day: "div",
  plan: "div",
  edge: "div",
})

const Week = parts.Root

const WeekDay = parts.Day

const WeekPlan = parts.Plan

const WeekEdge = parts.Edge

function Example() {
  const log = useLog()
  return (
    <Week onHover={(day, minutes) => log(`Pointer at ${day} ${time(minutes)}`)}>
      <div data-slot="spans-week-head">
        {["Mon", "Tue", "Wed"].map((day) => (
          <span key={day}>{day}</span>
        ))}
      </div>
      <div data-slot="spans-week-frame">
        <div data-slot="spans-week-hours">
          {[8, 9, 10, 11, 12, 13].map((hour) => (
            <div key={hour}>{hour}:00</div>
          ))}
        </div>
        {["Mon", "Tue", "Wed"].map((day) => (
          <WeekDay key={day} value={day} aria-label={day}>
            {({ plans }) =>
              plans.map((plan) => (
                <WeekPlan key={plan.id} value={plan.id}>
                  {({ plan, action }) => (
                    <>
                      <WeekEdge edge="start" />
                      {plan.title}
                      {action && ` ${time(plan.start)}–${time(plan.end)}`}
                      <WeekEdge edge="end" />
                    </>
                  )}
                </WeekPlan>
              ))
            }
          </WeekDay>
        ))}
      </div>
    </Week>
  )
}

export { Example }
在一天里向下拖动来绘制事件,或点击创建一小时的事件。在一到三小时之间移动或调整事件大小。拖动时把指针保持在顶部或底部附近即可滚动。

minSize 和 maxSize 限制持续时间;size 决定点击创建什么。tracks 控制键盘跨日期行进的顺序。自动滚动接受与其他拖动相同的选项。

允许重叠时,给每个事件一条泳道,让它们共享一天的宽度:

const lanes = stackSpans(plans.filter((other) => other.track === plan.track))
const style = spans.spanStyle(plan, lanes.get(plan.id))

spansOn(state, track) 读取一条轨道上的范围。valueAt(track, x, y) 把指针位置转换成该轨道范围内的值,并吸附到 step。action(state, id) 报告当前活动的指针动作。

用代码更改范围

对于表单字段或操作按钮,使用 update 和 remove:

spans.update("standup", { start: booking.start + 30, end: booking.end + 30 })
spans.update("standup", { end: booking.end + 30 })
spans.remove("standup")

update 会应用范围和重叠规则。这些方法会报告 imperative;它们不检查 disabled,后者只适用于指针和键盘输入。isSpanFree(bookings, proposed) 检查提议的预订是否与它所在轨道上的另一个预订重叠。

控制台
import * as React from "react"
import {
  createChange,
  createSpans,
  definePrimitive,
  isSpanFree,
  spansMessage,
  type Span,
  type SpansDraft,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type Booking = Span & { title: string }

type RoomState = { bookings: Booking[]; draft: SpansDraft<Booking> | null }

type RoomOptions = {
  onBookingsChange?: (bookings: Booking[]) => void
  onNote?: (note: string) => void
}

const hour = (minutes: number) =>
  `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}`

let lunches = 0

const room = definePrimitive({
  name: "room",
  options: { onBookingsChange: "callback", onNote: "callback" },
  state: (_options: RoomOptions): RoomState => ({
    bookings: [
      {
        id: "standup",
        track: "Atlas",
        start: 9 * 60 + 30,
        end: 11 * 60,
        title: "Standup",
      },
      {
        id: "board",
        track: "Atlas",
        start: 14 * 60,
        end: 16 * 60,
        title: "Board meeting",
      },
    ],
    draft: null,
  }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const spans = createSpans<RoomState, Booking>(context, {
      key: "bookings",
      draft: "draft",
      set: (value, details) => change("bookings", value, details),
      axis: "x",
      min: () => 9 * 60,
      max: () => 17 * 60,
      step: () => 30,
      overlap: false,
      disabled: (booking) => booking.id === "board",
      label: (booking) =>
        `${booking.title}, ${hour(booking.start)} to ${hour(booking.end)}`,
      message: (message) =>
        message.type === "delete"
          ? `${message.span.title} is cancelled.`
          : spansMessage(message),
      createAutoScroll: false,
    })
    const standup = () =>
      store.get().bookings.find((booking) => booking.id === "standup")
    return {
      spans,
      act(action: string) {
        const booking = standup()
        if (action === "later" && booking) {
          spans.update("standup", {
            start: booking.start + 30,
            end: booking.end + 30,
          })
        } else if (action === "longer" && booking) {
          spans.update("standup", { end: booking.end + 30 })
        } else if (action === "delete") {
          spans.remove("standup")
        } else if (action === "noon") {
          const noon: Booking = {
            id: `lunch-${++lunches}`,
            track: "Atlas",
            start: 12 * 60,
            end: 13 * 60,
            title: "Lunch",
          }
          const free = isSpanFree(store.get().bookings, noon)
          context.options().onNote?.(free ? "Booked noon" : "Noon is taken")
          if (free) {
            change("bookings", [...store.get().bookings, noon], {
              reason: "imperative",
            })
          }
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { bookings: Booking[] }>({
      state: (state, { api }) => ({ bookings: api.spans.spans(state) }),
    }),
    track: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({
        role: "group",
        style: "position:relative;touch-action:none;user-select:none",
      }),
      bind: (el, { api, key }) => {
        const unbind = api.spans.bindTrack(el, key)
        const view = el.ownerDocument.defaultView!
        view.addEventListener("blur", api.spans.cancel)
        return () => {
          unbind()
          view.removeEventListener("blur", api.spans.cancel)
        }
      },
    }),
    booking: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { api, key }) => {
        const booking = api.spans.spans(state).find((other) => other.id === key)
        return {
          tabindex: "0",
          "aria-label": booking
            ? `${booking.title}, ${hour(booking.start)} to ${hour(booking.end)}`
            : undefined,
          "aria-disabled": key === "board" ? "true" : undefined,
          ...api.spans.spanAttrs(state, key),
          style: booking ? api.spans.spanStyle(booking) : undefined,
        }
      },
      on: {
        pointerdown: (event, { api, key }) =>
          api.spans.spanPointerdown(event, key),
        keydown: (event, { api, key }) => api.spans.keydown(event, key),
      },
      bind: (el, { api, key }) => api.spans.bindSpan(el, key),
    }),
    action: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
      press: ({ api, key }) => api.act(key),
    }),
  }),
})

const parts = createParts(room, {
  root: "div",
  track: "div",
  booking: "div",
  action: "button",
})

const Room = parts.Root

const RoomTrack = parts.Track

const RoomBooking = parts.Booking

const RoomAction = parts.Action

function Example() {
  const log = useLog()
  return (
    <Room
      onBookingsChange={(bookings) =>
        log(
          bookings
            .map(
              (booking) =>
                `${booking.title} ${hour(booking.start)}–${hour(booking.end)}`
            )
            .join(" · ")
        )
      }
      onNote={log}
    >
      {({ bookings }) => (
        <>
          <div data-slot="controls">
            {[
              ["later", "Later"],
              ["longer", "Longer"],
              ["delete", "Delete"],
              ["noon", "Book Noon"],
            ].map(([value, text]) => (
              <RoomAction data-size="sm" key={value} value={value}>
                {text}
              </RoomAction>
            ))}
          </div>
          <div data-slot="spans-axis" aria-hidden="true">
            <span>9:00</span>
            <span>13:00</span>
            <span>17:00</span>
          </div>
          <RoomTrack value="Atlas" aria-label="Atlas">
            {bookings.map((booking) => (
              <RoomBooking key={booking.id} value={booking.id}>
                {booking.title}
              </RoomBooking>
            ))}
          </RoomTrack>
        </>
      )}
    </Room>
  )
}

export { Example }
用按钮移动、延长或删除 Standup。Book noon 会检查房间是否空闲。board meeting 已锁定,拖动期间离开窗口会取消拖动。

spans.cancel() 结束拖动但不提交。如果你在窗口失去焦点时取消,就在原语销毁时移除那个监听器:

window.addEventListener("blur", spans.cancel)
context.onDestroy(() => window.removeEventListener("blur", spans.cancel))

message 自定义播报,默认由 spansMessage 提供。当你的轨道不需要边缘滚动时,设置 createAutoScroll: false。

预览

按压并滑动

预览让人在选定之前先试用一个值。把一个 string | null 的预览放在已选值旁边,并渲染 preview ?? value:

const preview = createPreview(context, {
  key: "preview",
  slot: "font",
  value: () => context.store.get().value,
  choose: (key, details) => change("value", key, details),
})

预览直接写入它的状态字段。如果它还需要经过变更回调,就加上 set。

保留字体槽位已有的游走焦点绑定,并加上这些处理函数:

on: {
  pointerdown: (event, { el, api, key }) => api.preview.pointerdown(event, key, el!.parentElement!),
  keydown: (event, { el, api, key }) => {
    if (api.preview.keydown(event, key)) {
      return
    }
    const moved = api.roving.keydown(event, el!)
    if (moved) {
      api.preview.show(moved.key, { reason: "list-navigation", event })
    }
  },
},
控制台
import * as React from "react"
import {
  createChange,
  createPreview,
  createRovingFocus,
  definePrimitive,
  selects,
  type ChangeDetails,
  type PreviewReason,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type FontsState = {
  value: string
  preview: string | null
  focused: string | null
}

type FontsOptions = {
  defaultValue: string
  onValueChange?: (
    value: string,
    details: ChangeDetails<"item-press" | "list-navigation">
  ) => void
  onPreviewChange?: (
    preview: string | null,
    details: ChangeDetails<PreviewReason>
  ) => void
}

const fonts = definePrimitive({
  name: "fonts",
  options: {
    defaultValue: "string",
    onValueChange: "callback",
    onPreviewChange: "callback",
  },
  state: (options: FontsOptions): FontsState => ({
    value: options.defaultValue,
    preview: null,
    focused: null,
  }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const roving = createRovingFocus<FontsState, { value: string }>(context, {
      slot: "font",
      key: "focused",
      orientation: () => "horizontal",
    })
    const preview = createPreview<FontsState>(context, {
      key: "preview",
      slot: "font",
      value: () => store.get().value,
      set: (value, details) => change("preview", value, details),
      choose: (key, details) => change("value", key, details),
    })
    return { roving, preview }
  },
  slots: (slot) => ({
    root: slot<{}, { shown: string }>({
      state: (state) => ({ shown: state.preview ?? state.value }),
      attrs: () => ({ role: "radiogroup" }),
      on: {
        focusout: (event, { el, api }) => {
          if (
            api.preview.dragging() ||
            el?.contains(event.relatedTarget as Node)
          ) {
            return
          }
          api.preview.clear({ reason: "focus-out", event })
        },
      },
    }),
    font: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        type: "button",
        role: "radio",
        "aria-checked": String(state.value === part.key),
        tabindex: part.api.roving.tabIndex(state, part),
        "data-checked": state.value === part.key ? "" : undefined,
        "data-previewing": state.preview === part.key ? "" : undefined,
        style: "touch-action:none;user-select:none",
      }),
      on: {
        pointerdown: (event, { el, api, key }) =>
          api.preview.pointerdown(event, key, el!.parentElement!),
        keydown: (event, { el, api, key }) => {
          if (api.preview.keydown(event, key)) {
            return
          }
          const moved = api.roving.keydown(event, el!)
          if (moved) {
            api.preview.show(moved.key, { reason: "list-navigation", event })
          }
        },
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(fonts, { root: "div", font: "button" })

const Fonts = parts.Root

const FontsOption = parts.Font

const families: Record<string, string> = {
  Sans: "ui-sans-serif, system-ui",
  Serif: "ui-serif, Georgia, serif",
  Mono: "var(--mono)",
}

function Example() {
  const log = useLog()
  const [shown, setShown] = React.useState("Sans")
  const [preview, setPreview] = React.useState<string | null>(null)
  return (
    <div data-slot="stack">
      <p
        data-slot="preview-sample"
        style={
          {
            "--preview-font": families[preview ?? shown],
          } as React.CSSProperties
        }
      >
        The quick brown fox
      </p>
      <Fonts
        aria-label="Font"
        defaultValue="Sans"
        onValueChange={(value) => {
          setShown(value)
          log(`Chose ${value}`)
        }}
        onPreviewChange={setPreview}
      >
        {Object.keys(families).map((font) => (
          <FontsOption key={font} value={font}>
            {font}
          </FontsOption>
        ))}
      </Fonts>
    </div>
  )
}

export { Example }
按下一个字体,然后滑过其他字体来预览它们。在其中一个上松开即可选定,在外面松开则取消。使用键盘时,方向键预览,Enter 或 Space 选定。

把共同的父级表面传给 pointerdown,以便跨选项跟踪手势。show(key) 预览一个,choose(key) 提交它,clear() 回到已选的值。Enter 和 Space 选定;Escape 清除。

当焦点离开这一组时清除预览,除非指针仍在滑动:

focusout: (event, { el, api }) => {
  if (api.preview.dragging() || el?.contains(event.relatedTarget as Node)) {
    return
  }
  api.preview.clear({ reason: "focus-out", event })
},

按压并滑动也可以试用一种顺序。在按压开始时测量每个标签页,并把被拖动标签页可能占据的每个槽位的左边缘设为一个吸附点。scrubTo 会在标签页靠近时把它拉进槽位,最近的槽位显示它将形成的顺序,松开就保留它:

const slots = lefts([...others, key], widths)

onMove: ({ x, event }) => {
  const { value: left } = scrubTo(start + x, { min: 0, max: slots.at(-1), step: 1, snap: { points: slots, threshold: 12 } }, {
    snap: !event.metaKey,
  })
  preview(insert(others, key, nearest(slots, left)), left)
},

对于键盘,stepFromKey 和 stepBy 把聚焦的标签页移动一个位置,或用 Home 和 End 移到任意一端,方式和滑块步进一样。

import * as React from "react"
import { bindDrag, dragThreshold } from "@ui-sdk/core"
import { scrubTo, stepBy, stepFromKey } from "@ui-sdk/core/number"

const tabs = {
  inbox: "Inbox",
  drafts: "Drafts",
  sent: "Sent",
  spam: "Spam",
}

const counts: Record<string, string> = {
  inbox: "12 conversations, 3 unread",
  drafts: "2 drafts",
  sent: "48 conversations",
  spam: "No spam",
}

type Key = keyof typeof tabs

const gap = 4

type Drag = {
  key: Key
  left: number
  target: number
  others: Key[]
  widths: Record<string, number>
}

const insert = (others: Key[], key: Key, at: number) => [
  ...others.slice(0, at),
  key,
  ...others.slice(at),
]

const nearest = (points: number[], value: number) =>
  points.reduce(
    (best, point, index) =>
      Math.abs(point - value) < Math.abs(points[best] - value) ? index : best,
    0
  )

const lefts = (order: Key[], widths: Record<string, number>) =>
  order.reduce<number[]>(
    (all, key, index) => [
      ...all,
      index ? all[index - 1] + widths[order[index - 1]] + gap : 0,
    ],
    []
  )

function Example() {
  const [order, setOrder] = React.useState(Object.keys(tabs) as Key[])
  const [selected, setSelected] = React.useState<Key>("inbox")
  const [drag, setDrag] = React.useState<Drag | null>(null)
  const elements = React.useRef(new Map<Key, HTMLButtonElement>())
  const stop = React.useRef<(() => void) | undefined>(undefined)
  React.useEffect(() => () => stop.current?.(), [])

  const pointerdown = (
    event: React.PointerEvent<HTMLButtonElement>,
    key: Key
  ) => {
    if (event.button !== 0) {
      return
    }
    const widths = Object.fromEntries(
      order.map((candidate) => [
        candidate,
        elements.current.get(candidate)!.getBoundingClientRect().width,
      ])
    )
    const others = order.filter((candidate) => candidate !== key)
    const slots = lefts([...others, key], widths)
    const start = slots[order.indexOf(key)] - event.clientX
    let latest: Drag | null = null
    stop.current?.()
    stop.current = bindDrag(event.currentTarget, event.nativeEvent, {
      threshold: dragThreshold,
      cancelOnEscape: true,
      onMove: ({ x, event }) => {
        const { value: left } = scrubTo(
          start + x,
          {
            min: 0,
            max: slots[slots.length - 1],
            step: 1,
            snap: { points: slots, threshold: 12 },
          },
          { snap: !(event.metaKey || event.ctrlKey) }
        )
        latest = { key, left, target: nearest(slots, left), others, widths }
        setDrag(latest)
      },
      onEnd: (_end, canceled) => {
        stop.current = undefined
        if (latest && !canceled) {
          setOrder(insert(latest.others, latest.key, latest.target))
        }
        setDrag(null)
      },
    })
  }

  const keydown = (event: React.KeyboardEvent<HTMLButtonElement>, key: Key) => {
    const move = stepFromKey(event, { arrows: "horizontal" })
    if (!move) {
      return
    }
    event.preventDefault()
    const index = stepBy(order.indexOf(key), move, {
      min: 0,
      max: order.length - 1,
      step: 1,
    })
    if (event.altKey) {
      setOrder(
        insert(
          order.filter((candidate) => candidate !== key),
          key,
          index
        )
      )
      return
    }
    setSelected(order[index])
    elements.current.get(order[index])?.focus()
  }

  const shown = drag ? insert(drag.others, drag.key, drag.target) : order
  const placed = drag ? lefts(shown, drag.widths) : []
  return (
    <div data-slot="stack">
      <div
        role="tablist"
        aria-label="Mailboxes"
        data-slot="drag-tabs-list"
        data-dragging={drag ? "" : undefined}
        style={
          drag
            ? ({
                "--drag-tabs-width": `${placed[placed.length - 1] + drag.widths[shown[shown.length - 1]] + 4}px`,
              } as React.CSSProperties)
            : undefined
        }
      >
        {shown.map((key, index) => (
          <button
            key={key}
            ref={(el) => {
              if (el) {
                elements.current.set(key, el)
              } else {
                elements.current.delete(key)
              }
            }}
            type="button"
            role="tab"
            id={`mailbox-${key}`}
            data-slot="drag-tabs-tab"
            aria-selected={key === selected}
            aria-controls="mailbox-panel"
            tabIndex={key === selected ? 0 : -1}
            data-moving={drag?.key === key || undefined}
            onPointerDown={(event) => pointerdown(event, key)}
            onKeyDown={(event) => keydown(event, key)}
            onClick={() => setSelected(key)}
            style={
              drag
                ? ({
                    "--drag-tabs-left": `${(drag.key === key ? drag.left : placed[index]) + 2}px`,
                  } as React.CSSProperties)
                : undefined
            }
          >
            {tabs[key]}
          </button>
        ))}
      </div>
      <div
        role="tabpanel"
        id="mailbox-panel"
        data-slot="drag-tabs-panel"
        aria-labelledby={`mailbox-${selected}`}
      >
        <h3>{tabs[selected]}</h3>
        <span data-slot="hint">{counts[selected]}</span>
      </div>
    </div>
  )
}

export { Example }
沿标签栏拖动一个标签页:它靠近每个位置时会吸附进去,其他标签页会让出空间。按住 Command 或 Ctrl 可以自由放置,或按 Escape 取消。使用键盘时,Option 或 Alt 加方向键移动聚焦的标签页。

悬停,以及播报什么

对于悬停预览,在进入和离开时使用 show 和 clear,然后在点击时使用 choose:

pointerenter: (event, { api, key }) => api.preview.show(key, { reason: "item-hover", event }),
pointerleave: (event, { api }) => api.preview.clear({ reason: "item-hover", event }),
click: (event, { api, key }) => api.preview.choose(key, { event }),
import * as React from "react"
import {
  createChange,
  createPreview,
  createRovingFocus,
  definePrimitive,
  selects,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type ThemesState = {
  value: string
  preview: string | null
  focused: string | null
}

const names: Record<string, string> = {
  light: "Light",
  dark: "Dark",
  sepia: "Sepia",
  contrast: "Contrast",
}

const themes = definePrimitive({
  name: "themes",
  state: (): ThemesState => ({ value: "light", preview: null, focused: null }),
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    return {
      roving: createRovingFocus<ThemesState, { value: string }>(context, {
        slot: "theme",
        key: "focused",
      }),
      preview: createPreview<ThemesState>(context, {
        key: "preview",
        slot: "theme",
        value: () => store.get().value,
        choose: (key, details) => change("value", key, details),
        disabled: (key) => key === "contrast",
        label: (key) => `the ${names[key]} theme`,
        message: (label) =>
          `Trying ${label}. Enter keeps it, Escape puts it back.`,
      }),
    }
  },
  slots: (slot) => ({
    root: slot<{}, { shown: string }>({
      state: (state) => ({ shown: state.preview ?? state.value }),
    }),
    list: slot({
      attrs: () => ({ role: "radiogroup" }),
      on: {
        focusout: (event, { el, api }) => {
          if (!el?.contains(event.relatedTarget as Node)) {
            api.preview.clear({ reason: "focus-out", event })
          }
        },
      },
    }),
    theme: slot<{ value: string }>({
      props: { value: "string" },
      selects: selects({ focused: ({ key }) => [key, null] }),
      attrs: (state, part) => ({
        type: "button",
        role: "radio",
        "aria-checked": String(state.value === part.key),
        "aria-disabled": part.key === "contrast" ? "true" : undefined,
        tabindex: part.api.roving.tabIndex(state, part),
        "data-previewing": state.preview === part.key ? "" : undefined,
      }),
      on: {
        pointerenter: (event, { api, key }) =>
          api.preview.show(key, { reason: "item-hover", event }),
        pointerleave: (event, { api }) =>
          api.preview.clear({ reason: "item-hover", event }),
        click: (event, { api, key }) => api.preview.choose(key, { event }),
        keydown: (event, { el, api, key }) => {
          if (api.preview.keydown(event, key)) {
            return
          }
          const moved = api.roving.keydown(event, el!)
          if (moved) {
            api.preview.show(moved.key, { reason: "list-navigation", event })
          }
        },
      },
      bind: (el, part) => part.api.roving.bind(el, part),
    }),
  }),
})

const parts = createParts(themes, { root: "div", list: "div", theme: "button" })

const Themes = parts.Root

const ThemesList = parts.List

const ThemesOption = parts.Theme

const looks: Record<string, { paper: string; text: string }> = {
  light: { paper: "#ffffff", text: "#171717" },
  dark: { paper: "#171717", text: "#f5f5f5" },
  sepia: { paper: "#f4ecd8", text: "#5b4636" },
  contrast: { paper: "#000000", text: "#fde047" },
}

function Example() {
  return (
    <Themes>
      {({ shown }) => (
        <>
          <p
            data-slot="preview-sample"
            style={
              {
                "--preview-paper": looks[shown].paper,
                "--preview-text": looks[shown].text,
              } as React.CSSProperties
            }
          >
            The quick brown fox jumps over the lazy dog.
          </p>
          <ThemesList aria-label="Theme">
            {Object.keys(names).map((theme) => (
              <ThemesOption key={theme} value={theme}>
                {names[theme]}
                {theme === "contrast" && <span data-slot="hint">Soon</span>}
              </ThemesOption>
            ))}
          </ThemesList>
        </>
      )}
    </Themes>
  )
}

export { Example }
悬停在一个主题上试用它,点击即可保留。方向键也可以预览;Enter 选定,Escape 清除。Contrast 已禁用。

disabled(key) 阻止预览或选定选项。label(key) 和 message(label) 为原因为 list-navigation 的预览自定义播报;指针预览不会在每次经过选项时都播报。

API 参考

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

keykeyof State & string
The state key that holds every item's position, a Record<string, MovePoint>.
示例: Place Anything
draftkeyof State & string
The state key that holds the MoveDraft while a pointer drags. Start it at null, and list it in live.
示例: Place Anything
set(value: Record<string, MovePoint>, details: { reason: MoveReason; event?: Event; }) => boolean
Asks for new positions and returns whether they went through. Pass the primitive's change: set: (value, details) => change("positions", value, details).
示例: Place Anything
group?((key: string) => string[])
The keys that move together with the one pressed, like the selection when it holds it. Defaults to that one key.
示例: Several at Once
step?(() => number)
The grid a dropped position lands on, and how far Alt with an arrow nudges. Defaults to 1.
示例: Several at Once
largeStep?(() => number)
How far Alt with Shift and an arrow nudges. Defaults to ten steps.
示例: Place Anything
scale?(() => number)
How many screen pixels one unit of position takes, like a canvas's zoom, so a drag follows the pointer when the items are scaled. Defaults to 1.
示例: Zoom and Moving from Code
bounds?((key: string) => { minX: number; minY: number; maxX: number; maxY: number; } | undefined)
Keeps positions inside a box, like the board's size minus a card's.
示例: Place Anything
disabled?((key: string) => boolean)
Whether an item can't be moved.
示例: Several at Once
label?((key: string) => string | undefined)
The name screen readers hear for an item.
示例: Several at Once
message?((message: MoveMessage) => string)
The text screen readers hear after a move. Defaults to English.
示例: Several at Once
boxes(state: State) => Record<string, ResizeBox>
Every box in state, by key, like (state) => state.boxes or (state) => ({ crop: state.crop }).
示例: Handles on a Box
draftkeyof State & string
The state key that holds the ResizeDraft while a pointer drags. Start it at null, and list it in live.
示例: Handles on a Box
set(value: Record<string, ResizeBox>, details: { reason: ResizeReason; event?: Event; }) => boolean
Asks for new boxes and returns whether they went through. Pass the primitive's change: set: (value, details) => change("boxes", value, details), or change("crop", value.crop, details) for a primitive with one box.
示例: Handles on a Box
min?((key: string) => { width: number; height: number; })
The smallest a box gets. Defaults to 1 by 1.
示例: Handles on a Box
max?((key: string) => { width: number; height: number; } | undefined)
The largest a box gets.
示例: Keeping a Shape
bounds?((key: string) => { left: number; top: number; right: number; bottom: number; } | undefined)
Keeps a box inside an area, like the image a crop sits on.
示例: Handles on a Box
aspect?((key: string) => number | undefined)
Keeps width over height at this ratio, like 16 / 9. Without one, Shift on a corner keeps the ratio the box had when the drag started.
示例: Keeping a Shape
step?(() => number)
The grid a dropped box lands on, and how far an arrow moves an edge. Defaults to 1.
示例: Handles on a Box
largeStep?(() => number)
How far Shift with an arrow moves an edge. Defaults to ten steps.
示例: Keeping a Shape
scale?(() => number)
How many screen pixels one unit takes, like a canvas's zoom. Defaults to 1.
示例: Several Boxes, and from Code
disabled?((key: string) => boolean)
Whether a box can't be changed.
示例: Several Boxes, and from Code
label?((key: string) => string | undefined)
The name screen readers hear for a box.
示例: Several Boxes, and from Code
message?((message: ResizeMessage) => string)
The text screen readers hear after a change. Defaults to English.
示例: Several Boxes, and from Code
keykeyof State & string
The state key that holds the SwipeOpen row, or null.
示例: Actions Behind a Row
draftkeyof State & string
The state key that holds the SwipeDraft while a pointer swipes. Start it at null, and list it in live.
示例: Actions Behind a Row
onFullSwipe?((key: string, side: SwipeSide, details: { event: Event; }) => boolean)
Runs a side's first action when a swipe goes past fullSwipe of the row's width, and returns whether it did. Without it, a long swipe only opens the row.
示例: Full Swipes
fullSwipe?(() => number)
How far across the row a swipe runs the first action, as a fraction of its width.
示例: Full Swipes
disabled?((key: string) => boolean)
Whether a row can't be swiped.
示例: Full Swipes
delay?number
How long a press lasts before it's held, in milliseconds.
示例: Hold to Confirm
repeat?number
Runs onHold again this often while held, in milliseconds, like a stepper's button. Without it, onHold runs once.
示例: Repeat While Held
tolerance?number
How far a pointer can move before it's held, in pixels, before the press is canceled, like when a finger starts to scroll.
示例: Hold to Confirm
keys?string[]
The keys that press it while it has focus. A short press clicks it, as a pointer's does. An empty list leaves keys alone.
示例: Repeat While Held
disabled?(() => boolean)
Whether a press can't start, and a held one stops repeating.
示例: Repeat While Held
onPress?((details: HoldDetails) => boolean | void)
Runs as a press starts. Return false to ignore it, like a mouse press where only touch holds.
示例: Repeat While Held
onHold?((details: HoldDetails & { count: number; }) => boolean | void)
Runs once the press is held, then every repeat milliseconds. Return false to stop repeating, like at a bound; the press goes on until it ends.
示例: Repeat While Held
onEnd?((details: HoldEndDetails) => void)
Runs once when the press ends, released or canceled.
示例: Hold to Confirm
delay?number
How long a press lasts before it starts repeating, in milliseconds.
示例: Repeat While Held
repeat?number
How often it steps again while held, in milliseconds.
示例: Repeat While Held
keys?string[]
The keys that press it while it has focus. An empty list leaves keys to the browser, which clicks a button once per key press.
示例: Repeat While Held
disabled?(() => boolean)
Whether a press can't start, and a held one stops repeating.
示例: Repeat While Held
onPress?((details: HoldDetails) => boolean | void)
Runs as a press starts. Return false to ignore it.
示例: Repeat While Held
onStep?((details: RepeatDetails) => boolean | void)
Runs once for each press, then every repeat milliseconds while it's held. Return false to stop repeating, like at a bound.
示例: Repeat While Held
onEnd?((details: RepeatEndDetails) => void)
Runs once when a press ends, released or canceled, and after a click's step.
示例: Repeat While Held
value(state: State) => AreaValue
Reads the point from state, like (state) => state.value, or one made from other state, like a color's saturation and brightness.
示例: A Point on a Pad
set(value: AreaValue, details: { reason: AreaReason; event?: Event; }) => boolean
Asks for a new value and returns whether it went through. Pass the primitive's change: set: (value, details) => change("value", value, details).
示例: A Point on a Pad
x?(() => AreaAxis)
The x axis, left to right.
示例: A Point on a Pad
y?(() => AreaAxis)
The y axis, bottom to top, like a chart: a higher value sits higher.
示例: A Point on a Pad
valueText?((value: AreaValue) => string)
The text screen readers hear for the value. Defaults to each axis's label and percentage.
示例: What's Read Out, and When It Settles
onCommit?((value: AreaValue, details: { reason: AreaReason; event?: Event; }) => void)
Runs when a press or a drag ends, or a key changed the value, with the value it ended on, like Slider's onValueCommit.
示例: What's Read Out, and When It Settles
disabled?(() => boolean)
Whether it can't change.
示例: What's Read Out, and When It Settles
keykeyof State & string
The state key that holds the spans, an array of Span.
示例: Bookings on a Timeline
draftkeyof State & string
The state key that holds the SpansDraft while a pointer drags. Start it at null.
示例: Bookings on a Timeline
set(value: S[], details: { reason: SpansReason; event?: Event; id: string; action: SpanAction; }) => boolean
Asks for the new spans and returns whether they went through. Pass the primitive's change: set: (value, details) => change("spans", value, details).
示例: Bookings on a Timeline
min?(() => number)
Where tracks start, in their units.
示例: Bookings on a Timeline
max?(() => number)
Where tracks end.
示例: Bookings on a Timeline
step?(() => number)
What every start and end snaps to, and what arrows move by.
示例: Bookings on a Timeline
minSize?(() => number)
The shortest a span can be.
示例: Days That Run Down
maxSize?(() => number)
The longest a span can be.
示例: Days That Run Down
axis?"x" | "y"
The direction tracks run: y down, like a calendar's days, or x across, like a Gantt chart's rows.
示例: Bookings on a Timeline
tracks?(() => string[])
The tracks in the order the arrows across them go through. Defaults to the bound tracks in document order.
示例: Days That Run Down
overlap?boolean
Whether spans on one track can overlap. When they can't, a drag stops where it would.
示例: Bookings on a Timeline
create?((span: Span) => S | null)
Makes the span a press on a track starts to draw, with a new id and anything else it needs, like a title, or returns null to not draw. Runs on every press on an empty stretch of track. Without it, nothing is drawn.
示例: Bookings on a Timeline
size?(() => number | undefined)
How long a span a click on an empty track makes. Without it, a click makes none.
示例: Days That Run Down
disabled?((span: S) => boolean)
Whether a span can't change.
示例: Changing Ranges from Code
label?((span: S) => string)
What screen readers call a span, like "Standup, Tuesday 9:00 to 9:30". Defaults to its track and range.
示例: Bookings on a Timeline
message?((message: SpansMessage<S>) => string)
The text screen readers hear for each change. Defaults to English.
示例: Changing Ranges from Code
createAutoScroll?false | Omit<AutoScrollOptions, "ignore" | "onScroll">
How a drag near a scroller's edge scrolls it, or false not to.
示例: Days That Run Down
keykeyof State & string
The state key that holds the previewed option's key, or null.
示例: Press and Slide
slotstring
The slot whose parts are the options.
示例: Press and Slide
set?((value: string | null, details: { reason: PreviewReason; event?: Event; }) => boolean)
Asks for a new preview. Defaults to setting the state key; pass the primitive's change to fire onPreviewChange.
示例: Press and Slide
choose(key: string, details: { reason: "item-press"; event?: Event; }) => boolean
Chooses an option. Pass the primitive's change for its value.
示例: Press and Slide
value?(() => string | null)
The chosen option now, which previews as nothing.
示例: Press and Slide
disabled?((key: string) => boolean)
Whether an option can't be previewed or chosen.
示例: Hovering, and What's Read Out
label?((key: string) => string)
An option's name for screen readers. Defaults to its key.
示例: Hovering, and What's Read Out
message?((label: string) => string)
What screen readers hear when the keyboard previews one. Defaults to English.
示例: Hovering, and What's Read Out