@bpmnkit/core 1.15.0 → 1.17.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.
Files changed (60) hide show
  1. package/builder-reference.md +2 -1
  2. package/dist/bpmn/auto-layout.d.ts +0 -8
  3. package/dist/bpmn/auto-layout.js +605 -98
  4. package/dist/bpmn/bpmn-builder.d.ts +120 -14
  5. package/dist/bpmn/bpmn-builder.js +411 -152
  6. package/dist/bpmn/bpmn-model.d.ts +15 -0
  7. package/dist/bpmn/bpmn-parser.js +32 -6
  8. package/dist/bpmn/bpmn-serializer.js +9 -2
  9. package/dist/bpmn/compact-stream.d.ts +7 -0
  10. package/dist/bpmn/compact-stream.js +7 -0
  11. package/dist/bpmn/compact.d.ts +124 -9
  12. package/dist/bpmn/compact.js +295 -27
  13. package/dist/bpmn/full-operations.d.ts +19 -0
  14. package/dist/bpmn/full-operations.js +191 -7
  15. package/dist/bpmn/make-room.js +114 -0
  16. package/dist/bpmn/place-new-shapes.js +4 -2
  17. package/dist/bpmn/preserving-writer.d.ts +1 -1
  18. package/dist/bpmn/preserving-writer.js +1 -1
  19. package/dist/bpmn/process-delta.d.ts +32 -1
  20. package/dist/bpmn/process-delta.js +62 -1
  21. package/dist/bpmn/process-text-writer.d.ts +18 -7
  22. package/dist/bpmn/process-text-writer.js +105 -22
  23. package/dist/bpmn/process-text.d.ts +27 -1
  24. package/dist/bpmn/process-text.js +350 -2
  25. package/dist/bpmn/swimlanes.d.ts +178 -0
  26. package/dist/bpmn/swimlanes.js +774 -0
  27. package/dist/index.d.ts +5 -4
  28. package/dist/index.js +3 -2
  29. package/dist/layout/collaboration/crossings.d.ts +13 -0
  30. package/dist/layout/collaboration/crossings.js +37 -0
  31. package/dist/layout/collaboration/docked-labels.d.ts +21 -0
  32. package/dist/layout/collaboration/docked-labels.js +65 -0
  33. package/dist/layout/collaboration/message-tracks.d.ts +20 -0
  34. package/dist/layout/collaboration/message-tracks.js +78 -0
  35. package/dist/layout/collaboration/stack-crossings.d.ts +38 -0
  36. package/dist/layout/collaboration/stack-crossings.js +155 -0
  37. package/dist/layout/grid/edge-labels.js +21 -10
  38. package/dist/layout/layered/coords.d.ts +13 -0
  39. package/dist/layout/layered/coords.js +211 -0
  40. package/dist/layout/layered/index.d.ts +21 -0
  41. package/dist/layout/layered/index.js +288 -0
  42. package/dist/layout/layered/layers.d.ts +60 -0
  43. package/dist/layout/layered/layers.js +374 -0
  44. package/dist/layout/layered/route.d.ts +66 -0
  45. package/dist/layout/layered/route.js +369 -0
  46. package/dist/layout/layout-engine.d.ts +6 -2
  47. package/dist/layout/layout-engine.js +4 -2
  48. package/dist/layout/semantic/bands.js +8 -2
  49. package/dist/layout/semantic/graph.d.ts +33 -1
  50. package/dist/layout/semantic/graph.js +200 -4
  51. package/dist/layout/semantic/index.d.ts +8 -2
  52. package/dist/layout/semantic/index.js +114 -14
  53. package/dist/layout/semantic/lanes.d.ts +40 -0
  54. package/dist/layout/semantic/lanes.js +198 -0
  55. package/dist/layout/semantic/place.d.ts +46 -2
  56. package/dist/layout/semantic/place.js +248 -30
  57. package/dist/layout/semantic/route.js +35 -2
  58. package/dist/layout/types.d.ts +0 -8
  59. package/dist/xml/xml-patch.d.ts +1 -1
  60. package/package.json +2 -2
@@ -1,10 +1,15 @@
1
1
  import { associationWaypoints, packAnnotations } from "../layout/annotations.js";
2
2
  import { alignPools } from "../layout/collaboration/alignment.js";
3
+ import { pathCrossings } from "../layout/collaboration/crossings.js";
4
+ import { flipDockedLabels } from "../layout/collaboration/docked-labels.js";
3
5
  import { placeMessageFlowLabels } from "../layout/collaboration/message-labels.js";
6
+ import { assignTracks } from "../layout/collaboration/message-tracks.js";
4
7
  import { orderPools } from "../layout/collaboration/ordering.js";
8
+ import { orderByCrossings } from "../layout/collaboration/stack-crossings.js";
5
9
  import { collapseCollinear } from "../layout/grid/grid-router.js";
6
10
  import { layoutProcess } from "../layout/layout-engine.js";
7
11
  import { repairRoutes } from "../layout/repair.js";
12
+ import { MIN_LANE_HEIGHT } from "../layout/semantic/place.js";
8
13
  const POOL_HEADER = 30;
9
14
  const LANE_HEADER = 30;
10
15
  const PADDING = 20;
@@ -67,6 +72,23 @@ function contentBbox(nodes, extra) {
67
72
  }
68
73
  return { minX, minY, maxX, maxY };
69
74
  }
