orcasvn-react-diagrams 0.2.4 → 0.2.6

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 (75) hide show
  1. package/CHANGELOG.md +42 -4
  2. package/README.md +15 -32
  3. package/ai/api-contract.json +88 -3
  4. package/ai/manifest.json +1 -1
  5. package/dist/cjs/examples.js +6519 -4423
  6. package/dist/cjs/index.js +1513 -120
  7. package/dist/cjs/types/api/createDiagramEditor.d.ts +4 -1
  8. package/dist/cjs/types/api/types.d.ts +43 -1
  9. package/dist/cjs/types/displaybox/demos/LinkColorPoolDemoTab.d.ts +3 -0
  10. package/dist/cjs/types/displaybox/demos/OffsetAnchorAvoidanceDemoTab.d.ts +3 -0
  11. package/dist/cjs/types/displaybox/demos/SimpleDemo.d.ts +4 -1
  12. package/dist/cjs/types/displaybox/demos/ZoomToFitElementsDemoTab.d.ts +3 -0
  13. package/dist/cjs/types/displaybox/demos/linkColorPoolDemo.d.ts +2 -0
  14. package/dist/cjs/types/displaybox/demos/offsetAnchorAvoidanceDemo.d.ts +4 -0
  15. package/dist/cjs/types/displaybox/demos/textDemo.d.ts +3 -0
  16. package/dist/cjs/types/displaybox/demos/zoomToFitElementsDemo.d.ts +4 -0
  17. package/dist/cjs/types/displaybox/types.d.ts +3 -1
  18. package/dist/cjs/types/displaybox/useDemoEditor.d.ts +4 -2
  19. package/dist/cjs/types/engine/AutoLayoutService.d.ts +59 -2
  20. package/dist/cjs/types/engine/DiagramEngine.d.ts +20 -1
  21. package/dist/cjs/types/engine/LinkRoutingService.d.ts +9 -0
  22. package/dist/cjs/types/models/TextModel.d.ts +1 -0
  23. package/dist/cjs/types/renderer/konva/KonvaInteraction.d.ts +6 -0
  24. package/dist/cjs/types/strategies/ObstacleRouter.d.ts +2 -0
  25. package/dist/cjs/types/strategies/RouterStrategy.d.ts +10 -0
  26. package/dist/esm/examples.js +6519 -4423
  27. package/dist/esm/examples.js.map +1 -1
  28. package/dist/esm/index.js +1513 -120
  29. package/dist/esm/index.js.map +1 -1
  30. package/dist/esm/types/api/createDiagramEditor.d.ts +4 -1
  31. package/dist/esm/types/api/types.d.ts +43 -1
  32. package/dist/esm/types/displaybox/demos/LinkColorPoolDemoTab.d.ts +3 -0
  33. package/dist/esm/types/displaybox/demos/OffsetAnchorAvoidanceDemoTab.d.ts +3 -0
  34. package/dist/esm/types/displaybox/demos/SimpleDemo.d.ts +4 -1
  35. package/dist/esm/types/displaybox/demos/ZoomToFitElementsDemoTab.d.ts +3 -0
  36. package/dist/esm/types/displaybox/demos/linkColorPoolDemo.d.ts +2 -0
  37. package/dist/esm/types/displaybox/demos/offsetAnchorAvoidanceDemo.d.ts +4 -0
  38. package/dist/esm/types/displaybox/demos/textDemo.d.ts +3 -0
  39. package/dist/esm/types/displaybox/demos/zoomToFitElementsDemo.d.ts +4 -0
  40. package/dist/esm/types/displaybox/types.d.ts +3 -1
  41. package/dist/esm/types/displaybox/useDemoEditor.d.ts +4 -2
  42. package/dist/esm/types/engine/AutoLayoutService.d.ts +59 -2
  43. package/dist/esm/types/engine/DiagramEngine.d.ts +20 -1
  44. package/dist/esm/types/engine/LinkRoutingService.d.ts +9 -0
  45. package/dist/esm/types/models/TextModel.d.ts +1 -0
  46. package/dist/esm/types/renderer/konva/KonvaInteraction.d.ts +6 -0
  47. package/dist/esm/types/strategies/ObstacleRouter.d.ts +2 -0
  48. package/dist/esm/types/strategies/RouterStrategy.d.ts +10 -0
  49. package/dist/examples.d.ts +56 -1
  50. package/dist/index.d.ts +60 -2
  51. package/docs/API_CONTRACT.md +73 -3
  52. package/docs/CAPABILITIES.md +8 -0
  53. package/docs/COMMANDS_EVENTS.md +8 -0
  54. package/docs/DOCUMENTATION_WORKFLOW.md +4 -1
  55. package/docs/INTEGRATION_PLAYBOOK.md +3 -0
  56. package/docs/STATE_INVARIANTS.md +4 -0
  57. package/package.json +1 -1
  58. package/src/displaybox/demos/AutoLayoutDemoTab.tsx +515 -381
  59. package/src/displaybox/demos/EngineEventsDemoTab.tsx +12 -11
  60. package/src/displaybox/demos/LinkColorPoolDemoTab.tsx +49 -0
  61. package/src/displaybox/demos/ObstacleRoutingDemoTab.tsx +52 -31
  62. package/src/displaybox/demos/OffsetAnchorAvoidanceDemoTab.tsx +30 -0
  63. package/src/displaybox/demos/SimpleDemo.tsx +18 -13
  64. package/src/displaybox/demos/TextLayoutDemoTab.tsx +18 -1
  65. package/src/displaybox/demos/ZoomToFitElementsDemoTab.tsx +29 -0
  66. package/src/displaybox/demos/autoLayoutDemo.ts +62 -26
  67. package/src/displaybox/demos/index.tsx +81 -57
  68. package/src/displaybox/demos/linkColorPoolDemo.ts +122 -0
  69. package/src/displaybox/demos/obstacleRoutingDemo.ts +77 -1
  70. package/src/displaybox/demos/offsetAnchorAvoidanceDemo.ts +211 -0
  71. package/src/displaybox/demos/routingDemo.ts +5 -5
  72. package/src/displaybox/demos/shared.ts +17 -12
  73. package/src/displaybox/demos/textDemo.ts +6 -2
  74. package/src/displaybox/demos/zoomToFitElementsDemo.ts +83 -0
  75. package/src/displaybox/types.ts +10 -8
