平移和缩放画布,并连接它的节点。

createViewport 平移和缩放画布,createConnect 连接画布上的端口。

从 @ui-sdk/core 导入它们。移动节点、选择节点、用键盘导航和查找节点,分别使用拖动与调整大小、选择、焦点与按键和在页面中查找。

平移和缩放

视口是 { x, y, zoom }。x 和 y 以屏幕像素为单位,把画布原点放在外框内。zoom: 1 表示它的正常大小。

平移与缩放

先在状态里放一个视口,并把它标记为实时:

state: () => ({ viewport: { x: 0, y: 0, zoom: 1 } }),
live: ["viewport"],

在 api 里创建这个行为,并把它和 API 的其余部分一起返回:

const viewport = createViewport(context, {
  key: "viewport",
  surface: () => context.element("root"),
})

root 是外框,world 装下它内部的一切。连接外框的事件和 world 的实时样式:

root: slot({
  attrs: () => ({
    tabindex: "0",
    style: css({ position: "relative", overflow: "clip", "touch-action": "none" }),
  }),
  on: {
    wheel: (event, { api }) => api.viewport.wheel(event),
    pointerdown: (event, { el, api }) => {
      if (event.target === el) api.viewport.pointerdown(event)
    },
    keydown: (event, { api }) => api.viewport.keydown(event),
  },
}),
world: slot({
  attrs: () => ({ style: css({ position: "absolute", left: "0", top: "0" }) }),
  live: live((state, { api }) => ({ style: api.viewport.style(state) })),
}),

在你的组件里给外框一个可见的尺寸和无障碍名称。一次变换移动整个 world;实时样式让平移不会重新渲染每个节点。

import * as React from "react"
import {
  createViewport,
  css,
  definePrimitive,
  live,
  type Viewport,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type BoardState = { viewport: Viewport }

type BoardNoteProps = { value: string; x: number; y: number }

const home: Viewport = { x: 0, y: 0, zoom: 1 }

const board = definePrimitive({
  name: "board",
  state: (): BoardState => ({ viewport: home }),
  live: ["viewport"],
  api: (context) => {
    const viewport = createViewport<BoardState>(context, {
      key: "viewport",
      surface: () => context.element("root"),
    })
    return { viewport }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({
        tabindex: "0",
        "aria-roledescription": "board",
        style: css({
          position: "relative",
          overflow: "hidden",
          "touch-action": "none",
        }),
      }),
      on: {
        wheel: (event, { api }) => api.viewport.wheel(event),
        pointerdown: (event, { el, api }) =>
          event.target === el && api.viewport.pointerdown(event),
        keydown: (event, { api }) => api.viewport.keydown(event),
      },
    }),
    world: slot({
      attrs: () => ({
        style: css({ position: "absolute", left: "0", top: "0" }),
      }),
      live: live<BoardState, any, {}>((state, { api }) => ({
        style: api.viewport.style(state),
      })),
    }),
    note: slot<BoardNoteProps>({
      props: { value: "string", x: "number", y: "number" },
      attrs: (_state, { props }) => ({
        style: css({
          position: "absolute",
          left: `${props.x}px`,
          top: `${props.y}px`,
        }),
      }),
    }),
    reset: slot({
      attrs: () => ({ type: "button" }),
      press: ({ api }, event) =>
        api.viewport.setViewport(home, { reason: "imperative", event }),
    }),
  }),
})

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

const Board = parts.Root

const BoardWorld = parts.World

const BoardNote = parts.Note

const BoardReset = parts.Reset

const notes = [
  { value: "plan", text: "Plan the launch", x: 24, y: 24 },
  { value: "copy", text: "Write the copy", x: 144, y: 80 },
  { value: "ship", text: "Ship it", x: 40, y: 136 },
  { value: "far", text: "Found me", x: 520, y: 320 },
]

function Example() {
  return (
    <Board aria-label="Board">
      <BoardWorld>
        {notes.map((note) => (
          <BoardNote key={note.value} value={note.value} x={note.x} y={note.y}>
            {note.text}
          </BoardNote>
        ))}
      </BoardWorld>
      <BoardReset data-size="sm">Reset View</BoardReset>
    </Board>
  )
}

export {
  Board,
  board,
  BoardNote,
  BoardReset,
  BoardWorld,
  Example,
  type BoardNoteProps,
  type BoardState,
}
拖动空白画板或滚动来平移。双指捏合,或按住 Control 或 Command 滚动来缩放。聚焦画板后试试 +、− 和 0;Reset View 会恢复起始位置。

0 把缩放重置为 100%。要连同位置一起重置,就调用 viewport.setViewport({ x: 0, y: 0, zoom: 1 })。

从代码中适应、显示和缩放

用 fit 完整显示一个矩形。它的坐标以画布为单位:

viewport.fit(
  { left: 0, top: 0, right: 800, bottom: 600 },
  { padding: 16, maxZoom: 1 }
)
viewport.zoomBy(1.25)
viewport.panBy(80, 0)

