AI-native design editor. Open-source Figma alternative.
feat: draw and edit connectors in the editor, scripts, and agents (#1235)
Danila Poyarkovbf1b07d2dbb9
diff --git a/changes/1235/added.md b/changes/1235/added.mdnew file mode 100644index 000000000..fe49899c6--- /dev/null+++ b/changes/1235/added.md@@ -0,0 +1,2 @@+- A connector tool, shown from Customize toolbar, draws connectors between layers or points. Their end handles reattach them, double-click types a label, the Design panel sets line type and end caps, and scripts and agents create and edit them through `figma.createConnector()` and `create_connector` (#616).+- Figma's filled triangle, diamond, and circle line caps draw instead of showing no head.diff --git a/packages/core/src/canvas/overlays/connectors.ts b/packages/core/src/canvas/overlays/connectors.tsnew file mode 100644index 000000000..f34b47333--- /dev/null+++ b/packages/core/src/canvas/overlays/connectors.ts@@ -0,0 +1,116 @@+import type { Canvas, Paint } from 'canvaskit-wasm'++import { connectorSublayers, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'+import Matrix from '@open-pencil/scene-graph/matrix'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import type { SkiaRenderer } from '#core/canvas/renderer'+import type { ConnectorTarget } from '#core/editor/connectors/attach'+import {+ connectorScreenEnds,+ createSceneGeometry,+ viewportMatrix,+ type RotationPreview+} from '#core/geometry'+import { vectorNetworkToPath } from '#core/vector'++/** Radius of a connector's end handles and of a layer's magnet dots, in screen pixels. */+export const CONNECTOR_HANDLE_RADIUS = 5+const MAGNET_DOT_RADIUS = 4++/** A connector's line traced in screen space with `paint`. */+function strokeConnectorLine(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ connector: SceneNode,+ paint: Paint,+ preview?: RotationPreview | null+) {+ const line = connectorSublayers(graph, connector)?.line+ if (!line?.vectorNetwork) return+ // Traced as drawn, its elbows rounded.+ const paths = vectorNetworkToPath(r.ck, line.vectorNetwork, line.cornerRadius)+ canvas.save()+ canvas.concat(createSceneGeometry(graph, preview).screenMatrix(line, r))+ for (const path of paths) {+ canvas.drawPath(path, paint)+ path.delete()+ }+ canvas.restore()+}++function drawDot(r: SkiaRenderer, canvas: Canvas, point: Vector, radius: number, filled: boolean) {+ r.auxFill.setMaskFilter(null)+ r.auxFill.setColor(filled ? r.selColor() : r.ck.WHITE)+ canvas.drawCircle(point.x, point.y, radius, r.auxFill)+ r.auxStroke.setPathEffect(null)+ r.auxStroke.setStrokeWidth(1)+ r.auxStroke.setColor(r.selColor())+ canvas.drawCircle(point.x, point.y, radius, r.auxStroke)+}++/** A connector's hover outline: its line, not the box around its route. */+export function drawConnectorHover(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ connector: SceneNode,+ preview?: RotationPreview | null+) {+ r.auxStroke.setPathEffect(null)+ r.auxStroke.setColor(r.selColor())+ r.auxStroke.setStrokeWidth(2 / r.zoom)+ strokeConnectorLine(r, canvas, graph, connector, r.auxStroke, preview)+}++/** A selected connector, as FigJam shows it: its line outlined and a handle at each end. */+export function drawConnectorSelection(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ connector: SceneNode,+ preview?: RotationPreview | null+) {+ drawConnectorHover(r, canvas, graph, connector, preview)+ const ends = connectorScreenEnds(graph, connector, r, preview)+ if (!ends) return+ drawDot(r, canvas, ends.start, CONNECTOR_HANDLE_RADIUS, false)+ drawDot(r, canvas, ends.end, CONNECTOR_HANDLE_RADIUS, false)+}++/**+ * The layer a connector end would attach to: its outline and a dot at each side's midpoint, the+ * dot of the side it would take filled.+ */+export function drawConnectorTarget(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ target: ConnectorTarget | null | undefined,+ preview?: RotationPreview | null+) {+ const node = target ? graph.getNode(target.nodeId) : undefined+ if (!target || !node) return+ r.drawHoverHighlight(canvas, graph, node.id, preview)+ const page = graph.pageOf(node.id)+ if (!page) return+ const box = getAxisAlignedBoundsInParent([node], page, graph)+ const cx = box.x + box.width / 2+ const cy = box.y + box.height / 2+ const sides = [+ ['TOP', cx, box.y],+ ['RIGHT', box.x + box.width, cy],+ ['BOTTOM', cx, box.y + box.height],+ ['LEFT', box.x, cy]+ ] as const+ const screen = Matrix.mapPoints(+ viewportMatrix(r),+ sides.flatMap(([, x, y]) => [x, y])+ )+ sides.forEach(([side], index) => {+ const point = { x: screen[index * 2], y: screen[index * 2 + 1] }+ drawDot(r, canvas, point, MAGNET_DOT_RADIUS, side === target.magnet)+ })+}diff --git a/packages/core/src/canvas/overlays/selection.ts b/packages/core/src/canvas/overlays/selection.tsindex 761b29713..a1a796cd2 100644--- a/packages/core/src/canvas/overlays/selection.ts+++ b/packages/core/src/canvas/overlays/selection.ts@@ -6,6 +6,7 @@ import { computeBounds, rotatedCorners } from '@open-pencil/scene-graph/geometryimport Matrix from '@open-pencil/scene-graph/matrix'import type { Vector } from '@open-pencil/scene-graph/primitives'+import { drawConnectorHover, drawConnectorSelection } from '#core/canvas/overlays/connectors'import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'import {HANDLE_HALF_SIZE,@@ -39,6 +40,10 @@ export function drawHoverHighlight(): void {const node = hoveredNodeId ? graph.getNode(hoveredNodeId) : undefinedif (!node) return+ if (node.type === 'CONNECTOR') {+ drawConnectorHover(r, canvas, graph, node, preview)+ return+ }r.auxStroke.setStrokeWidth((node.type === 'SECTION' ? SECTION_HOVER_STROKE_WIDTH : 1) / r.zoom)r.auxStroke.setColor(r.outlineColor(node, graph))r.auxStroke.setPathEffect(null)@@ -111,7 +116,9 @@ function drawSingleSelection(r.selectionPaint.setStrokeWidth(1 / r.zoom)const rotation = node.rotation- if (isPathText) {+ if (node.type === 'CONNECTOR') {+ drawConnectorSelection(r, canvas, graph, node, preview)+ } else if (isPathText) {drawTextPathSelection(r, canvas, node, rotation, graph, preview)if (!editing) r.drawSelectionLabels(canvas, graph, selectedIds, overlays)} else {diff --git a/packages/core/src/canvas/renderer/overlay-pass.ts b/packages/core/src/canvas/renderer/overlay-pass.tsindex db634c9de..62076d903 100644--- a/packages/core/src/canvas/renderer/overlay-pass.ts+++ b/packages/core/src/canvas/renderer/overlay-pass.ts@@ -6,6 +6,7 @@ import { drawGuides } from '#core/canvas/guides/draw'import { drawIssueHighlight, drawIssueMarkers } from '#core/canvas/issues/draw'import { layoutIssueMarkers } from '#core/canvas/issues/layout'import { drawComponentSetBorders } from '#core/canvas/overlays/component-sets'+import { drawConnectorTarget } from '#core/canvas/overlays/connectors'import { drawDropTarget, drawEditingText } from '#core/canvas/overlays/feedback'import { drawGradientHandles } from '#core/canvas/overlays/gradient-handles'import { drawLayoutOutlines } from '#core/canvas/overlays/layout-outlines'@@ -113,6 +114,7 @@ export function drawOverlayPass(drawIssueHighlight(r, canvas, graph, overlays.designIssues?.highlight, overlays.rotationPreview)r.drawEnteredContainer(canvas, graph, overlays.enteredContainerId, overlays.rotationPreview)drawDropTarget(r, canvas, graph, overlays.dropTargetId, overlays.rotationPreview)+ drawConnectorTarget(r, canvas, graph, overlays.connectorTarget, overlays.rotationPreview)drawEditingText(r, canvas, graph, overlays)r.profiler.beginPhase('render:selection')// While a gradient is edited, Figma shows its handles instead of the layer's selection; adiff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.tsindex b5cf1c03c..116b0595e 100644--- a/packages/core/src/canvas/renderer/pipeline.ts+++ b/packages/core/src/canvas/renderer/pipeline.ts@@ -114,7 +114,8 @@ export function renderFromEditorState(designIssues: state.designIssues,codeFocusNodeId: state.codeFocusNodeId,autoLayoutHover: state.autoLayoutHover,- shapeHandleHover: state.shapeHandleHover+ shapeHandleHover: state.shapeHandleHover,+ connectorTarget: state.connectorTarget},// Recorded pictures follow what the canvas draws, not every document change.state.canvasVersion,diff --git a/packages/core/src/canvas/renderer/types.ts b/packages/core/src/canvas/renderer/types.tsindex 450771885..7e2448ff6 100644--- a/packages/core/src/canvas/renderer/types.ts+++ b/packages/core/src/canvas/renderer/types.ts@@ -4,6 +4,7 @@ import type { SnapGuide } from '@open-pencil/scene-graph/snap'import type { GuideOverlayState } from '#core/canvas/guides/types'import type { DesignIssueOverlay } from '#core/canvas/issues/types'+import type { ConnectorTarget } from '#core/editor/connectors/attach'import type { ShapeHandleHover, GradientEdit, PencilState } from '#core/editor/types'import type { RotationPreview } from '#core/geometry'import type { TextEditor } from '#core/text/editor'@@ -72,6 +73,8 @@ export interface RenderOverlays {} | null/** The selected shape's handles and the label of the one in use. */shapeHandleHover?: ShapeHandleHover | null+ /** The layer a connector end would attach to, outlined with its magnets. */+ connectorTarget?: ConnectorTarget | nullpenState?: {vertices: Vector[]segments: Array<{diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex 537ea028a..d3f72ccf4 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -6,7 +6,9 @@ import type { ArrowEndpoint } from '@open-pencil/scene-graph/arrow-caps'import {arrowCapOverflow,collectArrowEndpoints,- lineArrowEndpoints+ hasTrimmedShaft,+ lineArrowEndpoints,+ trimArrowShafts} from '@open-pencil/scene-graph/arrow-caps'import { computeDescendantVisualBounds } from '@open-pencil/scene-graph/geometry'import Matrix from '@open-pencil/scene-graph/matrix'@@ -15,7 +17,12 @@ import type { Color } from '@open-pencil/scene-graph/primitives'import { createSceneGeometry, nodeOrientationMatrix, projectedNode } from '#core/geometry'import { shownText } from '#core/text/case'import { fontManager } from '#core/text/fonts'-import { addStrokeRunToPath, strokeRuns, vectorNetworkToCenterlinePath } from '#core/vector'+import {+ addStrokeRunToPath,+ strokeRuns,+ vectorNetworkToCenterlinePath,+ vectorNetworkToPath+} from '#core/vector'import { figmaBlendModeToSkia, needsIsolatedBlendLayer } from './blend'import { renderBooleanOperation } from './boolean'@@ -862,6 +869,23 @@ function paintNodeStrokes(drawNodeArrowHeads(r, canvas, node, stroke, color)return}+ const cap = stroke.cap ?? node.strokeCap+ if (+ !sg &&+ stroke.align === 'CENTER' &&+ node.type === 'VECTOR' &&+ node.vectorNetwork &&+ hasTrimmedShaft(node.vectorNetwork, cap)+ ) {+ // The line stops short of a triangle or equilateral head, so it is stroked from its own+ // pulled-back copy rather than the cached paths; saved stroke geometry is already trimmed.+ const network = trimArrowShafts(node.vectorNetwork, cap, stroke.weight)+ const paths = vectorNetworkToPath(r.ck, network, node.cornerRadius)+ drawVectorPathStrokes(r, canvas, paths, stroke, color, node.strokeMiterLimit)+ for (const path of paths) path.delete()+ drawNodeArrowHeads(r, canvas, node, stroke, color)+ return+ }drawNodeStroke(r, canvas, node, rect, hasRadius, stroke, color, sg, vectorPaths, vectorStroke)drawNodeArrowHeads(r, canvas, node, stroke, color)})diff --git a/packages/core/src/canvas/strokes.ts b/packages/core/src/canvas/strokes.tsindex ef0432719..1cc8d96a0 100644--- a/packages/core/src/canvas/strokes.ts+++ b/packages/core/src/canvas/strokes.ts@@ -2,8 +2,14 @@ import type { Canvas, EmbindEnumEntity, Paint } from 'canvaskit-wasm'import type { SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'import type { ArrowEndpoint } from '@open-pencil/scene-graph/arrow-caps'-import { arrowLinesSegments, equilateralArrowPoints } from '@open-pencil/scene-graph/arrow-caps'-import type { Color } from '@open-pencil/scene-graph/primitives'+import {+ arrowLinesSegments,+ circleCapRadius,+ diamondCapPoints,+ equilateralArrowPoints,+ triangleCapPoints+} from '@open-pencil/scene-graph/arrow-caps'+import type { Color, Vector } from '@open-pencil/scene-graph/primitives'import { applyGradientFill, applyImageFill } from './fills'import type { SkiaRenderer } from './renderer'@@ -119,36 +125,59 @@ export function drawArrowHeads(opacity: number): void {for (const endpoint of endpoints) {- if (endpoint.cap === 'ARROW_EQUILATERAL') {- const [tip, left, right] = equilateralArrowPoints(- endpoint.x,- endpoint.y,- endpoint.angle,- weight- )- const builder = new r.ck.PathBuilder()- builder.moveTo(tip.x, tip.y)- builder.lineTo(left.x, left.y)- builder.lineTo(right.x, right.y)- builder.close()- const path = builder.detachAndDelete()- r.fillPaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))- r.fillPaint.setAlphaf(opacity)- canvas.drawPath(path, r.fillPaint)- path.delete()- } else {- r.strokePaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))- r.strokePaint.setAlphaf(opacity)- r.strokePaint.setStrokeWidth(weight)- r.strokePaint.setStrokeCap(r.ck.StrokeCap.Butt)- r.strokePaint.setPathEffect(null)- for (const wing of arrowLinesSegments(endpoint.x, endpoint.y, endpoint.angle, weight)) {- canvas.drawLine(wing.from.x, wing.from.y, wing.to.x, wing.to.y, r.strokePaint)- }+ const { x, y, angle } = endpoint+ switch (endpoint.cap) {+ case 'ARROW_LINES':+ r.strokePaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))+ r.strokePaint.setAlphaf(opacity)+ r.strokePaint.setStrokeWidth(weight)+ r.strokePaint.setStrokeCap(r.ck.StrokeCap.Butt)+ r.strokePaint.setPathEffect(null)+ for (const wing of arrowLinesSegments(x, y, angle, weight)) {+ canvas.drawLine(wing.from.x, wing.from.y, wing.to.x, wing.to.y, r.strokePaint)+ }+ break+ case 'CIRCLE_FILLED':+ setHeadPaint(r, color, opacity)+ canvas.drawCircle(x, y, circleCapRadius(weight), r.fillPaint)+ break+ case 'ARROW_EQUILATERAL':+ fillHead(r, canvas, equilateralArrowPoints(x, y, angle, weight), color, opacity)+ break+ case 'TRIANGLE_FILLED':+ fillHead(r, canvas, triangleCapPoints(x, y, angle, weight), color, opacity)+ break+ case 'DIAMOND_FILLED':+ fillHead(r, canvas, diamondCapPoints(x, y, angle, weight), color, opacity)+ break}}}+function setHeadPaint(r: SkiaRenderer, color: Color, opacity: number) {+ r.fillPaint.setColor(r.ck.Color4f(color.r, color.g, color.b, color.a))+ r.fillPaint.setAlphaf(opacity)+}++/** Fills a head outlined by `points` in the stroke's colour. */+function fillHead(+ r: SkiaRenderer,+ canvas: Canvas,+ points: readonly Vector[],+ color: Color,+ opacity: number+) {+ const builder = new r.ck.PathBuilder()+ points.forEach((point, index) =>+ index === 0 ? builder.moveTo(point.x, point.y) : builder.lineTo(point.x, point.y)+ )+ builder.close()+ const path = builder.detachAndDelete()+ setHeadPaint(r, color, opacity)+ canvas.drawPath(path, r.fillPaint)+ path.delete()+}+/*** A gradient or image stroke paints through a shader, the way the same paint does as a fill.* Both paints get it: a vector stroke's outline and an arrowhead are filled shapes drawn withdiff --git a/packages/core/src/editor/connectors/attach.ts b/packages/core/src/editor/connectors/attach.tsnew file mode 100644index 000000000..46360b11e--- /dev/null+++ b/packages/core/src/editor/connectors/attach.ts@@ -0,0 +1,162 @@+import { minBy } from 'es-toolkit'++import {+ boundEndpoint,+ freeEndpoint,+ type ConnectorEndpoint,+ type ConnectorMagnet,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'+import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'++/**+ * Where FigJam attaches a connector end dropped on a layer, measured on a 200 px square at 100%:+ * within 12 screen px inside its outline or 8 outside, the end holds to the outline and picks+ * left or right as the route needs; within 16 px of a side's midpoint it takes that side; inside,+ * the nearest of the side midpoints and the centre wins, the centre meaning any side.+ */+const OUTLINE_INSIDE = 12+const OUTLINE_OUTSIDE = 8+const MIDPOINT_SNAP = 16++/**+ * Layers whose children a connector end may attach to on their own, as FigJam looks into+ * sections; an end that misses every child attaches to the layer itself, except to a group.+ */+const PASS_THROUGH = new Set<SceneNode['type']>([+ 'SECTION',+ 'GROUP',+ 'FRAME',+ 'COMPONENT',+ 'COMPONENT_SET',+ 'INSTANCE'+])++/** The layer an end would attach to and how, for the canvas to highlight. */+export interface ConnectorTarget {+ nodeId: string+ magnet: ConnectorMagnet+}++type Side = 'TOP' | 'RIGHT' | 'BOTTOM' | 'LEFT'++function sidePoints(box: Rect): [Side | 'AUTO', Vector][] {+ const cx = box.x + box.width / 2+ const cy = box.y + box.height / 2+ return [+ ['TOP', { x: cx, y: box.y }],+ ['RIGHT', { x: box.x + box.width, y: cy }],+ ['BOTTOM', { x: cx, y: box.y + box.height }],+ ['LEFT', { x: box.x, y: cy }],+ ['AUTO', { x: cx, y: cy }]+ ]+}++/** Signed distance from `point` to the box's outline: negative inside. */+function outlineDistance(box: Rect, point: Vector): number {+ const dx = Math.max(box.x - point.x, point.x - (box.x + box.width))+ const dy = Math.max(box.y - point.y, point.y - (box.y + box.height))+ if (dx <= 0 && dy <= 0) return Math.max(dx, dy)+ return Math.hypot(Math.max(dx, 0), Math.max(dy, 0))+}++/** The magnet a point on or near `box` picks, or null when it is too far outside. */+export function magnetAt(box: Rect, point: Vector, zoom: number): ConnectorMagnet | null {+ const distance = outlineDistance(box, point)+ if (distance > OUTLINE_OUTSIDE / zoom) return null+ const candidates = sidePoints(box).map(([magnet, at]) => ({+ magnet,+ distance: Math.hypot(at.x - point.x, at.y - point.y)+ }))+ const nearest = candidates.reduce((best, candidate) =>+ candidate.distance < best.distance ? candidate : best+ )+ if (distance >= -OUTLINE_INSIDE / zoom) {+ // On a layer small enough for midpoints' reaches to overlap, the nearest one wins.+ const side = minBy(+ candidates.filter(+ (candidate) => candidate.magnet !== 'AUTO' && candidate.distance <= MIDPOINT_SNAP / zoom+ ),+ (candidate) => candidate.distance+ )+ return side?.magnet ?? 'AUTO_HORIZONTAL'+ }+ return nearest.magnet+}++function attachable(node: SceneNode): boolean {+ return node.visible && !node.locked && node.type !== 'CONNECTOR'+}++interface TargetSearch {+ pageId: string+ point: Vector+ zoom: number+ exclude: ReadonlySet<string>+ /** The layers the connector sits in: its canvas, which an end never attaches to. */+ around: ReadonlySet<string>+}++/** The topmost layer under `point` an end may attach to, looking into containers. */+function targetIn(+ graph: SceneGraph,+ parentId: string,+ search: TargetSearch+): { node: SceneNode; magnet: ConnectorMagnet } | null {+ const { pageId, point, zoom, exclude, around } = search+ const children = graph.getChildren(parentId)+ for (let index = children.length - 1; index >= 0; index--) {+ const node = children[index]+ if (!attachable(node) || exclude.has(node.id)) continue+ const box = getAxisAlignedBoundsInParent([node], pageId, graph)+ const magnet = magnetAt(box, point, zoom)+ // A container that does not clip shows children beyond its box, which an end may reach.+ if (PASS_THROUGH.has(node.type) && (magnet || !node.clipsContent)) {+ const inner = targetIn(graph, node.id, search)+ if (inner) return inner+ if (node.type === 'GROUP' || around.has(node.id)) continue+ }+ if (!magnet) continue+ return { node, magnet }+ }+ return null+}++/** The layers `nodeId` sits in, below its page. */+function containersOf(graph: SceneGraph, nodeId: string | undefined): Set<string> {+ const containers = new Set<string>()+ const parentId = nodeId ? graph.getNode(nodeId)?.parentId : null+ if (!parentId) return containers+ // A walk that stops at the page, and at a parent cycle in a damaged document.+ graph.closest(parentId, (node) => {+ if (node.type === 'CANVAS') return true+ containers.add(node.id)+ return false+ })+ return containers+}++/**+ * Where a connector end lands at `point`, in page coordinates: on the layer under it by the+ * magnet its position picks, or free at the point. Straight connectors attach by centres. An end+ * dropped on a layer the connector sits in stays free there, as FigJam leaves one in its section.+ */+export function connectorAttachment(+ graph: SceneGraph,+ pageId: string,+ point: Vector,+ options: { zoom: number; straight?: boolean; connectorId?: string }+): { endpoint: ConnectorEndpoint; target: ConnectorTarget | null } {+ const hit = targetIn(graph, pageId, {+ pageId,+ point,+ zoom: options.zoom,+ exclude: new Set(options.connectorId ? [options.connectorId] : []),+ around: containersOf(graph, options.connectorId)+ })+ if (!hit) return { endpoint: freeEndpoint(point.x, point.y), target: null }+ const magnet = options.straight ? 'CENTER' : hit.magnet+ return { endpoint: boundEndpoint(hit.node.id, magnet), target: { nodeId: hit.node.id, magnet } }+}diff --git a/packages/core/src/editor/connectors/draw.ts b/packages/core/src/editor/connectors/draw.tsnew file mode 100644index 000000000..b3651941f--- /dev/null+++ b/packages/core/src/editor/connectors/draw.ts@@ -0,0 +1,201 @@+import { createConnector, layoutConnector, type ConnectorEndpoint } from '@open-pencil/scene-graph'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import { connectorAttachment, type ConnectorTarget } from '#core/editor/connectors/attach'+import type { NodePreview } from '#core/editor/node-preview'+import type { EditorContext } from '#core/editor/types'+import { pushCreatedSubtreesUndo } from '#core/editor/undo'++/** A connector being drawn: where it started, and the layer made once the pointer moved. */+interface ConnectorDraft {+ start: ConnectorEndpoint+ connectorId: string | null+ previousSelection: Set<string>+ /** Set once a click placed the start: the line then follows the pointer to the next click. */+ clicked: boolean+}++/**+ * The connector tool, as FigJam's draws: press on a layer or the canvas and drag to where the+ * connector ends, or click its start and then its end. Each end attaches to the layer under it by+ * the magnet its position picks, or stays free. A new connector has no start cap and an arrow at+ * its end, and the tool stays active.+ */+export function createConnectorDrawActions(ctx: EditorContext) {+ let draft: ConnectorDraft | null = null++ function setTarget(target: ConnectorTarget | null) {+ ctx.state.connectorTarget = target+ ctx.requestRepaint()+ }++ function attach(point: Vector, connectorId?: string) {+ return connectorAttachment(ctx.graph, ctx.state.currentPageId, point, {+ zoom: ctx.state.zoom,+ connectorId+ })+ }++ /** Outlines the layer a connector end at `point` would attach to; a clicked start follows. */+ function connectorHover(x: number, y: number) {+ if (draft?.clicked) connectorDrag(x, y)+ else setTarget(attach({ x, y }).target)+ }++ /** Starts a connector at `point`, or ends the one a click started. */+ function connectorBegin(x: number, y: number) {+ if (draft) return+ draft = {+ start: attach({ x, y }).endpoint,+ connectorId: null,+ previousSelection: new Set(ctx.state.selectedIds),+ clicked: false+ }+ }++ function connectorDrag(x: number, y: number) {+ if (!draft) return+ const { endpoint, target } = attach({ x, y }, draft.connectorId ?? undefined)+ setTarget(target)+ const graph = ctx.graph+ if (!draft.connectorId) {+ const connector = createConnector(graph, ctx.state.currentPageId, {+ start: draft.start,+ end: endpoint,+ startCap: 'NONE',+ endCap: 'ARROW_LINES'+ })+ draft.connectorId = connector.id+ // Lays out the label, which loads its font, as a placed sticky note's text does.+ ctx.runLayoutForNode(connector.id)+ ctx.setSelectedIds(new Set())+ } else {+ graph.updateNode(draft.connectorId, { connectorEnd: endpoint })+ const connector = graph.getNode(draft.connectorId)+ if (connector) layoutConnector(graph, connector)+ }+ ctx.requestRender()+ }++ /**+ * Ends the connector at `point`. A release where the press was, with nothing drawn yet, leaves+ * the start waiting for a second click.+ */+ function connectorRelease(x: number, y: number, moved: boolean) {+ if (!draft) return+ if (!draft.connectorId && !moved && !draft.clicked) {+ draft.clicked = true+ return+ }+ connectorDrag(x, y)+ const { connectorId, previousSelection } = draft+ draft = null+ setTarget(null)+ if (!connectorId || !ctx.graph.getNode(connectorId)) return+ pushCreatedSubtreesUndo(ctx, 'Create connector', [connectorId], previousSelection)+ ctx.setSelectedIds(new Set())+ ctx.requestRender()+ }++ function connectorCancel() {+ const current = draft+ draft = null+ setTarget(null)+ if (current?.connectorId) {+ ctx.graph.deleteNode(current.connectorId)+ // Drawing cleared the selection; giving it up gives the selection back.+ ctx.setSelectedIds(new Set(current.previousSelection))+ }+ ctx.requestRender()+ }++ // Another tool leaves a connector a click started unfinished.+ ctx.onEditorEvent('tool:changed', () => {+ if (draft) connectorCancel()+ })++ return { connectorHover, connectorBegin, connectorDrag, connectorRelease, connectorCancel }+}++type BeginNodePreview = (label?: string) => NodePreview++/**+ * Dragging an end of a selected connector, as FigJam does: the end follows the pointer, attaches+ * to the layer under it by the magnet its position picks, and the connector routes as it goes.+ * One undo step puts the end back.+ */+export function createConnectorEndpointActions(+ ctx: EditorContext,+ beginNodePreview: BeginNodePreview,+ deleteNodes: (nodeIds: Iterable<string>) => void+) {+ let drag: {+ connectorId: string+ end: 'connectorStart' | 'connectorEnd'+ /** The layer the dragged end joined when the drag began. */+ joined: string | null+ preview: NodePreview+ } | null = null++ function connectorEndpointBegin(connectorId: string, end: 'connectorStart' | 'connectorEnd') {+ connectorEndpointCancel()+ const joined = ctx.graph.getNode(connectorId)?.[end]?.nodeId ?? null+ drag = { connectorId, end, joined, preview: beginNodePreview('Move connector end') }+ }++ function connectorEndpointDrag(x: number, y: number) {+ if (!drag) return+ const connector = ctx.graph.getNode(drag.connectorId)+ if (!connector) return+ const { endpoint, target } = connectorAttachment(+ ctx.graph,+ ctx.state.currentPageId,+ { x, y },+ {+ zoom: ctx.state.zoom,+ straight: connector.connectorLineType === 'STRAIGHT',+ connectorId: connector.id+ }+ )+ ctx.state.connectorTarget = target+ drag.preview.update(connector.id, { [drag.end]: endpoint })+ }++ function connectorEndpointCommit() {+ const current = drag+ drag = null+ ctx.state.connectorTarget = null+ const connector = current ? ctx.graph.getNode(current.connectorId) : undefined+ const dropped = current && connector ? connector[current.end]?.nodeId : null+ const other = current?.end === 'connectorStart' ? 'connectorEnd' : 'connectorStart'+ if (+ current &&+ connector &&+ dropped &&+ dropped !== current.joined &&+ dropped === connector[other]?.nodeId+ ) {+ // FigJam deletes a connector whose end is dropped on the layer its other end joins.+ current.preview.cancel()+ deleteNodes([connector.id])+ } else {+ current?.preview.commit()+ }+ ctx.requestRender()+ }++ function connectorEndpointCancel() {+ const current = drag+ drag = null+ ctx.state.connectorTarget = null+ current?.preview.cancel()+ ctx.requestRender()+ }++ return {+ connectorEndpointBegin,+ connectorEndpointDrag,+ connectorEndpointCommit,+ connectorEndpointCancel+ }+}diff --git a/packages/core/src/editor/connectors/routing.ts b/packages/core/src/editor/connectors/routing.tsindex c8f21b8f2..63a439ce2 100644--- a/packages/core/src/editor/connectors/routing.ts+++ b/packages/core/src/editor/connectors/routing.ts@@ -2,6 +2,7 @@ import { isEqual, pick } from 'es-toolkit'import {connectorRouteEnds,+ connectorsAffectedBy,freeEndpoint,generatedFrameOwner,layoutConnector,@@ -58,11 +59,6 @@ function carriedFreeEnds(graph: SceneGraph, connector: SceneNode): Partial<Scenereturn isEqual(changes, pick(connector, ['connectorStart', 'connectorEnd'])) ? null : changes}-/** Whether `id` or a layer above it is one of `ids`. */-function underAny(graph: SceneGraph, id: string, ids: ReadonlySet<string>): boolean {- return graph.closest(id, (node) => ids.has(node.id)) !== undefined-}-/*** Keeps connectors routed as the layers they attach to move, resize, or change, as FigJam does:* while a drag previews, and when an edit, undo, or redo lands. A route derives from the layers,@@ -71,8 +67,6 @@ function underAny(graph: SceneGraph, id: string, ids: ReadonlySet<string>): bool* once the page it is on is shown.*/export function createConnectorRouting(ctx: EditorContext) {- let indexed: SceneGraph | null = null- const connectorIds = new Set<string>()/** Layers changed since the last pass, and whether any change was more than a preview. */let pending: { ids: Set<string>; committed: boolean } | null = nulllet routing = false@@ -85,17 +79,6 @@ export function createConnectorRouting(ctx: EditorContext) {/** Steps already seen at the top of the history, to tell a new step from undo and redo. */const seenSteps = new WeakSet<UndoEntry>()- function connectors(graph: SceneGraph): Set<string> {- if (indexed !== graph) {- indexed = graph- connectorIds.clear()- for (const node of graph.getAllNodes()) {- if (node.type === 'CONNECTOR') connectorIds.add(node.id)- }- }- return connectorIds- }-function schedule(id: string, committed: boolean) {if (routing || ctx.graph.isApplyingImportedState) returnif (!pending) {@@ -193,19 +176,7 @@ export function createConnectorRouting(ctx: EditorContext) {pending = nullif (!batch) returnconst graph = ctx.graph- const ids = connectors(graph)- const affected: SceneNode[] = []- for (const id of ids) {- const connector = graph.getNode(id)- if (!connector) {- ids.delete(id)- continue- }- const watched = [id, connector.connectorStart?.nodeId, connector.connectorEnd?.nodeId]- if (watched.some((watchedId) => watchedId && underAny(graph, watchedId, batch.ids))) {- affected.push(connector)- }- }+ const affected = connectorsAffectedBy(graph, batch.ids)if (affected.length === 0) returnrouting = truetry {@@ -241,9 +212,6 @@ export function createConnectorRouting(ctx: EditorContext) {ctx.onEditorEvent('page:changed', (pageId) => routeShownPage(ctx.graph, pageId))ctx.onEditorEvent('node:updated', (id, changes) => changed(id, changes, true))ctx.onEditorEvent('node:previewUpdated', (id, changes) => changed(id, changes, false))- ctx.onEditorEvent('node:created', (node) => {- if (node.type === 'CONNECTOR' && indexed === ctx.graph) connectorIds.add(node.id)- })ctx.onEditorEvent('node:reparented', (id) => schedule(id, true))// Moving a layer into another parent by reordering moves it as reparenting does.ctx.onEditorEvent('node:reordered', (id, parentId, _index, previousParentId) => {diff --git a/packages/core/src/editor/connectors/style.ts b/packages/core/src/editor/connectors/style.tsnew file mode 100644index 000000000..9b651281e--- /dev/null+++ b/packages/core/src/editor/connectors/style.ts@@ -0,0 +1,65 @@+import {+ layoutConnector,+ type ConnectorEndpoint,+ type ConnectorLineType,+ type SceneNode,+ type StrokeCap+} from '@open-pencil/scene-graph'++import { recordSubtreeEdit } from '#core/editor/components/slots/history'+import type { EditorContext } from '#core/editor/types'++/** A straight connector attaches by its layers' centres, as Figma moves its magnets. */+function straightEnd(endpoint: ConnectorEndpoint | null): ConnectorEndpoint | null {+ if (!endpoint?.nodeId || endpoint.magnet === 'NONE') return endpoint+ return { ...endpoint, magnet: 'CENTER' }+}++/**+ * Connector commands from the Design panel: line type and caps. Each change records the+ * connectors' whole subtrees as one step, and the connectors route again.+ */+export function createConnectorStyleActions(ctx: EditorContext) {+ function edit(label: string, ids: Iterable<string>, change: (connector: SceneNode) => void) {+ const connectors = [...ids].flatMap((id) => {+ const node = ctx.graph.getNode(id)+ return node?.type === 'CONNECTOR' ? [node] : []+ })+ if (connectors.length === 0) return+ recordSubtreeEdit(+ ctx,+ label,+ connectors.map((connector) => connector.id),+ () => {+ // Routed inside the step, so undo and redo restore the route as well.+ for (const connector of connectors) {+ change(connector)+ layoutConnector(ctx.graph, connector)+ }+ }+ )+ ctx.requestRender()+ }++ function setConnectorLineType(ids: Iterable<string>, lineType: ConnectorLineType) {+ edit('Change connector line', ids, (connector) =>+ ctx.graph.updateNode(connector.id, {+ connectorLineType: lineType,+ ...(lineType === 'STRAIGHT' && {+ connectorStart: straightEnd(connector.connectorStart),+ connectorEnd: straightEnd(connector.connectorEnd)+ })+ })+ )+ }++ function setConnectorCap(ids: Iterable<string>, end: 'start' | 'end', cap: StrokeCap) {+ edit(end === 'start' ? 'Change start point' : 'Change end point', ids, (connector) =>+ ctx.graph.updateNode(connector.id, {+ [end === 'start' ? 'connectorStartCap' : 'connectorEndCap']: cap+ })+ )+ }++ return { setConnectorLineType, setConnectorCap }+}diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex 21c812ff8..2ddc5eeec 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -35,7 +35,9 @@ import { createClipboardPropertiesActions } from './clipboard/paste/properties'import { createColorSpaceActions } from './color-space'import { createComponentSyncScheduler } from './component-sync'import { createComponentActions } from './components'+import { createConnectorDrawActions, createConnectorEndpointActions } from './connectors/draw'import { createConnectorRouting } from './connectors/routing'+import { createConnectorStyleActions } from './connectors/style'import { createDesignTokenActions } from './design-tokens'import { createGraphEventSubscription } from './graph-events'import { createGraphReadActions } from './graph-reads'@@ -297,6 +299,13 @@ export function createEditor(options?: EditorOptions) {const stickies = createStickyActions(ctx)const statuses = createStatusActions(ctx)createConnectorRouting(ctx)+ const connectorDrawing = createConnectorDrawActions(ctx)+ const connectorEndpoints = createConnectorEndpointActions(+ ctx,+ nodes.beginNodePreview,+ clipboard.deleteNodes+ )+ const connectorStyles = createConnectorStyleActions(ctx)const shaders = createShaderActions(ctx, nodes)const alignment = createAlignmentActions(ctx)const preview = createPlayActions(ctx)@@ -468,6 +477,9 @@ export function createEditor(options?: EditorOptions) {getShownStatus: statuses.getShownStatus,setStatus: statuses.setStatus,setStatusWorkflow: statuses.setStatusWorkflow,+ ...connectorDrawing,+ ...connectorEndpoints,+ ...connectorStyles,...shaders,...shaderFrames,diff --git a/packages/core/src/editor/selection/overlays.ts b/packages/core/src/editor/selection/overlays.tsindex 0623aeb8f..015fc87ab 100644--- a/packages/core/src/editor/selection/overlays.ts+++ b/packages/core/src/editor/selection/overlays.ts@@ -4,6 +4,7 @@ import type { Rect } from '@open-pencil/scene-graph/primitives'import type { SnapGuide } from '@open-pencil/scene-graph/snap'import type { GuidePreview } from '#core/canvas/guides/types'+import type { ConnectorTarget } from '#core/editor/connectors/attach'import type { ShapeHandleHover, EditorContext } from '#core/editor/types'export function createSelectionOverlayActions(ctx: EditorContext) {@@ -98,6 +99,12 @@ export function createSelectionOverlayActions(ctx: EditorContext) {ctx.requestRepaint()}+ function setConnectorTarget(target: ConnectorTarget | null) {+ if (isEqual(ctx.state.connectorTarget, target)) return+ ctx.state.connectorTarget = target+ ctx.requestRepaint()+ }+function setShapeHandleHover(hover: ShapeHandleHover | null) {if (isEqual(ctx.state.shapeHandleHover, hover)) returnctx.state.shapeHandleHover = hover@@ -105,6 +112,7 @@ export function createSelectionOverlayActions(ctx: EditorContext) {}return {+ setConnectorTarget,setMarquee,setSnapGuides,setGuidePreview,diff --git a/packages/core/src/editor/state/view.ts b/packages/core/src/editor/state/view.tsindex 9e8ba2264..c3288d4ff 100644--- a/packages/core/src/editor/state/view.ts+++ b/packages/core/src/editor/state/view.ts@@ -22,6 +22,7 @@ export function createDefaultEditorViewState(pageId: string): EditorViewState {pencilState: null,autoLayoutHover: null,shapeHandleHover: null,+ connectorTarget: null,panX: 0,pageColor: { ...CANVAS_BG_COLOR },panY: 0,@@ -50,6 +51,7 @@ export function copyEditorViewState(source: EditorViewState): EditorViewState {pencilState: structuredClone(source.pencilState),autoLayoutHover: structuredClone(source.autoLayoutHover),shapeHandleHover: structuredClone(source.shapeHandleHover),+ connectorTarget: structuredClone(source.connectorTarget),pageColor: { ...source.pageColor },navigation: { ...source.navigation },nodeEditState: structuredClone(source.nodeEditState)diff --git a/packages/core/src/editor/tool-registry.ts b/packages/core/src/editor/tool-registry.tsindex 6ee384cbe..80f819b11 100644--- a/packages/core/src/editor/tool-registry.ts+++ b/packages/core/src/editor/tool-registry.ts@@ -20,6 +20,8 @@ export const EDITOR_TOOLS: EditorToolDef[] = [{ key: 'TEXT', label: 'Text', shortcut: 'T' },// Figma's S is Slice, and FigJam's sticky tool has no key in Figma Design.{ key: 'STICKY', label: 'Sticky note', shortcut: '' },+ // FigJam's X; Figma Design has no connector tool to take a key from.+ { key: 'CONNECTOR', label: 'Connector', shortcut: '' },{ key: 'HAND', label: 'Hand', shortcut: 'H' },{ key: 'COMMENT', label: 'Comment', shortcut: 'C' }]diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex fa47716b9..f1a221362 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -24,6 +24,7 @@ import type {SelectionTheme} from '#core/canvas/renderer/types'import type { InterfaceTheme } from '#core/constants'+import type { ConnectorTarget } from '#core/editor/connectors/attach'import type { PlayState } from '#core/editor/play/actions'import type { SnappingPreferences } from '#core/editor/preferences'import type { ShaderRasterizer } from '#core/editor/shaders/types'@@ -43,6 +44,7 @@ export type Tool =| 'STAR'| 'TEXT'| 'STICKY'+ | 'CONNECTOR'| 'PEN'| 'PENCIL'| 'HAND'@@ -166,6 +168,8 @@ export interface EditorViewState {side?: 'top' | 'right' | 'bottom' | 'left'} | nullshapeHandleHover: ShapeHandleHover | null+ /** The layer a connector end being drawn or dragged would attach to, and by which magnet. */+ connectorTarget: ConnectorTarget | nullpanX: numberpageColor: ColorpanY: numberdiff --git a/packages/core/src/figma-api/accessor-utils.ts b/packages/core/src/figma-api/accessor-utils.tsindex 5c35dba62..1dc3e82a6 100644--- a/packages/core/src/figma-api/accessor-utils.ts+++ b/packages/core/src/figma-api/accessor-utils.ts@@ -4,6 +4,7 @@ import {fitEnclosingGroups,FITTED_CONTAINER_TYPES,claimSlotContent,+ connectorSublayers,recordInstanceOverride,slotScope} from '@open-pencil/scene-graph'@@ -36,6 +37,20 @@ export function raw(target: ProxyThis, internals: NodeProxyInternals): SceneNodereturn node}+/**+ * The layer a node's strokes live on, as a proxy target: a connector keeps its stroke on its+ * line, which Figma presents as the connector's own.+ */+export function strokeOwner(target: ProxyThis, internals: NodeProxyInternals): ProxyThis {+ const node = raw(target, internals)+ if (node.type !== 'CONNECTOR') return target+ const line = connectorSublayers(graph(target, internals), node)?.line+ if (!line) return target+ const owner: ProxyThis = Object.create(target)+ owner[internals.id] = line.id+ return owner+}+export function assertProxyEditable(target: ProxyThis, internals: NodeProxyInternals): void {assertNodeEditable(graph(target, internals), nodeId(target, internals))}diff --git a/packages/core/src/figma-api/accessors/connector.ts b/packages/core/src/figma-api/accessors/connector.tsnew file mode 100644index 000000000..0f904ca83--- /dev/null+++ b/packages/core/src/figma-api/accessors/connector.ts@@ -0,0 +1,203 @@+import {+ boundEndpoint,+ connectorSublayers,+ freeEndpoint,+ layoutConnector,+ type ConnectorEndpoint,+ type ConnectorLineType,+ type SceneNode,+ type StrokeCap+} from '@open-pencil/scene-graph'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import {+ graph,+ raw,+ updateNode,+ type NodeProxyInternals,+ type ProxyThis+} from '#core/figma-api/accessor-utils'+import type { FigmaNodeProxy, NodeProxyHost } from '#core/figma-api/proxy'++/** Magnets Figma's plugin API takes with an `endpointNodeId`. */+const PLUGIN_MAGNETS = new Set(['NONE', 'AUTO', 'TOP', 'LEFT', 'BOTTOM', 'RIGHT', 'CENTER'])++/** Caps Figma lets a connector end take; its entity-relationship caps are not drawn here. */+const CONNECTOR_CAPS: readonly StrokeCap[] = [+ 'NONE',+ 'ARROW_EQUILATERAL',+ 'ARROW_LINES',+ 'TRIANGLE_FILLED',+ 'DIAMOND_FILLED',+ 'CIRCLE_FILLED'+]+/** The line types a connector takes. */+const CONNECTOR_LINE_TYPES: readonly ConnectorLineType[] = ['ELBOWED', 'STRAIGHT', 'CURVED']+const ENTITY_RELATIONSHIP_CAPS = new Set([+ 'ERD_ZERO_OR_ONE',+ 'ERD_EXACTLY_ONE',+ 'ERD_ZERO_OR_MORE',+ 'ERD_ONE_OR_MORE',+ 'ERD_ONE',+ 'ERD_MANY'+])++type ConnectorEnd = 'connectorStart' | 'connectorEnd'++function connector(target: ProxyThis, internals: NodeProxyInternals): SceneNode | null {+ const node = raw(target, internals)+ return node.type === 'CONNECTOR' ? node : null+}++/** Applies a connector edit and routes it again, so geometry read next sees the new route. */+function editConnector(+ target: ProxyThis,+ internals: NodeProxyInternals,+ changes: Partial<SceneNode>+) {+ updateNode(target, internals, changes)+ const node = connector(target, internals)+ if (node) layoutConnector(graph(target, internals), node)+}++/** An end as Figma's plugin API reports it; a free end names the page it lies on. */+function pluginEndpoint(target: ProxyThis, internals: NodeProxyInternals, end: ConnectorEnd) {+ const node = raw(target, internals)+ const endpoint = node[end]+ if (!endpoint) return undefined+ const position = { ...endpoint.position }+ if (endpoint.nodeId === null) {+ return { endpointNodeId: graph(target, internals).pageOf(node.id) ?? '', position }+ }+ if (endpoint.magnet === 'NONE') return { endpointNodeId: endpoint.nodeId, position }+ return { endpointNodeId: endpoint.nodeId, magnet: endpoint.magnet }+}++interface PluginEndpoint {+ endpointNodeId?: string+ magnet?: string+ position?: Vector+}++/** Reads an end a script sets, refusing what Figma refuses with its messages. */+function sceneEndpoint(+ target: ProxyThis,+ internals: NodeProxyInternals,+ end: ConnectorEnd,+ value: PluginEndpoint+): ConnectorEndpoint {+ const setter = `in set_${end}`+ const scene = graph(target, internals)+ const node = raw(target, internals)+ const { endpointNodeId, magnet, position } = value+ const page = scene.pageOf(node.id)+ if (endpointNodeId === undefined || endpointNodeId === page) {+ if (!position) throw new Error(`${setter}: Invalid endpoint`)+ return freeEndpoint(position.x, position.y)+ }+ const bound = scene.getNode(endpointNodeId)+ if (!bound || bound.id === node.id || scene.pageOf(bound.id) !== page) {+ throw new Error(`${setter}: Invalid endpointNodeId`)+ }+ if (position) return { nodeId: bound.id, magnet: 'NONE', position: { ...position } }+ if (!magnet || !PLUGIN_MAGNETS.has(magnet)) throw new Error(`${setter}: Invalid magnet`)+ if (node.connectorLineType === 'STRAIGHT' && magnet !== 'CENTER' && magnet !== 'NONE') {+ throw new Error(+ `${setter}: Straight connector endpoints may only use the CENTER or NONE magnets.`+ )+ }+ return boundEndpoint(bound.id, magnet as ConnectorEndpoint['magnet'])+}++function endAccessor(internals: NodeProxyInternals, end: ConnectorEnd) {+ return {+ get(this: ProxyThis) {+ return connector(this, internals) ? pluginEndpoint(this, internals, end) : undefined+ },+ set(this: ProxyThis, value: PluginEndpoint) {+ if (!connector(this, internals)) return+ editConnector(this, internals, { [end]: sceneEndpoint(this, internals, end, value) })+ }+ }+}++function capAccessor(+ internals: NodeProxyInternals,+ field: 'connectorStartCap' | 'connectorEndCap'+) {+ const property =+ field === 'connectorStartCap' ? 'connectorStartStrokeCap' : 'connectorEndStrokeCap'+ return {+ get(this: ProxyThis): StrokeCap | undefined {+ return connector(this, internals)?.[field]+ },+ set(this: ProxyThis, value: string) {+ if (!connector(this, internals)) return+ if (ENTITY_RELATIONSHIP_CAPS.has(value)) {+ throw new Error(`in set_${property}: ${value} is not supported`)+ }+ const cap = CONNECTOR_CAPS.find((candidate) => candidate === value)+ if (!cap) {+ throw new Error(+ `in set_${property}: Property "${property}" failed validation: Invalid enum value. Expected ${CONNECTOR_CAPS.map((name) => `'${name}'`).join(' | ')}, received '${value}'`+ )+ }+ editConnector(this, internals, { [field]: cap })+ }+ }+}++/** A connector made straight attaches by its layers' centres, as Figma moves its magnets. */+function straightEnd(endpoint: ConnectorEndpoint | null): ConnectorEndpoint | null {+ if (!endpoint?.nodeId || endpoint.magnet === 'NONE') return endpoint+ return { ...endpoint, magnet: 'CENTER' }+}++function plate(target: ProxyThis, internals: NodeProxyInternals): FigmaNodeProxy | undefined {+ const node = connector(target, internals)+ const layer = node && connectorSublayers(graph(target, internals), node)?.labelBackground+ return layer ? (target[internals.api] as NodeProxyHost).wrapNode(layer.id) : undefined+}++/**+ * `ConnectorNode`'s members: its ends, line type, caps, and its label's plate as `textBackground`;+ * `text` is shared with sticky notes. Each edit routes the connector again.+ */+export function installConnectorNodeProxyAccessors(+ prototype: object,+ internals: NodeProxyInternals+): void {+ Object.defineProperties(prototype, {+ connectorStart: endAccessor(internals, 'connectorStart'),+ connectorEnd: endAccessor(internals, 'connectorEnd'),+ connectorStartStrokeCap: capAccessor(internals, 'connectorStartCap'),+ connectorEndStrokeCap: capAccessor(internals, 'connectorEndCap'),+ connectorLineType: {+ get(this: ProxyThis): ConnectorLineType | undefined {+ return connector(this, internals)?.connectorLineType+ },+ set(this: ProxyThis, value: ConnectorLineType) {+ const node = connector(this, internals)+ if (!node) return+ if (!CONNECTOR_LINE_TYPES.includes(value)) {+ throw new Error(+ `in set_connectorLineType: Property "connectorLineType" failed validation: Invalid enum value. Expected ${CONNECTOR_LINE_TYPES.map((name) => `'${name}'`).join(' | ')}, received '${value}'`+ )+ }+ const straight = value === 'STRAIGHT'+ editConnector(this, internals, {+ connectorLineType: value,+ ...(straight && {+ connectorStart: straightEnd(node.connectorStart),+ connectorEnd: straightEnd(node.connectorEnd)+ })+ })+ }+ },+ textBackground: {+ get(this: ProxyThis): FigmaNodeProxy | undefined {+ return plate(this, internals)+ }+ }+ })+}diff --git a/packages/core/src/figma-api/accessors/sticky.ts b/packages/core/src/figma-api/accessors/sticky.tsindex 81fee50a3..6cf22a709 100644--- a/packages/core/src/figma-api/accessors/sticky.ts+++ b/packages/core/src/figma-api/accessors/sticky.ts@@ -44,7 +44,7 @@ export function installStickyNodeProxyAccessors(internals: NodeProxyInternals): void {Object.defineProperties(prototype, {- // A generated frame's text, such as a sticky note's body, as Figma's `text`.+ // A sticky note's body and a connector's label are both what Figma calls `text`.text: {get(this: ProxyThis): FigmaNodeProxy | undefined {const text = generatedFrameText(graph(this, internals), raw(this, internals))diff --git a/packages/core/src/figma-api/accessors/strokes.ts b/packages/core/src/figma-api/accessors/strokes.tsindex 9b2852ec0..271368985 100644--- a/packages/core/src/figma-api/accessors/strokes.ts+++ b/packages/core/src/figma-api/accessors/strokes.ts@@ -3,6 +3,7 @@ import { newStrokeGeometry, type SceneGraph, type SceneNode } from '@open-pencilimport {nodeId,raw,+ strokeOwner,updateNode,type NodeProxyInternals,type ProxyThis@@ -42,26 +43,26 @@ export function installStrokeNodeProxyAccessors(// Figma keeps stroke weight and alignment on the node, with or without strokes.strokeWeight: {get(this: ProxyThis): number {- return newStrokeGeometry(raw(this, internals)).weight+ return newStrokeGeometry(raw(strokeOwner(this, internals), internals)).weight},set(this: ProxyThis, value: number) {- setStrokeWeight(graph(this, internals), raw(this, internals), value)+ setStrokeWeight(graph(this, internals), raw(strokeOwner(this, internals), internals), value)}},strokeAlign: {get(this: ProxyThis): string {- return newStrokeGeometry(raw(this, internals)).align+ return newStrokeGeometry(raw(strokeOwner(this, internals), internals)).align},set(this: ProxyThis, value: SceneNode['strokeAlign']) {- setStrokeAlign(graph(this, internals), raw(this, internals), value)+ setStrokeAlign(graph(this, internals), raw(strokeOwner(this, internals), internals), value)}},dashPattern: {get(this: ProxyThis): readonly number[] {- return Object.freeze([...raw(this, internals).dashPattern])+ return Object.freeze([...raw(strokeOwner(this, internals), internals).dashPattern])},set(this: ProxyThis, value: readonly number[]) {- updateNode(this, internals, { dashPattern: [...value] })+ updateNode(strokeOwner(this, internals), internals, { dashPattern: [...value] })}},strokeCap: {@@ -79,12 +80,13 @@ export function installStrokeNodeProxyAccessors(},strokeJoin: {get(this: ProxyThis): string {- return raw(this, internals).strokeJoin+ return raw(strokeOwner(this, internals), internals).strokeJoin},set(this: ProxyThis, value: string) {const strokeJoin = value as SceneNode['strokeJoin']- const node = raw(this, internals)- updateNode(this, internals, {+ const owner = strokeOwner(this, internals)+ const node = raw(owner, internals)+ updateNode(owner, internals, {strokeJoin,strokes: node.strokes.map((stroke) => ({ ...stroke, join: strokeJoin }))})diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.tsindex 5563cb31c..58d4ad2ea 100644--- a/packages/core/src/figma-api/accessors/visual.ts+++ b/packages/core/src/figma-api/accessors/visual.ts@@ -11,6 +11,7 @@ import { copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'import {raw,+ strokeOwner,updateNode,type NodeProxyInternals,type ProxyThis@@ -98,7 +99,7 @@ export function installVisualNodeProxyAccessors(},strokes: {get(this: ProxyThis): readonly Stroke[] {- return Object.freeze(copyStrokes(raw(this, internals).strokes))+ return Object.freeze(copyStrokes(raw(strokeOwner(this, internals), internals).strokes))},// Figma paints carry no geometry; a stroke takes the node's weight and alignment, which// outlast its strokes.@@ -107,7 +108,8 @@ export function installVisualNodeProxyAccessors(value: readonly (Omit<Stroke, 'weight' | 'align'> &Partial<Pick<Stroke, 'weight' | 'align'>>)[]) {- const geometry = newStrokeGeometry(raw(this, internals))+ const owner = strokeOwner(this, internals)+ const geometry = newStrokeGeometry(raw(owner, internals))// The script keeps its paint objects; the node gets its own copies of every nested value.const strokes = copyStrokes(value.map((stroke) => ({@@ -123,7 +125,7 @@ export function installVisualNodeProxyAccessors(strokeWeight: geometry.weight,strokeAlign: geometry.align})- updateNode(this, internals, {+ updateNode(owner, internals, {strokes,strokeWeight: kept.weight,strokeAlign: kept.aligndiff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.tsindex 1b9240716..5b859f00b 100644--- a/packages/core/src/figma-api/compatibility.ts+++ b/packages/core/src/figma-api/compatibility.ts@@ -22,6 +22,7 @@ export type SupportedPluginAPI = Pick<| 'loadFontAsync'| 'notify'| 'createComponent'+ | 'createConnector'| 'createEllipse'| 'createFrame'| 'createLine'diff --git a/packages/core/src/figma-api/flatten.ts b/packages/core/src/figma-api/flatten.tsnew file mode 100644index 000000000..e5b2eabe1--- /dev/null+++ b/packages/core/src/figma-api/flatten.ts@@ -0,0 +1,35 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { copyFills } from '@open-pencil/scene-graph/copy'++import type { SkiaRenderer } from '#core/canvas'+import { canMakeBooleanSourceNode } from '#core/canvas/boolean'+import { flattenNodesToVectorProps } from '#core/canvas/flatten'++/** Without a renderer there are no outlines to merge: the first layer's box stands in. */+function flattenPlaceholder(graph: SceneGraph, nodes: SceneNode[], parentId: string): SceneNode {+ const first = nodes[0]+ return graph.createNode('VECTOR', parentId, {+ name: 'Flatten',+ x: first.x,+ y: first.y,+ width: first.width,+ height: first.height,+ fills: copyFills(first.fills)+ })+}++/** The vector `flatten` makes from `nodes` in `parentId`, before the sources are removed. */+export function flattenSceneNodes(+ graph: SceneGraph,+ renderer: SkiaRenderer | null,+ nodes: SceneNode[],+ parentId: string+): SceneNode {+ if (!renderer) return flattenPlaceholder(graph, nodes, parentId)+ if (nodes.some((node) => !canMakeBooleanSourceNode(node, graph))) {+ throw new Error('Cannot flatten unsupported node type')+ }+ const vectorProps = flattenNodesToVectorProps(renderer, graph, nodes)+ if (!vectorProps) throw new Error('Cannot flatten empty node path')+ return graph.createNode('VECTOR', parentId, vectorProps)+}diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.tsindex cef9fc043..3fec36fba 100644--- a/packages/core/src/figma-api/index.ts+++ b/packages/core/src/figma-api/index.ts@@ -1,5 +1,6 @@import { fromUint8Array, isValid, toUint8Array } from 'js-base64'+import { createConnector, freeEndpoint } from '@open-pencil/scene-graph'import type {GroupFitOptions,SceneGraph,@@ -10,14 +11,12 @@ import type {VariableType,VariableValue} from '@open-pencil/scene-graph'-import { copyFills } from '@open-pencil/scene-graph/copy'import { computeBounds } from '@open-pencil/scene-graph/geometry'import { computeImageHash } from '@open-pencil/scene-graph/images'import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'import type { SkiaRenderer } from '#core/canvas'-import { canMakeBooleanSourceNode, groupFitOptions } from '#core/canvas/boolean'-import { flattenNodesToVectorProps } from '#core/canvas/flatten'+import { groupFitOptions } from '#core/canvas/boolean'import { IS_BROWSER, type InterfaceTheme } from '#core/constants'import { newLayerDefaults } from '#core/editor/shapes/defaults'import { booleanOperationPaints, createBooleanOperation } from '#core/editor/structure/boolean'@@ -33,10 +32,12 @@ import { documentFontStatus, type DocumentFontStatus } from '#core/text/font/staimport { fontManager } from '#core/text/fonts'import { combineComponentsAsVariants, componentFromNode, exposeInstanceSwap } from './components'+import { flattenSceneNodes } from './flatten'import type {FigmaBooleanOperationNode,FigmaComponentNode,FigmaComponentSetNode,+ FigmaConnectorNode,FigmaEllipseNode,FigmaFrameNode,FigmaGroupNode,@@ -70,6 +71,7 @@ export type {FigmaBooleanOperationNode,FigmaComponentNode,FigmaComponentSetNode,+ FigmaConnectorNode,FigmaEllipseNode,FigmaFrameNode,FigmaGroupNode,@@ -227,6 +229,20 @@ export class FigmaAPI implements NodeProxyHost {return this.wrapNode(node.id) as FigmaFrameNode}+ /**+ * A connector as Figma's plugin API makes one: "Connector line", free from the page origin to+ * 200 px right of it, with no start cap and an arrow at the end.+ */+ createConnector(): FigmaConnectorNode {+ const node = createConnector(this.graph, this._currentPageId, {+ start: freeEndpoint(0, 0),+ end: freeEndpoint(200, 0),+ startCap: 'NONE',+ endCap: 'ARROW_LINES'+ })+ return this.wrapNode(node.id) as FigmaConnectorNode+ }+createComponent(): FigmaComponentNode {return this._createNode('COMPONENT') as FigmaComponentNode}@@ -472,9 +488,7 @@ export class FigmaAPI implements NodeProxyHost {if (!raw) throw new Error('Node not found')sourceNodes.push(raw)}- const vector = this._renderer- ? this._flattenWithRenderer(sourceNodes, parentId)- : this._flattenPlaceholder(sourceNodes, parentId)+ const vector = flattenSceneNodes(this.graph, this._renderer, sourceNodes, parentId)if (index != null) this.graph.reorderChild(vector.id, parentId, index)for (const node of nodes) {this.graph.deleteNode(this._nodeId(node))@@ -482,30 +496,6 @@ export class FigmaAPI implements NodeProxyHost {return this.wrapNode(vector.id) as FigmaVectorNode}- private _flattenPlaceholder(nodes: CoreSceneNode[], parentId: string): CoreSceneNode {- const first = nodes[0]- return this.graph.createNode('VECTOR', parentId, {- name: 'Flatten',- x: first.x,- y: first.y,- width: first.width,- height: first.height,- fills: copyFills(first.fills)- })- }-- private _flattenWithRenderer(nodes: CoreSceneNode[], parentId: string): CoreSceneNode {- const renderer = this._renderer- if (!renderer) return this._flattenPlaceholder(nodes, parentId)- if (nodes.some((node) => !canMakeBooleanSourceNode(node, this.graph))) {- throw new Error('Cannot flatten unsupported node type')- }-- const vectorProps = flattenNodesToVectorProps(renderer, this.graph, nodes)- if (!vectorProps) throw new Error('Cannot flatten empty node path')- return this.graph.createNode('VECTOR', parentId, vectorProps)- }-flattenNode(nodeIds: string[]): FigmaVectorNode {const first = this.graph.getNode(nodeIds[0])const parent = this.wrapNode(first?.parentId ?? this._currentPageId)diff --git a/packages/core/src/figma-api/node-types.ts b/packages/core/src/figma-api/node-types.tsindex 1132cb707..435311734 100644--- a/packages/core/src/figma-api/node-types.ts+++ b/packages/core/src/figma-api/node-types.ts@@ -18,3 +18,4 @@ export type FigmaSectionNode = FigmaNodeProxy & SectionNodeexport type FigmaGroupNode = FigmaNodeProxy & GroupNodeexport type FigmaBooleanOperationNode = FigmaNodeProxy & BooleanOperationNodeexport type FigmaStickyNode = FigmaNodeProxy & StickyNode+export type FigmaConnectorNode = FigmaNodeProxy & ConnectorNodediff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.tsindex 06c8b172b..d009a167e 100644--- a/packages/core/src/figma-api/proxy.ts+++ b/packages/core/src/figma-api/proxy.ts@@ -1,4 +1,5 @@import {+ attachedConnectors,createsComponentCycle,recordInstanceOverride,slotPropertyId@@ -28,6 +29,7 @@ import type { FigmaEffect } from '#core/figma-api/effects'import { prepareFollowedFieldEdit, fitGroupsAround } from './accessor-utils'import { installBasicNodeProxyAccessors } from './accessors/basic'+import { installConnectorNodeProxyAccessors } from './accessors/connector'import { installLayoutNodeProxyAccessors } from './accessors/layout'import { installStickyNodeProxyAccessors, pluginChildren } from './accessors/sticky'import { installStrokeNodeProxyAccessors } from './accessors/strokes'@@ -450,7 +452,10 @@ export class FigmaNodeProxy {assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])prepareSlotRemoval(this[INTERNAL_GRAPH], this[INTERNAL_ID])const parentId = this._raw().parentId+ // Connectors go with a layer they attach to, as Figma removes them.+ const attached = attachedConnectors(this[INTERNAL_GRAPH], [this[INTERNAL_ID]])this[INTERNAL_GRAPH].deleteNode(this[INTERNAL_ID])+ for (const connector of attached) this[INTERNAL_GRAPH].deleteNode(connector.id)fitGroupsAround(this[INTERNAL_GRAPH], parentId, this[INTERNAL_API].groupFitOptions)}@@ -579,6 +584,7 @@ const proxyInternals = {installStrokeNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)installStickyNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)+installConnectorNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)installTextNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals, MIXED)installTextRangeMethods(FigmaNodeProxy.prototype, proxyInternals, MIXED)installLayoutNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)diff --git a/packages/core/src/geometry/connectors.ts b/packages/core/src/geometry/connectors.tsnew file mode 100644index 000000000..5fe9642ea--- /dev/null+++ b/packages/core/src/geometry/connectors.ts@@ -0,0 +1,23 @@+import { connectorLineEnds, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import Matrix from '@open-pencil/scene-graph/matrix'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import { createSceneGeometry } from './scene'+import type { RotationPreview, ViewportTransform } from './types'++/** Where a connector's line starts and ends on screen, where its end handles sit. */+export function connectorScreenEnds(+ graph: SceneGraph,+ connector: SceneNode,+ viewport: ViewportTransform,+ preview?: RotationPreview | null+): { start: Vector; end: Vector } | null {+ const ends = connectorLineEnds(graph, connector)+ if (!ends) return null+ const { line, start, end } = ends+ const [sx, sy, ex, ey] = Matrix.mapPoints(+ createSceneGeometry(graph, preview).screenMatrix(line, viewport),+ [start.x, start.y, end.x, end.y]+ )+ return { start: { x: sx, y: sy }, end: { x: ex, y: ey } }+}diff --git a/packages/core/src/geometry/index.ts b/packages/core/src/geometry/index.tsindex 16a8b26ca..09f664fe1 100644--- a/packages/core/src/geometry/index.ts+++ b/packages/core/src/geometry/index.ts@@ -37,6 +37,7 @@ export type {GradientHit,GradientStopLayout} from './gradient'+export { connectorScreenEnds } from './connectors'export { createSceneGeometry, nodeOrientationMatrix, projectedNode, viewportMatrix } from './scene'export type { SceneGeometry } from './scene'export { selectionPath, selectionHandleRect, rotationHandleLayout } from './selection'diff --git a/packages/core/src/io/subgraph.ts b/packages/core/src/io/subgraph.tsindex ca968a27c..a85ad104b 100644--- a/packages/core/src/io/subgraph.ts+++ b/packages/core/src/io/subgraph.ts@@ -80,6 +80,7 @@ function cloneIntoGraph(instances.add(id)graph.instanceIndex.set(copy.componentId, instances)}+ if (copy.type === 'CONNECTOR') graph.connectorIds.add(id)}const rootClone = graph.getNode(source.rootId)diff --git a/packages/core/src/kiwi/fig/parse/transfer.ts b/packages/core/src/kiwi/fig/parse/transfer.tsindex ffb8336ba..a9cdce5b8 100644--- a/packages/core/src/kiwi/fig/parse/transfer.ts+++ b/packages/core/src/kiwi/fig/parse/transfer.ts@@ -68,6 +68,7 @@ export function cloneSceneGraphForFigExport(graph: SceneGraph): SceneGraph {cloned.instanceIndex = new Map([...graph.instanceIndex].map(([id, nodeIds]) => [id, new Set(nodeIds)]))+ cloned.connectorIds = new Set(graph.connectorIds)cloned.figKiwiVersion = graph.figKiwiVersioncloned.figSchemaDeflated = graph.figSchemaDeflatedcloned.documentColorSpace = graph.documentColorSpace@@ -97,6 +98,8 @@ export function deserializeSceneGraph(data: SerializedSceneGraph): SceneGraph {graph.variableCollections = new Map(data.variableCollections)graph.activeMode = new Map(data.activeMode)graph.instanceIndex = new Map(data.instanceIndex.map(([id, nodeIds]) => [id, new Set(nodeIds)]))+ // Routing finds connectors through the index the nodes it was sent without imply.+ for (const [id, node] of graph.nodes) if (node.type === 'CONNECTOR') graph.connectorIds.add(id)graph.figKiwiVersion = data.figKiwiVersiongraph.figSchemaDeflated = data.figSchemaDeflatedgraph.documentColorSpace = data.documentColorSpacediff --git a/packages/core/src/layout/mutations.ts b/packages/core/src/layout/mutations.tsindex 6519e30b1..86e2a06d2 100644--- a/packages/core/src/layout/mutations.ts+++ b/packages/core/src/layout/mutations.ts@@ -1,7 +1,12 @@+import { uniq } from 'es-toolkit'+import {collectSceneMutation,+ connectorsAffectedBy,+ layoutConnector,mutationLayoutScopeIds,type SceneGraph,+ type SceneNode,type SceneMutationImpact} from '@open-pencil/scene-graph'@@ -49,12 +54,40 @@ export function createLayoutRunner(getGraph: () => SceneGraph) {return result}- /** Lays out what an edit touched; returns whether there was anything to lay out. */+ /**+ * Lays out what an edit touched, and routes again the connectors it moved; returns whether+ * there was anything to lay out.+ */function runLayoutForImpact(impact: SceneMutationImpact): boolean {const scopeIds = compactLayoutScope(impact)for (const id of scopeIds) runLayoutForNode(id)+ routeConnectors(impact)return scopeIds.length > 0}+ /**+ * Routes the connectors an edit moved. One created together with the layers it joins, as a+ * paste makes it, keeps the route it came with; one that joins layers already there routes to+ * them.+ */+ function routeConnectors(impact: SceneMutationImpact) {+ const graph = getGraph()+ const created = impact.createdNodeIds+ const joinsExisting = (connector: SceneNode) =>+ [connector.connectorStart?.nodeId, connector.connectorEnd?.nodeId].some(+ (id) => id && !created.has(id) && graph.getNode(id)+ )+ const connectors = [+ ...connectorsAffectedBy(graph, impact.changedNodeIds),+ ...[...created].flatMap((id) => {+ const node = graph.getNode(id)+ return node?.type === 'CONNECTOR' && joinsExisting(node) ? [node] : []+ })+ ]+ graph.withLayoutMutations(() => {+ for (const connector of uniq(connectors)) layoutConnector(graph, connector)+ })+ }+return { runLayoutForNode, runLayoutForImpact, runMutationWithLayout }}diff --git a/packages/core/src/library/serialization.ts b/packages/core/src/library/serialization.tsindex a11f05d98..4bdbbf9f3 100644--- a/packages/core/src/library/serialization.ts+++ b/packages/core/src/library/serialization.ts@@ -55,6 +55,7 @@ export function deserializeLibraryRevision(graph.documentColorSpace = revision.graph.documentColorSpacegraph.instanceIndex = new Map()for (const node of graph.getAllNodes()) {+ if (node.type === 'CONNECTOR') graph.connectorIds.add(node.id)if (!node.componentId) continueconst instances = graph.instanceIndex.get(node.componentId) ?? new Set<string>()instances.add(node.id)diff --git a/packages/core/src/tools/create.ts b/packages/core/src/tools/create.tsindex 803016fe7..8f73fb06d 100644--- a/packages/core/src/tools/create.ts+++ b/packages/core/src/tools/create.ts@@ -10,3 +10,4 @@ export { fetchIconsTool, insertIcon, searchIconsTool } from './create/icons'export { render } from './create/render'export { importSVG } from './create/svg'export { createVector } from './create/vector'+export { createConnectorTool } from './create/connector'diff --git a/packages/core/src/tools/create/connector.ts b/packages/core/src/tools/create/connector.tsnew file mode 100644index 000000000..0b6f0d1f0--- /dev/null+++ b/packages/core/src/tools/create/connector.ts@@ -0,0 +1,69 @@+import * as v from 'valibot'++import { toolNumber } from '#core/tools/input'+import { defineTool, nodeSummary } from '#core/tools/schema'++const MAGNETS = ['AUTO', 'TOP', 'RIGHT', 'BOTTOM', 'LEFT', 'CENTER'] as const+const CAPS = [+ 'NONE',+ 'ARROW_LINES',+ 'ARROW_EQUILATERAL',+ 'TRIANGLE_FILLED',+ 'DIAMOND_FILLED',+ 'CIRCLE_FILLED'+] as const++const endInput = (label: string) =>+ v.optional(+ v.strictObject({+ id: v.optional(v.pipe(v.string(), v.description(`Node ID the ${label} attaches to`))),+ magnet: v.optional(+ v.pipe(+ v.picklist(MAGNETS),+ v.description('Side it attaches by; AUTO picks the nearest. Straight lines use CENTER')+ )+ ),+ x: v.optional(toolNumber(v.pipe(v.number(), v.description('Page X of a free end')))),+ y: v.optional(toolNumber(v.pipe(v.number(), v.description('Page Y of a free end'))))+ }),+ {}+ )++export const createConnectorTool = defineTool({+ name: 'create_connector',++ description:+ 'Create a FigJam-style connector between two layers, or from or to a point on the page. A connector follows the layers it joins as they move and is deleted with them. Give each end a node id (and optionally a magnet side), or x/y for a free end.',+ execution: { kind: 'sync', mutation: 'document' },+ input: v.strictObject({+ start: endInput('start'),+ end: endInput('end'),+ line_type: v.optional(+ v.pipe(v.picklist(['ELBOWED', 'STRAIGHT', 'CURVED']), v.description('Path shape'))+ ),+ start_cap: v.optional(v.pipe(v.picklist(CAPS), v.description('Cap at the start'))),+ end_cap: v.optional(+ v.pipe(v.picklist(CAPS), v.description('Cap at the end; an arrow by default'))+ ),+ label: v.optional(v.pipe(v.string(), v.description('Text on the line'))),+ name: v.optional(v.pipe(v.string(), v.description('Layer name')))+ }),+ execute: (figma, args) => {+ const connector = figma.createConnector()+ const straight = args.line_type === 'STRAIGHT'+ if (args.line_type) connector.connectorLineType = args.line_type+ const endpoint = (end: typeof args.start) => {+ if (end.id) {+ return { endpointNodeId: end.id, magnet: end.magnet ?? (straight ? 'CENTER' : 'AUTO') }+ }+ return { position: { x: end.x ?? 0, y: end.y ?? 0 } }+ }+ connector.connectorStart = endpoint(args.start)+ connector.connectorEnd = endpoint(args.end)+ if (args.start_cap) connector.connectorStartStrokeCap = args.start_cap+ if (args.end_cap) connector.connectorEndStrokeCap = args.end_cap+ if (args.label) connector.text.characters = args.label+ if (args.name) connector.name = args.name+ return nodeSummary(connector)+ }+})diff --git a/packages/core/src/tools/registry/extended.ts b/packages/core/src/tools/registry/extended.tsindex 8a5a2a10f..5b55660a1 100644--- a/packages/core/src/tools/registry/extended.ts+++ b/packages/core/src/tools/registry/extended.ts@@ -15,6 +15,7 @@ import {createComponent,createInstance,createPage,+ createConnectorTool,createShape,createSlice,createVector,@@ -147,6 +148,7 @@ export const EXTENDED_TOOLS: ToolDef[] = [createPage,createVector,createSlice,+ createConnectorTool,importSVG,// Modify (advanced)setEffects,diff --git a/packages/core/tests/editor/connectors/draw.test.ts b/packages/core/tests/editor/connectors/draw.test.tsnew file mode 100644index 000000000..c03d689ea--- /dev/null+++ b/packages/core/tests/editor/connectors/draw.test.ts@@ -0,0 +1,209 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'+import { boundEndpoint, createConnector, freeEndpoint } from '@open-pencil/scene-graph'+import { connectorAttachment, magnetAt } from '#core/editor/connectors/attach'++function setup() {+ const editor = createEditor()+ const page = editor.state.currentPageId+ const a = editor.graph.createNode('RECTANGLE', page, { x: 0, y: 0, width: 200, height: 200 })+ const b = editor.graph.createNode('RECTANGLE', page, { x: 500, y: 100, width: 200, height: 200 })+ return { editor, page, a, b }+}++function connectors(editor: ReturnType<typeof createEditor>) {+ return [...editor.graph.getAllNodes()].filter((node) => node.type === 'CONNECTOR')+}++const BOX = { x: 0, y: 0, width: 200, height: 200 }++// Measured with FigJam's connector tool on a 200 px square at 100% on 2026-10-15.+describe('where a connector end attaches', () => {+ test('the centre attaches by any side, and points inside take the nearest side', () => {+ expect(magnetAt(BOX, { x: 100, y: 100 }, 1)).toBe('AUTO')+ expect(magnetAt(BOX, { x: 16, y: 30 }, 1)).toBe('LEFT')+ expect(magnetAt(BOX, { x: 30, y: 16 }, 1)).toBe('TOP')+ expect(magnetAt(BOX, { x: 100, y: 50 }, 1)).toBe('TOP')+ })++ test('near the outline an end holds to it, by a side when at its midpoint', () => {+ expect(magnetAt(BOX, { x: 4, y: 50 }, 1)).toBe('AUTO_HORIZONTAL')+ expect(magnetAt(BOX, { x: -8, y: 30 }, 1)).toBe('AUTO_HORIZONTAL')+ expect(magnetAt(BOX, { x: 4, y: 100 }, 1)).toBe('LEFT')+ expect(magnetAt(BOX, { x: 100, y: -8 }, 1)).toBe('TOP')+ })++ test('on a layer so small that midpoints overlap, the nearest one wins', () => {+ const small = { x: 0, y: 0, width: 10, height: 10 }+ expect(magnetAt(small, { x: 5, y: 10 }, 1)).toBe('BOTTOM')+ expect(magnetAt(small, { x: 5, y: 0 }, 1)).toBe('TOP')+ })++ test('further outside an end stays free', () => {+ expect(magnetAt(BOX, { x: 210, y: 100 }, 1)).toBeNull()+ expect(magnetAt(BOX, { x: -8, y: -8 }, 1)).toBeNull()+ })++ test('a straight connector attaches by centres', () => {+ const { editor, page, a } = setup()+ const { endpoint } = connectorAttachment(editor.graph, page, { x: 30, y: 16 }, {+ zoom: 1,+ straight: true+ })+ expect(endpoint).toEqual({ nodeId: a.id, magnet: 'CENTER', position: { x: 0, y: 0 } })+ })+})++describe('the connector tool', () => {+ test('a drag from one layer to another joins them in one undo step and stays on', () => {+ const { editor, a, b } = setup()+ editor.setTool('CONNECTOR')+ editor.connectorBegin(100, 100)+ editor.connectorDrag(300, 150)+ editor.connectorDrag(600, 200)+ editor.connectorRelease(600, 200, true)+ const [connector] = connectors(editor)+ expect(connector.connectorStart).toMatchObject({ nodeId: a.id, magnet: 'AUTO' })+ expect(connector.connectorEnd).toMatchObject({ nodeId: b.id, magnet: 'AUTO' })+ expect([connector.connectorStartCap, connector.connectorEndCap]).toEqual(['NONE', 'ARROW_LINES'])+ expect(editor.state.activeTool).toBe('CONNECTOR')+ editor.undoAction()+ expect(connectors(editor)).toHaveLength(0)+ editor.redoAction()+ expect(connectors(editor)).toHaveLength(1)+ })++ test('a drag within one layer keeps a connector from side to side, as FigJam does', () => {+ const { editor, a } = setup()+ editor.setTool('CONNECTOR')+ editor.connectorBegin(45, 100)+ editor.connectorDrag(155, 100)+ editor.connectorRelease(155, 100, true)+ const [connector] = connectors(editor)+ expect(connector.connectorStart).toMatchObject({ nodeId: a.id, magnet: 'LEFT' })+ expect(connector.connectorEnd).toMatchObject({ nodeId: a.id, magnet: 'RIGHT' })+ })++ test('a click starts a connector that follows the pointer to the next click', () => {+ const { editor, b } = setup()+ editor.setTool('CONNECTOR')+ editor.connectorBegin(300, 400)+ editor.connectorRelease(300, 400, false)+ expect(connectors(editor)).toHaveLength(0)+ editor.connectorHover(450, 400)+ expect(connectors(editor)).toHaveLength(1)+ editor.connectorBegin(600, 200)+ editor.connectorRelease(600, 200, false)+ const [connector] = connectors(editor)+ expect(connector.connectorStart).toMatchObject({ nodeId: null, position: { x: 300, y: 400 } })+ expect(connector.connectorEnd).toMatchObject({ nodeId: b.id })+ })++ test('changing tool drops a connector a click started', () => {+ const { editor, a } = setup()+ editor.select([a.id])+ editor.setTool('CONNECTOR')+ editor.connectorBegin(300, 400)+ editor.connectorRelease(300, 400, false)+ editor.connectorHover(450, 400)+ editor.setTool('SELECT')+ expect(connectors(editor)).toHaveLength(0)+ // The selection the drawing cleared comes back.+ expect([...editor.state.selectedIds]).toEqual([a.id])+ })+})++describe('dragging a connector end', () => {+ test('attaches it where it is dropped, and undo puts it back', () => {+ const { editor, a, b } = setup()+ editor.setTool('CONNECTOR')+ editor.connectorBegin(100, 100)+ editor.connectorRelease(900, 600, true)+ const [connector] = connectors(editor)+ expect(connector.connectorEnd?.nodeId).toBeNull()+ editor.setTool('SELECT')+ editor.connectorEndpointBegin(connector.id, 'connectorEnd')+ editor.connectorEndpointDrag(600, 200)+ expect(editor.state.connectorTarget).toEqual({ nodeId: b.id, magnet: 'AUTO' })+ editor.connectorEndpointCommit()+ expect(editor.graph.getNode(connector.id)?.connectorEnd?.nodeId).toBe(b.id)+ expect(editor.state.connectorTarget).toBeNull()+ editor.undoAction()+ expect(editor.graph.getNode(connector.id)?.connectorEnd?.nodeId).toBeNull()+ expect(editor.graph.getNode(connector.id)?.connectorStart?.nodeId).toBe(a.id)+ })+})++describe('dropping a connector end', () => {+ function framed() {+ const editor = createEditor()+ const page = editor.state.currentPageId+ const frame = editor.graph.createNode('FRAME', page, { x: 0, y: 0, width: 1000, height: 600 })+ const a = editor.graph.createNode('RECTANGLE', frame.id, { x: 100, y: 100, width: 200, height: 200 })+ const b = editor.graph.createNode('RECTANGLE', frame.id, { x: 600, y: 100, width: 200, height: 200 })+ const connector = createConnector(editor.graph, frame.id, {+ start: boundEndpoint(a.id),+ end: boundEndpoint(b.id)+ })+ return { editor, frame, a, b, connector }+ }++ function dropEnd(editor: ReturnType<typeof createEditor>, id: string, x: number, y: number) {+ editor.connectorEndpointBegin(id, 'connectorEnd')+ editor.connectorEndpointDrag(x, y)+ editor.connectorEndpointCommit()+ }++ test('in the frame the connector sits in stays free there', () => {+ const { editor, connector } = framed()+ dropEnd(editor, connector.id, 500, 500)+ expect(editor.graph.getNode(connector.id)?.connectorEnd).toEqual(freeEndpoint(500, 500))+ })++ test('on a layer inside a frame attaches to that layer', () => {+ const { editor, connector } = framed()+ const c = editor.graph.createNode('RECTANGLE', editor.graph.getNode(connector.id)?.parentId ?? '', {+ x: 350,+ y: 400,+ width: 150,+ height: 150+ })+ dropEnd(editor, connector.id, 425, 475)+ expect(editor.graph.getNode(connector.id)?.connectorEnd).toMatchObject({ nodeId: c.id, magnet: 'AUTO' })+ })++ test('on a layer outside a frame that does not clip attaches to that layer', () => {+ const { editor, frame, connector } = framed()+ editor.graph.updateNode(frame.id, { clipsContent: false })+ const outside = editor.graph.createNode('RECTANGLE', frame.id, {+ x: 1100,+ y: 100,+ width: 100,+ height: 100+ })+ dropEnd(editor, connector.id, 1150, 150)+ expect(editor.graph.getNode(connector.id)?.connectorEnd).toMatchObject({+ nodeId: outside.id,+ magnet: 'AUTO'+ })+ })++ test('pressing and releasing an end without moving keeps a connector whose ends share a layer', () => {+ const { editor, a, connector } = framed()+ editor.graph.updateNode(connector.id, { connectorEnd: boundEndpoint(a.id, 'RIGHT') })+ editor.connectorEndpointBegin(connector.id, 'connectorEnd')+ editor.connectorEndpointCommit()+ expect(editor.graph.getNode(connector.id)).toBeDefined()+ })++ test('on the layer its other end joins deletes the connector, and undo brings it back', () => {+ const { editor, a, b, connector } = framed()+ dropEnd(editor, connector.id, 200, 200)+ expect(editor.graph.getNode(connector.id)).toBeUndefined()+ editor.undoAction()+ const restored = editor.graph.getNode(connector.id)+ expect(restored?.connectorStart?.nodeId).toBe(a.id)+ expect(restored?.connectorEnd?.nodeId).toBe(b.id)+ })+})diff --git a/packages/core/tests/figma-api/connector.test.ts b/packages/core/tests/figma-api/connector.test.tsnew file mode 100644index 000000000..60fa021bb--- /dev/null+++ b/packages/core/tests/figma-api/connector.test.ts@@ -0,0 +1,147 @@+import { describe, expect, test } from 'bun:test'++import { pick } from 'es-toolkit'++import { getNodeOrThrow } from '#core-tests/helpers/assert'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { connectorSublayers, SceneGraph } from '@open-pencil/scene-graph'++function setup() {+ const graph = new SceneGraph()+ const api = new FigmaAPI(graph)+ const a = api.createRectangle()+ a.resize(100, 100)+ a.x = 0+ a.y = 0+ const b = api.createRectangle()+ b.resize(100, 100)+ b.x = 400+ b.y = 200+ return { graph, api, a, b }+}++// Values recorded from `figma.createConnector()` in FigJam desktop on 2026-10-15.+describe('ConnectorNode', () => {+ test('a new connector runs free from the page origin with an arrow at its end', () => {+ const { api } = setup()+ const connector = api.createConnector()+ const page = api.currentPage.id+ expect({+ name: connector.name,+ x: connector.x,+ y: connector.y,+ width: connector.width,+ height: connector.height,+ lineType: connector.connectorLineType,+ start: connector.connectorStart,+ end: connector.connectorEnd,+ startCap: connector.connectorStartStrokeCap,+ endCap: connector.connectorEndStrokeCap,+ strokeWeight: connector.strokeWeight,+ color: connector.strokes[0]?.type === 'SOLID' && pick(connector.strokes[0].color, ['r', 'g', 'b']),+ text: connector.text.characters+ }).toEqual({+ name: 'Connector line',+ x: 0,+ y: 0,+ width: 200,+ height: 0,+ lineType: 'ELBOWED',+ start: { endpointNodeId: page, position: { x: 0, y: 0 } },+ end: { endpointNodeId: page, position: { x: 200, y: 0 } },+ startCap: 'NONE',+ endCap: 'ARROW_LINES',+ strokeWeight: 4,+ color: { r: 117 / 255, g: 117 / 255, b: 117 / 255 },+ text: ''+ })+ })++ test('ends bound to layers report their magnets and route between them', () => {+ const { api, a, b } = setup()+ const connector = api.createConnector()+ connector.connectorStart = { endpointNodeId: a.id, magnet: 'AUTO' }+ connector.connectorEnd = { endpointNodeId: b.id, magnet: 'RIGHT' }+ expect(connector.connectorStart).toEqual({ endpointNodeId: a.id, magnet: 'AUTO' })+ expect(connector.connectorEnd).toEqual({ endpointNodeId: b.id, magnet: 'RIGHT' })+ // Figma's FigJam shapes keep 2 px further off for their stroke: 108 and 440 there.+ expect([connector.x, connector.y, connector.width, connector.height]).toEqual([+ 106, 50, 442, 200+ ])++ connector.connectorEnd = { endpointNodeId: b.id, position: { x: 10, y: 20 } }+ expect(connector.connectorEnd).toEqual({ endpointNodeId: b.id, position: { x: 10, y: 20 } })++ a.x = 100+ expect(connector.x).toBe(206)+ })++ test('a straight connector attaches by centres and refuses side magnets', () => {+ const { api, a } = setup()+ const connector = api.createConnector()+ connector.connectorStart = { endpointNodeId: a.id, magnet: 'AUTO' }+ connector.connectorLineType = 'STRAIGHT'+ expect(connector.connectorStart).toEqual({ endpointNodeId: a.id, magnet: 'CENTER' })+ expect(() => {+ connector.connectorStart = { endpointNodeId: a.id, magnet: 'TOP' }+ }).toThrow(+ 'in set_connectorStart: Straight connector endpoints may only use the CENTER or NONE magnets.'+ )+ })++ test('refuses unknown layers and caps a connector cannot take', () => {+ const { api } = setup()+ const connector = api.createConnector()+ expect(() => {+ connector.connectorStart = { endpointNodeId: 'nope', magnet: 'AUTO' }+ }).toThrow('in set_connectorStart: Invalid endpointNodeId')+ expect(() => {+ connector.connectorStartStrokeCap = 'ROUND' as ConnectorStrokeCap+ }).toThrow('in set_connectorStartStrokeCap: Property "connectorStartStrokeCap" failed validation')+ connector.connectorStartStrokeCap = 'DIAMOND_FILLED'+ expect(connector.connectorStartStrokeCap).toBe('DIAMOND_FILLED')+ expect(() => {+ connector.connectorLineType = 'ARC' as 'STRAIGHT'+ }).toThrow('in set_connectorLineType: Property "connectorLineType" failed validation')+ expect(connector.connectorLineType).toBe('ELBOWED')+ })++ test('stroke alignment and joins style the line, as the other stroke fields do', () => {+ const { graph, api } = setup()+ const connector = api.createConnector()+ connector.strokeAlign = 'INSIDE'+ connector.strokeJoin = 'BEVEL'+ const line = connectorSublayers(graph, getNodeOrThrow(graph, connector.id))?.line+ expect(line?.strokes[0]).toMatchObject({ align: 'INSIDE', join: 'BEVEL' })+ expect([connector.strokeAlign, connector.strokeJoin]).toEqual(['INSIDE', 'BEVEL'])+ })++ test('the label is its text and is laid on its plate', () => {+ const { graph, api } = setup()+ const connector = api.createConnector()+ connector.text.characters = 'Label'+ expect(connector.text.characters).toBe('Label')+ // Reading geometry routes the edit, as it lays out any other.+ const labelHeight = connector.text.height+ const node = graph.getNode(connector.id)+ const plate = node && connectorSublayers(graph, node)?.labelBackground+ expect([plate?.height, plate?.visible]).toEqual([labelHeight + 17, true])+ })++ test('its stroke lives on its line, as Figma presents it', () => {+ const { api } = setup()+ const connector = api.createConnector()+ connector.strokeWeight = 8+ connector.dashPattern = [10, 6]+ expect([connector.strokeWeight, connector.dashPattern]).toEqual([8, [10, 6]])+ })++ test('removing a layer it joins removes the connector, as Figma does', () => {+ const { api, a } = setup()+ const connector = api.createConnector()+ connector.connectorStart = { endpointNodeId: a.id, magnet: 'AUTO' }+ a.remove()+ expect(connector.removed).toBe(true)+ })+})diff --git a/packages/core/tests/io/formats/fig/session/transfer.test.ts b/packages/core/tests/io/formats/fig/session/transfer.test.tsnew file mode 100644index 000000000..f9ceee393--- /dev/null+++ b/packages/core/tests/io/formats/fig/session/transfer.test.ts@@ -0,0 +1,16 @@+import { expect, test } from 'bun:test'++import { deserializeSceneGraph, serializeSceneGraph } from '#core/kiwi/fig/parse/transfer'++import { createConnector, freeEndpoint, SceneGraph } from '@open-pencil/scene-graph'++test('a graph sent from the reader keeps its connectors indexed for routing', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const connector = createConnector(graph, page, {+ start: freeEndpoint(0, 0),+ end: freeEndpoint(100, 0)+ })+ const received = deserializeSceneGraph(structuredClone(serializeSceneGraph(graph)))+ expect([...received.connectorIds]).toEqual([connector.id])+})diff --git a/packages/core/tests/tools/create/connector.test.ts b/packages/core/tests/tools/create/connector.test.tsnew file mode 100644index 000000000..5b3db72f1--- /dev/null+++ b/packages/core/tests/tools/create/connector.test.ts@@ -0,0 +1,43 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI, type FigmaConnectorNode } from '@open-pencil/core/figma-api'+import { ALL_TOOLS } from '@open-pencil/core/tools'+import { SceneGraph } from '@open-pencil/scene-graph'++function createConnector(figma: FigmaAPI, args: Record<string, unknown>) {+ const tool = ALL_TOOLS.find((item) => item.name === 'create_connector')+ if (!tool) throw new Error('No create_connector tool')+ return tool.execute(figma, args)+}++describe('create_connector', () => {+ test('joins two layers with a labelled elbow that follows them', () => {+ const figma = new FigmaAPI(new SceneGraph())+ const a = figma.createRectangle()+ const b = figma.createRectangle()+ b.x = 400+ const summary = createConnector(figma, {+ start: { id: a.id },+ end: { id: b.id, magnet: 'LEFT' },+ label: 'Next'+ }) as { id: string }+ const connector = figma.getNodeById(summary.id) as FigmaConnectorNode+ expect(connector.connectorStart).toEqual({ endpointNodeId: a.id, magnet: 'AUTO' })+ expect(connector.connectorEnd).toEqual({ endpointNodeId: b.id, magnet: 'LEFT' })+ expect(connector.text.characters).toBe('Next')+ })++ test('a straight connector to a point attaches by the layer centre', () => {+ const figma = new FigmaAPI(new SceneGraph())+ const a = figma.createRectangle()+ const summary = createConnector(figma, {+ start: { id: a.id },+ end: { x: 300, y: 300 },+ line_type: 'STRAIGHT',+ end_cap: 'TRIANGLE_FILLED'+ }) as { id: string }+ const connector = figma.getNodeById(summary.id) as FigmaConnectorNode+ expect(connector.connectorStart).toEqual({ endpointNodeId: a.id, magnet: 'CENTER' })+ expect(connector.connectorEndStrokeCap).toBe('TRIANGLE_FILLED')+ })+})diff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.mdindex ac2c89e9b..cb17db258 100644--- a/packages/docs/programmable/mcp-server.md+++ b/packages/docs/programmable/mcp-server.md@@ -236,6 +236,7 @@ Settings tools never expose credentials, AI models, MCP connections, storage, or| `create_shape` | Create a shape (`FRAME`, `RECTANGLE`, `ELLIPSE`, `TEXT`, `LINE`, `STAR`, `POLYGON`, `SECTION`) || `create_vector` | Create a vector node from a path string || `create_slice` | Create an export slice |+| `create_connector` | Join two layers, or a layer and a point, with a connector that follows them || `create_page` | Create a new page || `render` | Render JSX to design nodes — create entire component trees in one call || `create_component` | Convert a frame/group into a component |diff --git a/packages/docs/reference/keyboard-shortcuts.md b/packages/docs/reference/keyboard-shortcuts.mdindex d53546241..d9415fea0 100644--- a/packages/docs/reference/keyboard-shortcuts.md+++ b/packages/docs/reference/keyboard-shortcuts.md@@ -30,6 +30,7 @@ Full Figma-compatible shortcut map. ✅ = implemented.| <kbd>⇧</kbd><kbd>P</kbd> | Pencil | ✅ || <kbd>T</kbd> | Text | ✅ || — | Sticky note (FigJam) | ✅ (toolbar, hidden by default) |+| — | Connector (FigJam) | ✅ (toolbar, hidden by default) || <kbd>C</kbd> | Comment | ✅ || <kbd>I</kbd> | Eyedropper | 🔲 |diff --git a/packages/scene-graph/src/arrow-caps.ts b/packages/scene-graph/src/arrow-caps.tsindex ffdcb10ff..8269ade9d 100644--- a/packages/scene-graph/src/arrow-caps.ts+++ b/packages/scene-graph/src/arrow-caps.ts@@ -1,7 +1,12 @@import type { Vector } from './primitives'import type { Stroke, StrokeCap, VectorNetwork } from './types'-export type ArrowCapKind = 'ARROW_LINES' | 'ARROW_EQUILATERAL'+export type ArrowCapKind =+ | 'ARROW_LINES'+ | 'ARROW_EQUILATERAL'+ | 'TRIANGLE_FILLED'+ | 'DIAMOND_FILLED'+ | 'CIRCLE_FILLED'export interface ArrowEndpoint {x: number@@ -19,9 +24,25 @@ export interface ArrowWing {/** Arrow head side length relative to stroke weight, tuned to match Figma. */const ARROW_SIDE_PER_WEIGHT = 4const WING_SWEEP = Math.PI / 6+/**+ * Filled triangle, diamond, and circle heads relative to stroke weight, from the stroke outlines+ * Figma gives for them: the triangle runs 5 back from the end and spreads to 5/√3 on either side+ * at it, the diamond reaches 5/√3 from the end every way, and the circle has radius 8/3.+ */+const FILLED_HEAD_DEPTH = 5+const FILLED_HEAD_HALF_WIDTH = 5 / Math.sqrt(3)+const CIRCLE_HEAD_RADIUS = 8 / 3++const ARROW_CAPS: ReadonlySet<string> = new Set<ArrowCapKind>([+ 'ARROW_LINES',+ 'ARROW_EQUILATERAL',+ 'TRIANGLE_FILLED',+ 'DIAMOND_FILLED',+ 'CIRCLE_FILLED'+])export function isArrowCap(cap: string | undefined): cap is ArrowCapKind {- return cap === 'ARROW_LINES' || cap === 'ARROW_EQUILATERAL'+ return cap !== undefined && ARROW_CAPS.has(cap)}/**@@ -47,6 +68,32 @@ export function arrowCapOverflow(return overflow}+/** An open path end that carries a head: its segment and which end of it, and its cap. */+interface OpenArrowEnd {+ segment: number+ side: 'start' | 'end'+ cap: ArrowCapKind+}++/** The open ends of `network` that carry a head: vertices used by exactly one segment. */+function openArrowEnds(network: VectorNetwork, fallbackCap: StrokeCap): OpenArrowEnd[] {+ const degrees = Array.from({ length: network.vertices.length }, () => 0)+ for (const segment of network.segments) {+ degrees[segment.start]+++ degrees[segment.end]+++ }+ const ends: OpenArrowEnd[] = []+ network.segments.forEach((segment, index) => {+ for (const side of ['start', 'end'] as const) {+ const vertex = network.vertices[segment[side]]+ if (degrees[segment[side]] !== 1) continue+ const cap = (vertex.strokeCap as StrokeCap | undefined) ?? fallbackCap+ if (isArrowCap(cap)) ends.push({ segment: index, side, cap })+ }+ })+ return ends+}+/*** Finds the open path ends that should carry an arrow head: vertices used by* exactly one segment, with a per-vertex cap override falling back to the@@ -57,37 +104,25 @@ export function collectArrowEndpoints(network: VectorNetwork,fallbackCap: StrokeCap): ArrowEndpoint[] {- const degrees = Array.from({ length: network.vertices.length }, () => 0)- for (const segment of network.segments) {- degrees[segment.start]++- degrees[segment.end]++- }-const endpoints: ArrowEndpoint[] = []- for (const segment of network.segments) {- for (const side of ['start', 'end'] as const) {- const vertexIndex = segment[side]- if (degrees[vertexIndex] !== 1) continue- const vertex = network.vertices[vertexIndex]- const cap = (vertex.strokeCap as StrokeCap | undefined) ?? fallbackCap- if (!isArrowCap(cap)) continue-- const tangent = side === 'start' ? segment.tangentStart : segment.tangentEnd- let controlX: number- let controlY: number- if (Math.abs(tangent.x) > 0.001 || Math.abs(tangent.y) > 0.001) {- controlX = vertex.x + tangent.x- controlY = vertex.y + tangent.y- } else {- const other = network.vertices[side === 'start' ? segment.end : segment.start]- controlX = other.x- controlY = other.y- }- const dx = vertex.x - controlX- const dy = vertex.y - controlY- if (dx === 0 && dy === 0) continue- endpoints.push({ x: vertex.x, y: vertex.y, angle: Math.atan2(dy, dx), cap })+ for (const { segment: index, side, cap } of openArrowEnds(network, fallbackCap)) {+ const segment = network.segments[index]+ const vertex = network.vertices[segment[side]]+ const tangent = side === 'start' ? segment.tangentStart : segment.tangentEnd+ let controlX: number+ let controlY: number+ if (Math.abs(tangent.x) > 0.001 || Math.abs(tangent.y) > 0.001) {+ controlX = vertex.x + tangent.x+ controlY = vertex.y + tangent.y+ } else {+ const other = network.vertices[side === 'start' ? segment.end : segment.start]+ controlX = other.x+ controlY = other.y}+ const dx = vertex.x - controlX+ const dy = vertex.y - controlY+ if (dx === 0 && dy === 0) continue+ endpoints.push({ x: vertex.x, y: vertex.y, angle: Math.atan2(dy, dx), cap })}return endpoints}@@ -134,6 +169,177 @@ export function arrowLinesSegments(return [makeWing(angle + Math.PI - WING_SWEEP), makeWing(angle + Math.PI + WING_SWEEP)]}+function headAxes(angle: number) {+ const dir = { x: Math.cos(angle), y: Math.sin(angle) }+ return { dir, perp: { x: -dir.y, y: dir.x } }+}++/**+ * Points of a filled triangle head: its base across the end, narrowing back along the path to+ * the shaft's width, in drawing order.+ */+export function triangleCapPoints(+ x: number,+ y: number,+ angle: number,+ weight: number+): [Vector, Vector, Vector, Vector] {+ const { dir, perp } = headAxes(angle)+ const back = {+ x: x - FILLED_HEAD_DEPTH * weight * dir.x,+ y: y - FILLED_HEAD_DEPTH * weight * dir.y+ }+ const at = (point: Vector, side: number) => ({+ x: point.x + side * perp.x,+ y: point.y + side * perp.y+ })+ const half = FILLED_HEAD_HALF_WIDTH * weight+ return [at(back, weight / 2), at({ x, y }, half), at({ x, y }, -half), at(back, -weight / 2)]+}++/** Points of a filled diamond head centred on the end, in drawing order. */+export function diamondCapPoints(+ x: number,+ y: number,+ angle: number,+ weight: number+): [Vector, Vector, Vector, Vector] {+ const { dir, perp } = headAxes(angle)+ const reach = FILLED_HEAD_HALF_WIDTH * weight+ return [+ { x: x + reach * dir.x, y: y + reach * dir.y },+ { x: x + reach * perp.x, y: y + reach * perp.y },+ { x: x - reach * dir.x, y: y - reach * dir.y },+ { x: x - reach * perp.x, y: y - reach * perp.y }+ ]+}++/** Radius of a filled circle head, centred on the end. */+export function circleCapRadius(weight: number): number {+ return CIRCLE_HEAD_RADIUS * weight+}++/**+ * How far a line stops short of its end under a triangle or equilateral head, in stroke weights:+ * half a weight inside the head's base, as Figma draws its triangle 5 weights deep.+ */+function shaftTrim(cap: StrokeCap): number {+ if (cap === 'TRIANGLE_FILLED') return FILLED_HEAD_DEPTH - 0.5+ return (ARROW_SIDE_PER_WEIGHT / 2) * Math.sqrt(3) - 0.5+}++function trimsShaft(cap: StrokeCap | undefined): boolean {+ return cap === 'TRIANGLE_FILLED' || cap === 'ARROW_EQUILATERAL'+}++/** Whether any open end of `network` carries a head the line stops short of. */+export function hasTrimmedShaft(network: VectorNetwork, fallbackCap: StrokeCap): boolean {+ return network.vertices.some((vertex) =>+ trimsShaft((vertex.strokeCap as StrokeCap | undefined) ?? fallbackCap)+ )+}++/**+ * The network with its line pulled back from each open end that carries a triangle or+ * equilateral head, as Figma draws it, so the line's own cap stays inside the head.+ */+export function trimArrowShafts(+ network: VectorNetwork,+ fallbackCap: StrokeCap,+ weight: number+): VectorNetwork {+ const trimmed = structuredClone(network)+ // By segment and side, not position: an open path's two ends may meet at one point.+ for (const { segment, side, cap } of openArrowEnds(network, fallbackCap)) {+ if (!trimsShaft(cap)) continue+ trimSegmentEnd(trimmed, trimmed.segments[segment], side === 'end', shaftTrim(cap) * weight)+ }+ return trimmed+}++type Cubic = [Vector, Vector, Vector, Vector]++function cubicAt([a, b, c, d]: Cubic, t: number): Vector {+ const u = 1 - t+ return {+ x: u * u * u * a.x + 3 * u * u * t * b.x + 3 * u * t * t * c.x + t * t * t * d.x,+ y: u * u * u * a.y + 3 * u * u * t * b.y + 3 * u * t * t * c.y + t * t * t * d.y+ }+}++function lerp(a: Vector, b: Vector, t: number): Vector {+ return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }+}++/** The part of a cubic from its start to `t`, by de Casteljau. */+function cubicHead([a, b, c, d]: Cubic, t: number): Cubic {+ const ab = lerp(a, b, t)+ const bc = lerp(b, c, t)+ const cd = lerp(c, d, t)+ const abc = lerp(ab, bc, t)+ const bcd = lerp(bc, cd, t)+ return [a, ab, abc, lerp(abc, bcd, t)]+}++/**+ * Pulls one end of `segment` back along it until it lies `distance` from where it was, keeping+ * the rest of the curve where it is.+ */+function trimSegmentEnd(+ network: VectorNetwork,+ segment: VectorNetwork['segments'][number],+ atEnd: boolean,+ distance: number+) {+ const start = network.vertices[segment.start]+ const end = network.vertices[segment.end]+ // Oriented so the trimmed end comes last.+ const from = atEnd ? start : end+ const to = atEnd ? end : start+ const out = atEnd ? segment.tangentStart : segment.tangentEnd+ const back = atEnd ? segment.tangentEnd : segment.tangentStart+ const cubic: Cubic = [+ { x: from.x, y: from.y },+ { x: from.x + out.x, y: from.y + out.y },+ { x: to.x + back.x, y: to.y + back.y },+ { x: to.x, y: to.y }+ ]+ const length = Math.hypot(to.x - from.x, to.y - from.y)+ if (length <= distance) return+ const index = atEnd ? segment.end : segment.start+ const isStraight = out.x === 0 && out.y === 0 && back.x === 0 && back.y === 0+ if (isStraight) {+ // A straight segment stays straight, so the corner before it keeps its radius.+ const keep = (length - distance) / length+ const vertex = network.vertices[index]+ network.vertices[index] = {+ ...vertex,+ x: from.x + (to.x - from.x) * keep,+ y: from.y + (to.y - from.y) * keep+ }+ return+ }+ let low = 0+ let high = 1+ for (let step = 0; step < 40; step++) {+ const t = (low + high) / 2+ const point = cubicAt(cubic, t)+ if (Math.hypot(point.x - to.x, point.y - to.y) > distance) low = t+ else high = t+ }+ const [, c1, c2, tip] = cubicHead(cubic, low)+ network.vertices[index] = { ...network.vertices[index], x: tip.x, y: tip.y }+ const kept = { x: c1.x - from.x, y: c1.y - from.y }+ const trimmedBack = { x: c2.x - tip.x, y: c2.y - tip.y }+ if (atEnd) {+ segment.tangentStart = kept+ segment.tangentEnd = trimmedBack+ } else {+ segment.tangentEnd = kept+ segment.tangentStart = trimmedBack+ }+}+/** Arrow endpoints for a LINE node, whose local geometry runs (0,0) → (width,height). */export function lineArrowEndpoints(width: number, height: number, cap: StrokeCap): ArrowEndpoint[] {if (!isArrowCap(cap)) return []diff --git a/packages/scene-graph/src/connectors/create.ts b/packages/scene-graph/src/connectors/create.tsnew file mode 100644index 000000000..ef098c991--- /dev/null+++ b/packages/scene-graph/src/connectors/create.ts@@ -0,0 +1,45 @@+import type { SceneGraph } from '../index'+import type { ConnectorEndpoint, ConnectorLineType, SceneNode, StrokeCap } from '../types'+import { layoutConnector } from './layout'+import { buildConnectorSublayers } from './sublayers'++/** What a new connector joins and how it looks; anything left out takes Figma's defaults. */+export interface ConnectorContent {+ start: ConnectorEndpoint+ end: ConnectorEndpoint+ lineType?: ConnectorLineType+ startCap?: StrokeCap+ endCap?: StrokeCap+ /** The label on the line. */+ text?: string+}++/**+ * Makes a connector in `parentId` with its line and label, routed between its ends. Figma names+ * a new connector "Connector line".+ */+export function createConnector(+ graph: SceneGraph,+ parentId: string,+ content: ConnectorContent,+ props: Partial<SceneNode> = {}+): SceneNode {+ const connector = graph.createNode('CONNECTOR', parentId, {+ name: 'Connector line',+ fills: [],+ strokes: [],+ connectorStart: structuredClone(content.start),+ connectorEnd: structuredClone(content.end),+ ...(content.lineType && { connectorLineType: content.lineType }),+ ...(content.startCap && { connectorStartCap: content.startCap }),+ ...(content.endCap && { connectorEndCap: content.endCap }),+ ...props+ })+ const text = content.text ?? ''+ buildConnectorSublayers(graph, connector, {+ label: { text },+ labelBackground: { visible: text !== '' }+ })+ layoutConnector(graph, connector)+ return connector+}diff --git a/packages/scene-graph/src/connectors/index.ts b/packages/scene-graph/src/connectors/index.tsindex 1fb3ff8e2..0f2ca31c1 100644--- a/packages/scene-graph/src/connectors/index.ts+++ b/packages/scene-graph/src/connectors/index.ts@@ -1,6 +1,7 @@+export { createConnector, type ConnectorContent } from './create'export { hitsConnectorLine } from './hit'export { CONNECTOR_LABEL_PADDING, placeConnectorLabel, type ConnectorLabelLayout } from './label'-export { attachedConnectors, layoutConnector } from './layout'+export { attachedConnectors, connectorsAffectedBy, layoutConnector } from './layout'export { connectorEndGap } from './gaps'export { connectorNetwork, type ConnectorPiece } from './pieces'export { routeConnector } from './route'diff --git a/packages/scene-graph/src/connectors/layout.ts b/packages/scene-graph/src/connectors/layout.tsindex 20f0b8a90..cca674d9a 100644--- a/packages/scene-graph/src/connectors/layout.ts+++ b/packages/scene-graph/src/connectors/layout.ts@@ -10,7 +10,7 @@ import { CONNECTOR_LABEL_PADDING, placeConnectorLabel, type ConnectorLabelLayoutimport { connectorNetwork, piecesBounds, type ConnectorPiece } from './pieces'import { routeConnector } from './route'import type { ConnectorRouteEnd } from './sides'-import { connectorSublayers, type ConnectorSublayers } from './sublayers'+import { connectorRouteEnds, connectorSublayers, type ConnectorSublayers } from './sublayers'/*** An end as the router sees it, in the connector's parent's axes: the box of the layer it follows@@ -71,10 +71,11 @@ function routeWrites({ line, label, labelBackground }: ConnectorSublayers,pieces: ConnectorPiece[],placed: ConnectorLabelLayout | null,+ labelled: boolean,keepBox: boolean): Write[] | null {const lineBox = pieces.length > 0 ? piecesBounds(pieces) : null- const boxes = compact([lineBox, placed?.plate])+ const boxes = compact([lineBox, labelled ? placed?.plate : null])if (boxes.length === 0) return nullconst bounds = computeBounds(boxes)const frame = keepBox ? connector : bounds@@ -95,24 +96,18 @@ function routeWrites(}]]- if (!placed)- return [...writes, [labelBackground, { visible: false }], [label, { visible: false }]]+ if (!placed) return [...writes, [labelBackground, { visible: false }]]const x = placed.plate.x - frame.xconst y = placed.plate.y - frame.yconst { width, height } = placed.plate+ // An empty label still sits where its text goes, ready to be typed into.return [...writes,- [labelBackground, { x, y, width, height, visible: true }],+ [labelBackground, { x, y, width, height, visible: labelled }],[label, { x: x + CONNECTOR_LABEL_PADDING, y: y + CONNECTOR_LABEL_PADDING, visible: true }]]}-/** Where a connector's line last started or ended, for an end whose layer is gone. */-function lastRoutePoint(connector: SceneNode, line: SceneNode, index: 0 | -1): Vector | undefined {- const vertex = line.vectorNetwork?.vertices.at(index)- return vertex && { x: connector.x + line.x + vertex.x, y: connector.y + line.y + vertex.y }-}-/*** Routes a connector again from the layers its ends follow and lays out its line, label plate,* and label to match, through `update` so the caller decides whether that is an edit or a@@ -131,30 +126,26 @@ export function layoutConnector(const { connectorStart, connectorEnd } = connectorif (!parts || !connectorStart || !connectorEnd) return falseconst { line, label } = parts+ // Where the line last ran, for an end whose layer is gone.+ const drawn = connectorRouteEnds(graph, connector)const start = routeEnd(graph,connector,connectorStart,connector.connectorStartCap,- lastRoutePoint(connector, line, 0)- )- const end = routeEnd(- graph,- connector,- connectorEnd,- connector.connectorEndCap,- lastRoutePoint(connector, line, -1)+ drawn?.start)+ const end = routeEnd(graph, connector, connectorEnd, connector.connectorEndCap, drawn?.end)if (!start || !end) return falseconst weight = line.strokes[0]?.weight ?? line.strokeWeightconst pieces = routeConnector(connector.connectorLineType, start, end, weight)- const placed = label.text- ? placeConnectorLabel(pieces, {- width: label.width + CONNECTOR_LABEL_PADDING * 2,- height: label.height + CONNECTOR_LABEL_PADDING * 2- })- : null- const writes = routeWrites(connector, parts, placed?.pieces ?? pieces, placed, keepBox)+ const labelled = label.text !== ''+ const placed = placeConnectorLabel(pieces, {+ width: label.width + CONNECTOR_LABEL_PADDING * 2,+ height: label.height + CONNECTOR_LABEL_PADDING * 2+ })+ const routed = labelled && placed ? placed.pieces : pieces+ const writes = routeWrites(connector, parts, routed, placed, labelled, keepBox)let moved = false// A route derives from its ends, so laying it out is layout rather than an edit, as moving the// connector it fits is not.@@ -174,6 +165,14 @@ function withinAny(graph: SceneGraph, id: string, ids: ReadonlySet<string>): booreturn graph.closest(id, (node) => ids.has(node.id)) !== undefined}+/** The graph's connectors, from its index rather than a scan of every layer. */+function* connectorsIn(graph: SceneGraph): Generator<SceneNode> {+ for (const id of graph.connectorIds) {+ const node = graph.getNode(id)+ if (node?.type === 'CONNECTOR') yield node+ }+}+/*** The connectors with an end on one of `ids` or a layer inside them, which go when those layers* are deleted, as in FigJam. Connectors inside `ids` themselves are left out.@@ -181,10 +180,27 @@ function withinAny(graph: SceneGraph, id: string, ids: ReadonlySet<string>): booexport function attachedConnectors(graph: SceneGraph, ids: Iterable<string>): SceneNode[] {const roots = new Set(ids)const attached: SceneNode[] = []- for (const node of graph.getAllNodes()) {- if (node.type !== 'CONNECTOR' || withinAny(graph, node.id, roots)) continue+ for (const node of connectorsIn(graph)) {+ if (withinAny(graph, node.id, roots)) continueconst ends = [node.connectorStart?.nodeId, node.connectorEnd?.nodeId]if (ends.some((id) => id && withinAny(graph, id, roots))) attached.push(node)}return attached}++/**+ * The connectors an edit to `ids` moves: those with an end on one of them or on a layer inside+ * them, those inside them, and those whose line or label is among them.+ */+export function connectorsAffectedBy(graph: SceneGraph, ids: ReadonlySet<string>): SceneNode[] {+ if (ids.size === 0) return []+ const affected: SceneNode[] = []+ for (const node of connectorsIn(graph)) {+ const watched = [node.id, node.connectorStart?.nodeId, node.connectorEnd?.nodeId]+ const touched =+ watched.some((id) => id && withinAny(graph, id, ids)) ||+ node.childIds.some((id) => ids.has(id))+ if (touched) affected.push(node)+ }+ return affected+}diff --git a/packages/scene-graph/src/connectors/sublayers.ts b/packages/scene-graph/src/connectors/sublayers.tsindex 4d8bdeed1..ee205e840 100644--- a/packages/scene-graph/src/connectors/sublayers.ts+++ b/packages/scene-graph/src/connectors/sublayers.ts@@ -45,10 +45,13 @@ export function connectorSublayers(return { line, labelBackground, label }}-/** FigJam keeps a connector's box to its route: it never turns or resizes on its own. */+/**+ * FigJam keeps a connector's box to its route, so it never turns or resizes on its own; typing+ * into it edits its label.+ */export const CONNECTOR_KIND: GeneratedFrameKind = {complete: (graph, frame) => connectorSublayers(graph, frame) !== null,- text: () => undefined,+ text: (graph, frame) => connectorSublayers(graph, frame)?.label,rotates: false,resizes: false,namedByText: false@@ -105,16 +108,25 @@ export function connectorRouteEnds(graph: SceneGraph,connector: SceneNode): { start: Vector; end: Vector } | null {- const line = connectorSublayers(graph, connector)?.line- const vertices = line?.vectorNetwork?.vertices ?? []- const first = vertices.at(0)- const last = vertices.at(-1)- if (!line || !first || !last) return null+ const ends = connectorLineEnds(graph, connector)+ if (!ends) return nullconst at = (vertex: Vector) => ({- x: connector.x + line.x + vertex.x,- y: connector.y + line.y + vertex.y+ x: connector.x + ends.line.x + vertex.x,+ y: connector.y + ends.line.y + vertex.y})- return { start: at(first), end: at(last) }+ return { start: at(ends.start), end: at(ends.end) }+}++/** A connector's line and where it starts and ends, in the line's own axes. */+export function connectorLineEnds(+ graph: SceneGraph,+ connector: SceneNode+): { line: SceneNode; start: Vector; end: Vector } | null {+ const line = connectorSublayers(graph, connector)?.line+ const vertices = line?.vectorNetwork?.vertices ?? []+ const start = vertices.at(0)+ const end = vertices.at(-1)+ return line && start && end ? { line, start, end } : null}/** A free connector end at a point in the connector's parent's axes. */diff --git a/packages/scene-graph/src/generated/index.ts b/packages/scene-graph/src/generated/index.tsindex 90d5ae64e..d32215fda 100644--- a/packages/scene-graph/src/generated/index.ts+++ b/packages/scene-graph/src/generated/index.ts@@ -36,7 +36,7 @@ export function generatedFrameOwner(graph: SceneGraph, node: SceneNode): SceneNoreturn node.parentId ? graph.closest(node.parentId, isGeneratedFrame) : undefined}-/** The text a generated frame edits in place, such as a sticky note's body. */+/** The text a generated frame edits in place: a sticky note's body or a connector's label. */export function generatedFrameText(graph: SceneGraph, node: SceneNode): SceneNode | undefined {return generatedFrameKind(node)?.text(graph, node)}diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 3359ba8e6..9ca7f7873 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -224,6 +224,8 @@ export class SceneGraph {private derivedLayoutDepth = 0positionPreviewVersion = 0instanceIndex = new Map<string, Set<string>>()+ /** Every connector in the graph, so routing need not scan every layer. */+ connectorIds = new Set<string>()constructor(private readonly idGenerator: () => string = generateId) {const root = createDefaultNode(this.idGenerator, 'FRAME', {@@ -527,6 +529,7 @@ export class SceneGraph {private registerNode(node: SceneNode, parentId: string | null): SceneNode {node.parentId = parentIdthis.nodes.set(node.id, node)+ if (node.type === 'CONNECTOR') this.connectorIds.add(node.id)for (const observer of this.changeObservers) observer.created(node)if (node.type === 'INSTANCE' && node.componentId) {let set = this.instanceIndex.get(node.componentId)@@ -867,6 +870,7 @@ export class SceneGraph {if (node.type === 'INSTANCE' && node.componentId) {this.instanceIndex.get(node.componentId)?.delete(id)}+ this.connectorIds.delete(id)this.nodes.delete(id)this.emitter.emit('node:deleted', id, node.parentId)}diff --git a/packages/scene-graph/tests/connectors/layout.test.ts b/packages/scene-graph/tests/connectors/layout.test.tsindex d99cca9ae..9701d3256 100644--- a/packages/scene-graph/tests/connectors/layout.test.ts+++ b/packages/scene-graph/tests/connectors/layout.test.ts@@ -6,6 +6,7 @@ import {buildConnectorSublayers,connectorRouteEnds,connectorSublayers,+ createConnector,freeEndpoint,layoutConnector,SceneGraph,@@ -121,3 +122,15 @@ describe('connector layout', () => {).toEqual([nested.id, inside.id].sort())})})++test('the graph keeps its connectors indexed as they come and go', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const connector = createConnector(graph, page, {+ start: freeEndpoint(0, 0),+ end: freeEndpoint(100, 0)+ })+ expect(graph.connectorIds.has(connector.id)).toBe(true)+ graph.deleteNode(connector.id)+ expect(graph.connectorIds.has(connector.id)).toBe(false)+})diff --git a/packages/vue/src/canvas/text-edit/input.ts b/packages/vue/src/canvas/text-edit/input.tsindex 0418d4fc5..965b797e8 100644--- a/packages/vue/src/canvas/text-edit/input.ts+++ b/packages/vue/src/canvas/text-edit/input.ts@@ -82,10 +82,7 @@ export function createTextEditInput(options: TextEditInputOptions) {}}- /**- * A generated frame, such as a sticky note, keeps its selection while its text is edited, all of- * it selected, as in Figma.- */+ /** Edits a sticky note's body or a connector's label with all of it selected, as FigJam does. */function startGeneratedTextEditing(frame: SceneNode) {const body = generatedFrameText(editor.graph, frame)if (!body) returndiff --git a/packages/vue/src/canvas/tools/input.ts b/packages/vue/src/canvas/tools/input.tsindex 28efd1906..ef825a34c 100644--- a/packages/vue/src/canvas/tools/input.ts+++ b/packages/vue/src/canvas/tools/input.ts@@ -5,6 +5,7 @@ import type { Editor } from '@open-pencil/core/editor'import { startPenInput } from '#vue/canvas/pen/input'import { startPencilInput } from '#vue/canvas/pencil/input'import { HAND_GRAB_CURSOR } from '#vue/editor/tool-cursor'+import { startConnectorDraw } from '#vue/shared/input/connector/draw'import { startShapeDraw, startTextDraw } from '#vue/shared/input/draw'import { startPanDrag } from '#vue/shared/input/pan/drag'import { handleSelectDown } from '#vue/shared/input/select'@@ -83,6 +84,11 @@ export function handleToolMouseDown({return}+ if (tool === 'CONNECTOR') {+ startConnectorDraw(cx, cy, sx, sy, editor, setDrag)+ return+ }+if (tool === 'STICKY') {startStickyDraw(cx, cy, editor, setDrag)returndiff --git a/packages/vue/src/canvas/transform/rotation.ts b/packages/vue/src/canvas/transform/rotation.tsindex cb405d89b..97c89622c 100644--- a/packages/vue/src/canvas/transform/rotation.ts+++ b/packages/vue/src/canvas/transform/rotation.ts@@ -24,7 +24,7 @@ export function tryStartRotation(if (editor.state.selectedIds.size !== 1) return falseconst id = [...editor.state.selectedIds][0]const node = editor.graph.getNode(id)- // A generated frame such as a sticky note may stay upright.+ // FigJam keeps sticky notes upright, and a connector follows its ends.if (!node || node.locked || !layerRotates(node)) return falseconst geometry = createSceneGeometry(editor.graph, editor.state.rotationPreview)diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.tsindex 2411752ff..9ea596cd4 100644--- a/packages/vue/src/canvas/useCanvasInput.ts+++ b/packages/vue/src/canvas/useCanvasInput.ts@@ -22,6 +22,7 @@ import {} from '#vue/canvas/vector-input/input'import { resolveAutoLayoutHover } from '#vue/shared/input/auto-layout-hover'import { createClickCounter } from '#vue/shared/input/click-count'+import { handleConnectorDrawMove } from '#vue/shared/input/connector/draw'import { handleDrawMove } from '#vue/shared/input/draw'import { cancelMove, handleMoveMove, handleMoveUp } from '#vue/shared/input/move/drag'import { setupPanZoom } from '#vue/shared/input/pan/zoom'@@ -40,6 +41,15 @@ import { handleNodeEditMarqueeMove, handleNodeEditMove } from '#vue/shared/input* panning, drawing tools, scoped hit testing, and text-edit interaction.* It is primarily intended for editor shell components that own the canvas.*/+/** Drags Escape abandons, leaving the document as it was before the press. */+const ESCAPABLE_DRAGS: ReadonlySet<DragState['type']> = new Set<DragState['type']>([+ 'draw',+ 'gradient',+ 'rotate',+ 'connector-draw',+ 'connector-end'+])+export function useCanvasInput(canvasRef: Ref<HTMLCanvasElement | null>,editor: Editor,@@ -256,6 +266,10 @@ export function useCanvasInput(editor.setShapeHandleHover(shapeHandleHoverAt(sx, sy, e.altKey))}+ if (!drag.value && editor.state.activeTool === 'CONNECTOR') {+ editor.connectorHover(coords.cx, coords.cy)+ }+if (!drag.value && editor.state.activeTool === 'SELECT') {const { sx, sy, cx, cy } = coordsconst guideCursor = editor.state.readOnly ? null : guideInput.updateHover(sx, sy)@@ -351,6 +365,16 @@ export function useCanvasInput(return}+ if (d.type === 'connector-draw') {+ handleConnectorDrawMove(d, cx, cy, sx, sy, editor)+ return+ }++ if (d.type === 'connector-end') {+ editor.connectorEndpointDrag(cx, cy)+ return+ }+if (d.type === 'sticky-scale') {applyStickyScale(d, cx, cy, editor)return@@ -410,7 +434,13 @@ export function useCanvasInput(/** Drops what a resize or pencil stroke showed without changing the document. */function discardDrawnPreview(d: DragState) {if (d.type === 'resize') cancelResizePreview(d, editor)- else if (d.type === 'sticky-scale' || d.type === 'sticky-draw') d.cancel()+ else if (+ d.type === 'sticky-scale' ||+ d.type === 'sticky-draw' ||+ d.type === 'connector-draw' ||+ d.type === 'connector-end'+ )+ d.cancel()else if (d.type === 'pencil-drag') editor.pencilCancel()}@@ -473,7 +503,7 @@ export function useCanvasInput(const type = drag.value?.type// A vector edit marquee carries on through Escape, as in Figma, and keeps the path open.const swallowed = type === 'edit-marquee'- if (type !== 'draw' && type !== 'gradient' && type !== 'rotate' && !swallowed) return+ if (!type || (!ESCAPABLE_DRAGS.has(type) && !swallowed)) returnevent.preventDefault()event.stopImmediatePropagation()if (!swallowed) cancelPointerInteraction()diff --git a/packages/vue/src/controls/connector/use.ts b/packages/vue/src/controls/connector/use.tsnew file mode 100644index 000000000..6502a708d--- /dev/null+++ b/packages/vue/src/controls/connector/use.ts@@ -0,0 +1,47 @@+import { computed } from 'vue'++import type { ConnectorLineType, SceneNode, StrokeCap } from '@open-pencil/scene-graph'++import { useEditor } from '#vue/editor/context'+import { useSelectionState } from '#vue/editor/selection-state/use'+import { useSceneComputed } from '#vue/internal/scene-computed/use'++/**+ * Headless state and actions for selected connectors: their line type and the caps at their+ * ends. A selection of several connectors reads its first and edits them all.+ */+export function useConnector() {+ const editor = useEditor()+ const { selectedIds } = useSelectionState()++ const connectors = useSceneComputed(() => {+ const nodes = [...selectedIds.value].map((id) => editor.graph.getNode(id))+ return nodes.length > 0 && nodes.every((node) => node?.type === 'CONNECTOR')+ ? nodes.filter((node): node is SceneNode => node !== undefined)+ : []+ })+ const active = computed(() => connectors.value.length > 0)+ const ids = computed(() => connectors.value.map((connector) => connector.id))+ // Each reads the list itself: the first connector stays the same object as it changes.+ const lineType = computed<ConnectorLineType | null>(+ () => connectors.value.at(0)?.connectorLineType ?? null+ )+ const startCap = computed<StrokeCap | null>(+ () => connectors.value.at(0)?.connectorStartCap ?? null+ )+ const endCap = computed<StrokeCap | null>(() => connectors.value.at(0)?.connectorEndCap ?? null)++ function setLineType(value: ConnectorLineType) {+ editor.setConnectorLineType(ids.value, value)+ }++ function setStartCap(value: StrokeCap) {+ editor.setConnectorCap(ids.value, 'start', value)+ }++ function setEndCap(value: StrokeCap) {+ editor.setConnectorCap(ids.value, 'end', value)+ }++ return { active, lineType, startCap, endCap, setLineType, setStartCap, setEndCap }+}diff --git a/packages/vue/src/editor/tool-cursor/index.ts b/packages/vue/src/editor/tool-cursor/index.tsindex 0bee1459a..40cf874bd 100644--- a/packages/vue/src/editor/tool-cursor/index.ts+++ b/packages/vue/src/editor/tool-cursor/index.ts@@ -32,6 +32,7 @@ const TOOL_CURSORS: Record<Tool, string> = {STAR: 'crosshair',TEXT: 'text',STICKY: 'crosshair',+ CONNECTOR: 'crosshair',PEN: PEN_CURSOR,PENCIL: PENCIL_CURSOR,HAND: HAND_CURSOR,diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex 37fe41fc3..064203726 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -220,6 +220,17 @@"strokeCapSquare": "Quadratisches Ende","strokeCapArrowLines": "Linienpfeil","strokeCapArrowEquilateral": "Dreieckspfeil",+ "strokeCapNone": "Keine",+ "strokeCapTriangleFilled": "Umgekehrtes Dreieck",+ "strokeCapDiamondFilled": "Rautenpfeil",+ "strokeCapCircleFilled": "Kreispfeil",+ "connector": "Verbinder",+ "connectorLine": "Linie",+ "connectorElbowed": "Gewinkelt",+ "connectorStraight": "Gerade",+ "connectorCurved": "Gebogen",+ "connectorStart": "Startpunkt",+ "connectorEnd": "Endpunkt","strokeJoin": "Linienverbindung","strokeJoinMiter": "Gehrungsverbindung","strokeJoinBevel": "Abgeschrägte Verbindung",diff --git a/packages/vue/src/i18n/locales/de/tools.json b/packages/vue/src/i18n/locales/de/tools.jsonindex 9cfbde641..a53b520c3 100644--- a/packages/vue/src/i18n/locales/de/tools.json+++ b/packages/vue/src/i18n/locales/de/tools.json@@ -11,6 +11,7 @@"pencil": "Bleistift","text": "Text","sticky": "Haftnotiz",+ "connector": "Verbinder","hand": "Hand","comment": "Kommentar"}diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex c73762e63..69bf184a7 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -238,6 +238,17 @@"strokeCapSquare": "Extremo cuadrado","strokeCapArrowLines": "Flecha de líneas","strokeCapArrowEquilateral": "Flecha triangular",+ "strokeCapNone": "Ninguno",+ "strokeCapTriangleFilled": "Triángulo invertido",+ "strokeCapDiamondFilled": "Flecha de rombo",+ "strokeCapCircleFilled": "Flecha circular",+ "connector": "Conector",+ "connectorLine": "Línea",+ "connectorElbowed": "En ángulo",+ "connectorStraight": "Recta",+ "connectorCurved": "Curva",+ "connectorStart": "Punto inicial",+ "connectorEnd": "Punto final","strokeJoin": "Unión del trazo","strokeJoinMiter": "Unión en inglete","strokeJoinBevel": "Unión biselada",diff --git a/packages/vue/src/i18n/locales/es/tools.json b/packages/vue/src/i18n/locales/es/tools.jsonindex 25010c286..ee78bafdd 100644--- a/packages/vue/src/i18n/locales/es/tools.json+++ b/packages/vue/src/i18n/locales/es/tools.json@@ -11,6 +11,7 @@"pencil": "Lápiz","text": "Texto","sticky": "Nota adhesiva",+ "connector": "Conector","hand": "Mano","comment": "Comentario"}diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex a0ab6ea50..7d02c195f 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -220,6 +220,17 @@"strokeCapSquare": "Extrémité carrée","strokeCapArrowLines": "Flèche en lignes","strokeCapArrowEquilateral": "Flèche triangulaire",+ "strokeCapNone": "Aucun",+ "strokeCapTriangleFilled": "Triangle inversé",+ "strokeCapDiamondFilled": "Flèche losange",+ "strokeCapCircleFilled": "Flèche cercle",+ "connector": "Connecteur",+ "connectorLine": "Ligne",+ "connectorElbowed": "Coudée",+ "connectorStraight": "Droite",+ "connectorCurved": "Courbe",+ "connectorStart": "Point de départ",+ "connectorEnd": "Point d’arrivée","strokeJoin": "Jonction du trait","strokeJoinMiter": "Jonction en onglet","strokeJoinBevel": "Jonction biseautée",diff --git a/packages/vue/src/i18n/locales/fr/tools.json b/packages/vue/src/i18n/locales/fr/tools.jsonindex 57ae831c7..5b60ea5cf 100644--- a/packages/vue/src/i18n/locales/fr/tools.json+++ b/packages/vue/src/i18n/locales/fr/tools.json@@ -11,6 +11,7 @@"pencil": "Crayon","text": "Texte","sticky": "Note autocollante",+ "connector": "Connecteur","hand": "Main","comment": "Commentaire"}diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex 469fbaba6..db4f6654a 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -220,6 +220,17 @@"strokeCapSquare": "Estremità quadrata","strokeCapArrowLines": "Freccia a linee","strokeCapArrowEquilateral": "Freccia triangolare",+ "strokeCapNone": "Nessuno",+ "strokeCapTriangleFilled": "Triangolo invertito",+ "strokeCapDiamondFilled": "Freccia a rombo",+ "strokeCapCircleFilled": "Freccia a cerchio",+ "connector": "Connettore",+ "connectorLine": "Linea",+ "connectorElbowed": "Ad angolo",+ "connectorStraight": "Dritta",+ "connectorCurved": "Curva",+ "connectorStart": "Punto iniziale",+ "connectorEnd": "Punto finale","strokeJoin": "Giunzione del tratto","strokeJoinMiter": "Giunzione a mitra","strokeJoinBevel": "Giunzione smussata",diff --git a/packages/vue/src/i18n/locales/it/tools.json b/packages/vue/src/i18n/locales/it/tools.jsonindex eb84af858..4efb89869 100644--- a/packages/vue/src/i18n/locales/it/tools.json+++ b/packages/vue/src/i18n/locales/it/tools.json@@ -11,6 +11,7 @@"pencil": "Matita","text": "Testo","sticky": "Nota adesiva",+ "connector": "Connettore","hand": "Mano","comment": "Commento"}diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex 6cb9bee63..2eda4f35a 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -238,6 +238,17 @@"strokeCapSquare": "角型線端","strokeCapArrowLines": "ライン矢印","strokeCapArrowEquilateral": "三角矢印",+ "strokeCapNone": "なし",+ "strokeCapTriangleFilled": "逆三角形",+ "strokeCapDiamondFilled": "ひし形矢印",+ "strokeCapCircleFilled": "円矢印",+ "connector": "コネクタ",+ "connectorLine": "線",+ "connectorElbowed": "折れ線",+ "connectorStraight": "直線",+ "connectorCurved": "曲線",+ "connectorStart": "始点",+ "connectorEnd": "終点","strokeJoin": "線の結合","strokeJoinMiter": "マイター結合","strokeJoinBevel": "ベベル結合",diff --git a/packages/vue/src/i18n/locales/ja/tools.json b/packages/vue/src/i18n/locales/ja/tools.jsonindex 8dad7f3a7..b06b54df3 100644--- a/packages/vue/src/i18n/locales/ja/tools.json+++ b/packages/vue/src/i18n/locales/ja/tools.json@@ -11,6 +11,7 @@"pencil": "鉛筆","text": "テキスト","sticky": "付箋",+ "connector": "コネクタ","hand": "手のひらツール","comment": "コメント"}diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex fb3224b68..af1d439a9 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -220,6 +220,17 @@"strokeCapSquare": "Kwadratowe zakończenie","strokeCapArrowLines": "Strzałka liniowa","strokeCapArrowEquilateral": "Strzałka trójkątna",+ "strokeCapNone": "Brak",+ "strokeCapTriangleFilled": "Odwrócony trójkąt",+ "strokeCapDiamondFilled": "Strzałka rombowa",+ "strokeCapCircleFilled": "Strzałka okrągła",+ "connector": "Łącznik",+ "connectorLine": "Linia",+ "connectorElbowed": "Łamana",+ "connectorStraight": "Prosta",+ "connectorCurved": "Zakrzywiona",+ "connectorStart": "Punkt początkowy",+ "connectorEnd": "Punkt końcowy","strokeJoin": "Łączenie obrysu","strokeJoinMiter": "Łączenie ostre","strokeJoinBevel": "Łączenie ścięte",diff --git a/packages/vue/src/i18n/locales/pl/tools.json b/packages/vue/src/i18n/locales/pl/tools.jsonindex 7d7d50170..cdb776fae 100644--- a/packages/vue/src/i18n/locales/pl/tools.json+++ b/packages/vue/src/i18n/locales/pl/tools.json@@ -11,6 +11,7 @@"pencil": "Ołówek","text": "Tekst","sticky": "Karteczka",+ "connector": "Łącznik","hand": "Dłoń","comment": "Komentarz"}diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex e7a7a9a5c..e09b89b2a 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -220,6 +220,17 @@"strokeCapSquare": "Квадратный конец","strokeCapArrowLines": "Линейная стрелка","strokeCapArrowEquilateral": "Треугольная стрелка",+ "strokeCapNone": "Нет",+ "strokeCapTriangleFilled": "Обратный треугольник",+ "strokeCapDiamondFilled": "Ромбовидная стрелка",+ "strokeCapCircleFilled": "Круглая стрелка",+ "connector": "Соединитель",+ "connectorLine": "Линия",+ "connectorElbowed": "Ломаная",+ "connectorStraight": "Прямая",+ "connectorCurved": "Изогнутая",+ "connectorStart": "Начальная точка",+ "connectorEnd": "Конечная точка","strokeJoin": "Соединение обводки","strokeJoinMiter": "Острое соединение","strokeJoinBevel": "Скошенное соединение",diff --git a/packages/vue/src/i18n/locales/ru/tools.json b/packages/vue/src/i18n/locales/ru/tools.jsonindex 56bfa1cfa..9ccdbb2e1 100644--- a/packages/vue/src/i18n/locales/ru/tools.json+++ b/packages/vue/src/i18n/locales/ru/tools.json@@ -11,6 +11,7 @@"pencil": "Карандаш","text": "Текст","sticky": "Стикер",+ "connector": "Соединитель","hand": "Рука","comment": "Комментарий"}diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex 9a970f4ce..d694a229a 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -220,6 +220,17 @@"strokeCapSquare": "方形端点","strokeCapArrowLines": "线条箭头","strokeCapArrowEquilateral": "三角箭头",+ "strokeCapNone": "无",+ "strokeCapTriangleFilled": "反向三角形",+ "strokeCapDiamondFilled": "菱形箭头",+ "strokeCapCircleFilled": "圆形箭头",+ "connector": "连接线",+ "connectorLine": "线条",+ "connectorElbowed": "折线",+ "connectorStraight": "直线",+ "connectorCurved": "曲线",+ "connectorStart": "起点",+ "connectorEnd": "终点","strokeJoin": "描边连接","strokeJoinMiter": "尖角连接","strokeJoinBevel": "斜角连接",diff --git a/packages/vue/src/i18n/locales/zh-cn/tools.json b/packages/vue/src/i18n/locales/zh-cn/tools.jsonindex 7f5fdc344..0c0ea18e3 100644--- a/packages/vue/src/i18n/locales/zh-cn/tools.json+++ b/packages/vue/src/i18n/locales/zh-cn/tools.json@@ -11,6 +11,7 @@"pencil": "铅笔","text": "文本","sticky": "便利贴",+ "connector": "连接线","hand": "抓手","comment": "评论"}diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex 4d3dd055b..d16be9b56 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -447,6 +447,17 @@ export const panelMessageDefaults = {strokeCapSquare: 'Square cap',strokeCapArrowLines: 'Line arrow',strokeCapArrowEquilateral: 'Triangle arrow',+ strokeCapNone: 'None',+ strokeCapTriangleFilled: 'Reversed triangle',+ strokeCapDiamondFilled: 'Diamond arrow',+ strokeCapCircleFilled: 'Circle arrow',+ connector: 'Connector',+ connectorLine: 'Line',+ connectorElbowed: 'Elbowed',+ connectorStraight: 'Straight',+ connectorCurved: 'Curved',+ connectorStart: 'Start point',+ connectorEnd: 'End point',strokeJoin: 'Stroke join',strokeJoinMiter: 'Miter join',strokeJoinBevel: 'Bevel join',diff --git a/packages/vue/src/i18n/messages/tools.ts b/packages/vue/src/i18n/messages/tools.tsindex 124aafb0f..396ad6c46 100644--- a/packages/vue/src/i18n/messages/tools.ts+++ b/packages/vue/src/i18n/messages/tools.ts@@ -13,6 +13,7 @@ export const toolMessageDefaults = {pencil: 'Pencil',text: 'Text',sticky: 'Sticky note',+ connector: 'Connector',hand: 'Hand',comment: 'Comment'} as constdiff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex 7abf2b964..fb01c1fae 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -126,6 +126,7 @@ export {type VariableModeOption} from '#vue/controls/variable-modes/helpers'export { useMask } from '#vue/controls/mask/use'+export { useConnector } from '#vue/controls/connector/use'export { useStickyNote } from '#vue/controls/sticky/use'export { useIcon } from '#vue/controls/icon/use'export { useIconSearch } from '#vue/controls/icon/search'diff --git a/packages/vue/src/shared/input/connector/draw.ts b/packages/vue/src/shared/input/connector/draw.tsnew file mode 100644index 000000000..f70c79b30--- /dev/null+++ b/packages/vue/src/shared/input/connector/draw.ts@@ -0,0 +1,41 @@+import type { Editor } from '@open-pencil/core/editor'++import { isPastPointerDragThreshold } from '#vue/shared/input/drag-threshold'+import type { DragConnectorDraw, DragState } from '#vue/shared/input/types'++/** Starts a connector at the press, or ends the one a click started, as FigJam's tool does. */+export function startConnectorDraw(+ cx: number,+ cy: number,+ sx: number,+ sy: number,+ editor: Editor,+ setDrag: (drag: DragState) => void+) {+ editor.connectorBegin(cx, cy)+ const drag: DragConnectorDraw = {+ type: 'connector-draw',+ startSX: sx,+ startSY: sy,+ moved: false,+ x: cx,+ y: cy,+ commit: () => editor.connectorRelease(drag.x, drag.y, drag.moved),+ cancel: () => editor.connectorCancel()+ }+ setDrag(drag)+}++export function handleConnectorDrawMove(+ drag: DragConnectorDraw,+ cx: number,+ cy: number,+ sx: number,+ sy: number,+ editor: Editor+) {+ drag.x = cx+ drag.y = cy+ drag.moved ||= isPastPointerDragThreshold(drag.startSX, drag.startSY, sx, sy)+ if (drag.moved) editor.connectorDrag(cx, cy)+}diff --git a/packages/vue/src/shared/input/connector/end.ts b/packages/vue/src/shared/input/connector/end.tsnew file mode 100644index 000000000..6f45e7618--- /dev/null+++ b/packages/vue/src/shared/input/connector/end.ts@@ -0,0 +1,46 @@+import type { Editor } from '@open-pencil/core/editor'+import { connectorScreenEnds } from '@open-pencil/core/geometry'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import type { DragState } from '#vue/shared/input/types'++/** How near a connector's end handle the pointer picks it, in screen pixels. */+const CONNECTOR_HANDLE_HIT_RADIUS = 8++/** The end handle of the only selected connector under a screen point, if any. */+export function connectorEndAt(+ editor: Editor,+ sx: number,+ sy: number+): { connectorId: string; end: 'connectorStart' | 'connectorEnd' } | null {+ const { state } = editor+ if (state.selectedIds.size !== 1) return null+ const [id] = state.selectedIds+ const connector = editor.graph.getNode(id)+ if (connector?.type !== 'CONNECTOR' || connector.locked) return null+ const ends = connectorScreenEnds(editor.graph, connector, state, state.rotationPreview)+ if (!ends) return null+ const near = (point: Vector) =>+ Math.hypot(point.x - sx, point.y - sy) <= CONNECTOR_HANDLE_HIT_RADIUS+ if (near(ends.end)) return { connectorId: id, end: 'connectorEnd' }+ if (near(ends.start)) return { connectorId: id, end: 'connectorStart' }+ return null+}++/** Drags a selected connector's end handle, attaching it where it is dropped. */+export function tryStartConnectorEndDrag(+ editor: Editor,+ sx: number,+ sy: number,+ setDrag: (drag: DragState) => void+): boolean {+ const hit = connectorEndAt(editor, sx, sy)+ if (!hit) return false+ editor.connectorEndpointBegin(hit.connectorId, hit.end)+ setDrag({+ type: 'connector-end',+ commit: () => editor.connectorEndpointCommit(),+ cancel: () => editor.connectorEndpointCancel()+ })+ return true+}diff --git a/packages/vue/src/shared/input/resize/start.ts b/packages/vue/src/shared/input/resize/start.tsindex 2be1d9a12..8de3ea4a2 100644--- a/packages/vue/src/shared/input/resize/start.ts+++ b/packages/vue/src/shared/input/resize/start.ts@@ -8,8 +8,8 @@ import type { DragResize } from '#vue/shared/input/types'export function tryStartResize(cx: number, cy: number, editor: Editor): DragResize | null {for (const id of editor.state.selectedIds) {const node = editor.graph.getNode(id)- // A generated frame such as a sticky note is shaped by its own handles; see- // `tryStartStickyScale`.+ // A sticky note only scales, from its corners; see `tryStartStickyScale`. A connector is+ // shaped by its ends.if (!node || node.locked || !layerResizes(node)) continueconst handleResult = getHitHandleByMatrix(cx,diff --git a/packages/vue/src/shared/input/select.ts b/packages/vue/src/shared/input/select.tsindex 7d4cf0a8f..509ec1acc 100644--- a/packages/vue/src/shared/input/select.ts+++ b/packages/vue/src/shared/input/select.ts@@ -5,6 +5,7 @@ export { updateHoverCursor } from '#vue/shared/input/select/hover'import { editedGradient, type Editor } from '@open-pencil/core/editor'import type { SceneNode } from '@open-pencil/scene-graph'+import { tryStartConnectorEndDrag } from '#vue/shared/input/connector/end'import { tryStartGradientDrag } from '#vue/shared/input/gradient'import { tryStartResize } from '#vue/shared/input/resize'import {@@ -53,6 +54,7 @@ function tryStartHandleDrag(// An open gradient's handles replace the layer's selection handles, which then do not respond.if (editedGradient(editor.graph, editor.state.gradientEdit)) return falseif (tryStartShapeHandleDrag(editor, sx, sy, altKey, setDrag)) return true+ if (tryStartConnectorEndDrag(editor, sx, sy, setDrag)) return trueconst scaleDrag = tryStartStickyScale(cx, cy, editor)if (scaleDrag) {setDrag(scaleDrag)diff --git a/packages/vue/src/shared/input/select/hover.ts b/packages/vue/src/shared/input/select/hover.tsindex 03e04ba65..250d83455 100644--- a/packages/vue/src/shared/input/select/hover.ts+++ b/packages/vue/src/shared/input/select/hover.ts@@ -1,5 +1,5 @@import type { Editor } from '@open-pencil/core/editor'-import { layerRotates } from '@open-pencil/scene-graph'+import { layerResizes, layerRotates } from '@open-pencil/scene-graph'import {buildResizeCursor,@@ -9,12 +9,14 @@ import {} from '#vue/shared/input/geometry'import type { HitTestFns } from '#vue/shared/input/select'import { hitTestLabel } from '#vue/shared/input/select/hit'+import { scalesByHandles } from '#vue/shared/input/sticky/scale'import { getNodeEditState } from '#vue/shared/input/vector'function getResizeCursorForSelection(cx: number, cy: number, editor: Editor): string | null {for (const id of editor.state.selectedIds) {const node = editor.graph.getNode(id)- if (!node) continue+ // As a press does: only a layer its handles resize or scale shows a resize cursor on them.+ if (!node || (!layerResizes(node) && !scalesByHandles(node))) continueconst handleHit = getHitHandleByMatrix(cx,diff --git a/packages/vue/src/shared/input/sticky/scale.ts b/packages/vue/src/shared/input/sticky/scale.tsindex 54e3f36fb..83c28e653 100644--- a/packages/vue/src/shared/input/sticky/scale.ts+++ b/packages/vue/src/shared/input/sticky/scale.ts@@ -28,6 +28,11 @@ export function subtree(editor: Editor, root: SceneNode): Map<string, SceneNode>return nodes}+/** Whether a layer's handles scale it as a sticky note's do, rather than resize it. */+export function scalesByHandles(node: SceneNode): boolean {+ return node.type === 'STICKY' && !node.locked+}+/*** Dragging a selected sticky note's handle changes it as FigJam does: a corner, the top, or the* bottom scales the whole note, its text included, and a side switches it between square and@@ -40,7 +45,7 @@ export function tryStartStickyScale(): DragStickyScale | null {if (editor.state.selectedIds.size !== 1) return nullconst node = editor.graph.getNode([...editor.state.selectedIds][0])- if (node?.type !== 'STICKY' || node.locked) return null+ if (!node || !scalesByHandles(node)) return nullconst hit = getHitHandleByMatrix(cx,cy,diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.tsindex f175e0cbe..570aaf417 100644--- a/packages/vue/src/shared/input/types.ts+++ b/packages/vue/src/shared/input/types.ts@@ -32,6 +32,29 @@ export interface DragDraw {cancel: () => void}+/**+ * A connector drawn with the connector tool, from the press to the release or from one click to+ * the next. Positions are screen pixels, to tell a click from a drag.+ */+export interface DragConnectorDraw {+ type: 'connector-draw'+ startSX: number+ startSY: number+ moved: boolean+ /** Where the pointer is, in canvas coordinates. */+ x: number+ y: number+ commit: () => void+ cancel: () => void+}++/** An end of a selected connector dragged to another layer or point. */+export interface DragConnectorEnd {+ type: 'connector-end'+ commit: () => void+ cancel: () => void+}+/** A sticky note being drawn: it grows from the press corner with the drag, as a frame does. */export interface DragStickyDraw {type: 'sticky-draw'@@ -254,6 +277,8 @@ export type DragState =| DragShapeHandle| DragDraw| DragStickyDraw+ | DragConnectorDraw+ | DragConnectorEnd| DragGradient| DragMove| DragPandiff --git a/packages/vue/tests/shared/input/select/hover.test.ts b/packages/vue/tests/shared/input/select/hover.test.tsindex f23545a4f..9aed5af67 100644--- a/packages/vue/tests/shared/input/select/hover.test.ts+++ b/packages/vue/tests/shared/input/select/hover.test.ts@@ -1,7 +1,7 @@import { afterEach, expect, test } from 'bun:test'import { createEditor, type Editor } from '@open-pencil/core/editor'-import type { SceneNode } from '@open-pencil/scene-graph'+import { boundEndpoint, createConnector, createSticky, type SceneNode } from '@open-pencil/scene-graph'import {cornerRotationCursor,@@ -46,3 +46,37 @@ test('a label does not take the press from a resize band', () => {expect(cursorAt(-3, -3)).toBe(buildResizeCursor(hit?.rotation ?? 0))expect(getHitHandleByMatrix(120, -5, frame, editor.graph)?.handle).toBe('n')})++const NO_HITS = {+ hitTestInScope: () => null,+ hitTestFrameTitle: () => null,+ hitTestSectionTitle: () => null,+ hitTestComponentLabel: () => null+}++test('a connector has no resize cursor, its end handles included, as in FigJam', () => {+ editor = createEditor()+ const page = editor.state.currentPageId+ const a = editor.graph.createNode('RECTANGLE', page, { x: 0, y: 0, width: 100, height: 100 })+ const b = editor.graph.createNode('RECTANGLE', page, { x: 300, y: 0, width: 100, height: 100 })+ const connector = createConnector(editor.graph, page, {+ start: boundEndpoint(a.id),+ end: boundEndpoint(b.id)+ })+ editor.graph.updateNode(connector.id, { x: 100, y: 30, width: 200, height: 40 })+ editor.select([connector.id])+ expect(getHitHandleByMatrix(300, 50, connector, editor.graph)?.handle).toBe('e')+ expect(updateHoverCursor(300, 50, editor, NO_HITS)).toBeNull()+})++test("a sticky note's handles keep their cursor, since they scale it", () => {+ editor = createEditor()+ const sticky = createSticky(editor.graph, editor.state.currentPageId, { text: '' })+ editor.select([sticky.id])+ const hit = getHitHandleByMatrix(sticky.width, sticky.height, sticky, editor.graph)+ expect(hit?.handle).toBe('se')+ expect(updateHoverCursor(sticky.width, sticky.height, editor, NO_HITS)).toBe(+ buildResizeCursor(hit?.rotation ?? 0)+ )+})+diff --git a/src/app/editor/icons.ts b/src/app/editor/icons.tsindex a8d57ad80..7471ef13a 100644--- a/src/app/editor/icons.ts+++ b/src/app/editor/icons.ts@@ -40,6 +40,7 @@ export const toolIcons: Record<Tool, Component> = {PENCIL: IconPencil,TEXT: IconType,STICKY: IconStickyNote,+ CONNECTOR: IconSpline,HAND: IconHand,COMMENT: IconMessageCircle}diff --git a/src/app/editor/toolbar/layout.ts b/src/app/editor/toolbar/layout.tsindex d46306053..679ca5f52 100644--- a/src/app/editor/toolbar/layout.ts+++ b/src/app/editor/toolbar/layout.ts@@ -26,9 +26,9 @@ export const PINNED_TOOLBAR_ENTRY: ToolbarEntry = 'SELECT'/*** Tools the toolbar keeps hidden until shown from Customize toolbar, such as FigJam's sticky- * note, which Figma's own toolbar does not offer.+ * note and connector, which Figma's own toolbar does not offer.*/-const HIDDEN_BY_DEFAULT: readonly ToolbarEntry[] = ['STICKY']+const HIDDEN_BY_DEFAULT: readonly ToolbarEntry[] = ['STICKY', 'CONNECTOR']export const DEFAULT_TOOLBAR_LAYOUT: Readonly<ToolbarLayout> = {groups: [diff --git a/src/app/editor/toolbar/shortcuts.ts b/src/app/editor/toolbar/shortcuts.tsindex 53f61a280..68a6ef61d 100644--- a/src/app/editor/toolbar/shortcuts.ts+++ b/src/app/editor/toolbar/shortcuts.ts@@ -17,6 +17,7 @@ const TOOL_SHORTCUT_KEYS: Readonly<Record<Tool, string>> = {PENCIL: 'SHIFT+P',TEXT: 'T',STICKY: '',+ CONNECTOR: '',HAND: 'H',COMMENT: 'C'}diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.tsindex e14e22107..2736c500a 100644--- a/src/app/shell/keyboard/actions.ts+++ b/src/app/shell/keyboard/actions.ts@@ -56,8 +56,8 @@ export function createKeyboardActions({store.enterNodeEditMode(node.id)return}- // A generated frame opens its text, such as a sticky note's body, all of it selected,- // keeping the frame selected.+ // A sticky note opens its body and a connector its label, all of it selected, keeping the+ // note or connector selected.const text = (node && generatedFrameText(store.graph, node)) ?? nodeif (text?.type === 'TEXT') {requestAnimationFrame(() => {diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vueindex 88ad76b8a..a5ac9300e 100644--- a/src/components/DesignPanel.vue+++ b/src/components/DesignPanel.vue@@ -23,6 +23,7 @@ import PropertyBoundField from './properties/component-properties/PropertyBoundFimport SlotAuthoringSection from './properties/component-properties/slot/SlotAuthoringSection.vue'import { usePropertyBinding } from './properties/component-properties/usePropertyBinding'import VariantAuthoringSection from './properties/component-properties/variant/VariantAuthoringSection.vue'+import ConnectorSection from './properties/connector/ConnectorSection.vue'import ConstraintsSection from './properties/constraints/ConstraintsSection.vue'import EffectsSection from './properties/EffectsSection.vue'import ExportSection from './properties/ExportSection.vue'@@ -212,16 +213,22 @@ const { panels } = useI18n()<IconSection /><StickySection />- <PositionSection />- <ConstraintsSection />- <!-- A sticky note's size follows its text and its scale; Figma leaves W and H read-only. -->- <LayoutSection v-if="layerResizes(node)" />+ <ConnectorSection />+ <!-- A connector is placed and shaped by its ends, and styled by its line. -->+ <template v-if="node.type !== 'CONNECTOR'">+ <PositionSection />+ <ConstraintsSection />+ <!-- A sticky note's size follows its text and its scale; Figma leaves W and H read-only. -->+ <LayoutSection v-if="layerResizes(node)" />+ </template><AppearanceSection />- <MaskSection />- <TypographySection v-if="node.type === 'TEXT'" />- <FillSection />- <StrokeSection />- <EffectsSection />+ <template v-if="node.type !== 'CONNECTOR'">+ <MaskSection />+ <TypographySection v-if="node.type === 'TEXT'" />+ <FillSection />+ <StrokeSection />+ <EffectsSection />+ </template><SelectionColorsSection /><LayoutGridSection v-if="supportsLayoutGuides" />diff --git a/src/components/properties/connector/ConnectorControls.stories.ts b/src/components/properties/connector/ConnectorControls.stories.tsnew file mode 100644index 000000000..18c031d9e--- /dev/null+++ b/src/components/properties/connector/ConnectorControls.stories.ts@@ -0,0 +1,56 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, within } from 'storybook/test'+import { ref } from 'vue'++import type { ConnectorLineType, StrokeCap } from '@open-pencil/scene-graph'++import ConnectorControls from './ConnectorControls.vue'++const meta = {+ title: 'App/Editor/Properties/Connector',+ tags: ['autodocs'],+ parameters: {+ docs: {+ description: {+ component:+ "A selected connector's line type and the caps at its ends, as the Design panel shows them."+ }+ }+ },+ render: () => ({+ components: { ConnectorControls },+ setup() {+ const lineType = ref<ConnectorLineType>('ELBOWED')+ const startCap = ref<StrokeCap>('NONE')+ const endCap = ref<StrokeCap>('ARROW_LINES')+ return { lineType, startCap, endCap }+ },+ template: `+ <div class="w-[240px] bg-panel p-4">+ <ConnectorControls+ :line-type="lineType"+ :start-cap="startCap"+ :end-cap="endCap"+ @update:line-type="lineType = $event"+ @update:start-cap="startCap = $event"+ @update:end-cap="endCap = $event"+ />+ </div>`+ })+} satisfies Meta++export default meta+type Story = StoryObj<typeof meta>++export const Default: Story = {}++export const PicksACap: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await userEvent.click(canvas.getByRole('combobox', { name: 'End point' }))+ await userEvent.click(within(document.body).getByRole('option', { name: 'Circle arrow' }))+ await expect(canvas.getByRole('combobox', { name: 'End point' })).toHaveTextContent(+ 'Circle arrow'+ )+ }+}diff --git a/src/components/properties/connector/ConnectorControls.vue b/src/components/properties/connector/ConnectorControls.vuenew file mode 100644index 000000000..a44ce7b4e--- /dev/null+++ b/src/components/properties/connector/ConnectorControls.vue@@ -0,0 +1,81 @@+<script setup lang="ts">+import { computed } from 'vue'++import type { ConnectorLineType, StrokeCap } from '@open-pencil/scene-graph'+import { useI18n } from '@open-pencil/vue'++import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'+import AppSelect from '@/components/ui/select/AppSelect.vue'++const { lineType, startCap, endCap } = defineProps<{+ lineType: ConnectorLineType | null+ startCap: StrokeCap | null+ endCap: StrokeCap | null+}>()++const emit = defineEmits<{+ 'update:lineType': [value: ConnectorLineType]+ 'update:startCap': [value: StrokeCap]+ 'update:endCap': [value: StrokeCap]+}>()++const { panels } = useI18n()++const lineOptions = computed<Array<{ value: ConnectorLineType; label: string }>>(() => [+ { value: 'ELBOWED', label: panels.value.connectorElbowed },+ { value: 'STRAIGHT', label: panels.value.connectorStraight },+ { value: 'CURVED', label: panels.value.connectorCurved }+])++/** The caps FigJam offers at a connector's ends. */+const capOptions = computed<Array<{ value: StrokeCap; label: string }>>(() => [+ { value: 'NONE', label: panels.value.strokeCapNone },+ { value: 'ARROW_LINES', label: panels.value.strokeCapArrowLines },+ { value: 'ARROW_EQUILATERAL', label: panels.value.strokeCapArrowEquilateral },+ { value: 'TRIANGLE_FILLED', label: panels.value.strokeCapTriangleFilled },+ { value: 'DIAMOND_FILLED', label: panels.value.strokeCapDiamondFilled },+ { value: 'CIRCLE_FILLED', label: panels.value.strokeCapCircleFilled }+])++const selectedLine = computed<ConnectorLineType>({+ get: () => lineType ?? 'ELBOWED',+ set: (value) => emit('update:lineType', value)+})+const selectedStart = computed<StrokeCap>({+ get: () => startCap ?? 'NONE',+ set: (value) => emit('update:startCap', value)+})+const selectedEnd = computed<StrokeCap>({+ get: () => endCap ?? 'NONE',+ set: (value) => emit('update:endCap', value)+})+</script>++<template>+ <div class="grid gap-2.5">+ <PanelFieldGroup :label="panels.connectorLine">+ <AppSelect+ v-model="selectedLine"+ :label="panels.connectorLine"+ :options="lineOptions"+ data-property="connector-line"+ />+ </PanelFieldGroup>+ <PanelFieldGroup :label="panels.connectorStart">+ <AppSelect+ v-model="selectedStart"+ :label="panels.connectorStart"+ :options="capOptions"+ data-property="connector-start-cap"+ />+ </PanelFieldGroup>+ <PanelFieldGroup :label="panels.connectorEnd">+ <AppSelect+ v-model="selectedEnd"+ :label="panels.connectorEnd"+ :options="capOptions"+ data-property="connector-end-cap"+ />+ </PanelFieldGroup>+ </div>+</template>diff --git a/src/components/properties/connector/ConnectorSection.vue b/src/components/properties/connector/ConnectorSection.vuenew file mode 100644index 000000000..b2dd71df4--- /dev/null+++ b/src/components/properties/connector/ConnectorSection.vue@@ -0,0 +1,23 @@+<script setup lang="ts">+import { useConnector, useI18n } from '@open-pencil/vue'++import PanelSection from '@/components/ui/panel/PanelSection.vue'++import ConnectorControls from './ConnectorControls.vue'++const { panels } = useI18n()+const { active, lineType, startCap, endCap, setLineType, setStartCap, setEndCap } = useConnector()+</script>++<template>+ <PanelSection v-if="active" :label="panels.connector">+ <ConnectorControls+ :line-type="lineType"+ :start-cap="startCap"+ :end-cap="endCap"+ @update:line-type="setLineType"+ @update:start-cap="setStartCap"+ @update:end-cap="setEndCap"+ />+ </PanelSection>+</template>diff --git a/src/components/toolbar/labels.ts b/src/components/toolbar/labels.tsindex a2327ff4e..da7d946a9 100644--- a/src/components/toolbar/labels.ts+++ b/src/components/toolbar/labels.ts@@ -22,6 +22,7 @@ export function useToolLabels() {PENCIL: tools.value.pencil,TEXT: tools.value.text,STICKY: tools.value.sticky,+ CONNECTOR: tools.value.connector,HAND: tools.value.hand,COMMENT: tools.value.comment}))diff --git a/tests/app/editor/toolbar/layout.test.ts b/tests/app/editor/toolbar/layout.test.tsindex 7a6a9a3b5..09dcc6f5e 100644--- a/tests/app/editor/toolbar/layout.test.ts+++ b/tests/app/editor/toolbar/layout.test.ts@@ -37,8 +37,8 @@ describe('normalizeToolbarLayout', () => {const groups = [['SELECT', 'LASSO', 'SELECT'], [], ['FRAME', 'SECTION', 'FRAME']]const result = normalizeToolbarLayout(groups, ['HAND', 'HAND', 'GHOST'])expect(result.groups.slice(0, 2)).toEqual([['SELECT'], ['FRAME', 'SECTION']])- // The sticky tool is placed hidden, as the default layout keeps it.- expect(result.hidden).toEqual(['HAND', 'STICKY'])+ // The sticky and connector tools are placed hidden, as the default layout keeps them.+ expect(result.hidden).toEqual(['HAND', 'STICKY', 'CONNECTOR'])})test('never hides Move', () => {@@ -48,8 +48,8 @@ describe('normalizeToolbarLayout', () => {test('keeps commands out of flyouts', () => {const result = layout([['SELECT', 'insert-icon', 'HAND'], ['COMMENT']])expect(result.groups.slice(-5)).toEqual([- ['TEXT'],['STICKY'],+ ['CONNECTOR'],['insert-icon'],['HAND'],['COMMENT']@@ -67,6 +67,7 @@ describe('normalizeToolbarLayout', () => {expect(layout(stored).groups).toEqual([['TEXT'],['STICKY'],+ ['CONNECTOR'],['SELECT'],['FRAME', 'SECTION'],SHAPES,diff --git a/tests/e2e/canvas/connectors-visual.spec.ts b/tests/e2e/canvas/connectors-visual.spec.tsindex bea998b4b..ed2f0e329 100644--- a/tests/e2e/canvas/connectors-visual.spec.ts+++ b/tests/e2e/canvas/connectors-visual.spec.ts@@ -1,11 +1,13 @@import { readFile } from 'node:fs/promises'import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { connectorDriver } from '#tests/helpers/canvas/connector-driver'import { pasteFigmaClipboard } from '#tests/helpers/canvas/figma-paste'import { layerDriver } from '#tests/helpers/canvas/layers'const editor = useEditorSetupWithClear('/?test&no-chrome&no-rulers')const layers = layerDriver(() => editor.page)+const connectors = connectorDriver(() => editor.page)test('FigJam connectors draw their elbows, curve, caps, dashes, and label as Figma routed them', async () => {const html = await readFile('tests/fixtures/clipboard/figjam-connectors.html', 'utf8')@@ -28,3 +30,12 @@ test('dragging a sticky routes the connectors attached to it again', async () =>'figjam-connectors-moved.png')})++test('connectors draw their filled caps, the end handles of a selected one, and an attach target', async () => {+ await connectors.showCapsAndHandles()+ await editor.canvas.waitForRender()+ editor.canvas.assertNoErrors()+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot(+ 'connector-caps-and-handles.png'+ )+})diff --git a/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/connector-caps-and-handles-openpencil-darwin.png b/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/connector-caps-and-handles-openpencil-darwin.pngnew file mode 100644index 000000000..1cf98b3d9Binary files /dev/null and b/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/connector-caps-and-handles-openpencil-darwin.png differdiff --git a/tests/e2e/tools/connector.spec.ts b/tests/e2e/tools/connector.spec.tsnew file mode 100644index 000000000..032a89b98--- /dev/null+++ b/tests/e2e/tools/connector.spec.ts@@ -0,0 +1,139 @@+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { connectorDriver } from '#tests/helpers/canvas/connector-driver'+import { toolbarToolTestId } from '#tests/helpers/test-ids'++const editor = useEditorSetupWithClear()+const connectors = connectorDriver(() => editor.page)++let ids: Record<string, string> = {}++test.beforeEach(async () => {+ await editor.page.keyboard.press('Escape')+ await connectors.showOrigin()+ ids = await connectors.addBoxes([+ { name: 'A', x: 0, y: 0, width: 200, height: 200 },+ { name: 'B', x: 500, y: 100, width: 200, height: 200 }+ ])+})++async function drag(from: [number, number], to: [number, number]) {+ const start = connectors.point(...from)+ const end = connectors.point(...to)+ await editor.canvas.drag(start.x, start.y, end.x, end.y, 12)+ await editor.canvas.waitForRender()+}++async function lastConnector() {+ const connector = (await connectors.connectors()).at(-1)+ if (!connector) throw new Error('Missing connector')+ return connector+}++test('the toolbar keeps the connector tool hidden', async () => {+ await expect(editor.page.getByTestId(toolbarToolTestId('CONNECTOR'))).toHaveCount(0)+})++test('the connector tool joins the layers a drag starts and ends on, and stays picked', async () => {+ await connectors.showTool()+ await connectors.pickTool()+ await drag([100, 100], [600, 200])+ const connector = await lastConnector()+ expect(connector.start).toMatchObject({ nodeId: ids.A, magnet: 'AUTO' })+ expect(connector.end).toMatchObject({ nodeId: ids.B, magnet: 'AUTO' })+ expect((await connectors.focus()).tool).toBe('CONNECTOR')+})++test('hovering a layer with the tool outlines it with its magnets', async () => {+ await connectors.showTool()+ await connectors.pickTool()+ const point = connectors.point(30, 100)+ await editor.canvas.hover(point.x, point.y)+ await editor.canvas.waitForRender()+ expect((await connectors.focus()).target).toEqual({ nodeId: ids.A, magnet: 'LEFT' })+})++test('a selected connector’s end drags to another layer', async () => {+ await connectors.showTool()+ await connectors.pickTool()+ await drag([100, 100], [400, 450])+ const drawn = await lastConnector()+ expect(drawn.end?.nodeId).toBeNull()+ await editor.page.keyboard.press('v')+ await connectors.select(drawn.id)++ // The free end sits where the drag ended; its handle is dragged from there.+ const { x, y } = drawn.end?.position ?? { x: 0, y: 0 }+ await drag([x, y], [600, 200])+ expect((await lastConnector()).end).toMatchObject({ nodeId: ids.B })+})++test('Escape while dragging a connector end puts it back', async () => {+ await connectors.showTool()+ await connectors.pickTool()+ await drag([100, 100], [400, 450])+ const drawn = await lastConnector()+ await editor.page.keyboard.press('v')+ await connectors.select(drawn.id)+ const box = await editor.canvas.canvas.boundingBox()+ if (!box) throw new Error('Missing canvas')+ const { x, y } = drawn.end?.position ?? { x: 0, y: 0 }+ const from = connectors.point(x, y)+ const to = connectors.point(600, 200)+ await editor.page.mouse.move(box.x + from.x, box.y + from.y)+ await editor.page.mouse.down()+ await editor.page.mouse.move(box.x + to.x, box.y + to.y, { steps: 8 })+ await editor.page.keyboard.press('Escape')+ await editor.page.mouse.up()+ await editor.canvas.waitForRender()+ expect((await lastConnector()).end).toEqual(drawn.end)+})++test('Enter on a selected connector types its label', async () => {+ await connectors.showTool()+ await connectors.pickTool()+ await drag([100, 100], [600, 200])+ await editor.page.keyboard.press('v')+ const connector = await lastConnector()+ await connectors.select(connector.id)+ await editor.page.keyboard.press('Enter')+ await editor.page.keyboard.type('Next')+ await editor.page.keyboard.press('Escape')+ await editor.canvas.waitForRender()+ expect((await lastConnector()).label).toBe('Next')+})++test('double-clicking a connector types its label', async () => {+ await connectors.showTool()+ await connectors.pickTool()+ await drag([100, 100], [600, 200])+ await editor.page.keyboard.press('v')+ const connector = await lastConnector()+ const point = await connectors.linePoint(connector.id)+ const at = connectors.point(point.x, point.y)+ const box = await editor.canvas.canvas.boundingBox()+ if (!box) throw new Error('Missing canvas')+ await editor.page.mouse.dblclick(box.x + at.x, box.y + at.y)+ await editor.page.keyboard.type('Next')+ await editor.page.keyboard.press('Escape')+ await editor.canvas.waitForRender()+ expect((await lastConnector()).label).toBe('Next')+})++test('the Connector section sets the line type and end caps', async () => {+ await connectors.showTool()+ await connectors.pickTool()+ await drag([100, 100], [600, 200])+ await editor.page.keyboard.press('v')+ const connector = await lastConnector()+ await connectors.select(connector.id)+ const section = editor.page.getByRole('region', { name: 'Connector' })+ await section.getByRole('combobox', { name: 'Line' }).click()+ await editor.page.getByRole('option', { name: 'Curved' }).click()+ await section.getByRole('combobox', { name: 'End point' }).click()+ await editor.page.getByRole('option', { name: 'Circle arrow' }).click()+ expect(await connectors.style(connector.id)).toEqual({+ line: 'CURVED',+ startCap: 'NONE',+ endCap: 'CIRCLE_FILLED'+ })+})diff --git a/tests/engine/geometry/arrow-caps.test.ts b/tests/engine/geometry/arrow-caps.test.tsindex 0125aa6a9..411ceec68 100644--- a/tests/engine/geometry/arrow-caps.test.ts+++ b/tests/engine/geometry/arrow-caps.test.ts@@ -6,11 +6,16 @@ import {arrowCapOverflow,arrowLinesSegments,collectArrowEndpoints,+ circleCapRadius,+ diamondCapPoints,equilateralArrowPoints,isArrowCap,- lineArrowEndpoints+ lineArrowEndpoints,+ triangleCapPoints,+ trimArrowShafts} from '@open-pencil/scene-graph/arrow-caps'import { strokeOverflow } from '@open-pencil/scene-graph/geometry'+import type { Vector } from '@open-pencil/scene-graph/primitives'const SQRT3 = Math.sqrt(3)@@ -32,9 +37,12 @@ function straightOpenLine(): VectorNetwork {}describe('isArrowCap', () => {- test('recognizes both arrow cap kinds and nothing else', () => {+ test('recognizes the arrow and filled head caps and nothing else', () => {expect(isArrowCap('ARROW_LINES')).toBe(true)expect(isArrowCap('ARROW_EQUILATERAL')).toBe(true)+ expect(isArrowCap('TRIANGLE_FILLED')).toBe(true)+ expect(isArrowCap('DIAMOND_FILLED')).toBe(true)+ expect(isArrowCap('CIRCLE_FILLED')).toBe(true)expect(isArrowCap('ROUND')).toBe(false)expect(isArrowCap('SQUARE')).toBe(false)expect(isArrowCap('NONE')).toBe(false)@@ -288,3 +296,78 @@ describe('strokeOverflow with arrow caps', () => {expect(strokeOverflow([stroke()])).toBe(2)})})++// Stroke outlines Figma gives for a line from (0, 0) to (200, 0) at weight 4, recorded 2026-10-15.+describe('filled heads', () => {+ const rounded = (points: Vector[]) =>+ points.map(({ x, y }) => [Math.round(x * 1000) / 1000, Math.round(y * 1000) / 1000 + 0])++ test('a triangle spreads across the end and narrows back to the line', () => {+ expect(rounded(triangleCapPoints(200, 0, 0, 4))).toEqual([+ [180, 2],+ [200, 11.547],+ [200, -11.547],+ [180, -2]+ ])+ })++ test('a diamond and a circle sit centred on the end', () => {+ expect(rounded(diamondCapPoints(200, 0, 0, 4))).toEqual([+ [211.547, 0],+ [200, 11.547],+ [188.453, 0],+ [200, -11.547]+ ])+ expect(circleCapRadius(4)).toBeCloseTo(10.6667, 4)+ })++ test('a straight end stays straight when the line stops short, so its corner keeps its radius', () => {+ const network: VectorNetwork = {+ vertices: [+ { x: 0, y: 0 },+ { x: 0, y: 60 },+ { x: 100, y: 60, strokeCap: 'TRIANGLE_FILLED' }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: []+ }+ const trimmed = trimArrowShafts(network, 'NONE', 8)+ expect(trimmed.vertices[2]).toMatchObject({ x: 64, y: 60 })+ expect(trimmed.segments[1]).toMatchObject({+ tangentStart: { x: 0, y: 0 },+ tangentEnd: { x: 0, y: 0 }+ })+ })++ test('both ends of an open path that meet at one point stop short of their heads', () => {+ const network: VectorNetwork = {+ vertices: [+ { x: 0, y: 0, strokeCap: 'TRIANGLE_FILLED' },+ { x: 100, y: 0 },+ { x: 0, y: 0, strokeCap: 'TRIANGLE_FILLED' }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } },+ { start: 1, end: 2, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: []+ }+ const trimmed = trimArrowShafts(network, 'NONE', 4)+ expect(trimmed.vertices[0].x).toBeCloseTo(18, 6)+ expect(trimmed.vertices[2].x).toBeCloseTo(18, 6)+ })++ test('the line stops 4.5 weights short of a triangle or equilateral head only', () => {+ const network = straightOpenLine()+ network.vertices[0].strokeCap = 'CIRCLE_FILLED'+ network.vertices[1].strokeCap = 'TRIANGLE_FILLED'+ const trimmed = trimArrowShafts(network, 'NONE', 4)+ expect(trimmed.vertices[0]).toMatchObject({ x: 0, y: 0 })+ expect(trimmed.vertices[1].x).toBeCloseTo(82, 6)+ expect(trimmed.vertices[1].y).toBeCloseTo(0, 6)+ expect(network.vertices[1].x).toBe(100)+ })+})diff --git a/tests/helpers/canvas/connector-driver.ts b/tests/helpers/canvas/connector-driver.tsnew file mode 100644index 000000000..9e0966752--- /dev/null+++ b/tests/helpers/canvas/connector-driver.ts@@ -0,0 +1,209 @@+import { expect, type Page } from '@playwright/test'++import type { ConnectorEndpoint } from '@open-pencil/scene-graph'++import { toolbarToolTestId } from '#tests/helpers/test-ids'++/** The canvas point the page's origin is shown at, at 100%. */+const ORIGIN = 100++export interface ConnectorState {+ id: string+ start: ConnectorEndpoint | null+ end: ConnectorEndpoint | null+ label: string+}++/** Connectors between layers on a page shown at 100% with its origin 100 px into the canvas. */+export function connectorDriver(page: () => Page) {+ return {+ /** Setup: shows the page's origin at a known canvas point. */+ showOrigin() {+ return page().evaluate((origin) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ store.state.zoom = 1+ store.state.panX = origin+ store.state.panY = origin+ store.requestRender()+ }, ORIGIN)+ },++ /** Setup: named rectangles at page boxes; returns their ids by name. */+ addBoxes(boxes: { name: string; x: number; y: number; width: number; height: number }[]) {+ return page().evaluate((specs) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const ids: Record<string, string> = {}+ for (const spec of specs) {+ const node = store.graph.createNode('RECTANGLE', store.state.currentPageId, {+ ...spec,+ fills: [+ {+ type: 'SOLID',+ color: { r: 0.85, g: 0.88, b: 0.95, a: 1 },+ opacity: 1,+ visible: true+ }+ ]+ })+ ids[spec.name] = node.id+ }+ store.clearSelection()+ store.requestRender()+ return ids+ }, boxes)+ },++ /** Probe: the page's connectors, the last drawn last. */+ connectors(): Promise<ConnectorState[]> {+ return page().evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ return store.graph+ .getChildren(store.state.currentPageId)+ .filter((node) => node.type === 'CONNECTOR')+ .map((connector) => ({+ id: connector.id,+ start: connector.connectorStart,+ end: connector.connectorEnd,+ label: store.graph.getChildren(connector.id)[2]?.text ?? ''+ }))+ })+ },++ /** Probe: the active tool, the selection, the text being typed into, and the attach target. */+ focus() {+ return page().evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ return {+ tool: store.state.activeTool,+ selected: [...store.state.selectedIds],+ editing: store.state.editingTextId,+ target: store.state.connectorTarget+ }+ })+ },++ /** A point on a connector's line, midway along its first piece, in page coordinates. */+ linePoint(id: string) {+ return page().evaluate((connectorId) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const connector = store.graph.getNode(connectorId)+ const line = connector && store.graph.getChildren(connector.id)[0]+ const [a, b] = line?.vectorNetwork?.vertices ?? []+ if (!connector || !line || !a || !b) throw new Error(`No route for ${connectorId}`)+ return {+ x: connector.x + line.x + (a.x + b.x) / 2,+ y: connector.y + line.y + (a.y + b.y) / 2+ }+ }, id)+ },++ /**+ * Setup: four connectors at 100%, one per filled cap, the first selected, and a layer+ * outlined as an attach target, for the canvas to draw them all.+ */+ showCapsAndHandles() {+ return page().evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const page = store.state.currentPageId+ const box = (x: number, y: number) =>+ store.graph.createNode('RECTANGLE', page, {+ x,+ y,+ width: 160,+ height: 120,+ fills: [+ {+ type: 'SOLID',+ color: { r: 0.85, g: 0.88, b: 0.95, a: 1 },+ opacity: 1,+ visible: true+ }+ ]+ })+ const caps = [+ 'TRIANGLE_FILLED',+ 'DIAMOND_FILLED',+ 'CIRCLE_FILLED',+ 'ARROW_EQUILATERAL'+ ] as const+ let selected = ''+ caps.forEach((cap, row) => {+ const from = box(40, 40 + row * 160)+ const to = box(480, 100 + row * 160)+ store.setTool('CONNECTOR')+ store.connectorBegin(from.x + 80, from.y + 60)+ store.connectorRelease(to.x + 80, to.y + 60, true)+ const connector = store.graph+ .getChildren(page)+ .findLast((node) => node.type === 'CONNECTOR')+ if (!connector) throw new Error('No connector')+ store.setConnectorCap([connector.id], 'start', cap)+ store.setConnectorCap([connector.id], 'end', cap)+ if (row === 0) selected = connector.id+ })+ store.setTool('SELECT')+ store.select([selected])+ const target = box(760, 300)+ store.state.connectorTarget = { nodeId: target.id, magnet: 'TOP' }+ store.state.zoom = 1+ store.state.panX = 0+ store.state.panY = 0+ store.requestRender()+ })+ },++ /** Driver: selects one connector, as clicking its line would. */+ select(id: string) {+ return page().evaluate((connectorId) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ store.select([connectorId])+ }, id)+ },++ /** A connector's line type and end caps, as the Connector section sets them. */+ style(id: string) {+ return page().evaluate((connectorId) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const node = store.graph.getNode(connectorId)+ if (!node) throw new Error(`No connector ${connectorId}`)+ return {+ line: node.connectorLineType,+ startCap: node.connectorStartCap,+ endCap: node.connectorEndCap+ }+ }, id)+ },++ /** Canvas coordinates of a page point, under `showOrigin`. */+ point(x: number, y: number) {+ return { x: ORIGIN + x, y: ORIGIN + y }+ },++ /** Driver: shows the connector tool from Customize toolbar, where it starts hidden. */+ async showTool() {+ const button = page().getByTestId(toolbarToolTestId('CONNECTOR'))+ if ((await button.count()) > 0) return+ await page().getByTestId('toolbar').click({ button: 'right' })+ await page().getByRole('menuitem', { name: 'Customize toolbar…' }).click()+ await page()+ .getByTestId('settings-toolbar-panel')+ .getByRole('switch', { name: 'Show Connector', exact: true })+ .click()+ await page().getByTestId('app-settings-done').click()+ await expect(button).toBeVisible()+ },++ /** Driver: picks the connector tool from the toolbar. */+ async pickTool() {+ await page().getByTestId(toolbarToolTestId('CONNECTOR')).click()+ }+ }+}