@bpmnkit/core 1.16.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 (35) hide show
  1. package/dist/bpmn/auto-layout.d.ts +0 -8
  2. package/dist/bpmn/auto-layout.js +432 -59
  3. package/dist/bpmn/make-room.js +114 -0
  4. package/dist/bpmn/place-new-shapes.js +4 -2
  5. package/dist/layout/collaboration/crossings.d.ts +13 -0
  6. package/dist/layout/collaboration/crossings.js +37 -0
  7. package/dist/layout/collaboration/docked-labels.d.ts +21 -0
  8. package/dist/layout/collaboration/docked-labels.js +65 -0
  9. package/dist/layout/collaboration/message-tracks.d.ts +20 -0
  10. package/dist/layout/collaboration/message-tracks.js +78 -0
  11. package/dist/layout/collaboration/stack-crossings.d.ts +38 -0
  12. package/dist/layout/collaboration/stack-crossings.js +155 -0
  13. package/dist/layout/grid/edge-labels.js +21 -10
  14. package/dist/layout/layered/coords.d.ts +13 -0
  15. package/dist/layout/layered/coords.js +211 -0
  16. package/dist/layout/layered/index.d.ts +21 -0
  17. package/dist/layout/layered/index.js +288 -0
  18. package/dist/layout/layered/layers.d.ts +60 -0
  19. package/dist/layout/layered/layers.js +374 -0
  20. package/dist/layout/layered/route.d.ts +66 -0
  21. package/dist/layout/layered/route.js +369 -0
  22. package/dist/layout/layout-engine.d.ts +6 -2
  23. package/dist/layout/layout-engine.js +4 -2
  24. package/dist/layout/semantic/bands.js +8 -2
  25. package/dist/layout/semantic/graph.d.ts +33 -1
  26. package/dist/layout/semantic/graph.js +200 -4
  27. package/dist/layout/semantic/index.d.ts +8 -2
  28. package/dist/layout/semantic/index.js +114 -14
  29. package/dist/layout/semantic/lanes.d.ts +40 -0
  30. package/dist/layout/semantic/lanes.js +198 -0
  31. package/dist/layout/semantic/place.d.ts +44 -2
  32. package/dist/layout/semantic/place.js +220 -21
  33. package/dist/layout/semantic/route.js +35 -2
  34. package/dist/layout/types.d.ts +0 -8
  35. package/package.json +1 -1
@@ -3,13 +3,5 @@ import type { Bounds, LayoutHints, LayoutNode } from "../layout/types.js";
3
3
  import type { BpmnDefinitions, BpmnDiEdge, BpmnDiShape, BpmnProcess } from "./bpmn-model.js";
4
4
  /** Also used by `expand`, which lays out one process without the pool handling above. */
5
5
  export declare function addAnnotationShapes(process: BpmnProcess, layoutNodes: LayoutNode[], annLocalBounds: Map<string, Bounds>, allShapes: BpmnDiShape[], allEdges: BpmnDiEdge[], dx: number, dy: number): void;
6
- /**
7
- * Replace every diagram-interchange position in `defs` with a computed layout.
8
- *
9
- * @param engine - Which process layout algorithm to run. Defaults to `semantic`;
10
- * `grid` runs the older cell-grid walk and is used to compare the two.
11
- * @param hints - Tool-grid shapes and annotation sides the builder collected;
12
- * they steer placement only and are not written to `defs`.
13
- */
14
6
  export declare function applyAutoLayout(defs: BpmnDefinitions, engine?: LayoutEngine, hints?: LayoutHints): BpmnDefinitions;
15
7
  //# sourceMappingURL=auto-layout.d.ts.map