不传点时,zoomBy 和 zoomTo 使用外框的中心。panBy 接收屏幕像素。在行为的选项里设置 minZoom 和 maxZoom 来限制缩放;默认值分别是 0.1 和 4。

节点获得焦点时,reveal 会把它带入视野。rectOf 以画布为单位读取元素的矩形:

sight: slot({
  on: {
    focus: (_event, { el, api }) => {
      if (el) api.viewport.reveal(api.viewport.rectOf(el), { padding: 16 })
    },
  },
}),

在外框上使用 overflow: clip,让原生焦点滚动不与视口冲突;或者用 bindFindable 让视口接管这些滚动。message 选项自定义缩放按键播报的内容:

message: (zoom) => `Map at ${Math.round(zoom * 100)} percent`,
import * as React from "react"
import {
  ArrowLeftIcon,
  ArrowRightIcon,
  MapPinIcon,
  ZoomInIcon,
  ZoomOutIcon,
} from "lucide-react"
import {
  createViewport,
  css,
  definePrimitive,
  live,
  type Viewport,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type Sight = { value: string; label: string; x: number; y: number }

type MapState = { viewport: Viewport; sights: Sight[] }

const pin = { width: 96, height: 28 }

const sights: Sight[] = [
  { value: "museum", label: "Museum", x: 24, y: 24 },
  { value: "park", label: "Park", x: 260, y: 120 },
  { value: "market", label: "Market", x: 80, y: 260 },
  { value: "tower", label: "Tower", x: 520, y: 60 },
  { value: "harbor", label: "Harbor", x: 640, y: 380 },
]

const map = definePrimitive({
  name: "map",
  state: (): MapState => ({ viewport: { x: 0, y: 0, zoom: 1 }, sights }),
  live: ["viewport"],
  api: (context) => {
    const { store } = context
    const viewport = createViewport<MapState>(context, {
      key: "viewport",
      surface: () => context.element("frame"),
      minZoom: () => 0.25,
      maxZoom: () => 2,
      message: (zoom) => `Map at ${Math.round(zoom * 100)} percent`,
    })
    const bounds = () => {
      const all = store.get().sights
      return {
        left: Math.min(...all.map((sight) => sight.x)),
        top: Math.min(...all.map((sight) => sight.y)),
        right: Math.max(...all.map((sight) => sight.x + pin.width)),
        bottom: Math.max(...all.map((sight) => sight.y + pin.height)),
      }
    }
    return {
      viewport,
      act(action: string) {
        if (action === "fit") {
          viewport.fit(bounds(), { padding: 16, maxZoom: 1 })
        } else if (action === "in") {
          viewport.zoomBy(1.25)
        } else if (action === "out") {
          viewport.zoomBy(1 / 1.25)
        } else if (action === "reset") {
          viewport.zoomTo(1)
        } else if (action === "left") {
          viewport.panBy(80, 0)
        } else if (action === "right") {
          viewport.panBy(-80, 0)
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot({}),
    frame: slot({
      attrs: () => ({
        tabindex: "0",
        "aria-roledescription": "map",
        style: css({
          position: "relative",
          overflow: "clip",
          "touch-action": "none",
        }),
      }),
      on: {
        wheel: (event, { api }) => api.viewport.wheel(event),
        pointerdown: (event, { el, api }) =>
          event.target === el && api.viewport.pointerdown(event),
        keydown: (event, { api }) => api.viewport.keydown(event),
      },
    }),
    world: slot({
      attrs: () => ({
        style: css({ position: "absolute", left: "0", top: "0" }),
      }),
      live: live<MapState, any, {}>((state, { api }) => ({
        style: api.viewport.style(state),
      })),
    }),
    sight: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { key }) => {
        const sight = state.sights.find((other) => other.value === key)!
        return {
          type: "button",
          style: css({
            position: "absolute",
            left: `${sight.x}px`,
            top: `${sight.y}px`,
            width: `${pin.width}px`,
            height: `${pin.height}px`,
          }),
        }
      },
      on: {
        focus: (_event, { el, api }) =>
          api.viewport.reveal(api.viewport.rectOf(el!), { padding: 16 }),
      },
    }),
    zoom: slot({
      live: live<MapState, any, {}>((state) => ({
        "data-zoom": `${Math.round(state.viewport.zoom * 100)}%`,
      })),
    }),
    action: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
      press: ({ api, key }) => api.act(key),
    }),
  }),
})

const parts = createParts(map, {
  root: "div",
  frame: "div",
  world: "div",
  sight: "button",
  zoom: "span",
  action: "button",
})

const SightsMap = parts.Root

const SightsMapFrame = parts.Frame

const SightsMapWorld = parts.World

const SightsMapSight = parts.Sight

const SightsMapZoom = parts.Zoom

const SightsMapAction = parts.Action

