AI-native design editor. Open-source Figma alternative.
fix: pin connector ends to the point of a section they are dropped on (#1303)
Danila Poyarkov270dddec4c61
diff --git a/packages/core/src/editor/connectors/attach.ts b/packages/core/src/editor/connectors/attach.tsindex 46360b11e..ba4cc2468 100644--- a/packages/core/src/editor/connectors/attach.ts+++ b/packages/core/src/editor/connectors/attach.ts@@ -8,14 +8,17 @@ import {type SceneGraph,type SceneNode} from '@open-pencil/scene-graph'-import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'+import { getAxisAlignedBoundsInParent, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'+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.+ * 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.*/const OUTLINE_INSIDE = 12const OUTLINE_OUTSIDE = 8@@ -62,8 +65,16 @@ function outlineDistance(box: Rect, point: Vector): number {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 {+/**+ * 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`.+ */+export function magnetAt(+ box: Rect,+ point: Vector,+ zoom: number,+ pins = false+): ConnectorMagnet | null {const distance = outlineDistance(box, point)if (distance > OUTLINE_OUTSIDE / zoom) return nullconst candidates = sidePoints(box).map(([magnet, at]) => ({@@ -83,7 +94,13 @@ export function magnetAt(box: Rect, point: Vector, zoom: number): ConnectorMagne)return side?.magnet ?? 'AUTO_HORIZONTAL'}- return nearest.magnet+ 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.+ return candidates+ .slice(0, -1)+ .reduce((best, candidate) => (candidate.distance < best.distance ? candidate : best)).magnet}function attachable(node: SceneNode): boolean {@@ -111,7 +128,7 @@ function targetIn(const node = children[index]if (!attachable(node) || exclude.has(node.id)) continueconst box = getAxisAlignedBoundsInParent([node], pageId, graph)- const magnet = magnetAt(box, point, zoom)+ const magnet = magnetAt(box, point, zoom, node.type === 'SECTION')// 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)@@ -140,8 +157,9 @@ function containersOf(graph: SceneGraph, nodeId: string | undefined): Set<string/*** 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.+ * 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.*/export function connectorAttachment(graph: SceneGraph,@@ -158,5 +176,9 @@ export function connectorAttachment(})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 } }+ 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 }}diff --git a/packages/core/src/figma-api/accessors/connector.ts b/packages/core/src/figma-api/accessors/connector.tsindex 0f904ca83..d6681429c 100644--- a/packages/core/src/figma-api/accessors/connector.ts+++ b/packages/core/src/figma-api/accessors/connector.ts@@ -60,7 +60,10 @@ function editConnector(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. */+/**+ * An end as Figma's plugin API reports it; a free end names the page it lies on, and an end+ * pinned to a point of a section reports the magnet as `EDGE`.+ */function pluginEndpoint(target: ProxyThis, internals: NodeProxyInternals, end: ConnectorEnd) {const node = raw(target, internals)const endpoint = node[end]@@ -70,7 +73,8 @@ function pluginEndpoint(target: ProxyThis, internals: NodeProxyInternals, end: Creturn { endpointNodeId: graph(target, internals).pageOf(node.id) ?? '', position }}if (endpoint.magnet === 'NONE') return { endpointNodeId: endpoint.nodeId, position }- return { endpointNodeId: endpoint.nodeId, magnet: endpoint.magnet }+ const magnet = endpoint.magnet === 'ABSOLUTE' ? 'EDGE' : endpoint.magnet+ return { endpointNodeId: endpoint.nodeId, magnet }}interface PluginEndpoint {diff --git a/packages/core/tests/editor/connectors/draw.test.ts b/packages/core/tests/editor/connectors/draw.test.tsindex c03d689ea..5655381fd 100644--- a/packages/core/tests/editor/connectors/draw.test.ts+++ b/packages/core/tests/editor/connectors/draw.test.ts@@ -55,6 +55,36 @@ describe('where a connector end attaches', () => {})})+// Measured with FigJam's connector tool on a 400 × 320 section at 100% on 2026-10-19.+describe('where a connector end attaches inside a section', () => {+ const SECTION = { x: 0, y: 0, width: 400, height: 320 }++ test('near its outline it attaches as to any layer', () => {+ expect(magnetAt(SECTION, { x: 212, y: 10 }, 1, true)).toBe('TOP')+ expect(magnetAt(SECTION, { x: 220, y: 10 }, 1, true)).toBe('AUTO_HORIZONTAL')+ expect(magnetAt(SECTION, { x: 200, y: 312 }, 1, true)).toBe('BOTTOM')+ })++ test('near its centre it takes the nearest side, and elsewhere it is pinned', () => {+ expect(magnetAt(SECTION, { x: 200, y: 160 }, 1, true)).toBe('TOP')+ expect(magnetAt(SECTION, { x: 216, y: 160 }, 1, true)).toBe('TOP')+ expect(magnetAt(SECTION, { x: 224, y: 160 }, 1, true)).toBe('ABSOLUTE')+ expect(magnetAt(SECTION, { x: 20, y: 168 }, 1, true)).toBe('ABSOLUTE')+ expect(magnetAt(SECTION, { x: 40, y: 288 }, 1, true)).toBe('ABSOLUTE')+ })++ test("a pinned end keeps the point in the section's own axes", () => {+ const editor = createEditor()+ const page = editor.state.currentPageId+ const section = editor.graph.createNode('SECTION', page, { x: 480, y: -100, width: 400, height: 320 })+ expect(connectorAttachment(editor.graph, page, { x: 520, y: 158 }, { zoom: 1 })).toEqual({+ endpoint: { nodeId: section.id, magnet: 'ABSOLUTE', position: { x: 40, y: 258 } },+ target: { nodeId: section.id, magnet: 'ABSOLUTE' }+ })+ editor.dispose()+ })+})+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()diff --git a/packages/core/tests/editor/connectors/routing.test.ts b/packages/core/tests/editor/connectors/routing.test.tsindex fe7333ed4..7418e8091 100644--- a/packages/core/tests/editor/connectors/routing.test.ts+++ b/packages/core/tests/editor/connectors/routing.test.ts@@ -123,6 +123,30 @@ describe('connector routing', () => {}})+ test('an end pinned to a point of a section follows it as it moves, not as it resizes', async () => {+ const { editor, page, connector } = setup()+ try {+ const section = editor.graph.createNode('SECTION', page, {+ x: 400,+ y: -200,+ width: 400,+ height: 320+ })+ const pinned = { nodeId: section.id, magnet: 'ABSOLUTE' as const, position: { x: 40, y: 258 } }+ editor.updateNodeWithUndo(connector.id, { connectorEnd: pinned }, 'Bind')+ await settle()+ expect(route(editor, connector).at(-1)).toEqual([433.5, 58])+ editor.updateNodeWithUndo(section.id, { x: 500 }, 'Move')+ await settle()+ expect(route(editor, connector).at(-1)).toEqual([533.5, 58])+ editor.updateNodeWithUndo(section.id, { width: 200, height: 160 }, 'Resize')+ await settle()+ expect(route(editor, connector).at(-1)).toEqual([533.5, 58])+ } finally {+ editor.dispose()+ }+ })+test('a free end stays where it is put', async () => {const { editor, connector } = setup()try {diff --git a/packages/core/tests/figma-api/connector.test.ts b/packages/core/tests/figma-api/connector.test.tsindex 60fa021bb..6d3292d60 100644--- a/packages/core/tests/figma-api/connector.test.ts+++ b/packages/core/tests/figma-api/connector.test.ts@@ -77,6 +77,19 @@ describe('ConnectorNode', () => {expect(connector.x).toBe(206)})+ test('an end FigJam pinned to a point of a section reports the magnet as EDGE', () => {+ const { graph, api, a } = setup()+ const connector = api.createConnector()+ const section = api.createSection()+ graph.updateNode(connector.id, {+ connectorEnd: { nodeId: section.id, magnet: 'ABSOLUTE', position: { x: 40, y: 258 } }+ })+ connector.connectorStart = { endpointNodeId: a.id, magnet: 'AUTO' }+ // Figma's plugin typings leave `EDGE` out, though Figma reports it.+ const end: unknown = connector.connectorEnd+ expect(end).toEqual({ endpointNodeId: section.id, magnet: 'EDGE' })+ })+test('a straight connector attaches by centres and refuses side magnets', () => {const { api, a } = setup()const connector = api.createConnector()diff --git a/packages/scene-graph/src/connectors/layout.ts b/packages/scene-graph/src/connectors/layout.tsindex cca674d9a..c01c53b5d 100644--- a/packages/scene-graph/src/connectors/layout.ts+++ b/packages/scene-graph/src/connectors/layout.ts@@ -14,7 +14,8 @@ import { connectorRouteEnds, connectorSublayers, type ConnectorSublayers } from/*** An end as the router sees it, in the connector's parent's axes: the box of the layer it follows- * by a magnet, or a point. An end whose layer is gone stays where its route last ended.+ * by a magnet, or a point, which an end pinned to a point of its layer follows as the layer moves.+ * An end whose layer is gone stays where its route last ended.*/function routeEnd(graph: SceneGraph,@@ -31,7 +32,7 @@ function routeEnd(const point = endpoint.nodeId && fallback ? fallback : endpoint.positionreturn { box: null, point, magnet: 'NONE', cap, outline: 0 }}- if (endpoint.magnet === 'NONE') {+ if (endpoint.magnet === 'NONE' || endpoint.magnet === 'ABSOLUTE') {// 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()@@ -39,7 +40,7 @@ function routeEnd(endpoint.position.x,endpoint.position.y])- return { box: null, point: { x, y }, magnet: 'NONE', cap, outline: 0 }+ return { box: null, point: { x, y }, magnet: endpoint.magnet, cap, outline: 0 }}return {box: getAxisAlignedBoundsInParent([node], parentId, graph),diff --git a/packages/scene-graph/src/connectors/route.ts b/packages/scene-graph/src/connectors/route.tsindex e1402f574..90990423a 100644--- a/packages/scene-graph/src/connectors/route.ts+++ b/packages/scene-graph/src/connectors/route.ts@@ -91,8 +91,17 @@ function curvedRoute(}/**- * The pieces of a connector's line between its two ends, in the connector's parent's axes. Bound- * ends stop short of their layers by their caps' gaps; free ends sit on their points. Layers that+ * Whether an end stops short of where it attaches by its cap's gap: every end attached by a+ * magnet does, including one FigJam pins to a point of a section (`ABSOLUTE`); a free end, or a+ * point a script sets (`NONE`), is reached exactly.+ */+function gapped(end: ConnectorRouteEnd): boolean {+ return end.magnet !== 'NONE'+}++/**+ * The pieces of a connector's line between its two ends, in the connector's parent's axes. Ends+ * attached by a magnet stop short by their caps' gaps; free ends sit on their points. Layers that* touch or overlap leave an elbow or a curve nothing to route but the start, as in Figma.*/export function routeConnector(@@ -102,8 +111,8 @@ export function routeConnector(strokeWeight: number): ConnectorPiece[] {const gaps: [number, number] = [- start.box ? connectorEndGap(start, strokeWeight, 'start') : 0,- end.box ? connectorEndGap(end, strokeWeight, 'end') : 0+ gapped(start) ? connectorEndGap(start, strokeWeight, 'start') : 0,+ gapped(end) ? connectorEndGap(end, strokeWeight, 'end') : 0]if (lineType === 'STRAIGHT') return straightRoute(start, end, gaps)const [startSide, endSide] = connectorSides(start, end)diff --git a/packages/scene-graph/src/connectors/sides.ts b/packages/scene-graph/src/connectors/sides.tsindex 446232ef0..7d10dab50 100644--- a/packages/scene-graph/src/connectors/sides.ts+++ b/packages/scene-graph/src/connectors/sides.ts@@ -15,9 +15,9 @@ export const OUTWARD: Record<ConnectorSide, Vector> = {/** One end of a connector as the router sees it: the box it follows, or a free point. */export interface ConnectorRouteEnd {- /** The bound layer's box in the connector's parent's axes; null for a free end. */+ /** The bound layer's box in the connector's parent's axes; null for an end at a point. */box: Rect | null- /** Where a free end sits, in the connector's parent's axes. */+ /** Where an end at a point sits, in the connector's parent's axes. */point: Vectormagnet: ConnectorMagnetcap: StrokeCap@@ -39,8 +39,8 @@ export function sidesFor(magnet: ConnectorMagnet): readonly ConnectorSide[] {if (magnet === 'TOP' || magnet === 'RIGHT' || magnet === 'BOTTOM' || magnet === 'LEFT') {return [magnet]}- // Figma keeps `EDGE` and `ABSOLUTE` ends at a point of the layer; until those are drawn they- // leave by the nearest side.+ // No file seen so far uses `EDGE`; until one shows what it means, its ends leave by the nearest+ // side.return SIDES}diff --git a/packages/scene-graph/tests/connectors/route.test.ts b/packages/scene-graph/tests/connectors/route.test.tsindex d31853709..cdeb89e4d 100644--- a/packages/scene-graph/tests/connectors/route.test.ts+++ b/packages/scene-graph/tests/connectors/route.test.ts@@ -158,3 +158,37 @@ test('a label on a line with no length keeps the line its one point', () => {expect(placed?.pieces).toEqual(pieces)expect(placed?.plate).toEqual({ x: 30, y: -10, width: 40, height: 20 })})++/**+ * Ends FigJam pinned to a point of a 400 × 320 section at (480, -100), dropped there from a+ * connector leaving a 160 px shape at the origin, a 96 px one below the section, and one to its+ * right; measured on 2026-10-19 from the connectors' boxes.+ */+describe('an end pinned to a point of a section', () => {+ const pinned = (x: number, y: number, magnet: 'ABSOLUTE' | 'NONE'): ConnectorRouteEnd => ({+ box: null,+ point: { x, y },+ magnet,+ cap: 'ARROW_LINES',+ outline: 0+ })+ const from = (x: number, y: number, size: number): ConnectorRouteEnd => ({+ box: { x, y, width: size, height: size },+ point: { x: 0, y: 0 },+ magnet: 'AUTO',+ cap: 'ROUND',+ outline: 0+ })+ const last = (start: ConnectorRouteEnd, end: ConnectorRouteEnd) =>+ routeConnector('ELBOWED', start, end, 4).at(-1)?.to++ test('is reached along the longer axis and stops short by its cap', () => {+ expect(last(from(0, 0, 160), pinned(520, 158, 'ABSOLUTE'))).toEqual({ x: 513.5, y: 158 })+ expect(last(from(632, 364, 96), pinned(560, 158, 'ABSOLUTE'))).toEqual({ x: 560, y: 164.5 })+ expect(last(from(1040, 12, 96), pinned(560, 158, 'ABSOLUTE'))).toEqual({ x: 566.5, y: 158 })+ })++ test('set by a script, is reached exactly', () => {+ expect(last(from(0, 0, 160), pinned(520, 158, 'NONE'))).toEqual({ x: 520, y: 158 })+ })+})diff --git a/tests/e2e/canvas/connectors-visual.spec.ts b/tests/e2e/canvas/connectors-visual.spec.tsindex ed2f0e329..0d483ad03 100644--- a/tests/e2e/canvas/connectors-visual.spec.ts+++ b/tests/e2e/canvas/connectors-visual.spec.ts@@ -39,3 +39,15 @@ test('connectors draw their filled caps, the end handles of a selected one, and'connector-caps-and-handles.png')})++test('connector ends pinned to points of a section stop short of them, reached along the longer axis', async () => {+ await connectors.showPinnedEnds()+ await editor.canvas.waitForRender()+ editor.canvas.assertNoErrors()+ expect((await connectors.connectors()).map((connector) => connector.end?.magnet)).toEqual([+ 'ABSOLUTE',+ 'ABSOLUTE',+ 'ABSOLUTE'+ ])+ expect(await editor.canvas.screenshotCanvasRegion()).toMatchSnapshot('connector-pinned-ends.png')+})diff --git a/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/connector-pinned-ends-openpencil-darwin.png b/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/connector-pinned-ends-openpencil-darwin.pngnew file mode 100644index 000000000..beddd9ab0Binary files /dev/null and b/tests/e2e/canvas/connectors-visual.spec.ts-snapshots/connector-pinned-ends-openpencil-darwin.png differdiff --git a/tests/helpers/canvas/connector-driver.ts b/tests/helpers/canvas/connector-driver.tsindex 9e0966752..26ead4669 100644--- a/tests/helpers/canvas/connector-driver.ts+++ b/tests/helpers/canvas/connector-driver.ts@@ -158,6 +158,44 @@ export function connectorDriver(page: () => Page) {})},+ /**+ * Setup: a section with connectors drawn into it from boxes left of it, below it, and right+ * of it, dropped away from its outline and centre so each end is pinned where it was dropped.+ */+ showPinnedEnds() {+ return page().evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const page = store.state.currentPageId+ const fills = [+ {+ type: 'SOLID' as const,+ color: { r: 0.85, g: 0.88, b: 0.95, a: 1 },+ opacity: 1,+ visible: true+ }+ ]+ store.graph.createNode('SECTION', page, { x: 400, y: 40, width: 360, height: 320, fills })+ const sources = [+ { box: { x: 20, y: 140, width: 160, height: 160 }, drop: { x: 440, y: 298 } },+ { box: { x: 552, y: 504, width: 96, height: 96 }, drop: { x: 480, y: 298 } },+ { box: { x: 790, y: 152, width: 96, height: 96 }, drop: { x: 480, y: 120 } }+ ]+ store.setTool('CONNECTOR')+ for (const { box, drop } of sources) {+ store.graph.createNode('RECTANGLE', page, { ...box, fills })+ store.connectorBegin(box.x + box.width / 2, box.y + box.height / 2)+ store.connectorRelease(drop.x, drop.y, true)+ }+ store.setTool('SELECT')+ store.clearSelection()+ 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) => {