75
+ /**
76
+ * Data elements are never lane members, and the engine stacks them below the
77
+ * bands; growing the pool for them leaves tall empty tails, so only flow nodes
78
+ * count.
79
+ */
80
+ const NOT_LANE_MEMBERS = new Set(["dataObject", "dataObjectReference", "dataStoreReference"]);
81
+ /**
82
+ * Where a laned pool has to end so the nodes no lane claims stay inside it.
83
+ * The engine stacks those nodes below the lane bands, so they are the ones
84
+ * whose top lies at or under `bandBottom`; with none, `bandBottom` itself.
85
+ */
86
+ function orphanExtent(nodes, bandBottom) {
87
+ const orphans = nodes.filter((node) => node.bounds.y >= bandBottom && !NOT_LANE_MEMBERS.has(node.type));
88
+ if (orphans.length === 0)
89
+ return bandBottom;
90
+ return contentBbox(orphans).maxY + PADDING;
91
+ }
70
92
  function nodeToShape(node, dx, dy) {
71
93
  const shape = {
72
94
  id: `${node.id}_di`,
@@ -119,26 +141,6 @@ function edgeToShape(edge, dx, dy) {
119
141
  }
120
142
  return diEdge;
121
143
  }
122
- /**
123
- * Lane shapes for one process: the engine's bands when it placed nodes by lane,
124
- * otherwise the top-level lanes tiled proportionally over the content height.
125
- */
126
- function laneShapesFor(lanes, laneBands, nodes, dx, dy, top, x, width, height) {
127
- if (!laneBands)
128
- return buildLaneShapes(lanes, nodes, dx, dy, top, x, width, height);
129
- return laneBands.map((lane) => ({
130
- id: `${lane.id}_di`,
131
- bpmnElement: lane.id,
132
- isHorizontal: true,
133
- bounds: {
134
- x: Math.round(x),
135
- y: Math.round(lane.bounds.y + dy),
136
- width: Math.round(width),
137
- height: Math.round(lane.bounds.height),
138
- },
139
- unknownAttributes: {},
140
- }));
141
- }
142
144
  function buildLaneShapes(lanes, nodes, dx, dy, poolY, poolHeaderWidth, laneContentWidth, poolHeight) {
143
145
  const elemToLane = new Map();
144
146
  for (const lane of lanes) {
@@ -240,6 +242,36 @@ function withNestedAnnotations(process) {
240
242
  }
241
243
  return { ...process, textAnnotations, associations };
242
244
  }
245
+ /**
246
+ * The lane shapes of a laid-out process, outermost lanes first: the engine's
247
+ * bands when it placed the nodes by lane, each nesting level one header
248
+ * further in with right edges aligned; else top-level bands tiled in
249
+ * proportion to the nodes each lane holds. The outermost lanes start at
250
+ * `frame.left` and span `frame.width`; `frame.top` and `frame.height` are the
251
+ * extent the proportional bands tile. `dx` and `dy` shift layout space onto
252
+ * the plane.
253
+ */
254
+ function laneShapesOf(lanes, levels, laneBands, nodes, dx, dy, frame) {
255
+ if (!laneBands) {
256
+ return buildLaneShapes(lanes, nodes, dx, dy, frame.top, frame.left, frame.width, frame.height);
257
+ }
258
+ const depthOf = new Map(levels.map((level) => [level.lane.id, level.depth]));
259
+ return laneBands.map((lane) => {
260
+ const inset = (depthOf.get(lane.id) ?? 0) * LANE_HEADER;
261
+ return {
262
+ id: `${lane.id}_di`,
263
+ bpmnElement: lane.id,
264
+ isHorizontal: true,
265
+ bounds: {
266
+ x: Math.round(frame.left + inset),
267
+ y: Math.round(lane.bounds.y + dy),
268
+ width: Math.round(frame.width - inset),
269
+ height: Math.round(lane.bounds.height),
270
+ },
271
+ unknownAttributes: {},
272
+ };
273
+ });
274
+ }
243
275
  /** Also used by `expand`, which lays out one process without the pool handling above. */
244
276
  export function addAnnotationShapes(process, layoutNodes, annLocalBounds, allShapes, allEdges, dx, dy) {
245
277
  if (process.textAnnotations.length === 0 && process.associations.length === 0)
@@ -336,6 +368,96 @@ const MESSAGE_FLOW_STEM_STEP = 8;
336
368
  const MESSAGE_FLOW_JOG = 20;
337
369
  const MESSAGE_FLOW_MAX_JOG = 2400;
338
370
  const EMPTY_POOL_WIDTH = 300;
371
+ /**
372
+ * Every lane of a lane set, each parent before its children (pre-order).
373
+ * Empty for an absent lane set.
374
+ *
375
+ * @throws Error when one lane object occurs twice, as a lane set that contains
376
+ * itself does; walking it would never end.
377
+ */
378
+ function laneLevels(laneSet) {
379
+ const levels = [];
380
+ const seen = new Set();
381
+ const walk = (set, depth, parentId) => {
382
+ for (const lane of set.lanes) {
383
+ if (seen.has(lane))
384
+ throw new Error(`Lane ${lane.id} occurs twice in its lane set`);
385
+ seen.add(lane);
386
+ const leaf = (lane.childLaneSet?.lanes.length ?? 0) === 0;
387
+ levels.push(parentId === undefined ? { lane, depth, leaf } : { lane, depth, parentId, leaf });
388
+ if (lane.childLaneSet)
389
+ walk(lane.childLaneSet, depth + 1, lane.id);
390
+ }
391
+ };
392
+ if (laneSet)
393
+ walk(laneSet, 0);
394
+ return levels;
395
+ }
396
+ /**
397
+ * Width the lane headers take at the left of a pool: one header per nesting
398
+ * level, since each level is inset by one header; 0 without lanes.
399
+ */
400
+ function laneHeadersWidth(levels) {
401
+ if (levels.length === 0)
402
+ return 0;
403
+ return (Math.max(...levels.map((level) => level.depth)) + 1) * LANE_HEADER;
404
+ }
405
+ /**
406
+ * Pool and lane shapes for a laned process with no flow nodes. Each leaf lane
407
+ * gets a band of {@link MIN_LANE_HEIGHT} and each parent spans its children, so
408
+ * every lane keeps DI to draw and to drop into. Lanes come outermost first.
409
+ *
410
+ * @returns the shapes, pool first, and the pool height.
411
+ */
412
+ function emptyLanedPool(participantId, levels, poolY) {
413
+ const span = new Map();
414
+ let top = 0;
415
+ for (const level of levels) {
416
+ if (!level.leaf)
417
+ continue;
418
+ span.set(level.lane.id, { top, bottom: top + MIN_LANE_HEIGHT });
419
+ top += MIN_LANE_HEIGHT;
420
+ }
421
+ // Reversed pre-order reaches every child before its parent.
422
+ for (const level of [...levels].reverse()) {
423
+ const own = span.get(level.lane.id);
424
+ if (level.parentId === undefined || !own)
425
+ continue;
426
+ const parent = span.get(level.parentId);
427
+ span.set(level.parentId, parent
428
+ ? { top: Math.min(parent.top, own.top), bottom: Math.max(parent.bottom, own.bottom) }
429
+ : own);
430
+ }
431
+ const shapes = [
432
+ {
433
+ id: `${participantId}_di`,
434
+ bpmnElement: participantId,
435
+ isHorizontal: true,
436
+ bounds: { x: 0, y: poolY, width: EMPTY_POOL_WIDTH, height: top },
437
+ unknownAttributes: {},
438
+ },
439
+ ];
440
+ const ordered = [...levels].sort((a, b) => a.depth - b.depth || (span.get(a.lane.id)?.top ?? 0) - (span.get(b.lane.id)?.top ?? 0));
441
+ for (const { lane, depth } of ordered) {
442
+ const band = span.get(lane.id);
443
+ if (!band)
444
+ continue;
445
+ const inset = POOL_HEADER + depth * LANE_HEADER;
446
+ shapes.push({
447
+ id: `${lane.id}_di`,
448
+ bpmnElement: lane.id,
449
+ isHorizontal: true,
450
+ bounds: {
451
+ x: inset,
452
+ y: poolY + band.top,
453
+ width: EMPTY_POOL_WIDTH - inset,
454
+ height: band.bottom - band.top,
455
+ },
456
+ unknownAttributes: {},
457
+ });
458
+ }
459
+ return { shapes, height: top };
460
+ }
339
461
  /**
340
462
  * Sub-processes the source diagram draws collapsed. A collapsed sub-process
341
463
  * keeps its activity shape on the parent plane and carries its contents on a
@@ -452,7 +574,20 @@ function clearColumn(x, fromY, toY, obstacles, own, dock) {
452
574
  */
453
575
  function messageFlowLeg(dockX, fromY, toY, obstacles, own, dock,
454
576
  /** Staggers the stem so two flows jogging side by side do not share a line. */
455
- stemOffset = 0) {
577
+ stemOffset = 0,
578
+ /** Labels: missed when a nudge on the dock can, otherwise crossed. */
579
+ labels = []) {
580
+ const withLabels = [...obstacles, ...labels];
581
+ const tidy = clearColumn(dockX, fromY, toY, withLabels, own, dock);
582
+ if (!columnBlocked(tidy, fromY, toY, withLabels, own)) {
583
+ return {
584
+ points: [
585
+ { x: tidy, y: fromY },
586
+ { x: tidy, y: toY },
587
+ ],
588
+ blocked: false,
589
+ };
590
+ }
456
591
  const straight = clearColumn(dockX, fromY, toY, obstacles, own, dock);
457
592
  if (!columnBlocked(straight, fromY, toY, obstacles, own)) {
458
593
  return {
@@ -507,7 +642,11 @@ stemOffset = 0) {
507
642
  */
508
643
  function messageFlowRoute(src, tgt, srcIsPool, tgtIsPool, gaps, obstacles, stemOffset,
509
644
  /** Containers holding an endpoint: a route out of one has to cross it. */
510
- containers = []) {
645
+ containers = [],
646
+ /** Shape labels, which a leg sidesteps only when that costs no bend. */
647
+ labels = [],
648
+ /** Snap docks a rounding apart onto one x. */
649
+ snap = true) {
511
650
  const srcBelow = src.y + src.height / 2 > tgt.y + tgt.height / 2;
512
651
  const sy = srcBelow ? src.y : src.y + src.height;
513
652
  const ty = srcBelow ? tgt.y + tgt.height : tgt.y;
@@ -518,9 +657,14 @@ containers = []) {
518
657
  const midpoint = (sy + ty) / 2;
519
658
  const low = Math.min(sy, ty);
520
659
  const high = Math.max(sy, ty);
660
+ const srcX = Math.round(src.x + src.width / 2);
661
+ const centreX = Math.round(tgt.x + tgt.width / 2);
662
+ // Centres a rounding apart are meant to line up: a 1 px jog would cost the
663
+ // message two bends for nothing.
664
+ const tgtX = snap && Math.abs(centreX - srcX) <= 1 ? srcX : centreX;
521
665
  const build = (bandY) => {
522
- const source = messageFlowLeg(Math.round(src.x + src.width / 2), sy, bandY, obstacles, own, src, stemOffset);
523
- const target = messageFlowLeg(Math.round(tgt.x + tgt.width / 2), ty, bandY, obstacles, own, tgt, stemOffset);
666
+ const source = messageFlowLeg(srcX, sy, bandY, obstacles, own, src, stemOffset, labels);
667
+ const target = messageFlowLeg(tgtX, ty, bandY, obstacles, own, tgt, stemOffset, labels);
524
668
  // A pool has no position of its own to respect: dock it under whatever it
525
669
  // is talking to, so the flow drops straight instead of fanning into the
526
670
  // pool's centre along with every other flow.
@@ -565,6 +709,82 @@ containers = []) {
565
709
  const route = build(fallback?.y ?? midpoint);
566
710
  return { source: route.source, target: route.target, gap: fallback?.index ?? -1 };
567
711
  }
712
+ /** Two routes of one message flow that draw the same line. */
713
+ function sameRoute(a, b) {
714
+ const same = (p, q) => p.length === q.length && p.every((w, i) => w.x === q[i]?.x && w.y === q[i]?.y);
715
+ return a.gap === b.gap && same(a.source, b.source) && same(a.target, b.target);
716
+ }
717
+ /**
718
+ * Give every pool the width of the widest, lanes included. Pools already share
719
+ * x 0, so only the right edges move; a lane grows with its pool when it ends
720
+ * where the pool did.
721
+ */
722
+ function uniformPoolFrame(shapes, collab, defs) {
723
+ const participantIds = new Set(collab.participants.map((p) => p.id));
724
+ const laneIds = new Set(defs.processes.flatMap((p) => laneLevels(p.laneSet).map((level) => level.lane.id)));
725
+ const pools = shapes.filter((s) => participantIds.has(s.bpmnElement));
726
+ const right = (b) => b.x + b.width;
727
+ const widest = pools.reduce((max, s) => Math.max(max, right(s.bounds)), EMPTY_POOL_WIDTH);
728
+ for (const pool of pools) {
729
+ const edge = right(pool.bounds);
730
+ if (edge >= widest)
731
+ continue;
732
+ const top = pool.bounds.y;
733
+ const bottom = top + pool.bounds.height;
734
+ for (const lane of shapes) {
735
+ const b = lane.bounds;
736
+ if (!laneIds.has(lane.bpmnElement) || right(b) !== edge)
737
+ continue;
738
+ if (b.y >= top && b.y + b.height <= bottom)
739
+ b.width = widest - b.x;
740
+ }
741
+ pool.bounds.width = widest - pool.bounds.x;
742
+ }
743
+ }
744
+ /**
745
+ * Grid phase for pooled content, before message flows are routed: one x shift
746
+ * for the content of every pool, so columns stay aligned across pools and
747
+ * message flows stay vertical. It stays within the padding (-4..5 px), so no
748
+ * pool or lane frame moves. Rows are left alone: a y shift moves where message
749
+ * flows can run past element labels.
750
+ */
751
+ function poolGridPhaseX(shapes, edges, collab, defs) {
752
+ const participantIds = new Set(collab.participants.map((p) => p.id));
753
+ const laneIds = new Set(defs.processes.flatMap((p) => laneLevels(p.laneSet).map((level) => level.lane.id)));
754
+ const pools = shapes.filter((s) => participantIds.has(s.bpmnElement));
755
+ const within = (y, pool) => y >= pool.bounds.y && y <= pool.bounds.y + pool.bounds.height;
756
+ const inPool = (y) => pools.some((pool) => within(y, pool));
757
+ const content = shapes.filter((s) => !participantIds.has(s.bpmnElement) &&
758
+ !laneIds.has(s.bpmnElement) &&
759
+ inPool(s.bounds.y + s.bounds.height / 2));
760
+ if (content.length === 0)
761
+ return;
762
+ let tx = 0;
763
+ let best = -1;
764
+ for (let t = 0; t < 10; t++) {
765
+ const n = content.filter((s) => (Math.round(s.bounds.x) + t) % 10 === 0 && Math.round(s.bounds.y) % 10 === 0).length;
766
+ if (n > best) {
767
+ best = n;
768
+ tx = t > 5 ? t - 10 : t;
769
+ }
770
+ }
771
+ if (tx === 0)
772
+ return;
773
+ for (const s of content) {
774
+ s.bounds.x += tx;
775
+ if (s.label?.bounds)
776
+ s.label.bounds.x += tx;
777
+ }
778
+ for (const e of edges) {
779
+ const pool = pools.find((p) => e.waypoints[0] && within(e.waypoints[0].y, p));
780
+ if (!pool || !e.waypoints.every((w) => within(w.y, pool)))
781
+ continue;
782
+ for (const w of e.waypoints)
783
+ w.x += tx;
784
+ if (e.label?.bounds)
785
+ e.label.bounds.x += tx;
786
+ }
787
+ }
568
788
  /**
569
789
  * Apply auto-layout to all processes in a BpmnDefinitions, replacing the
570
790
  * diagram interchange (BPMNDi) with freshly computed positions.
@@ -596,6 +816,53 @@ function poolOwners(defs, collab) {
596
816
  }
597
817
  return owners;
598
818
  }
819
+ /**
820
+ * The pools as the crossing sketch sees them: each at its aligned offset with
821
+ * its sequence flows and shapes, plus every message between them.
822
+ */
823
+ function stackSketch(collab, participantPools, layoutOf) {
824
+ const layouts = participantPools.map((p) => (p.process && layoutOf.get(p.process)) || { nodes: [], edges: [] });
825
+ const offsets = alignPools(participantPools.length, layouts.map(contentWidth), messageLinks(collab, participantPools, layouts));
826
+ const ends = new Map();
827
+ const pools = layouts.map((layout, index) => {
828
+ if (layout.nodes.length === 0)
829
+ return { height: EMPTY_POOL_HEIGHT, paths: [] };
830
+ const { minX, minY, maxY } = contentBbox(layout.nodes);
831
+ const lanes = laneLevels(participantPools[index]?.process?.laneSet);
832
+ const dx = (offsets[index] ?? 0) + POOL_HEADER + laneHeadersWidth(lanes) + PADDING - minX;
833
+ const dy = PADDING - minY;
834
+ for (const node of layout.nodes) {
835
+ ends.set(node.id, {
836
+ pool: index,
837
+ x: Math.round(node.bounds.x + node.bounds.width / 2 + dx),
838
+ top: node.bounds.y + dy,
839
+ bottom: node.bounds.y + node.bounds.height + dy,
840
+ });
841
+ }
842
+ return {
843
+ height: poolHeightOf(maxY - minY),
844
+ paths: layout.edges.map((e) => e.waypoints.map((w) => ({ x: w.x + dx, y: w.y + dy }))),
845
+ boxes: layout.nodes.map((n) => ({ ...n.bounds, x: n.bounds.x + dx, y: n.bounds.y + dy })),
846
+ };
847
+ });
848
+ const poolIndex = new Map(participantPools.map((p, i) => [p.participantId, i]));
849
+ const messages = [];
850
+ for (const flow of collab.messageFlows) {
851
+ const a = ends.get(flow.sourceRef);
852
+ const b = ends.get(flow.targetRef);
853
+ const from = a?.pool ?? poolIndex.get(flow.sourceRef);
854
+ const to = b?.pool ?? poolIndex.get(flow.targetRef);
855
+ if (from === undefined || to === undefined)
856
+ continue;
857
+ const message = { from, to };
858
+ if (a)
859
+ message.fromEnd = a;
860
+ if (b)
861
+ message.toEnd = b;
862
+ messages.push(message);
863
+ }
864
+ return { pools, messages };
865
+ }
599
866
  /**
600
867
  * Message flows as pool-to-pool relationships, one per flow, each carrying how
601
868
  * deep inside its pool the message leaves and arrives.
@@ -655,8 +922,7 @@ function messageLinks(collab, pools, layouts) {
655
922
  if (!layout || !pool?.participantId || layout.nodes.length === 0)
656
923
  continue;
657
924
  const { minX } = contentBbox(layout.nodes);
658
- const hasLanes = (pool.process?.laneSet?.lanes.length ?? 0) > 0;
659
- const elemX = POOL_HEADER + (hasLanes ? LANE_HEADER : 0) + PADDING;
925
+ const elemX = POOL_HEADER + laneHeadersWidth(laneLevels(pool.process?.laneSet)) + PADDING;
660
926
  for (const node of layout.nodes) {
661
927
  centres.set(node.id, {
662
928
  pool: index,
@@ -706,7 +972,135 @@ function ancestorIndex(defs, collab) {
706
972
  * @param hints - Tool-grid shapes and annotation sides the builder collected;
707
973
  * they steer placement only and are not written to `defs`.
708
974
  */
975
+ /**
976
+ * Translation (0-9 px per axis) that puts the most shape origins on the 10 px
977
+ * grid. A pure shift keeps every distance, so no other aesthetic moves; ties
978
+ * keep the unshifted position.
979
+ */
980
+ function gridPhase(nodes, dx, dy) {
981
+ const on = (v, t) => (Math.round(v) + t) % 10 === 0;
982
+ let best = { x: 0, y: 0 };
983
+ let bestN = -1;
984
+ for (let ty = 0; ty < 10; ty++) {
985
+ for (let tx = 0; tx < 10; tx++) {
986
+ let n = 0;
987
+ for (const node of nodes) {
988
+ if (on(node.bounds.x + dx, tx) && on(node.bounds.y + dy, ty))
989
+ n++;
990
+ }
991
+ if (n > bestN) {
992
+ bestN = n;
993
+ best = { x: tx, y: ty };
994
+ }
995
+ }
996
+ }
997
+ return best;
998
+ }
999
+ /**
1000
+ * A lane-less pool's height: content plus padding, to the nearest 10 px, so
1001
+ * the pools below start on the grid whatever order they are stacked in.
1002
+ */
1003
+ function poolHeightOf(contentHeight) {
1004
+ return Math.round((contentHeight + 2 * PADDING) / 10) * 10;
1005
+ }
1006
+ /**
1007
+ * Vertical shift (-4..5 px, inside the pool's padding) that puts the most
1008
+ * shapes on the 10 px grid; the smallest shift wins a tie.
1009
+ */
1010
+ function poolGridPhaseY(nodes, dx, dy) {
1011
+ const on = (v) => Math.round(v) % 10 === 0;
1012
+ let best = 0;
1013
+ let bestN = -1;
1014
+ for (const t of [0, -1, 1, -2, 2, -3, 3, -4, 4, 5]) {
1015
+ let n = 0;
1016
+ for (const node of nodes)
1017
+ if (on(node.bounds.x + dx) && on(node.bounds.y + dy + t))
1018
+ n++;
1019
+ if (n > bestN) {
1020
+ bestN = n;
1021
+ best = t;
1022
+ }
1023
+ }
1024
+ return best;
1025
+ }
709
1026
  export function applyAutoLayout(defs, engine = "semantic", hints) {
1027
+ if (engine === "layered" && defs.collaborations.some((c) => c.messageFlows.length > 0)) {
1028
+ // Pools are laid out one by one, blind to the message flows between them.
1029
+ // The layered collaboration stands unless it crosses more messages than
1030
+ // the semantic one composed from the same pool order rules.
1031
+ const layered = layoutWithOrdering(defs, "layered", hints);
1032
+ const semantic = layoutWithOrdering(defs, "semantic", hints);
1033
+ return messageScore(layered).crossings <= messageScore(semantic).crossings ? layered : semantic;
1034
+ }
1035
+ return layoutWithOrdering(defs, engine, hints);
1036
+ }
1037
+ function layoutWithOrdering(defs, engine, hints) {
1038
+ const nearest = { useSketch: false, sketchDiffers: false };
1039
+ const laidOut = layoutDefinitions(defs, engine, hints, nearest);
1040
+ if (!nearest.sketchDiffers)
1041
+ return laidOut;
1042
+ // The sketch only estimates; the drawn result decides. The crossing order
1043
+ // wins only when it crosses less without bending or slanting more.
1044
+ const crossing = layoutDefinitions(defs, engine, hints, {
1045
+ useSketch: true,
1046
+ sketchDiffers: true,
1047
+ });
1048
+ const a = messageScore(laidOut);
1049
+ const b = messageScore(crossing);
1050
+ const better = b.crossings < a.crossings &&
1051
+ b.bends <= a.bends &&
1052
+ b.slanted <= a.slanted &&
1053
+ b.labelsCrossed <= a.labelsCrossed &&
1054
+ b.onGrid >= a.onGrid;
1055
+ return better ? crossing : laidOut;
1056
+ }
1057
+ /**
1058
+ * What a pool order changes in a laid-out diagram: message-flow crossings
1059
+ * (with anything), message bends and slanted messages, labels an edge runs
1060
+ * through, and shapes on the 10 px grid (pools stacked at other heights shift
1061
+ * whole processes off it).
1062
+ */
1063
+ function messageScore(defs) {
1064
+ const ids = new Set(defs.collaborations.flatMap((c) => c.messageFlows.map((f) => f.id)));
1065
+ const plane = defs.diagrams[0]?.plane;
1066
+ const edges = plane?.edges ?? [];
1067
+ const shapes = plane?.shapes ?? [];
1068
+ const messages = edges.filter((e) => ids.has(e.bpmnElement));
1069
+ const others = edges.filter((e) => !ids.has(e.bpmnElement));
1070
+ let crossings = 0;
1071
+ let bends = 0;
1072
+ let slanted = 0;
1073
+ for (let i = 0; i < messages.length; i++) {
1074
+ const path = messages[i]?.waypoints ?? [];
1075
+ for (let j = i + 1; j < messages.length; j++)
1076
+ crossings += pathCrossings(path, messages[j]?.waypoints ?? []);
1077
+ for (const other of others)
1078
+ crossings += pathCrossings(path, other.waypoints);
1079
+ bends += Math.max(0, path.length - 2);
1080
+ if (path.length > 2)
1081
+ slanted++;
1082
+ }
1083
+ const labels = [...shapes, ...edges].flatMap((item) => item.label?.bounds ? [{ owner: item.bpmnElement, bounds: item.label.bounds }] : []);
1084
+ const labelsCrossed = labels.filter((label) => edges.some((e) => e.bpmnElement !== label.owner && pathThrough(e.waypoints, label.bounds))).length;
1085
+ const onGrid = shapes.filter((s) => s.bounds.x % 10 === 0 && s.bounds.y % 10 === 0).length;
1086
+ return { crossings, bends, slanted, labelsCrossed, onGrid };
1087
+ }
1088
+ /** Does an orthogonal polyline pass through the inside of `r` (1 px in from its outline)? */
1089
+ function pathThrough(points, r) {
1090
+ for (let i = 1; i < points.length; i++) {
1091
+ const p = points[i - 1];
1092
+ const q = points[i];
1093
+ if (!p || !q)
1094
+ continue;
1095
+ if (Math.max(p.x, q.x) > r.x + 1 &&
1096
+ Math.min(p.x, q.x) < r.x + r.width - 1 &&
1097
+ Math.max(p.y, q.y) > r.y + 1 &&
1098
+ Math.min(p.y, q.y) < r.y + r.height - 1)
1099
+ return true;
1100
+ }
1101
+ return false;
1102
+ }
1103
+ function layoutDefinitions(defs, engine, hints, ordering) {
710
1104
  if (defs.processes.length === 0)
711
1105
  return defs;
712
1106
  const collab = defs.collaborations[0];
@@ -738,11 +1132,20 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
738
1132
  // stack follows the message flows rather than the declaration order.
739
1133
  for (const pool of participantPools) {
740
1134
  if (pool.process && !layoutOf.has(pool.process)) {
741
- layoutOf.set(pool.process, layoutProcess(pool.process, engine, collapsed, hints?.grids));
1135
+ layoutOf.set(pool.process, layoutProcess(pool.process, engine, collapsed, hints?.grids, true));
742
1136
  }
743
1137
  }
744
1138
  const depths = depthIndex(layoutOf.values());
745
- const order = orderPools(participantPools.length, poolLinks(collab, poolOwners(defs, collab), (id) => depths.get(id)), new Set(participantPools.flatMap((pool, i) => (pool.process ? [] : [i]))));
1139
+ const contentOf = (pool) => (pool.process && layoutOf.get(pool.process)?.nodes) || [];
1140
+ const nearest = orderPools(participantPools.length, poolLinks(collab, poolOwners(defs, collab), (id) => depths.get(id)), new Set(participantPools.flatMap((pool, i) => (contentOf(pool).length > 0 ? [] : [i]))));
1141
+ let order = nearest;
1142
+ if (participantPools.length >= 3 && collab.messageFlows.length > 0) {
1143
+ const sketch = stackSketch(collab, participantPools, layoutOf);
1144
+ const fewer = orderByCrossings(nearest, sketch.pools, sketch.messages);
1145
+ ordering.sketchDiffers = fewer.some((pool, i) => pool !== nearest[i]);
1146
+ if (ordering.useSketch)
1147
+ order = fewer;
1148
+ }
746
1149
  for (const index of order) {
747
1150
  const pool = participantPools[index];
748
1151
  if (pool)
@@ -760,11 +1163,10 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
760
1163
  // Lay every pool out first: alignment needs to see all of them before any
761
1164
  // geometry is committed.
762
1165
  const layouts = pools.map((pool) => pool.process
763
- ? (layoutOf.get(pool.process) ?? layoutProcess(pool.process, engine, collapsed, hints?.grids))
1166
+ ? (layoutOf.get(pool.process) ??
1167
+ layoutProcess(pool.process, engine, collapsed, hints?.grids, pool.participantId !== undefined))
764
1168
  : { nodes: [], edges: [] });
765
1169
  const alignment = alignPools(pools.length, layouts.map((layout) => contentWidth(layout)), messageLinks(collab, pools, layouts));
766
- /** Pools with nothing to draw; widened to match the others once all are placed. */
767
- const blackBoxPools = [];
768
1170
  /** Root processes that are not the primary one, each on a plane of its own. */
769
1171
  const rootPlanes = [];
770
1172
  const primaryProcessId = defs.processes[0]?.id;
@@ -775,6 +1177,8 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
775
1177
  const { participantId, process } = pool;
776
1178
  const lanes = process?.laneSet?.lanes ?? [];
777
1179
  const hasLanes = lanes.length > 0;
1180
+ const levels = laneLevels(process?.laneSet);
1181
+ const headersWidth = laneHeadersWidth(levels);
778
1182
  const result = layouts[poolIndex] ?? { nodes: [], edges: [] };
779
1183
  const alignDx = alignment[poolIndex] ?? 0;
780
1184
  // A participant with no process, or one whose process has no flow nodes,
@@ -791,6 +1195,13 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
791
1195
  addAnnotationShapes(process, [], annOnly, allShapes, allEdges, PADDING - bbox.minX, PADDING - bbox.minY);
792
1196
  continue;
793
1197
  }
1198
+ // Lanes with nothing in them still need bands, or they have no DI at all.
1199
+ if (participantId && hasLanes) {
1200
+ const empty = emptyLanedPool(participantId, levels, poolY);
1201
+ allShapes.push(...empty.shapes);
1202
+ poolY += empty.height + POOL_GAP;
1203
+ continue;
1204
+ }
794
1205
  if (participantId) {
795
1206
  const shape = {
796
1207
  id: `${participantId}_di`,
@@ -800,7 +1211,6 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
800
1211
  unknownAttributes: {},
801
1212
  };
802
1213
  allShapes.push(shape);
803
- blackBoxPools.push(shape);
804
1214
  poolY += EMPTY_POOL_HEIGHT + POOL_GAP;
805
1215
  }
806
1216
  continue;
@@ -832,21 +1242,33 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
832
1242
  let dx;
833
1243
  let dy;
834
1244
  if (participantId) {
835
- const elemX = POOL_HEADER + (hasLanes ? LANE_HEADER : 0) + PADDING;
1245
+ const elemX = POOL_HEADER + headersWidth + PADDING;
836
1246
  dx = elemX - minX + alignDx;
837
1247
  dy = laneBands ? poolY - bandTop : poolY + PADDING - minY;
1248
+ // x is the message alignment's to keep, and lane bands fix y; otherwise
1249
+ // a few px of the padding put the most shapes on the 10 px grid.
1250
+ if (!laneBands)
1251
+ dy += poolGridPhaseY(result.nodes, dx, dy);
838
1252
  }
839
1253
  else {
840
1254
  // A process outside any pool draws its lanes on the plane itself (bpmn-js
841
1255
  // imports lane DI under a process root), header at x 0, so the content
842
- // clears the lane header the way it does in a pool.
1256
+ // clears the lane headers the way it does in a pool.
843
1257
  // A layout pass must not invent a participant to hold them.
844
- dx = (hasLanes ? LANE_HEADER : 0) + PADDING - minX;
1258
+ dx = headersWidth + PADDING - minX;
845
1259
  dy = laneBands ? processTop - bandTop : processTop + PADDING - minY;
1260
+ const phase = gridPhase(result.nodes, dx, dy);
1261
+ dx += phase.x;
1262
+ dy += phase.y;
846
1263
  }
847
1264
  /** Lanes of a process outside any pool, drawn straight on its plane. */
848
1265
  const bareLanes = !participantId && hasLanes
849
- ? laneShapesFor(lanes, laneBands, result.nodes, dx, dy, processTop, 0, LANE_HEADER + contentW + 2 * PADDING, laneBands ? bandHeight : contentH + 2 * PADDING)
1266
+ ? laneShapesOf(lanes, levels, laneBands, result.nodes, dx, dy, {
1267
+ left: 0,
1268
+ top: processTop,
1269
+ width: headersWidth + contentW + 2 * PADDING,
1270
+ height: laneBands ? bandHeight : contentH + 2 * PADDING,
1271
+ })
850
1272
  : [];
851
1273
  // Only the primary process shares the root plane; any other root process
852
1274
  // owns one, instead of being stacked on top of the first at the origin.
@@ -871,33 +1293,38 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
871
1293
  }
872
1294
  allShapes.push(...bareLanes);
873
1295
  if (participantId) {
874
- const innerW = (hasLanes ? LANE_HEADER : 0) + contentW + 2 * PADDING + alignDx;
875
- // Lanes must tile the pool exactly, so the pool takes their height.
876
- const innerH = laneBands ? bandHeight : contentH + 2 * PADDING;
877
- const poolW = POOL_HEADER + innerW;
1296
+ const innerW = headersWidth + contentW + 2 * PADDING + alignDx;
1297
+ // Lanes must tile the pool exactly, so the pool takes their height, and
1298
+ // grows past them only for nodes no lane claims, which the engine
1299
+ // places below the bands.
1300
+ const innerH = laneBands
1301
+ ? Math.max(bandHeight, orphanExtent(result.nodes, bandTop + bandHeight) - bandTop)
1302
+ : poolHeightOf(contentH);
878
1303
  allShapes.push({
879
1304
  id: `${participantId}_di`,
880
1305
  bpmnElement: participantId,
881
1306
  isHorizontal: true,
882
- bounds: { x: 0, y: poolY, width: poolW, height: innerH },
1307
+ bounds: { x: 0, y: poolY, width: POOL_HEADER + innerW, height: innerH },
883
1308
  unknownAttributes: {},
884
1309
  });
885
1310
  if (hasLanes) {
886
- allShapes.push(...laneShapesFor(lanes, laneBands, result.nodes, dx, dy, poolY, POOL_HEADER, innerW, innerH));
1311
+ allShapes.push(...laneShapesOf(lanes, levels, laneBands, result.nodes, dx, dy, {
1312
+ left: POOL_HEADER,
1313
+ top: poolY,
1314
+ width: innerW,
1315
+ height: innerH,
1316
+ }));
887
1317
  }
888
1318
  poolY += innerH + POOL_GAP;
889
1319
  }
890
1320
  }
891
- // Give the black boxes the width of the widest pool that has content, so the
892
- // stack reads as one diagram rather than a ragged column.
893
- if (blackBoxPools.length > 0) {
894
- const participantIds = new Set(collab?.participants.map((p) => p.id) ?? []);
895
- const widest = allShapes
896
- .filter((s) => participantIds.has(s.bpmnElement) && !blackBoxPools.includes(s))
897
- .reduce((max, s) => Math.max(max, s.bounds.width), EMPTY_POOL_WIDTH);
898
- for (const shape of blackBoxPools)
899
- shape.bounds.width = widest;
900
- }
1321
+ // One frame for every pool: the stack reads as one diagram rather than a
1322
+ // ragged column, black boxes included.
1323
+ if (collab)
1324
+ uniformPoolFrame(allShapes, collab, defs);
1325
+ if (collab)
1326
+ poolGridPhaseX(allShapes, allEdges, collab, defs);
1327
+ const repair = routeRepair(defs);
901
1328
  if (collab && collab.messageFlows.length > 0) {
902
1329
  const shapeByElement = new Map(allShapes.map((s) => [s.bpmnElement, s.bounds]));
903
1330
  // An endpoint inside a collapsed sub-process has no shape on this plane;
@@ -911,15 +1338,22 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
911
1338
  return current ?? id;
912
1339
  };
913
1340
  const participantIds = new Set(collab.participants.map((p) => p.id));
914
- const laneIds = new Set(defs.processes.flatMap((p) => (p.laneSet?.lanes ?? []).map((lane) => lane.id)));
1341
+ const laneIds = new Set(defs.processes.flatMap((p) => laneLevels(p.laneSet).map((level) => level.lane.id)));
915
1342
  // Pools and lanes are containers; message flows cross them by design. It is
916
1343
  // the elements inside that a route has to miss.
917
- const obstacles = allShapes
918
- .filter((s) => !participantIds.has(s.bpmnElement) && !laneIds.has(s.bpmnElement))
919
- .map((s) => s.bounds);
1344
+ const inside = allShapes.filter((s) => !participantIds.has(s.bpmnElement) && !laneIds.has(s.bpmnElement));
1345
+ const obstacles = inside.map((s) => s.bounds);
1346
+ // Labels are worth a sideways nudge on the dock, never a jog: a riser
1347
+ // through a name is hard to read, but two extra bends read worse.
1348
+ const labels = inside.flatMap((s) => (s.label?.bounds ? [s.label.bounds] : []));
920
1349
  const poolGaps = poolBands(allShapes, participantIds);
921
- const runs = [];
922
- /** Bounds of every expanded scope an element sits inside. */
1350
+ /**
1351
+ * Each message flow routed twice: `tidy` lines up docks a rounding apart
1352
+ * and nudges a riser off element labels; `plain` does neither. A nudge is
1353
+ * local and can push a riser across another message's run, so a flow keeps
1354
+ * its tidy route only where that adds no crossing (see below).
1355
+ */
1356
+ const candidates = [];
923
1357
  const containersOf = (id) => {
924
1358
  const out = [];
925
1359
  let parent = visibleAncestors.get(id);
@@ -931,6 +1365,12 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
931
1365
  }
932
1366
  return out;
933
1367
  };
1368
+ const labelByElement = new Map(allShapes.flatMap((s) => (s.label?.bounds ? [[s.bpmnElement, s.label.bounds]] : [])));
1369
+ /** An endpoint's own label: the message starts or ends right beside it. */
1370
+ const labelOf = (id) => {
1371
+ const label = labelByElement.get(id);
1372
+ return label ? [label] : [];
1373
+ };
934
1374
  let stemOffset = 0;
935
1375
  for (const mf of collab.messageFlows) {
936
1376
  const sourceRef = resolve(mf.sourceRef);
@@ -939,50 +1379,122 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
939
1379
  const tgt = shapeByElement.get(targetRef);
940
1380
  if (!src || !tgt)
941
1381
  continue;
942
- const run = {
1382
+ const route = (tidy) => messageFlowRoute(src, tgt, participantIds.has(sourceRef), participantIds.has(targetRef), poolGaps, obstacles, stemOffset, [
1383
+ ...containersOf(sourceRef),
1384
+ ...containersOf(targetRef),
1385
+ ...(tidy ? [...labelOf(sourceRef), ...labelOf(targetRef)] : []),
1386
+ ], tidy ? labels : [], tidy);
1387
+ candidates.push({
943
1388
  id: mf.id,
944
- ...messageFlowRoute(src, tgt, participantIds.has(sourceRef), participantIds.has(targetRef), poolGaps, obstacles, stemOffset, [...containersOf(sourceRef), ...containersOf(targetRef)]),
945
- };
946
- runs.push(run);
1389
+ from: sourceRef,
1390
+ to: targetRef,
1391
+ tidy: route(true),
1392
+ plain: route(false),
1393
+ });
947
1394
  stemOffset = (stemOffset + MESSAGE_FLOW_STEM_STEP) % (MESSAGE_FLOW_STEM_STEP * 4);
948
1395
  }
949
- // Flows sharing a gap get their own line inside it, so parallel runs do not
950
- // pile onto one row and cross every other flow's riser.
951
- const perGap = new Map();
952
- for (const run of runs) {
953
- const list = perGap.get(run.gap);
954
- if (list)
955
- list.push(run);
956
- else
957
- perGap.set(run.gap, [run]);
958
- }
959
1396
  const endX = (points) => points[points.length - 1]?.x ?? 0;
960
- for (const [index, list] of perGap) {
961
- const gap = poolGaps[index];
962
- if (!gap)
963
- continue;
964
- list.sort((a, b) => Math.min(endX(a.source), endX(a.target)) - Math.min(endX(b.source), endX(b.target)));
965
- for (let i = 0; i < list.length; i++) {
966
- const run = list[i];
967
- if (!run)
1397
+ const copy = (points) => points.map((p) => ({ ...p }));
1398
+ /** The finished waypoints of every message flow, tidy where `tidy[i]`. */
1399
+ const place = (tidy) => {
1400
+ const runs = candidates.map((c, i) => {
1401
+ const r = tidy[i] ? c.tidy : c.plain;
1402
+ return { source: copy(r.source), target: copy(r.target), gap: r.gap };
1403
+ });
1404
+ // Flows sharing a gap get their own line inside it, so parallel runs do
1405
+ // not pile onto one row and cross every other flow's riser.
1406
+ const perGap = new Map();
1407
+ for (const run of runs) {
1408
+ const list = perGap.get(run.gap);
1409
+ if (list)
1410
+ list.push(run);
1411
+ else
1412
+ perGap.set(run.gap, [run]);
1413
+ }
1414
+ for (const [index, list] of perGap) {
1415
+ const gap = poolGaps[index];
1416
+ if (!gap)
968
1417
  continue;
969
1418
  // The gap is clear ground, so moving the crossing inside it cannot
970
- // introduce a collision.
971
- const y = Math.round(gap.top + ((i + 1) * (gap.bottom - gap.top)) / (list.length + 1));
972
- const last = run.source[run.source.length - 1];
973
- const lastTarget = run.target[run.target.length - 1];
974
- if (last)
975
- last.y = y;
976
- if (lastTarget)
977
- lastTarget.y = y;
1419
+ // introduce a collision; the track order decides the crossings.
1420
+ const fromAbove = (run) => (run.source[0]?.y ?? 0) < gap.top;
1421
+ const ys = assignTracks(list.map((run) => ({
1422
+ upper: fromAbove(run) ? endX(run.source) : endX(run.target),
1423
+ lower: fromAbove(run) ? endX(run.target) : endX(run.source),
1424
+ })), gap.top, gap.bottom);
1425
+ for (let i = 0; i < list.length; i++) {
1426
+ const run = list[i];
1427
+ const y = ys[i];
1428
+ if (!run || y === undefined)
1429
+ continue;
1430
+ const last = run.source[run.source.length - 1];
1431
+ const lastTarget = run.target[run.target.length - 1];
1432
+ if (last)
1433
+ last.y = y;
1434
+ if (lastTarget)
1435
+ lastTarget.y = y;
1436
+ }
1437
+ }
1438
+ return runs.map((run) => collapseCollinear([...run.source, ...[...run.target].reverse()]));
1439
+ };
1440
+ // Start from the plain routes and take each tidy one that adds no
1441
+ // crossing with the other messages or the flows already drawn, so the
1442
+ // tidying can never cost a crossing. Scored after the final route repair,
1443
+ // which reroutes a message still running through a shape.
1444
+ const crossingsOf = (paths) => {
1445
+ const drawn = allEdges.map((e) => ({
1446
+ ...e,
1447
+ waypoints: e.waypoints.map((w) => ({ ...w })),
1448
+ }));
1449
+ const messages = candidates.map((c, i) => ({
1450
+ id: `${c.id}_di`,
1451
+ bpmnElement: c.id,
1452
+ waypoints: copy(paths[i] ?? []),
1453
+ unknownAttributes: {},
1454
+ }));
1455
+ repair(allShapes, [...drawn, ...messages]);
1456
+ let n = 0;
1457
+ for (let i = 0; i < messages.length; i++) {
1458
+ const path = messages[i]?.waypoints ?? [];
1459
+ for (let j = i + 1; j < messages.length; j++)
1460
+ n += pathCrossings(path, messages[j]?.waypoints ?? []);
1461
+ for (const other of drawn)
1462
+ n += pathCrossings(path, other.waypoints);
978
1463
  }
1464
+ return n;
1465
+ };
1466
+ const tidy = candidates.map(() => false);
1467
+ let paths = place(tidy);
1468
+ let best = crossingsOf(paths);
1469
+ for (let i = 0; i < candidates.length; i++) {
1470
+ const c = candidates[i];
1471
+ if (!c || sameRoute(c.tidy, c.plain))
1472
+ continue;
1473
+ tidy[i] = true;
1474
+ const trial = place(tidy);
1475
+ const n = crossingsOf(trial);
1476
+ if (n <= best) {
1477
+ best = n;
1478
+ paths = trial;
1479
+ }
1480
+ else
1481
+ tidy[i] = false;
979
1482
  }
980
- for (const run of runs) {
981
- const waypoints = collapseCollinear([...run.source, ...[...run.target].reverse()]);
1483
+ const docks = [];
1484
+ for (let i = 0; i < candidates.length; i++) {
1485
+ const run = candidates[i];
1486
+ const waypoints = paths[i];
1487
+ if (!run || !waypoints)
1488
+ continue;
982
1489
  allEdges.push({ id: `${run.id}_di`, bpmnElement: run.id, waypoints, unknownAttributes: {} });
1490
+ docks.push({ element: run.from, y: waypoints[0]?.y ?? 0 }, { element: run.to, y: waypoints[waypoints.length - 1]?.y ?? 0 });
983
1491
  }
1492
+ flipDockedLabels(allShapes, allEdges, docks, new Set([
1493
+ ...participantIds,
1494
+ ...laneIds,
1495
+ ...allShapes.filter((s) => s.isExpanded === true).map((s) => s.bpmnElement),
1496
+ ]));
984
1497
  }
985
- const repair = routeRepair(defs);
986
1498
  repair(allShapes, allEdges);
987
1499
  if (collab && collab.messageFlows.length > 0) {
988
1500
  const pools = new Set(collab.participants.map((p) => p.id));
@@ -1210,13 +1722,8 @@ function routeRepair(defs) {
1210
1722
  }
1211
1723
  for (const group of process.groups ?? [])
1212
1724
  containers.add(group.id);
1213
- const lanes = (set) => {
1214
- for (const lane of set?.lanes ?? []) {
1215
- containers.add(lane.id);
1216
- lanes(lane.childLaneSet);
1217
- }
1218
- };
1219
- lanes(process.laneSet);
1725
+ for (const level of laneLevels(process.laneSet))
1726
+ containers.add(level.lane.id);
1220
1727
  }
1221
1728
  const related = (id) => {
1222
1729
  const out = [...(attachers.get(id) ?? [])];