function Example() {
  return (
    <SightsMap>
      <SightsMapFrame aria-label="Sights">
        <SightsMapWorld>
          {sights.map((sight) => (
            <SightsMapSight key={sight.value} value={sight.value}>
              <MapPinIcon aria-hidden="true" />
              {sight.label}
            </SightsMapSight>
          ))}
        </SightsMapWorld>
      </SightsMapFrame>
      <div data-slot="row">
        <SightsMapAction data-size="sm" value="fit">
          Fit
        </SightsMapAction>
        <SightsMapAction data-size="sm" value="out" aria-label="Zoom out">
          <ZoomOutIcon aria-hidden="true" />
        </SightsMapAction>
        <SightsMapAction data-size="sm" value="in" aria-label="Zoom in">
          <ZoomInIcon aria-hidden="true" />
        </SightsMapAction>
        <SightsMapAction data-size="sm" value="reset">
          100%
        </SightsMapAction>
        <SightsMapAction data-size="sm" value="left" aria-label="Pan left">
          <ArrowLeftIcon aria-hidden="true" />
        </SightsMapAction>
        <SightsMapAction data-size="sm" value="right" aria-label="Pan right">
          <ArrowRightIcon aria-hidden="true" />
        </SightsMapAction>
        <SightsMapZoom />
      </div>
    </SightsMap>
  )
}

export {
  Example,
  map,
  type MapState,
  type Sight,
  SightsMap,
  SightsMapAction,
  SightsMapFrame,
  SightsMapSight,
  SightsMapWorld,
  SightsMapZoom,
}
按 Fit 查看每个景点。试试缩放和平移按钮,然后用 Tab 在景点之间移动:地图会把每个获得焦点的景点带入视野。

在页面中查找

在页面中查找(⌘F 或 Ctrl+F)能找到画布上任意位置的文本,但它通过滚动来显示匹配项,而视口用的是平移。把 world 放进一个填满外框的面板,并用 bindFindable 绑定这个面板:

pane: slot({
  attrs: () => ({
    style: css({
      position: "absolute",
      inset: "0",
      overflow: "scroll",
      "scrollbar-width": "none",
      "touch-action": "none",
      "pointer-events": "none",
    }),
  }),
  bind: (el, { api }) => api.viewport.bindFindable(el),
}),
world: slot({
  attrs: () => ({ style: css({ position: "absolute", left: "0", top: "0", "pointer-events": "auto" }) }),
  live: live((state, { api }) => ({ style: api.viewport.style(state) })),
}),

面板必须是用户能滚动的元素,使用 overflow: scroll,因为在页面中查找不会滚动 overflow: hidden 的元素;scrollbar-width: none 会隐藏它的滚动条。保留外框的 overflow: clip,并把重置按钮之类的控件留在外框里、面板之外。面板会把空白处的按压和转轮事件传给外框,所以外框的处理函数照常工作。

浏览器在面板里的每次滚动都会变成原因为 find-in-page 的平移,于是匹配项会按浏览器自己的显示方式进入视野,带着它自己的高亮和计数。其他会滚动到元素的行为也一样,比如 scrollIntoView 或指向元素 id 的链接;用 Tab 移到视野外的节点时,会以 focus-in 为原因平移。

面板静止时,滚动位置停在远离原点的地方,并用一个空元素留出空间,这样无论节点在视野的哪一侧,浏览器都能朝它滚动。绑定时,world 的 style 会跟着移动;面板里的其他东西会滚走,所以面板只装 world。平滑的 scrollIntoView 只按第一步平移;要给平移加动画,就调用 reveal。