@@ -1,7 +1,11 @@
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";
@@ -570,7 +574,20 @@ function clearColumn(x, fromY, toY, obstacles, own, dock) {
570
574
  */
571
575
  function messageFlowLeg(dockX, fromY, toY, obstacles, own, dock,
572
576
  /** Staggers the stem so two flows jogging side by side do not share a line. */
573
- 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
+ }
574
591
  const straight = clearColumn(dockX, fromY, toY, obstacles, own, dock);
575
592
  if (!columnBlocked(straight, fromY, toY, obstacles, own)) {
576
593
  return {
@@ -625,7 +642,11 @@ stemOffset = 0) {
625
642
  */
626
643
  function messageFlowRoute(src, tgt, srcIsPool, tgtIsPool, gaps, obstacles, stemOffset,
627
644
  /** Containers holding an endpoint: a route out of one has to cross it. */
628
- 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) {
629
650
  const srcBelow = src.y + src.height / 2 > tgt.y + tgt.height / 2;
630
651
  const sy = srcBelow ? src.y : src.y + src.height;
631
652
  const ty = srcBelow ? tgt.y + tgt.height : tgt.y;
@@ -636,9 +657,14 @@ containers = []) {
636
657
  const midpoint = (sy + ty) / 2;
637
658
  const low = Math.min(sy, ty);
638
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;
639
665
  const build = (bandY) => {
640
- const source = messageFlowLeg(Math.round(src.x + src.width / 2), sy, bandY, obstacles, own, src, stemOffset);
641
- 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);
642
668
  // A pool has no position of its own to respect: dock it under whatever it
643
669
  // is talking to, so the flow drops straight instead of fanning into the
644
670
  // pool's centre along with every other flow.
@@ -683,6 +709,82 @@ containers = []) {
683
709
  const route = build(fallback?.y ?? midpoint);
684
710
  return { source: route.source, target: route.target, gap: fallback?.index ?? -1 };
685
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
+ }
686
788
  /**
687
789
  * Apply auto-layout to all processes in a BpmnDefinitions, replacing the
688
790
  * diagram interchange (BPMNDi) with freshly computed positions.
@@ -714,6 +816,53 @@ function poolOwners(defs, collab) {
714
816
  }
715
817
  return owners;
716
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
+ }
717
866
  /**
718
867
  * Message flows as pool-to-pool relationships, one per flow, each carrying how
719
868
  * deep inside its pool the message leaves and arrives.
@@ -823,7 +972,135 @@ function ancestorIndex(defs, collab) {
823
972
  * @param hints - Tool-grid shapes and annotation sides the builder collected;
824
973
  * they steer placement only and are not written to `defs`.
825
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
+ }
826
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) {
827
1104
  if (defs.processes.length === 0)
828
1105
  return defs;
829
1106
  const collab = defs.collaborations[0];
@@ -855,11 +1132,20 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
855
1132
  // stack follows the message flows rather than the declaration order.
856
1133
  for (const pool of participantPools) {
857
1134
  if (pool.process && !layoutOf.has(pool.process)) {
858
- layoutOf.set(pool.process, layoutProcess(pool.process, engine, collapsed, hints?.grids));
1135
+ layoutOf.set(pool.process, layoutProcess(pool.process, engine, collapsed, hints?.grids, true));
859
1136
  }
860
1137
  }
861
1138
  const depths = depthIndex(layoutOf.values());
862
- 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
+ }
863
1149
  for (const index of order) {
864
1150
  const pool = participantPools[index];
865
1151
  if (pool)
@@ -877,11 +1163,10 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
877
1163
  // Lay every pool out first: alignment needs to see all of them before any
878
1164
  // geometry is committed.
879
1165
  const layouts = pools.map((pool) => pool.process
880
- ? (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))
881
1168
  : { nodes: [], edges: [] });
882
1169
  const alignment = alignPools(pools.length, layouts.map((layout) => contentWidth(layout)), messageLinks(collab, pools, layouts));
883
- /** Pools with nothing to draw; widened to match the others once all are placed. */
884
- const blackBoxPools = [];
885
1170
  /** Root processes that are not the primary one, each on a plane of its own. */
886
1171
  const rootPlanes = [];
887
1172
  const primaryProcessId = defs.processes[0]?.id;
@@ -926,7 +1211,6 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
926
1211
  unknownAttributes: {},
927
1212
  };
928
1213
  allShapes.push(shape);
929
- blackBoxPools.push(shape);
930
1214
  poolY += EMPTY_POOL_HEIGHT + POOL_GAP;
931
1215
  }
932
1216
  continue;
@@ -961,6 +1245,10 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
961
1245
  const elemX = POOL_HEADER + headersWidth + PADDING;
962
1246
  dx = elemX - minX + alignDx;
963
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);
964
1252
  }
965
1253
  else {
966
1254
  // A process outside any pool draws its lanes on the plane itself (bpmn-js
@@ -969,6 +1257,9 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
969
1257
  // A layout pass must not invent a participant to hold them.
970
1258
  dx = headersWidth + PADDING - minX;
971
1259
  dy = laneBands ? processTop - bandTop : processTop + PADDING - minY;
1260
+ const phase = gridPhase(result.nodes, dx, dy);
1261
+ dx += phase.x;
1262
+ dy += phase.y;
972
1263
  }
973
1264
  /** Lanes of a process outside any pool, drawn straight on its plane. */
974
1265
  const bareLanes = !participantId && hasLanes
@@ -1008,7 +1299,7 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
1008
1299
  // places below the bands.
1009
1300
  const innerH = laneBands
1010
1301
  ? Math.max(bandHeight, orphanExtent(result.nodes, bandTop + bandHeight) - bandTop)
1011
- : contentH + 2 * PADDING;
1302
+ : poolHeightOf(contentH);
1012
1303
  allShapes.push({
1013
1304
  id: `${participantId}_di`,
1014
1305
  bpmnElement: participantId,
@@ -1027,16 +1318,13 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
1027
1318
  poolY += innerH + POOL_GAP;
1028
1319
  }
1029
1320
  }
