@opsydyn/foldkit-zloz-elk 0.3.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ - Qualify loose-mode requests through shared core validation with real-engine endpoint-identity tests.
6
+
7
+ - Reserve declared group headings through padding/minimum size, with qualified DOWN compound-minimum normalization and nested/empty group coverage.
8
+
9
+ - Reserve caller-declared composite edge-label bounds in compound layouts and return validated world-coordinate boxes, including custom badges on unlabeled edges.
10
+
11
+ ## [0.6.0](https://github.com/opsydyn/fold-kit-experiments/compare/foldkit-zloz-elk-v0.5.0...foldkit-zloz-elk-v0.6.0) (2026-11-16)
12
+
13
+ ### Features
14
+
15
+ - **zloz:** complete native v3 workflows and release qualification ([#151](https://github.com/opsydyn/fold-kit-experiments/issues/151)) ([629f7a3](https://github.com/opsydyn/fold-kit-experiments/commit/629f7a3824fe0751ca6ea816880ede1f5b4bb2ee))
16
+
17
+ ## [0.5.0](https://github.com/opsydyn/fold-kit-experiments/compare/foldkit-zloz-elk-v0.4.0...foldkit-zloz-elk-v0.5.0) (2026-11-15)
18
+
19
+ ### Miscellaneous Chores
20
+
21
+ - **foldkit-zloz-elk:** Synchronize foldkit-zloz versions
22
+
23
+ ## [0.4.0](https://github.com/opsydyn/fold-kit-experiments/compare/foldkit-zloz-elk-v0.3.0...foldkit-zloz-elk-v0.4.0) (2026-11-15)
24
+
25
+ ### Features
26
+
27
+ - **zloz:** add opt-in ELK descriptor preview layout ([26b4732](https://github.com/opsydyn/fold-kit-experiments/commit/26b47325c4538a6137a20736c49ce793addca61b))
28
+ - **zloz:** measure label bounds with stale-result protection ([b184bde](https://github.com/opsydyn/fold-kit-experiments/commit/b184bdea255264078a2c81127c34fefcb2f949b4))
29
+ - **zloz:** qualify v2 portable adapter boundaries ([e19efa7](https://github.com/opsydyn/fold-kit-experiments/commit/e19efa782bcd22424d62ea545fafa8770120a49c))
30
+ - **zloz:** reserve explicit layout label bounds ([ecc2284](https://github.com/opsydyn/fold-kit-experiments/commit/ecc22846fdf3d69efc29046a183109323eb795e4))
31
+ - **zloz:** reserve group heading layout bounds ([e67a3e1](https://github.com/opsydyn/fold-kit-experiments/commit/e67a3e1f37ab9fa4d25d45543bb61693f99e39c3))
32
+
3
33
  ## [0.3.0](https://github.com/opsydyn/fold-kit-experiments/compare/foldkit-zloz-elk-v0.2.0...foldkit-zloz-elk-v0.3.0) (2026-11-10)
4
34
 
5
35
  ### Miscellaneous Chores
package/README.md CHANGED
@@ -3,12 +3,10 @@
3
3
  Optional automatic layout for `@opsydyn/foldkit-zloz`. The adapter maps flat and nested graphs with fixed ports to ELK Layered. It returns node
4
4
  positions, fitted group bounds, and orthogonal edge routes. It owns no UI, persistence, graph state or workflow execution.
5
5
 
6
- Version 0.1.0 is a local release candidate; npm publication has not been performed.
6
+ The public package family is released together. The native v3 entry below is an unreleased addition to 0.5.0.
7
7
 
8
8
  ## Install and use
9
9
 
10
- After publication:
11
-
12
10
  ```sh
13
11
  npm install @opsydyn/foldkit-zloz @opsydyn/foldkit-zloz-elk
14
12
  ```
@@ -46,8 +44,7 @@ does not cancel ELK computation; request/revision checks prevent late publicatio
46
44
  See [ELK's worker documentation](https://github.com/kieler/elkjs#web-worker).
47
45
 
48
46
  ELK is an external dependency, not bundled into this package. The core package
49
- installs and works without it. Node 22+, ESM only. Initial compatibility is Zloz
50
- 0.1.0 and the pinned elkjs 0.12.1. Both Zloz packages release at the same version.
47
+ installs and works without it. Node 22+, ESM only. Compatibility uses the matching Zloz version and the pinned elkjs 0.12.1. Both Zloz packages release at the same version.
51
48
  The adapter has no FoldKit or Effect peer.
52
49
 
53
50
  The default adapter is qualified in Node and Chromium. Bun can compute layouts,
@@ -67,3 +64,91 @@ real layout plus the optional FoldKit renderer.
67
64
 
68
65
  See [publication standards](https://github.com/opsydyn/fold-kit-experiments/blob/main/docs/releases/foldkit-zloz.md) and
69
66
  [dependency notices](THIRD-PARTY-NOTICES.md).
67
+
68
+ ### Compound preview layouts (unreleased)
69
+
70
+ Configured `direction` and `spacing` now apply to root **and group parent**
71
+ containers. A real-engine regression retains at least the requested inter-layer
72
+ gap for RIGHT and DOWN inside a boundary; nested-boundary routes and custom anchors
73
+ remain tested. This corrects grouped children silently using ELK defaults.
74
+
75
+ For a detached read-only editor, compose `layoutRequest`, `createElkLayout` and
76
+ core's `applyPreviewLayout`; use `applyLayout` for normal undoable editing. The
77
+ workbench opts into ELK on explicit request, with direction controls, logical
78
+ cancellation, geometry-only restoration and preserved source/findings. See
79
+ [qualification](../../apps/zloz-demo/evidence/alchemy-layout.md). Label dimensions
80
+ are not yet supplied to ELK, so this is not a universal label-collision guarantee.
81
+
82
+ ### Custom label envelopes (unreleased)
83
+
84
+ Pass `layoutRequest(editor, id, { edgeLabels: [{ id: edgeId, size: { width: 176,
85
+ height: 36 } }] })` to reserve space for a composite label, including badges.
86
+ One envelope per existing edge is supported. ELK returns centered world-coordinate
87
+ boxes in `result.routes[*].label`; core validates and retains them on application.
88
+ Nested layouts use ROOT coordinates for both route points and labels. Unlabeled
89
+ custom content uses a private sizing token inside ELK, without changing graph text.
90
+ Omitting hints preserves the previous geometry-only behavior. Caller-supplied
91
+ engines must return the requested label IDs, dimensions and finite positions.
92
+ Supply sizes matching the actual renderer; arbitrary custom geometry, inaccurate
93
+ bounds and group headers are outside this space-reservation guarantee.
94
+
95
+ For intrinsic custom badges, core's `startLabelMeasurement`,
96
+ `updateLabelMeasurements` and `resolveLabelMeasurements` can supply the explicit
97
+ `edgeLabels` hints. The optional Foldkit view measures HTML border boxes only on
98
+ request. Recheck freshness before both starting ELK and applying its result; ELK
99
+ does not load fonts, inspect DOM or start measurement itself. See the
100
+ [core measured-label guide](../foldkit-zloz/README.md#opt-in-measured-label-bounds-unreleased).
101
+
102
+ ### Group heading envelopes (unreleased)
103
+
104
+ Core requests may declare `groupHeaders` with an existing group ID, header `size`,
105
+ `padding: { top, right, bottom, left }` and a `gap` before children. ELK maps these
106
+ to parent padding and a minimum group size, including empty groups and headings
107
+ wider than their content. Core rejects results that violate the reserved area.
108
+ Share the same declaration with C4/DDD `groupHeader` renderer options. Omitted
109
+ hints keep the existing 52/24/24/24 parent padding.
110
+
111
+ The pinned elkjs 0.12.1 adapter corrects transposed minima for nonempty DOWN groups;
112
+ empty groups use physical axes. Wide/tall nested/empty and cross-boundary-edge
113
+ regressions qualify both directions. Requalify the correction when upgrading ELK
114
+ or supplying a worker from another version. No post-layout stretching is used.
115
+ These hints reserve child-node space; they do not guarantee arbitrary route or
116
+ custom-artwork collision avoidance.
117
+
118
+ ## Native v3 group-port layout (unreleased)
119
+
120
+ Use the distinct full-document entry for authored group ports:
121
+
122
+ ```ts
123
+ import { groupLayoutRequestV3, applyGroupLayoutV3 } from '@opsydyn/foldkit-zloz';
124
+ import { createElkGroupLayoutV3 } from '@opsydyn/foldkit-zloz-elk';
125
+
126
+ const active = groupLayoutRequestV3(editorV3, 'arrange-v3-1');
127
+ // Store active in Model before executing this Promise in a Command.
128
+ const result = await createElkGroupLayoutV3({ direction: 'RIGHT' })(active);
129
+ // At completion, read the current editor, active request and live policy from Model.
130
+ const decision = applyGroupLayoutV3(currentEditor, currentActive, result, livePolicy);
131
+ ```
132
+
133
+ Both RIGHT and DOWN support nested rectangular groups, unused/authored group
134
+ ports, ancestor-to-descendant edges and crossing boundaries. Group port definitions,
135
+ custom anchors, identities, membership, metadata, modes, capabilities and camera
136
+ remain authored data. ELK changes world positions and group bounds; core validates
137
+ all nodes/routes, declared header/label envelopes and resize/extent constraints.
138
+ A stale source, lifecycle veto or protected move/resize blocks the entire result.
139
+ A changed layout appends one Undo frame; identical geometry appends none.
140
+
141
+ `applyGroupWorkbenchLayoutV3` integrates accepted routes into the native controller.
142
+ Its optional Foldkit view renders them only while the complete document matches,
143
+ no move/connection gesture is active and no collapsed projection is present.
144
+ Undo/editing invalidates routes; camera/selection do not author layout geometry.
145
+ Routes are transient, not serialized into authored edges. Authored waypoints keep
146
+ precedence. Engine interiors are orthogonal; connector leads join ELK's fixed
147
+ boundary points to the exact final authored anchors after group resizing, and
148
+ may be oblique. This is not an obstacle/collision guarantee for arbitrary custom
149
+ content. Fixed-position compound ports are qualified with elkjs 0.12.1; its
150
+ FIXED_RATIO path failed on the nested regression and is not used.
151
+
152
+ Logical cancellation and supersession ignore late results; they do not terminate
153
+ ELK computation. Worker ownership and the Node/Bun qualification limits above
154
+ also apply to the native entry. V1/v2 `createElkLayout` still rejects group ports.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { LayoutEngine } from "@opsydyn/foldkit-zloz";
1
+ import { LayoutEngine, ZlozGroupLayoutEngineV3 } from "@opsydyn/foldkit-zloz";
2
2
  import { ELK } from "elkjs/lib/elk-api.js";
3
3
 
4
4
  //#region src/index.d.ts
@@ -7,8 +7,10 @@ type ElkLayoutOptions = Readonly<{
7
7
  spacing?: number; /** Supply a worker-backed instance when needed; the caller owns its lifetime. */
8
8
  elk?: Pick<ELK, 'layout'>;
9
9
  }>;
10
- /** Default invocations use in-process ELK. Caller-supplied worker instances remain caller-owned. */
10
+ /** Legacy graph layout. Group ports require the distinct native v3 entry. */
11
11
  declare function createElkLayout(options?: ElkLayoutOptions): LayoutEngine;
12
+ /** Native v3 compound layout; preserves authored group ports and their endpoint identities. */
13
+ declare function createElkGroupLayoutV3(options?: ElkLayoutOptions): ZlozGroupLayoutEngineV3;
12
14
  //#endregion
13
- export { ElkLayoutOptions, createElkLayout };
15
+ export { ElkLayoutOptions, createElkGroupLayoutV3, createElkLayout };
14
16
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { ZlozError, portBoundaryPosition, portPosition, validateGraph } from "@opsydyn/foldkit-zloz";
1
+ import { ZlozError, portBoundaryPosition, portPosition, resolveLayoutGroupHeader, validateGroupLayoutRequestV3, validateLayoutRequest } from "@opsydyn/foldkit-zloz";
2
2
  import ELK from "elkjs/lib/elk.bundled.js";
3
3
  //#region src/index.ts
4
4
  /**
@@ -29,47 +29,75 @@ function routePoints(sections, edgeId) {
29
29
  throw new ZlozError("invalid-layout", `ELK omitted a continuous route for ${edgeId}`);
30
30
  }
31
31
  /** Default invocations use in-process ELK. Caller-supplied worker instances remain caller-owned. */
32
- function createElkLayout(options = {}) {
32
+ function elkLayout(options, nativeV3) {
33
33
  const spacing = options.spacing ?? 64;
34
34
  if (!Number.isFinite(spacing) || spacing <= 0) throw new ZlozError("invalid-layout", "Layout spacing must be positive and finite");
35
35
  return async (request) => {
36
- validateGraph(request.graph);
36
+ if (!nativeV3) validateLayoutRequest(request);
37
+ const labelHints = new Map((request.edgeLabels ?? []).map((label) => [label.id, label]));
38
+ const groupHeaders = new Map((request.groupHeaders ?? []).map((header) => [header.id, header]));
37
39
  const nodeIds = new Map(request.graph.nodes.map((node, index) => [node.id, `n:${index}`]));
38
40
  const portIds = /* @__PURE__ */ new Map();
39
41
  const hasGroups = request.graph.nodes.some((node) => node.kind === "group");
42
+ const layoutOptions = {
43
+ "elk.algorithm": "layered",
44
+ "elk.direction": options.direction ?? "RIGHT",
45
+ "elk.edgeRouting": "ORTHOGONAL",
46
+ "elk.spacing.nodeNode": String(spacing),
47
+ "elk.layered.spacing.nodeNodeBetweenLayers": String(spacing)
48
+ };
40
49
  const children = [];
41
50
  const elkNodes = new Map(request.graph.nodes.map((node, index) => {
42
- if (node.kind === "group") return [node.id, {
43
- id: `n:${index}`,
44
- width: node.size.width,
45
- height: node.size.height,
46
- children: [],
47
- layoutOptions: { "elk.padding": "[top=52,left=24,bottom=24,right=24]" }
48
- }];
49
51
  const ports = new Map(node.ports.map((port, at) => [port.id, `p:${index}:${at}`]));
50
52
  portIds.set(node.id, ports);
53
+ const elkPorts = node.ports.map((port) => {
54
+ const point = portBoundaryPosition(node, port.id);
55
+ return {
56
+ id: ports.get(port.id) ?? "",
57
+ width: 0,
58
+ height: 0,
59
+ x: point.x - node.position.x,
60
+ y: point.y - node.position.y,
61
+ layoutOptions: { "elk.port.side": {
62
+ left: "WEST",
63
+ right: "EAST",
64
+ top: "NORTH",
65
+ bottom: "SOUTH"
66
+ }[port.side] }
67
+ };
68
+ });
69
+ if (node.kind === "group") {
70
+ const hint = groupHeaders.get(node.id);
71
+ const header = hint ? resolveLayoutGroupHeader(node, hint) : void 0;
72
+ const groupOptions = {
73
+ ...layoutOptions,
74
+ "elk.padding": "[top=52,left=24,bottom=24,right=24]"
75
+ };
76
+ if (nativeV3) groupOptions["elk.portConstraints"] = "FIXED_POS";
77
+ if (header) {
78
+ const p = header.contentPadding;
79
+ groupOptions["elk.padding"] = `[top=${p.top},left=${p.left},bottom=${p.bottom},right=${p.right}]`;
80
+ groupOptions["elk.nodeSize.constraints"] = "MINIMUM_SIZE";
81
+ const transposed = options.direction === "DOWN" && request.graph.nodes.some((child) => child.parentId === node.id);
82
+ const minimum = header.minimumSize;
83
+ groupOptions["elk.nodeSize.minimum"] = transposed ? `(${minimum.height},${minimum.width})` : `(${minimum.width},${minimum.height})`;
84
+ }
85
+ const group = {
86
+ id: `n:${index}`,
87
+ width: node.size.width,
88
+ height: node.size.height,
89
+ children: [],
90
+ layoutOptions: groupOptions
91
+ };
92
+ if (nativeV3) group.ports = elkPorts;
93
+ return [node.id, group];
94
+ }
51
95
  return [node.id, {
52
96
  id: `n:${index}`,
53
97
  width: node.size.width,
54
98
  height: node.size.height,
55
99
  layoutOptions: { "elk.portConstraints": "FIXED_POS" },
56
- ports: node.ports.map((port) => {
57
- const point = portBoundaryPosition(node, port.id);
58
- const side = {
59
- left: "WEST",
60
- right: "EAST",
61
- top: "NORTH",
62
- bottom: "SOUTH"
63
- }[port.side];
64
- return {
65
- id: ports.get(port.id) ?? "",
66
- width: 0,
67
- height: 0,
68
- x: point.x - node.position.x,
69
- y: point.y - node.position.y,
70
- layoutOptions: { "elk.port.side": side }
71
- };
72
- })
100
+ ports: elkPorts
73
101
  }];
74
102
  }));
75
103
  for (const node of request.graph.nodes) {
@@ -82,31 +110,44 @@ function createElkLayout(options = {}) {
82
110
  const graph = {
83
111
  id: "graph",
84
112
  layoutOptions: {
85
- "elk.algorithm": "layered",
113
+ ...layoutOptions,
86
114
  "elk.hierarchyHandling": hasGroups ? "INCLUDE_CHILDREN" : "SEPARATE_CHILDREN",
87
115
  "elk.json.shapeCoords": "ROOT",
88
- "elk.json.edgeCoords": "ROOT",
89
- "elk.direction": options.direction ?? "RIGHT",
90
- "elk.edgeRouting": "ORTHOGONAL",
91
- "elk.spacing.nodeNode": String(spacing),
92
- "elk.layered.spacing.nodeNodeBetweenLayers": String(spacing)
116
+ "elk.json.edgeCoords": "ROOT"
93
117
  },
94
118
  children,
95
- edges: request.graph.edges.map((edge, index) => ({
96
- id: `e:${index}`,
97
- sources: [portIds.get(edge.source.node)?.get(edge.source.port) ?? ""],
98
- targets: [portIds.get(edge.target.node)?.get(edge.target.port) ?? ""]
99
- }))
119
+ edges: request.graph.edges.map((edge, index) => {
120
+ const base = {
121
+ id: `e:${index}`,
122
+ sources: [portIds.get(edge.source.node)?.get(edge.source.port) ?? ""],
123
+ targets: [portIds.get(edge.target.node)?.get(edge.target.port) ?? ""]
124
+ };
125
+ const hint = labelHints.get(edge.id);
126
+ return hint ? {
127
+ ...base,
128
+ labels: [{
129
+ id: `l:${index}`,
130
+ text: edge.label?.trim() || "label",
131
+ width: hint.size.width,
132
+ height: hint.size.height,
133
+ layoutOptions: { "elk.edgeLabels.placement": "CENTER" }
134
+ }]
135
+ } : base;
136
+ })
100
137
  };
101
138
  const result = await (options.elk ?? new ELK()).layout(graph);
102
139
  const laidOutNodes = /* @__PURE__ */ new Map();
103
140
  const laidOutEdges = /* @__PURE__ */ new Map();
141
+ const laidOutLabels = /* @__PURE__ */ new Map();
104
142
  const pending = [result];
105
143
  while (pending.length > 0) {
106
144
  const node = pending.pop();
107
145
  if (!node) break;
108
146
  laidOutNodes.set(node.id, node);
109
- for (const edge of node.edges ?? []) laidOutEdges.set(edge.id, edge.sections ?? []);
147
+ for (const edge of node.edges ?? []) {
148
+ laidOutEdges.set(edge.id, edge.sections ?? []);
149
+ laidOutLabels.set(edge.id, edge.labels ?? []);
150
+ }
110
151
  for (const child of node.children ?? []) pending.push(child);
111
152
  }
112
153
  const positions = request.graph.nodes.map((node) => {
@@ -139,21 +180,37 @@ function createElkLayout(options = {}) {
139
180
  const anchored = [
140
181
  portPosition({
141
182
  ...sourceNode,
142
- position: sourcePosition
183
+ position: sourcePosition,
184
+ size: sourcePosition.size ?? sourceNode.size
143
185
  }, edge.source.port),
144
186
  ...points,
145
187
  portPosition({
146
188
  ...targetNode,
147
- position: targetPosition
189
+ position: targetPosition,
190
+ size: targetPosition.size ?? targetNode.size
148
191
  }, edge.target.port)
149
192
  ];
150
- return {
193
+ const route = {
151
194
  id: edge.id,
152
195
  points: anchored.filter((point, index) => {
153
196
  const previous = anchored[index - 1];
154
197
  return !previous || previous.x !== point.x || previous.y !== point.y;
155
198
  })
156
199
  };
200
+ const hint = labelHints.get(edge.id);
201
+ if (!hint) return route;
202
+ const labels = laidOutLabels.get(`e:${index}`) ?? [], label = labels[0];
203
+ if (labels.length !== 1 || !label || label.id !== `l:${index}` || label.x === void 0 || label.y === void 0 || !Number.isFinite(label.x) || !Number.isFinite(label.y) || label.width !== hint.size.width || label.height !== hint.size.height) throw new ZlozError("invalid-layout", `ELK omitted a valid label box for ${edge.id}`);
204
+ return {
205
+ ...route,
206
+ label: {
207
+ position: {
208
+ x: label.x + hint.size.width / 2,
209
+ y: label.y + hint.size.height / 2
210
+ },
211
+ size: { ...hint.size }
212
+ }
213
+ };
157
214
  });
158
215
  return {
159
216
  requestId: request.requestId,
@@ -163,7 +220,29 @@ function createElkLayout(options = {}) {
163
220
  };
164
221
  };
165
222
  }
223
+ /** Legacy graph layout. Group ports require the distinct native v3 entry. */
224
+ function createElkLayout(options = {}) {
225
+ return elkLayout(options, false);
226
+ }
227
+ /** Native v3 compound layout; preserves authored group ports and their endpoint identities. */
228
+ function createElkGroupLayoutV3(options = {}) {
229
+ const engine = elkLayout(options, true);
230
+ return async (request) => {
231
+ validateGroupLayoutRequestV3(request);
232
+ const document = request.source.document;
233
+ return {
234
+ ...await engine({
235
+ ...request.options,
236
+ requestId: request.requestId,
237
+ revision: request.source.revision,
238
+ graph: document.graph,
239
+ connectionMode: document.connectionMode
240
+ }),
241
+ version: 3
242
+ };
243
+ };
244
+ }
166
245
  //#endregion
167
- export { createElkLayout };
246
+ export { createElkGroupLayoutV3, createElkLayout };
168
247
 
169
248
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Optional ELK layout adapter; the host owns request publication and worker lifetime.\n * @module ELK\n */\nimport {\n ZlozError,\n portPosition,\n portBoundaryPosition,\n validateGraph,\n type EdgeRoute,\n type LayoutEngine,\n} from '@opsydyn/foldkit-zloz';\nimport type { ELK as ElkInstance, ElkNode, ElkEdgeSection } from 'elkjs/lib/elk-api';\nimport ELK from 'elkjs/lib/elk.bundled.js';\n\nexport type ElkLayoutOptions = Readonly<{\n direction?: 'RIGHT' | 'DOWN';\n spacing?: number;\n /** Supply a worker-backed instance when needed; the caller owns its lifetime. */\n elk?: Pick<ElkInstance, 'layout'>;\n}>;\n\nfunction routePoints(sections: readonly ElkEdgeSection[], edgeId: string): EdgeRoute['points'] {\n const byId = new Map(sections.map((section) => [section.id, section]));\n const visited = new Set<string>();\n const points: Array<{ x: number; y: number }> = [];\n let current = sections.find((section) => !section.incomingSections?.length);\n while (current && !visited.has(current.id)) {\n visited.add(current.id);\n const previous = points.at(-1);\n if (\n previous &&\n (Math.abs(previous.x - current.startPoint.x) > 1e-6 ||\n Math.abs(previous.y - current.startPoint.y) > 1e-6)\n )\n break;\n if (!previous) points.push(current.startPoint);\n for (const bend of current.bendPoints ?? []) points.push(bend);\n points.push(current.endPoint);\n const outgoing = current.outgoingSections ?? [];\n if (outgoing.length === 0 && visited.size === sections.length)\n return points.map(({ x, y }) => ({ x, y }));\n const next = outgoing[0];\n if (outgoing.length !== 1 || next === undefined) break;\n current = byId.get(next);\n }\n throw new ZlozError('invalid-layout', `ELK omitted a continuous route for ${edgeId}`);\n}\n\n/** Default invocations use in-process ELK. Caller-supplied worker instances remain caller-owned. */\nexport function createElkLayout(options: ElkLayoutOptions = {}): LayoutEngine {\n const spacing = options.spacing ?? 64;\n if (!Number.isFinite(spacing) || spacing <= 0)\n throw new ZlozError('invalid-layout', 'Layout spacing must be positive and finite');\n return async (request) => {\n validateGraph(request.graph);\n const nodeIds = new Map(request.graph.nodes.map((node, index) => [node.id, `n:${index}`]));\n const portIds = new Map<string, Map<string, string>>();\n const hasGroups = request.graph.nodes.some((node) => node.kind === 'group');\n const children: ElkNode[] = [];\n const elkNodes = new Map(\n request.graph.nodes.map((node, index): [string, ElkNode] => {\n if (node.kind === 'group')\n return [\n node.id,\n {\n id: `n:${index}`,\n width: node.size.width,\n height: node.size.height,\n children: [],\n layoutOptions: { 'elk.padding': '[top=52,left=24,bottom=24,right=24]' },\n },\n ];\n const ports = new Map(node.ports.map((port, at) => [port.id, `p:${index}:${at}`]));\n portIds.set(node.id, ports);\n return [\n node.id,\n {\n id: `n:${index}`,\n width: node.size.width,\n height: node.size.height,\n layoutOptions: { 'elk.portConstraints': 'FIXED_POS' },\n ports: node.ports.map((port) => {\n const point = portBoundaryPosition(node, port.id);\n const side = { left: 'WEST', right: 'EAST', top: 'NORTH', bottom: 'SOUTH' }[\n port.side\n ];\n return {\n id: ports.get(port.id) ?? '',\n width: 0,\n height: 0,\n x: point.x - node.position.x,\n y: point.y - node.position.y,\n layoutOptions: { 'elk.port.side': side },\n };\n }),\n },\n ];\n }),\n );\n for (const node of request.graph.nodes) {\n const elkNode = elkNodes.get(node.id);\n if (!elkNode) throw new ZlozError('invalid-layout', `Missing input elkNode for ${node.id}`);\n const siblings =\n node.parentId === undefined ? children : elkNodes.get(node.parentId)?.children;\n if (!siblings) throw new ZlozError('invalid-layout', `Missing parent elkNode for ${node.id}`);\n siblings.push(elkNode);\n }\n const graph: ElkNode = {\n id: 'graph',\n layoutOptions: {\n 'elk.algorithm': 'layered',\n 'elk.hierarchyHandling': hasGroups ? 'INCLUDE_CHILDREN' : 'SEPARATE_CHILDREN',\n 'elk.json.shapeCoords': 'ROOT',\n 'elk.json.edgeCoords': 'ROOT',\n 'elk.direction': options.direction ?? 'RIGHT',\n 'elk.edgeRouting': 'ORTHOGONAL',\n 'elk.spacing.nodeNode': String(spacing),\n 'elk.layered.spacing.nodeNodeBetweenLayers': String(spacing),\n },\n children,\n edges: request.graph.edges.map((edge, index) => ({\n id: `e:${index}`,\n sources: [portIds.get(edge.source.node)?.get(edge.source.port) ?? ''],\n targets: [portIds.get(edge.target.node)?.get(edge.target.port) ?? ''],\n })),\n };\n const elk = options.elk ?? new ELK();\n const result = await elk.layout(graph);\n const laidOutNodes = new Map<string, ElkNode>();\n const laidOutEdges = new Map<string, ElkEdgeSection[]>();\n const pending = [result];\n while (pending.length > 0) {\n const node = pending.pop();\n if (!node) break;\n laidOutNodes.set(node.id, node);\n for (const edge of node.edges ?? []) laidOutEdges.set(edge.id, edge.sections ?? []);\n for (const child of node.children ?? []) pending.push(child);\n }\n const positions = request.graph.nodes.map((node) => {\n const laidOut = laidOutNodes.get(nodeIds.get(node.id) ?? '');\n if (\n !laidOut ||\n !Number.isFinite(laidOut.x) ||\n !Number.isFinite(laidOut.y) ||\n laidOut.x === undefined ||\n laidOut.y === undefined\n )\n throw new ZlozError('invalid-layout', `ELK omitted position for ${node.id}`);\n const position = { id: node.id, x: laidOut.x, y: laidOut.y };\n if (node.kind !== 'group') return position;\n const { width, height } = laidOut;\n if (\n width === undefined ||\n height === undefined ||\n !Number.isFinite(width) ||\n !Number.isFinite(height) ||\n width <= 0 ||\n height <= 0\n )\n throw new ZlozError('invalid-layout', `ELK returned invalid bounds for ${node.id}`);\n return { ...position, size: { width, height } };\n });\n const routes: EdgeRoute[] = request.graph.edges.map((edge, index) => {\n const sections = laidOutEdges.get(`e:${index}`) ?? [];\n const points = routePoints(sections, edge.id);\n if (!points.every((point) => Number.isFinite(point.x) && Number.isFinite(point.y)))\n throw new ZlozError('invalid-layout', `ELK returned an invalid route for ${edge.id}`);\n const sourceNode = request.graph.nodes.find((node) => node.id === edge.source.node);\n const targetNode = request.graph.nodes.find((node) => node.id === edge.target.node);\n const sourcePosition = positions.find((position) => position.id === edge.source.node);\n const targetPosition = positions.find((position) => position.id === edge.target.node);\n if (!sourceNode || !targetNode || !sourcePosition || !targetPosition)\n throw new ZlozError('invalid-layout', 'Missing routed endpoint');\n const anchored = [\n portPosition({ ...sourceNode, position: sourcePosition }, edge.source.port),\n ...points,\n portPosition({ ...targetNode, position: targetPosition }, edge.target.port),\n ];\n return {\n id: edge.id,\n points: anchored.filter((point, index) => {\n const previous = anchored[index - 1];\n return !previous || previous.x !== point.x || previous.y !== point.y;\n }),\n };\n });\n return { requestId: request.requestId, revision: request.revision, positions, routes };\n };\n}\n"],"mappings":";;;;;;;AAsBA,SAAS,YAAY,UAAqC,QAAqC;CAC7F,MAAM,OAAO,IAAI,IAAI,SAAS,KAAK,YAAY,CAAC,QAAQ,IAAI,QAAQ,CAAC,CAAC;CACtE,MAAM,0BAAU,IAAI,KAAa;CACjC,MAAM,SAA0C,EAAE;CAClD,IAAI,UAAU,SAAS,MAAM,YAAY,CAAC,QAAQ,kBAAkB,OAAO;AAC3E,QAAO,WAAW,CAAC,QAAQ,IAAI,QAAQ,GAAG,EAAE;AAC1C,UAAQ,IAAI,QAAQ,GAAG;EACvB,MAAM,WAAW,OAAO,GAAG,GAAG;AAC9B,MACE,aACC,KAAK,IAAI,SAAS,IAAI,QAAQ,WAAW,EAAE,GAAG,QAC7C,KAAK,IAAI,SAAS,IAAI,QAAQ,WAAW,EAAE,GAAG,MAEhD;AACF,MAAI,CAAC,SAAU,QAAO,KAAK,QAAQ,WAAW;AAC9C,OAA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layout adapter; the host owns request publication and worker lifetime.\n * @module ELK\n */\nimport {\n ZlozError,\n portPosition,\n portBoundaryPosition,\n validateLayoutRequest,\n resolveLayoutGroupHeader,\n type EdgeRoute,\n type LayoutEngine,\n validateGroupLayoutRequestV3,\n type ZlozGroupLayoutEngineV3,\n type LayoutRequest,\n type LayoutResult,\n} from '@opsydyn/foldkit-zloz';\nimport type {\n ELK as ElkInstance,\n ElkNode,\n ElkEdgeSection,\n ElkLabel,\n LayoutOptions as ElkLayoutProperties,\n} from 'elkjs/lib/elk-api';\nimport ELK from 'elkjs/lib/elk.bundled.js';\n\nexport type ElkLayoutOptions = Readonly<{\n direction?: 'RIGHT' | 'DOWN';\n spacing?: number;\n /** Supply a worker-backed instance when needed; the caller owns its lifetime. */\n elk?: Pick<ElkInstance, 'layout'>;\n}>;\n\nfunction routePoints(sections: readonly ElkEdgeSection[], edgeId: string): EdgeRoute['points'] {\n const byId = new Map(sections.map((section) => [section.id, section]));\n const visited = new Set<string>();\n const points: Array<{ x: number; y: number }> = [];\n let current = sections.find((section) => !section.incomingSections?.length);\n while (current && !visited.has(current.id)) {\n visited.add(current.id);\n const previous = points.at(-1);\n if (\n previous &&\n (Math.abs(previous.x - current.startPoint.x) > 1e-6 ||\n Math.abs(previous.y - current.startPoint.y) > 1e-6)\n )\n break;\n if (!previous) points.push(current.startPoint);\n for (const bend of current.bendPoints ?? []) points.push(bend);\n points.push(current.endPoint);\n const outgoing = current.outgoingSections ?? [];\n if (outgoing.length === 0 && visited.size === sections.length)\n return points.map(({ x, y }) => ({ x, y }));\n const next = outgoing[0];\n if (outgoing.length !== 1 || next === undefined) break;\n current = byId.get(next);\n }\n throw new ZlozError('invalid-layout', `ELK omitted a continuous route for ${edgeId}`);\n}\n\n/** Default invocations use in-process ELK. Caller-supplied worker instances remain caller-owned. */\nfunction elkLayout(options: ElkLayoutOptions, nativeV3: boolean): LayoutEngine {\n const spacing = options.spacing ?? 64;\n if (!Number.isFinite(spacing) || spacing <= 0)\n throw new ZlozError('invalid-layout', 'Layout spacing must be positive and finite');\n return async (request) => {\n if (!nativeV3) validateLayoutRequest(request);\n const labelHints = new Map((request.edgeLabels ?? []).map((label) => [label.id, label]));\n const groupHeaders = new Map((request.groupHeaders ?? []).map((header) => [header.id, header]));\n const nodeIds = new Map(request.graph.nodes.map((node, index) => [node.id, `n:${index}`]));\n const portIds = new Map<string, Map<string, string>>();\n const hasGroups = request.graph.nodes.some((node) => node.kind === 'group');\n const layoutOptions = {\n 'elk.algorithm': 'layered',\n 'elk.direction': options.direction ?? 'RIGHT',\n 'elk.edgeRouting': 'ORTHOGONAL',\n 'elk.spacing.nodeNode': String(spacing),\n 'elk.layered.spacing.nodeNodeBetweenLayers': String(spacing),\n } as const;\n const children: ElkNode[] = [];\n const elkNodes = new Map(\n request.graph.nodes.map((node, index): [string, ElkNode] => {\n const ports = new Map(node.ports.map((port, at) => [port.id, `p:${index}:${at}`]));\n portIds.set(node.id, ports);\n const elkPorts = node.ports.map((port) => {\n const point = portBoundaryPosition(node, port.id);\n return {\n id: ports.get(port.id) ?? '',\n width: 0,\n height: 0,\n x: point.x - node.position.x,\n y: point.y - node.position.y,\n layoutOptions: {\n 'elk.port.side': { left: 'WEST', right: 'EAST', top: 'NORTH', bottom: 'SOUTH' }[\n port.side\n ],\n },\n };\n });\n if (node.kind === 'group') {\n const hint = groupHeaders.get(node.id);\n const header = hint ? resolveLayoutGroupHeader(node, hint) : undefined;\n const groupOptions: ElkLayoutProperties = {\n ...layoutOptions,\n 'elk.padding': '[top=52,left=24,bottom=24,right=24]',\n };\n if (nativeV3) groupOptions['elk.portConstraints'] = 'FIXED_POS';\n if (header) {\n const p = header.contentPadding;\n groupOptions['elk.padding'] =\n `[top=${p.top},left=${p.left},bottom=${p.bottom},right=${p.right}]`;\n groupOptions['elk.nodeSize.constraints'] = 'MINIMUM_SIZE';\n // ELK 0.12.1 transposes compound graph minima in DOWN, but leaf/empty group minima remain physical.\n // Keep this correction behind the adapter; nested/empty, wide/tall real-engine regressions qualify upgrades.\n const transposed =\n options.direction === 'DOWN' &&\n request.graph.nodes.some((child) => child.parentId === node.id);\n const minimum = header.minimumSize;\n groupOptions['elk.nodeSize.minimum'] = transposed\n ? `(${minimum.height},${minimum.width})`\n : `(${minimum.width},${minimum.height})`;\n }\n const group: ElkNode = {\n id: `n:${index}`,\n width: node.size.width,\n height: node.size.height,\n children: [],\n layoutOptions: groupOptions,\n };\n if (nativeV3) group.ports = elkPorts;\n return [node.id, group];\n }\n return [\n node.id,\n {\n id: `n:${index}`,\n width: node.size.width,\n height: node.size.height,\n layoutOptions: { 'elk.portConstraints': 'FIXED_POS' },\n ports: elkPorts,\n },\n ];\n }),\n );\n for (const node of request.graph.nodes) {\n const elkNode = elkNodes.get(node.id);\n if (!elkNode) throw new ZlozError('invalid-layout', `Missing input elkNode for ${node.id}`);\n const siblings =\n node.parentId === undefined ? children : elkNodes.get(node.parentId)?.children;\n if (!siblings) throw new ZlozError('invalid-layout', `Missing parent elkNode for ${node.id}`);\n siblings.push(elkNode);\n }\n const graph: ElkNode = {\n id: 'graph',\n layoutOptions: {\n ...layoutOptions,\n 'elk.hierarchyHandling': hasGroups ? 'INCLUDE_CHILDREN' : 'SEPARATE_CHILDREN',\n 'elk.json.shapeCoords': 'ROOT',\n 'elk.json.edgeCoords': 'ROOT',\n },\n children,\n edges: request.graph.edges.map((edge, index) => {\n const base = {\n id: `e:${index}`,\n sources: [portIds.get(edge.source.node)?.get(edge.source.port) ?? ''],\n targets: [portIds.get(edge.target.node)?.get(edge.target.port) ?? ''],\n };\n const hint = labelHints.get(edge.id);\n return hint\n ? {\n ...base,\n labels: [\n {\n id: `l:${index}`,\n text: edge.label?.trim() || 'label',\n width: hint.size.width,\n height: hint.size.height,\n layoutOptions: { 'elk.edgeLabels.placement': 'CENTER' },\n },\n ],\n }\n : base;\n }),\n };\n const elk = options.elk ?? new ELK();\n const result = await elk.layout(graph);\n const laidOutNodes = new Map<string, ElkNode>();\n const laidOutEdges = new Map<string, ElkEdgeSection[]>();\n const laidOutLabels = new Map<string, readonly ElkLabel[]>();\n const pending = [result];\n while (pending.length > 0) {\n const node = pending.pop();\n if (!node) break;\n laidOutNodes.set(node.id, node);\n for (const edge of node.edges ?? []) {\n laidOutEdges.set(edge.id, edge.sections ?? []);\n laidOutLabels.set(edge.id, edge.labels ?? []);\n }\n for (const child of node.children ?? []) pending.push(child);\n }\n const positions: LayoutResult['positions'] = request.graph.nodes.map((node) => {\n const laidOut = laidOutNodes.get(nodeIds.get(node.id) ?? '');\n if (\n !laidOut ||\n !Number.isFinite(laidOut.x) ||\n !Number.isFinite(laidOut.y) ||\n laidOut.x === undefined ||\n laidOut.y === undefined\n )\n throw new ZlozError('invalid-layout', `ELK omitted position for ${node.id}`);\n const position = { id: node.id, x: laidOut.x, y: laidOut.y };\n if (node.kind !== 'group') return position;\n const { width, height } = laidOut;\n if (\n width === undefined ||\n height === undefined ||\n !Number.isFinite(width) ||\n !Number.isFinite(height) ||\n width <= 0 ||\n height <= 0\n )\n throw new ZlozError('invalid-layout', `ELK returned invalid bounds for ${node.id}`);\n return { ...position, size: { width, height } };\n });\n const routes: EdgeRoute[] = request.graph.edges.map((edge, index) => {\n const sections = laidOutEdges.get(`e:${index}`) ?? [];\n const points = routePoints(sections, edge.id);\n if (!points.every((point) => Number.isFinite(point.x) && Number.isFinite(point.y)))\n throw new ZlozError('invalid-layout', `ELK returned an invalid route for ${edge.id}`);\n const sourceNode = request.graph.nodes.find((node) => node.id === edge.source.node);\n const targetNode = request.graph.nodes.find((node) => node.id === edge.target.node);\n const sourcePosition = positions.find((position) => position.id === edge.source.node);\n const targetPosition = positions.find((position) => position.id === edge.target.node);\n if (!sourceNode || !targetNode || !sourcePosition || !targetPosition)\n throw new ZlozError('invalid-layout', 'Missing routed endpoint');\n const anchored = [\n portPosition(\n { ...sourceNode, position: sourcePosition, size: sourcePosition.size ?? sourceNode.size },\n edge.source.port,\n ),\n ...points,\n portPosition(\n { ...targetNode, position: targetPosition, size: targetPosition.size ?? targetNode.size },\n edge.target.port,\n ),\n ];\n const route = {\n id: edge.id,\n points: anchored.filter((point, index) => {\n const previous = anchored[index - 1];\n return !previous || previous.x !== point.x || previous.y !== point.y;\n }),\n };\n const hint = labelHints.get(edge.id);\n if (!hint) return route;\n const labels = laidOutLabels.get(`e:${index}`) ?? [],\n label = labels[0];\n if (\n labels.length !== 1 ||\n !label ||\n label.id !== `l:${index}` ||\n label.x === undefined ||\n label.y === undefined ||\n !Number.isFinite(label.x) ||\n !Number.isFinite(label.y) ||\n label.width !== hint.size.width ||\n label.height !== hint.size.height\n )\n throw new ZlozError('invalid-layout', `ELK omitted a valid label box for ${edge.id}`);\n return {\n ...route,\n label: {\n position: { x: label.x + hint.size.width / 2, y: label.y + hint.size.height / 2 },\n size: { ...hint.size },\n },\n };\n });\n return { requestId: request.requestId, revision: request.revision, positions, routes };\n };\n}\n\n/** Legacy graph layout. Group ports require the distinct native v3 entry. */\nexport function createElkLayout(options: ElkLayoutOptions = {}): LayoutEngine {\n return elkLayout(options, false);\n}\n/** Native v3 compound layout; preserves authored group ports and their endpoint identities. */\nexport function createElkGroupLayoutV3(options: ElkLayoutOptions = {}): ZlozGroupLayoutEngineV3 {\n const engine = elkLayout(options, true);\n return async (request) => {\n validateGroupLayoutRequestV3(request);\n const document = request.source.document;\n // This internal geometry input never crosses a legacy validation/publication boundary.\n const geometry: LayoutRequest = {\n ...request.options,\n requestId: request.requestId,\n revision: request.source.revision,\n graph: document.graph,\n connectionMode: document.connectionMode,\n };\n return { ...(await engine(geometry)), version: 3 };\n };\n}\n"],"mappings":";;;;;;;AAiCA,SAAS,YAAY,UAAqC,QAAqC;CAC7F,MAAM,OAAO,IAAI,IAAI,SAAS,KAAK,YAAY,CAAC,QAAQ,IAAI,QAAQ,CAAC,CAAC;CACtE,MAAM,0BAAU,IAAI,KAAa;CACjC,MAAM,SAA0C,EAAE;CAClD,IAAI,UAAU,SAAS,MAAM,YAAY,CAAC,QAAQ,kB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AQ;IACnB,UAAU,QAAQ,OAAO;IACzB,OAAO,SAAS;IAChB,gBAAgB,SAAS;IAEO,CAAC;GAAG,SAAS;GAAG"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opsydyn/foldkit-zloz-elk",
3
- "version": "0.3.0",
3
+ "version": "0.6.0",
4
4
  "description": "Optional ELK layout adapter for Foldkit Zloz.",
5
5
  "keywords": [
6
6
  "diagram",
@@ -53,7 +53,7 @@
53
53
  },
54
54
  "devDependencies": {
55
55
  "@arethetypeswrong/cli": "0.18.5",
56
- "@opsydyn/foldkit-zloz": "0.3.0",
56
+ "@opsydyn/foldkit-zloz": "0.6.0",
57
57
  "@types/node": "^22.0.0",
58
58
  "bun-types": "^1.3.14",
59
59
  "publint": "0.3.25",
@@ -61,7 +61,7 @@
61
61
  "typescript": "^6.0.3"
62
62
  },
63
63
  "peerDependencies": {
64
- "@opsydyn/foldkit-zloz": "0.3.0"
64
+ "@opsydyn/foldkit-zloz": "0.6.0"
65
65
  },
66
66
  "engines": {
67
67
  "node": ">=22.0.0"