import * as React from "react"
import {
  createViewport,
  css,
  definePrimitive,
  live,
  type Viewport,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type MapState = { viewport: Viewport }

type MapNoteProps = { value: string; x: number; y: number }

const home: Viewport = { x: 0, y: 0, zoom: 1 }

const map = definePrimitive({
  name: "map",
  state: (): MapState => ({ viewport: home }),
  live: ["viewport"],
  api: (context) => {
    const viewport = createViewport<MapState>(context, {
      key: "viewport",
      surface: () => context.element("root"),
    })
    return { viewport }
  },
  slots: (slot) => ({
    root: slot({
      attrs: () => ({
        tabindex: "0",
        "aria-roledescription": "map",
        style: css({
          position: "relative",
          overflow: "clip",
          "touch-action": "none",
        }),
      }),
      on: {
        wheel: (event, { api }) => api.viewport.wheel(event),
        pointerdown: (event, { el, api }) =>
          event.target === el && api.viewport.pointerdown(event),
        keydown: (event, { api }) => api.viewport.keydown(event),
      },
    }),
    pane: slot({
      attrs: () => ({
        style: css({
          position: "absolute",
          inset: "0",
          overflow: "scroll",
          "scrollbar-width": "none",
          "touch-action": "none",
          "pointer-events": "none",
        }),
      }),
      bind: (el, { api }) => api.viewport.bindFindable(el),
    }),
    world: slot({
      attrs: () => ({
        style: css({
          position: "absolute",
          left: "0",
          top: "0",
          "pointer-events": "auto",
        }),
      }),
      live: live<MapState, any, {}>((state, { api }) => ({
        style: api.viewport.style(state),
      })),
    }),
    note: slot<MapNoteProps>({
      props: { value: "string", x: "number", y: "number" },
      attrs: (_state, { props }) => ({
        style: css({
          position: "absolute",
          left: `${props.x}px`,
          top: `${props.y}px`,
        }),
      }),
    }),
    reset: slot({
      attrs: () => ({ type: "button" }),
      press: ({ api }, event) =>
        api.viewport.setViewport(home, { reason: "imperative", event }),
    }),
  }),
})

const parts = createParts(map, {
  root: "div",
  pane: "div",
  world: "div",
  note: "div",
  reset: "button",
})

const notes = [
  { value: "harbor", text: "Harbor", x: 112, y: 88 },
  { value: "east", text: "East lighthouse", x: 760, y: 96 },
  { value: "south", text: "South lighthouse", x: 120, y: 640 },
  { value: "west", text: "West lighthouse", x: -560, y: 80 },
  { value: "north", text: "North lighthouse", x: 104, y: -480 },
]

function Example() {
  return (
    <div data-slot="stack">
      <p data-slot="hint">
        Search <span data-slot="viewport-term">lighthouse</span> with ⌘F or
        Ctrl+F
      </p>
      <parts.Root aria-label="Map">
        <parts.Pane>
          <parts.World>
            {notes.map((note) => (
              <parts.Note
                key={note.value}
                value={note.value}
                x={note.x}
                y={note.y}
              >
                {note.text}
              </parts.Note>
            ))}
          </parts.World>
        </parts.Pane>
        <parts.Reset data-size="sm">Reset View</parts.Reset>
      </parts.Root>
    </div>
  )
}

export { Example }
按 ⌘F 或 Ctrl+F,搜索 lighthouse。每个灯塔都在地图外不同的方向;按 Enter 从一个跳到下一个,地图会平移到每一个。

屏幕坐标与画布坐标

指针事件给出屏幕坐标。在往画布上放置东西之前,先把它们转换过来:

const point = viewport.toCanvas(event.clientX, event.clientY)

toScreen(point) 转换回客户端坐标,适合缩放后的 world 外部的标签。visible() 给出当前视野内的矩形,get() 返回视口。

默认情况下,行为直接写入它的状态键。要让组件控制视口,就配合 set 使用变更模式:

set: (value, details) => change("viewport", value, details),

变更会报告原因:wheel、drag、pinch、zoom-key、focus-in、find-in-page 或 imperative。

控制台
import * as React from "react"
import {
  createChange,
  createViewport,
  css,
  definePrimitive,
  live,
  type ChangeDetails,
  type Viewport,
  type ViewportReason,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"
import { useLog } from "./log"

type Point = { x: number; y: number }

type DotsState = { viewport: Viewport; dots: Point[] }

type DotsOptions = {
  viewport?: Viewport
  onViewportChange?: (
    viewport: Viewport,
    details: ChangeDetails<ViewportReason>
  ) => void
}

const round = (point: Point) => `${Math.round(point.x)}, ${Math.round(point.y)}`

const dots = definePrimitive({
  name: "dots",
  options: { viewport: "value", onViewportChange: "callback" },
  state: (options: DotsOptions): DotsState => ({
    viewport: options.viewport ?? { x: 0, y: 0, zoom: 1 },
    dots: [],
  }),
  sync: (options) => (options.viewport ? { viewport: options.viewport } : {}),
  live: ["viewport"],
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const viewport = createViewport<DotsState>(context, {
      key: "viewport",
      surface: () => context.element("root"),
      set: (value, details) => change("viewport", value, details),
    })
    return {
      viewport,
      drop(event: MouseEvent) {
        store.set({
          dots: [
            ...store.get().dots,
            viewport.toCanvas(event.clientX, event.clientY),
          ],
        })
      },
      labelAt(state: DotsState) {
        const surface = context.element("root")
        const dot = state.dots.at(-1)
        if (!surface || !dot) {
          return undefined
        }
        const box = surface.getBoundingClientRect()
        const at = viewport.toScreen(dot)
        return { x: at.x - box.left, y: at.y - box.top }
      },
      inView() {
        const { left, top, right, bottom } = viewport.visible()
        return `${round({ x: left, y: top })} to ${round({ x: right, y: bottom })}`
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { dots: Point[] }>({
      state: (state) => ({ dots: state.dots }),
      attrs: () => ({
        tabindex: "0",
        "aria-roledescription": "board",
        style: css({
          position: "relative",
          overflow: "clip",
          "touch-action": "none",
        }),
      }),
      on: {
        wheel: (event, { api }) => api.viewport.wheel(event),
        pointerdown: (event, { el, api }) =>
          event.target === el && api.viewport.pointerdown(event),
        keydown: (event, { api }) => api.viewport.keydown(event),
        dblclick: (event, { el, api }) =>
          event.target === el && api.drop(event),
      },
    }),
    world: slot({
      attrs: () => ({
        style: css({
          position: "absolute",
          left: "0",
          top: "0",
          "pointer-events": "none",
        }),
      }),
      live: live<DotsState, any, {}>((state, { api }) => ({
        style: api.viewport.style(state),
      })),
    }),
    label: slot({
      live: live<DotsState, any, {}>((state, { api }) => {
        const at = api.labelAt(state)
        const dot = state.dots.at(-1)
        return at && dot
          ? {
              "data-at": round(dot),
              style: css({
                position: "absolute",
                left: `${at.x}px`,
                top: `${at.y}px`,
                "pointer-events": "none",
              }),
            }
          : { hidden: "" }
      }),
    }),
    view: slot({
      live: live<DotsState, any, {}>((state, { api }) => ({
        "data-view": state.viewport && api.inView(),
      })),
    }),
  }),
})

const parts = createParts(dots, {
  root: "div",
  world: "div",
  label: "span",
  view: "span",
})

const Dots = parts.Root

const DotsWorld = parts.World

const DotsLabel = parts.Label

const DotsView = parts.View

function Example() {
  const [viewport, setViewport] = React.useState<Viewport>({
    x: 0,
    y: 0,
    zoom: 1,
  })
  const log = useLog()
  const last = React.useRef("")
  return (
    <Dots
      aria-label="Dots"
      viewport={viewport}
      onViewportChange={(next, details) => {
        setViewport(next)
        const message = `Moved by ${details.reason}, zoom ${Math.round(next.zoom * 100)}%`
        if (message !== last.current) {
          log(message)
        }
        last.current = message
      }}
    >
      {({ dots }) => (
        <>
          <DotsWorld>
            {dots.map((dot, index) => (
              <span
                key={index}
                data-slot="viewport-dot"
                style={{ left: dot.x, top: dot.y }}
              />
            ))}
          </DotsWorld>
          <DotsView />
          <DotsLabel />
        </>
      )}
    </Dots>
  )
}

export {
  Dots,
  dots,
  DotsLabel,
  type DotsOptions,
  type DotsState,
  DotsView,
  DotsWorld,
  Example,
  type Point,
}
双击添加一个圆点。平移或缩放后再添加一个:它会落在你点击的位置。画布缩放时,最新圆点的标签保持原来的大小。

连接

createConnect 跟踪从一个端口到另一个端口的一条线。哪些端口对可以连接、连接后保存什么,由你决定。

绘制连接

在状态里加一个 connecting 字段,初始值为 null as ConnectDraft | null,并把它列进 live。然后在 api 里创建这个行为:

const connect = createConnect(context, {
  slot: "port",
  draft: "connecting",
  canConnect: (from, to) => from.endsWith(":out") && to.endsWith(":in"),
  point: (x, y) => viewport.toCanvas(x, y),
  connect: (from, to, details) =>
    change("edges", [...context.store.get().edges, { from, to }], details),
})

这里,端口键以 :out 或 :in 结尾。canConnect 只接受输出到输入的端口对。你可以在那里加上自己的检查,比如拒绝同一节点上的两个端口。point 把线的自由端放进画布坐标。

给每个端口一个 value,比如 "prompt:out" 或 "answer:in",并接上它的指针处理函数。role 会给出 source、target 或 candidate,用于设置样式:

port: slot<{ value: string }>({
  props: { value: "string" },
  live: live((state, { api, key }) => ({ "data-connect": api.connect.role(state, key) })),
  on: {
    pointerdown: (event, { el, api, key }) => {
      if (el) api.connect.pointerdown(event, key, el)
    },
  },
}),

绘制过程中,connecting 保存 { from, to, x, y, keyboard }。把这个草稿和已保存的边一起渲染,to 为 null 时用 x 和 y 作为它的自由端。

为了键盘操作,在节点的动作里调用 connect.start(portKey),再把它的按键事件传给 connect.keydown(event)。方向键选择该方向上的有效端口;Enter 或 Space 连接;Escape 或 Tab 取消。

import * as React from "react"
import {
  createChange,
  createConnect,
  css,
  definePrimitive,
  live,
  type ChangeDetails,
  type ConnectDraft,
  type ConnectReason,
} from "@ui-sdk/core"
import { createParts, usePart, type PartProps } from "@ui-sdk/react/primitive"

type FlowNode = { value: string; label: string; x: number; y: number }

type FlowEdge = { from: string; to: string }

type FlowState = {
  nodes: FlowNode[]
  edges: FlowEdge[]
  connecting: ConnectDraft | null
}

type FlowOptions = {
  nodes: FlowNode[]
  onEdgesChange?: (
    edges: FlowEdge[],
    details: ChangeDetails<ConnectReason>
  ) => void
}

const size = { width: 112, height: 40 }

const nodeOf = (port: string) => port.slice(0, port.lastIndexOf(":"))

function portPoint(nodes: FlowNode[], port: string) {
  const node = nodes.find((other) => other.value === nodeOf(port))!
  return {
    x: node.x + (port.endsWith(":out") ? size.width : 0),
    y: node.y + size.height / 2,
  }
}

function curve(from: { x: number; y: number }, to: { x: number; y: number }) {
  const reach = Math.max(30, Math.hypot(to.x - from.x, to.y - from.y) / 2)
  return `M${from.x},${from.y} C${from.x + reach},${from.y} ${to.x - reach},${to.y} ${to.x},${to.y}`
}

const flow = definePrimitive({
  name: "flow",
  options: { nodes: "value", onEdgesChange: "callback" },
  state: (options: FlowOptions): FlowState => ({
    nodes: options.nodes,
    edges: [],
    connecting: null,
  }),
  live: ["connecting"],
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const connect = createConnect<FlowState>(context, {
      slot: "port",
      draft: "connecting",
      canConnect: (from, to) =>
        from.endsWith(":out") &&
        to.endsWith(":in") &&
        nodeOf(from) !== nodeOf(to) &&
        !store.get().edges.some((edge) => edge.from === from && edge.to === to),
      point: (clientX, clientY) => {
        const box = context.element("root")!.getBoundingClientRect()
        return { x: clientX - box.left, y: clientY - box.top }
      },
      label: (port) =>
        store.get().nodes.find((node) => node.value === nodeOf(port))!.label,
      connect: (from, to, details) =>
        change("edges", [...store.get().edges, { from, to }], details),
    })
    return {
      connect,
      nodeKeydown(event: KeyboardEvent, node: string) {
        if (connect.keydown(event)) {
          return
        }
        if (event.key.toLowerCase() !== "c" || event.ctrlKey || event.metaKey) {
          return
        }
        event.preventDefault()
        connect.start(`${node}:out`)
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { edges: FlowEdge[] }>({
      state: (state) => ({ edges: state.edges }),
      attrs: () => ({ style: css({ position: "relative" }) }),
    }),
    node: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { key }) => {
        const node = state.nodes.find((other) => other.value === key)!
        const to = state.edges
          .filter((edge) => nodeOf(edge.from) === key)
          .map(
            (edge) =>
              state.nodes.find((other) => other.value === nodeOf(edge.to))!
                .label
          )
        return {
          role: "button",
          tabindex: "0",
          "aria-description": to.length
            ? `Connected to ${to.join(", ")}.`
            : undefined,
          style: css({
            position: "absolute",
            left: `${node.x}px`,
            top: `${node.y}px`,
            width: `${size.width}px`,
            height: `${size.height}px`,
          }),
        }
      },
      on: { keydown: (event, { api, key }) => api.nodeKeydown(event, key) },
    }),
    port: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (_state, { key }) => ({
        "aria-hidden": "true",
        "data-side": key.endsWith(":out") ? "right" : "left",
        style: "touch-action:none",
      }),
      live: live<FlowState, any, { value: string }>((state, { api, key }) => ({
        "data-connect": api.connect.role(state, key),
      })),
      on: {
        pointerdown: (event, { el, api, key }) =>
          api.connect.pointerdown(event, key, el!),
      },
    }),
    edge: slot<{ value: string; from: string; to: string }>({
      props: { value: "string", from: "string", to: "string" },
      attrs: (state, { props }) => ({
        d: curve(
          portPoint(state.nodes, props.from),
          portPoint(state.nodes, props.to)
        ),
      }),
    }),
    draft: slot({
      live: live<FlowState, any, {}>((state) => {
        const draft = state.connecting
        if (!draft) {
          return { d: "" }
        }
        const end = draft.to ? portPoint(state.nodes, draft.to) : draft
        return { d: curve(portPoint(state.nodes, draft.from), end) }
      }),
    }),
  }),
})

