Skip to content

AI-native design editor. Open-source Figma alternative.

fix: attach connector ends as Figma Design does (#1477)

Danila Poyarkovca58baa6efec
diff --git a/changes/1477/fixed.md b/changes/1477/fixed.md
new file mode 100644
index 000000000..8da19b0d6
--- /dev/null
+++ b/changes/1477/fixed.md
@@ -0,0 +1 @@
+- Connector ends attach as in Figma Design: to the nearest side inside a layer, only within 8 px outside it, pinned at the exact point with ⌘ or Ctrl, and to the centre with Shift.
diff --git a/packages/core/src/editor/connectors/attach.ts b/packages/core/src/editor/connectors/attach.ts
index 102687d44..9abaf7932 100644
--- a/packages/core/src/editor/connectors/attach.ts
+++ b/packages/core/src/editor/connectors/attach.ts
@@ -1,4 +1,4 @@
-import { minBy } from 'es-toolkit'
+import { clamp, minBy } from 'es-toolkit'
import type {
ConnectorEndpoint,
@@ -12,15 +12,20 @@ import Matrix from '@open-pencil/scene-graph/matrix'
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. Inside a
- * section, measured on a 400 × 320 one, an end within 16 px of the centre takes the nearest side
- * and any other is pinned where it was dropped.
+ * Where Figma Design attaches a connector end dropped on a layer, measured on 200 and 400 px
+ * squares at 100% and 200%: within 8 screen px outside its outline, the end takes the side it is
+ * past; inside, the nearest side, or any side within 24 units of the centre. Ties go to the top,
+ * then right, bottom, and left.
*/
-const OUTLINE_INSIDE = 12
const OUTLINE_OUTSIDE = 8
+const CENTRE_REACH = 24
+/**
+ * A section, measured in FigJam on a 400 × 320 one: within 12 screen px inside its outline the
+ * end takes a side within 16 px of its midpoint, or holds to the outline and picks left or right
+ * as the route needs; within 16 px of the centre it takes the nearest side, and elsewhere it is
+ * pinned where it was dropped.
+ */
+const OUTLINE_INSIDE = 12
const MIDPOINT_SNAP = 16
/**
@@ -64,6 +69,16 @@ function outlineDistance(box: Rect, point: Vector): number {
return Math.hypot(Math.max(dx, 0), Math.max(dy, 0))
}
+/** How far `point` is inside each side of `box`, in the order ties go: negative past it. */
+function sideDepths(box: Rect, point: Vector): [Side, number][] {
+ return [
+ ['TOP', point.y - box.y],
+ ['RIGHT', box.x + box.width - point.x],
+ ['BOTTOM', box.y + box.height - point.y],
+ ['LEFT', point.x - box.x]
+ ]
+}
+
/**
* The magnet a point on or near `box` picks, or null when it is too far outside. A layer that
* `pins` ends, as a section does, takes one dropped inside away from its centre as `ABSOLUTE`.
@@ -76,13 +91,22 @@ export function magnetAt(
): ConnectorMagnet | null {
const distance = outlineDistance(box, point)
if (distance > OUTLINE_OUTSIDE / zoom) return null
+ if (!pins) {
+ const centre = { x: box.x + box.width / 2, y: box.y + box.height / 2 }
+ if (distance <= 0 && Math.hypot(point.x - centre.x, point.y - centre.y) < CENTRE_REACH) {
+ return 'AUTO'
+ }
+ // Inside, the side nearest the point; outside, the side it is farthest past.
+ return minBy(sideDepths(box, point), ([, depth]) => depth)?.[0] ?? 'AUTO'
+ }
+ return sectionMagnet(box, point, zoom, distance)
+}
+
+function sectionMagnet(box: Rect, point: Vector, zoom: number, distance: number): ConnectorMagnet {
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(
@@ -93,7 +117,6 @@ export function magnetAt(
)
return side?.magnet ?? 'AUTO_HORIZONTAL'
}
- if (!pins) return nearest.magnet
const centre = candidates[candidates.length - 1]
if (centre.distance > MIDPOINT_SNAP / zoom) return 'ABSOLUTE'
// Near the centre the nearest side midpoint wins, ties going to the top.
@@ -154,17 +177,42 @@ function containersOf(graph: SceneGraph, nodeId: string | undefined): Set<string
return containers
}
+/** How the keys held while an end is dropped change where it attaches, as in Figma Design. */
+export interface AttachModifiers {
+ /** ⌘ or Ctrl: the end is pinned at the point on the layer, kept within its box. */
+ pin?: boolean
+ /** Shift: the end attaches to the layer's centre. */
+ centre?: boolean
+}
+
+/** The magnet an end takes once its line type and the keys held have their say. */
+function droppedMagnet(
+ magnet: ConnectorMagnet,
+ options: { straight?: boolean } & AttachModifiers
+): ConnectorMagnet {
+ if (options.straight || options.centre) return 'CENTER'
+ return options.pin ? 'NONE' : magnet
+}
+
+/** `point` in `node`'s own axes, held within its box. */
+function pointOn(graph: SceneGraph, node: SceneNode, point: Vector): Vector {
+ const toLayer = Matrix.invert(getWorldMatrix(node, graph)) ?? Matrix.identity()
+ const [x, y] = Matrix.mapPoints(toLayer, [point.x, point.y])
+ return { x: clamp(x, 0, node.width), y: clamp(y, 0, node.height) }
+}
+
/**
* Where a connector end lands at `point`, in page coordinates: on the layer under it by the
* magnet its position picks, pinned at the point in the layer's own axes, 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.
+ * Straight connectors attach by centres, as do ends dropped with `centre`; `pin` pins an end at
+ * the point. 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 }
+ options: { zoom: number; straight?: boolean; connectorId?: string } & AttachModifiers
): { endpoint: ConnectorEndpoint; target: ConnectorTarget | null } {
const hit = targetIn(graph, pageId, {
pageId,
@@ -174,10 +222,11 @@ export function connectorAttachment(
around: containersOf(graph, options.connectorId)
})
if (!hit) return { endpoint: freeEndpoint(point.x, point.y), target: null }
- const magnet = options.straight ? 'CENTER' : hit.magnet
+ const magnet = droppedMagnet(hit.magnet, options)
const target = { nodeId: hit.node.id, magnet }
- if (magnet !== 'ABSOLUTE') return { endpoint: boundEndpoint(hit.node.id, magnet), target }
- const toLayer = Matrix.invert(getWorldMatrix(hit.node, graph)) ?? Matrix.identity()
- const [x, y] = Matrix.mapPoints(toLayer, [point.x, point.y])
- return { endpoint: { nodeId: hit.node.id, magnet, position: { x, y } }, target }
+ if (magnet !== 'ABSOLUTE' && magnet !== 'NONE') {
+ return { endpoint: boundEndpoint(hit.node.id, magnet), target }
+ }
+ const position = pointOn(graph, hit.node, point)
+ return { endpoint: { nodeId: hit.node.id, magnet, position }, target }
}
diff --git a/packages/core/src/editor/connectors/draw.ts b/packages/core/src/editor/connectors/draw.ts
index 15e981d38..aa4354d95 100644
--- a/packages/core/src/editor/connectors/draw.ts
+++ b/packages/core/src/editor/connectors/draw.ts
@@ -2,7 +2,11 @@ import type { ConnectorEndpoint } from '@open-pencil/scene-graph'
import { createConnector, layoutConnector } from '@open-pencil/scene-graph/connectors'
import type { Vector } from '@open-pencil/scene-graph/primitives'
-import { connectorAttachment, type ConnectorTarget } from '#core/editor/connectors/attach'
+import {
+ connectorAttachment,
+ type AttachModifiers,
+ 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'
@@ -30,33 +34,34 @@ export function createConnectorDrawActions(ctx: EditorContext) {
ctx.requestRepaint()
}
- function attach(point: Vector, connectorId?: string) {
+ function attach(point: Vector, modifiers: AttachModifiers, connectorId?: string) {
return connectorAttachment(ctx.graph, ctx.state.currentPageId, point, {
zoom: ctx.state.zoom,
- connectorId
+ connectorId,
+ ...modifiers
})
}
/** 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)
+ function connectorHover(x: number, y: number, modifiers: AttachModifiers = {}) {
+ if (draft?.clicked) connectorDrag(x, y, modifiers)
+ else setTarget(attach({ x, y }, modifiers).target)
}
/** Starts a connector at `point`, or ends the one a click started. */
- function connectorBegin(x: number, y: number) {
+ function connectorBegin(x: number, y: number, modifiers: AttachModifiers = {}) {
if (draft) return
draft = {
- start: attach({ x, y }).endpoint,
+ start: attach({ x, y }, modifiers).endpoint,
connectorId: null,
previousSelection: new Set(ctx.state.selectedIds),
clicked: false
}
}
- function connectorDrag(x: number, y: number) {
+ function connectorDrag(x: number, y: number, modifiers: AttachModifiers = {}) {
if (!draft) return
- const { endpoint, target } = attach({ x, y }, draft.connectorId ?? undefined)
+ const { endpoint, target } = attach({ x, y }, modifiers, draft.connectorId ?? undefined)
setTarget(target)
const graph = ctx.graph
if (!draft.connectorId) {
@@ -82,13 +87,13 @@ export function createConnectorDrawActions(ctx: EditorContext) {
* 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) {
+ function connectorRelease(x: number, y: number, moved: boolean, modifiers: AttachModifiers = {}) {
if (!draft) return
if (!draft.connectorId && !moved && !draft.clicked) {
draft.clicked = true
return
}
- connectorDrag(x, y)
+ connectorDrag(x, y, modifiers)
const { connectorId, previousSelection } = draft
draft = null
setTarget(null)
@@ -121,9 +126,9 @@ export function createConnectorDrawActions(ctx: EditorContext) {
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.
+ * Dragging an end of a selected connector, as Figma does: the end follows the pointer, attaches
+ * to the layer under it by the magnet its position picks, or pinned or centred as the keys held
+ * say, and the connector routes as it goes. One undo step puts the end back.
*/
export function createConnectorEndpointActions(
ctx: EditorContext,
@@ -144,7 +149,7 @@ export function createConnectorEndpointActions(
drag = { connectorId, end, joined, preview: beginNodePreview('Move connector end') }
}
- function connectorEndpointDrag(x: number, y: number) {
+ function connectorEndpointDrag(x: number, y: number, modifiers: AttachModifiers = {}) {
if (!drag) return
const connector = ctx.graph.getNode(drag.connectorId)
if (!connector) return
@@ -155,7 +160,8 @@ export function createConnectorEndpointActions(
{
zoom: ctx.state.zoom,
straight: connector.connectorLineType === 'STRAIGHT',
- connectorId: connector.id
+ connectorId: connector.id,
+ ...modifiers
}
)
ctx.state.connectorTarget = target
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index 3735930ff..fdb89c33e 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -11,6 +11,7 @@ export { createDefaultEditorSharedState } from './state/shared'
export { editedGradient, editedGradientLayout } from './gradient-edit'
export type { SelectionSpacing } from './alignment'
export type { MovePlace } from './undo'
+export type { AttachModifiers } from './connectors/attach'
export {
replaceSelectionColor,
selectionColors,
diff --git a/packages/core/tests/editor/connectors/draw.test.ts b/packages/core/tests/editor/connectors/draw.test.ts
index 1d502925a..d1c98a719 100644
--- a/packages/core/tests/editor/connectors/draw.test.ts
+++ b/packages/core/tests/editor/connectors/draw.test.ts
@@ -19,31 +19,40 @@ function connectors(editor: ReturnType<typeof createEditor>) {
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.
+// Measured by dragging a connector end in Figma Design onto 200 and 400 px squares at 100% and
+// 200% on 2026-10-25.
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('points inside take the nearest side, ties going top, right, bottom, then left', () => {
+ expect(magnetAt(BOX, { x: 100, y: 30 }, 1)).toBe('TOP')
+ expect(magnetAt(BOX, { x: 30, y: 100 }, 1)).toBe('LEFT')
+ expect(magnetAt(BOX, { x: 150, y: 60 }, 1)).toBe('RIGHT')
+ expect(magnetAt(BOX, { x: 40, y: 4 }, 1)).toBe('TOP')
+ expect(magnetAt(BOX, { x: 196, y: 10 }, 1)).toBe('RIGHT')
+ expect(magnetAt(BOX, { x: 50, y: 50 }, 1)).toBe('TOP')
+ expect(magnetAt(BOX, { x: 60, y: 140 }, 1)).toBe('BOTTOM')
+ expect(magnetAt(BOX, { x: 200, y: 0 }, 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('within 24 units of the centre an end attaches by any side, at any size and zoom', () => {
+ expect(magnetAt(BOX, { x: 100, y: 77 }, 1)).toBe('AUTO')
+ expect(magnetAt(BOX, { x: 115, y: 115 }, 1)).toBe('AUTO')
+ expect(magnetAt(BOX, { x: 100, y: 76 }, 1)).toBe('TOP')
+ expect(magnetAt(BOX, { x: 80, y: 80 }, 1)).toBe('TOP')
+ expect(magnetAt(BOX, { x: 100, y: 77 }, 2)).toBe('AUTO')
+ const large = { x: 0, y: 0, width: 400, height: 400 }
+ expect(magnetAt(large, { x: 200, y: 177 }, 1)).toBe('AUTO')
+ expect(magnetAt(large, { x: 200, y: 176 }, 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()
+ test('within 8 screen px outside an end takes the side it is past, and further out stays free', () => {
+ expect(magnetAt(BOX, { x: 40, y: -7 }, 1)).toBe('TOP')
+ expect(magnetAt(BOX, { x: 204, y: 0 }, 1)).toBe('RIGHT')
+ expect(magnetAt(BOX, { x: -4, y: -4 }, 1)).toBe('TOP')
+ expect(magnetAt(BOX, { x: -5, y: 0 }, 1)).toBe('LEFT')
+ expect(magnetAt(BOX, { x: 100, y: -8.5 }, 1)).toBeNull()
expect(magnetAt(BOX, { x: -8, y: -8 }, 1)).toBeNull()
+ expect(magnetAt(BOX, { x: 100, y: -3 }, 2)).toBe('TOP')
+ expect(magnetAt(BOX, { x: 100, y: -4.5 }, 2)).toBeNull()
})
test('a straight connector attaches by centres', () => {
@@ -59,6 +68,16 @@ describe('where a connector end attaches', () => {
)
expect(endpoint).toEqual({ nodeId: a.id, magnet: 'CENTER', position: { x: 0, y: 0 } })
})
+
+ test('⌘ pins an end at the point, held within the layer, and Shift centres it', () => {
+ const { editor, page, a } = setup()
+ const at = (x: number, y: number, modifiers: { pin?: boolean; centre?: boolean }) =>
+ connectorAttachment(editor.graph, page, { x, y }, { zoom: 1, ...modifiers }).endpoint
+ expect(at(60, 40, { pin: true })).toEqual({ nodeId: a.id, magnet: 'NONE', position: { x: 60, y: 40 } })
+ expect(at(100, -4, { pin: true })).toEqual({ nodeId: a.id, magnet: 'NONE', position: { x: 100, y: 0 } })
+ expect(at(100, -20, { pin: true }).nodeId).toBeNull()
+ expect(at(60, 40, { centre: true })).toMatchObject({ nodeId: a.id, magnet: 'CENTER' })
+ })
})
// Measured with FigJam's connector tool on a 400 × 320 section at 100% on 2026-10-19.
diff --git a/packages/scene-graph/src/connectors/layout.ts b/packages/scene-graph/src/connectors/layout.ts
index 63b4afd7d..1da1ef51c 100644
--- a/packages/scene-graph/src/connectors/layout.ts
+++ b/packages/scene-graph/src/connectors/layout.ts
@@ -32,13 +32,17 @@ function routeEnd(
const point = endpoint.nodeId && fallback ? fallback : endpoint.position
return { box: null, point, magnet: 'NONE', cap, outline: 0 }
}
- if (endpoint.magnet === 'NONE' || endpoint.magnet === 'ABSOLUTE') {
+ // An elbow or curve joined at the centre runs into the layer to its centre, as Figma Design
+ // draws it; a straight line stops at the outline on its way there.
+ const centred = endpoint.magnet === 'CENTER' && connector.connectorLineType !== 'STRAIGHT'
+ if (endpoint.magnet === 'NONE' || endpoint.magnet === 'ABSOLUTE' || centred) {
// A point in the layer's own axes, carried into the connector's parent's.
const toParent =
Matrix.invert(getParentWorldMatrix(graph.getNode(parentId), graph)) ?? Matrix.identity()
+ const local = centred ? { x: node.width / 2, y: node.height / 2 } : endpoint.position
const [x, y] = Matrix.mapPoints(Matrix.multiply(toParent, getWorldMatrix(node, graph)), [
- endpoint.position.x,
- endpoint.position.y
+ local.x,
+ local.y
])
return { box: null, point: { x, y }, magnet: endpoint.magnet, cap, outline: 0 }
}
diff --git a/packages/scene-graph/tests/connectors/layout.test.ts b/packages/scene-graph/tests/connectors/layout.test.ts
index cba7a823e..acc95b0e7 100644
--- a/packages/scene-graph/tests/connectors/layout.test.ts
+++ b/packages/scene-graph/tests/connectors/layout.test.ts
@@ -133,3 +133,29 @@ test('the graph keeps its connectors indexed as they come and go', () => {
graph.deleteNode(connector.id)
expect(graph.connectorIds.has(connector.id)).toBe(false)
})
+
+// Live Figma Design 2026-10-25: an elbow from a 96 × 64 shape's AUTO to a 200 px square's CENTER
+// runs down, across midway, and down into the square, stopping its end gap short of the centre.
+test('an elbow joined at the centre runs into the layer to its centre', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const from = graph.createNode('RECTANGLE', page, { x: 4980, y: 4915, width: 96, height: 64 })
+ const to = graph.createNode('RECTANGLE', page, { x: 5020, y: 5085, width: 200, height: 200 })
+ const connector = createConnector(graph, page, {
+ start: boundEndpoint(from.id),
+ end: boundEndpoint(to.id, 'CENTER'),
+ startCap: 'ROUND',
+ endCap: 'ARROW_LINES'
+ })
+ layoutConnector(graph, connector)
+ const laid = graph.getNode(connector.id) ?? connector
+ expect(connectorRouteEnds(graph, laid)?.end).toEqual({ x: 5120, y: 5178.5 })
+ const line = connectorSublayers(graph, laid)?.line
+ const ys = (line?.vectorNetwork?.vertices ?? []).map((v) => laid.y + (line?.y ?? 0) + v.y)
+ expect(ys).toContain(5082)
+ // A straight connector still stops at the outline.
+ graph.updateNode(connector.id, { connectorLineType: 'STRAIGHT' })
+ const straight = graph.getNode(connector.id) ?? connector
+ layoutConnector(graph, straight)
+ expect(connectorRouteEnds(graph, straight)?.end.y).toBeLessThan(5085)
+})
diff --git a/packages/vue/src/canvas/tools/input.ts b/packages/vue/src/canvas/tools/input.ts
index 79e9a46b5..dba1a5be7 100644
--- a/packages/vue/src/canvas/tools/input.ts
+++ b/packages/vue/src/canvas/tools/input.ts
@@ -5,7 +5,7 @@ import type { Editor } from '@open-pencil/core'
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 { attachModifiers, 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'
@@ -85,7 +85,7 @@ export function handleToolMouseDown({
}
if (tool === 'CONNECTOR') {
- startConnectorDraw(cx, cy, sx, sy, editor, setDrag)
+ startConnectorDraw(cx, cy, sx, sy, editor, setDrag, attachModifiers(event))
return
}
diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.ts
index b506e9eda..33027a853 100644
--- a/packages/vue/src/canvas/useCanvasInput.ts
+++ b/packages/vue/src/canvas/useCanvasInput.ts
@@ -22,7 +22,11 @@ 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 {
+ attachModifiers,
+ handleConnectorDrawMove,
+ refreshConnectorDrag
+} 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'
@@ -268,7 +272,7 @@ export function useCanvasInput(
}
if (!drag.value && editor.state.activeTool === 'CONNECTOR') {
- editor.connectorHover(coords.cx, coords.cy)
+ editor.connectorHover(coords.cx, coords.cy, attachModifiers(e))
}
if (!drag.value && editor.state.activeTool === 'SELECT') {
@@ -367,12 +371,12 @@ export function useCanvasInput(
}
if (d.type === 'connector-draw') {
- handleConnectorDrawMove(d, cx, cy, sx, sy, editor)
+ handleConnectorDrawMove(d, cx, cy, sx, sy, editor, attachModifiers(e))
return
}
if (d.type === 'connector-end') {
- editor.connectorEndpointDrag(cx, cy)
+ editor.connectorEndpointDrag(cx, cy, attachModifiers(e))
return
}
@@ -491,9 +495,14 @@ export function useCanvasInput(
useEventListener(canvasRef, 'mousemove', onMouseMove)
useEventListener(canvasRef, 'mouseup', onMouseUp)
useEventListener(window, 'keydown', (event) => {
- if (!guideInput.deleteSelected(event)) updateModifier(event.code, true)
+ if (guideInput.deleteSelected(event)) return
+ updateModifier(event.code, true)
+ refreshConnectorDrag(drag.value, lastPointer.value, event, editor)
+ })
+ useEventListener(window, 'keyup', (event) => {
+ updateModifier(event.code, false)
+ refreshConnectorDrag(drag.value, lastPointer.value, event, editor)
})
- useEventListener(window, 'keyup', (event) => updateModifier(event.code, false))
useEventListener(
window,
'keydown',
diff --git a/packages/vue/src/shared/input/connector/draw.ts b/packages/vue/src/shared/input/connector/draw.ts
index 07654cff0..a25a7b090 100644
--- a/packages/vue/src/shared/input/connector/draw.ts
+++ b/packages/vue/src/shared/input/connector/draw.ts
@@ -1,8 +1,15 @@
-import type { Editor } from '@open-pencil/core'
+import type { AttachModifiers, Editor } from '@open-pencil/core'
import { isPastPointerDragThreshold } from '#vue/shared/input/drag-threshold'
import type { DragConnectorDraw, DragState } from '#vue/shared/input/types'
+/** How the keys held on a pointer or key event change where a connector end attaches. */
+export function attachModifiers(
+ e: Pick<MouseEvent, 'metaKey' | 'ctrlKey' | 'shiftKey'>
+): AttachModifiers {
+ return { pin: e.metaKey || e.ctrlKey, centre: e.shiftKey }
+}
+
/** Starts a connector at the press, or ends the one a click started, as FigJam's tool does. */
export function startConnectorDraw(
cx: number,
@@ -10,9 +17,10 @@ export function startConnectorDraw(
sx: number,
sy: number,
editor: Editor,
- setDrag: (drag: DragState) => void
+ setDrag: (drag: DragState) => void,
+ modifiers: AttachModifiers
) {
- editor.connectorBegin(cx, cy)
+ editor.connectorBegin(cx, cy, modifiers)
const drag: DragConnectorDraw = {
type: 'connector-draw',
startSX: sx,
@@ -20,7 +28,8 @@ export function startConnectorDraw(
moved: false,
x: cx,
y: cy,
- commit: () => editor.connectorRelease(drag.x, drag.y, drag.moved),
+ modifiers,
+ commit: () => editor.connectorRelease(drag.x, drag.y, drag.moved, drag.modifiers),
cancel: () => editor.connectorCancel()
}
setDrag(drag)
@@ -32,10 +41,34 @@ export function handleConnectorDrawMove(
cy: number,
sx: number,
sy: number,
- editor: Editor
+ editor: Editor,
+ modifiers: AttachModifiers
) {
drag.x = cx
drag.y = cy
+ drag.modifiers = modifiers
drag.moved ||= isPastPointerDragThreshold(drag.startSX, drag.startSY, sx, sy)
- if (drag.moved) editor.connectorDrag(cx, cy)
+ if (drag.moved) editor.connectorDrag(cx, cy, modifiers)
+}
+
+/** The keys that change where a connector end attaches: Shift centres it, ⌘ or Ctrl pins it. */
+const CONNECTOR_KEYS = new Set(['Shift', 'Meta', 'Control'])
+
+/**
+ * A key pressed or let go mid-drag changes where a drawn or dragged connector end attaches at
+ * once, at the last pointer position, so a release without a move after it attaches by it.
+ */
+export function refreshConnectorDrag(
+ drag: DragState | null,
+ pointer: { cx: number; cy: number; sx: number; sy: number } | null,
+ e: Pick<KeyboardEvent, 'key' | 'metaKey' | 'ctrlKey' | 'shiftKey'>,
+ editor: Editor
+) {
+ if (!drag || !pointer || !CONNECTOR_KEYS.has(e.key)) return
+ const { cx, cy, sx, sy } = pointer
+ if (drag.type === 'connector-draw') {
+ handleConnectorDrawMove(drag, cx, cy, sx, sy, editor, attachModifiers(e))
+ } else if (drag.type === 'connector-end') {
+ editor.connectorEndpointDrag(cx, cy, attachModifiers(e))
+ }
}
diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.ts
index 3c69245ba..5f3425481 100644
--- a/packages/vue/src/shared/input/types.ts
+++ b/packages/vue/src/shared/input/types.ts
@@ -1,4 +1,4 @@
-import type { MovePlace, Tool } from '@open-pencil/core'
+import type { AttachModifiers, MovePlace, Tool } from '@open-pencil/core'
import type { HandlePosition } from '@open-pencil/core/geometry'
import type {
DerivedTextGlyph,
@@ -44,6 +44,8 @@ export interface DragConnectorDraw {
/** Where the pointer is, in canvas coordinates. */
x: number
y: number
+ /** The keys held at the last move, which the release attaches by. */
+ modifiers: AttachModifiers
commit: () => void
cancel: () => void
}
diff --git a/packages/vue/tests/shared/input/connector/draw.test.ts b/packages/vue/tests/shared/input/connector/draw.test.ts
new file mode 100644
index 000000000..0354ed791
--- /dev/null
+++ b/packages/vue/tests/shared/input/connector/draw.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, expect, test } from 'bun:test'
+
+import { createEditor, type Editor } from '@open-pencil/core'
+import { boundEndpoint, createConnector, freeEndpoint } from '@open-pencil/scene-graph/connectors'
+
+import { refreshConnectorDrag, startConnectorDraw } from '#vue/shared/input/connector/draw'
+import type { DragState } from '#vue/shared/input/types'
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+function square() {
+ editor = createEditor()
+ const page = editor.state.currentPageId
+ const target = editor.graph.createNode('RECTANGLE', page, { width: 200, height: 200 })
+ return { page, target }
+}
+
+/** A key event as the window reports it: the key, and the modifiers held once it changed. */
+const keyEvent = (key: string, held: { shiftKey?: boolean; metaKey?: boolean }) => ({
+ key,
+ shiftKey: false,
+ metaKey: false,
+ ctrlKey: false,
+ ...held
+})
+
+test('Shift pressed after the last move attaches a dragged end to the centre at once', () => {
+ const { page, target } = square()
+ const source = editor.graph.createNode('RECTANGLE', page, { x: -300, width: 50, height: 50 })
+ const connector = createConnector(editor.graph, page, {
+ start: boundEndpoint(source.id),
+ end: freeEndpoint(-100, -100)
+ })
+ editor.connectorEndpointBegin(connector.id, 'connectorEnd')
+ const drag: DragState = {
+ type: 'connector-end',
+ commit: () => editor.connectorEndpointCommit(),
+ cancel: () => editor.connectorEndpointCancel()
+ }
+ const pointer = { cx: 60, cy: 40, sx: 60, sy: 40 }
+ editor.connectorEndpointDrag(pointer.cx, pointer.cy)
+ expect(editor.state.connectorTarget?.magnet).toBe('TOP')
+ refreshConnectorDrag(drag, pointer, keyEvent('Shift', { shiftKey: true }), editor)
+ expect(editor.state.connectorTarget).toEqual({ nodeId: target.id, magnet: 'CENTER' })
+ // Letting go before the release attaches by the side again.
+ refreshConnectorDrag(drag, pointer, keyEvent('Shift', {}), editor)
+ editor.connectorEndpointCommit()
+ expect(editor.graph.getNode(connector.id)?.connectorEnd?.magnet).toBe('TOP')
+})
+
+test('⌘ pressed after the last move pins a drawn end where the pointer is', () => {
+ const { target } = square()
+ editor.setTool('CONNECTOR')
+ const drags: DragState[] = []
+ startConnectorDraw(-300, 100, -300, 100, editor, (d) => drags.push(d), {})
+ const [drag] = drags
+ if (drag?.type !== 'connector-draw') throw new Error('Expected a connector draw')
+ const pointer = { cx: 60, cy: 40, sx: 60, sy: 40 }
+ refreshConnectorDrag(drag, pointer, keyEvent('Meta', { metaKey: true }), editor)
+ drag.commit()
+ const connector = [...editor.graph.getAllNodes()].find((node) => node.type === 'CONNECTOR')
+ expect(connector?.connectorEnd).toEqual({
+ nodeId: target.id,
+ magnet: 'NONE',
+ position: { x: 60, y: 40 }
+ })
+})