AI-native design editor. Open-source Figma alternative.
fix(core): lay out looping diagrams in Radial, and keep Radial and Network shapes apart (#1583)
Danila Poyarkovc7eb49ab9c62
diff --git a/packages/core/src/layout/arrange/boxes.ts b/packages/core/src/layout/arrange/boxes.tsindex 223b4b2d2..15d2e7ea8 100644--- a/packages/core/src/layout/arrange/boxes.ts+++ b/packages/core/src/layout/arrange/boxes.ts@@ -1,4 +1,5 @@import type { ElkExtendedEdge, ElkNode, ElkPort } from 'elkjs/lib/elk-api'+import { groupBy } from 'es-toolkit'import type { ConnectorSide } from '@open-pencil/scene-graph/connectors'import type { Rect, Size, Vector } from '@open-pencil/scene-graph/primitives'@@ -67,7 +68,7 @@ export interface ArrangedRoute {/*** 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.+ * sides its own edges leave and enter by, and other layouts leave edges to the connectors.*/export interface Arrangement {boxes: Map<string, Rect>@@ -149,6 +150,59 @@ function inputOrder(input: ArrangeInput): Map<string, number> {return order}+/**+ * The edges of a spanning forest of the boxes and groups, taken breadth first from those no edge+ * enters, in the input's order, then from the first still unreached: the tree a tree or radial layout+ * lays out. ELK's radial layout recurses without end on a loop, and a tree reads from its start;+ * the edges left out, such as one looping back, still join their boxes. Only edges within one+ * group count, as these layouts arrange each group on its own.+ */+function treeEdges(input: ArrangeInput): Set<string> {+ // A group laid out around its members is a node of its parent's layout, as a box is.+ const order = inputOrder(input)+ const members = [...input.groups, ...input.boxes].sort(+ (a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0)+ )+ const groupOf = new Map(members.map((member) => [member.id, member.group]))+ const edges = input.edges.filter(+ (edge) =>+ edge.from !== edge.to &&+ groupOf.has(edge.from) &&+ groupOf.has(edge.to) &&+ groupOf.get(edge.from) === groupOf.get(edge.to)+ )+ const outgoing = groupBy(edges, (edge) => edge.from)+ const entered = new Set(edges.map((edge) => edge.to))+ const starts = [+ ...members.filter((member) => !entered.has(member.id)),+ ...members.filter((member) => entered.has(member.id))+ ]+ const reached = new Set<string>()+ const tree = new Set<string>()+ for (const start of starts) {+ if (reached.has(start.id)) continue+ reached.add(start.id)+ const queue = [start.id]+ for (let at = queue.shift(); at !== undefined; at = queue.shift()) {+ // An id such as `constructor` must not read a property every object has.+ for (const edge of Object.hasOwn(outgoing, at) ? outgoing[at] : []) {+ if (reached.has(edge.to)) continue+ reached.add(edge.to)+ tree.add(edge.id)+ queue.push(edge.to)+ }+ }+ }+ return tree+}++/** The edges ELK lays out: a tree or radial layout's tree, every edge for the others. */+function laidOutEdges(input: ArrangeInput): ArrangeInput['edges'] {+ if (input.layout !== 'tree' && input.layout !== 'radial') return input.edges+ const tree = treeEdges(input)+ return input.edges.filter((edge) => tree.has(edge.id))+}+/** 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@@ -242,7 +296,7 @@ function elkGraph(input: ArrangeInput): ElkNode {const node = elk.get(member.id)if (node) container(member.group).children?.push(node)}- for (const edge of input.edges) {+ for (const edge of laidOutEdges(input)) {if (!elk.has(edge.from) || !elk.has(edge.to)) continueif (flow) {root.edges?.push({@@ -291,11 +345,13 @@ function collect(result: ElkNode, input: ArrangeInput): Arrangement {}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.+ // A tree runs one way, so its own edges leave and enter boxes by the sides a flow would, with+ // the connectors' own elbows between them. An edge outside the tree, such as one looping+ // back up, picks its sides itself rather than running the length of a branch.const [startSide, endSide] = FLOW_SIDES[input.direction ?? 'TB']+ const tree = treeEdges(input)for (const edge of input.edges) {- if (arrangement.boxes.has(edge.from) && arrangement.boxes.has(edge.to)) {+ if (tree.has(edge.id) && arrangement.boxes.has(edge.from) && arrangement.boxes.has(edge.to)) {arrangement.edges.set(edge.id, { startSide, endSide, points: [] })}}@@ -359,5 +415,11 @@ export async function arrangeBoxes(input: ArrangeInput): Promise<Arrangement> {const compacted = placedAt(input, spread)return collect(await layoutWithElk(elkGraph(compacted)), compacted)}+ if (input.layout === 'radial' || input.layout === 'network') {+ // These place boxes by their centres alone, so wide boxes can land on each other: pull them+ // apart afterwards, as a spread does, keeping each near where the layout put it.+ const placed = placedAt(input, await layoutWithElk(elkGraph(input)))+ return collect(await layoutWithElk(elkGraph({ ...placed, layout: 'spread' })), placed)+ }return collect(await layoutWithElk(elkGraph(input)), input)}diff --git a/packages/core/tests/layout/arrange/boxes.test.ts b/packages/core/tests/layout/arrange/boxes.test.tsindex ad46d0171..8146b37ff 100644--- a/packages/core/tests/layout/arrange/boxes.test.ts+++ b/packages/core/tests/layout/arrange/boxes.test.ts@@ -181,6 +181,82 @@ describe('arrangeBoxes', () => {expect(arrangement.edges.get('ra')).toEqual({ startSide: 'RIGHT', endSide: 'LEFT', points: [] })})+ test('tree leaves an edge outside the tree, such as one looping back, to pick its own sides', async () => {+ const arrangement = await arrangeBoxes({+ layout: 'tree',+ ...TREE,+ edges: [...TREE.edges, { id: 'cr', from: 'c', to: 'r' }, { id: 'bc', from: 'b', to: 'c' }]+ })+ expect([...arrangement.edges.keys()].sort()).toEqual(['ac', 'ra', 'rb'])+ })++ test('tree and radial lay out a looping diagram from the box nothing enters', async () => {+ // a → c and c → a loop below the root r, which nothing enters.+ const looping = { ...TREE, edges: [...TREE.edges, { id: 'ca', from: 'c', to: 'a' }] }+ const tree = await arrangeBoxes({ layout: 'tree', ...looping })+ const root = expectDefined(tree.boxes.get('r'))+ for (const id of ['a', 'b', 'c']) {+ expect(root.y + root.height).toBeLessThan(expectDefined(tree.boxes.get(id)).y)+ }+ const radial = await arrangeBoxes({ layout: 'radial', ...looping })+ const centre = (rect: Rect) => ({ x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 })+ const middle = centre(bounds([...radial.boxes.values()]))+ const distance = (id: string) => {+ const point = centre(expectDefined(radial.boxes.get(id)))+ return Math.hypot(point.x - middle.x, point.y - middle.y)+ }+ expect(distance('r')).toBeLessThan(distance('c'))+ })++ test('tree lays out an edge from a group to a box beside it', async () => {+ const arrangement = await arrangeBoxes({+ layout: 'tree',+ boxes: [box('inside', 0, 0, 'g'), box('below')],+ groups: [{ id: 'g' }],+ edges: [{ id: 'gb', from: 'g', to: 'below' }]+ })+ const group = expectDefined(arrangement.groups.get('g'))+ expect(group.y + group.height).toBeLessThan(expectDefined(arrangement.boxes.get('below')).y)+ })++ test('tree reads a box whose id names an object property', async () => {+ const arrangement = await arrangeBoxes({+ layout: 'tree',+ boxes: [box('root'), box('constructor')],+ groups: [],+ edges: [{ id: 'e', from: 'root', to: 'constructor' }]+ })+ expect(arrangement.boxes.size).toBe(2)+ })++ test('radial lays out a loop that every box is part of', async () => {+ const arrangement = await arrangeBoxes({+ layout: 'radial',+ boxes: [box('a'), box('b'), box('c')],+ groups: [],+ edges: [+ { id: 'ab', from: 'a', to: 'b' },+ { id: 'bc', from: 'b', to: 'c' },+ { id: 'ca', from: 'c', to: 'a' }+ ]+ })+ expect(arrangement.boxes.size).toBe(3)+ })++ test.each(['radial', 'network'] satisfies BoxLayout[])(+ '%s keeps wide boxes off each other',+ async (layout) => {+ const wide = (id: string): ArrangeBox => ({ ...box(id), width: 360 })+ const arrangement = await arrangeBoxes({+ layout,+ boxes: ['hub', 'a', 'b', 'c', 'd', 'e', 'f'].map(wide),+ groups: [],+ edges: ['a', 'b', 'c', 'd', 'e', 'f'].map((id) => ({ id, from: 'hub', to: id }))+ })+ expect(overlapping([...arrangement.boxes.values()])).toBe(false)+ }+ )+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 })