const parts = createParts(flow, {
  root: "div",
  node: "div",
  port: "span",
  draft: "path",
})

const Flow = parts.Root

const FlowNode = parts.Node

const FlowPort = parts.Port

function FlowEdgePath({
  edge,
  ...props
}: { edge: FlowEdge } & PartProps<"path">) {
  return usePart(
    flow,
    "edge",
    { value: `${edge.from}>${edge.to}`, from: edge.from, to: edge.to },
    props,
    "path"
  )
}

const FlowDraft = parts.Draft

const nodes: FlowNode[] = [
  { value: "prompt", label: "Prompt", x: 8, y: 70 },
  { value: "answer", label: "Answer", x: 176, y: 16 },
  { value: "summary", label: "Summary", x: 176, y: 124 },
]

function Example() {
  return (
    <Flow nodes={nodes}>
      {({ edges }) => (
        <>
          <svg data-slot="connect-edges">
            {edges.map((edge) => (
              <FlowEdgePath key={`${edge.from}>${edge.to}`} edge={edge} />
            ))}
            <FlowDraft />
          </svg>
          {nodes.map((node) => (
            <FlowNode
              key={node.value}
              value={node.value}
              aria-label={node.label}
            >
              {node.label}
              {node.value === "prompt" ? (
                <FlowPort value="prompt:out" />
              ) : (
                <FlowPort value={`${node.value}:in`} />
              )}
            </FlowNode>
          ))}
        </>
      )}
    </Flow>
  )
}