package/dist/esm/index.js CHANGED
@@ -268,6 +268,7 @@ var TextModel = /** @class */ (function () {
268
268
  this.size = data.size ? __assign({}, data.size) : undefined;
269
269
  this.style = data.style;
270
270
  this.ownerId = (_a = data.ownerId) !== null && _a !== void 0 ? _a : null;
271
+ this.interaction = data.interaction ? __assign({}, data.interaction) : undefined;
271
272
  this.layout = data.layout ? __assign({}, data.layout) : undefined;
272
273
  this.displayContent = (_b = data.displayContent) !== null && _b !== void 0 ? _b : data.content;
273
274
  this.displayOffset = data.displayOffset ? __assign({}, data.displayOffset) : undefined;
@@ -304,6 +305,7 @@ var TextModel = /** @class */ (function () {
304
305
  size: this.size ? __assign({}, this.size) : undefined,
305
306
  style: this.style,
306
307
  ownerId: this.ownerId,
308
+ interaction: this.interaction ? __assign({}, this.interaction) : undefined,
307
309
  layout: this.layout ? __assign({}, this.layout) : undefined,
308
310
  displayContent: (_a = this.displayContent) !== null && _a !== void 0 ? _a : this.content,
309
311
  displayOffset: this.displayOffset ? __assign({}, this.displayOffset) : undefined,
@@ -318,7 +320,7 @@ var distance = function (a, b) {
318
320
  var dy = a.y - b.y;
319
321
  return Math.sqrt(dx * dx + dy * dy);
320
322
  };
321
- var clamp = function (value, min, max) {
323
+ var clamp$2 = function (value, min, max) {
322
324
  if (value < min)
323
325
  return min;
324
326
  if (value > max)
@@ -1165,6 +1167,7 @@ var pathLength = function (points) {
1165
1167
  }
1166
1168
  return total;
1167
1169
  };
1170
+ var clamp$1 = function (value, min, max) { return Math.max(min, Math.min(max, value)); };
1168
1171
  var ObstacleRouter = /** @class */ (function () {
1169
1172
  function ObstacleRouter(options) {
1170
1173
  var _a, _b, _c;
@@ -1180,7 +1183,7 @@ var ObstacleRouter = /** @class */ (function () {
1180
1183
  var targetStub = this.computeStubEndpoint(target, context === null || context === void 0 ? void 0 : context.targetEndpoint, bounds, obstacles);
1181
1184
  var innerSource = sourceStub !== null && sourceStub !== void 0 ? sourceStub : source;
1182
1185
  var innerTarget = targetStub !== null && targetStub !== void 0 ? targetStub : target;
1183
- var core = this.routeBetween(innerSource, innerTarget, obstacles, bounds);
1186
+ var core = this.routeBetween(innerSource, innerTarget, obstacles, bounds, context);
1184
1187
  var normalizedCore = this.ensureEndpoints(core, innerSource, innerTarget);
1185
1188
  var middle = normalizedCore.slice(1, -1).map(function (p) { return (__assign({}, p)); });
1186
1189
  var result = [__assign({}, source)];
@@ -1196,7 +1199,7 @@ var ObstacleRouter = /** @class */ (function () {
1196
1199
  result.push(__assign({}, target));
1197
1200
  return this.compactPreservingStubs(result, hasSourceStub, hasTargetStub);
1198
1201
  };
1199
- ObstacleRouter.prototype.buildCandidates = function (source, target, obstacles) {
1202
+ ObstacleRouter.prototype.buildCandidates = function (source, target, obstacles, context) {
1200
1203
  var _this = this;
1201
1204
  var midXValues = new Set();
1202
1205
  var midYValues = new Set();
@@ -1231,26 +1234,38 @@ var ObstacleRouter = /** @class */ (function () {
1231
1234
  ]);
1232
1235
  candidates.push(path);
1233
1236
  });
1237
+ var corridorCandidate = this.buildCommonAncestorCorridorCandidate(source, target, context === null || context === void 0 ? void 0 : context.commonAncestorCorridor);
1238
+ if (corridorCandidate) {
1239
+ candidates.push(corridorCandidate);
1240
+ }
1234
1241
  return candidates;
1235
1242
  };
1236
- ObstacleRouter.prototype.routeBetween = function (source, target, obstacles, bounds) {
1243
+ ObstacleRouter.prototype.routeBetween = function (source, target, obstacles, bounds, context) {
1237
1244
  var _this = this;
1238
1245
  var direct = compactPath([__assign({}, source), __assign({}, target)]);
1239
- if (obstacles.length === 0 && (!bounds || this.pointsWithinBounds(direct, bounds))) {
1246
+ var hasCommonAncestorCorridor = Boolean(context === null || context === void 0 ? void 0 : context.commonAncestorCorridor);
1247
+ if (!hasCommonAncestorCorridor && obstacles.length === 0 && (!bounds || this.pointsWithinBounds(direct, bounds))) {
1240
1248
  return direct;
1241
1249
  }
1242
- if (this.isPathClear(direct, obstacles, bounds)) {
1250
+ if (!hasCommonAncestorCorridor && this.isPathClear(direct, obstacles, bounds)) {
1243
1251
  return direct;
1244
1252
  }
1245
- var candidates = this.buildCandidates(source, target, obstacles);
1253
+ var candidates = this.buildCandidates(source, target, obstacles, context);
1246
1254
  var best = null;
1255
+ var bestPenalty = Number.POSITIVE_INFINITY;
1256
+ var bestCorridorSpan = Number.NEGATIVE_INFINITY;
1247
1257
  var bestLength = Number.POSITIVE_INFINITY;
1248
1258
  candidates.forEach(function (candidate) {
1249
1259
  if (!_this.isPathClear(candidate, obstacles, bounds))
1250
1260
  return;
1261
+ var scored = _this.scoreCommonAncestorCorridor(candidate, context === null || context === void 0 ? void 0 : context.commonAncestorCorridor, source, target);
1251
1262
  var length = pathLength(candidate);
1252
- if (length < bestLength) {
1263
+ if (scored.penalty < bestPenalty ||
1264
+ (scored.penalty === bestPenalty && scored.corridorSpan > bestCorridorSpan) ||
1265
+ (scored.penalty === bestPenalty && scored.corridorSpan === bestCorridorSpan && length < bestLength)) {
1253
1266
  best = candidate;
1267
+ bestPenalty = scored.penalty;
1268
+ bestCorridorSpan = scored.corridorSpan;
1254
1269
  bestLength = length;
1255
1270
  }
1256
1271
  });
@@ -1427,6 +1442,78 @@ var ObstacleRouter = /** @class */ (function () {
1427
1442
  result.push(deduped[deduped.length - 1]);
1428
1443
  return result.map(function (p) { return (__assign({}, p)); });
1429
1444
  };
1445
+ ObstacleRouter.prototype.buildCommonAncestorCorridorCandidate = function (source, target, corridor) {
1446
+ if (!corridor)
1447
+ return null;
1448
+ if (corridor.axis === 'horizontal') {
1449
+ var direction_1 = source.x <= target.x ? 1 : -1;
1450
+ var corridorY = clamp$1((source.y + target.y) / 2, corridor.bounds.y + this.padding, corridor.bounds.y + corridor.bounds.height - this.padding);
1451
+ var sourceExitX = direction_1 > 0
1452
+ ? corridor.sourceBranchRect.x + corridor.sourceBranchRect.width + this.padding
1453
+ : corridor.sourceBranchRect.x - this.padding;
1454
+ var targetEntryX = direction_1 > 0
1455
+ ? corridor.targetBranchRect.x - this.padding
1456
+ : corridor.targetBranchRect.x + corridor.targetBranchRect.width + this.padding;
1457
+ return compactPath([
1458
+ __assign({}, source),
1459
+ { x: sourceExitX, y: source.y },
1460
+ { x: sourceExitX, y: corridorY },
1461
+ { x: targetEntryX, y: corridorY },
1462
+ { x: targetEntryX, y: target.y },
1463
+ __assign({}, target),
1464
+ ]);
1465
+ }
1466
+ var direction = source.y <= target.y ? 1 : -1;
1467
+ var corridorX = clamp$1((source.x + target.x) / 2, corridor.bounds.x + this.padding, corridor.bounds.x + corridor.bounds.width - this.padding);
1468
+ var sourceExitY = direction > 0
1469
+ ? corridor.sourceBranchRect.y + corridor.sourceBranchRect.height + this.padding
1470
+ : corridor.sourceBranchRect.y - this.padding;
1471
+ var targetEntryY = direction > 0
1472
+ ? corridor.targetBranchRect.y - this.padding
1473
+ : corridor.targetBranchRect.y + corridor.targetBranchRect.height + this.padding;
1474
+ return compactPath([
1475
+ __assign({}, source),
1476
+ { x: source.x, y: sourceExitY },
1477
+ { x: corridorX, y: sourceExitY },
1478
+ { x: corridorX, y: targetEntryY },
1479
+ { x: target.x, y: targetEntryY },
1480
+ __assign({}, target),
1481
+ ]);
1482
+ };
1483
+ ObstacleRouter.prototype.scoreCommonAncestorCorridor = function (candidate, corridor, source, target) {
1484
+ if (!corridor || candidate.length < 3) {
1485
+ return { penalty: 0, corridorSpan: 0 };
1486
+ }
1487
+ var firstTurn = candidate[1];
1488
+ var lastTurn = candidate[candidate.length - 2];
1489
+ var penalty = 0;
1490
+ var corridorSpan = 0;
1491
+ if (corridor.axis === 'horizontal') {
1492
+ var direction = source.x <= target.x ? 1 : -1;
1493
+ var sourceBoundary = direction > 0 ? corridor.sourceBranchRect.x + corridor.sourceBranchRect.width : corridor.sourceBranchRect.x;
1494
+ var targetBoundary = direction > 0 ? corridor.targetBranchRect.x : corridor.targetBranchRect.x + corridor.targetBranchRect.width;
1495
+ var sourceExited = direction > 0 ? firstTurn.x > sourceBoundary + this.tolerance : firstTurn.x < sourceBoundary - this.tolerance;
1496
+ var targetDeferred = direction > 0 ? lastTurn.x < targetBoundary - this.tolerance : lastTurn.x > targetBoundary + this.tolerance;
1497
+ if (!sourceExited)
1498
+ penalty += 1000;
1499
+ if (!targetDeferred)
1500
+ penalty += 1000;
1501
+ corridorSpan = Math.abs(lastTurn.x - firstTurn.x);
1502
+ }
1503
+ else {
1504
+ var direction = source.y <= target.y ? 1 : -1;
1505
+ var sourceBoundary = direction > 0 ? corridor.sourceBranchRect.y + corridor.sourceBranchRect.height : corridor.sourceBranchRect.y;
1506
+ var targetBoundary = direction > 0 ? corridor.targetBranchRect.y : corridor.targetBranchRect.y + corridor.targetBranchRect.height;
1507
+ var sourceExited = direction > 0 ? firstTurn.y > sourceBoundary + this.tolerance : firstTurn.y < sourceBoundary - this.tolerance;
1508
+ var targetDeferred = direction > 0 ? lastTurn.y < targetBoundary - this.tolerance : lastTurn.y > targetBoundary + this.tolerance;
1509
+ if (!sourceExited)
1510
+ penalty += 1000;
1511
+ if (!targetDeferred)
1512
+ penalty += 1000;
1513
+ corridorSpan = Math.abs(lastTurn.y - firstTurn.y);
1514
+ }
1515
+ return { penalty: penalty, corridorSpan: corridorSpan };
1516
+ };
1430
1517
  return ObstacleRouter;
1431
1518
  }());
1432
1519
 
@@ -1929,34 +2016,211 @@ var TextLayoutService = /** @class */ (function () {
1929
2016
  return TextLayoutService;
1930
2017
  }());
1931
2018
 
2019
+ var GRID_ROW_UNITS = 12;
1932
2020
  var AutoLayoutService = /** @class */ (function () {
1933
2021
  function AutoLayoutService(config) {
1934
2022
  this.model = config.model;
1935
2023
  this.commandQueue = config.commandQueue;
1936
2024
  this.collectElementPortIds = config.collectElementPortIds;
1937
2025
  }
1938
- AutoLayoutService.prototype.applyLayoutForParent = function (parentId) {
1939
- var _a;
1940
- var _this = this;
1941
- var _b, _c, _d, _e;
2026
+ AutoLayoutService.prototype.applyLayoutForParent = function (parentId, options) {
1942
2027
  var parent = this.model.getElement(parentId);
1943
2028
  if (!parent)
1944
2029
  return { patches: [], movedPortIds: [] };
1945
2030
  var layout = parent.layout;
1946
2031
  if (!layout || layout.mode === 'manual')
1947
2032
  return { patches: [], movedPortIds: [] };
2033
+ var preserveParentSize = Boolean(options === null || options === void 0 ? void 0 : options.preserveParentSize);
2034
+ var preserveParentWidth = preserveParentSize || Boolean(options === null || options === void 0 ? void 0 : options.preserveParentWidth);
2035
+ var preserveParentHeight = preserveParentSize || Boolean(options === null || options === void 0 ? void 0 : options.preserveParentHeight);
2036
+ var padding = this.resolveLayoutPadding(layout);
2037
+ var labelReservedTopLane = this.resolveLabelReservedTopLane(parentId, layout);
2038
+ var autoResize = this.resolveAutoResizeMode(layout);
1948
2039
  var children = this.model.getChildren(parentId);
1949
- if (children.length === 0)
1950
- return { patches: [], movedPortIds: [] };
1951
- var axis = layout.mode;
2040
+ if (children.length === 0) {
2041
+ if (preserveParentWidth || preserveParentHeight) {
2042
+ var targetWidth_1 = preserveParentWidth ? parent.size.width : Math.max(0, Math.round(padding.x * 2));
2043
+ var targetHeight_1 = preserveParentHeight
2044
+ ? parent.size.height
2045
+ : Math.max(0, Math.round(padding.y * 2 + labelReservedTopLane));
2046
+ if (parent.size.width === targetWidth_1 && parent.size.height === targetHeight_1) {
2047
+ return { patches: [], movedPortIds: [] };
2048
+ }
2049
+ var resizePatches_1 = this.commandQueue.run(createResizeElementCommand(parentId, { width: targetWidth_1, height: targetHeight_1 }), this.model);
2050
+ return { patches: resizePatches_1, movedPortIds: __spreadArray([], parent.portIds, true) };
2051
+ }
2052
+ if (preserveParentSize) {
2053
+ return { patches: [], movedPortIds: [] };
2054
+ }
2055
+ if (autoResize !== 'grow-shrink')
2056
+ return { patches: [], movedPortIds: [] };
2057
+ var targetWidth = Math.max(0, Math.round(padding.x * 2));
2058
+ var targetHeight = Math.max(0, Math.round(padding.y * 2 + labelReservedTopLane));
2059
+ if (parent.size.width === targetWidth && parent.size.height === targetHeight) {
2060
+ return { patches: [], movedPortIds: [] };
2061
+ }
2062
+ var resizePatches = this.commandQueue.run(createResizeElementCommand(parentId, { width: targetWidth, height: targetHeight }), this.model);
2063
+ return { patches: resizePatches, movedPortIds: __spreadArray([], parent.portIds, true) };
2064
+ }
2065
+ if (layout.mode === 'grid') {
2066
+ return this.applyGridLayoutForParent(parentId, parent, children, {
2067
+ preserveParentSize: preserveParentSize,
2068
+ preserveParentWidth: preserveParentWidth,
2069
+ preserveParentHeight: preserveParentHeight,
2070
+ });
2071
+ }
2072
+ return this.applyAxisLayoutForParent(parentId, parent, children, layout.mode, {
2073
+ preserveParentSize: preserveParentSize,
2074
+ preserveParentWidth: preserveParentWidth,
2075
+ preserveParentHeight: preserveParentHeight,
2076
+ });
2077
+ };
2078
+ AutoLayoutService.prototype.applyLayoutCascade = function (startParentId) {
2079
+ var _a;
2080
+ var patches = [];
2081
+ var movedPortIds = [];
2082
+ var visited = new Set();
2083
+ var current = startParentId;
2084
+ while (current) {
2085
+ if (visited.has(current))
2086
+ break;
2087
+ visited.add(current);
2088
+ var result = this.applyLayoutForParent(current);
2089
+ patches.push.apply(patches, result.patches);
2090
+ movedPortIds.push.apply(movedPortIds, result.movedPortIds);
2091
+ var parent_1 = this.model.getElement(current);
2092
+ current = (_a = parent_1 === null || parent_1 === void 0 ? void 0 : parent_1.parentId) !== null && _a !== void 0 ? _a : null;
2093
+ }
2094
+ return { patches: patches, movedPortIds: Array.from(new Set(movedPortIds)) };
2095
+ };
2096
+ AutoLayoutService.prototype.applyAllLayouts = function () {
2097
+ var _this = this;
2098
+ var layoutParents = Array.from(this.model.elements.values()).filter(function (element) { return element.layout && element.layout.mode !== 'manual'; });
2099
+ var patches = [];
2100
+ var movedPortIds = [];
2101
+ var depth = function (elementId) {
2102
+ var level = 0;
2103
+ var current = _this.model.getElement(elementId);
2104
+ while (current === null || current === void 0 ? void 0 : current.parentId) {
2105
+ level += 1;
2106
+ current = _this.model.getElement(current.parentId);
2107
+ }
2108
+ return level;
2109
+ };
2110
+ layoutParents
2111
+ .sort(function (a, b) { return depth(b.id) - depth(a.id); })
2112
+ .forEach(function (element) {
2113
+ var result = _this.applyLayoutForParent(element.id);
2114
+ patches.push.apply(patches, result.patches);
2115
+ movedPortIds.push.apply(movedPortIds, result.movedPortIds);
2116
+ });
2117
+ return { patches: patches, movedPortIds: Array.from(new Set(movedPortIds)) };
2118
+ };
2119
+ AutoLayoutService.prototype.describeGridRows = function (parentId) {
2120
+ var _a;
2121
+ var parent = this.model.getElement(parentId);
2122
+ if (!parent || ((_a = parent.layout) === null || _a === void 0 ? void 0 : _a.mode) !== 'grid')
2123
+ return [];
2124
+ return this.resolveAssignedGridRows(parent).map(function (row) { return ({ childIds: __spreadArray([], row.childIds, true) }); });
2125
+ };
2126
+ AutoLayoutService.prototype.describeGridSlotState = function (parentId) {
2127
+ var _this = this;
2128
+ var _a;
2129
+ var parent = this.model.getElement(parentId);
2130
+ if (!parent || ((_a = parent.layout) === null || _a === void 0 ? void 0 : _a.mode) !== 'grid')
2131
+ return null;
2132
+ var assignedRows = this.resolveAssignedGridRows(parent);
2133
+ return {
2134
+ orderedChildIds: assignedRows.flatMap(function (row) { return row.childIds; }),
2135
+ slotWeights: assignedRows.flatMap(function (row) { return row.weights.slice(0, row.childIds.length).map(function (weight) { return _this.clampGridUnits(weight); }); }),
2136
+ };
2137
+ };
2138
+ AutoLayoutService.prototype.resolveGridReorderedLayout = function (parentId, previousState) {
2139
+ var _this = this;
2140
+ var _a;
2141
+ var parent = this.model.getElement(parentId);
2142
+ if (!parent || ((_a = parent.layout) === null || _a === void 0 ? void 0 : _a.mode) !== 'grid' || !parent.layout)
2143
+ return null;
2144
+ var sortedChildren = this.sortGridChildrenForLayout(this.model.getChildren(parentId));
2145
+ var orderedChildIds = sortedChildren.map(function (child) { return child.id; });
2146
+ if (orderedChildIds.length === previousState.orderedChildIds.length &&
2147
+ orderedChildIds.every(function (childId, index) { return childId === previousState.orderedChildIds[index]; })) {
2148
+ return null;
2149
+ }
2150
+ var weightByChildId = new Map();
2151
+ previousState.orderedChildIds.forEach(function (childId, index) {
2152
+ var _a;
2153
+ weightByChildId.set(childId, _this.clampGridUnits((_a = previousState.slotWeights[index]) !== null && _a !== void 0 ? _a : GRID_ROW_UNITS));
2154
+ });
2155
+ var reorderedTemplate = orderedChildIds.map(function (childId) { var _a; return (_a = weightByChildId.get(childId)) !== null && _a !== void 0 ? _a : GRID_ROW_UNITS; });
2156
+ return __assign(__assign({}, parent.layout), { gridTemplate: reorderedTemplate });
2157
+ };
2158
+ AutoLayoutService.prototype.resolveGridChildResizeTopologyChange = function (parentId, childId, requestedWidth) {
2159
+ var _a;
2160
+ var parent = this.model.getElement(parentId);
2161
+ if (!parent || ((_a = parent.layout) === null || _a === void 0 ? void 0 : _a.mode) !== 'grid' || !parent.layout)
2162
+ return null;
2163
+ var slotState = this.resolveGridChildSlotState(parentId, childId);
2164
+ if (!slotState)
2165
+ return null;
2166
+ var assignedRows = slotState.assignedRows, orderedChildIds = slotState.orderedChildIds, slotWeights = slotState.slotWeights, childFlatIndex = slotState.childFlatIndex, rowIndex = slotState.rowIndex;
2167
+ var currentUnits = slotWeights[childFlatIndex];
2168
+ var requestedUnits = this.resolveRequestedGridUnits(parent, assignedRows[rowIndex], requestedWidth);
2169
+ if (requestedUnits === currentUnits)
2170
+ return null;
2171
+ var nextSlotWeights = __spreadArray([], slotWeights, true);
2172
+ nextSlotWeights[childFlatIndex] = requestedUnits;
2173
+ var nextRows = this.packGridRowsFromSlots(orderedChildIds, nextSlotWeights);
2174
+ var beforeRows = assignedRows.map(function (row) { return ({ childIds: __spreadArray([], row.childIds, true) }); });
2175
+ var afterRows = nextRows.map(function (row) { return ({ childIds: __spreadArray([], row.childIds, true) }); });
2176
+ var rowsChanged = !this.gridRowSnapshotsEqual(beforeRows, afterRows);
2177
+ var reason = requestedUnits < currentUnits && rowsChanged ? 'child-resize-split' : 'child-resize-redistribute';
2178
+ return {
2179
+ parentId: parentId,
2180
+ triggerChildId: childId,
2181
+ reason: reason,
2182
+ beforeRows: beforeRows,
2183
+ afterRows: afterRows,
2184
+ nextLayout: __assign(__assign({}, parent.layout), { gridTemplate: nextSlotWeights }),
2185
+ };
2186
+ };
2187
+ AutoLayoutService.prototype.snapGridChildRequestedWidth = function (parentId, childId, requestedWidth) {
2188
+ var _a, _b;
2189
+ var parent = this.model.getElement(parentId);
2190
+ if (!parent || ((_a = parent.layout) === null || _a === void 0 ? void 0 : _a.mode) !== 'grid' || !parent.layout)
2191
+ return requestedWidth;
2192
+ var slotState = this.resolveGridChildSlotState(parentId, childId);
2193
+ if (!slotState)
2194
+ return requestedWidth;
2195
+ var requestedUnits = this.resolveRequestedGridUnits(parent, slotState.assignedRows[slotState.rowIndex], requestedWidth);
2196
+ var rowUnitWidth = this.resolveGridRowUnitWidth(Math.max(0, parent.size.width - this.resolveLayoutPadding(parent.layout).x * 2), slotState.assignedRows[slotState.rowIndex].childIds.length, (_b = parent.layout.gap) !== null && _b !== void 0 ? _b : 12);
2197
+ return Math.max(1, Math.round(requestedUnits * rowUnitWidth));
2198
+ };
2199
+ AutoLayoutService.prototype.canGridChildGrowRightward = function (parentId, childId) {
2200
+ var _a;
2201
+ var parent = this.model.getElement(parentId);
2202
+ if (!parent || ((_a = parent.layout) === null || _a === void 0 ? void 0 : _a.mode) !== 'grid' || !parent.layout)
2203
+ return false;
2204
+ var orderedIds = this.resolveAssignedGridRows(parent).flatMap(function (row) { return row.childIds; });
2205
+ var childIndex = orderedIds.indexOf(childId);
2206
+ return childIndex >= 0 && childIndex < orderedIds.length - 1;
2207
+ };
2208
+ AutoLayoutService.prototype.applyAxisLayoutForParent = function (parentId, parent, children, axis, options) {
2209
+ var _a, _b;
2210
+ var _this = this;
2211
+ var _c, _d, _e, _f;
2212
+ var preserveParentSize = Boolean(options === null || options === void 0 ? void 0 : options.preserveParentSize);
2213
+ var preserveParentWidth = preserveParentSize || Boolean(options === null || options === void 0 ? void 0 : options.preserveParentWidth);
2214
+ var preserveParentHeight = preserveParentSize || Boolean(options === null || options === void 0 ? void 0 : options.preserveParentHeight);
2215
+ var layout = parent.layout;
1952
2216
  var padding = this.resolveLayoutPadding(layout);
1953
- var gap = (_b = layout.gap) !== null && _b !== void 0 ? _b : 12;
1954
- var align = (_c = layout.align) !== null && _c !== void 0 ? _c : 'center';
1955
- var childFitMainAxis = (_d = layout.childFitMainAxis) !== null && _d !== void 0 ? _d : 'none';
1956
- var childFitCrossAxis = (_e = layout.childFitCrossAxis) !== null && _e !== void 0 ? _e : 'none';
1957
- var childFitMinSize = layout.childFitMinSize;
1958
- var childFitMaxSize = layout.childFitMaxSize;
2217
+ var gap = (_c = layout === null || layout === void 0 ? void 0 : layout.gap) !== null && _c !== void 0 ? _c : 12;
2218
+ var align = (_d = layout === null || layout === void 0 ? void 0 : layout.align) !== null && _d !== void 0 ? _d : 'center';
2219
+ var childFitMainAxis = (_e = layout === null || layout === void 0 ? void 0 : layout.childFitMainAxis) !== null && _e !== void 0 ? _e : 'none';
2220
+ var childFitCrossAxis = (_f = layout === null || layout === void 0 ? void 0 : layout.childFitCrossAxis) !== null && _f !== void 0 ? _f : 'none';
1959
2221
  var labelReservedTopLane = this.resolveLabelReservedTopLane(parentId, layout);
2222
+ var constraints = this.resolveChildSizeConstraints(layout);
2223
+ var autoResize = this.resolveAutoResizeMode(layout);
1960
2224
  var sorted = __spreadArray([], children, true).sort(function (a, b) {
1961
2225
  var aPos = axis === 'horizontal' ? a.position.x : a.position.y;
1962
2226
  var bPos = axis === 'horizontal' ? b.position.x : b.position.y;
@@ -1972,16 +2236,11 @@ var AutoLayoutService = /** @class */ (function () {
1972
2236
  ? Math.max(0, availableWidth - gap * gapCount)
1973
2237
  : Math.max(0, availableHeight - gap * gapCount);
1974
2238
  var distributedMainSizes = childFitMainAxis === 'distribute'
1975
- ? _this.distributeLayoutSizes(availableMain, sorted.length, sorted.map(function () { var _a, _b; return axis === 'horizontal' ? (_a = childFitMinSize === null || childFitMinSize === void 0 ? void 0 : childFitMinSize.width) !== null && _a !== void 0 ? _a : 0 : (_b = childFitMinSize === null || childFitMinSize === void 0 ? void 0 : childFitMinSize.height) !== null && _b !== void 0 ? _b : 0; }), sorted.map(function () {
1976
- var _a, _b;
1977
- return axis === 'horizontal'
1978
- ? (_a = childFitMaxSize === null || childFitMaxSize === void 0 ? void 0 : childFitMaxSize.width) !== null && _a !== void 0 ? _a : Number.POSITIVE_INFINITY
1979
- : (_b = childFitMaxSize === null || childFitMaxSize === void 0 ? void 0 : childFitMaxSize.height) !== null && _b !== void 0 ? _b : Number.POSITIVE_INFINITY;
1980
- }))
2239
+ ? _this.distributeLayoutSizes(availableMain, sorted.length, sorted.map(function () { return (axis === 'horizontal' ? constraints.minWidth : constraints.minHeight); }), sorted.map(function () { return (axis === 'horizontal' ? constraints.maxWidth : constraints.maxHeight); }))
1981
2240
  : null;
1982
2241
  return sorted.map(function (child, index) {
1983
- var width = child.size.width;
1984
- var height = child.size.height;
2242
+ var width = _this.clampLayoutSize(child.size.width, constraints.minWidth, constraints.maxWidth);
2243
+ var height = _this.clampLayoutSize(child.size.height, constraints.minHeight, constraints.maxHeight);
1985
2244
  if (distributedMainSizes) {
1986
2245
  if (axis === 'horizontal') {
1987
2246
  width = distributedMainSizes[index];
@@ -1999,8 +2258,8 @@ var AutoLayoutService = /** @class */ (function () {
1999
2258
  }
2000
2259
  }
2001
2260
  return {
2002
- width: _this.clampLayoutSize(width, childFitMinSize === null || childFitMinSize === void 0 ? void 0 : childFitMinSize.width, childFitMaxSize === null || childFitMaxSize === void 0 ? void 0 : childFitMaxSize.width),
2003
- height: _this.clampLayoutSize(height, childFitMinSize === null || childFitMinSize === void 0 ? void 0 : childFitMinSize.height, childFitMaxSize === null || childFitMaxSize === void 0 ? void 0 : childFitMaxSize.height),
2261
+ width: _this.clampLayoutSize(width, constraints.minWidth, constraints.maxWidth),
2262
+ height: _this.clampLayoutSize(height, constraints.minHeight, constraints.maxHeight),
2004
2263
  };
2005
2264
  });
2006
2265
  };
@@ -2010,20 +2269,42 @@ var AutoLayoutService = /** @class */ (function () {
2010
2269
  var totalWidth = fittedSizes.reduce(function (sum, size) { return sum + size.width; }, 0);
2011
2270
  var totalHeight = fittedSizes.reduce(function (sum, size) { return sum + size.height; }, 0);
2012
2271
  if (axis === 'horizontal') {
2272
+ var requiredWidth_1 = padding.x * 2 + totalWidth + gap * gapCount;
2273
+ var requiredHeight_1 = padding.y * 2 + labelReservedTopLane + maxHeight;
2013
2274
  return {
2014
- width: Math.max(parent.size.width, padding.x * 2 + totalWidth + gap * gapCount),
2015
- height: Math.max(parent.size.height, padding.y * 2 + labelReservedTopLane + maxHeight),
2275
+ width: _this.resolveAutoResizedDimension(parent.size.width, requiredWidth_1, autoResize),
2276
+ height: _this.resolveAutoResizedDimension(parent.size.height, requiredHeight_1, autoResize),
2016
2277
  };
2017
2278
  }
2279
+ var requiredWidth = padding.x * 2 + maxWidth;
2280
+ var requiredHeight = padding.y * 2 + labelReservedTopLane + totalHeight + gap * gapCount;
2018
2281
  return {
2019
- width: Math.max(parent.size.width, padding.x * 2 + maxWidth),
2020
- height: Math.max(parent.size.height, padding.y * 2 + labelReservedTopLane + totalHeight + gap * gapCount),
2282
+ width: _this.resolveAutoResizedDimension(parent.size.width, requiredWidth, autoResize),
2283
+ height: _this.resolveAutoResizedDimension(parent.size.height, requiredHeight, autoResize),
2021
2284
  };
2022
2285
  };
2023
- var fittedSizes = calculateFittedSizes(parent.size.width, parent.size.height);
2024
- var _f = resolveParentSize(fittedSizes), newParentWidth = _f.width, newParentHeight = _f.height;
2025
- fittedSizes = calculateFittedSizes(newParentWidth, newParentHeight);
2026
- (_a = resolveParentSize(fittedSizes), newParentWidth = _a.width, newParentHeight = _a.height);
2286
+ var preservedParentWidth = Math.max(0, Math.round(parent.size.width));
2287
+ var preservedParentHeight = Math.max(0, Math.round(parent.size.height));
2288
+ var fittedSizes = calculateFittedSizes(preservedParentWidth, preservedParentHeight);
2289
+ var newParentWidth;
2290
+ var newParentHeight;
2291
+ if (preserveParentSize) {
2292
+ newParentWidth = preservedParentWidth;
2293
+ newParentHeight = preservedParentHeight;
2294
+ }
2295
+ else {
2296
+ (_a = resolveParentSize(fittedSizes), newParentWidth = _a.width, newParentHeight = _a.height);
2297
+ if (preserveParentWidth)
2298
+ newParentWidth = preservedParentWidth;
2299
+ if (preserveParentHeight)
2300
+ newParentHeight = preservedParentHeight;
2301
+ fittedSizes = calculateFittedSizes(newParentWidth, newParentHeight);
2302
+ (_b = resolveParentSize(fittedSizes), newParentWidth = _b.width, newParentHeight = _b.height);
2303
+ if (preserveParentWidth)
2304
+ newParentWidth = preservedParentWidth;
2305
+ if (preserveParentHeight)
2306
+ newParentHeight = preservedParentHeight;
2307
+ }
2027
2308
  var availableWidth = Math.max(0, newParentWidth - padding.x * 2);
2028
2309
  var availableHeight = Math.max(0, newParentHeight - padding.y * 2 - labelReservedTopLane);
2029
2310
  var cursorX = padding.x;
@@ -2052,6 +2333,122 @@ var AutoLayoutService = /** @class */ (function () {
2052
2333
  cursorY += fittedSize.height + (index < sorted.length - 1 ? gap : 0);
2053
2334
  }
2054
2335
  });
2336
+ return this.applyResolvedLayout(parentId, parent, desiredPositions, desiredSizes, {
2337
+ width: newParentWidth,
2338
+ height: newParentHeight,
2339
+ });
2340
+ };
2341
+ AutoLayoutService.prototype.applyGridLayoutForParent = function (parentId, parent, children, options) {
2342
+ var _this = this;
2343
+ var _a, _b;
2344
+ var preserveParentSize = Boolean(options === null || options === void 0 ? void 0 : options.preserveParentSize);
2345
+ var preserveParentWidth = preserveParentSize || Boolean(options === null || options === void 0 ? void 0 : options.preserveParentWidth);
2346
+ var preserveParentHeight = preserveParentSize || Boolean(options === null || options === void 0 ? void 0 : options.preserveParentHeight);
2347
+ var layout = parent.layout;
2348
+ var padding = this.resolveLayoutPadding(layout);
2349
+ var gap = (_a = layout === null || layout === void 0 ? void 0 : layout.gap) !== null && _a !== void 0 ? _a : 12;
2350
+ var align = (_b = layout === null || layout === void 0 ? void 0 : layout.align) !== null && _b !== void 0 ? _b : 'center';
2351
+ var labelReservedTopLane = this.resolveLabelReservedTopLane(parentId, layout);
2352
+ var constraints = this.resolveChildSizeConstraints(layout);
2353
+ var autoResize = this.resolveAutoResizeMode(layout);
2354
+ var sorted = this.sortGridChildrenForLayout(children);
2355
+ var templateRows = this.normalizeGridTemplate(layout === null || layout === void 0 ? void 0 : layout.gridTemplate);
2356
+ var assignedRows = this.assignChildrenToGridRows(sorted.map(function (child) { return child.id; }), templateRows);
2357
+ var rowMetrics = assignedRows.map(function (row) {
2358
+ var effectiveWeights = row.weights.slice(0, row.childIds.length);
2359
+ var clampedSizes = row.childIds.map(function (childId) {
2360
+ var child = _this.model.getElement(childId);
2361
+ var width = child ? child.size.width : 0;
2362
+ var height = child ? child.size.height : 0;
2363
+ return {
2364
+ width: _this.clampLayoutSize(width, constraints.minWidth, constraints.maxWidth),
2365
+ height: _this.clampLayoutSize(height, constraints.minHeight, constraints.maxHeight),
2366
+ };
2367
+ });
2368
+ var rowHeight = clampedSizes.reduce(function (max, size) { return Math.max(max, size.height); }, 0);
2369
+ var totalGap = Math.max(0, clampedSizes.length - 1) * gap;
2370
+ var usedUnits = effectiveWeights.reduce(function (sum, weight) { return sum + _this.clampGridUnits(weight); }, 0);
2371
+ var requiredUnitWidth = effectiveWeights.reduce(function (max, weight, index) {
2372
+ var _a, _b;
2373
+ var slotUnits = Math.max(1, weight !== null && weight !== void 0 ? weight : 1);
2374
+ var width = (_b = (_a = clampedSizes[index]) === null || _a === void 0 ? void 0 : _a.width) !== null && _b !== void 0 ? _b : 0;
2375
+ return Math.max(max, width / slotUnits);
2376
+ }, 0);
2377
+ var rowWidth = usedUnits >= GRID_ROW_UNITS
2378
+ ? autoResize === 'grow-shrink'
2379
+ ? Math.round(requiredUnitWidth * GRID_ROW_UNITS) + totalGap
2380
+ : clampedSizes.reduce(function (sum, size) { return sum + size.width; }, 0) + totalGap
2381
+ : Math.round(requiredUnitWidth * Math.max(1, usedUnits)) + totalGap;
2382
+ return {
2383
+ row: row,
2384
+ rowHeight: rowHeight,
2385
+ rowWidth: rowWidth,
2386
+ usedUnits: usedUnits,
2387
+ effectiveWeights: effectiveWeights,
2388
+ };
2389
+ });
2390
+ var requiredInnerWidth = rowMetrics.reduce(function (max, metric) { return Math.max(max, metric.rowWidth); }, 0);
2391
+ var requiredInnerHeight = rowMetrics.reduce(function (sum, metric) { return sum + metric.rowHeight; }, 0) + Math.max(0, rowMetrics.length - 1) * gap;
2392
+ var newParentWidth = preserveParentWidth
2393
+ ? Math.max(0, Math.round(parent.size.width))
2394
+ : this.resolveAutoResizedDimension(parent.size.width, padding.x * 2 + requiredInnerWidth, autoResize);
2395
+ var newParentHeight = preserveParentHeight
2396
+ ? Math.max(0, Math.round(parent.size.height))
2397
+ : this.resolveAutoResizedDimension(parent.size.height, padding.y * 2 + labelReservedTopLane + requiredInnerHeight, autoResize);
2398
+ var availableWidth = Math.max(0, newParentWidth - padding.x * 2);
2399
+ var availableHeight = Math.max(0, newParentHeight - padding.y * 2 - labelReservedTopLane);
2400
+ var contentHeight = requiredInnerHeight;
2401
+ var blockOffsetY = align === 'start'
2402
+ ? 0
2403
+ : align === 'end'
2404
+ ? Math.max(0, availableHeight - contentHeight)
2405
+ : Math.max(0, (availableHeight - contentHeight) / 2);
2406
+ var cursorY = padding.y + labelReservedTopLane + blockOffsetY;
2407
+ var desiredPositions = new Map();
2408
+ var desiredSizes = new Map();
2409
+ rowMetrics.forEach(function (metric) {
2410
+ var childCount = metric.row.childIds.length;
2411
+ if (childCount <= 0)
2412
+ return;
2413
+ var totalGap = Math.max(0, childCount - 1) * gap;
2414
+ var rowOuterWidth = metric.usedUnits >= GRID_ROW_UNITS
2415
+ ? availableWidth
2416
+ : Math.min(availableWidth, metric.rowWidth);
2417
+ var rowInnerWidth = Math.max(0, rowOuterWidth - totalGap);
2418
+ var cellWidths = _this.resolveGridCellWidths(rowInnerWidth, metric.effectiveWeights);
2419
+ var rowHeight = metric.rowHeight;
2420
+ var cursorX = padding.x;
2421
+ metric.row.childIds.forEach(function (childId, index) {
2422
+ var _a;
2423
+ var cellWidth = (_a = cellWidths[index]) !== null && _a !== void 0 ? _a : 0;
2424
+ var targetWidth = _this.clampLayoutSize(cellWidth, constraints.minWidth, constraints.maxWidth);
2425
+ var targetHeight = _this.clampLayoutSize(rowHeight, constraints.minHeight, constraints.maxHeight);
2426
+ var offsetX = _this.resolveAlignmentOffset(align, cellWidth, targetWidth);
2427
+ var offsetY = _this.resolveAlignmentOffset(align, rowHeight, targetHeight);
2428
+ desiredSizes.set(childId, { width: targetWidth, height: targetHeight });
2429
+ desiredPositions.set(childId, {
2430
+ x: cursorX + offsetX,
2431
+ y: cursorY + offsetY,
2432
+ });
2433
+ cursorX += cellWidth + gap;
2434
+ });
2435
+ cursorY += rowHeight + gap;
2436
+ });
2437
+ return this.applyResolvedLayout(parentId, parent, desiredPositions, desiredSizes, {
2438
+ width: newParentWidth,
2439
+ height: newParentHeight,
2440
+ });
2441
+ };
2442
+ AutoLayoutService.prototype.resolveGridCellWidths = function (rowInnerWidth, weights) {
2443
+ var _this = this;
2444
+ if (weights.length === 0)
2445
+ return [];
2446
+ var safeWeights = weights.map(function (weight) { return _this.clampGridUnits(weight); });
2447
+ return this.distributeWeightedSizes(Math.max(0, rowInnerWidth), safeWeights);
2448
+ };
2449
+ AutoLayoutService.prototype.applyResolvedLayout = function (parentId, parent, desiredPositions, desiredSizes, parentSize) {
2450
+ var _this = this;
2451
+ var _a;
2055
2452
  var patches = [];
2056
2453
  var movedPortIds = [];
2057
2454
  desiredPositions.forEach(function (position, childId) {
@@ -2073,54 +2470,13 @@ var AutoLayoutService = /** @class */ (function () {
2073
2470
  movedPortIds.push.apply(movedPortIds, nested.movedPortIds);
2074
2471
  }
2075
2472
  });
2076
- if (newParentWidth !== parent.size.width || newParentHeight !== parent.size.height) {
2077
- var resizePatches = this.commandQueue.run(createResizeElementCommand(parentId, { width: newParentWidth, height: newParentHeight }), this.model);
2473
+ if (parentSize.width !== parent.size.width || parentSize.height !== parent.size.height) {
2474
+ var resizePatches = this.commandQueue.run(createResizeElementCommand(parentId, parentSize), this.model);
2078
2475
  patches.push.apply(patches, resizePatches);
2079
- movedPortIds.push.apply(movedPortIds, parent.portIds);
2080
- }
2081
- return { patches: patches, movedPortIds: Array.from(new Set(movedPortIds)) };
2082
- };
2083
- AutoLayoutService.prototype.applyLayoutCascade = function (startParentId) {
2084
- var _a;
2085
- var patches = [];
2086
- var movedPortIds = [];
2087
- var visited = new Set();
2088
- var current = startParentId;
2089
- while (current) {
2090
- if (visited.has(current))
2091
- break;
2092
- visited.add(current);
2093
- var result = this.applyLayoutForParent(current);
2094
- patches.push.apply(patches, result.patches);
2095
- movedPortIds.push.apply(movedPortIds, result.movedPortIds);
2096
- var parent_1 = this.model.getElement(current);
2097
- current = (_a = parent_1 === null || parent_1 === void 0 ? void 0 : parent_1.parentId) !== null && _a !== void 0 ? _a : null;
2476
+ movedPortIds.push.apply(movedPortIds, ((_a = parent.portIds) !== null && _a !== void 0 ? _a : []));
2098
2477
  }
2099
2478
  return { patches: patches, movedPortIds: Array.from(new Set(movedPortIds)) };
2100
2479
  };
2101
- AutoLayoutService.prototype.applyAllLayouts = function () {
2102
- var _this = this;
2103
- var layoutParents = Array.from(this.model.elements.values()).filter(function (element) { return element.layout && element.layout.mode !== 'manual'; });
2104
- var patches = [];
2105
- var movedPortIds = [];
2106
- var depth = function (elementId) {
2107
- var level = 0;
2108
- var current = _this.model.getElement(elementId);
2109
- while (current === null || current === void 0 ? void 0 : current.parentId) {
2110
- level += 1;
2111
- current = _this.model.getElement(current.parentId);
2112
- }
2113
- return level;
2114
- };
2115
- layoutParents
2116
- .sort(function (a, b) { return depth(b.id) - depth(a.id); })
2117
- .forEach(function (element) {
2118
- var result = _this.applyLayoutForParent(element.id);
2119
- patches.push.apply(patches, result.patches);
2120
- movedPortIds.push.apply(movedPortIds, result.movedPortIds);
2121
- });
2122
- return { patches: patches, movedPortIds: Array.from(new Set(movedPortIds)) };
2123
- };
2124
2480
  AutoLayoutService.prototype.resolveLayoutPadding = function (layout) {
2125
2481
  var _a, _b, _c;
2126
2482
  var padding = (_a = layout === null || layout === void 0 ? void 0 : layout.padding) !== null && _a !== void 0 ? _a : 12;
@@ -2131,6 +2487,474 @@ var AutoLayoutService = /** @class */ (function () {
2131
2487
  y: (_c = padding.y) !== null && _c !== void 0 ? _c : 12,
2132
2488
  };
2133
2489
  };
2490
+ AutoLayoutService.prototype.resolveAutoResizeMode = function (layout) {
2491
+ return (layout === null || layout === void 0 ? void 0 : layout.autoResize) === 'grow-shrink' ? 'grow-shrink' : 'grow';
2492
+ };
2493
+ AutoLayoutService.prototype.resolveAutoResizedDimension = function (current, required, mode) {
2494
+ var safeRequired = Math.max(0, Math.round(required));
2495
+ return mode === 'grow-shrink' ? safeRequired : Math.max(Math.max(0, current), safeRequired);
2496
+ };
2497
+ AutoLayoutService.prototype.resolveChildSizeConstraints = function (layout) {
2498
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
2499
+ var minWidth = Math.max(0, (_c = (_a = layout === null || layout === void 0 ? void 0 : layout.childMinWidth) !== null && _a !== void 0 ? _a : (_b = layout === null || layout === void 0 ? void 0 : layout.childFitMinSize) === null || _b === void 0 ? void 0 : _b.width) !== null && _c !== void 0 ? _c : 0);
2500
+ var minHeight = Math.max(0, (_f = (_d = layout === null || layout === void 0 ? void 0 : layout.childMinHeight) !== null && _d !== void 0 ? _d : (_e = layout === null || layout === void 0 ? void 0 : layout.childFitMinSize) === null || _e === void 0 ? void 0 : _e.height) !== null && _f !== void 0 ? _f : 0);
2501
+ var resolvedMaxWidth = (_g = layout === null || layout === void 0 ? void 0 : layout.childMaxWidth) !== null && _g !== void 0 ? _g : (_h = layout === null || layout === void 0 ? void 0 : layout.childFitMaxSize) === null || _h === void 0 ? void 0 : _h.width;
2502
+ var resolvedMaxHeight = (_j = layout === null || layout === void 0 ? void 0 : layout.childMaxHeight) !== null && _j !== void 0 ? _j : (_k = layout === null || layout === void 0 ? void 0 : layout.childFitMaxSize) === null || _k === void 0 ? void 0 : _k.height;
2503
+ var maxWidth = Number.isFinite(resolvedMaxWidth !== null && resolvedMaxWidth !== void 0 ? resolvedMaxWidth : Number.NaN)
2504
+ ? Math.max(minWidth, resolvedMaxWidth)
2505
+ : Number.POSITIVE_INFINITY;
2506
+ var maxHeight = Number.isFinite(resolvedMaxHeight !== null && resolvedMaxHeight !== void 0 ? resolvedMaxHeight : Number.NaN)
2507
+ ? Math.max(minHeight, resolvedMaxHeight)
2508
+ : Number.POSITIVE_INFINITY;
2509
+ return { minWidth: minWidth, maxWidth: maxWidth, minHeight: minHeight, maxHeight: maxHeight };
2510
+ };
2511
+ AutoLayoutService.prototype.resolveAssignedGridRows = function (parent) {
2512
+ var _a;
2513
+ var children = this.model.getChildren(parent.id);
2514
+ var sorted = this.sortGridChildrenForLayout(children);
2515
+ var templateRows = this.normalizeGridTemplate((_a = parent.layout) === null || _a === void 0 ? void 0 : _a.gridTemplate);
2516
+ return this.assignChildrenToGridRows(sorted.map(function (child) { return child.id; }), templateRows);
2517
+ };
2518
+ AutoLayoutService.prototype.repartitionAssignedGridRows = function (assignedRows, rowIndex, nextCurrentRowCount) {
2519
+ var _a, _b;
2520
+ var allChildIds = assignedRows.flatMap(function (row) { return row.childIds; });
2521
+ var prefixRows = assignedRows.slice(0, rowIndex).map(function (row) { return ({
2522
+ weights: __spreadArray([], row.weights.slice(0, row.childIds.length), true),
2523
+ childIds: __spreadArray([], row.childIds, true),
2524
+ }); });
2525
+ var prefixCount = prefixRows.reduce(function (sum, row) { return sum + row.childIds.length; }, 0);
2526
+ var nextRows = __spreadArray([], prefixRows, true);
2527
+ var currentChildIds = allChildIds.slice(prefixCount, prefixCount + nextCurrentRowCount);
2528
+ if (currentChildIds.length > 0) {
2529
+ nextRows.push({
2530
+ weights: this.fitGridRowWeights((_a = assignedRows[rowIndex]) === null || _a === void 0 ? void 0 : _a.weights, currentChildIds.length),
2531
+ childIds: currentChildIds,
2532
+ });
2533
+ }
2534
+ var cursor = prefixCount + currentChildIds.length;
2535
+ var trailingRowIndex = rowIndex + 1;
2536
+ while (cursor < allChildIds.length) {
2537
+ var sourceRow = assignedRows[Math.min(trailingRowIndex, assignedRows.length - 1)];
2538
+ var sourceCapacity = Math.max(1, (_b = sourceRow === null || sourceRow === void 0 ? void 0 : sourceRow.childIds.length) !== null && _b !== void 0 ? _b : 1);
2539
+ var rowChildIds = allChildIds.slice(cursor, cursor + sourceCapacity);
2540
+ nextRows.push({
2541
+ weights: this.fitGridRowWeights(sourceRow === null || sourceRow === void 0 ? void 0 : sourceRow.weights, rowChildIds.length),
2542
+ childIds: rowChildIds,
2543
+ });
2544
+ cursor += rowChildIds.length;
2545
+ trailingRowIndex += 1;
2546
+ }
2547
+ return nextRows;
2548
+ };
2549
+ AutoLayoutService.prototype.fitGridRowWeights = function (sourceWeights, childCount) {
2550
+ if (childCount <= 0)
2551
+ return [];
2552
+ var base = Array.isArray(sourceWeights) && sourceWeights.length > 0 ? sourceWeights : [1];
2553
+ var normalizedBase = this.normalizeRowWeightsToTwelveUnits(base);
2554
+ if (normalizedBase.length === childCount) {
2555
+ return normalizedBase;
2556
+ }
2557
+ if (normalizedBase.length > childCount) {
2558
+ return this.normalizeRowWeightsToTwelveUnits(normalizedBase.slice(0, childCount));
2559
+ }
2560
+ return this.buildEqualGridUnits(childCount);
2561
+ };
2562
+ AutoLayoutService.prototype.gridRowSnapshotsEqual = function (a, b) {
2563
+ var _a, _b, _c, _d;
2564
+ if (a.length !== b.length)
2565
+ return false;
2566
+ for (var index = 0; index < a.length; index += 1) {
2567
+ var left = (_b = (_a = a[index]) === null || _a === void 0 ? void 0 : _a.childIds) !== null && _b !== void 0 ? _b : [];
2568
+ var right = (_d = (_c = b[index]) === null || _c === void 0 ? void 0 : _c.childIds) !== null && _d !== void 0 ? _d : [];
2569
+ if (left.length !== right.length)
2570
+ return false;
2571
+ for (var childIndex = 0; childIndex < left.length; childIndex += 1) {
2572
+ if (left[childIndex] !== right[childIndex])
2573
+ return false;
2574
+ }
2575
+ }
2576
+ return true;
2577
+ };
2578
+ AutoLayoutService.prototype.normalizeGridTemplate = function (template) {
2579
+ var slots = this.normalizeGridSlotUnits(template);
2580
+ var rows = [];
2581
+ var currentRow = [];
2582
+ var currentUnits = 0;
2583
+ slots.forEach(function (slotUnits) {
2584
+ if (currentRow.length > 0 && currentUnits + slotUnits > GRID_ROW_UNITS) {
2585
+ rows.push({ weights: __spreadArray([], currentRow, true) });
2586
+ currentRow = [];
2587
+ currentUnits = 0;
2588
+ }
2589
+ currentRow.push(slotUnits);
2590
+ currentUnits += slotUnits;
2591
+ });
2592
+ if (currentRow.length > 0) {
2593
+ rows.push({ weights: __spreadArray([], currentRow, true) });
2594
+ }
2595
+ if (rows.length === 0) {
2596
+ rows.push({ weights: [GRID_ROW_UNITS] });
2597
+ }
2598
+ return rows;
2599
+ };
2600
+ AutoLayoutService.prototype.assignChildrenToGridRows = function (childIds, templateRows) {
2601
+ var assigned = [];
2602
+ var cursor = 0;
2603
+ templateRows.forEach(function (rowTemplate) {
2604
+ if (cursor >= childIds.length)
2605
+ return;
2606
+ var rowChildren = childIds.slice(cursor, cursor + rowTemplate.weights.length);
2607
+ if (rowChildren.length === 0)
2608
+ return;
2609
+ assigned.push({
2610
+ weights: rowTemplate.weights,
2611
+ childIds: rowChildren,
2612
+ });
2613
+ cursor += rowChildren.length;
2614
+ });
2615
+ while (cursor < childIds.length) {
2616
+ var rowChildren = childIds.slice(cursor, cursor + 1);
2617
+ assigned.push({
2618
+ weights: [GRID_ROW_UNITS],
2619
+ childIds: rowChildren,
2620
+ });
2621
+ cursor += rowChildren.length;
2622
+ }
2623
+ return assigned;
2624
+ };
2625
+ AutoLayoutService.prototype.resolveGridChildSlotState = function (parentId, childId) {
2626
+ var _this = this;
2627
+ var _a;
2628
+ var parent = this.model.getElement(parentId);
2629
+ if (!parent || ((_a = parent.layout) === null || _a === void 0 ? void 0 : _a.mode) !== 'grid')
2630
+ return null;
2631
+ var assignedRows = this.resolveAssignedGridRows(parent);
2632
+ if (assignedRows.length === 0)
2633
+ return null;
2634
+ var orderedChildIds = assignedRows.flatMap(function (row) { return row.childIds; });
2635
+ var slotWeights = assignedRows.flatMap(function (row) { return row.weights.slice(0, row.childIds.length).map(function (weight) { return _this.clampGridUnits(weight); }); });
2636
+ var childFlatIndex = orderedChildIds.indexOf(childId);
2637
+ if (childFlatIndex < 0)
2638
+ return null;
2639
+ var rowIndex = assignedRows.findIndex(function (row) { return row.childIds.includes(childId); });
2640
+ if (rowIndex < 0)
2641
+ return null;
2642
+ return { assignedRows: assignedRows, orderedChildIds: orderedChildIds, slotWeights: slotWeights, childFlatIndex: childFlatIndex, rowIndex: rowIndex };
2643
+ };
2644
+ AutoLayoutService.prototype.packGridRowsFromSlots = function (childIds, slotWeights) {
2645
+ var _this = this;
2646
+ var rows = [];
2647
+ var currentChildIds = [];
2648
+ var currentWeights = [];
2649
+ var currentUnits = 0;
2650
+ childIds.forEach(function (childId, index) {
2651
+ var _a;
2652
+ var slotUnits = _this.clampGridUnits((_a = slotWeights[index]) !== null && _a !== void 0 ? _a : GRID_ROW_UNITS);
2653
+ if (currentChildIds.length > 0 && currentUnits + slotUnits > GRID_ROW_UNITS) {
2654
+ rows.push({ childIds: __spreadArray([], currentChildIds, true), weights: __spreadArray([], currentWeights, true) });
2655
+ currentChildIds = [];
2656
+ currentWeights = [];
2657
+ currentUnits = 0;
2658
+ }
2659
+ currentChildIds.push(childId);
2660
+ currentWeights.push(slotUnits);
2661
+ currentUnits += slotUnits;
2662
+ });
2663
+ if (currentChildIds.length > 0) {
2664
+ rows.push({ childIds: __spreadArray([], currentChildIds, true), weights: __spreadArray([], currentWeights, true) });
2665
+ }
2666
+ return rows;
2667
+ };
2668
+ AutoLayoutService.prototype.resolveRequestedGridUnits = function (parent, currentRow, requestedWidth) {
2669
+ var _a;
2670
+ if (!parent.layout || parent.layout.mode !== 'grid' || !currentRow)
2671
+ return GRID_ROW_UNITS;
2672
+ var rowUnitWidth = this.resolveGridRowUnitWidth(Math.max(0, parent.size.width - this.resolveLayoutPadding(parent.layout).x * 2), currentRow.childIds.length, (_a = parent.layout.gap) !== null && _a !== void 0 ? _a : 12);
2673
+ if (rowUnitWidth <= 0)
2674
+ return GRID_ROW_UNITS;
2675
+ return this.clampGridUnits(Math.round(requestedWidth / rowUnitWidth));
2676
+ };
2677
+ AutoLayoutService.prototype.sortGridChildrenForLayout = function (children) {
2678
+ return __spreadArray([], children, true).sort(function (a, b) {
2679
+ if (a.position.y === b.position.y) {
2680
+ if (a.position.x === b.position.x)
2681
+ return a.id.localeCompare(b.id);
2682
+ return a.position.x - b.position.x;
2683
+ }
2684
+ return a.position.y - b.position.y;
2685
+ });
2686
+ };
2687
+ AutoLayoutService.prototype.resolveRightwardGridOverflowChange = function (params) {
2688
+ var _a, _b;
2689
+ var assignedRows = params.assignedRows, rowIndex = params.rowIndex, childIndex = params.childIndex, requestedWidth = params.requestedWidth, availableWidth = params.availableWidth, gap = params.gap, parentLayout = params.parentLayout, parentId = params.parentId, childId = params.childId;
2690
+ var currentRow = assignedRows[rowIndex];
2691
+ if (!currentRow || childIndex < 0 || childIndex >= currentRow.childIds.length - 1)
2692
+ return null;
2693
+ var rowUnitWidth = this.resolveGridRowUnitWidth(availableWidth, currentRow.childIds.length, gap);
2694
+ if (rowUnitWidth <= 0)
2695
+ return null;
2696
+ var currentUnits = (_b = (_a = currentRow.weights[childIndex]) !== null && _a !== void 0 ? _a : this.normalizeRowWeightsToTwelveUnits(currentRow.weights)[childIndex]) !== null && _b !== void 0 ? _b : 1;
2697
+ var requestedUnits = this.clampLayoutSize(Math.round(requestedWidth / rowUnitWidth), currentUnits + 1, GRID_ROW_UNITS - 1);
2698
+ var leftWeights = currentRow.weights.slice(0, childIndex);
2699
+ var leftSum = leftWeights.reduce(function (sum, value) { return sum + value; }, 0);
2700
+ var rightWeights = currentRow.weights.slice(childIndex + 1);
2701
+ var rightIds = currentRow.childIds.slice(childIndex + 1);
2702
+ var followingRows = assignedRows.slice(rowIndex + 1);
2703
+ for (var retainCount = rightIds.length - 1; retainCount >= 0; retainCount -= 1) {
2704
+ var maxTargetUnits = GRID_ROW_UNITS - leftSum - retainCount;
2705
+ if (requestedUnits > maxTargetUnits)
2706
+ continue;
2707
+ var retainedIds = rightIds.slice(0, retainCount);
2708
+ var retainedWeights = rightWeights.slice(0, retainCount);
2709
+ var overflowIds = __spreadArray(__spreadArray([], rightIds.slice(retainCount), true), followingRows.flatMap(function (row) { return row.childIds; }), true);
2710
+ var remainingUnits = GRID_ROW_UNITS - leftSum - requestedUnits;
2711
+ var nextCurrentWeights = __spreadArray(__spreadArray(__spreadArray([], leftWeights, true), [
2712
+ requestedUnits
2713
+ ], false), this.distributeUnitsWithMinimums(remainingUnits, retainedWeights), true);
2714
+ var nextRows = assignedRows.slice(0, rowIndex).map(function (row) { return ({
2715
+ weights: __spreadArray([], row.weights, true),
2716
+ childIds: __spreadArray([], row.childIds, true),
2717
+ }); });
2718
+ nextRows.push({
2719
+ weights: nextCurrentWeights,
2720
+ childIds: __spreadArray(__spreadArray([], currentRow.childIds.slice(0, childIndex + 1), true), retainedIds, true),
2721
+ });
2722
+ var trailingRows = this.reflowTrailingGridRows(overflowIds, followingRows, currentRow.weights.length);
2723
+ var allRows = __spreadArray(__spreadArray([], nextRows, true), trailingRows, true);
2724
+ var beforeRows = assignedRows.map(function (row) { return ({ childIds: __spreadArray([], row.childIds, true) }); });
2725
+ var afterRows = allRows.map(function (row) { return ({ childIds: __spreadArray([], row.childIds, true) }); });
2726
+ if (this.gridRowSnapshotsEqual(beforeRows, afterRows) && this.gridWeightsEqual(assignedRows, allRows)) {
2727
+ return null;
2728
+ }
2729
+ return {
2730
+ parentId: parentId,
2731
+ triggerChildId: childId,
2732
+ reason: 'child-resize-redistribute',
2733
+ beforeRows: beforeRows,
2734
+ afterRows: afterRows,
2735
+ nextLayout: __assign(__assign({}, parentLayout), { gridTemplate: this.flattenAssignedRowsToGridTemplate(allRows) }),
2736
+ };
2737
+ }
2738
+ return null;
2739
+ };
2740
+ AutoLayoutService.prototype.resolveSameRowGridUnitResizeChange = function (params) {
2741
+ var _this = this;
2742
+ var _a, _b, _c, _d;
2743
+ var assignedRows = params.assignedRows, rowIndex = params.rowIndex, childIndex = params.childIndex, requestedWidth = params.requestedWidth, availableWidth = params.availableWidth, gap = params.gap, parentLayout = params.parentLayout, parentId = params.parentId, childId = params.childId;
2744
+ var currentRow = assignedRows[rowIndex];
2745
+ if (!currentRow || currentRow.childIds.length <= 1)
2746
+ return null;
2747
+ var donorIndices = Array.from({ length: Math.max(0, currentRow.childIds.length - childIndex - 1) }, function (_, index) { return childIndex + 1 + index; });
2748
+ if (donorIndices.length === 0)
2749
+ return null;
2750
+ var rowUnitWidth = this.resolveGridRowUnitWidth(availableWidth, currentRow.childIds.length, gap);
2751
+ if (rowUnitWidth <= 0)
2752
+ return null;
2753
+ var currentUnits = (_b = (_a = currentRow.weights[childIndex]) !== null && _a !== void 0 ? _a : this.normalizeRowWeightsToTwelveUnits(currentRow.weights)[childIndex]) !== null && _b !== void 0 ? _b : 1;
2754
+ var requestedUnits = this.clampLayoutSize(Math.round(requestedWidth / rowUnitWidth), 1, GRID_ROW_UNITS - 1);
2755
+ if (requestedUnits === currentUnits)
2756
+ return null;
2757
+ var nextWeights = __spreadArray([], currentRow.weights, true);
2758
+ var delta = requestedUnits - currentUnits;
2759
+ if (delta > 0) {
2760
+ for (var _i = 0, donorIndices_1 = donorIndices; _i < donorIndices_1.length; _i++) {
2761
+ var donorIndex = donorIndices_1[_i];
2762
+ if (delta <= 0)
2763
+ break;
2764
+ var donorCapacity = Math.max(0, ((_c = nextWeights[donorIndex]) !== null && _c !== void 0 ? _c : 1) - 1);
2765
+ var transfer = Math.min(delta, donorCapacity);
2766
+ nextWeights[donorIndex] -= transfer;
2767
+ nextWeights[childIndex] += transfer;
2768
+ delta -= transfer;
2769
+ }
2770
+ }
2771
+ else {
2772
+ var release = Math.abs(delta);
2773
+ for (var _e = 0, donorIndices_2 = donorIndices; _e < donorIndices_2.length; _e++) {
2774
+ var donorIndex = donorIndices_2[_e];
2775
+ if (release <= 0)
2776
+ break;
2777
+ var transfer = release;
2778
+ nextWeights[donorIndex] += transfer;
2779
+ nextWeights[childIndex] -= transfer;
2780
+ release -= transfer;
2781
+ }
2782
+ }
2783
+ if (delta > 0)
2784
+ return null;
2785
+ if (((_d = nextWeights[childIndex]) !== null && _d !== void 0 ? _d : currentUnits) === currentUnits)
2786
+ return null;
2787
+ var nextRows = assignedRows.map(function (row, index) {
2788
+ return index === rowIndex
2789
+ ? {
2790
+ weights: _this.normalizeRowWeightsToTwelveUnits(nextWeights),
2791
+ childIds: __spreadArray([], row.childIds, true),
2792
+ }
2793
+ : { weights: __spreadArray([], row.weights, true), childIds: __spreadArray([], row.childIds, true) };
2794
+ });
2795
+ return {
2796
+ parentId: parentId,
2797
+ triggerChildId: childId,
2798
+ reason: 'child-resize-redistribute',
2799
+ beforeRows: assignedRows.map(function (row) { return ({ childIds: __spreadArray([], row.childIds, true) }); }),
2800
+ afterRows: nextRows.map(function (row) { return ({ childIds: __spreadArray([], row.childIds, true) }); }),
2801
+ nextLayout: __assign(__assign({}, parentLayout), { gridTemplate: this.flattenAssignedRowsToGridTemplate(nextRows) }),
2802
+ };
2803
+ };
2804
+ AutoLayoutService.prototype.splitGridRowIntoTwelveUnits = function (assignedRows, rowIndex, childId, requestedWidth, availableWidth, gap) {
2805
+ var _a;
2806
+ var currentRow = assignedRows[rowIndex];
2807
+ var nextRow = assignedRows[rowIndex + 1];
2808
+ if (!currentRow || !nextRow || currentRow.childIds.length !== 1 || nextRow.childIds.length === 0) {
2809
+ return [];
2810
+ }
2811
+ var rowUnitWidth = this.resolveGridRowUnitWidth(availableWidth, 2, gap);
2812
+ var requestedUnits = this.clampLayoutSize(Math.round(requestedWidth / rowUnitWidth), 1, GRID_ROW_UNITS - 1);
2813
+ var nextRows = assignedRows.slice(0, rowIndex).map(function (row) { return ({
2814
+ weights: __spreadArray([], row.weights, true),
2815
+ childIds: __spreadArray([], row.childIds, true),
2816
+ }); });
2817
+ nextRows.push({
2818
+ weights: [requestedUnits, GRID_ROW_UNITS - requestedUnits],
2819
+ childIds: [childId, nextRow.childIds[0]],
2820
+ });
2821
+ var trailingRows = [];
2822
+ var remainingChildIds = __spreadArray(__spreadArray([], nextRow.childIds.slice(1), true), assignedRows.slice(rowIndex + 2).flatMap(function (row) { return row.childIds; }), true);
2823
+ var cursor = 0;
2824
+ var seedRows = assignedRows.slice(rowIndex + 1);
2825
+ var seedIndex = 0;
2826
+ while (cursor < remainingChildIds.length) {
2827
+ var seed = seedRows[Math.min(seedIndex, seedRows.length - 1)];
2828
+ var capacity = Math.max(1, (_a = seed === null || seed === void 0 ? void 0 : seed.childIds.length) !== null && _a !== void 0 ? _a : 1);
2829
+ var rowChildIds = remainingChildIds.slice(cursor, cursor + capacity);
2830
+ trailingRows.push({
2831
+ weights: this.fitGridRowWeights(seed === null || seed === void 0 ? void 0 : seed.weights, rowChildIds.length),
2832
+ childIds: rowChildIds,
2833
+ });
2834
+ cursor += rowChildIds.length;
2835
+ seedIndex += 1;
2836
+ }
2837
+ return __spreadArray(__spreadArray([], nextRows, true), trailingRows, true);
2838
+ };
2839
+ AutoLayoutService.prototype.reflowTrailingGridRows = function (childIds, seedRows, fallbackColumnCount) {
2840
+ var _a;
2841
+ if (childIds.length === 0)
2842
+ return [];
2843
+ var trailingRows = [];
2844
+ var cursor = 0;
2845
+ var seedIndex = 0;
2846
+ var normalizedSeedRows = seedRows.length > 0 ? seedRows : [{ weights: this.buildEqualGridUnits(Math.max(1, fallbackColumnCount)), childIds: [] }];
2847
+ while (cursor < childIds.length) {
2848
+ var seed = normalizedSeedRows[Math.min(seedIndex, normalizedSeedRows.length - 1)];
2849
+ var capacity = Math.max(1, (_a = seed === null || seed === void 0 ? void 0 : seed.weights.length) !== null && _a !== void 0 ? _a : fallbackColumnCount);
2850
+ var rowChildIds = childIds.slice(cursor, cursor + capacity);
2851
+ trailingRows.push({
2852
+ weights: this.fitGridRowWeights(seed === null || seed === void 0 ? void 0 : seed.weights, rowChildIds.length),
2853
+ childIds: rowChildIds,
2854
+ });
2855
+ cursor += rowChildIds.length;
2856
+ seedIndex += 1;
2857
+ }
2858
+ return trailingRows;
2859
+ };
2860
+ AutoLayoutService.prototype.flattenAssignedRowsToGridTemplate = function (rows) {
2861
+ var _this = this;
2862
+ return rows.flatMap(function (row) { return _this.normalizeRowWeightsToTwelveUnits(row.weights.slice(0, row.childIds.length)); });
2863
+ };
2864
+ AutoLayoutService.prototype.buildEqualGridUnits = function (count) {
2865
+ if (count <= 0)
2866
+ return [];
2867
+ var base = Math.floor(GRID_ROW_UNITS / count);
2868
+ var remainder = GRID_ROW_UNITS - base * count;
2869
+ return Array.from({ length: count }, function (_, index) { return base + (index < remainder ? 1 : 0); });
2870
+ };
2871
+ AutoLayoutService.prototype.normalizeRowWeightsToTwelveUnits = function (weights) {
2872
+ var safeWeights = weights.map(function (weight) { return (Number.isFinite(weight) && weight > 0 ? weight : 1); });
2873
+ if (safeWeights.length === 0)
2874
+ return [GRID_ROW_UNITS];
2875
+ if (safeWeights.length === 1)
2876
+ return [GRID_ROW_UNITS];
2877
+ var distributed = this.distributeWeightedSizes(GRID_ROW_UNITS, safeWeights);
2878
+ var normalized = distributed.map(function (value) { return Math.max(1, value); });
2879
+ var total = normalized.reduce(function (sum, value) { return sum + value; }, 0);
2880
+ if (total === GRID_ROW_UNITS)
2881
+ return normalized;
2882
+ if (total < GRID_ROW_UNITS) {
2883
+ var cursor_1 = 0;
2884
+ while (total < GRID_ROW_UNITS) {
2885
+ normalized[cursor_1 % normalized.length] += 1;
2886
+ total += 1;
2887
+ cursor_1 += 1;
2888
+ }
2889
+ return normalized;
2890
+ }
2891
+ var cursor = normalized.length - 1;
2892
+ while (total > GRID_ROW_UNITS && cursor >= 0) {
2893
+ if (normalized[cursor] > 1) {
2894
+ normalized[cursor] -= 1;
2895
+ total -= 1;
2896
+ }
2897
+ else {
2898
+ cursor -= 1;
2899
+ }
2900
+ if (cursor < 0 && total > GRID_ROW_UNITS) {
2901
+ cursor = normalized.length - 1;
2902
+ }
2903
+ }
2904
+ return normalized;
2905
+ };
2906
+ AutoLayoutService.prototype.normalizeGridSlotUnits = function (template) {
2907
+ var _this = this;
2908
+ var slots = [];
2909
+ (template !== null && template !== void 0 ? template : []).forEach(function (entry) {
2910
+ if (typeof entry === 'number') {
2911
+ if (Number.isFinite(entry) && entry > 0) {
2912
+ slots.push(_this.clampGridUnits(entry));
2913
+ }
2914
+ return;
2915
+ }
2916
+ if (!Array.isArray(entry))
2917
+ return;
2918
+ entry.forEach(function (value) {
2919
+ if (Number.isFinite(value) && value > 0) {
2920
+ slots.push(_this.clampGridUnits(value));
2921
+ }
2922
+ });
2923
+ });
2924
+ return slots;
2925
+ };
2926
+ AutoLayoutService.prototype.clampGridUnits = function (value) {
2927
+ return Math.max(1, Math.min(GRID_ROW_UNITS, Math.round(value)));
2928
+ };
2929
+ AutoLayoutService.prototype.distributeUnitsWithMinimums = function (totalUnits, seedWeights) {
2930
+ if (seedWeights.length === 0)
2931
+ return [];
2932
+ var minimumTotal = seedWeights.length;
2933
+ var clampedTotal = Math.max(minimumTotal, totalUnits);
2934
+ var distributed = this.distributeWeightedSizes(clampedTotal - minimumTotal, seedWeights).map(function (value) { return value + 1; });
2935
+ return distributed;
2936
+ };
2937
+ AutoLayoutService.prototype.gridWeightsEqual = function (leftRows, rightRows) {
2938
+ var _a, _b, _c, _d;
2939
+ if (leftRows.length !== rightRows.length)
2940
+ return false;
2941
+ for (var rowIndex = 0; rowIndex < leftRows.length; rowIndex += 1) {
2942
+ var left = (_b = (_a = leftRows[rowIndex]) === null || _a === void 0 ? void 0 : _a.weights) !== null && _b !== void 0 ? _b : [];
2943
+ var right = (_d = (_c = rightRows[rowIndex]) === null || _c === void 0 ? void 0 : _c.weights) !== null && _d !== void 0 ? _d : [];
2944
+ if (left.length !== right.length)
2945
+ return false;
2946
+ for (var index = 0; index < left.length; index += 1) {
2947
+ if (left[index] !== right[index])
2948
+ return false;
2949
+ }
2950
+ }
2951
+ return true;
2952
+ };
2953
+ AutoLayoutService.prototype.resolveGridRowUnitWidth = function (availableWidth, childCount, gap) {
2954
+ var totalGap = Math.max(0, childCount - 1) * gap;
2955
+ var rowInnerWidth = Math.max(0, availableWidth - totalGap);
2956
+ return rowInnerWidth / GRID_ROW_UNITS;
2957
+ };
2134
2958
  AutoLayoutService.prototype.resolveLabelReservedTopLane = function (parentId, layout) {
2135
2959
  var _a, _b, _c, _d;
2136
2960
  var policy = layout === null || layout === void 0 ? void 0 : layout.labelReservedSpace;
@@ -2170,11 +2994,43 @@ var AutoLayoutService = /** @class */ (function () {
2170
2994
  });
2171
2995
  return Math.max(0, lane);
2172
2996
  };
2997
+ AutoLayoutService.prototype.resolveAlignmentOffset = function (align, container, content) {
2998
+ var delta = Math.max(0, container - content);
2999
+ if (align === 'start')
3000
+ return 0;
3001
+ if (align === 'end')
3002
+ return delta;
3003
+ return delta / 2;
3004
+ };
2173
3005
  AutoLayoutService.prototype.clampLayoutSize = function (value, min, max) {
2174
3006
  var minValue = min !== null && min !== void 0 ? min : 0;
2175
3007
  var maxValue = max !== null && max !== void 0 ? max : Number.POSITIVE_INFINITY;
2176
3008
  return Math.max(minValue, Math.min(maxValue, value));
2177
3009
  };
3010
+ AutoLayoutService.prototype.distributeWeightedSizes = function (total, weights) {
3011
+ if (weights.length === 0)
3012
+ return [];
3013
+ var safeTotal = Math.max(0, total);
3014
+ var normalized = weights.map(function (weight) { return (Number.isFinite(weight) && weight > 0 ? weight : 1); });
3015
+ var sumWeights = normalized.reduce(function (sum, weight) { return sum + weight; }, 0);
3016
+ if (sumWeights <= 0) {
3017
+ return Array.from({ length: normalized.length }, function () { return 0; });
3018
+ }
3019
+ var raw = normalized.map(function (weight) { return (safeTotal * weight) / sumWeights; });
3020
+ var floored = raw.map(function (value) { return Math.floor(value); });
3021
+ var remainder = Math.max(0, Math.round(safeTotal - floored.reduce(function (sum, value) { return sum + value; }, 0)));
3022
+ var fractions = raw
3023
+ .map(function (value, index) { return ({ index: index, fraction: value - floored[index] }); })
3024
+ .sort(function (a, b) { return b.fraction - a.fraction || a.index - b.index; });
3025
+ var cursor = 0;
3026
+ while (remainder > 0 && fractions.length > 0) {
3027
+ var index = fractions[cursor % fractions.length].index;
3028
+ floored[index] += 1;
3029
+ remainder -= 1;
3030
+ cursor += 1;
3031
+ }
3032
+ return floored;
3033
+ };
2178
3034
  AutoLayoutService.prototype.distributeLayoutSizes = function (total, count, minValues, maxValues) {
2179
3035
  if (count <= 0)
2180
3036
  return [];
@@ -2393,6 +3249,35 @@ var LinkRoutingService = /** @class */ (function () {
2393
3249
  });
2394
3250
  return patches;
2395
3251
  };
3252
+ LinkRoutingService.prototype.refreshLinksForRedraw = function (options) {
3253
+ var _this = this;
3254
+ var includeManual = Boolean(options === null || options === void 0 ? void 0 : options.includeManual);
3255
+ var patches = [];
3256
+ var links = Array.from(this.model.links.values()).sort(function (a, b) { return a.id.localeCompare(b.id); });
3257
+ links.forEach(function (link) {
3258
+ var _a;
3259
+ if (link.points.length < 2)
3260
+ return;
3261
+ var routing = (_a = link.routing) !== null && _a !== void 0 ? _a : 'auto';
3262
+ if (routing === 'manual' && !includeManual)
3263
+ return;
3264
+ var endpoints = _this.resolveLinkEndpoints(link);
3265
+ var source = endpoints.source;
3266
+ var target = endpoints.target;
3267
+ if (!source || !target)
3268
+ return;
3269
+ var first = link.points[0];
3270
+ var last = link.points[link.points.length - 1];
3271
+ var sourceChanged = !_this.pointsEqual(first, source);
3272
+ var targetChanged = !_this.pointsEqual(last, target);
3273
+ if (!sourceChanged || !targetChanged)
3274
+ return;
3275
+ var points = _this.resolveLinkPointsForUpdate(link, source, target);
3276
+ var linkPatches = _this.commandQueue.run(createUpdateLinkCommand(link.id, { points: points }), _this.model);
3277
+ patches.push.apply(patches, linkPatches);
3278
+ });
3279
+ return patches;
3280
+ };
2396
3281
  LinkRoutingService.prototype.getPortLinkWorldPosition = function (portId, options) {
2397
3282
  var _a;
2398
3283
  var port = this.model.getPort(portId);
@@ -2470,6 +3355,9 @@ var LinkRoutingService = /** @class */ (function () {
2470
3355
  return __assign({}, point);
2471
3356
  });
2472
3357
  };
3358
+ LinkRoutingService.prototype.pointsEqual = function (a, b) {
3359
+ return Math.abs(a.x - b.x) <= POSITION_EPSILON$1 && Math.abs(a.y - b.y) <= POSITION_EPSILON$1;
3360
+ };
2473
3361
  LinkRoutingService.prototype.buildRouteContext = function (link) {
2474
3362
  var _this = this;
2475
3363
  var _a, _b;
@@ -2492,6 +3380,8 @@ var LinkRoutingService = /** @class */ (function () {
2492
3380
  var targetOnEdge = (_b = targetEndpointGeometry === null || targetEndpointGeometry === void 0 ? void 0 : targetEndpointGeometry.onEdge) !== null && _b !== void 0 ? _b : false;
2493
3381
  var ancestorExclusions = this.getAncestorExclusions(sourceElementId, targetElementId);
2494
3382
  var _c = this.resolveRouteBounds(sourceElementId, targetElementId), bounds = _c.bounds, boundsElementId = _c.boundsElementId;
3383
+ var commonAncestorCorridor = this.resolveCommonAncestorCorridorHint(sourceElementId, targetElementId);
3384
+ var effectiveBounds = bounds !== null && bounds !== void 0 ? bounds : commonAncestorCorridor === null || commonAncestorCorridor === void 0 ? void 0 : commonAncestorCorridor.bounds;
2495
3385
  var forcedObstacles = new Set();
2496
3386
  if (sourceElementId && sourceOnEdge)
2497
3387
  forcedObstacles.add(sourceElementId);
@@ -2534,7 +3424,7 @@ var LinkRoutingService = /** @class */ (function () {
2534
3424
  sourcePortId: link.sourcePortId,
2535
3425
  targetPortId: link.targetPortId,
2536
3426
  obstacles: obstacles,
2537
- bounds: bounds,
3427
+ bounds: effectiveBounds,
2538
3428
  sourceEndpoint: sourcePosition && sourceRect
2539
3429
  ? {
2540
3430
  elementId: sourceElementId !== null && sourceElementId !== void 0 ? sourceElementId : undefined,
@@ -2549,6 +3439,48 @@ var LinkRoutingService = /** @class */ (function () {
2549
3439
  onEdgeSide: targetEndpointGeometry === null || targetEndpointGeometry === void 0 ? void 0 : targetEndpointGeometry.onEdgeSide,
2550
3440
  }
2551
3441
  : undefined,
3442
+ commonAncestorCorridor: commonAncestorCorridor,
3443
+ };
3444
+ };
3445
+ LinkRoutingService.prototype.resolveCommonAncestorCorridorHint = function (sourceElementId, targetElementId) {
3446
+ if (!sourceElementId || !targetElementId)
3447
+ return undefined;
3448
+ if (sourceElementId === targetElementId)
3449
+ return undefined;
3450
+ var sourceElement = this.model.getElement(sourceElementId);
3451
+ var targetElement = this.model.getElement(targetElementId);
3452
+ if (!sourceElement || !targetElement)
3453
+ return undefined;
3454
+ if (sourceElement.parentId === targetElement.parentId)
3455
+ return undefined;
3456
+ if (this.isAncestorOf(sourceElementId, targetElementId) || this.isAncestorOf(targetElementId, sourceElementId)) {
3457
+ return undefined;
3458
+ }
3459
+ var commonAncestorId = this.getFirstCommonAncestorId(sourceElementId, targetElementId);
3460
+ if (!commonAncestorId)
3461
+ return undefined;
3462
+ var commonBounds = this.getElementRect(commonAncestorId);
3463
+ if (!commonBounds)
3464
+ return undefined;
3465
+ var sourceBranchId = this.resolveImmediateChildUnderAncestor(sourceElementId, commonAncestorId);
3466
+ var targetBranchId = this.resolveImmediateChildUnderAncestor(targetElementId, commonAncestorId);
3467
+ if (!sourceBranchId || !targetBranchId || sourceBranchId === targetBranchId)
3468
+ return undefined;
3469
+ var sourceBranchRect = this.getElementRect(sourceBranchId);
3470
+ var targetBranchRect = this.getElementRect(targetBranchId);
3471
+ if (!sourceBranchRect || !targetBranchRect)
3472
+ return undefined;
3473
+ var horizontalSeparation = sourceBranchRect.x + sourceBranchRect.width <= targetBranchRect.x ||
3474
+ targetBranchRect.x + targetBranchRect.width <= sourceBranchRect.x;
3475
+ var axis = horizontalSeparation ? 'horizontal' : 'vertical';
3476
+ return {
3477
+ ancestorId: commonAncestorId,
3478
+ bounds: commonBounds,
3479
+ sourceBranchId: sourceBranchId,
3480
+ targetBranchId: targetBranchId,
3481
+ sourceBranchRect: sourceBranchRect,
3482
+ targetBranchRect: targetBranchRect,
3483
+ axis: axis,
2552
3484
  };
2553
3485
  };
2554
3486
  LinkRoutingService.prototype.resolveEndpointGeometry = function (point, rect, elementId, oppositePoint) {
@@ -2557,11 +3489,18 @@ var LinkRoutingService = /** @class */ (function () {
2557
3489
  var onEdge = (shape === null || shape === void 0 ? void 0 : shape.projectToBorder)
2558
3490
  ? this.isPointOnProjectedBorder(point, rect, shape.projectToBorder, EDGE_TOLERANCE)
2559
3491
  : this.isPointOnRectEdge(point, rect, EDGE_TOLERANCE);
2560
- var onEdgeSide = onEdge ? (_b = (_a = shape === null || shape === void 0 ? void 0 : shape.resolveBorderSide) === null || _a === void 0 ? void 0 : _a.call(shape, point, rect)) !== null && _b !== void 0 ? _b : this.resolveEdgeSide(point, rect) : undefined;
3492
+ var projectedBorderPoint = (shape === null || shape === void 0 ? void 0 : shape.projectToBorder)
3493
+ ? shape.projectToBorder(point, rect)
3494
+ : projectPointToBoundary(point, rect, 'rect');
3495
+ var projectedBoundaryEquivalent = !onEdge && !this.isPointInsideRect(point, rect, EDGE_TOLERANCE);
3496
+ var sidePoint = projectedBoundaryEquivalent ? projectedBorderPoint : point;
3497
+ var onEdgeSide = onEdge || projectedBoundaryEquivalent
3498
+ ? (_b = (_a = shape === null || shape === void 0 ? void 0 : shape.resolveBorderSide) === null || _a === void 0 ? void 0 : _a.call(shape, sidePoint, rect)) !== null && _b !== void 0 ? _b : this.resolveEdgeSide(sidePoint, rect)
3499
+ : undefined;
2561
3500
  if (onEdgeSide && oppositePoint) {
2562
3501
  onEdgeSide = this.resolveCornerTieBreakSide(point, rect, oppositePoint, onEdgeSide);
2563
3502
  }
2564
- return { onEdge: onEdge, onEdgeSide: onEdgeSide };
3503
+ return { onEdge: onEdge || projectedBoundaryEquivalent, onEdgeSide: onEdgeSide };
2565
3504
  };
2566
3505
  LinkRoutingService.prototype.resolveCornerTieBreakSide = function (point, rect, oppositePoint, currentSide) {
2567
3506
  var onLeft = Math.abs(point.x - rect.x) <= EDGE_TOLERANCE;
@@ -2653,6 +3592,34 @@ var LinkRoutingService = /** @class */ (function () {
2653
3592
  }
2654
3593
  return chain;
2655
3594
  };
3595
+ LinkRoutingService.prototype.getFirstCommonAncestorId = function (sourceElementId, targetElementId) {
3596
+ var sourceChain = this.getAncestorChain(sourceElementId);
3597
+ var targetSet = new Set(this.getAncestorChain(targetElementId));
3598
+ for (var i = 0; i < sourceChain.length; i += 1) {
3599
+ var candidate = sourceChain[i];
3600
+ if (targetSet.has(candidate))
3601
+ return candidate;
3602
+ }
3603
+ return null;
3604
+ };
3605
+ LinkRoutingService.prototype.resolveImmediateChildUnderAncestor = function (elementId, ancestorId) {
3606
+ var _a;
3607
+ if (elementId === ancestorId)
3608
+ return null;
3609
+ var currentId = elementId;
3610
+ var previousId = null;
3611
+ while (currentId) {
3612
+ var current = this.model.getElement(currentId);
3613
+ if (!current)
3614
+ return null;
3615
+ if (current.id === ancestorId) {
3616
+ return previousId;
3617
+ }
3618
+ previousId = current.id;
3619
+ currentId = (_a = current.parentId) !== null && _a !== void 0 ? _a : null;
3620
+ }
3621
+ return null;
3622
+ };
2656
3623
  LinkRoutingService.prototype.getAncestorExclusions = function (sourceElementId, targetElementId) {
2657
3624
  var exclusions = new Set();
2658
3625
  if (sourceElementId) {
@@ -2695,6 +3662,12 @@ var LinkRoutingService = /** @class */ (function () {
2695
3662
  var onBottom = Math.abs(point.y - (rect.y + rect.height)) <= tolerance;
2696
3663
  return onLeft || onRight || onTop || onBottom;
2697
3664
  };
3665
+ LinkRoutingService.prototype.isPointInsideRect = function (point, rect, tolerance) {
3666
+ return (point.x >= rect.x - tolerance &&
3667
+ point.x <= rect.x + rect.width + tolerance &&
3668
+ point.y >= rect.y - tolerance &&
3669
+ point.y <= rect.y + rect.height + tolerance);
3670
+ };
2698
3671
  LinkRoutingService.prototype.resolveEdgeSide = function (point, rect) {
2699
3672
  var distances = [
2700
3673
  { side: 'left', value: Math.abs(point.x - rect.x) },
@@ -2739,8 +3712,8 @@ var MutationPipeline = /** @class */ (function () {
2739
3712
  }());
2740
3713
 
2741
3714
  var clampToRect = function (point, rect) { return ({
2742
- x: clamp(point.x, rect.x, rect.x + rect.width),
2743
- y: clamp(point.y, rect.y, rect.y + rect.height),
3715
+ x: clamp$2(point.x, rect.x, rect.x + rect.width),
3716
+ y: clamp$2(point.y, rect.y, rect.y + rect.height),
2744
3717
  }); };
2745
3718
  var snapToRectBorder = function (point, rect) {
2746
3719
  var clamped = clampToRect(point, rect);
@@ -2759,10 +3732,41 @@ var snapToRectBorder = function (point, rect) {
2759
3732
  };
2760
3733
  var POSITION_EPSILON = 1e-6;
2761
3734
  var ANCHOR_PRESET_FALLBACK_ORDER = ['vertices', 'cardinal'];
3735
+ var DEFAULT_LINK_COLOR_POOL = [
3736
+ '#1f77b4',
3737
+ '#ff7f0e',
3738
+ '#2ca02c',
3739
+ '#d62728',
3740
+ '#9467bd',
3741
+ '#8c564b',
3742
+ '#e377c2',
3743
+ '#7f7f7f',
3744
+ '#bcbd22',
3745
+ '#17becf',
3746
+ '#4e79a7',
3747
+ '#f28e2b',
3748
+ '#e15759',
3749
+ '#76b7b2',
3750
+ '#59a14f',
3751
+ '#edc948',
3752
+ '#b07aa1',
3753
+ '#ff9da7',
3754
+ '#9c755f',
3755
+ '#bab0ab',
3756
+ ];
3757
+ var normalizeLinkColorPoolPolicy = function (policy) {
3758
+ var _a;
3759
+ var enabled = Boolean(policy === null || policy === void 0 ? void 0 : policy.enabled);
3760
+ var normalizedColors = ((_a = policy === null || policy === void 0 ? void 0 : policy.colors) !== null && _a !== void 0 ? _a : [])
3761
+ .map(function (color) { return color.trim(); })
3762
+ .filter(function (color) { return color.length > 0; });
3763
+ var colors = normalizedColors.length > 0 ? normalizedColors : __spreadArray([], DEFAULT_LINK_COLOR_POOL, true);
3764
+ return { enabled: enabled, colors: colors };
3765
+ };
2762
3766
  var DiagramEngine = /** @class */ (function () {
2763
3767
  function DiagramEngine(config) {
2764
3768
  var _this = this;
2765
- var _a, _b, _c, _d, _e;
3769
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2766
3770
  this.model = new DiagramModel();
2767
3771
  this.events = new EventBus();
2768
3772
  this.commandQueue = new CommandQueue();
@@ -2786,6 +3790,11 @@ var DiagramEngine = /** @class */ (function () {
2786
3790
  router: router,
2787
3791
  shapeRegistry: this.shapeRegistry,
2788
3792
  });
3793
+ this.linkRouteRefreshPolicy = {
3794
+ mode: (_g = (_f = config.linkRouteRefreshPolicy) === null || _f === void 0 ? void 0 : _f.mode) !== null && _g !== void 0 ? _g : 'mutation-only',
3795
+ includeManual: Boolean((_h = config.linkRouteRefreshPolicy) === null || _h === void 0 ? void 0 : _h.includeManual),
3796
+ };
3797
+ this.linkColorPoolPolicy = normalizeLinkColorPoolPolicy(config.linkColorPoolPolicy);
2789
3798
  this.mutationPipeline = new MutationPipeline({
2790
3799
  routeLinksWithEmptyPoints: function () { return _this.routeLinksWithEmptyPoints(); },
2791
3800
  reprojectBorderPortsForResizedElements: function (patches) { return _this.reprojectBorderPortsForResizedElements(patches); },
@@ -2841,9 +3850,7 @@ var DiagramEngine = /** @class */ (function () {
2841
3850
  });
2842
3851
  this.emitChange(allPatches);
2843
3852
  };
2844
- DiagramEngine.prototype.moveElementTo = function (id, x, y) {
2845
- var _this = this;
2846
- var oldWorld = this.model.getElementWorldPosition(id);
3853
+ DiagramEngine.prototype.resolveElementMovePosition = function (id, x, y) {
2847
3854
  var snapped = this.snapper.snap({ x: x, y: y });
2848
3855
  var element = this.model.getElement(id);
2849
3856
  var position = snapped;
@@ -2883,14 +3890,46 @@ var DiagramEngine = /** @class */ (function () {
2883
3890
  }
2884
3891
  }
2885
3892
  }
3893
+ return { element: element === null || element === void 0 ? void 0 : element.toData(), position: position };
3894
+ };
3895
+ DiagramEngine.prototype.buildChildMutationLayoutSteps = function (parentId, options) {
3896
+ var _this = this;
3897
+ var _a;
3898
+ if (!parentId) {
3899
+ return [function () { return _this.applyLayoutCascade(null); }];
3900
+ }
3901
+ var parent = this.model.getElement(parentId);
3902
+ if ((options === null || options === void 0 ? void 0 : options.preserveGridParentWidth) && ((_a = parent === null || parent === void 0 ? void 0 : parent.layout) === null || _a === void 0 ? void 0 : _a.mode) === 'grid') {
3903
+ return [
3904
+ function () { return _this.applyLayoutForParent(parentId, { preserveParentWidth: true }); },
3905
+ function () { var _a; return _this.applyLayoutCascade((_a = parent.parentId) !== null && _a !== void 0 ? _a : null); },
3906
+ ];
3907
+ }
3908
+ return [function () { return _this.applyLayoutCascade(parentId); }];
3909
+ };
3910
+ DiagramEngine.prototype.moveElementTo = function (id, x, y) {
3911
+ var _a;
3912
+ var oldWorld = this.model.getElementWorldPosition(id);
3913
+ var _b = this.resolveElementMovePosition(id, x, y), element = _b.element, position = _b.position;
3914
+ var beforeGridSlotState = (element === null || element === void 0 ? void 0 : element.parentId)
3915
+ ? this.autoLayoutService.describeGridSlotState(element.parentId)
3916
+ : null;
2886
3917
  var patches = this.commandQueue.run(createMoveElementCommand(id, position), this.model);
3918
+ if ((element === null || element === void 0 ? void 0 : element.parentId) && beforeGridSlotState) {
3919
+ var reorderedLayout = this.autoLayoutService.resolveGridReorderedLayout(element.parentId, beforeGridSlotState);
3920
+ if (reorderedLayout) {
3921
+ patches.push.apply(patches, this.commandQueue.run(createSetElementLayoutCommand(element.parentId, reorderedLayout), this.model));
3922
+ }
3923
+ }
2887
3924
  var movedPortIds = [];
2888
3925
  if (element) {
2889
3926
  movedPortIds.push.apply(movedPortIds, this.collectElementPortIds(element.id));
2890
3927
  }
2891
3928
  var allPatches = this.mutationPipeline.run({
2892
3929
  basePatches: patches,
2893
- layoutSteps: [function () { var _a; return _this.applyLayoutCascade((_a = element === null || element === void 0 ? void 0 : element.parentId) !== null && _a !== void 0 ? _a : null); }],
3930
+ layoutSteps: this.buildChildMutationLayoutSteps((_a = element === null || element === void 0 ? void 0 : element.parentId) !== null && _a !== void 0 ? _a : null, {
3931
+ preserveGridParentWidth: true,
3932
+ }),
2894
3933
  movedPortIds: movedPortIds,
2895
3934
  });
2896
3935
  this.emitChange(allPatches);
@@ -2907,20 +3946,106 @@ var DiagramEngine = /** @class */ (function () {
2907
3946
  }
2908
3947
  }
2909
3948
  };
3949
+ DiagramEngine.prototype.resizeElementBounds = function (id, bounds) {
3950
+ var _this = this;
3951
+ var _a, _b, _c, _d;
3952
+ var _e = this.resolveElementMovePosition(id, bounds.x, bounds.y), element = _e.element, position = _e.position;
3953
+ if (!element)
3954
+ return;
3955
+ var oldSize = __assign({}, element.size);
3956
+ var preserveParentSize = Boolean(element.layout && element.layout.mode !== 'manual');
3957
+ var gridLayoutChange = this.resolveGridChildWidthResizeTopologyChange(element, bounds.width);
3958
+ var patches = [];
3959
+ if (gridLayoutChange) {
3960
+ patches.push.apply(patches, this.commandQueue.run(createSetElementLayoutCommand(gridLayoutChange.parentId, gridLayoutChange.afterLayout), this.model));
3961
+ }
3962
+ var positionChanged = element.position.x !== position.x || element.position.y !== position.y;
3963
+ if (positionChanged) {
3964
+ patches.push.apply(patches, this.commandQueue.run(createMoveElementCommand(id, position), this.model));
3965
+ }
3966
+ patches.push.apply(patches, this.commandQueue.run(createResizeElementCommand(id, { width: bounds.width, height: bounds.height }), this.model));
3967
+ var movedPortIds = this.collectElementPortIds(element.id);
3968
+ var layoutSteps = [function () { return _this.applyLayoutForParent(id, { preserveParentSize: preserveParentSize }); }];
3969
+ if (gridLayoutChange && element.parentId) {
3970
+ var grandParentId_1 = (_b = (_a = this.model.getElement(element.parentId)) === null || _a === void 0 ? void 0 : _a.parentId) !== null && _b !== void 0 ? _b : null;
3971
+ layoutSteps.push(function () { var _a; return _this.applyLayoutForParent((_a = element.parentId) !== null && _a !== void 0 ? _a : '', { preserveParentWidth: true }); });
3972
+ if (grandParentId_1) {
3973
+ layoutSteps.push(function () { return _this.applyLayoutCascade(grandParentId_1); });
3974
+ }
3975
+ }
3976
+ else {
3977
+ layoutSteps.push.apply(layoutSteps, this.buildChildMutationLayoutSteps((_c = element.parentId) !== null && _c !== void 0 ? _c : null, {
3978
+ preserveGridParentWidth: true,
3979
+ }));
3980
+ }
3981
+ var allPatches = this.mutationPipeline.run({
3982
+ basePatches: patches,
3983
+ layoutSteps: layoutSteps,
3984
+ movedPortIds: movedPortIds,
3985
+ });
3986
+ if (gridLayoutChange) {
3987
+ this.events.emit('gridLayoutChanged', {
3988
+ parentId: gridLayoutChange.parentId,
3989
+ triggerChildId: gridLayoutChange.triggerChildId,
3990
+ reason: gridLayoutChange.reason,
3991
+ beforeRows: gridLayoutChange.beforeRows,
3992
+ afterRows: gridLayoutChange.afterRows,
3993
+ beforeGridTemplate: gridLayoutChange.beforeGridTemplate,
3994
+ afterGridTemplate: gridLayoutChange.afterGridTemplate,
3995
+ });
3996
+ }
3997
+ this.emitChange(allPatches);
3998
+ var newSize = (_d = this.model.getElement(id)) === null || _d === void 0 ? void 0 : _d.size;
3999
+ if (newSize && (oldSize.width !== newSize.width || oldSize.height !== newSize.height)) {
4000
+ this.events.emit('elementResized', { elementId: id, oldSize: oldSize, newSize: __assign({}, newSize) });
4001
+ }
4002
+ };
2910
4003
  DiagramEngine.prototype.resizeElement = function (id, width, height) {
2911
4004
  var _this = this;
2912
- var _a;
4005
+ var _a, _b, _c, _d;
2913
4006
  var element = this.model.getElement(id);
2914
4007
  var oldSize = element === null || element === void 0 ? void 0 : element.size;
2915
- var patches = this.commandQueue.run(createResizeElementCommand(id, { width: width, height: height }), this.model);
4008
+ var preserveParentSize = Boolean((element === null || element === void 0 ? void 0 : element.layout) && element.layout.mode !== 'manual');
4009
+ var gridLayoutChange = element
4010
+ ? this.resolveGridChildWidthResizeTopologyChange(element, width)
4011
+ : null;
4012
+ var patches = [];
4013
+ if (gridLayoutChange) {
4014
+ patches.push.apply(patches, this.commandQueue.run(createSetElementLayoutCommand(gridLayoutChange.parentId, gridLayoutChange.afterLayout), this.model));
4015
+ }
4016
+ patches.push.apply(patches, this.commandQueue.run(createResizeElementCommand(id, { width: width, height: height }), this.model));
2916
4017
  var movedPortIds = element ? this.collectElementPortIds(element.id) : [];
4018
+ var layoutSteps = [function () { return _this.applyLayoutForParent(id, { preserveParentSize: preserveParentSize }); }];
4019
+ if (gridLayoutChange && (element === null || element === void 0 ? void 0 : element.parentId)) {
4020
+ var grandParentId_2 = (_b = (_a = this.model.getElement(element.parentId)) === null || _a === void 0 ? void 0 : _a.parentId) !== null && _b !== void 0 ? _b : null;
4021
+ layoutSteps.push(function () { var _a; return _this.applyLayoutForParent((_a = element.parentId) !== null && _a !== void 0 ? _a : '', { preserveParentWidth: true }); });
4022
+ if (grandParentId_2) {
4023
+ layoutSteps.push(function () { return _this.applyLayoutCascade(grandParentId_2); });
4024
+ }
4025
+ }
4026
+ else {
4027
+ layoutSteps.push.apply(layoutSteps, this.buildChildMutationLayoutSteps((_c = element === null || element === void 0 ? void 0 : element.parentId) !== null && _c !== void 0 ? _c : null, {
4028
+ preserveGridParentWidth: true,
4029
+ }));
4030
+ }
2917
4031
  var allPatches = this.mutationPipeline.run({
2918
4032
  basePatches: patches,
2919
- layoutSteps: [function () { return _this.applyLayoutForParent(id); }, function () { var _a; return _this.applyLayoutCascade((_a = element === null || element === void 0 ? void 0 : element.parentId) !== null && _a !== void 0 ? _a : null); }],
4033
+ layoutSteps: layoutSteps,
2920
4034
  movedPortIds: movedPortIds,
2921
4035
  });
4036
+ if (gridLayoutChange) {
4037
+ this.events.emit('gridLayoutChanged', {
4038
+ parentId: gridLayoutChange.parentId,
4039
+ triggerChildId: gridLayoutChange.triggerChildId,
4040
+ reason: gridLayoutChange.reason,
4041
+ beforeRows: gridLayoutChange.beforeRows,
4042
+ afterRows: gridLayoutChange.afterRows,
4043
+ beforeGridTemplate: gridLayoutChange.beforeGridTemplate,
4044
+ afterGridTemplate: gridLayoutChange.afterGridTemplate,
4045
+ });
4046
+ }
2922
4047
  this.emitChange(allPatches);
2923
- var newSize = (_a = this.model.getElement(id)) === null || _a === void 0 ? void 0 : _a.size;
4048
+ var newSize = (_d = this.model.getElement(id)) === null || _d === void 0 ? void 0 : _d.size;
2924
4049
  if (oldSize && newSize && (oldSize.width !== newSize.width || oldSize.height !== newSize.height)) {
2925
4050
  this.events.emit('elementResized', { elementId: id, oldSize: __assign({}, oldSize), newSize: __assign({}, newSize) });
2926
4051
  }
@@ -3023,23 +4148,24 @@ var DiagramEngine = /** @class */ (function () {
3023
4148
  };
3024
4149
  DiagramEngine.prototype.addLink = function (link) {
3025
4150
  var _a;
3026
- var source = this.linkRoutingService.getPortLinkWorldPosition(link.sourcePortId, {
3027
- oppositePortId: link.targetPortId,
4151
+ var nextLink = this.applyOptionalLinkColor(link);
4152
+ var source = this.linkRoutingService.getPortLinkWorldPosition(nextLink.sourcePortId, {
4153
+ oppositePortId: nextLink.targetPortId,
3028
4154
  });
3029
- var target = this.linkRoutingService.getPortLinkWorldPosition(link.targetPortId, {
3030
- oppositePortId: link.sourcePortId,
4155
+ var target = this.linkRoutingService.getPortLinkWorldPosition(nextLink.targetPortId, {
4156
+ oppositePortId: nextLink.sourcePortId,
3031
4157
  });
3032
- var routing = (_a = link.routing) !== null && _a !== void 0 ? _a : 'auto';
3033
- var points = link.points;
4158
+ var routing = (_a = nextLink.routing) !== null && _a !== void 0 ? _a : 'auto';
4159
+ var points = nextLink.points;
3034
4160
  if (source && target) {
3035
4161
  if (routing === 'auto') {
3036
- points = this.computeAutoRoute(link, source, target);
4162
+ points = this.computeAutoRoute(nextLink, source, target);
3037
4163
  }
3038
4164
  else if (points.length < 2) {
3039
4165
  points = [__assign({}, source), __assign({}, target)];
3040
4166
  }
3041
4167
  }
3042
- var patches = this.commandQueue.run(createAddLinkCommand(__assign(__assign({}, link), { points: points, routing: routing })), this.model);
4168
+ var patches = this.commandQueue.run(createAddLinkCommand(__assign(__assign({}, nextLink), { points: points, routing: routing })), this.model);
3043
4169
  this.emitChange(patches);
3044
4170
  };
3045
4171
  DiagramEngine.prototype.updateLinkPoints = function (id, points) {
@@ -3224,6 +4350,7 @@ var DiagramEngine = /** @class */ (function () {
3224
4350
  return baseRotation + instanceRotation;
3225
4351
  };
3226
4352
  DiagramEngine.prototype.normalizeElementResize = function (id, proposal, handle, minSize) {
4353
+ var _a, _b;
3227
4354
  if (minSize === void 0) { minSize = 20; }
3228
4355
  var clamped = {
3229
4356
  x: proposal.x,
@@ -3234,20 +4361,39 @@ var DiagramEngine = /** @class */ (function () {
3234
4361
  var element = this.model.getElement(id);
3235
4362
  if (!element)
3236
4363
  return clamped;
4364
+ var lockHorizontalResize = this.shouldLockAutoLayoutChildHorizontalResize(element);
4365
+ var currentWorldPosition = this.model.getElementWorldPosition(id);
4366
+ var anchorGridWidthToLeft = this.shouldAnchorAutoLayoutGridChildWidthToLeft(element);
4367
+ var freezeGridLeftEdge = anchorGridWidthToLeft || lockHorizontalResize;
4368
+ var snappedGridWidth = this.resolveSnappedGridChildWidth(element, clamped.width);
3237
4369
  var shape = this.shapeRegistry.get(element.shapeId);
3238
- if (!(shape === null || shape === void 0 ? void 0 : shape.normalizeResize))
3239
- return clamped;
4370
+ if (!(shape === null || shape === void 0 ? void 0 : shape.normalizeResize)) {
4371
+ if (!lockHorizontalResize && !anchorGridWidthToLeft)
4372
+ return clamped;
4373
+ var width_1 = lockHorizontalResize
4374
+ ? Math.max(minSize, element.size.width)
4375
+ : Math.max(minSize, snappedGridWidth);
4376
+ var x_1 = freezeGridLeftEdge ? ((_a = currentWorldPosition === null || currentWorldPosition === void 0 ? void 0 : currentWorldPosition.x) !== null && _a !== void 0 ? _a : clamped.x) : clamped.x;
4377
+ if (!freezeGridLeftEdge && (handle === 'sw' || handle === 'nw')) {
4378
+ x_1 += clamped.width - width_1;
4379
+ }
4380
+ return { x: x_1, y: clamped.y, width: width_1, height: clamped.height };
4381
+ }
3240
4382
  var normalized = shape.normalizeResize({
3241
4383
  element: element.toData(),
3242
4384
  handle: handle,
3243
4385
  minSize: minSize,
3244
4386
  proposal: { width: clamped.width, height: clamped.height },
3245
4387
  });
3246
- var width = Math.max(minSize, normalized.width);
4388
+ var width = lockHorizontalResize
4389
+ ? Math.max(minSize, element.size.width)
4390
+ : anchorGridWidthToLeft
4391
+ ? Math.max(minSize, snappedGridWidth)
4392
+ : Math.max(minSize, normalized.width);
3247
4393
  var height = Math.max(minSize, normalized.height);
3248
- var x = clamped.x;
4394
+ var x = freezeGridLeftEdge ? ((_b = currentWorldPosition === null || currentWorldPosition === void 0 ? void 0 : currentWorldPosition.x) !== null && _b !== void 0 ? _b : clamped.x) : clamped.x;
3249
4395
  var y = clamped.y;
3250
- if (handle === 'sw' || handle === 'nw') {
4396
+ if (!freezeGridLeftEdge && (handle === 'sw' || handle === 'nw')) {
3251
4397
  x += clamped.width - width;
3252
4398
  }
3253
4399
  if (handle === 'ne' || handle === 'nw') {
@@ -3255,6 +4401,75 @@ var DiagramEngine = /** @class */ (function () {
3255
4401
  }
3256
4402
  return { x: x, y: y, width: width, height: height };
3257
4403
  };
4404
+ DiagramEngine.prototype.shouldLockAutoLayoutChildHorizontalResize = function (element) {
4405
+ var _a, _b;
4406
+ var parentId = (_a = element.parentId) !== null && _a !== void 0 ? _a : null;
4407
+ if (!parentId)
4408
+ return false;
4409
+ if (this.model.getChildren(element.id).length > 0)
4410
+ return false;
4411
+ if (element.layout && element.layout.mode !== 'manual')
4412
+ return false;
4413
+ var parent = this.model.getElement(parentId);
4414
+ if (((_b = parent === null || parent === void 0 ? void 0 : parent.layout) === null || _b === void 0 ? void 0 : _b.mode) !== 'grid')
4415
+ return false;
4416
+ return !Boolean(parent.layout.gridChildWidthResizeEnabled);
4417
+ };
4418
+ DiagramEngine.prototype.shouldAnchorAutoLayoutGridChildWidthToLeft = function (element) {
4419
+ var _a, _b;
4420
+ var parentId = (_a = element.parentId) !== null && _a !== void 0 ? _a : null;
4421
+ if (!parentId)
4422
+ return false;
4423
+ if (this.model.getChildren(element.id).length > 0)
4424
+ return false;
4425
+ if (element.layout && element.layout.mode !== 'manual')
4426
+ return false;
4427
+ var parent = this.model.getElement(parentId);
4428
+ return Boolean(((_b = parent === null || parent === void 0 ? void 0 : parent.layout) === null || _b === void 0 ? void 0 : _b.mode) === 'grid' && parent.layout.gridChildWidthResizeEnabled);
4429
+ };
4430
+ DiagramEngine.prototype.shouldRestrictAutoLayoutChildRightGrowth = function (element, handle, requestedWidth) {
4431
+ return false;
4432
+ };
4433
+ DiagramEngine.prototype.resolveSnappedGridChildWidth = function (element, requestedWidth) {
4434
+ var _a;
4435
+ var parentId = (_a = element.parentId) !== null && _a !== void 0 ? _a : null;
4436
+ if (!parentId)
4437
+ return requestedWidth;
4438
+ if (this.model.getChildren(element.id).length > 0)
4439
+ return requestedWidth;
4440
+ if (element.layout && element.layout.mode !== 'manual')
4441
+ return requestedWidth;
4442
+ var parent = this.model.getElement(parentId);
4443
+ if (!(parent === null || parent === void 0 ? void 0 : parent.layout) || parent.layout.mode !== 'grid' || !parent.layout.gridChildWidthResizeEnabled)
4444
+ return requestedWidth;
4445
+ return this.autoLayoutService.snapGridChildRequestedWidth(parentId, element.id, requestedWidth);
4446
+ };
4447
+ DiagramEngine.prototype.resolveGridChildWidthResizeTopologyChange = function (element, requestedWidth) {
4448
+ var _a, _b, _c;
4449
+ var parentId = (_a = element.parentId) !== null && _a !== void 0 ? _a : null;
4450
+ if (!parentId)
4451
+ return null;
4452
+ if (this.model.getChildren(element.id).length > 0)
4453
+ return null;
4454
+ if (element.layout && element.layout.mode !== 'manual')
4455
+ return null;
4456
+ var parent = this.model.getElement(parentId);
4457
+ if (!parent || ((_b = parent.layout) === null || _b === void 0 ? void 0 : _b.mode) !== 'grid' || !parent.layout.gridChildWidthResizeEnabled)
4458
+ return null;
4459
+ var topologyChange = this.autoLayoutService.resolveGridChildResizeTopologyChange(parentId, element.id, requestedWidth);
4460
+ if (!topologyChange)
4461
+ return null;
4462
+ return {
4463
+ parentId: topologyChange.parentId,
4464
+ triggerChildId: topologyChange.triggerChildId,
4465
+ reason: topologyChange.reason,
4466
+ beforeRows: topologyChange.beforeRows,
4467
+ afterRows: topologyChange.afterRows,
4468
+ beforeGridTemplate: parent.layout.gridTemplate ? __spreadArray([], parent.layout.gridTemplate, true) : undefined,
4469
+ afterGridTemplate: __spreadArray([], ((_c = topologyChange.nextLayout.gridTemplate) !== null && _c !== void 0 ? _c : []), true),
4470
+ afterLayout: topologyChange.nextLayout,
4471
+ };
4472
+ };
3258
4473
  DiagramEngine.prototype.getPortWorldPosition = function (id) {
3259
4474
  return this.model.getPortWorldPosition(id);
3260
4475
  };
@@ -3337,6 +4552,10 @@ var DiagramEngine = /** @class */ (function () {
3337
4552
  this.events.emit('config', { type: 'rendering' });
3338
4553
  };
3339
4554
  DiagramEngine.prototype.render = function () {
4555
+ var redrawRoutingPatches = this.refreshLinksForRenderCycle();
4556
+ if (redrawRoutingPatches.length > 0) {
4557
+ this.emitChange(redrawRoutingPatches, { render: false });
4558
+ }
3340
4559
  this.renderer.render(this.model);
3341
4560
  };
3342
4561
  DiagramEngine.prototype.emitElementDrop = function (event) {
@@ -3532,8 +4751,8 @@ var DiagramEngine = /** @class */ (function () {
3532
4751
  }
3533
4752
  if (style === null || style === void 0 ? void 0 : style.moveBounds) {
3534
4753
  var bounds = style.moveBounds;
3535
- position.x = clamp(position.x, bounds.x, bounds.x + bounds.width);
3536
- position.y = clamp(position.y, bounds.y, bounds.y + bounds.height);
4754
+ position.x = clamp$2(position.x, bounds.x, bounds.x + bounds.width);
4755
+ position.y = clamp$2(position.y, bounds.y, bounds.y + bounds.height);
3537
4756
  }
3538
4757
  if (effectiveMoveMode === 'border') {
3539
4758
  var resolvedBorder = this.resolveBorderPositionWithLimits(position, element, (_e = element.portMovement) === null || _e === void 0 ? void 0 : _e.positionLimits);
@@ -3825,8 +5044,8 @@ var DiagramEngine = /** @class */ (function () {
3825
5044
  });
3826
5045
  this.renderer.renderSelection(selectedIds);
3827
5046
  };
3828
- DiagramEngine.prototype.applyLayoutForParent = function (parentId) {
3829
- return this.autoLayoutService.applyLayoutForParent(parentId);
5047
+ DiagramEngine.prototype.applyLayoutForParent = function (parentId, options) {
5048
+ return this.autoLayoutService.applyLayoutForParent(parentId, options);
3830
5049
  };
3831
5050
  DiagramEngine.prototype.applyLayoutCascade = function (startParentId) {
3832
5051
  return this.autoLayoutService.applyLayoutCascade(startParentId);
@@ -3892,6 +5111,30 @@ var DiagramEngine = /** @class */ (function () {
3892
5111
  DiagramEngine.prototype.routeLinksWithEmptyPoints = function () {
3893
5112
  return this.linkRoutingService.routeLinksWithEmptyPoints();
3894
5113
  };
5114
+ DiagramEngine.prototype.applyOptionalLinkColor = function (link) {
5115
+ if (!this.linkColorPoolPolicy.enabled)
5116
+ return link;
5117
+ var existingStyle = link.style;
5118
+ var hasExplicitStroke = existingStyle !== undefined &&
5119
+ Object.prototype.hasOwnProperty.call(existingStyle, 'stroke') &&
5120
+ existingStyle.stroke !== undefined &&
5121
+ existingStyle.stroke !== null &&
5122
+ "".concat(existingStyle.stroke).trim().length > 0;
5123
+ if (hasExplicitStroke)
5124
+ return link;
5125
+ var colors = this.linkColorPoolPolicy.colors;
5126
+ if (colors.length === 0)
5127
+ return link;
5128
+ var index = Math.max(0, Math.min(colors.length - 1, Math.floor(Math.random() * colors.length)));
5129
+ return __assign(__assign({}, link), { style: __assign(__assign({}, (existingStyle !== null && existingStyle !== void 0 ? existingStyle : {})), { stroke: colors[index] }) });
5130
+ };
5131
+ DiagramEngine.prototype.refreshLinksForRenderCycle = function () {
5132
+ if (this.linkRouteRefreshPolicy.mode !== 'redraw-two-endpoint-change')
5133
+ return [];
5134
+ return this.linkRoutingService.refreshLinksForRedraw({
5135
+ includeManual: this.linkRouteRefreshPolicy.includeManual,
5136
+ });
5137
+ };
3895
5138
  DiagramEngine.prototype.normalizePortsForHostPolicies = function (portIds) {
3896
5139
  var _this = this;
3897
5140
  var ids = portIds !== null && portIds !== void 0 ? portIds : Array.from(this.model.ports.keys());
@@ -5151,6 +6394,7 @@ var KonvaInteraction = /** @class */ (function () {
5151
6394
  this.dragThreshold = 4;
5152
6395
  this.panSpeed = 0.5;
5153
6396
  this.occupiedVertexTolerance = 2;
6397
+ this.nestedHoverElementPadding = 12;
5154
6398
  this.emittingElementLinkEnded = false;
5155
6399
  this.engine = engine;
5156
6400
  this.stage = config.stage;
@@ -5429,6 +6673,10 @@ var KonvaInteraction = /** @class */ (function () {
5429
6673
  return;
5430
6674
  }
5431
6675
  if (hit.type === 'text') {
6676
+ if (!_this.isTextMovable(hit.id)) {
6677
+ _this.setCursor('default');
6678
+ return;
6679
+ }
5432
6680
  var base = _this.engine.getTextWorldPosition(hit.id);
5433
6681
  if (base) {
5434
6682
  _this.dragState = {
@@ -5818,6 +7066,8 @@ var KonvaInteraction = /** @class */ (function () {
5818
7066
  var hit = _this.resolveHit(point);
5819
7067
  if (!hit || hit.type !== 'text')
5820
7068
  return;
7069
+ if (!_this.isTextEditable(hit.id))
7070
+ return;
5821
7071
  _this.startTextEdit(hit.id);
5822
7072
  };
5823
7073
  this.stage.on('dblclick dbltap', doubleClick);
@@ -6370,7 +7620,13 @@ var KonvaInteraction = /** @class */ (function () {
6370
7620
  this.clearActiveShapeHoverControl();
6371
7621
  return;
6372
7622
  }
6373
- var resolved = this.resolveShapeHoverControl(hit.id, point);
7623
+ var hoverElementIds = this.resolveNestedHoverElementCandidates(point, hit.id);
7624
+ var resolved = null;
7625
+ for (var i = 0; i < hoverElementIds.length; i += 1) {
7626
+ resolved = this.resolveShapeHoverControl(hoverElementIds[i], point);
7627
+ if (resolved)
7628
+ break;
7629
+ }
6374
7630
  if (!resolved) {
6375
7631
  this.clearActiveShapeHoverControl();
6376
7632
  return;
@@ -6386,6 +7642,70 @@ var KonvaInteraction = /** @class */ (function () {
6386
7642
  this.activeShapeHoverControl = resolved;
6387
7643
  (_b = (_a = this.renderer) === null || _a === void 0 ? void 0 : _a.renderShapeHoverControl) === null || _b === void 0 ? void 0 : _b.call(_a, this.toShapeHoverRenderConfig(resolved));
6388
7644
  };
7645
+ KonvaInteraction.prototype.resolveNestedHoverElementCandidates = function (point, rootElementId) {
7646
+ var _this = this;
7647
+ var _a;
7648
+ var state = this.engine.getState();
7649
+ var root = state.elements.find(function (element) { return element.id === rootElementId; });
7650
+ if (!root)
7651
+ return [rootElementId];
7652
+ var byId = new Map(state.elements.map(function (element) { var _a; return [element.id, { parentId: (_a = element.parentId) !== null && _a !== void 0 ? _a : null }]; }));
7653
+ var activeElementId = (_a = this.activeShapeHoverControl) === null || _a === void 0 ? void 0 : _a.elementId;
7654
+ var entries = state.elements
7655
+ .map(function (element, order) { return ({ element: element, order: order }); })
7656
+ .filter(function (_a) {
7657
+ var element = _a.element;
7658
+ return _this.isDescendantOrSelf(element.id, rootElementId, byId);
7659
+ })
7660
+ .filter(function (_a) {
7661
+ var element = _a.element;
7662
+ return _this.isPointWithinElementHoverBounds(point, element, _this.nestedHoverElementPadding);
7663
+ })
7664
+ .map(function (_a) {
7665
+ var element = _a.element, order = _a.order;
7666
+ return ({
7667
+ id: element.id,
7668
+ depth: _this.computeElementDepth(element.id, byId),
7669
+ order: order,
7670
+ active: activeElementId === element.id,
7671
+ });
7672
+ });
7673
+ entries.sort(function (a, b) {
7674
+ if (a.active !== b.active)
7675
+ return a.active ? -1 : 1;
7676
+ if (a.depth !== b.depth)
7677
+ return b.depth - a.depth;
7678
+ return b.order - a.order;
7679
+ });
7680
+ var ordered = entries.map(function (entry) { return entry.id; });
7681
+ if (!ordered.includes(rootElementId)) {
7682
+ ordered.push(rootElementId);
7683
+ }
7684
+ return ordered;
7685
+ };
7686
+ KonvaInteraction.prototype.isDescendantOrSelf = function (candidateId, ancestorId, byId) {
7687
+ if (candidateId === ancestorId)
7688
+ return true;
7689
+ var current = byId.get(candidateId);
7690
+ while (current === null || current === void 0 ? void 0 : current.parentId) {
7691
+ if (current.parentId === ancestorId)
7692
+ return true;
7693
+ current = byId.get(current.parentId);
7694
+ }
7695
+ return false;
7696
+ };
7697
+ KonvaInteraction.prototype.isPointWithinElementHoverBounds = function (point, element, padding) {
7698
+ var _a, _b;
7699
+ var world = (_a = this.engine.getElementWorldPosition(element.id)) !== null && _a !== void 0 ? _a : element.position;
7700
+ var rect = {
7701
+ x: world.x - padding,
7702
+ y: world.y - padding,
7703
+ width: Math.max(0, element.size.width + padding * 2),
7704
+ height: Math.max(0, element.size.height + padding * 2),
7705
+ };
7706
+ var rotation = this.engine.getElementRotation(element.id);
7707
+ return pointInRotatedRect(point, { x: rect.x, y: rect.y }, { width: rect.width, height: rect.height }, rotation, (_b = element.anchorCenter) !== null && _b !== void 0 ? _b : false);
7708
+ };
6389
7709
  KonvaInteraction.prototype.resolveShapeHoverControl = function (elementId, point) {
6390
7710
  var _a, _b, _c, _d, _e, _f, _g;
6391
7711
  var controls = (_a = this.shapeHoverControls) === null || _a === void 0 ? void 0 : _a.controls;
@@ -6900,8 +8220,12 @@ var KonvaInteraction = /** @class */ (function () {
6900
8220
  y: normalized.y + normalized.height / 2,
6901
8221
  }
6902
8222
  : { x: normalized.x, y: normalized.y };
6903
- this.engine.moveElementTo(state.elementId, moveTarget.x, moveTarget.y);
6904
- this.engine.resizeElement(state.elementId, normalized.width, normalized.height);
8223
+ this.engine.resizeElementBounds(state.elementId, {
8224
+ x: moveTarget.x,
8225
+ y: moveTarget.y,
8226
+ width: normalized.width,
8227
+ height: normalized.height,
8228
+ });
6905
8229
  this.updateSelectionOverlays();
6906
8230
  };
6907
8231
  KonvaInteraction.prototype.parseResizeHandle = function (id) {
@@ -7237,6 +8561,14 @@ var KonvaInteraction = /** @class */ (function () {
7237
8561
  KonvaInteraction.prototype.getTextById = function (id) {
7238
8562
  return this.engine.getState().texts.find(function (text) { return text.id === id; });
7239
8563
  };
8564
+ KonvaInteraction.prototype.isTextMovable = function (id) {
8565
+ var _a, _b;
8566
+ return ((_b = (_a = this.getTextById(id)) === null || _a === void 0 ? void 0 : _a.interaction) === null || _b === void 0 ? void 0 : _b.movable) !== false;
8567
+ };
8568
+ KonvaInteraction.prototype.isTextEditable = function (id) {
8569
+ var _a, _b;
8570
+ return ((_b = (_a = this.getTextById(id)) === null || _a === void 0 ? void 0 : _a.interaction) === null || _b === void 0 ? void 0 : _b.editable) !== false;
8571
+ };
7240
8572
  KonvaInteraction.prototype.getLinkById = function (id) {
7241
8573
  return this.engine.getState().links.find(function (link) { return link.id === id; });
7242
8574
  };
@@ -7919,6 +9251,24 @@ var hasBounds = function (bounds) {
7919
9251
  bounds.maxX >= bounds.minX &&
7920
9252
  bounds.maxY >= bounds.minY;
7921
9253
  };
9254
+ var DEFAULT_VIEWPORT_FIT_PADDING = 24;
9255
+ var DEFAULT_VIEWPORT_FIT_MIN_ZOOM = 0.2;
9256
+ var DEFAULT_VIEWPORT_FIT_MAX_ZOOM = 3;
9257
+ var resolveViewportFitOptions = function (options) {
9258
+ var padding = typeof (options === null || options === void 0 ? void 0 : options.padding) === 'number' && Number.isFinite(options.padding)
9259
+ ? Math.max(0, options.padding)
9260
+ : DEFAULT_VIEWPORT_FIT_PADDING;
9261
+ var requestedMinZoom = typeof (options === null || options === void 0 ? void 0 : options.minZoom) === 'number' && Number.isFinite(options.minZoom)
9262
+ ? Math.max(0.000001, options.minZoom)
9263
+ : DEFAULT_VIEWPORT_FIT_MIN_ZOOM;
9264
+ var requestedMaxZoom = typeof (options === null || options === void 0 ? void 0 : options.maxZoom) === 'number' && Number.isFinite(options.maxZoom)
9265
+ ? Math.max(0.000001, options.maxZoom)
9266
+ : DEFAULT_VIEWPORT_FIT_MAX_ZOOM;
9267
+ var minZoom = Math.min(requestedMinZoom, requestedMaxZoom);
9268
+ var maxZoom = Math.max(requestedMinZoom, requestedMaxZoom);
9269
+ return { padding: padding, minZoom: minZoom, maxZoom: maxZoom };
9270
+ };
9271
+ var clamp = function (value, min, max) { return Math.max(min, Math.min(max, value)); };
7922
9272
  var resolveStateWorldBounds = function (state) {
7923
9273
  var bounds = createBounds();
7924
9274
  state.elements.forEach(function (element) {
@@ -7955,6 +9305,34 @@ var resolveStateWorldBounds = function (state) {
7955
9305
  });
7956
9306
  return hasBounds(bounds) ? bounds : null;
7957
9307
  };
9308
+ var resolveElementWorldBounds = function (state) {
9309
+ var bounds = createBounds();
9310
+ state.elements.forEach(function (element) {
9311
+ includeRect(bounds, element.position.x, element.position.y, element.size.width, element.size.height);
9312
+ });
9313
+ return hasBounds(bounds) ? bounds : null;
9314
+ };
9315
+ var resolveViewportFitTransform = function (state, viewportSize, options) {
9316
+ var bounds = resolveElementWorldBounds(state);
9317
+ if (!bounds)
9318
+ return null;
9319
+ var safeWidth = Math.max(1, viewportSize.width);
9320
+ var safeHeight = Math.max(1, viewportSize.height);
9321
+ var _a = resolveViewportFitOptions(options), padding = _a.padding, minZoom = _a.minZoom, maxZoom = _a.maxZoom;
9322
+ var availableWidth = Math.max(1, safeWidth - padding * 2);
9323
+ var availableHeight = Math.max(1, safeHeight - padding * 2);
9324
+ var contentWidth = Math.max(1, bounds.maxX - bounds.minX);
9325
+ var contentHeight = Math.max(1, bounds.maxY - bounds.minY);
9326
+ var rawZoom = Math.min(availableWidth / contentWidth, availableHeight / contentHeight);
9327
+ var zoom = clamp(rawZoom, minZoom, maxZoom);
9328
+ var centerX = (bounds.minX + bounds.maxX) / 2;
9329
+ var centerY = (bounds.minY + bounds.maxY) / 2;
9330
+ var pan = {
9331
+ x: safeWidth / 2 - centerX * zoom,
9332
+ y: safeHeight / 2 - centerY * zoom,
9333
+ };
9334
+ return { pan: pan, zoom: zoom };
9335
+ };
7958
9336
  var resolveFitToContentPadding = function (fitToContent) {
7959
9337
  if (typeof fitToContent === 'object' && typeof fitToContent.padding === 'number') {
7960
9338
  return Math.max(0, fitToContent.padding);
@@ -8030,10 +9408,12 @@ var registerSimpleShapes = function (registry, shapes, isPort) {
8030
9408
  var createDiagramEditor = function (config) {
8031
9409
  var _a, _b;
8032
9410
  var Konva = getKonva();
9411
+ var stageWidth = (_a = config.width) !== null && _a !== void 0 ? _a : 900;
9412
+ var stageHeight = (_b = config.height) !== null && _b !== void 0 ? _b : 560;
8033
9413
  var stage = new Konva.Stage({
8034
9414
  container: config.container,
8035
- width: (_a = config.width) !== null && _a !== void 0 ? _a : 900,
8036
- height: (_b = config.height) !== null && _b !== void 0 ? _b : 560,
9415
+ width: stageWidth,
9416
+ height: stageHeight,
8037
9417
  });
8038
9418
  var stageContainer = typeof stage.container === 'function' ? stage.container() : stage.container;
8039
9419
  if (stageContainer && stageContainer.tabIndex < 0) {
@@ -8043,7 +9423,12 @@ var createDiagramEditor = function (config) {
8043
9423
  registerSimpleShapes(shapeRegistry, config.elementShapes, false);
8044
9424
  registerSimpleShapes(shapeRegistry, config.portShapes, true);
8045
9425
  var renderer = new KonvaRenderer({ stage: stage, konva: Konva, shapeRegistry: shapeRegistry });
8046
- var engine = new DiagramEngine({ renderer: renderer, shapeRegistry: shapeRegistry });
9426
+ var engine = new DiagramEngine({
9427
+ renderer: renderer,
9428
+ shapeRegistry: shapeRegistry,
9429
+ linkRouteRefreshPolicy: config.linkRouteRefreshPolicy,
9430
+ linkColorPoolPolicy: config.linkColorPoolPolicy,
9431
+ });
8047
9432
  if (config.onChange) {
8048
9433
  engine.on('change', config.onChange);
8049
9434
  }
@@ -8175,6 +9560,12 @@ var createDiagramEditor = function (config) {
8175
9560
  completeLinkToPort: function (targetPortId) { return interaction.completeLinkToPort(targetPortId); },
8176
9561
  completeLinkToElement: function (targetElementId, pointer) { return interaction.completeLinkToElement(targetElementId, pointer); },
8177
9562
  cancelLink: function () { return interaction.cancelLink(); },
9563
+ zoomToFitElements: function (options) {
9564
+ var transform = resolveViewportFitTransform(engine.getState(), { width: stageWidth, height: stageHeight }, options);
9565
+ if (!transform)
9566
+ return;
9567
+ engine.setViewport(transform.pan, transform.zoom);
9568
+ },
8178
9569
  exportImage: function (options) {
8179
9570
  engine.render();
8180
9571
  if (typeof stage.toDataURL !== 'function') {
@@ -8201,6 +9592,8 @@ var createDiagramEditor = function (config) {
8201
9592
  return stage.toDataURL(__assign(__assign({}, baseOptions), { x: cropX, y: cropY, width: cropWidth, height: cropHeight }));
8202
9593
  },
8203
9594
  resize: function (width, height) {
9595
+ stageWidth = width;
9596
+ stageHeight = height;
8204
9597
  stage.width(width);
8205
9598
  stage.height(height);
8206
9599
  engine.render();