AI-native design editor. Open-source Figma alternative.
feat: arrange layers with ELK layouts: spread, pack, flow, tree, radial (#1553)
Danila Poyarkov93ab5f81b68d
diff --git a/changes/1553/added.md b/changes/1553/added.mdnew file mode 100644index 000000000..a39555b39--- /dev/null+++ b/changes/1553/added.md@@ -0,0 +1 @@+- AI and MCP agents tidy layers with more `arrange` modes: `spread` pushes overlapping layers apart and keeps each near where it was, `compact` also closes the gaps, `pack` packs screens into rows, and `flow`, `tree`, `radial`, and `network` lay shapes out along the connectors joining them, rerouting the connectors.diff --git a/changes/1553/changed.md b/changes/1553/changed.mdnew file mode 100644index 000000000..3c0bd9af4--- /dev/null+++ b/changes/1553/changed.md@@ -0,0 +1 @@+- `arrange` spreads overlapping layers apart by default instead of placing them in a grid; pass `mode: "grid"` for the grid.diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.mdindex b16e25a11..c130c50bc 100644--- a/packages/core/AGENTS.md+++ b/packages/core/AGENTS.md@@ -17,7 +17,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do- `@open-pencil/yoga-layout` supplies both flexbox and CSS Grid.- Recompute layout after demo creation and for each materialized or imported page; scope computation to the affected page or subtree where possible.- The first Hug/Fill dimension mutation switches only that axis to Fixed; focus is non-destructive, and mode/value changes share one undo transaction.-- Diagrams of nodes, groups, and edges lay out in `packages/core/src/layout/diagram/`: `layoutDiagram` runs ELK, loaded on first use, and `applyDiagramLayout` moves the layers that draw it and runs their connectors along its routes; importers and tools that arrange diagrams go through them, and connectors that pass through stored bend points use `bendConnectorThrough` (`packages/core/tests/layout/diagram/apply.test.ts`).+- Arranging layers runs through `packages/core/src/layout/arrange/`: `arrangeBoxes` runs an ELK layout (spread, compact, pack, flow, tree, radial, network), loaded on first use, `applyArrangement` moves the layers that draw it and joins their connectors, routing them when they flow, and `arrangeLayers` does both for layers already on a page, finding the connectors between them; importers and tools that arrange layers go through them, and connectors that pass through stored bend points use `bendConnectorThrough` (`packages/core/tests/layout/arrange/layers.test.ts`).- A shape with text fits itself to its label before its auto layout runs: it grows from its given size only while the label needs room, and layout never changes that given size (`packages/core/tests/layout/generated/shape-with-text.test.ts`).## Components and instancesdiff --git a/packages/core/src/io/formats/drawio/edges.ts b/packages/core/src/io/formats/drawio/edges.tsindex 586d43dbe..33cfda3c3 100644--- a/packages/core/src/io/formats/drawio/edges.ts+++ b/packages/core/src/io/formats/drawio/edges.ts@@ -18,7 +18,7 @@ import {import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'import type { Vector } from '@open-pencil/scene-graph/primitives'-import { bendConnectorThrough } from '#core/layout/diagram/routes'+import { bendConnectorThrough } from '#core/layout/arrange/routes'import { readLabel } from './label'import { dashOf, labelFields, labelFormat, lineColor } from './paint'diff --git a/packages/core/src/io/formats/mermaid/layers.ts b/packages/core/src/io/formats/mermaid/layers.tsindex d7fa5102c..a3a31d4e9 100644--- a/packages/core/src/io/formats/mermaid/layers.ts+++ b/packages/core/src/io/formats/mermaid/layers.ts@@ -18,9 +18,9 @@ import type { Color } from '@open-pencil/scene-graph/primitives'import { newLayerDefaults } from '#core/editor/shapes/defaults'import { layoutAuthoredNodes } from '#core/layout'-import { layoutDiagram, type DiagramInput } from '#core/layout/diagram'-import { applyDiagramLayout, type DiagramPlacement } from '#core/layout/diagram/apply'-import { connectorLabelSize } from '#core/layout/diagram/routes'+import { applyArrangement, type ArrangePlacement } from '#core/layout/arrange/apply'+import { arrangeBoxes, type ArrangeInput } from '#core/layout/arrange/boxes'+import { connectorLabelSize } from '#core/layout/arrange/routes'import { shapeWithTextWidthFor } from '#core/layout/shape-with-text'import { prepareGraphFonts } from '#core/text/prepare'@@ -236,7 +236,7 @@ export async function addFlowchart(graph: SceneGraph,parentId: string,chart: Flowchart,- placement: DiagramPlacement = { topLeft: { x: 0, y: 0 } }+ placement: ArrangePlacement = { topLeft: { x: 0, y: 0 } }): Promise<FlowchartLayers> {const before = new Set(graph.getNode(parentId)?.childIds)const builder = new FlowchartBuilder(graph, parentId, chart)@@ -264,9 +264,10 @@ export async function addFlowchart(const connectorId = builder.connectors.get(edgeId)return (connectorId && connectorLabelSize(graph, connectorId)) || undefined}- const input: DiagramInput = {+ const input: ArrangeInput = {+ layout: 'flow',direction: chart.direction,- nodes: chart.nodes.map((node) => ({+ boxes: chart.nodes.map((node) => ({id: node.id,...size(node.id),group: enclosing.get(node.id)@@ -282,11 +283,11 @@ export async function addFlowchart(label: labelSize(edge.id)}))}- const layout = await layoutDiagram(input)- applyDiagramLayout(+ const arrangement = await arrangeBoxes(input)+ applyArrangement(graph,input,- layout,+ arrangement,{ boxes: builder.layers, connectors: builder.connectors },placement)diff --git a/packages/core/src/layout/arrange/apply.ts b/packages/core/src/layout/arrange/apply.tsnew file mode 100644index 000000000..88d057783--- /dev/null+++ b/packages/core/src/layout/arrange/apply.ts@@ -0,0 +1,127 @@+import type { SceneGraph } from '@open-pencil/scene-graph'+import { boundEndpoint, layoutConnector } from '@open-pencil/scene-graph/connectors'+import { getParentWorldMatrix } from '@open-pencil/scene-graph/coordinate'+import Matrix from '@open-pencil/scene-graph/matrix'+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'++import type { ArrangeInput, ArrangedRoute, Arrangement } from './boxes'+import { runConnectorAlong } from './routes'++/** The layers that draw an arrangement's boxes and edges, by their ids. */+export interface ArrangedLayers {+ /** The layer drawing each box and group. */+ boxes: Map<string, string>+ /** The connector drawing each edge; an edge drawn by none only shapes the arrangement. */+ connectors: Map<string, string>+}++/** Where an arrangement goes in its parent: by its top-left corner or by its centre. */+export type ArrangePlacement = { topLeft: Vector } | { center: Vector }++function bounds(boxes: Rect[]): Rect {+ const x = Math.min(...boxes.map((box) => box.x))+ const y = Math.min(...boxes.map((box) => box.y))+ return {+ x,+ y,+ width: Math.max(...boxes.map((box) => box.x + box.width)) - x,+ height: Math.max(...boxes.map((box) => box.y + box.height)) - y+ }+}++/**+ * Joins a connector to the layers at its edge's ends by the sides the route takes: an elbow runs+ * along the route, which `place` carries into the connector's parent's axes, a curve bends between those sides,+ * and a straight line keeps its ends.+ */+function joinConnector(+ graph: SceneGraph,+ connectorId: string,+ [start, end]: [string, string],+ route: ArrangedRoute | undefined,+ place: (point: Vector) => Vector+): void {+ const connector = graph.getNode(connectorId)+ if (!connector) return+ if (connector.connectorLineType === 'STRAIGHT') {+ layoutConnector(graph, connector)+ return+ }+ graph.updateNode(connectorId, {+ connectorStart: boundEndpoint(start, route?.startSide ?? 'AUTO'),+ connectorEnd: boundEndpoint(end, route?.endSide ?? 'AUTO'),+ connectorCurveHandles: null,+ connectorControlPoints: []+ })+ if (connector.connectorLineType === 'CURVED') {+ const curve = graph.getNode(connectorId)+ if (curve) layoutConnector(graph, curve)+ return+ }+ runConnectorAlong(graph, connectorId, (route?.points ?? []).map(place))+}++/**+ * Puts the layers that draw an arrangement where it placed them, the whole at `placement` in its+ * parent: each box's layer at its box and each group's at its box and size, in the axes of the group+ * holding it, if any. Each edge's connector is joined to the layers at its ends by the sides the+ * arrangement chose: an elbow runs along the route a flow gave, a curve bends between those sides, and a+ * straight line keeps its ends.+ */+export function applyArrangement(+ graph: SceneGraph,+ input: ArrangeInput,+ arrangement: Arrangement,+ layers: ArrangedLayers,+ placement: ArrangePlacement+): void {+ const boxes = new Map<string, Rect>([...arrangement.groups, ...arrangement.boxes])+ if (boxes.size === 0) return+ const drawing = bounds([...boxes.values()])+ const origin =+ 'center' in placement+ ? {+ x: placement.center.x - drawing.width / 2,+ y: placement.center.y - drawing.height / 2+ }+ : placement.topLeft+ const shift = { x: origin.x - drawing.x, y: origin.y - drawing.y }+ const groupOf = new Map(+ [...input.boxes, ...input.groups].map((member) => [member.id, member.group])+ )+ // The layer the arrangement's top-level layers share.+ const topLayer = [...layers.boxes].find(([id]) => groupOf.get(id) === undefined)?.[1]+ const parentId = topLayer ? graph.getNode(topLayer)?.parentId : null+ const parent = parentId ? graph.getNode(parentId) : undefined+ for (const [id, layerId] of layers.boxes) {+ const box = boxes.get(id)+ if (!box) continue+ const group = groupOf.get(id)+ const outer = group ? boxes.get(group) : undefined+ const position = outer+ ? { x: box.x - outer.x, y: box.y - outer.y }+ : { x: box.x + shift.x, y: box.y + shift.y }+ // A group's layer takes the size the arrangement gave it; a box's keeps its own.+ if (arrangement.groups.has(id)) {+ graph.updateNode(layerId, { ...position, width: box.width, height: box.height })+ } else {+ graph.updateNode(layerId, position)+ }+ }+ for (const edge of input.edges) {+ const connectorId = layers.connectors.get(edge.id)+ const start = layers.boxes.get(edge.from)+ const end = layers.boxes.get(edge.to)+ if (!connectorId || !start || !end) continue+ // The route is in the arrangement's parent's axes; the connector may live in another layer.+ const connector = graph.getNode(connectorId)+ const into = Matrix.multiply(+ Matrix.invert(getParentWorldMatrix(graph.getNode(connector?.parentId ?? ''), graph)) ??+ Matrix.identity(),+ getParentWorldMatrix(parent, graph)+ )+ const place = (point: Vector) =>+ Matrix.mapPoint(into, { x: point.x + shift.x, y: point.y + shift.y })+ joinConnector(graph, connectorId, [start, end], arrangement.edges.get(edge.id), place)+ }+}diff --git a/packages/core/src/layout/arrange/boxes.ts b/packages/core/src/layout/arrange/boxes.tsnew file mode 100644index 000000000..223b4b2d2--- /dev/null+++ b/packages/core/src/layout/arrange/boxes.ts@@ -0,0 +1,363 @@+import type { ElkExtendedEdge, ElkNode, ElkPort } from 'elkjs/lib/elk-api'++import type { ConnectorSide } from '@open-pencil/scene-graph/connectors'+import type { Rect, Size, Vector } from '@open-pencil/scene-graph/primitives'++import { layoutWithElk } from './elk'++/**+ * How boxes are arranged, by the ELK algorithm behind each:+ * - `spread` pushes overlapping boxes apart, keeping them near where they were (SPOrE overlap+ * removal);+ * - `compact` spreads them and then closes the gaps, keeping their relative places (SPOrE+ * compaction);+ * - `pack` packs them into rows in their order (rectangle packing);+ * - `flow` ranks them along their edges with right-angled routes (layered);+ * - `tree` lays a tree out from its roots (Mr. Tree);+ * - `radial` lays a tree out in rings around its root (radial);+ * - `network` places joined boxes near each other, with no direction (stress).+ */+export type BoxLayout = 'spread' | 'compact' | 'pack' | 'flow' | 'tree' | 'radial' | 'network'++/** The way a flow or a tree runs: top to bottom, bottom to top, left to right, or right to left. */+export type ArrangeDirection = 'TB' | 'BT' | 'LR' | 'RL'++/** A box or group, at the top or inside the group it names. */+export interface ArrangeMember {+ id: string+ group?: string+ /** Where it is now, in the arrangement's axes, which `spread` and `compact` start from. */+ position?: Vector+}++export interface ArrangeBox extends ArrangeMember, Size {}++/** A box around boxes and other groups, sized to hold them. */+export type ArrangeGroup = ArrangeMember++/** An edge between two boxes or groups; its label, by size, gets room along it in a flow. */+export interface ArrangeEdge {+ id: string+ from: string+ to: string+ label?: Size+}++export interface ArrangeInput {+ layout: BoxLayout+ /** For `flow` and `tree`; top to bottom unless given. */+ direction?: ArrangeDirection+ /** Room between boxes; ranks of a flow get half as much again. */+ spacing?: number+ boxes: ArrangeBox[]+ groups: ArrangeGroup[]+ edges: ArrangeEdge[]+}++/** The way a flow's edge runs: the sides it leaves and enters by, and its corners between them. */+export interface ArrangedRoute {+ startSide: ConnectorSide+ endSide: ConnectorSide+ /**+ * From its start, on the middle of `startSide`, to its end, on the middle of `endSide`; empty+ * when only the sides are given.+ */+ points: Vector[]+}++/**+ * Where everything went, in the arrangement's axes. A flow routes its edges, a tree gives only the+ * sides they leave and enter by, and other layouts leave edges to the connectors.+ */+export interface Arrangement {+ boxes: Map<string, Rect>+ groups: Map<string, Rect>+ edges: Map<string, ArrangedRoute>+}++const SPACING = 40+/** Room inside a group around what it holds, and above it for the group's title. */+const GROUP_PADDING = 24+const GROUP_TITLE = 48++const ALGORITHMS: Record<BoxLayout, string> = {+ spread: 'sporeOverlap',+ compact: 'sporeCompaction',+ pack: 'rectpacking',+ flow: 'layered',+ tree: 'mrtree',+ radial: 'radial',+ network: 'stress'+}++const ELK_DIRECTION: Record<ArrangeDirection, string> = {+ TB: 'DOWN',+ BT: 'UP',+ LR: 'RIGHT',+ RL: 'LEFT'+}++/** The side a flow's edges leave a box by, and the side they enter one by. */+const FLOW_SIDES: Record<ArrangeDirection, [ConnectorSide, ConnectorSide]> = {+ TB: ['BOTTOM', 'TOP'],+ BT: ['TOP', 'BOTTOM'],+ LR: ['RIGHT', 'LEFT'],+ RL: ['LEFT', 'RIGHT']+}++const ELK_SIDE: Record<ConnectorSide, string> = {+ TOP: 'NORTH',+ RIGHT: 'EAST',+ BOTTOM: 'SOUTH',+ LEFT: 'WEST'+}++function portId(boxId: string, side: ConnectorSide): string {+ return `${boxId}\u0000${side}`+}++/**+ * A port on the middle of each side a box's edges use, fixed there: connectors attach to side+ * midpoints, so ELK routes every edge to where its connector will meet the box.+ */+function ports(boxId: string, size: Size, sides: ConnectorSide[]): ElkPort[] {+ const at: Record<ConnectorSide, Vector> = {+ TOP: { x: size.width / 2, y: 0 },+ RIGHT: { x: size.width, y: size.height / 2 },+ BOTTOM: { x: size.width / 2, y: size.height },+ LEFT: { x: 0, y: size.height / 2 }+ }+ return sides.map((side) => ({+ id: portId(boxId, side),+ ...at[side],+ width: 0,+ height: 0,+ layoutOptions: { 'elk.port.side': ELK_SIDE[side] }+ }))+}++/** Each box's place in the input: a box's own, a group's that of its first member. */+function inputOrder(input: ArrangeInput): Map<string, number> {+ const order = new Map<string, number>()+ const groupOf = new Map(input.groups.map((group) => [group.id, group.group]))+ for (const [index, box] of input.boxes.entries()) {+ order.set(box.id, index)+ for (let group = box.group; group !== undefined; group = groupOf.get(group)) {+ if (!order.has(group)) order.set(group, index)+ }+ }+ return order+}++/** The layout options of the root and of each group, for the input's layout. */+function layoutOptions(input: ArrangeInput): Record<string, string> {+ const spacing = input.spacing ?? SPACING+ const direction = ELK_DIRECTION[input.direction ?? 'TB']+ const common = {+ 'elk.algorithm': ALGORITHMS[input.layout],+ 'elk.spacing.nodeNode': String(spacing),+ 'elk.spacing.componentComponent': String(spacing),+ 'elk.padding': `[top=${GROUP_TITLE},left=${GROUP_PADDING},bottom=${GROUP_PADDING},right=${GROUP_PADDING}]`+ }+ switch (input.layout) {+ case 'flow':+ return {+ ...common,+ 'elk.direction': direction,+ 'elk.hierarchyHandling': 'INCLUDE_CHILDREN',+ 'elk.edgeRouting': 'ORTHOGONAL',+ 'elk.layered.spacing.nodeNodeBetweenLayers': String(spacing * 1.5),+ 'elk.spacing.edgeNode': '20',+ 'elk.spacing.edgeEdge': '12',+ 'elk.layered.spacing.edgeNodeBetweenLayers': '20',+ // Flowcharts read from their first node: break cycles along the order they were written+ // in, rather than where ELK's greedy pass would, which can put the start mid-drawing.+ 'elk.layered.cycleBreaking.strategy': 'DEPTH_FIRST',+ 'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',+ 'elk.edgeLabels.placement': 'CENTER'+ }+ case 'tree':+ return {+ ...common,+ 'elk.direction': direction,+ 'elk.mrtree.spacing.nodeNode': String(spacing)+ }+ case 'network':+ return { ...common, 'elk.stress.desiredEdgeLength': String(spacing * 4) }+ default:+ return common+ }+}++function elkGraph(input: ArrangeInput): ElkNode {+ const flow = input.layout === 'flow'+ const [outSide, inSide] = FLOW_SIDES[input.direction ?? 'TB']+ const options = layoutOptions(input)+ const elk = new Map<string, ElkNode>()+ for (const group of input.groups) {+ elk.set(group.id, {+ id: group.id,+ ...group.position,+ children: [],+ edges: [],+ layoutOptions: flow ? { ...options, 'elk.portConstraints': 'FIXED_SIDE' } : options,+ ports: flow+ ? [+ {+ id: portId(group.id, outSide),+ layoutOptions: { 'elk.port.side': ELK_SIDE[outSide] }+ },+ { id: portId(group.id, inSide), layoutOptions: { 'elk.port.side': ELK_SIDE[inSide] } }+ ]+ : []+ })+ }+ for (const box of input.boxes) {+ elk.set(box.id, {+ id: box.id,+ ...box.position,+ width: box.width,+ height: box.height,+ layoutOptions: flow ? { 'elk.portConstraints': 'FIXED_POS' } : {},+ ports: flow ? ports(box.id, box, [outSide, inSide]) : []+ })+ }+ const root: ElkNode = {+ id: '\u0000root',+ layoutOptions: { ...options, 'elk.json.shapeCoords': 'ROOT', 'elk.json.edgeCoords': 'ROOT' },+ children: [],+ edges: []+ }+ const groupOf = new Map(+ [...input.groups, ...input.boxes].map((member) => [member.id, member.group])+ )+ const container = (group: string | undefined) => (group ? elk.get(group) : undefined) ?? root+ // ELK keeps the order it is given, so boxes go in the input's order: a box where it appears, a+ // group where its first member does.+ const order = inputOrder(input)+ const members = [...input.groups, ...input.boxes].sort(+ (a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0)+ )+ for (const member of members) {+ const node = elk.get(member.id)+ if (node) container(member.group).children?.push(node)+ }+ for (const edge of input.edges) {+ if (!elk.has(edge.from) || !elk.has(edge.to)) continue+ if (flow) {+ root.edges?.push({+ id: edge.id,+ sources: [portId(edge.from, outSide)],+ targets: [portId(edge.to, inSide)],+ // ELK skips a label without text; only its size matters here.+ labels: edge.label ? [{ text: edge.id, ...edge.label }] : []+ })+ continue+ }+ // Other layouts arrange each group on its own, so an edge counts only between boxes that+ // share one.+ const group = groupOf.get(edge.from)+ if (group !== groupOf.get(edge.to)) continue+ container(group).edges?.push({ id: edge.id, sources: [edge.from], targets: [edge.to] })+ }+ return root+}++function sideOf(point: Vector, box: Rect): ConnectorSide {+ const distances: [ConnectorSide, number][] = [+ ['TOP', Math.abs(point.y - box.y)],+ ['RIGHT', Math.abs(point.x - (box.x + box.width))],+ ['BOTTOM', Math.abs(point.y - (box.y + box.height))],+ ['LEFT', Math.abs(point.x - box.x)]+ ]+ return distances.reduce((best, entry) => (entry[1] < best[1] ? entry : best))[0]+}++function rectOf(node: ElkNode): Rect {+ return { x: node.x ?? 0, y: node.y ?? 0, width: node.width ?? 0, height: node.height ?? 0 }+}++function collect(result: ElkNode, input: ArrangeInput): Arrangement {+ const groupIds = new Set(input.groups.map((group) => group.id))+ const arrangement: Arrangement = { boxes: new Map(), groups: new Map(), edges: new Map() }+ const walk = (node: ElkNode) => {+ for (const child of node.children ?? []) {+ ;(groupIds.has(child.id) ? arrangement.groups : arrangement.boxes).set(+ child.id,+ rectOf(child)+ )+ walk(child)+ }+ }+ walk(result)+ if (input.layout === 'tree') {+ // A tree runs one way, so its edges leave and enter boxes by the sides a flow would, with+ // the connectors' own elbows between them.+ const [startSide, endSide] = FLOW_SIDES[input.direction ?? 'TB']+ for (const edge of input.edges) {+ if (arrangement.boxes.has(edge.from) && arrangement.boxes.has(edge.to)) {+ arrangement.edges.set(edge.id, { startSide, endSide, points: [] })+ }+ }+ return arrangement+ }+ if (input.layout !== 'flow') return arrangement+ const ends = new Map(input.edges.map((edge) => [edge.id, edge]))+ const placed = new Map([...arrangement.groups, ...arrangement.boxes])+ // ELK may hand an edge back in the group that holds both its ends.+ const edgesOf = (node: ElkNode): ElkExtendedEdge[] => [+ ...(node.edges ?? []),+ ...(node.children ?? []).flatMap(edgesOf)+ ]+ for (const edge of edgesOf(result)) {+ const ended = ends.get(edge.id)+ const from = ended && placed.get(ended.from)+ const to = ended && placed.get(ended.to)+ const points = (edge.sections ?? []).flatMap((section) => [+ section.startPoint,+ ...(section.bendPoints ?? []),+ section.endPoint+ ])+ const first = points.at(0)+ const last = points.at(-1)+ if (!from || !to || !first || !last) continue+ arrangement.edges.set(edge.id, {+ startSide: sideOf(first, from),+ endSide: sideOf(last, to),+ points: points.map(({ x, y }) => ({ x, y }))+ })+ }+ return arrangement+}++/** The input again, each box and group where `result` put it, for a second pass to start from. */+function placedAt(input: ArrangeInput, result: ElkNode): ArrangeInput {+ const positions = new Map<string, Vector>()+ const walk = (node: ElkNode) => {+ for (const child of node.children ?? []) {+ positions.set(child.id, { x: child.x ?? 0, y: child.y ?? 0 })+ walk(child)+ }+ }+ walk(result)+ const at = <Member extends ArrangeMember>(member: Member): Member => ({+ ...member,+ position: positions.get(member.id) ?? member.position+ })+ return { ...input, boxes: input.boxes.map(at), groups: input.groups.map(at) }+}++/**+ * Arranges boxes with ELK in the input's layout: groups around their members, and, in a flow,+ * every edge routed at right angles from the middle of the side it leaves by to the middle of the+ * side it enters by.+ */+export async function arrangeBoxes(input: ArrangeInput): Promise<Arrangement> {+ if (input.layout === 'compact') {+ // Compaction keeps boxes apart only once they are: spread them first.+ const spread = await layoutWithElk(elkGraph({ ...input, layout: 'spread' }))+ const compacted = placedAt(input, spread)+ return collect(await layoutWithElk(elkGraph(compacted)), compacted)+ }+ return collect(await layoutWithElk(elkGraph(input)), input)+}diff --git a/packages/core/src/layout/diagram/elk.ts b/packages/core/src/layout/arrange/elk.tssimilarity index 100%rename from packages/core/src/layout/diagram/elk.tsrename to packages/core/src/layout/arrange/elk.tsdiff --git a/packages/core/src/layout/arrange/layers.ts b/packages/core/src/layout/arrange/layers.tsnew file mode 100644index 000000000..b171b55bb--- /dev/null+++ b/packages/core/src/layout/arrange/layers.ts@@ -0,0 +1,266 @@+import { uniq } from 'es-toolkit'++import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { connectorsAffectedBy, layoutConnector } from '@open-pencil/scene-graph/connectors'+import type { Vector } from '@open-pencil/scene-graph/primitives'++import { applyArrangement } from './apply'+import {+ arrangeBoxes,+ type ArrangeDirection,+ type ArrangeEdge,+ type ArrangeInput,+ type BoxLayout+} from './boxes'+import { connectorLabelSize } from './routes'++/**+ * How layers are arranged: an ELK layout (see `BoxLayout`), or in a grid, a row, or a column in+ * the order given, starting where the first layer is.+ */+export type LayerLayout = BoxLayout | 'grid' | 'row' | 'column'++export interface ArrangeLayersOptions {+ layout: LayerLayout+ /** For `flow` and `tree`. */+ direction?: ArrangeDirection+ /** Room between layers. */+ spacing?: number+ /** Columns of a grid; as many as make it square unless given. */+ columns?: number+}++/** What an arrangement moved. */+export interface LayerArrangement {+ /** Layers placed as boxes. */+ layers: number+ /** Sections laid out around what they hold. */+ groups: number+ /** Connectors routed or joined anew. */+ connectors: number+}++const SPACING = 40++/**+ * A chosen section lays out around its children when all of them were chosen too; a section+ * holding anything else moves as one box, so what was not chosen stays as it was.+ */+function groupsAmong(graph: SceneGraph, chosen: Set<string>): Set<string> {+ const groups = new Set<string>()+ for (const id of chosen) {+ const node = graph.getNode(id)+ if (node?.type !== 'SECTION') continue+ const children = graph.getChildren(id).filter((child) => child.type !== 'CONNECTOR')+ if (children.length > 0 && children.every((child) => chosen.has(child.id))) groups.add(id)+ }+ return groups+}++/**+ * Whether a chosen layer sits inside another chosen layer that moves as one box, rather than one+ * laid out around its children, and so moves with it.+ */+function movesWithAncestor(+ graph: SceneGraph,+ node: SceneNode,+ given: SceneNode[],+ groups: Set<string>+): boolean {+ const ids = new Set(given.map((candidate) => candidate.id))+ for (+ let ancestor = node.parentId ? graph.getNode(node.parentId) : undefined;+ ancestor;+ ancestor = ancestor.parentId ? graph.getNode(ancestor.parentId) : undefined+ ) {+ if (ids.has(ancestor.id) && !groups.has(ancestor.id)) return true+ }+ return false+}++/** The chosen layer a connector end joins: the layer itself, or the nearest chosen ancestor. */+function chosenOwner(graph: SceneGraph, nodeId: string, chosen: Set<string>): string | null {+ for (+ let node = graph.getNode(nodeId);+ node;+ node = node.parentId ? graph.getNode(node.parentId) : undefined+ ) {+ if (chosen.has(node.id)) return node.id+ }+ return null+}++/** Lays layers out in a grid, a row, or a column, in their order, from where the first is. */+function line(nodes: SceneNode[], graph: SceneGraph, options: ArrangeLayersOptions): void {+ const spacing = options.spacing ?? SPACING+ const first = nodes.at(0)+ if (!first) return+ let columns = options.columns ?? Math.ceil(Math.sqrt(nodes.length))+ if (options.layout === 'row') columns = nodes.length+ if (options.layout === 'column') columns = 1+ let x = first.x+ let y = first.y+ let rowHeight = 0+ for (const [index, node] of nodes.entries()) {+ if (index > 0 && index % columns === 0) {+ x = first.x+ y += rowHeight + spacing+ rowHeight = 0+ }+ graph.updateNode(node.id, { x, y })+ x += node.width + spacing+ rowHeight = Math.max(rowHeight, node.height)+ }+}++/** The connectors between chosen layers, as edges, and those joined to the layers themselves. */+function connectorEdges(graph: SceneGraph, pageId: string, chosen: Set<string>) {+ const edges: ArrangeEdge[] = []+ const joined = new Map<string, string>()+ for (const { node } of graph.flattenTree(pageId)) {+ if (node.type !== 'CONNECTOR') continue+ const startId = node.connectorStart?.nodeId+ const endId = node.connectorEnd?.nodeId+ if (!startId || !endId) continue+ const from = chosenOwner(graph, startId, chosen)+ const to = chosenOwner(graph, endId, chosen)+ if (!from || !to || from === to) continue+ edges.push({ id: node.id, from, to, label: connectorLabelSize(graph, node.id) ?? undefined })+ // Only a connector joined to the boxes themselves is joined anew; one joined inside a box+ // keeps where it attaches.+ if (from === startId && to === endId) joined.set(node.id, node.id)+ }+ return { edges, joined }+}++/**+ * What an arrangement read from the graph: each layer's parent and box, each chosen section's+ * children, and the connectors between the layers with their ends, line types, and label sizes,+ * so a result computed from them can tell whether they still hold.+ */+function readFrom(+ graph: SceneGraph,+ pageId: string,+ nodes: SceneNode[],+ groups: Set<string>+): string {+ const chosen = new Set(nodes.map((node) => node.id))+ const layer = (id: string) => {+ const node = graph.getNode(id)+ if (!node) return null+ const box = [node.parentId, node.x, node.y, node.width, node.height]+ return groups.has(id) ? [...box, node.childIds] : box+ }+ // Everything the arrangement reads from a connector or rewrites on it.+ const connector = (id: string) => {+ const node = graph.getNode(id)+ if (!node) return null+ return [+ id,+ node.parentId,+ node.connectorStart,+ node.connectorEnd,+ node.connectorLineType,+ connectorLabelSize(graph, id)+ ]+ }+ return JSON.stringify([+ nodes.map((node) => layer(node.id)),+ connectorEdges(graph, pageId, chosen).edges.map((edge) => connector(edge.id))+ ])+}++/**+ * Arranges the layers `ids` in `options.layout`. ELK layouts take the connectors that join the+ * layers into account: each layer is a box at its own size, each chosen section is laid out+ * around the chosen layers it holds, and the whole keeps its top-left corner. Layers not inside a+ * chosen section must share a parent. Connectors are found, not chosen: those joined to the+ * layers are joined anew, routed when they flow, and any other connector on what moved follows.+ * Throws, moving nothing, when the layers change while the layout runs.+ */+export async function arrangeLayers(+ graph: SceneGraph,+ ids: string[],+ options: ArrangeLayersOptions+): Promise<LayerArrangement> {+ const given = uniq(ids)+ .map((id) => graph.getNode(id))+ .filter(+ (node): node is SceneNode =>+ node !== undefined && node.type !== 'CONNECTOR' && node.type !== 'CANVAS'+ )+ const groups = groupsAmong(graph, new Set(given.map((node) => node.id)))+ // A layer inside another chosen layer that is not laid out around it moves with that layer.+ const nodes = given.filter((node) => !movesWithAncestor(graph, node, given, groups))+ const chosen = new Set(nodes.map((node) => node.id))+ const relayout = () => {+ const moved = connectorsAffectedBy(graph, chosen)+ for (const connector of moved) {+ const current = graph.getNode(connector.id)+ if (current) layoutConnector(graph, current)+ }+ return moved.length+ }+ if (options.layout === 'grid' || options.layout === 'row' || options.layout === 'column') {+ // These place layers in their parents' axes, so the layers must share one.+ if (new Set(nodes.map((node) => node.parentId)).size > 1) {+ throw new Error('Layers to place in a grid, row, or column must share a parent')+ }+ line(nodes, graph, options)+ return { layers: nodes.length, groups: 0, connectors: relayout() }+ }++ const inGroup = (node: SceneNode) => node.parentId !== null && groups.has(node.parentId)+ const top = nodes.filter((node) => !inGroup(node))+ if (new Set(top.map((node) => node.parentId)).size > 1) {+ throw new Error('Layers to arrange must share a parent, apart from those in chosen sections')+ }+ const pageId = top[0] ? graph.pageOf(top[0].id) : null+ if (!pageId) return { layers: 0, groups: 0, connectors: 0 }++ // Where each layer is now, in the shared parent's axes, for the layouts that keep places.+ const position = (node: SceneNode): Vector => {+ const parent = inGroup(node) && node.parentId ? graph.getNode(node.parentId) : undefined+ const offset = parent ? position(parent) : { x: 0, y: 0 }+ return { x: offset.x + node.x, y: offset.y + node.y }+ }+ const { edges, joined } = connectorEdges(graph, pageId, chosen)+ const groupOf = (node: SceneNode) => (inGroup(node) ? (node.parentId ?? undefined) : undefined)+ const input: ArrangeInput = {+ layout: options.layout,+ direction: options.direction,+ spacing: options.spacing,+ boxes: nodes+ .filter((node) => !groups.has(node.id))+ .map((node) => ({+ id: node.id,+ width: node.width,+ height: node.height,+ position: position(node),+ group: groupOf(node)+ })),+ groups: nodes+ .filter((node) => groups.has(node.id))+ .map((node) => ({ id: node.id, position: position(node), group: groupOf(node) })),+ edges+ }+ const topLeft = {+ x: Math.min(...top.map((node) => node.x)),+ y: Math.min(...top.map((node) => node.y))+ }+ const before = readFrom(graph, pageId, nodes, groups)+ const arrangement = await arrangeBoxes(input)+ // Someone may have moved or removed a layer while the layout ran; its result is stale then.+ if (readFrom(graph, pageId, nodes, groups) !== before) {+ throw new Error('The layers changed while they were being arranged; nothing was moved')+ }+ applyArrangement(+ graph,+ input,+ arrangement,+ { boxes: new Map(nodes.map((node) => [node.id, node.id])), connectors: joined },+ { topLeft }+ )+ relayout()+ return { layers: input.boxes.length, groups: input.groups.length, connectors: joined.size }+}diff --git a/packages/core/src/layout/diagram/routes.ts b/packages/core/src/layout/arrange/routes.tssimilarity index 100%rename from packages/core/src/layout/diagram/routes.tsrename to packages/core/src/layout/arrange/routes.tsdiff --git a/packages/core/src/layout/diagram/apply.ts b/packages/core/src/layout/diagram/apply.tsdeleted file mode 100644index 81bb8f40f..000000000--- a/packages/core/src/layout/diagram/apply.ts+++ /dev/null@@ -1,88 +0,0 @@-import type { SceneGraph } from '@open-pencil/scene-graph'-import { boundEndpoint } from '@open-pencil/scene-graph/connectors'-import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'--import type { DiagramInput, DiagramLayout } from './index'-import { runConnectorAlong } from './routes'--/** The layers that draw a diagram, by the diagram's ids. */-export interface DiagramLayers {- /** The layer drawing each node and group. */- boxes: Map<string, string>- /** The connector drawing each edge; an edge drawn by none only shapes the layout. */- connectors: Map<string, string>-}--/** Where a diagram goes in its parent: by its top-left corner or by its centre. */-export type DiagramPlacement = { topLeft: Vector } | { center: Vector }--function bounds(boxes: Rect[]): Rect {- const x = Math.min(...boxes.map((box) => box.x))- const y = Math.min(...boxes.map((box) => box.y))- return {- x,- y,- width: Math.max(...boxes.map((box) => box.x + box.width)) - x,- height: Math.max(...boxes.map((box) => box.y + box.height)) - y- }-}--/**- * Puts a diagram's layers where `layout` placed it, the drawing at `placement` in its parent:- * each node's layer at its box and each group's at its box and size, in the axes of the group- * holding it, if any. Each edge's connector is joined to the layers at its ends by the sides the- * layout chose and runs along the route it gave.- */-export function applyDiagramLayout(- graph: SceneGraph,- input: DiagramInput,- layout: DiagramLayout,- layers: DiagramLayers,- placement: DiagramPlacement-): void {- const boxes = new Map<string, Rect>([...layout.groups, ...layout.nodes])- if (boxes.size === 0) return- const drawing = bounds([...boxes.values()])- const origin =- 'center' in placement- ? {- x: placement.center.x - drawing.width / 2,- y: placement.center.y - drawing.height / 2- }- : placement.topLeft- const shift = { x: origin.x - drawing.x, y: origin.y - drawing.y }- const groupOf = new Map(- [...input.nodes, ...input.groups].map((member) => [member.id, member.group])- )- for (const [id, layerId] of layers.boxes) {- const box = boxes.get(id)- if (!box) continue- const group = groupOf.get(id)- const outer = group ? boxes.get(group) : undefined- const position = outer- ? { x: box.x - outer.x, y: box.y - outer.y }- : { x: box.x + shift.x, y: box.y + shift.y }- // A group's layer takes the size the layout gave it; a node's keeps its own.- if (layout.groups.has(id)) {- graph.updateNode(layerId, { ...position, width: box.width, height: box.height })- } else {- graph.updateNode(layerId, position)- }- }- for (const edge of input.edges) {- const connectorId = layers.connectors.get(edge.id)- const start = layers.boxes.get(edge.from)- const end = layers.boxes.get(edge.to)- if (!connectorId || !start || !end) continue- const route = layout.edges.get(edge.id)- graph.updateNode(connectorId, {- connectorStart: boundEndpoint(start, route?.startSide ?? 'AUTO'),- connectorEnd: boundEndpoint(end, route?.endSide ?? 'AUTO')- })- runConnectorAlong(- graph,- connectorId,- (route?.points ?? []).map((point) => ({ x: point.x + shift.x, y: point.y + shift.y }))- )- }-}diff --git a/packages/core/src/layout/diagram/index.ts b/packages/core/src/layout/diagram/index.tsdeleted file mode 100644index 93e75c841..000000000--- a/packages/core/src/layout/diagram/index.ts+++ /dev/null@@ -1,252 +0,0 @@-import type { ElkExtendedEdge, ElkNode, ElkPort } from 'elkjs/lib/elk-api'--import type { ConnectorSide } from '@open-pencil/scene-graph/connectors'-import type { Rect, Size, Vector } from '@open-pencil/scene-graph/primitives'--import { layoutWithElk } from './elk'--/** The way a diagram flows: top to bottom, bottom to top, left to right, or right to left. */-export type DiagramDirection = 'TB' | 'BT' | 'LR' | 'RL'--/** A node or group, at the top or inside the group it names. */-export interface DiagramMember {- id: string- group?: string-}--export interface DiagramNode extends DiagramMember, Size {}--/** A box around nodes and other groups, sized to hold them. */-export type DiagramGroup = DiagramMember--/** An edge between two nodes or groups; its label, by size, gets room along it. */-export interface DiagramEdge {- id: string- from: string- to: string- label?: Size-}--export interface DiagramInput {- direction: DiagramDirection- nodes: DiagramNode[]- groups: DiagramGroup[]- edges: DiagramEdge[]-}--/** The way an edge runs: the sides it leaves and enters by, and its corners between them. */-export interface DiagramRoute {- startSide: ConnectorSide- endSide: ConnectorSide- /** From its start, on the middle of `startSide`, to its end, on the middle of `endSide`. */- points: Vector[]-}--/** Where everything went, in the diagram's own axes. */-export interface DiagramLayout {- nodes: Map<string, Rect>- groups: Map<string, Rect>- edges: Map<string, DiagramRoute>-}--/** Room between nodes side by side, and between ranks of them along the flow. */-const NODE_SPACING = 40-const RANK_SPACING = 60-/** Room inside a group around what it holds, and above it for the group's title. */-const GROUP_PADDING = 24-const GROUP_TITLE = 48--const ELK_DIRECTION: Record<DiagramDirection, string> = {- TB: 'DOWN',- BT: 'UP',- LR: 'RIGHT',- RL: 'LEFT'-}--/** The side edges leave a box by, and the side they enter one by, along the flow. */-const FLOW_SIDES: Record<DiagramDirection, [ConnectorSide, ConnectorSide]> = {- TB: ['BOTTOM', 'TOP'],- BT: ['TOP', 'BOTTOM'],- LR: ['RIGHT', 'LEFT'],- RL: ['LEFT', 'RIGHT']-}--const ELK_SIDE: Record<ConnectorSide, string> = {- TOP: 'NORTH',- RIGHT: 'EAST',- BOTTOM: 'SOUTH',- LEFT: 'WEST'-}--function portId(boxId: string, side: ConnectorSide): string {- return `${boxId}\u0000${side}`-}--/**- * A port on the middle of each side a box's edges use, fixed there: connectors attach to side- * midpoints, so ELK routes every edge to where its connector will meet the box.- */-function ports(boxId: string, size: Size, sides: ConnectorSide[]): ElkPort[] {- const at: Record<ConnectorSide, Vector> = {- TOP: { x: size.width / 2, y: 0 },- RIGHT: { x: size.width, y: size.height / 2 },- BOTTOM: { x: size.width / 2, y: size.height },- LEFT: { x: 0, y: size.height / 2 }- }- return sides.map((side) => ({- id: portId(boxId, side),- ...at[side],- width: 0,- height: 0,- layoutOptions: { 'elk.port.side': ELK_SIDE[side] }- }))-}--/** Each box's place in the input: a node's own, a group's that of its first member. */-function writtenOrder(input: DiagramInput): Map<string, number> {- const order = new Map<string, number>()- const groupOf = new Map(input.groups.map((group) => [group.id, group.group]))- for (const [index, node] of input.nodes.entries()) {- order.set(node.id, index)- for (let group = node.group; group !== undefined; group = groupOf.get(group)) {- if (!order.has(group)) order.set(group, index)- }- }- return order-}--function elkGraph(input: DiagramInput): ElkNode {- const [outSide, inSide] = FLOW_SIDES[input.direction]- const boxes = new Map<string, ElkNode>()- for (const group of input.groups) {- boxes.set(group.id, {- id: group.id,- children: [],- layoutOptions: {- 'elk.padding': `[top=${GROUP_TITLE},left=${GROUP_PADDING},bottom=${GROUP_PADDING},right=${GROUP_PADDING}]`,- 'elk.portConstraints': 'FIXED_SIDE'- },- ports: [- { id: portId(group.id, outSide), layoutOptions: { 'elk.port.side': ELK_SIDE[outSide] } },- { id: portId(group.id, inSide), layoutOptions: { 'elk.port.side': ELK_SIDE[inSide] } }- ]- })- }- for (const node of input.nodes) {- boxes.set(node.id, {- id: node.id,- width: node.width,- height: node.height,- layoutOptions: { 'elk.portConstraints': 'FIXED_POS' },- ports: ports(node.id, node, [outSide, inSide])- })- }- const root: ElkNode = {- id: '\u0000root',- layoutOptions: {- 'elk.algorithm': 'layered',- 'elk.direction': ELK_DIRECTION[input.direction],- 'elk.hierarchyHandling': 'INCLUDE_CHILDREN',- 'elk.edgeRouting': 'ORTHOGONAL',- 'elk.spacing.nodeNode': String(NODE_SPACING),- 'elk.layered.spacing.nodeNodeBetweenLayers': String(RANK_SPACING),- 'elk.spacing.edgeNode': '20',- 'elk.spacing.edgeEdge': '12',- 'elk.layered.spacing.edgeNodeBetweenLayers': '20',- 'elk.spacing.componentComponent': String(RANK_SPACING),- // Flowcharts read from their first node: break cycles along the order they were written- // in, rather than where ELK's greedy pass would, which can put the start mid-drawing.- 'elk.layered.cycleBreaking.strategy': 'DEPTH_FIRST',- 'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',- 'elk.edgeLabels.placement': 'CENTER',- 'elk.json.shapeCoords': 'ROOT',- 'elk.json.edgeCoords': 'ROOT'- },- children: [],- edges: []- }- const parentOf = (group: string | undefined) => (group ? boxes.get(group) : undefined) ?? root- // ELK keeps the order it is given, so boxes go in the order they were written: a node where it- // first appears, a group where its first member does.- const order = writtenOrder(input)- const members = [...input.groups, ...input.nodes].sort(- (a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0)- )- for (const member of members) {- const box = boxes.get(member.id)- if (box) parentOf(member.group).children?.push(box)- }- root.edges = input.edges- .filter((edge) => boxes.has(edge.from) && boxes.has(edge.to))- .map((edge): ElkExtendedEdge => ({- id: edge.id,- sources: [portId(edge.from, outSide)],- targets: [portId(edge.to, inSide)],- // ELK skips a label without text; only its size matters here.- labels: edge.label ? [{ text: edge.id, ...edge.label }] : []- }))- return root-}--function sideOf(point: Vector, box: Rect): ConnectorSide {- const distances: [ConnectorSide, number][] = [- ['TOP', Math.abs(point.y - box.y)],- ['RIGHT', Math.abs(point.x - (box.x + box.width))],- ['BOTTOM', Math.abs(point.y - (box.y + box.height))],- ['LEFT', Math.abs(point.x - box.x)]- ]- return distances.reduce((best, entry) => (entry[1] < best[1] ? entry : best))[0]-}--function collect(result: ElkNode, input: DiagramInput): DiagramLayout {- const groupIds = new Set(input.groups.map((group) => group.id))- const layout: DiagramLayout = { nodes: new Map(), groups: new Map(), edges: new Map() }- const boxes = new Map<string, Rect>()- const walk = (node: ElkNode) => {- for (const child of node.children ?? []) {- const rect = {- x: child.x ?? 0,- y: child.y ?? 0,- width: child.width ?? 0,- height: child.height ?? 0- }- boxes.set(child.id, rect)- ;(groupIds.has(child.id) ? layout.groups : layout.nodes).set(child.id, rect)- walk(child)- }- }- walk(result)- const edgesOf = (node: ElkNode): ElkExtendedEdge[] => [- ...(node.edges ?? []),- ...(node.children ?? []).flatMap(edgesOf)- ]- const ends = new Map(input.edges.map((edge) => [edge.id, edge]))- for (const edge of edgesOf(result)) {- const input = ends.get(edge.id)- const from = input && boxes.get(input.from)- const to = input && boxes.get(input.to)- const points = (edge.sections ?? []).flatMap((section) => [- section.startPoint,- ...(section.bendPoints ?? []),- section.endPoint- ])- const first = points.at(0)- const last = points.at(-1)- if (!from || !to || !first || !last) continue- layout.edges.set(edge.id, {- startSide: sideOf(first, from),- endSide: sideOf(last, to),- points: points.map(({ x, y }) => ({ x, y }))- })- }- return layout-}--/**- * Lays a diagram out with ELK's layered algorithm: nodes in ranks along the flow, groups around- * their members, and every edge routed at right angles from the middle of the side it leaves by- * to the middle of the side it enters by.- */-export async function layoutDiagram(input: DiagramInput): Promise<DiagramLayout> {- return collect(await layoutWithElk(elkGraph(input)), input)-}diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex d7f9d3adf..24363971d 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -45,6 +45,7 @@ export {} from './analyze/overlaps/params'export { setPexelsAPIKey, setUnsplashAccessKey } from './stock-photo'export { importMermaid, importSVG } from './create'+export { arrangeNodes } from './structure'export {getStockPhotoProviders,registerStockPhotoProvider,diff --git a/packages/core/src/tools/structure/arrange.ts b/packages/core/src/tools/structure/arrange.tsindex 6fe75fbc1..644d381b5 100644--- a/packages/core/src/tools/structure/arrange.ts+++ b/packages/core/src/tools/structure/arrange.ts@@ -1,28 +1,60 @@import * as v from 'valibot'-import type { FigmaNodeProxy } from '#core/figma-api'+import { arrangeLayers } from '#core/layout/arrange/layers'import { toolNumber, defineTool } from '#core/tools/schema'export const arrangeNodes = defineTool({name: 'arrange',- description:- 'Arrange top-level nodes on the canvas in a grid, row, or column layout. Useful after batch creation to tidy up overlapping frames.',- execution: { kind: 'sync', mutation: 'document' },+ description: `Arrange layers so they stop overlapping or follow a structure. Modes:+- spread (default): push overlapping layers apart, keeping each near where it was. Use it after creating layers that landed on each other.+- compact: spread, then close the gaps, keeping the layers' relative places.+- pack: pack the layers into rows in their order, as tidy as a page of screens or components.+- grid, row, column: place them in a grid (cols), a row, or a column, in order, from the first layer.+- flow: rank them along the connectors joining them, rerouting elbowed connectors with right-angled bends; for flowcharts, pipelines, and state machines.+- tree: a tidy tree from its roots along the connectors; for sitemaps, org charts, and hierarchies.+- radial: a tree in rings around its root; for mind maps.+- network: joined layers near each other with no direction; for relationship maps.+Connectors between the layers are found automatically. Include a section and all its children to lay them out inside it; a section given alone moves as one box. Layers outside chosen sections must share a parent. The arrangement keeps its top-left corner.`,+ execution: { kind: 'async', mutation: 'document' },input: v.strictObject({ids: v.optional(v.pipe(v.array(v.string()),v.minLength(1),- v.description('Node IDs to arrange (default: all top-level children)')+ v.description('Layer IDs to arrange (default: every top-level layer on the current page)'))),mode: v.optional(- v.pipe(v.picklist(['grid', 'row', 'column']), v.description('Layout mode')),- 'grid'+ v.pipe(+ v.picklist([+ 'spread',+ 'compact',+ 'pack',+ 'grid',+ 'row',+ 'column',+ 'flow',+ 'tree',+ 'radial',+ 'network'+ ]),+ v.description('How to arrange them (default: spread)')+ ),+ 'spread'+ ),+ direction: v.optional(+ v.pipe(+ v.picklist(['TB', 'BT', 'LR', 'RL']),+ v.description(+ 'Direction of a flow or tree: top to bottom (default), bottom to top, left to right, right to left'+ )+ )),gap: v.optional(- toolNumber(v.pipe(v.number(), v.description('Spacing between nodes (default: 40)')))+ toolNumber(+ v.pipe(v.number(), v.minValue(0), v.description('Spacing between layers (default: 40)'))+ )),cols: v.optional(toolNumber(@@ -35,74 +67,19 @@ export const arrangeNodes = defineTool({))}),- execute: (figma, args) => {- const gap = args.gap ?? 40- const mode = args.mode- const page = figma.currentPage-- let nodes: FigmaNodeProxy[]- if (args.ids && args.ids.length > 0) {- nodes = args.ids- .map((id) => figma.getNodeById(id))- .filter((node): node is FigmaNodeProxy => node !== null)- } else {- nodes = [...page.children]- }-- if (nodes.length === 0) return { error: 'No nodes to arrange' }- const first = nodes[0]-- if (mode === 'row') {- arrangeRow(nodes, first.x, first.y, gap)- } else if (mode === 'column') {- arrangeColumn(nodes, first.x, first.y, gap)- } else {- arrangeGrid(nodes, first.x, first.y, args.cols ?? Math.ceil(Math.sqrt(nodes.length)), gap)+ execute: async (figma, args) => {+ const ids = args.ids ?? figma.currentPage.children.map((node) => node.id)+ if (ids.length === 0) return { error: 'No layers to arrange' }+ try {+ const arranged = await arrangeLayers(figma.graph, ids, {+ layout: args.mode,+ direction: args.direction,+ spacing: args.gap,+ columns: args.cols+ })+ return { mode: args.mode, ...arranged }+ } catch (error) {+ return { error: error instanceof Error ? error.message : String(error) }}-- return { arranged: nodes.length, mode }}})--function arrangeRow(nodes: FigmaNodeProxy[], startX: number, y: number, gap: number) {- let x = startX- for (const node of nodes) {- node.x = x- node.y = y- x += node.width + gap- }-}--function arrangeColumn(nodes: FigmaNodeProxy[], x: number, startY: number, gap: number) {- let y = startY- for (const node of nodes) {- node.x = x- node.y = y- y += node.height + gap- }-}--function arrangeGrid(- nodes: FigmaNodeProxy[],- startX: number,- startY: number,- cols: number,- gap: number-) {- let x = startX- let y = startY- let rowHeight = 0-- for (let index = 0; index < nodes.length; index++) {- const node = nodes[index]- if (index > 0 && index % cols === 0) {- x = startX- y += rowHeight + gap- rowHeight = 0- }- node.x = x- node.y = y- x += node.width + gap- rowHeight = Math.max(rowHeight, node.height)- }-}diff --git a/packages/core/tests/layout/diagram/apply.test.ts b/packages/core/tests/layout/arrange/apply.test.tssimilarity index 85%rename from packages/core/tests/layout/diagram/apply.test.tsrename to packages/core/tests/layout/arrange/apply.test.tsindex 6d31920c2..fe4029d93 100644--- a/packages/core/tests/layout/diagram/apply.test.ts+++ b/packages/core/tests/layout/arrange/apply.test.ts@@ -5,10 +5,10 @@ import { expectDefined } from '#core-tests/helpers/assert'import { SceneGraph } from '@open-pencil/scene-graph'import { connectorRoute, createConnector, freeEndpoint } from '@open-pencil/scene-graph/connectors'-import { layoutDiagram, type DiagramInput } from '#core/layout/diagram'-import { applyDiagramLayout } from '#core/layout/diagram/apply'+import { applyArrangement } from '#core/layout/arrange/apply'+import { arrangeBoxes, type ArrangeInput } from '#core/layout/arrange/boxes'-describe('applyDiagramLayout', () => {+describe('applyArrangement', () => {test('arranges existing layers and joins their connector by the sides the layout chose', async () => {const graph = new SceneGraph()const pageId = expectDefined(graph.getPages()[0]).id@@ -19,18 +19,19 @@ describe('applyDiagramLayout', () => {start: freeEndpoint(0, 0),end: freeEndpoint(0, 0)})- const input: DiagramInput = {+ const input: ArrangeInput = {+ layout: 'flow',direction: 'LR',- nodes: [+ boxes: [{ id: 'a', width: 100, height: 40 },{ id: 'b', width: 100, height: 40, group: 'g' }],groups: [{ id: 'g' }],edges: [{ id: 'ab', from: 'a', to: 'b' }]}- const layout = await layoutDiagram(input)+ const layout = await arrangeBoxes(input)- applyDiagramLayout(+ applyArrangement(graph,input,layout,@@ -62,7 +63,7 @@ describe('applyDiagramLayout', () => {})})-describe('applyDiagramLayout routes', () => {+describe('applyArrangement routes', () => {test('runs each connector through the corners of the route the layout gave it', async () => {const graph = new SceneGraph()const pageId = expectDefined(graph.getPages()[0]).id@@ -78,21 +79,22 @@ describe('applyDiagramLayout routes', () => {['ab', connector()],['ac', connector()]])- const input: DiagramInput = {+ const input: ArrangeInput = {+ layout: 'flow',direction: 'TB',- nodes: ['a', 'b', 'c'].map((id) => ({ id, width: 100, height: 40 })),+ boxes: ['a', 'b', 'c'].map((id) => ({ id, width: 100, height: 40 })),groups: [],edges: [{ id: 'ab', from: 'a', to: 'b' },{ id: 'ac', from: 'a', to: 'c' }]}- const layout = await layoutDiagram(input)+ const layout = await arrangeBoxes(input)const origin = { x: 1000, y: 2000 }- applyDiagramLayout(graph, input, layout, { boxes, connectors }, { topLeft: origin })+ applyArrangement(graph, input, layout, { boxes, connectors }, { topLeft: origin })- const all = [...layout.nodes.values()]+ const all = [...layout.boxes.values()]const shift = {x: origin.x - Math.min(...all.map((rect) => rect.x)),y: origin.y - Math.min(...all.map((rect) => rect.y))diff --git a/packages/core/tests/layout/arrange/boxes.test.ts b/packages/core/tests/layout/arrange/boxes.test.tsnew file mode 100644index 000000000..ad46d0171--- /dev/null+++ b/packages/core/tests/layout/arrange/boxes.test.ts@@ -0,0 +1,217 @@+import { describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import type { Rect } from '@open-pencil/scene-graph/primitives'++import {+ arrangeBoxes,+ type ArrangeBox,+ type ArrangeInput,+ type BoxLayout+} from '#core/layout/arrange/boxes'++const box = (id: string, x = 0, y = 0, group?: string): ArrangeBox => ({+ id,+ width: 120,+ height: 50,+ position: { x, y },+ group+})++function overlap(a: Rect, b: Rect): boolean {+ return a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height+}++function overlapping(rects: Rect[]): boolean {+ return rects.some((a, i) => rects.slice(i + 1).some((b) => overlap(a, b)))+}++function bounds(rects: Rect[]): Rect {+ const x = Math.min(...rects.map((rect) => rect.x))+ const y = Math.min(...rects.map((rect) => rect.y))+ return {+ x,+ y,+ width: Math.max(...rects.map((rect) => rect.x + rect.width)) - x,+ height: Math.max(...rects.map((rect) => rect.y + rect.height)) - y+ }+}++/** A root with two children, one of which has a child: `r → a, r → b, a → c`. */+const TREE: Pick<ArrangeInput, 'boxes' | 'groups' | 'edges'> = {+ boxes: [box('r'), box('a'), box('b'), box('c')],+ groups: [],+ edges: [+ { id: 'ra', from: 'r', to: 'a' },+ { id: 'rb', from: 'r', to: 'b' },+ { id: 'ac', from: 'a', to: 'c' }+ ]+}++describe('arrangeBoxes', () => {+ describe('flow', () => {+ test('routes every edge from the middle of the side it leaves by to the middle of the one it enters', async () => {+ const input: ArrangeInput = {+ layout: 'flow',+ direction: 'TB',+ boxes: [box('a'), box('b'), box('c')],+ groups: [],+ edges: [+ { id: 'ab', from: 'a', to: 'b' },+ { id: 'ac', from: 'a', to: 'c' }+ ]+ }+ const arrangement = await arrangeBoxes(input)+ for (const edge of input.edges) {+ const route = expectDefined(arrangement.edges.get(edge.id))+ const from = expectDefined(arrangement.boxes.get(edge.from))+ const to = expectDefined(arrangement.boxes.get(edge.to))+ expect([route.startSide, route.endSide]).toEqual(['BOTTOM', 'TOP'])+ expect(route.points[0]).toEqual({ x: from.x + from.width / 2, y: from.y + from.height })+ expect(route.points.at(-1)).toEqual({ x: to.x + to.width / 2, y: to.y })+ for (const [i, point] of route.points.slice(1).entries()) {+ const previous = expectDefined(route.points[i])+ expect(point.x === previous.x || point.y === previous.y).toBe(true)+ }+ }+ })++ test('keeps the first box first when edges loop back to it', async () => {+ const arrangement = await arrangeBoxes({+ layout: 'flow',+ direction: 'LR',+ boxes: [box('start'), box('work', 0, 0, 'loop'), box('check', 0, 0, 'loop')],+ groups: [{ id: 'loop' }],+ edges: [+ { id: 'a', from: 'start', to: 'work' },+ { id: 'b', from: 'work', to: 'check' },+ { id: 'c', from: 'check', to: 'start' }+ ]+ })+ const start = expectDefined(arrangement.boxes.get('start'))+ const work = expectDefined(arrangement.boxes.get('work'))+ const loop = expectDefined(arrangement.groups.get('loop'))+ expect(start.x + start.width).toBeLessThan(work.x)+ expect(loop.x).toBeLessThanOrEqual(work.x)+ expect(loop.x + loop.width).toBeGreaterThanOrEqual(work.x + work.width)+ })++ test('leaves room along an edge for its label', async () => {+ const gap = async (label?: { width: number; height: number }) => {+ const arrangement = await arrangeBoxes({+ layout: 'flow',+ boxes: [box('a'), box('b')],+ groups: [],+ edges: [{ id: 'e', from: 'a', to: 'b', label }]+ })+ const a = expectDefined(arrangement.boxes.get('a'))+ return expectDefined(arrangement.boxes.get('b')).y - (a.y + a.height)+ }+ expect(await gap({ width: 60, height: 40 })).toBeGreaterThanOrEqual((await gap()) + 40)+ })+ })++ test('spread pushes overlapping boxes apart and leaves those clear of others nearly in place', async () => {+ const boxes = [box('a', 0, 0), box('b', 40, 20), box('far', 600, 0)]+ const arrangement = await arrangeBoxes({ layout: 'spread', boxes, groups: [], edges: [] })+ const placed = [...arrangement.boxes.values()]+ expect(overlapping(placed)).toBe(false)+ const a = expectDefined(arrangement.boxes.get('a'))+ const far = expectDefined(arrangement.boxes.get('far'))+ // Relative places hold: the far box stays well to the right.+ expect(far.x - a.x).toBeGreaterThan(400)+ })++ test('compact closes the gaps a spread leaves, without overlaps', async () => {+ const boxes = [box('a', 0, 0), box('b', 40, 20), box('c', 900, 0), box('d', 0, 700)]+ const spread = await arrangeBoxes({ layout: 'spread', boxes, groups: [], edges: [] })+ const compact = await arrangeBoxes({ layout: 'compact', boxes, groups: [], edges: [] })+ const compacted = [...compact.boxes.values()]+ expect(overlapping(compacted)).toBe(false)+ const area = (rect: Rect) => rect.width * rect.height+ expect(area(bounds(compacted))).toBeLessThan(area(bounds([...spread.boxes.values()])))+ })++ test('compact starts from where the spread put each group, so no group lands on a box', async () => {+ const arrangement = await arrangeBoxes({+ layout: 'compact',+ boxes: [box('a', 0, 0), box('b', 900, 0), box('inner', 30, 70, 'g')],+ groups: [{ id: 'g', position: { x: 10, y: 10 } }],+ edges: []+ })+ const group = expectDefined(arrangement.groups.get('g'))+ for (const id of ['a', 'b'])+ expect(overlap(group, expectDefined(arrangement.boxes.get(id)))).toBe(false)+ })++ test('pack fills rows in the boxes’ order, the given space apart', async () => {+ const arrangement = await arrangeBoxes({+ layout: 'pack',+ spacing: 20,+ boxes: ['a', 'b', 'c', 'd'].map((id) => box(id, 500, 500)),+ groups: [],+ edges: []+ })+ const [a, b] = ['a', 'b'].map((id) => expectDefined(arrangement.boxes.get(id)))+ expect(overlapping([...arrangement.boxes.values()])).toBe(false)+ expect(expectDefined(b).y).toBe(expectDefined(a).y)+ expect(expectDefined(b).x - (expectDefined(a).x + expectDefined(a).width)).toBe(20)+ })++ test('tree puts each child below its parent, and LR to its right', async () => {+ const down = await arrangeBoxes({ layout: 'tree', ...TREE })+ const across = await arrangeBoxes({ layout: 'tree', direction: 'LR', ...TREE })+ for (const [parent, child] of [+ ['r', 'a'],+ ['r', 'b'],+ ['a', 'c']+ ] as const) {+ const p = expectDefined(down.boxes.get(parent))+ const c = expectDefined(down.boxes.get(child))+ expect(p.y + p.height).toBeLessThan(c.y)+ const pr = expectDefined(across.boxes.get(parent))+ const cr = expectDefined(across.boxes.get(child))+ expect(pr.x + pr.width).toBeLessThan(cr.x)+ }+ })++ test('tree has its edges leave and enter boxes along its direction', async () => {+ const arrangement = await arrangeBoxes({ layout: 'tree', direction: 'LR', ...TREE })+ expect(arrangement.edges.get('ra')).toEqual({ startSide: 'RIGHT', endSide: 'LEFT', points: [] })+ })++ test('radial places the root nearer the middle than the leaf farthest down the tree', async () => {+ const arrangement = await arrangeBoxes({ layout: 'radial', ...TREE })+ const centre = (rect: Rect) => ({ x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 })+ const middle = centre(bounds([...arrangement.boxes.values()]))+ const distance = (id: string) => {+ const point = centre(expectDefined(arrangement.boxes.get(id)))+ return Math.hypot(point.x - middle.x, point.y - middle.y)+ }+ expect(distance('r')).toBeLessThan(distance('c'))+ })++ test.each(['spread', 'compact', 'pack', 'tree', 'radial', 'network'] satisfies BoxLayout[])(+ '%s places every box, inside its group',+ async (layout) => {+ const arrangement = await arrangeBoxes({+ layout,+ boxes: [box('a'), box('b', 30, 10, 'g'), box('c', 60, 20, 'g')],+ groups: [{ id: 'g' }],+ edges: [{ id: 'bc', from: 'b', to: 'c' }]+ })+ expect([...arrangement.boxes.keys()].sort()).toEqual(['a', 'b', 'c'])+ const group = expectDefined(arrangement.groups.get('g'))+ for (const id of ['b', 'c']) {+ const inner = expectDefined(arrangement.boxes.get(id))+ expect(inner.x).toBeGreaterThanOrEqual(group.x)+ expect(inner.y).toBeGreaterThanOrEqual(group.y)+ expect(inner.x + inner.width).toBeLessThanOrEqual(group.x + group.width)+ expect(inner.y + inner.height).toBeLessThanOrEqual(group.y + group.height)+ }+ // A flow routes its edges and a tree sets their sides; the others leave them to connectors.+ expect(arrangement.edges.size).toBe(layout === 'tree' ? 1 : 0)+ }+ )+})diff --git a/packages/core/tests/layout/arrange/layers.test.ts b/packages/core/tests/layout/arrange/layers.test.tsnew file mode 100644index 000000000..ec0f23c9d--- /dev/null+++ b/packages/core/tests/layout/arrange/layers.test.ts@@ -0,0 +1,303 @@+import { describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import {+ boundEndpoint,+ connectorRoute,+ connectorSublayers,+ createConnector+} from '@open-pencil/scene-graph/connectors'+import type { Rect } from '@open-pencil/scene-graph/primitives'++import { arrangeLayers } from '#core/layout/arrange/layers'++function overlap(a: Rect, b: Rect): boolean {+ return a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height+}++/** A page with layers piled on each other, as an agent drawing blindly leaves them. */+function pile() {+ const graph = new SceneGraph()+ const pageId = expectDefined(graph.getPages()[0]).id+ const box = (name: string, parentId = pageId) =>+ graph.createNode('RECTANGLE', parentId, { name, x: 100, y: 100, width: 120, height: 50 })+ const join = (from: SceneNode, to: SceneNode, lineType?: 'STRAIGHT') =>+ createConnector(graph, pageId, {+ start: boundEndpoint(from.id),+ end: boundEndpoint(to.id),+ ...(lineType ? { lineType } : {})+ })+ return { graph, pageId, box, join }+}++const node = (graph: SceneGraph, id: string) => expectDefined(graph.getNode(id))++describe('arrangeLayers', () => {+ test('spreads piled layers into ranks along the flow and reroutes their connectors', async () => {+ const { graph, box, join } = pile()+ const [a, b, c] = [box('A'), box('B'), box('C')]+ const ab = join(a, b)+ const ac = join(a, c)++ const result = await arrangeLayers(graph, [a.id, b.id, c.id], { layout: 'flow' })++ expect(result).toEqual({ layers: 3, groups: 0, connectors: 2 })+ const [placedA, placedB, placedC] = [a, b, c].map((layer) => node(graph, layer.id))+ expect(overlap(placedB, placedC)).toBe(false)+ expect(placedA.y + placedA.height).toBeLessThan(Math.min(placedB.y, placedC.y))+ // The drawing keeps its top-left corner.+ expect(Math.min(placedA.x, placedB.x, placedC.x)).toBe(100)+ expect(Math.min(placedA.y, placedB.y, placedC.y)).toBe(100)+ for (const connector of [ab, ac]) {+ const routed = node(graph, connector.id)+ expect(routed.connectorStart).toMatchObject({ nodeId: a.id, magnet: 'BOTTOM' })+ expect(routed.connectorEnd?.magnet).toBe('TOP')+ }+ })++ test('lays a section out around its layers only when all of them were chosen', async () => {+ const { graph, pageId, box, join } = pile()+ const start = box('Start')+ const section = graph.createNode('SECTION', pageId, {+ name: 'Steps',+ x: 0,+ y: 0,+ width: 50,+ height: 50+ })+ const [one, two] = [box('One', section.id), box('Two', section.id)]+ join(start, one)+ join(one, two)++ expect(+ await arrangeLayers(graph, [start.id, section.id, one.id, two.id], {+ layout: 'flow',+ direction: 'LR'+ })+ ).toMatchObject({ layers: 3, groups: 1 })+ const placed = node(graph, section.id)+ for (const inner of [one, two]) {+ const child = node(graph, inner.id)+ expect(child.x).toBeGreaterThan(0)+ expect(child.x + child.width).toBeLessThan(placed.width)+ expect(child.y + child.height).toBeLessThan(placed.height)+ }++ // A section holding a layer that was not chosen moves as one box and keeps its size.+ const other = pile()+ const first = other.box('First')+ const held = other.graph.createNode('SECTION', other.pageId, {+ x: 400,+ y: 400,+ width: 300,+ height: 200+ })+ const inside = other.box('Inside', held.id)+ other.join(first, held)+ expect(await arrangeLayers(other.graph, [first.id, held.id], { layout: 'flow' })).toMatchObject(+ {+ layers: 2,+ groups: 0+ }+ )+ expect(node(other.graph, held.id)).toMatchObject({ width: 300, height: 200 })+ expect(node(other.graph, inside.id)).toMatchObject({ x: 100, y: 100 })+ })++ test('keeps where a connector attaches inside a box, and a straight line its ends', async () => {+ const { graph, pageId, box, join } = pile()+ const frame = graph.createNode('FRAME', pageId, { x: 0, y: 0, width: 300, height: 200 })+ const button = box('Button', frame.id)+ const target = box('Target')+ const inner = join(button, target)+ const straight = join(target, box('Next'), 'STRAIGHT')+ const before = node(graph, straight.id)++ const result = await arrangeLayers(+ graph,+ [frame.id, target.id, expectDefined(before.connectorEnd?.nodeId)],+ { layout: 'flow' }+ )++ expect(result.connectors).toBe(1)+ expect(node(graph, inner.id).connectorStart?.nodeId).toBe(button.id)+ expect(node(graph, straight.id).connectorStart).toEqual(before.connectorStart)+ expect(node(graph, straight.id).connectorEnd).toEqual(before.connectorEnd)+ })++ test('refuses layers with different parents outside chosen sections', async () => {+ const { graph, pageId, box } = pile()+ const frame = graph.createNode('FRAME', pageId, { width: 300, height: 200 })+ await expect(+ arrangeLayers(graph, [box('Page').id, box('Framed', frame.id).id], { layout: 'flow' })+ ).rejects.toThrow('must share a parent')+ })++ test('spread unpiles layers without connectors and keeps the pile’s corner', async () => {+ const { graph, box } = pile()+ const layers = ['A', 'B', 'C', 'D'].map((name) => box(name))++ await arrangeLayers(+ graph,+ layers.map((layer) => layer.id),+ { layout: 'spread' }+ )++ const placed = layers.map((layer) => node(graph, layer.id))+ for (const [i, a] of placed.entries()) {+ for (const b of placed.slice(i + 1)) expect(overlap(a, b)).toBe(false)+ }+ expect(Math.min(...placed.map((layer) => layer.x))).toBe(100)+ expect(Math.min(...placed.map((layer) => layer.y))).toBe(100)+ })++ test('grid, row, and column place layers in order from the first, and connectors follow', async () => {+ const { graph, box, join } = pile()+ const [a, b, c] = [box('A'), box('B'), box('C')]+ const ab = join(a, b)++ await arrangeLayers(graph, [a.id, b.id, c.id], { layout: 'row', spacing: 10 })+ expect([a, b, c].map((layer) => node(graph, layer.id).x)).toEqual([100, 230, 360])+ // The connector between them was laid out again where they now are.+ const routed = node(graph, ab.id)+ expect(routed.x).toBeGreaterThanOrEqual(100 + 120)++ await arrangeLayers(graph, [a.id, b.id, c.id], { layout: 'grid', columns: 2, spacing: 10 })+ expect([a, b, c].map((layer) => [node(graph, layer.id).x, node(graph, layer.id).y])).toEqual([+ [100, 100],+ [230, 100],+ [100, 160]+ ])+ })++ test('bends a page connector between layers inside a frame where the layers are', async () => {+ const { graph, pageId, box, join } = pile()+ const frame = graph.createNode('FRAME', pageId, { x: 500, y: 300, width: 900, height: 600 })+ const [a, b, c] = [box('A', frame.id), box('B', frame.id), box('C', frame.id)]+ const connectors = [join(a, b), join(a, c)]++ await arrangeLayers(graph, [a.id, b.id, c.id], { layout: 'flow' })++ const world = (layer: SceneNode) => {+ const placed = node(graph, layer.id)+ return { ...placed, x: placed.x + 500, y: placed.y + 300 }+ }+ const top = world(a)+ for (const [connector, target] of [+ [connectors[0], b],+ [connectors[1], c]+ ] as const) {+ const route = expectDefined(connectorRoute(graph, node(graph, connector.id)))+ const bottom = world(target)+ // Every bend lies between the source's bottom and the target's top, in page axes.+ for (const piece of route.pieces.slice(1)) {+ expect(piece.from.y).toBeGreaterThan(top.y + top.height)+ expect(piece.from.y).toBeLessThan(bottom.y)+ }+ }+ })++ test('counts a layer given twice once', async () => {+ const { graph, box, join } = pile()+ const [a, b] = [box('A'), box('B')]+ join(a, b)+ expect(await arrangeLayers(graph, [a.id, a.id, b.id], { layout: 'flow' })).toMatchObject({+ layers: 2+ })+ })++ test('moves a chosen layer with a chosen section that is not laid out around it', async () => {+ const { graph, pageId, box, join } = pile()+ const start = box('Start')+ const section = graph.createNode('SECTION', pageId, { x: 600, y: 600, width: 400, height: 300 })+ const [one] = [box('One', section.id), box('Two', section.id)]+ join(start, section)++ expect(+ await arrangeLayers(graph, [start.id, section.id, one.id], { layout: 'flow' })+ ).toMatchObject({ layers: 2, groups: 0 })+ expect(node(graph, one.id)).toMatchObject({ x: 100, y: 100 })+ })++ test('places grid, row, and column layers only within one parent', async () => {+ const { graph, pageId, box } = pile()+ const frame = graph.createNode('FRAME', pageId, { x: 500, y: 0, width: 300, height: 200 })+ await expect(+ arrangeLayers(graph, [box('Page').id, box('Framed', frame.id).id], { layout: 'row' })+ ).rejects.toThrow('must share a parent')+ })++ test('spread starts a section from where it is, like the layers beside it', async () => {+ const { graph, pageId, box } = pile()+ const near = box('Near')+ const section = graph.createNode('SECTION', pageId, {+ x: 1500,+ y: 100,+ width: 300,+ height: 200+ })+ const inside = box('Inside', section.id)++ await arrangeLayers(graph, [near.id, section.id, inside.id], { layout: 'spread' })++ expect(node(graph, section.id).x - node(graph, near.id).x).toBeGreaterThan(1000)+ })++ test('moves nothing when a layer changes while the layout runs', async () => {+ const { graph, box, join } = pile()+ const [a, b] = [box('A'), box('B')]+ join(a, b)++ const arranging = arrangeLayers(graph, [a.id, b.id], { layout: 'flow' })+ // A user drags A before the layout comes back.+ graph.updateNode(a.id, { x: 700 })++ await expect(arranging).rejects.toThrow('changed while they were being arranged')+ expect(node(graph, a.id).x).toBe(700)+ expect(node(graph, b.id)).toMatchObject({ x: 100, y: 100 })+ })++ test('moves nothing when a connector or a section child is added while the layout runs', async () => {+ const joined = pile()+ const [a, b, c] = [joined.box('A'), joined.box('B'), joined.box('C')]+ joined.join(a, b)+ const arranging = arrangeLayers(joined.graph, [a.id, b.id, c.id], { layout: 'flow' })+ joined.join(b, c)+ await expect(arranging).rejects.toThrow('changed while they were being arranged')++ const held = pile()+ const section = held.graph.createNode('SECTION', held.pageId, {+ x: 0,+ y: 0,+ width: 300,+ height: 200+ })+ const inside = held.box('Inside', section.id)+ const outside = held.box('Outside')+ const layingOut = arrangeLayers(held.graph, [section.id, inside.id, outside.id], {+ layout: 'flow'+ })+ held.box('Added', section.id)+ await expect(layingOut).rejects.toThrow('changed while they were being arranged')+ })++ test('moves nothing when a connector is re-pinned or relabelled while the layout runs', async () => {+ const pinned = pile()+ const [a, b] = [pinned.box('A'), pinned.box('B')]+ const ab = pinned.join(a, b)+ const arranging = arrangeLayers(pinned.graph, [a.id, b.id], { layout: 'flow' })+ pinned.graph.updateNode(ab.id, { connectorEnd: boundEndpoint(b.id, 'LEFT') })+ await expect(arranging).rejects.toThrow('changed while they were being arranged')+ expect(node(pinned.graph, ab.id).connectorEnd?.magnet).toBe('LEFT')++ const labelled = pile()+ const [c, d] = [labelled.box('C'), labelled.box('D')]+ const cd = labelled.join(c, d)+ const label = expectDefined(connectorSublayers(labelled.graph, cd)).label+ const layingOut = arrangeLayers(labelled.graph, [c.id, d.id], { layout: 'flow' })+ labelled.graph.updateNode(label.id, { text: 'A much longer label', width: 160, height: 24 })+ await expect(layingOut).rejects.toThrow('changed while they were being arranged')+ })+})diff --git a/packages/core/tests/layout/diagram/layout.test.ts b/packages/core/tests/layout/diagram/layout.test.tsdeleted file mode 100644index 22c685c4e..000000000--- a/packages/core/tests/layout/diagram/layout.test.ts+++ /dev/null@@ -1,68 +0,0 @@-import { describe, expect, test } from 'bun:test'--import { expectDefined } from '#core-tests/helpers/assert'--import { layoutDiagram, type DiagramInput } from '#core/layout/diagram'--const node = (id: string, group?: string) => ({ id, width: 120, height: 50, group })--describe('layoutDiagram', () => {- test('routes every edge from the middle of the side it leaves by to the middle of the one it enters', async () => {- const input: DiagramInput = {- direction: 'TB',- nodes: [node('a'), node('b'), node('c')],- groups: [],- edges: [- { id: 'ab', from: 'a', to: 'b' },- { id: 'ac', from: 'a', to: 'c' }- ]- }- const layout = await layoutDiagram(input)- for (const edge of input.edges) {- const route = expectDefined(layout.edges.get(edge.id))- const from = expectDefined(layout.nodes.get(edge.from))- const to = expectDefined(layout.nodes.get(edge.to))- expect([route.startSide, route.endSide]).toEqual(['BOTTOM', 'TOP'])- expect(route.points[0]).toEqual({ x: from.x + from.width / 2, y: from.y + from.height })- expect(route.points.at(-1)).toEqual({ x: to.x + to.width / 2, y: to.y })- // Every corner is a right angle.- for (const [i, point] of route.points.slice(1).entries()) {- const previous = expectDefined(route.points[i])- expect(point.x === previous.x || point.y === previous.y).toBe(true)- }- }- })-- test('keeps the first node written first when edges loop back to it', async () => {- const layout = await layoutDiagram({- direction: 'LR',- nodes: [node('start'), node('work', 'loop'), node('check', 'loop')],- groups: [{ id: 'loop' }],- edges: [- { id: 'a', from: 'start', to: 'work' },- { id: 'b', from: 'work', to: 'check' },- { id: 'c', from: 'check', to: 'start' }- ]- })- const start = expectDefined(layout.nodes.get('start'))- const work = expectDefined(layout.nodes.get('work'))- const loop = expectDefined(layout.groups.get('loop'))- expect(start.x + start.width).toBeLessThan(work.x)- expect(loop.x).toBeLessThanOrEqual(work.x)- expect(loop.x + loop.width).toBeGreaterThanOrEqual(work.x + work.width)- })-- test('leaves room along an edge for its label', async () => {- const gap = async (label?: { width: number; height: number }) => {- const layout = await layoutDiagram({- direction: 'TB',- nodes: [node('a'), node('b')],- groups: [],- edges: [{ id: 'e', from: 'a', to: 'b', label }]- })- const a = expectDefined(layout.nodes.get('a'))- return expectDefined(layout.nodes.get('b')).y - (a.y + a.height)- }- expect(await gap({ width: 60, height: 40 })).toBeGreaterThanOrEqual((await gap()) + 40)- })-})diff --git a/packages/core/tests/tools/structure/arrange.test.ts b/packages/core/tests/tools/structure/arrange.test.tsnew file mode 100644index 000000000..7369e0a63--- /dev/null+++ b/packages/core/tests/tools/structure/arrange.test.ts@@ -0,0 +1,71 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { arrangeNodes } from '@open-pencil/core/tools'+import { SceneGraph } from '@open-pencil/scene-graph'+import type { Rect } from '@open-pencil/scene-graph/primitives'++function overlaps(nodes: Rect[]): boolean {+ return nodes.some((a, i) =>+ nodes+ .slice(i + 1)+ .some(+ (b) =>+ a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height+ )+ )+}++describe('arrange', () => {+ test('spreads every top-level layer on the page apart by default', async () => {+ const figma = new FigmaAPI(new SceneGraph())+ const layers = [figma.createRectangle(), figma.createRectangle(), figma.createRectangle()]++ expect(await arrangeNodes.execute(figma, {})).toMatchObject({ mode: 'spread', layers: 3 })+ expect(overlaps(layers)).toBe(false)+ })++ test('flows layers along the connectors joining them', async () => {+ const figma = new FigmaAPI(new SceneGraph())+ const [first, second] = [figma.createRectangle(), figma.createRectangle()]+ const connector = figma.createConnector()+ connector.connectorStart = { endpointNodeId: first.id, magnet: 'AUTO' }+ connector.connectorEnd = { endpointNodeId: second.id, magnet: 'AUTO' }++ expect(+ await arrangeNodes.execute(figma, {+ ids: [first.id, second.id],+ mode: 'flow',+ direction: 'LR'+ })+ ).toEqual({ mode: 'flow', layers: 2, groups: 0, connectors: 1 })+ expect(first.x + first.width).toBeLessThan(second.x)+ })++ test('keeps the grid it always had', async () => {+ const figma = new FigmaAPI(new SceneGraph())+ const layers = Array.from({ length: 4 }, () => figma.createRectangle())+ await arrangeNodes.execute(figma, { mode: 'grid', gap: 10 })+ expect(layers.map((layer) => [layer.x, layer.y])).toEqual([+ [0, 0],+ [110, 0],+ [0, 110],+ [110, 110]+ ])+ })++ test('reports layers it cannot arrange together', async () => {+ const figma = new FigmaAPI(new SceneGraph())+ const frame = figma.createFrame()+ const inside = figma.createRectangle()+ frame.appendChild(inside)+ expect(+ await arrangeNodes.execute(figma, {+ ids: [figma.createRectangle().id, inside.id],+ mode: 'flow'+ })+ ).toEqual({+ error: 'Layers to arrange must share a parent, apart from those in chosen sections'+ })+ })+})diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.mdindex 085e1d55f..3d1b579b6 100644--- a/packages/design-jsx/src/reference/authoring.md+++ b/packages/design-jsx/src/reference/authoring.md@@ -13,7 +13,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- `wrap` and `rowGap` enable wrapped flex rows. `grid`, `columns`, and `rows` enable grid (for example `columns="1fr 200px 1fr"` or `columns="repeat(7, 1fr)"`); tracks are `fr`, pixel lengths, `auto`, `repeat()`, and `minmax()`, which grows like its maximum. Grid children use `colStart`, `rowStart`, `colSpan`, and `rowSpan`. The current grid `gap` shorthand takes precedence over `columnGap` and `rowGap`.- `flow="auto"|"ltr"|"rtl"` controls container flow; text `dir` controls writing direction. Preserve these separately.- Outside auto-layout, and for `position="absolute"` children, `constraints={{ horizontal, vertical }}` sets how a layer follows its parent's resizing, with Figma's values in lowercase: `"min"`, `"center"`, `"max"`, `"stretch"`, or `"scale"`. `minW`, `maxW`, `minH`, and `maxH` bound a layer's size. `visible={false}` hides a layer and `locked` locks it.-- Use measured node bounds and the existing `arrange` tool for independent artboards. Prefer layout constraints to calculating child coordinates; ordinary JavaScript arithmetic is appropriate when real geometry calculations are needed.+- Use measured node bounds and the existing `arrange` tool for independent artboards: `pack` for a page of screens, `spread` when generated layers overlap. Prefer layout constraints to calculating child coordinates; ordinary JavaScript arithmetic is appropriate when real geometry calculations are needed.## Paint, text, and artworkdiff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.mdindex 043d77d87..3689da432 100644--- a/packages/docs/programmable/mcp-server.md+++ b/packages/docs/programmable/mcp-server.md@@ -275,7 +275,7 @@ Settings tools never expose credentials, AI models, MCP connections, storage, or| `node_move` | Move a node to a new position || `node_resize` | Resize a node || `node_replace_with` | Replace a node with another node |-| `arrange` | Align or distribute selected nodes |+| `arrange` | Spread overlapping layers apart, pack them, place them in a grid, row, or column, or lay them out along their connectors as a flow, tree, radial map, or network |### Structurediff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.mdindex 289b6c1db..f5a585ad4 100644--- a/packages/docs/reference/design-authoring.md+++ b/packages/docs/reference/design-authoring.md@@ -15,7 +15,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- `wrap` and `rowGap` enable wrapped flex rows. `grid`, `columns`, and `rows` enable grid (for example `columns="1fr 200px 1fr"` or `columns="repeat(7, 1fr)"`); tracks are `fr`, pixel lengths, `auto`, `repeat()`, and `minmax()`, which grows like its maximum. Grid children use `colStart`, `rowStart`, `colSpan`, and `rowSpan`. The current grid `gap` shorthand takes precedence over `columnGap` and `rowGap`.- `flow="auto"|"ltr"|"rtl"` controls container flow; text `dir` controls writing direction. Preserve these separately.- Outside auto-layout, and for `position="absolute"` children, `constraints={{ horizontal, vertical }}` sets how a layer follows its parent's resizing, with Figma's values in lowercase: `"min"`, `"center"`, `"max"`, `"stretch"`, or `"scale"`. `minW`, `maxW`, `minH`, and `maxH` bound a layer's size. `visible={false}` hides a layer and `locked` locks it.-- Use measured node bounds and the existing `arrange` tool for independent artboards. Prefer layout constraints to calculating child coordinates; ordinary JavaScript arithmetic is appropriate when real geometry calculations are needed.+- Use measured node bounds and the existing `arrange` tool for independent artboards: `pack` for a page of screens, `spread` when generated layers overlap. Prefer layout constraints to calculating child coordinates; ordinary JavaScript arithmetic is appropriate when real geometry calculations are needed.## Paint, text, and artworkdiff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.mdindex ef291e8dc..38be20042 100644--- a/skills/open-pencil/SKILL.md+++ b/skills/open-pencil/SKILL.md@@ -303,7 +303,7 @@ The CLI defaults the filesystem root to the home directory on Windows and the cu1. **Find or open a document** — `list_documents` for open tabs and their IDs; `open_file { path }` within the effective filesystem root (`list_recent_files` lists recently opened files there), or `new_document {}`. Pass `document_id` and `page_id` explicitly instead of relying on the active tab; `activate_document { document_id }` brings a tab to the front when the user should see it.2. **Query** — `get_page_tree`, `find_nodes`, `query_nodes`, `get_node`, `list_pages`, `get_current_page`.3. **Inspect** — `get_jsx`, `diff_jsx`, `diff_create`, `diff_visual`, `describe`, `export_image`, `export_svg`, `export_pdf`.-4. **Modify** — `render`, `batch_update`, `update_node`, `set_fill`, `set_layout`, `create_shape`, `import_svg`, etc. For a flowchart, write it as Mermaid and call `import_mermaid { mermaid }`: it lays out FigJam shapes, sections, and connectors without overlaps and returns each node's layer id, instead of placing shapes and connectors by hand.+4. **Modify** — `render`, `batch_update`, `update_node`, `set_fill`, `set_layout`, `create_shape`, `import_svg`, etc. For a flowchart, write it as Mermaid and call `import_mermaid { mermaid }`: it lays out FigJam shapes, sections, and connectors without overlaps and returns each node's layer id, instead of placing shapes and connectors by hand. When layers you created overlap, call `arrange { ids }`: it spreads them apart and keeps each near where it was. `arrange` also packs screens (`mode: "pack"`) and lays shapes out along the connectors joining them (`mode: "flow"` for flows, `"tree"` for hierarchies, `"radial"` for mind maps, `"network"` for relationship maps).5. **Save/export** — `save_file`, `export_image`, `export_svg`, `export_pdf`, or CLI `export`.6. **Close** — `close_file { document_id, unsaved }` closes a document tab after the workflow. With unsaved changes it fails unless `unsaved` is `"save"` or `"discard"`; automation never prompts in the app.diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.mdindex 289b6c1db..f5a585ad4 100644--- a/skills/open-pencil/references/design-authoring.md+++ b/skills/open-pencil/references/design-authoring.md@@ -15,7 +15,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- `wrap` and `rowGap` enable wrapped flex rows. `grid`, `columns`, and `rows` enable grid (for example `columns="1fr 200px 1fr"` or `columns="repeat(7, 1fr)"`); tracks are `fr`, pixel lengths, `auto`, `repeat()`, and `minmax()`, which grows like its maximum. Grid children use `colStart`, `rowStart`, `colSpan`, and `rowSpan`. The current grid `gap` shorthand takes precedence over `columnGap` and `rowGap`.- `flow="auto"|"ltr"|"rtl"` controls container flow; text `dir` controls writing direction. Preserve these separately.- Outside auto-layout, and for `position="absolute"` children, `constraints={{ horizontal, vertical }}` sets how a layer follows its parent's resizing, with Figma's values in lowercase: `"min"`, `"center"`, `"max"`, `"stretch"`, or `"scale"`. `minW`, `maxW`, `minH`, and `maxH` bound a layer's size. `visible={false}` hides a layer and `locked` locks it.-- Use measured node bounds and the existing `arrange` tool for independent artboards. Prefer layout constraints to calculating child coordinates; ordinary JavaScript arithmetic is appropriate when real geometry calculations are needed.+- Use measured node bounds and the existing `arrange` tool for independent artboards: `pack` for a page of screens, `spread` when generated layers overlap. Prefer layout constraints to calculating child coordinates; ordinary JavaScript arithmetic is appropriate when real geometry calculations are needed.## Paint, text, and artwork