export {
  Example,
  flow,
  Flow,
  FlowDraft,
  FlowEdgePath,
  FlowNode,
  FlowPort,
  type FlowEdge,
  type FlowOptions,
  type FlowState,
}
从 Prompt 的输出拖到一个输入,落在 Answer 或 Summary 上。或者聚焦 Prompt,按 C,用方向键选一个输入,再按 Enter。Escape 取消。

这个行为会播报每一步。给它一个 label 函数,提供易读的端口名称。如果端口对辅助技术隐藏,要保留节点键盘动作的可访问性,并用文字描述它的连接,比如 aria-description="Connected to Answer."。

吸附、文字和代码

radius 控制指针要离多近,端口才会成为目标。它以屏幕像素为单位,所以在不同缩放级别下保持一致。默认值是 28。

默认播报不合适时,覆盖 message。connectMessage 为其他步骤提供默认播报:

radius: () => 48,
message: (message, label) =>
  message.type === "connect"
    ? `${label(message.from)} into ${label(message.to)}.`
    : connectMessage(message, label),

你也可以从代码里连接:

if (connect.start("synth")) {
  connect.target("ch3")
  connect.commit({ reason: "connect-key" })
}

active() 告诉你是否有连接正在进行;cancel() 清除它的草稿。connect 回调决定保存什么。在这个接线板里,再次连接已有的端口对会移除它的线缆。