1030
- // Give the black boxes the width of the widest pool that has content, so the
1031
- // stack reads as one diagram rather than a ragged column.
1032
- if (blackBoxPools.length > 0) {
1033
- const participantIds = new Set(collab?.participants.map((p) => p.id) ?? []);
1034
- const widest = allShapes
1035
- .filter((s) => participantIds.has(s.bpmnElement) && !blackBoxPools.includes(s))
1036
- .reduce((max, s) => Math.max(max, s.bounds.width), EMPTY_POOL_WIDTH);
1037
- for (const shape of blackBoxPools)
1038
- shape.bounds.width = widest;
1039
- }
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);
1040
1328
  if (collab && collab.messageFlows.length > 0) {
1041
1329
  const shapeByElement = new Map(allShapes.map((s) => [s.bpmnElement, s.bounds]));
1042
1330
  // An endpoint inside a collapsed sub-process has no shape on this plane;
@@ -1053,12 +1341,19 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
1053
1341
  const laneIds = new Set(defs.processes.flatMap((p) => laneLevels(p.laneSet).map((level) => level.lane.id)));
1054
1342
  // Pools and lanes are containers; message flows cross them by design. It is
1055
1343
  // the elements inside that a route has to miss.
1056
- const obstacles = allShapes
1057
- .filter((s) => !participantIds.has(s.bpmnElement) && !laneIds.has(s.bpmnElement))
1058
- .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] : []));
1059
1349
  const poolGaps = poolBands(allShapes, participantIds);
1060
- const runs = [];
1061
- /** 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 = [];
1062
1357
  const containersOf = (id) => {
1063
1358
  const out = [];
1064
1359
  let parent = visibleAncestors.get(id);
@@ -1070,6 +1365,12 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
1070
1365
  }
1071
1366
  return out;
1072
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
+ };
1073
1374
  let stemOffset = 0;
1074
1375
  for (const mf of collab.messageFlows) {
1075
1376
  const sourceRef = resolve(mf.sourceRef);
@@ -1078,50 +1379,122 @@ export function applyAutoLayout(defs, engine = "semantic", hints) {
1078
1379
  const tgt = shapeByElement.get(targetRef);
1079
1380
  if (!src || !tgt)
1080
1381
  continue;
1081
- 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({
1082
1388
  id: mf.id,
1083
- ...messageFlowRoute(src, tgt, participantIds.has(sourceRef), participantIds.has(targetRef), poolGaps, obstacles, stemOffset, [...containersOf(sourceRef), ...containersOf(targetRef)]),
1084
- };
1085
- runs.push(run);
1389
+ from: sourceRef,
1390
+ to: targetRef,
1391
+ tidy: route(true),
1392
+ plain: route(false),
1393
+ });
1086
1394
  stemOffset = (stemOffset + MESSAGE_FLOW_STEM_STEP) % (MESSAGE_FLOW_STEM_STEP * 4);
1087
1395
  }
1088
- // Flows sharing a gap get their own line inside it, so parallel runs do not
1089
- // pile onto one row and cross every other flow's riser.
1090
- const perGap = new Map();
1091
- for (const run of runs) {
1092
- const list = perGap.get(run.gap);
1093
- if (list)
1094
- list.push(run);
1095
- else
1096
- perGap.set(run.gap, [run]);
1097
- }
1098
1396
  const endX = (points) => points[points.length - 1]?.x ?? 0;
1099
- for (const [index, list] of perGap) {
1100
- const gap = poolGaps[index];
1101
- if (!gap)
1102
- continue;
1103
- list.sort((a, b) => Math.min(endX(a.source), endX(a.target)) - Math.min(endX(b.source), endX(b.target)));
1104
- for (let i = 0; i < list.length; i++) {
1105
- const run = list[i];
1106
- 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)
1107
1417
  continue;
1108
1418
  // The gap is clear ground, so moving the crossing inside it cannot
1109
- // introduce a collision.
1110
- const y = Math.round(gap.top + ((i + 1) * (gap.bottom - gap.top)) / (list.length + 1));
1111
- const last = run.source[run.source.length - 1];
1112
- const lastTarget = run.target[run.target.length - 1];
1113
- if (last)
1114
- last.y = y;
1115
- if (lastTarget)
1116
- 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);
1117
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;
1118
1482
  }
1119
- for (const run of runs) {
1120
- 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;
1121
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 });
1122
1491
  }
1492
+ flipDockedLabels(allShapes, allEdges, docks, new Set([
1493
+ ...participantIds,
1494
+ ...laneIds,
1495
+ ...allShapes.filter((s) => s.isExpanded === true).map((s) => s.bpmnElement),
1496
+ ]));
1123
1497
  }
1124
- const repair = routeRepair(defs);
1125
1498
  repair(allShapes, allEdges);
1126
1499
  if (collab && collab.messageFlows.length > 0) {
1127
1500
  const pools = new Set(collab.participants.map((p) => p.id));