@bpmnkit/core 1.10.1 → 1.12.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.
@@ -0,0 +1,1265 @@
1
+ import { layoutProcess } from "../layout/layout-engine.js";
2
+ import { routeOrthogonal, sidePorts } from "../layout/orthogonal.js";
3
+ /**
4
+ * Diagram interchange for the elements an edit added, around a layout that
5
+ * stays put.
6
+ *
7
+ * {@link applyAutoLayout} replaces every position, which is right for a new
8
+ * diagram and wrong for an edit: a reviewer reads "the whole diagram moved"
9
+ * when two tasks were added. This places only what has no shape yet, next to
10
+ * the element it connects to, and routes only the connections that have no
11
+ * edge (or whose ends no longer touch their shapes). Existing shapes keep their
12
+ * bounds; the one change they can see is a pool, lane or sub-process growing
13
+ * wider (or a sub-process deeper) when the new shapes do not fit inside it.
14
+ *
15
+ * @packageDocumentation
16
+ */
17
+ import { externalLabelWidth } from "../layout/semantic/place.js";
18
+ import { ELEMENT_SIZES, LABEL_HEIGHT } from "../layout/types.js";
19
+ /** Pool and lane title bands on the left; the layout uses the same widths. */
20
+ const HEADER = 30;
21
+ const GAP = 50;
22
+ const STEP = 30;
23
+ const MAX_COLUMNS = 120;
24
+ const ROW_STEP = 20;
25
+ const MAX_ROWS = 20;
26
+ const MARGIN = 12;
27
+ const INNER_PADDING = 15;
28
+ const SUB_PROCESS_TOP = 30;
29
+ const NEW_POOL_GAP = 30;
30
+ const BLACK_BOX_HEIGHT = 60;
31
+ const ANNOTATION_WIDTH = 100;
32
+ /** An edge end further than this from its shape no longer belongs to it. */
33
+ const STALE_DISTANCE = 12;
34
+ const CONTAINER_TYPES = new Set(["subProcess", "adHocSubProcess", "eventSubProcess", "transaction"]);
35
+ /**
36
+ * Gives every element that has no shape a place next to what it connects to,
37
+ * and every connection that has no edge a route, without moving existing shapes.
38
+ *
39
+ * Use it after editing a parsed file and before {@link exportPreserving}:
40
+ *
41
+ * ```ts
42
+ * const original = readFileSync("order.bpmn", "utf8")
43
+ * const defs = Bpmn.parse(original)
44
+ * // … add elements and flows to defs …
45
+ * const { definitions, unplaced } = placeNewShapes(defs)
46
+ * writeFileSync("order.bpmn", exportPreserving(original, definitions))
47
+ * ```
48
+ *
49
+ * New lanes are not placed: they need room inside a pool, which means moving
50
+ * the lanes below. They are reported in `unplaced`.
51
+ */
52
+ export function placeNewShapes(input, options = {}) {
53
+ const defs = structuredClone(input);
54
+ const result = {
55
+ definitions: defs,
56
+ placed: [],
57
+ routed: [],
58
+ rerouted: [],
59
+ resized: [],
60
+ laneAssigned: [],
61
+ unplaced: [],
62
+ };
63
+ if (defs.diagrams.length === 0) {
64
+ result.unplaced.push({
65
+ id: "",
66
+ reason: "the document has no diagram; use applyAutoLayout for a first layout",
67
+ });
68
+ return result;
69
+ }
70
+ new Placer(defs, result, options).run();
71
+ return result;
72
+ }
73
+ class Placer {
74
+ defs;
75
+ result;
76
+ options;
77
+ scopes = new Map();
78
+ scopeOf = new Map();
79
+ elements = new Map();
80
+ annotations = new Map();
81
+ shapes = new Map();
82
+ edgeIds = new Set();
83
+ diIds = new Set();
84
+ participantOf = new Map();
85
+ /** Every pool, black boxes included. */
86
+ participants = new Set();
87
+ laneOf = new Map();
88
+ lanesOfProcess = new Map();
89
+ mainPlane;
90
+ constructor(defs, result, options) {
91
+ this.defs = defs;
92
+ this.result = result;
93
+ this.options = options;
94
+ this.mainPlane = defs.diagrams[0].plane;
95
+ for (const diagram of defs.diagrams) {
96
+ const plane = diagram.plane;
97
+ if (plane.id)
98
+ this.diIds.add(plane.id);
99
+ for (const shape of plane.shapes) {
100
+ this.shapes.set(shape.bpmnElement, { shape, plane });
101
+ this.diIds.add(shape.id);
102
+ }
103
+ for (const edge of plane.edges) {
104
+ this.edgeIds.add(edge.bpmnElement);
105
+ this.diIds.add(edge.id);
106
+ }
107
+ }
108
+ for (const process of defs.processes)
109
+ this.indexScope(process, process.id, true);
110
+ for (const collaboration of defs.collaborations) {
111
+ for (const p of collaboration.participants) {
112
+ this.participants.add(p.id);
113
+ if (p.processRef)
114
+ this.participantOf.set(p.processRef, p.id);
115
+ }
116
+ for (const a of collaboration.textAnnotations)
117
+ this.annotations.set(a.id, a);
118
+ }
119
+ for (const process of defs.processes) {
120
+ const lanes = [];
121
+ const walk = (set) => {
122
+ for (const lane of set?.lanes ?? []) {
123
+ lanes.push(lane);
124
+ // The deepest lane wins, so nested lanes overwrite their parent.
125
+ for (const ref of lane.flowNodeRefs)
126
+ this.laneOf.set(ref, lane);
127
+ walk(lane.childLaneSet);
128
+ }
129
+ };
130
+ walk(process.laneSet);
131
+ this.lanesOfProcess.set(process.id, lanes);
132
+ }
133
+ }
134
+ run() {
135
+ this.placePools();
136
+ this.placeFlowNodes();
137
+ this.placeAnnotations();
138
+ this.reportLanes();
139
+ this.routeEdges();
140
+ }
141
+ // -------------------------------------------------------------------------
142
+ // Indexing
143
+ // -------------------------------------------------------------------------
144
+ indexScope(owner, processId, isProcess) {
145
+ const scope = {
146
+ id: owner.id,
147
+ processId,
148
+ isProcess,
149
+ flowElements: owner.flowElements,
150
+ sequenceFlows: owner.sequenceFlows,
151
+ textAnnotations: owner.textAnnotations ?? [],
152
+ associations: owner.associations ?? [],
153
+ };
154
+ this.scopes.set(owner.id, scope);
155
+ for (const a of scope.textAnnotations)
156
+ this.annotations.set(a.id, a);
157
+ for (const el of owner.flowElements) {
158
+ this.elements.set(el.id, el);
159
+ this.scopeOf.set(el.id, scope);
160
+ if (CONTAINER_TYPES.has(el.type) && "flowElements" in el) {
161
+ this.indexScope(el, processId, false);
162
+ }
163
+ }
164
+ }
165
+ // -------------------------------------------------------------------------
166
+ // Pools
167
+ // -------------------------------------------------------------------------
168
+ placePools() {
169
+ for (const collaboration of this.defs.collaborations) {
170
+ for (const participant of collaboration.participants) {
171
+ if (this.shapes.has(participant.id))
172
+ continue;
173
+ const pools = this.mainPlane.shapes.filter((s) => collaboration.participants.some((p) => p.id === s.bpmnElement));
174
+ const left = pools.length > 0 ? Math.min(...pools.map((s) => s.bounds.x)) : 0;
175
+ const width = pools.length > 0 ? Math.max(...pools.map((s) => s.bounds.width)) : 600;
176
+ const top = pools.length > 0
177
+ ? Math.max(...pools.map((s) => s.bounds.y + s.bounds.height)) + NEW_POOL_GAP
178
+ : 0;
179
+ const process = participant.processRef
180
+ ? this.defs.processes.find((p) => p.id === participant.processRef)
181
+ : undefined;
182
+ if (!process || process.flowElements.length === 0) {
183
+ this.addShape(this.mainPlane, participant.id, {
184
+ x: left,
185
+ y: top,
186
+ width,
187
+ height: BLACK_BOX_HEIGHT,
188
+ }, { isHorizontal: true });
189
+ continue;
190
+ }
191
+ // A pool whose whole content is new: lay that content out on its own and
192
+ // size the pool around it.
193
+ const content = this.layoutContent(process);
194
+ const poolWidth = Math.max(width, content.width + HEADER + 2 * INNER_PADDING);
195
+ const poolHeight = content.height + 2 * INNER_PADDING;
196
+ const pool = { x: left, y: top, width: poolWidth, height: poolHeight };
197
+ this.addShape(this.mainPlane, participant.id, pool, { isHorizontal: true });
198
+ const dx = left + HEADER + INNER_PADDING - content.minX;
199
+ const dy = top + INNER_PADDING - content.minY;
200
+ for (const lane of content.layout.lanes ?? []) {
201
+ this.addShape(this.mainPlane, lane.id, {
202
+ x: left + HEADER,
203
+ y: lane.bounds.y + dy,
204
+ width: poolWidth - HEADER,
205
+ height: lane.bounds.height,
206
+ }, { isHorizontal: true });
207
+ }
208
+ this.commitLayout(this.mainPlane, content.layout, dx, dy);
209
+ }
210
+ }
211
+ }
212
+ // -------------------------------------------------------------------------
213
+ // Flow nodes
214
+ // -------------------------------------------------------------------------
215
+ placeFlowNodes() {
216
+ const pending = [];
217
+ for (const el of this.elements.values()) {
218
+ if (this.shapes.has(el.id) || el.type === "dataObject")
219
+ continue;
220
+ const scope = this.scopeOf.get(el.id);
221
+ // Children of a sub-process that is itself new are placed with it.
222
+ if (scope && !scope.isProcess && !this.shapes.has(scope.id) && !this.ownPlane(scope.id)) {
223
+ continue;
224
+ }
225
+ pending.push(el);
226
+ }
227
+ // Successors first, so a new chain grows left to right from what exists;
228
+ // a node reachable only backwards from a placed successor waits for that.
229
+ let allowBackward = false;
230
+ while (pending.length > 0) {
231
+ let progressed = false;
232
+ for (let i = 0; i < pending.length; i++) {
233
+ const el = pending[i];
234
+ const anchor = this.anchorFor(el, allowBackward);
235
+ if (!anchor)
236
+ continue;
237
+ pending.splice(i, 1);
238
+ i--;
239
+ progressed = true;
240
+ this.placeNode(el, anchor.id, anchor.direction);
241
+ if (allowBackward)
242
+ break;
243
+ }
244
+ if (progressed) {
245
+ allowBackward = false;
246
+ continue;
247
+ }
248
+ if (!allowBackward) {
249
+ allowBackward = true;
250
+ continue;
251
+ }
252
+ // Nothing connects to what is drawn: put the first one in free space,
253
+ // which may unlock the rest.
254
+ const el = pending.shift();
255
+ this.placeNode(el, undefined, "free");
256
+ allowBackward = false;
257
+ }
258
+ }
259
+ anchorFor(el, allowBackward) {
260
+ if (el.type === "boundaryEvent") {
261
+ const host = el.attachedToRef;
262
+ return this.shapes.has(host) ? { id: host, direction: "below" } : undefined;
263
+ }
264
+ if (el.type === "dataObjectReference" || el.type === "dataStoreReference") {
265
+ const user = this.dataUser(el.id);
266
+ if (user && this.shapes.has(user))
267
+ return { id: user, direction: "above" };
268
+ return undefined;
269
+ }
270
+ const scope = this.scopeOf.get(el.id);
271
+ const flows = scope?.sequenceFlows ?? [];
272
+ const preds = flows
273
+ .filter((f) => f.targetRef === el.id && this.shapes.has(f.sourceRef))
274
+ .map((f) => f.sourceRef);
275
+ if (preds.length > 0) {
276
+ // The rightmost predecessor: the new node goes after the latest of them.
277
+ const id = preds.reduce((best, id) => (this.rightOf(id) > this.rightOf(best) ? id : best));
278
+ // A boundary event's path leaves downwards, below its host.
279
+ const pred = this.elements.get(id);
280
+ return { id, direction: pred?.type === "boundaryEvent" ? "down" : "right" };
281
+ }
282
+ if (!allowBackward)
283
+ return undefined;
284
+ const succ = flows.find((f) => f.sourceRef === el.id && this.shapes.has(f.targetRef));
285
+ return succ ? { id: succ.targetRef, direction: "left" } : undefined;
286
+ }
287
+ dataUser(dataId) {
288
+ for (const el of this.elements.values()) {
289
+ const node = el;
290
+ if (node.dataInputAssociations?.some((a) => a.sourceRefs.includes(dataId)))
291
+ return el.id;
292
+ if (node.dataOutputAssociations?.some((a) => a.targetRef === dataId))
293
+ return el.id;
294
+ }
295
+ return undefined;
296
+ }
297
+ rightOf(id) {
298
+ const b = this.shapes.get(id)?.shape.bounds;
299
+ return b ? b.x + b.width : Number.NEGATIVE_INFINITY;
300
+ }
301
+ placeNode(el, anchorId, direction) {
302
+ const scope = this.scopeOf.get(el.id);
303
+ if (!scope)
304
+ return;
305
+ const plane = this.planeFor(scope);
306
+ if (!plane) {
307
+ this.result.unplaced.push({
308
+ id: el.id,
309
+ reason: `its container ${scope.id} is drawn collapsed and has no plane of its own`,
310
+ });
311
+ return;
312
+ }
313
+ // A new sub-process with content: lay the content out, then place the
314
+ // sub-process as one block of that size.
315
+ let content;
316
+ let size = ELEMENT_SIZES[el.type] ?? { width: 100, height: 80 };
317
+ const children = el.flowElements;
318
+ if (CONTAINER_TYPES.has(el.type) && children && children.length > 0) {
319
+ content = this.layoutContent(el);
320
+ size = {
321
+ width: content.width + 2 * INNER_PADDING,
322
+ height: content.height + SUB_PROCESS_TOP + INNER_PADDING,
323
+ };
324
+ }
325
+ const lane = this.laneFor(el, anchorId, scope);
326
+ const box = this.boxFor(scope, lane, plane);
327
+ const label = this.labelSize(el);
328
+ let chosen;
329
+ if (direction === "below" && anchorId) {
330
+ chosen = this.boundarySpot(el.id, anchorId, size, plane);
331
+ }
332
+ else {
333
+ chosen = this.bestSpot(el.id, size, label, anchorId, direction, box, plane);
334
+ }
335
+ if (!chosen) {
336
+ this.result.unplaced.push({ id: el.id, reason: "no free spot found" });
337
+ return;
338
+ }
339
+ if (box)
340
+ this.growToFit(box, chosen, label, plane);
341
+ const extra = {};
342
+ if (el.type === "exclusiveGateway")
343
+ extra.isMarkerVisible = true;
344
+ if (content)
345
+ extra.isExpanded = true;
346
+ const shape = this.addShape(plane, el.id, chosen, extra);
347
+ if (label)
348
+ shape.label = { bounds: this.labelRect(chosen, label) };
349
+ this.result.placed.push(el.id);
350
+ if (content) {
351
+ const dx = chosen.x + INNER_PADDING - content.minX;
352
+ const dy = chosen.y + SUB_PROCESS_TOP - content.minY;
353
+ this.commitLayout(plane, content.layout, dx, dy);
354
+ }
355
+ if (lane && this.options.assignLanes !== false && !this.laneOf.has(el.id)) {
356
+ lane.flowNodeRefs.push(el.id);
357
+ this.laneOf.set(el.id, lane);
358
+ this.result.laneAssigned.push(el.id);
359
+ }
360
+ }
361
+ /** Lays out content that is entirely new, at its own origin. */
362
+ layoutContent(owner) {
363
+ const process = {
364
+ id: owner.id,
365
+ extensionElements: [],
366
+ flowElements: owner.flowElements,
367
+ sequenceFlows: owner.sequenceFlows,
368
+ textAnnotations: [],
369
+ associations: [],
370
+ groups: [],
371
+ unknownAttributes: {},
372
+ ...(owner.laneSet ? { laneSet: owner.laneSet } : {}),
373
+ };
374
+ const layout = layoutProcess(process);
375
+ let minX = Number.POSITIVE_INFINITY;
376
+ let minY = Number.POSITIVE_INFINITY;
377
+ let maxX = Number.NEGATIVE_INFINITY;
378
+ let maxY = Number.NEGATIVE_INFINITY;
379
+ const extend = (b) => {
380
+ minX = Math.min(minX, b.x);
381
+ minY = Math.min(minY, b.y);
382
+ maxX = Math.max(maxX, b.x + b.width);
383
+ maxY = Math.max(maxY, b.y + b.height);
384
+ };
385
+ for (const node of layout.nodes) {
386
+ extend(node.bounds);
387
+ if (node.labelBounds)
388
+ extend(node.labelBounds);
389
+ }
390
+ for (const lane of layout.lanes ?? [])
391
+ extend(lane.bounds);
392
+ if (!Number.isFinite(minX))
393
+ return { layout, minX: 0, minY: 0, width: 100, height: 80 };
394
+ return { layout, minX, minY, width: maxX - minX, height: maxY - minY };
395
+ }
396
+ /** Writes a layout's nodes and edges onto a plane, shifted by `dx`/`dy`. */
397
+ commitLayout(plane, layout, dx, dy) {
398
+ for (const node of layout.nodes) {
399
+ if (this.shapes.has(node.id))
400
+ continue;
401
+ const extra = {};
402
+ if (node.isExpanded !== undefined)
403
+ extra.isExpanded = node.isExpanded;
404
+ if (node.type === "exclusiveGateway")
405
+ extra.isMarkerVisible = true;
406
+ const shape = this.addShape(plane, node.id, shift(node.bounds, dx, dy), extra);
407
+ if (node.labelBounds)
408
+ shape.label = { bounds: round(shift(node.labelBounds, dx, dy)) };
409
+ this.result.placed.push(node.id);
410
+ }
411
+ for (const edge of layout.edges) {
412
+ if (this.edgeIds.has(edge.id))
413
+ continue;
414
+ const di = {
415
+ id: this.diId(edge.id),
416
+ bpmnElement: edge.id,
417
+ waypoints: edge.waypoints.map((p) => ({
418
+ x: Math.round(p.x + dx),
419
+ y: Math.round(p.y + dy),
420
+ })),
421
+ unknownAttributes: {},
422
+ };
423
+ if (edge.labelBounds)
424
+ di.label = { bounds: round(shift(edge.labelBounds, dx, dy)) };
425
+ plane.edges.push(di);
426
+ this.edgeIds.add(edge.id);
427
+ this.result.routed.push(edge.id);
428
+ }
429
+ }
430
+ // -------------------------------------------------------------------------
431
+ // Where a node may go
432
+ // -------------------------------------------------------------------------
433
+ /** The plane a scope's content is drawn on, or undefined when it is not drawn. */
434
+ planeFor(scope) {
435
+ if (!scope.isProcess) {
436
+ const own = this.ownPlane(scope.id);
437
+ if (own)
438
+ return own;
439
+ const sub = this.shapes.get(scope.id);
440
+ if (!sub || sub.shape.isExpanded === false)
441
+ return undefined;
442
+ return sub.plane;
443
+ }
444
+ const participant = this.participantOf.get(scope.processId);
445
+ if (participant) {
446
+ const pool = this.shapes.get(participant);
447
+ if (pool)
448
+ return pool.plane;
449
+ }
450
+ for (const diagram of this.defs.diagrams) {
451
+ if (diagram.plane.bpmnElement === scope.processId)
452
+ return diagram.plane;
453
+ }
454
+ return this.mainPlane;
455
+ }
456
+ ownPlane(elementId) {
457
+ for (const diagram of this.defs.diagrams) {
458
+ if (diagram.plane.bpmnElement === elementId && diagram.plane !== this.mainPlane) {
459
+ return diagram.plane;
460
+ }
461
+ }
462
+ return undefined;
463
+ }
464
+ laneFor(el, anchorId, scope) {
465
+ if (!scope.isProcess)
466
+ return undefined;
467
+ const own = this.laneOf.get(el.id);
468
+ if (own)
469
+ return own;
470
+ const host = el.type === "boundaryEvent" ? el.attachedToRef : undefined;
471
+ const via = host ?? anchorId;
472
+ if (via && this.scopeOf.get(via)?.processId === scope.processId) {
473
+ const lane = this.laneOf.get(via);
474
+ if (lane)
475
+ return lane;
476
+ }
477
+ // The process draws lanes but neither the node nor its anchor is listed in
478
+ // one: use the lane the anchor is drawn in, else the first drawn lane, so the
479
+ // node does not land across lane borders.
480
+ const drawn = (this.lanesOfProcess.get(scope.processId) ?? []).filter((l) => this.shapes.has(l.id) && !l.childLaneSet?.lanes.length);
481
+ if (drawn.length === 0)
482
+ return undefined;
483
+ const anchor = via ? this.shapes.get(via)?.shape.bounds : undefined;
484
+ if (anchor) {
485
+ const centre = {
486
+ x: anchor.x + anchor.width / 2,
487
+ y: anchor.y + anchor.height / 2,
488
+ width: 0,
489
+ height: 0,
490
+ };
491
+ const hit = drawn.find((l) => contains(this.shapes.get(l.id)?.shape.bounds, centre));
492
+ if (hit)
493
+ return hit;
494
+ }
495
+ return drawn[0];
496
+ }
497
+ boxFor(scope, lane, plane) {
498
+ if (!scope.isProcess) {
499
+ if (this.ownPlane(scope.id))
500
+ return undefined;
501
+ const sub = this.shapes.get(scope.id)?.shape;
502
+ if (!sub)
503
+ return undefined;
504
+ const b = sub.bounds;
505
+ const limits = this.growthLimits(sub, plane);
506
+ return {
507
+ id: scope.id,
508
+ inner: {
509
+ x: b.x + INNER_PADDING,
510
+ y: b.y + SUB_PROCESS_TOP,
511
+ width: b.width - 2 * INNER_PADDING,
512
+ height: b.height - SUB_PROCESS_TOP - INNER_PADDING,
513
+ },
514
+ maxRight: limits.right - INNER_PADDING,
515
+ maxBottom: limits.bottom - INNER_PADDING,
516
+ };
517
+ }
518
+ const laneShape = lane ? this.shapes.get(lane.id)?.shape : undefined;
519
+ const participant = this.participantOf.get(scope.processId);
520
+ const poolShape = participant ? this.shapes.get(participant)?.shape : undefined;
521
+ const frame = laneShape ?? poolShape;
522
+ if (!frame)
523
+ return undefined;
524
+ const b = frame.bounds;
525
+ const inner = {
526
+ x: b.x + HEADER + INNER_PADDING,
527
+ y: b.y + INNER_PADDING / 2,
528
+ width: b.width - HEADER - 2 * INNER_PADDING,
529
+ height: b.height - INNER_PADDING,
530
+ };
531
+ return {
532
+ id: frame.bpmnElement,
533
+ inner,
534
+ maxRight: Number.POSITIVE_INFINITY,
535
+ maxBottom: inner.y + inner.height,
536
+ };
537
+ }
538
+ /**
539
+ * How far a sub-process may grow before it runs into a shape that is not
540
+ * inside it, and the bottom of the lane or pool it sits in.
541
+ */
542
+ growthLimits(sub, plane) {
543
+ const b = sub.bounds;
544
+ let right = Number.POSITIVE_INFINITY;
545
+ let bottom = Number.POSITIVE_INFINITY;
546
+ for (const other of plane.shapes) {
547
+ if (other === sub || this.isContainerShape(other))
548
+ continue;
549
+ const o = other.bounds;
550
+ if (contains(b, o))
551
+ continue;
552
+ if (o.y < b.y + b.height && o.y + o.height > b.y && o.x >= b.x + b.width) {
553
+ right = Math.min(right, o.x - MARGIN);
554
+ }
555
+ if (o.x < b.x + b.width && o.x + o.width > b.x && o.y >= b.y + b.height) {
556
+ bottom = Math.min(bottom, o.y - MARGIN);
557
+ }
558
+ }
559
+ for (const other of plane.shapes) {
560
+ if (!this.isFrameShape(other))
561
+ continue;
562
+ if (contains(other.bounds, b)) {
563
+ bottom = Math.min(bottom, other.bounds.y + other.bounds.height - INNER_PADDING / 2);
564
+ }
565
+ }
566
+ return { right, bottom };
567
+ }
568
+ bestSpot(id, size, label, anchorId, direction, box, plane) {
569
+ const a = anchorId ? this.shapes.get(anchorId)?.shape.bounds : undefined;
570
+ // After a gateway, a new branch reads best as another row below the
571
+ // existing ones, not as a shape pushed far to the right.
572
+ const anchorType = anchorId ? this.elements.get(anchorId)?.type : undefined;
573
+ const columnWeight = anchorType?.endsWith("Gateway") ? 2 : 1;
574
+ const candidates = this.candidates(size, a, direction, box, plane, columnWeight);
575
+ candidates.sort((p, q) => p.cost - q.cost);
576
+ const obstacles = this.obstacles(plane, id);
577
+ const frames = this.foreignFrames(plane, box);
578
+ const segments = edgeSegments(plane);
579
+ let best;
580
+ for (const c of candidates) {
581
+ if (best && c.cost >= best.cost)
582
+ break;
583
+ const r = c.rect;
584
+ if (box && !this.fits(r, box))
585
+ continue;
586
+ if (obstacles.some((o) => overlaps(r, o, MARGIN)))
587
+ continue;
588
+ if (frames.some((f) => overlaps(r, f, 0)))
589
+ continue;
590
+ let cost = c.cost;
591
+ if (box) {
592
+ const overRight = r.x + r.width - (box.inner.x + box.inner.width);
593
+ const overBottom = r.y + r.height - (box.inner.y + box.inner.height);
594
+ if (overRight > 0)
595
+ cost += 4 + overRight / STEP;
596
+ if (overBottom > 0)
597
+ cost += 4 + overBottom / STEP;
598
+ }
599
+ if (segments.some((s) => segmentHits(s, r, 4)))
600
+ cost += 6;
601
+ if (label) {
602
+ const l = this.labelRect(r, label);
603
+ if (obstacles.some((o) => overlaps(l, o, 2)))
604
+ cost += 3;
605
+ }
606
+ if (!best || cost < best.cost)
607
+ best = { rect: r, cost };
608
+ }
609
+ return best?.rect;
610
+ }
611
+ candidates(size, a, direction, box, plane, columnWeight = 1) {
612
+ const out = [];
613
+ const rows = [{ dy: 0, cost: 0 }];
614
+ for (let k = 1; k <= MAX_ROWS; k++) {
615
+ const cost = 3 + (k * ROW_STEP) / 40;
616
+ rows.push({ dy: k * ROW_STEP, cost });
617
+ rows.push({ dy: -k * ROW_STEP, cost: cost + 0.1 });
618
+ }
619
+ const push = (x, y, cost) => out.push({ rect: { x: Math.round(x), y: Math.round(y), ...size }, cost });
620
+ if (a && (direction === "right" || direction === "left")) {
621
+ const cy = a.y + a.height / 2;
622
+ for (let c = 0; c < MAX_COLUMNS; c++) {
623
+ const x = direction === "right" ? a.x + a.width + GAP + c * STEP : a.x - GAP - size.width - c * STEP;
624
+ for (const row of rows)
625
+ push(x, cy + row.dy - size.height / 2, c * columnWeight + row.cost);
626
+ }
627
+ return out;
628
+ }
629
+ if (a && direction === "down") {
630
+ // Below the boundary event, clear of its label: straight down first, then
631
+ // stepping right, as a modeller draws an exception path.
632
+ const cx = a.x + a.width / 2;
633
+ for (let r = 0; r < MAX_ROWS; r++) {
634
+ const y = a.y + a.height + GAP + r * ROW_STEP;
635
+ for (let c = -4; c < MAX_COLUMNS / 2; c++) {
636
+ const cost = r * 0.5 + (c < 0 ? 2 - c : c * 0.5);
637
+ push(cx - size.width / 2 + c * STEP, y, cost);
638
+ }
639
+ }
640
+ return out;
641
+ }
642
+ if (a && direction === "above") {
643
+ const cx = a.x + a.width / 2;
644
+ for (let r = 0; r < MAX_ROWS; r++) {
645
+ const y = a.y - GAP - size.height - r * ROW_STEP;
646
+ for (let c = -10; c <= 10; c++) {
647
+ push(cx - size.width / 2 + c * STEP, y, r + Math.abs(c) * 1.5);
648
+ }
649
+ }
650
+ // Below as the second choice.
651
+ for (let r = 0; r < MAX_ROWS; r++) {
652
+ const y = a.y + a.height + GAP + r * ROW_STEP;
653
+ for (let c = -10; c <= 10; c++) {
654
+ push(cx - size.width / 2 + c * STEP, y, 5 + r + Math.abs(c) * 1.5);
655
+ }
656
+ }
657
+ return out;
658
+ }
659
+ // Free space: right of what the container already holds, or below it.
660
+ const area = box?.inner ?? this.planeExtent(plane);
661
+ const content = this.contentIn(area, plane);
662
+ const startX = content ? content.x + content.width + GAP : area.x;
663
+ const midY = area.y + area.height / 2;
664
+ for (let c = 0; c < MAX_COLUMNS; c++) {
665
+ for (const row of rows) {
666
+ push(startX + c * STEP, midY + row.dy - size.height / 2, c + row.cost);
667
+ }
668
+ }
669
+ const belowY = content ? content.y + content.height + GAP : area.y;
670
+ for (let r = 0; r < MAX_ROWS; r++) {
671
+ for (let c = 0; c < 40; c++) {
672
+ push(area.x + c * STEP, belowY + r * ROW_STEP, 2 + c * 0.5 + r);
673
+ }
674
+ }
675
+ return out;
676
+ }
677
+ /** A spot on the host's bottom border, the right-most free one; then the top border. */
678
+ boundarySpot(id, hostId, size, plane) {
679
+ const host = this.shapes.get(hostId)?.shape.bounds;
680
+ if (!host)
681
+ return undefined;
682
+ const siblings = plane.shapes
683
+ .filter((s) => {
684
+ const el = this.elements.get(s.bpmnElement);
685
+ return el?.type === "boundaryEvent" && el.attachedToRef === hostId;
686
+ })
687
+ .map((s) => s.bounds);
688
+ for (const y of [host.y + host.height - size.height / 2, host.y - size.height / 2]) {
689
+ for (let x = host.x + host.width - size.width - 8; x >= host.x + 4; x -= 6) {
690
+ const r = { x: Math.round(x), y: Math.round(y), ...size };
691
+ if (siblings.some((s) => overlaps(r, s, 6)))
692
+ continue;
693
+ return r;
694
+ }
695
+ }
696
+ this.result.unplaced.push({ id, reason: `no room left on the border of ${hostId}` });
697
+ return undefined;
698
+ }
699
+ fits(r, box) {
700
+ return (r.x >= box.inner.x &&
701
+ r.y >= box.inner.y &&
702
+ r.x + r.width <= box.maxRight &&
703
+ r.y + r.height <= box.maxBottom);
704
+ }
705
+ /** Widens (or for a sub-process, deepens) the container and what holds it. */
706
+ growToFit(box, r, label, plane) {
707
+ const l = label ? this.labelRect(r, label) : r;
708
+ const needRight = Math.max(r.x + r.width, l.x + l.width) + INNER_PADDING;
709
+ const needBottom = r.y + r.height + INNER_PADDING;
710
+ this.growShape(box.id, needRight, needBottom, plane);
711
+ }
712
+ growShape(elementId, right, bottom, plane) {
713
+ const entry = this.shapes.get(elementId);
714
+ if (!entry)
715
+ return;
716
+ const shape = entry.shape;
717
+ const b = shape.bounds;
718
+ const isSub = CONTAINER_TYPES.has(this.elements.get(elementId)?.type ?? "");
719
+ let changed = false;
720
+ if (right > b.x + b.width) {
721
+ b.width = Math.round(right - b.x);
722
+ changed = true;
723
+ }
724
+ if (isSub && bottom > b.y + b.height) {
725
+ b.height = Math.round(bottom - b.y);
726
+ changed = true;
727
+ }
728
+ if (!changed)
729
+ return;
730
+ this.result.resized.push(elementId);
731
+ const edge = b.x + b.width;
732
+ if (isSub) {
733
+ // What holds the sub-process grows with it.
734
+ for (const other of plane.shapes) {
735
+ if (other === shape || !this.isContainerShape(other))
736
+ continue;
737
+ const holds = contains(other.bounds, { x: b.x, y: b.y, width: 1, height: 1 });
738
+ if (!holds || contains(other.bounds, b))
739
+ continue;
740
+ this.growShape(other.bpmnElement, edge + INNER_PADDING, b.y + b.height + INNER_PADDING, plane);
741
+ }
742
+ return;
743
+ }
744
+ // A lane or pool: every frame of the same pool shares its right edge.
745
+ const pool = this.poolOfFrame(elementId);
746
+ if (!pool)
747
+ return;
748
+ for (const frameId of [pool.participantId, ...pool.laneIds]) {
749
+ if (frameId === elementId)
750
+ continue;
751
+ const frame = this.shapes.get(frameId)?.shape;
752
+ if (!frame || frame.bounds.x + frame.bounds.width >= edge)
753
+ continue;
754
+ frame.bounds.width = Math.round(edge - frame.bounds.x);
755
+ this.result.resized.push(frameId);
756
+ }
757
+ }
758
+ poolOfFrame(elementId) {
759
+ for (const [processId, lanes] of this.lanesOfProcess) {
760
+ const participantId = this.participantOf.get(processId);
761
+ if (!participantId)
762
+ continue;
763
+ if (participantId === elementId || lanes.some((l) => l.id === elementId)) {
764
+ return { participantId, laneIds: lanes.map((l) => l.id) };
765
+ }
766
+ }
767
+ return undefined;
768
+ }
769
+ // -------------------------------------------------------------------------
770
+ // Annotations and lanes
771
+ // -------------------------------------------------------------------------
772
+ placeAnnotations() {
773
+ for (const annotation of this.annotations.values()) {
774
+ if (this.shapes.has(annotation.id))
775
+ continue;
776
+ const association = this.allAssociations().find((a) => a.sourceRef === annotation.id || a.targetRef === annotation.id);
777
+ const anchorId = association &&
778
+ (association.sourceRef === annotation.id ? association.targetRef : association.sourceRef);
779
+ const anchor = anchorId ? this.shapes.get(anchorId) : undefined;
780
+ const plane = anchor?.plane ?? this.mainPlane;
781
+ const lines = Math.max(1, Math.ceil(((annotation.text ?? "").length * 7) / ANNOTATION_WIDTH));
782
+ const size = { width: ANNOTATION_WIDTH, height: Math.max(30, lines * LABEL_HEIGHT + 12) };
783
+ const scope = anchorId ? this.scopeOf.get(anchorId) : undefined;
784
+ const box = scope ? this.boxFor(scope, this.laneOf.get(anchorId ?? ""), plane) : undefined;
785
+ const spot = this.bestSpot(annotation.id, size, undefined, anchor ? anchorId : undefined, anchor ? "above" : "free", box, plane);
786
+ if (!spot) {
787
+ this.result.unplaced.push({ id: annotation.id, reason: "no free spot found" });
788
+ continue;
789
+ }
790
+ if (box)
791
+ this.growToFit(box, spot, undefined, plane);
792
+ this.addShape(plane, annotation.id, spot, {});
793
+ this.result.placed.push(annotation.id);
794
+ }
795
+ }
796
+ reportLanes() {
797
+ for (const [processId, lanes] of this.lanesOfProcess) {
798
+ const participant = this.participantOf.get(processId);
799
+ if (!participant || !this.shapes.has(participant))
800
+ continue;
801
+ if (!lanes.some((l) => this.shapes.has(l.id)))
802
+ continue;
803
+ for (const lane of lanes) {
804
+ if (this.shapes.has(lane.id))
805
+ continue;
806
+ this.result.unplaced.push({
807
+ id: lane.id,
808
+ reason: "a new lane needs room in its pool, which moves the lanes below; draw it by hand or run applyAutoLayout",
809
+ });
810
+ }
811
+ }
812
+ }
813
+ // -------------------------------------------------------------------------
814
+ // Edges
815
+ // -------------------------------------------------------------------------
816
+ routeEdges() {
817
+ const connections = [];
818
+ for (const scope of this.scopes.values()) {
819
+ for (const f of scope.sequenceFlows) {
820
+ connections.push({
821
+ id: f.id,
822
+ sourceRef: f.sourceRef,
823
+ targetRef: f.targetRef,
824
+ kind: "sequence",
825
+ ...(f.name ? { name: f.name } : {}),
826
+ });
827
+ }
828
+ }
829
+ for (const a of this.allAssociations()) {
830
+ connections.push({
831
+ id: a.id,
832
+ sourceRef: a.sourceRef,
833
+ targetRef: a.targetRef,
834
+ kind: "association",
835
+ });
836
+ }
837
+ for (const collaboration of this.defs.collaborations) {
838
+ for (const m of collaboration.messageFlows) {
839
+ connections.push({
840
+ id: m.id,
841
+ sourceRef: m.sourceRef,
842
+ targetRef: m.targetRef,
843
+ kind: "message",
844
+ ...(m.name ? { name: m.name } : {}),
845
+ });
846
+ }
847
+ }
848
+ for (const el of this.elements.values()) {
849
+ const node = el;
850
+ for (const a of node.dataInputAssociations ?? []) {
851
+ const source = a.sourceRefs[0];
852
+ if (a.id && source)
853
+ connections.push({ id: a.id, sourceRef: source, targetRef: el.id, kind: "association" });
854
+ }
855
+ for (const a of node.dataOutputAssociations ?? []) {
856
+ if (a.id && a.targetRef)
857
+ connections.push({
858
+ id: a.id,
859
+ sourceRef: el.id,
860
+ targetRef: a.targetRef,
861
+ kind: "association",
862
+ });
863
+ }
864
+ }
865
+ const existing = new Map();
866
+ for (const diagram of this.defs.diagrams) {
867
+ for (const edge of diagram.plane.edges)
868
+ existing.set(edge.bpmnElement, { edge, plane: diagram.plane });
869
+ }
870
+ for (const c of connections) {
871
+ const source = this.shapes.get(c.sourceRef);
872
+ const target = this.shapes.get(c.targetRef);
873
+ const current = existing.get(c.id);
874
+ if (current) {
875
+ if (this.options.rerouteStale === false || !source || !target)
876
+ continue;
877
+ const wps = current.edge.waypoints;
878
+ const first = wps[0];
879
+ const last = wps[wps.length - 1];
880
+ if (first &&
881
+ last &&
882
+ distance(first, source.shape.bounds) <= STALE_DISTANCE &&
883
+ distance(last, target.shape.bounds) <= STALE_DISTANCE) {
884
+ continue;
885
+ }
886
+ current.edge.waypoints = this.route(c.kind, source.shape, target.shape, current.plane, c.id);
887
+ if (c.name && current.edge.label) {
888
+ current.edge.label.bounds = this.edgeLabel(current.edge.waypoints, c.name, current.plane);
889
+ }
890
+ this.result.rerouted.push(c.id);
891
+ continue;
892
+ }
893
+ if (!source || !target) {
894
+ // A data association to an undrawn data object is not an error; anything
895
+ // else is worth reporting.
896
+ if (this.elements.get(c.sourceRef)?.type !== "dataObject" &&
897
+ this.elements.get(c.targetRef)?.type !== "dataObject") {
898
+ this.result.unplaced.push({ id: c.id, reason: "one of its ends has no shape" });
899
+ }
900
+ continue;
901
+ }
902
+ const plane = c.kind === "message" ? this.mainPlane : target.plane;
903
+ const di = {
904
+ id: this.diId(c.id),
905
+ bpmnElement: c.id,
906
+ waypoints: this.route(c.kind, source.shape, target.shape, plane, c.id),
907
+ unknownAttributes: {},
908
+ };
909
+ if (c.name)
910
+ di.label = { bounds: this.edgeLabel(di.waypoints, c.name, plane) };
911
+ plane.edges.push(di);
912
+ this.edgeIds.add(c.id);
913
+ this.result.routed.push(c.id);
914
+ }
915
+ }
916
+ route(kind, source, target, plane, edgeId) {
917
+ const s = source.bounds;
918
+ const t = target.bounds;
919
+ const sourcePool = this.participants.has(source.bpmnElement);
920
+ const targetPool = this.participants.has(target.bpmnElement);
921
+ if (kind === "message" && (sourcePool || targetPool)) {
922
+ // A pool end docks straight above or below the other end.
923
+ const x = Math.round(sourcePool && targetPool
924
+ ? (Math.max(s.x, t.x) + Math.min(s.x + s.width, t.x + t.width)) / 2
925
+ : sourcePool
926
+ ? clamp(t.x + t.width / 2, s.x + HEADER, s.x + s.width)
927
+ : clamp(s.x + s.width / 2, t.x + HEADER, t.x + t.width));
928
+ const down = s.y + s.height / 2 < t.y + t.height / 2;
929
+ return [
930
+ { x, y: Math.round(down ? s.y + s.height : s.y) },
931
+ { x, y: Math.round(down ? t.y : t.y + t.height) },
932
+ ];
933
+ }
934
+ const sourceEl = this.elements.get(source.bpmnElement);
935
+ const targetEl = this.elements.get(target.bpmnElement);
936
+ const exempt = new Set([source.bpmnElement, target.bpmnElement]);
937
+ for (const el of [sourceEl, targetEl]) {
938
+ if (el?.type === "boundaryEvent")
939
+ exempt.add(el.attachedToRef);
940
+ }
941
+ for (const shape of plane.shapes) {
942
+ const el = this.elements.get(shape.bpmnElement);
943
+ if (el?.type === "boundaryEvent" && exempt.has(el.attachedToRef)) {
944
+ exempt.add(shape.bpmnElement);
945
+ }
946
+ }
947
+ const obstacles = plane.shapes
948
+ .filter((sh) => !exempt.has(sh.bpmnElement) && !this.isContainerShape(sh))
949
+ .map((sh) => sh.bounds);
950
+ const sCx = s.x + s.width / 2;
951
+ const sCy = s.y + s.height / 2;
952
+ const tCy = t.y + t.height / 2;
953
+ if (kind === "sequence" && Math.abs(sCy - tCy) < 1 && t.x > s.x + s.width) {
954
+ const straight = [
955
+ { x: Math.round(s.x + s.width), y: Math.round(sCy) },
956
+ { x: Math.round(t.x), y: Math.round(tCy) },
957
+ ];
958
+ if (!obstacles.some((o) => segmentHits(straight, o, 0))) {
959
+ return straight;
960
+ }
961
+ }
962
+ let from;
963
+ let to;
964
+ if (kind === "sequence") {
965
+ const fromBoundary = sourceEl?.type === "boundaryEvent";
966
+ const hostTop = fromBoundary
967
+ ? this.shapes.get(sourceEl.attachedToRef)?.shape.bounds
968
+ : undefined;
969
+ const boundarySide = hostTop
970
+ ? Math.abs(sCy - hostTop.y) < Math.abs(sCy - (hostTop.y + hostTop.height))
971
+ ? "top"
972
+ : "bottom"
973
+ : undefined;
974
+ from = boundarySide
975
+ ? sidePorts(s, sideOnly(boundarySide))
976
+ : sidePorts(s, { right: 0, top: 15, bottom: 15, left: 120 });
977
+ to = sidePorts(t, { left: 0, top: 15, bottom: 15, right: 120 });
978
+ }
979
+ else if (kind === "message") {
980
+ const down = sCy < tCy;
981
+ from = sidePorts(s, down
982
+ ? { bottom: 0, left: 60, right: 60, top: 120 }
983
+ : { top: 0, left: 60, right: 60, bottom: 120 });
984
+ to = sidePorts(t, down
985
+ ? { top: 0, left: 60, right: 60, bottom: 120 }
986
+ : { bottom: 0, left: 60, right: 60, top: 120 });
987
+ }
988
+ else {
989
+ from = sidePorts(s);
990
+ to = sidePorts(t);
991
+ }
992
+ const others = edgeSegments(plane, edgeId);
993
+ const route = routeOrthogonal({
994
+ from,
995
+ to,
996
+ obstacles,
997
+ crossings: (a, b) => countCrossings(a, b, others),
998
+ });
999
+ if (route)
1000
+ return route.map((p) => ({ x: Math.round(p.x), y: Math.round(p.y) }));
1001
+ // No clear route at all: an elbow between facing sides.
1002
+ const midX = Math.round((s.x + s.width + t.x) / 2);
1003
+ return [
1004
+ { x: Math.round(s.x + s.width), y: Math.round(sCy) },
1005
+ { x: midX, y: Math.round(sCy) },
1006
+ { x: midX, y: Math.round(tCy) },
1007
+ { x: Math.round(t.x), y: Math.round(tCy) },
1008
+ ].filter((p, i, all) => i === 0 || p.x !== all[i - 1]?.x || p.y !== all[i - 1]?.y);
1009
+ }
1010
+ /** A spot for a flow's name next to its first segments, clear of shapes and other labels. */
1011
+ edgeLabel(waypoints, name, plane) {
1012
+ const width = Math.min(Math.max(name.length * 7, 40), 120);
1013
+ const height = LABEL_HEIGHT * Math.max(1, Math.ceil((name.length * 7) / width));
1014
+ const taken = [];
1015
+ for (const shape of plane.shapes) {
1016
+ if (!this.isContainerShape(shape))
1017
+ taken.push(shape.bounds);
1018
+ if (shape.label?.bounds)
1019
+ taken.push(shape.label.bounds);
1020
+ }
1021
+ for (const edge of plane.edges)
1022
+ if (edge.label?.bounds)
1023
+ taken.push(edge.label.bounds);
1024
+ const spots = [];
1025
+ for (let i = 1; i < Math.min(waypoints.length, 4); i++) {
1026
+ const p = waypoints[i - 1];
1027
+ const q = waypoints[i];
1028
+ if (p.y === q.y) {
1029
+ const x = Math.min(p.x, q.x) + 6;
1030
+ spots.push({ x, y: p.y - height - 4, width, height });
1031
+ spots.push({ x, y: p.y + 4, width, height });
1032
+ }
1033
+ else {
1034
+ const y = q.y > p.y ? p.y + 6 : p.y - height - 6;
1035
+ spots.push({ x: p.x + 6, y, width, height });
1036
+ spots.push({ x: p.x - width - 6, y, width, height });
1037
+ }
1038
+ }
1039
+ const free = spots.find((r) => !taken.some((t) => overlaps(r, t, 2)));
1040
+ return round(free ?? spots[0] ?? { x: 0, y: 0, width, height });
1041
+ }
1042
+ // -------------------------------------------------------------------------
1043
+ // Helpers
1044
+ // -------------------------------------------------------------------------
1045
+ allAssociations() {
1046
+ const out = [];
1047
+ for (const scope of this.scopes.values())
1048
+ out.push(...scope.associations);
1049
+ for (const collaboration of this.defs.collaborations)
1050
+ out.push(...collaboration.associations);
1051
+ return out;
1052
+ }
1053
+ labelSize(el) {
1054
+ const name = el.name;
1055
+ if (!name)
1056
+ return undefined;
1057
+ const width = externalLabelWidth(el.type, name);
1058
+ if (width === undefined)
1059
+ return undefined;
1060
+ return { width, height: LABEL_HEIGHT };
1061
+ }
1062
+ labelRect(shape, label) {
1063
+ return {
1064
+ x: Math.round(shape.x + shape.width / 2 - label.width / 2),
1065
+ y: Math.round(shape.y + shape.height + 4),
1066
+ width: label.width,
1067
+ height: label.height,
1068
+ };
1069
+ }
1070
+ /** Pools and lanes: frames drawn around other shapes. */
1071
+ isFrameShape(shape) {
1072
+ return (this.participants.has(shape.bpmnElement) ||
1073
+ [...this.lanesOfProcess.values()].some((lanes) => lanes.some((l) => l.id === shape.bpmnElement)));
1074
+ }
1075
+ /** Frames, and sub-processes drawn expanded around their content. */
1076
+ isContainerShape(shape) {
1077
+ if (this.isFrameShape(shape))
1078
+ return true;
1079
+ const type = this.elements.get(shape.bpmnElement)?.type;
1080
+ return type !== undefined && CONTAINER_TYPES.has(type) && shape.isExpanded !== false;
1081
+ }
1082
+ /** Everything a new shape must keep clear of: shapes that are not frames, and their labels. */
1083
+ obstacles(plane, self) {
1084
+ const out = [];
1085
+ for (const shape of plane.shapes) {
1086
+ if (shape.bpmnElement === self)
1087
+ continue;
1088
+ if (this.isContainerShape(shape))
1089
+ continue;
1090
+ out.push(shape.bounds);
1091
+ if (shape.label?.bounds)
1092
+ out.push(shape.label.bounds);
1093
+ }
1094
+ return out;
1095
+ }
1096
+ /** Containers the new shape is not inside, so it may not cross their border. */
1097
+ foreignFrames(plane, box) {
1098
+ const own = box ? this.shapes.get(box.id)?.shape.bounds : undefined;
1099
+ return plane.shapes
1100
+ .filter((shape) => {
1101
+ if (!this.isContainerShape(shape))
1102
+ return false;
1103
+ if (!own)
1104
+ return true;
1105
+ // Ancestors of the box (its pool, its parent lane) contain it.
1106
+ return !contains(shape.bounds, own);
1107
+ })
1108
+ .map((shape) => shape.bounds);
1109
+ }
1110
+ planeExtent(plane) {
1111
+ if (plane.shapes.length === 0)
1112
+ return { x: 0, y: 0, width: 600, height: 200 };
1113
+ const xs = plane.shapes.map((s) => s.bounds);
1114
+ const minX = Math.min(...xs.map((b) => b.x));
1115
+ const minY = Math.min(...xs.map((b) => b.y));
1116
+ const maxY = Math.max(...xs.map((b) => b.y + b.height));
1117
+ const maxX = Math.max(...xs.map((b) => b.x + b.width));
1118
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
1119
+ }
1120
+ contentIn(area, plane) {
1121
+ const inside = plane.shapes
1122
+ .filter((s) => !this.isFrameShape(s) && contains(area, s.bounds))
1123
+ .map((s) => s.bounds);
1124
+ if (inside.length === 0)
1125
+ return undefined;
1126
+ const minX = Math.min(...inside.map((b) => b.x));
1127
+ const minY = Math.min(...inside.map((b) => b.y));
1128
+ const maxX = Math.max(...inside.map((b) => b.x + b.width));
1129
+ const maxY = Math.max(...inside.map((b) => b.y + b.height));
1130
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
1131
+ }
1132
+ addShape(plane, elementId, bounds, extra) {
1133
+ const shape = {
1134
+ id: this.diId(elementId),
1135
+ bpmnElement: elementId,
1136
+ ...extra,
1137
+ bounds: round(bounds),
1138
+ unknownAttributes: {},
1139
+ };
1140
+ plane.shapes.push(shape);
1141
+ this.shapes.set(elementId, { shape, plane });
1142
+ return shape;
1143
+ }
1144
+ diId(elementId) {
1145
+ let id = `${elementId}_di`;
1146
+ for (let n = 2; this.diIds.has(id); n++)
1147
+ id = `${elementId}_di_${n}`;
1148
+ this.diIds.add(id);
1149
+ return id;
1150
+ }
1151
+ }
1152
+ // ---------------------------------------------------------------------------
1153
+ // Geometry
1154
+ // ---------------------------------------------------------------------------
1155
+ function round(b) {
1156
+ return {
1157
+ x: Math.round(b.x),
1158
+ y: Math.round(b.y),
1159
+ width: Math.round(b.width),
1160
+ height: Math.round(b.height),
1161
+ };
1162
+ }
1163
+ function shift(b, dx, dy) {
1164
+ return { x: b.x + dx, y: b.y + dy, width: b.width, height: b.height };
1165
+ }
1166
+ function clamp(v, lo, hi) {
1167
+ return Math.min(Math.max(v, lo), hi);
1168
+ }
1169
+ function overlaps(a, b, margin) {
1170
+ return (a.x < b.x + b.width + margin &&
1171
+ b.x < a.x + a.width + margin &&
1172
+ a.y < b.y + b.height + margin &&
1173
+ b.y < a.y + a.height + margin);
1174
+ }
1175
+ function contains(outer, inner) {
1176
+ return (inner.x >= outer.x &&
1177
+ inner.y >= outer.y &&
1178
+ inner.x + inner.width <= outer.x + outer.width &&
1179
+ inner.y + inner.height <= outer.y + outer.height);
1180
+ }
1181
+ function distance(p, r) {
1182
+ const dx = Math.max(r.x - p.x, 0, p.x - (r.x + r.width));
1183
+ const dy = Math.max(r.y - p.y, 0, p.y - (r.y + r.height));
1184
+ return Math.hypot(dx, dy);
1185
+ }
1186
+ function sideOnly(side) {
1187
+ const all = ["top", "right", "bottom", "left"];
1188
+ const out = {};
1189
+ for (const s of all)
1190
+ out[s] = s === side ? 0 : Number.POSITIVE_INFINITY;
1191
+ return out;
1192
+ }
1193
+ function edgeSegments(plane, skip) {
1194
+ const out = [];
1195
+ for (const edge of plane.edges) {
1196
+ if (edge.bpmnElement === skip)
1197
+ continue;
1198
+ for (let i = 1; i < edge.waypoints.length; i++) {
1199
+ out.push([edge.waypoints[i - 1], edge.waypoints[i]]);
1200
+ }
1201
+ }
1202
+ return out;
1203
+ }
1204
+ /** Whether a segment passes through a rectangle grown by `margin`. */
1205
+ function segmentHits([p, q], r, margin) {
1206
+ const x0 = r.x - margin;
1207
+ const y0 = r.y - margin;
1208
+ const x1 = r.x + r.width + margin;
1209
+ const y1 = r.y + r.height + margin;
1210
+ if (Math.max(p.x, q.x) <= x0 || Math.min(p.x, q.x) >= x1)
1211
+ return false;
1212
+ if (Math.max(p.y, q.y) <= y0 || Math.min(p.y, q.y) >= y1)
1213
+ return false;
1214
+ if (p.x === q.x || p.y === q.y)
1215
+ return true;
1216
+ // A diagonal segment: test it against the rectangle by clipping.
1217
+ let t0 = 0;
1218
+ let t1 = 1;
1219
+ const dx = q.x - p.x;
1220
+ const dy = q.y - p.y;
1221
+ const clip = (pp, qq) => {
1222
+ if (pp === 0)
1223
+ return qq >= 0;
1224
+ const t = qq / pp;
1225
+ if (pp < 0) {
1226
+ if (t > t1)
1227
+ return false;
1228
+ if (t > t0)
1229
+ t0 = t;
1230
+ }
1231
+ else {
1232
+ if (t < t0)
1233
+ return false;
1234
+ if (t < t1)
1235
+ t1 = t;
1236
+ }
1237
+ return true;
1238
+ };
1239
+ return clip(-dx, p.x - x0) && clip(dx, x1 - p.x) && clip(-dy, p.y - y0) && clip(dy, y1 - p.y);
1240
+ }
1241
+ /** How many other segments the orthogonal segment a→b crosses. */
1242
+ function countCrossings(a, b, others) {
1243
+ let n = 0;
1244
+ const horizontal = a.y === b.y;
1245
+ for (const [p, q] of others) {
1246
+ if (horizontal && p.x === q.x) {
1247
+ if (p.x > Math.min(a.x, b.x) &&
1248
+ p.x < Math.max(a.x, b.x) &&
1249
+ a.y > Math.min(p.y, q.y) &&
1250
+ a.y < Math.max(p.y, q.y)) {
1251
+ n++;
1252
+ }
1253
+ }
1254
+ else if (!horizontal && p.y === q.y) {
1255
+ if (p.y > Math.min(a.y, b.y) &&
1256
+ p.y < Math.max(a.y, b.y) &&
1257
+ a.x > Math.min(p.x, q.x) &&
1258
+ a.x < Math.max(p.x, q.x)) {
1259
+ n++;
1260
+ }
1261
+ }
1262
+ }
1263
+ return n;
1264
+ }
1265
+ //# sourceMappingURL=place-new-shapes.js.map