import * as React from "react"
import {
  connectMessage,
  createChange,
  createConnect,
  css,
  definePrimitive,
  live,
  type ConnectDraft,
} from "@ui-sdk/core"
import { createParts } from "@ui-sdk/react/primitive"

type Cable = { from: string; to: string }

type BayState = { cables: Cable[]; drawing: ConnectDraft | null }

const sources = ["mic", "guitar", "synth"]
const channels = ["ch1", "ch2", "ch3"]
const names: Record<string, string> = {
  mic: "Mic",
  guitar: "Guitar",
  synth: "Synth",
  ch1: "Channel 1",
  ch2: "Channel 2",
  ch3: "Channel 3",
}

function jack(port: string) {
  const source = sources.includes(port)
  const row = (source ? sources : channels).indexOf(port)
  return { x: source ? 104 : 184, y: 20 + row * 48 }
}

function curve(from: { x: number; y: number }, to: { x: number; y: number }) {
  const reach = Math.max(30, Math.hypot(to.x - from.x, to.y - from.y) / 2)
  return `M${from.x},${from.y} C${from.x + reach},${from.y} ${to.x - reach},${to.y} ${to.x},${to.y}`
}

const bay = definePrimitive({
  name: "bay",
  state: (): BayState => ({ cables: [], drawing: null }),
  live: ["drawing"],
  api: (context) => {
    const { store } = context
    const change = createChange(context)
    const connect = createConnect<BayState>(context, {
      slot: "jack",
      draft: "drawing",
      canConnect: (from, to) => sources.includes(from) && channels.includes(to),
      point: (clientX, clientY) => {
        const box = context.element("root")!.getBoundingClientRect()
        return { x: clientX - box.left, y: clientY - box.top }
      },
      radius: () => 48,
      label: (port) => names[port],
      message: (message, label) =>
        message.type === "connect"
          ? `${label(message.from)} into ${label(message.to)}.`
          : connectMessage(message, label),
      connect: (from, to, details) => {
        const { cables } = store.get()
        const patched = cables.some(
          (cable) => cable.from === from && cable.to === to
        )
        const next = patched
          ? cables.filter((cable) => cable.from !== from || cable.to !== to)
          : [...cables, { from, to }]
        return change("cables", next, details)
      },
    })
    return {
      connect,
      sourceKeydown(event: KeyboardEvent, source: string) {
        if (connect.keydown(event)) {
          return
        }
        if (event.key !== "Enter") {
          return
        }
        event.preventDefault()
        connect.start(source)
      },
      act(action: string) {
        if (action === "cancel") {
          return connect.active() && connect.cancel()
        }
        const [from, to] = action.split("-")
        if (connect.start(from)) {
          connect.target(to)
          connect.commit({ reason: "connect-key" })
        }
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { cables: Cable[] }>({
      state: (state) => ({ cables: state.cables }),
      attrs: () => ({ style: css({ position: "relative" }) }),
    }),
    source: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (state, { key }) => ({
        type: "button",
        "aria-description": state.cables.some((cable) => cable.from === key)
          ? `Into ${state.cables
              .filter((cable) => cable.from === key)
              .map((cable) => names[cable.to])
              .join(", ")}.`
          : undefined,
      }),
      on: { keydown: (event, { api, key }) => api.sourceKeydown(event, key) },
    }),
    jack: slot<{ value: string }>({
      props: { value: "string" },
      attrs: (_state, { key }) => {
        const { x, y } = jack(key)
        return {
          "aria-hidden": "true",
          style: css({
            position: "absolute",
            left: `${x}px`,
            top: `${y}px`,
            "touch-action": "none",
          }),
        }
      },
      live: live<BayState, any, { value: string }>((state, { api, key }) => ({
        "data-connect": api.connect.role(state, key),
      })),
      on: {
        pointerdown: (event, { el, api, key }) =>
          api.connect.pointerdown(event, key, el!),
      },
    }),
    cable: slot<{ value: string; from: string; to: string }>({
      props: { value: "string", from: "string", to: "string" },
      attrs: (_state, { props }) => ({
        d: curve(jack(props.from), jack(props.to)),
      }),
    }),
    draft: slot({
      live: live<BayState, any, {}>((state) => {
        const draft = state.drawing
        if (!draft) {
          return { d: "" }
        }
        return { d: curve(jack(draft.from), draft.to ? jack(draft.to) : draft) }
      }),
    }),
    action: slot<{ value: string }>({
      props: { value: "string" },
      attrs: () => ({ type: "button" }),
      press: ({ api, key }) => api.act(key),
    }),
  }),
})

