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