const parts = createParts(bay, {
  root: "div",
  source: "button",
  jack: "span",
  cable: "path",
  draft: "path",
  action: "button",
})

const Bay = parts.Root

const BaySource = parts.Source

const BayJack = parts.Jack

const BayCable = parts.Cable

const BayDraft = parts.Draft

const BayAction = parts.Action

function Example() {
  return (
    <Bay>
      {({ cables }) => (
        <>
          <div data-slot="connect-canvas">
            <svg data-slot="connect-edges">
              {cables.map((cable) => (
                <BayCable
                  key={`${cable.from}-${cable.to}`}
                  value={`${cable.from}-${cable.to}`}
                  from={cable.from}
                  to={cable.to}
                />
              ))}
              <BayDraft />
            </svg>
            {sources.map((source, index) => (
              <BaySource
                key={source}
                value={source}
                style={{ "--row": index } as React.CSSProperties}
              >
                {names[source]}
              </BaySource>
            ))}
            {channels.map((channel, index) => (
              <span
                key={channel}
                data-slot="connect-channel"
                style={{ "--row": index } as React.CSSProperties}
              >
                {names[channel]}
              </span>
            ))}
            {[...sources, ...channels].map((port) => (
              <BayJack key={port} value={port} />
            ))}
          </div>
          <div data-slot="row">
            <BayAction data-size="sm" value="synth-ch3">
              Synth into 3
            </BayAction>
            <BayAction data-size="sm" value="cancel">
              Cancel
            </BayAction>
          </div>
        </>
      )}
    </Bay>
  )
}

export {
  Bay,
  bay,
  BayAction,
  BayCable,
  BayDraft,
  BayJack,
  BaySource,
  type BayState,
  type Cable,
  Example,
}
把源插孔拖向一个通道,再连接同一对端口即可拔掉。试试把 Synth 连到 3,或者聚焦一个源并按 Enter 开始;用方向键选择,Enter 连接,Escape 取消。

可访问性

给每个指针动作一条键盘路径,并在画布旁说明它。把获得焦点的节点带入视野,并用文字和线条一起描述连接。

要做一个完整的编辑器,把这些辅助函数与在二维中移动、选择和空间焦点组合起来。测试涵盖对结果的键盘和可访问性检查。

API 参考

keykeyof State & string
The state key that holds the Viewport. List it in live, so panning renders nothing.
示例: Pan and Zoom
surface() => HTMLElement | null
The element that clips the canvas and takes the gestures.
示例: Pan and Zoom
set?((value: Viewport, details: { reason: ViewportReason; event?: Event; }) => boolean)
Asks for a new viewport. Defaults to setting the state key; pass the primitive's change to make it controllable.
示例: Screen and Canvas Points
minZoom?(() => number)
示例: Fit, Reveal and Zoom from Code
maxZoom?(() => number)
示例: Fit, Reveal and Zoom from Code
message?((zoom: number) => string)
What screen readers hear after a zoom key. Defaults to English, like "Zoom 150%".
示例: Fit, Reveal and Zoom from Code
slotstring
The slot whose parts are ports.
示例: Draw a Connection
draftkeyof State & string
The state key that holds the ConnectDraft while one is drawn. Start it at null, and list it in live.
示例: Draw a Connection
connect(from: string, to: string, details: { reason: ConnectReason; event?: Event; }) => boolean
Makes the connection and returns whether it went through.
示例: Draw a Connection
canConnect?((from: string, to: string) => boolean)
Whether from can connect to to. Defaults to any other port.
示例: Draw a Connection
point?((clientX: number, clientY: number) => { x: number; y: number; })
Turns a point on screen into your units, like a canvas viewport's toCanvas. Defaults to client pixels.
示例: Draw a Connection
radius?(() => number)
How near, in screen pixels, a pointer must come to a port to snap to it.
示例: Snapping, Words and Code
label?((key: string) => string)
A port's name for screen readers. Defaults to its key.
示例: Draw a Connection
message?((message: ConnectMessage, label: (key: string) => string) => string)
What screen readers hear. Defaults to English.
示例: Snapping, Words and Code