@affino/diagram-core 0.6.0 → 0.8.1

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.
@@ -1,4 +1,4 @@
1
- import { createEntityGeometry, distance, rectContainsPoint, rectIntersects } from "./geometry.js";
1
+ import { createEntityGeometry, distance, inflateRect, rectContainsPoint, rectIntersects } from "./geometry.js";
2
2
  import { DiagramClipboardService } from "./internal/DiagramClipboardService.js";
3
3
  import { DiagramGeometryService } from "./internal/DiagramGeometryService.js";
4
4
  import { DiagramHistory } from "./internal/DiagramHistory.js";
@@ -104,6 +104,12 @@ export class DiagramEngine {
104
104
  writable: true,
105
105
  value: false
106
106
  });
107
+ Object.defineProperty(this, "dependencyIndexRebuildCount", {
108
+ enumerable: true,
109
+ configurable: true,
110
+ writable: true,
111
+ value: 0
112
+ });
107
113
  Object.defineProperty(this, "dependencyEntityIds", {
108
114
  enumerable: true,
109
115
  configurable: true,
@@ -128,6 +134,18 @@ export class DiagramEngine {
128
134
  writable: true,
129
135
  value: new Map()
130
136
  });
137
+ Object.defineProperty(this, "dependencyEdgeEndpoints", {
138
+ enumerable: true,
139
+ configurable: true,
140
+ writable: true,
141
+ value: new Map()
142
+ });
143
+ Object.defineProperty(this, "dependencyPortOwners", {
144
+ enumerable: true,
145
+ configurable: true,
146
+ writable: true,
147
+ value: new Map()
148
+ });
131
149
  this.history = new DiagramHistory(options.history);
132
150
  this.store = new DiagramSceneStore(initialScene);
133
151
  this.state = this.store.state;
@@ -143,6 +161,9 @@ export class DiagramEngine {
143
161
  var _a;
144
162
  return (_a = this.state.versions.get(id)) !== null && _a !== void 0 ? _a : 0;
145
163
  }
164
+ getDocumentRevision() {
165
+ return this.state.documentRevision;
166
+ }
146
167
  getGeometryReadCount() {
147
168
  return this.geometryService.getReadCount();
148
169
  }
@@ -173,6 +194,51 @@ export class DiagramEngine {
173
194
  this.lastCommandMs = now() - startedAt;
174
195
  return result;
175
196
  }
197
+ dispatchBatch(commands, options = {}) {
198
+ const failure = (reason, index, ids = []) => ({
199
+ ok: false, changed: false, revision: this.state.revision, documentRevision: this.state.documentRevision,
200
+ failedCommandIndex: index, reason, affectedIds: [...new Set(ids)],
201
+ });
202
+ if (options.expectedRevision !== undefined && options.expectedRevision !== this.state.documentRevision) {
203
+ return failure("revision-mismatch", null);
204
+ }
205
+ const draft = new DiagramEngine(serializeScene(this.store.getSnapshot()));
206
+ draft.state.revision = this.state.revision;
207
+ draft.state.documentRevision = this.state.documentRevision;
208
+ draft.state.orderRevision = this.state.orderRevision;
209
+ const patches = [];
210
+ const affected = new Set();
211
+ for (let index = 0; index < commands.length; index += 1) {
212
+ const command = commands[index];
213
+ if (command.type === "undo" || command.type === "redo")
214
+ return failure("unsupported-command", index);
215
+ const patch = draft.createPatch(command);
216
+ if (!patch) {
217
+ if (isBatchNoOp(draft.state, command))
218
+ continue;
219
+ const ids = commandIds(command);
220
+ const missing = ids.filter((id) => !draft.hasEntity(id));
221
+ return failure("invalid-command", index, missing.length ? missing : ids);
222
+ }
223
+ const changed = draft.commitPatch(patch, false, null).changedIds;
224
+ if (changed.size) {
225
+ patches.push(patch);
226
+ for (const id of changed)
227
+ affected.add(id);
228
+ }
229
+ }
230
+ if (!patches.length)
231
+ return { ok: true, changed: false, revision: this.state.revision, documentRevision: this.state.documentRevision, failedCommandIndex: null, reason: null, affectedIds: [] };
232
+ let combined = patches[0];
233
+ for (let index = 1; index < patches.length; index += 1)
234
+ combined = composePatches(combined, patches[index]);
235
+ let inverse = patches[patches.length - 1].inverse;
236
+ for (let index = patches.length - 2; index >= 0; index -= 1)
237
+ inverse = composePatches(inverse, patches[index].inverse);
238
+ combined.inverse = inverse;
239
+ const changed = this.commitPatch(combined, true, null).changedIds;
240
+ return { ok: true, changed: changed.size > 0, revision: this.state.revision, documentRevision: this.state.documentRevision, failedCommandIndex: null, reason: null, affectedIds: [...affected] };
241
+ }
176
242
  transact(mutator) {
177
243
  const next = mutator(this.store.getSnapshot());
178
244
  const patch = createReplaceScenePatch(next, serializeScene(this.store.getSnapshot()));
@@ -311,14 +377,14 @@ export class DiagramEngine {
311
377
  if (custom) {
312
378
  return { point: custom, snapped: true, source: "custom" };
313
379
  }
314
- const port = this.nearestPort(point, (_b = context.radius) !== null && _b !== void 0 ? _b : 12, (_c = context.excludeIds) !== null && _c !== void 0 ? _c : new Set());
380
+ const port = context.snapToPorts === false ? null : this.nearestPort(point, (_b = context.radius) !== null && _b !== void 0 ? _b : 12, (_c = context.excludeIds) !== null && _c !== void 0 ? _c : new Set());
315
381
  if (port) {
316
382
  const geometry = this.getGeometry(port.id);
317
383
  if (geometry === null || geometry === void 0 ? void 0 : geometry.point) {
318
384
  return { point: geometry.point, snapped: true, source: "port" };
319
385
  }
320
386
  }
321
- const aligned = this.snapToAlignment(point, (_d = context.radius) !== null && _d !== void 0 ? _d : 6, context.excludeIds);
387
+ const aligned = context.snapToAlignment === false ? null : this.snapToAlignment(point, (_d = context.radius) !== null && _d !== void 0 ? _d : 6, context.excludeIds);
322
388
  if (aligned) {
323
389
  return { point: aligned, snapped: true, source: "alignment" };
324
390
  }
@@ -338,15 +404,67 @@ export class DiagramEngine {
338
404
  return { point, snapped: false, source: null };
339
405
  }
340
406
  snapTranslation(selection, delta, context = {}) {
341
- var _a;
407
+ var _a, _b, _c;
342
408
  const primaryId = (_a = selection.primaryId) !== null && _a !== void 0 ? _a : selection.ids[0];
343
409
  const geometry = primaryId ? this.getGeometry(primaryId) : null;
344
410
  const origin = geometry ? { x: geometry.bounds.x, y: geometry.bounds.y } : { x: 0, y: 0 };
345
- const snapped = this.snapPoint({ x: origin.x + delta.x, y: origin.y + delta.y }, context);
411
+ const radius = (_b = context.radius) !== null && _b !== void 0 ? _b : 6;
412
+ const excludeIds = new Set([...((_c = context.excludeIds) !== null && _c !== void 0 ? _c : []), ...selection.ids]);
413
+ const proposed = { x: origin.x + delta.x, y: origin.y + delta.y };
414
+ const guides = [];
415
+ let point = proposed;
416
+ let source = null;
417
+ let prioritySnap = false;
418
+ const portSnap = context.snapToPorts === false && !context.custom
419
+ ? { point, snapped: false, source: null }
420
+ : this.snapPoint(point, { ...context, gridSize: undefined, radius, excludeIds, snapToAlignment: false });
421
+ if (portSnap.source === "port" || portSnap.source === "custom") {
422
+ point = portSnap.point;
423
+ source = portSnap.source;
424
+ prioritySnap = true;
425
+ }
426
+ if (!prioritySnap && context.snapToAlignment !== false && geometry) {
427
+ const aligned = this.findTranslationAlignment(geometry.bounds, point, radius, excludeIds);
428
+ if (aligned) {
429
+ point = { x: point.x + aligned.dx, y: point.y + aligned.dy };
430
+ guides.push(...aligned.guides);
431
+ source !== null && source !== void 0 ? source : (source = "alignment");
432
+ }
433
+ }
434
+ if (!prioritySnap && context.snapToEqualSpacing && geometry) {
435
+ const alignedAxes = new Set(guides.filter((guide) => guide.kind === "alignment").map((guide) => guide.axis));
436
+ const spaced = this.findEqualSpacing(geometry.bounds, point, radius, excludeIds, alignedAxes);
437
+ if (spaced) {
438
+ point = { x: point.x + spaced.dx, y: point.y + spaced.dy };
439
+ guides.push(...spaced.guides);
440
+ source !== null && source !== void 0 ? source : (source = "equal-spacing");
441
+ }
442
+ }
443
+ if (!prioritySnap && context.gridSize && context.gridSize > 0) {
444
+ const snappedAxes = new Set(guides.map((guide) => guide.axis));
445
+ let gridChanged = false;
446
+ if (!snappedAxes.has("x")) {
447
+ const x = Math.round(point.x / context.gridSize) * context.gridSize;
448
+ gridChanged || (gridChanged = x !== point.x);
449
+ point = { ...point, x };
450
+ }
451
+ if (!snappedAxes.has("y")) {
452
+ const y = Math.round(point.y / context.gridSize) * context.gridSize;
453
+ gridChanged || (gridChanged = y !== point.y);
454
+ point = { ...point, y };
455
+ }
456
+ if (gridChanged)
457
+ source !== null && source !== void 0 ? source : (source = "grid");
458
+ }
346
459
  return {
347
- point: { x: snapped.point.x - origin.x, y: snapped.point.y - origin.y },
348
- snapped: snapped.snapped,
349
- source: snapped.source,
460
+ point: { x: point.x - origin.x, y: point.y - origin.y },
461
+ snapped: source !== null,
462
+ source,
463
+ guides: Object.freeze(guides.map((guide) => Object.freeze({
464
+ ...guide,
465
+ start: Object.freeze({ ...guide.start }),
466
+ end: Object.freeze({ ...guide.end }),
467
+ }))),
350
468
  };
351
469
  }
352
470
  canUndo() {
@@ -359,7 +477,7 @@ export class DiagramEngine {
359
477
  return ids.some((id) => this.hasEntity(id) && !this.isEntityNonDeletable(id) && !this.isEntityLockedOrReadOnly(id));
360
478
  }
361
479
  canMove(ids = this.state.selection.ids) {
362
- return ids.some((id) => this.hasEntity(id) && !this.isEntityLockedOrReadOnly(id));
480
+ return ids.some((id) => this.isEntityTranslatable(id) && !this.isEntityLockedOrReadOnly(id));
363
481
  }
364
482
  canResize(ids = this.state.selection.ids) {
365
483
  return ids.some((id) => !this.isEntityLockedOrReadOnly(id) && (this.state.entities.nodesById.has(id) || this.state.entities.shapesById.has(id) || this.state.entities.textsById.has(id)));
@@ -383,6 +501,9 @@ export class DiagramEngine {
383
501
  entityQueryCount: this.entityQueryCount,
384
502
  hitTestCount: this.hitTestCount,
385
503
  geometryRecomputeCount: this.geometryService.getReadCount(),
504
+ spatialIndexRebuildCount: this.spatialIndex.getRebuildCount(),
505
+ spatialIndexUpdateCount: this.spatialIndex.getUpdateCount(),
506
+ dependencyIndexRebuildCount: this.dependencyIndexRebuildCount,
386
507
  lastCommandMs: this.lastCommandMs,
387
508
  undoDepth: this.history.undoDepth(),
388
509
  redoDepth: this.history.redoDepth(),
@@ -421,6 +542,15 @@ export class DiagramEngine {
421
542
  serialize() {
422
543
  return serializeScene(this.store.getSnapshot());
423
544
  }
545
+ serializeDocument(options = {}) {
546
+ const scene = this.serialize();
547
+ return {
548
+ format: "affino-diagram",
549
+ version: 1,
550
+ content: { nodes: scene.nodes, edges: scene.edges, texts: scene.texts, shapes: scene.shapes, ports: scene.ports },
551
+ ...(options.includeView === false ? {} : { view: { viewport: scene.viewport, selection: scene.selection } }),
552
+ };
553
+ }
424
554
  undo() {
425
555
  const entry = this.history.popUndo();
426
556
  if (!entry) {
@@ -451,6 +581,10 @@ export class DiagramEngine {
451
581
  this.state.versions.set(id, ((_a = this.state.versions.get(id)) !== null && _a !== void 0 ? _a : 0) + 1);
452
582
  }
453
583
  this.state.revision += 1;
584
+ if (patch.documentChanged !== false)
585
+ this.state.documentRevision += 1;
586
+ if (patch.orderChanged === true)
587
+ this.state.orderRevision += 1;
454
588
  this.geometryService.invalidate(invalidatedIds);
455
589
  const invalidatedGeometryIds = [...invalidatedIds];
456
590
  this.spatialIndex.update(invalidatedGeometryIds
@@ -479,17 +613,58 @@ export class DiagramEngine {
479
613
  return invalidated;
480
614
  }
481
615
  ensureDependencyIndex(changedIds) {
482
- let rebuild = !this.dependencyIndexReady;
483
- for (const id of changedIds) {
484
- const exists = this.hasEntity(id);
485
- if (this.dependencyEntityIds.has(id) !== exists || this.state.entities.edgesById.has(id) || this.state.entities.portsById.has(id)) {
486
- rebuild = true;
487
- break;
616
+ var _a;
617
+ if (this.dependencyIndexReady) {
618
+ const structuralChange = [...changedIds].some((id) => this.dependencyEntityIds.has(id) !== this.hasEntity(id));
619
+ if (structuralChange) {
620
+ this.dependencyIndexReady = false;
621
+ }
622
+ else {
623
+ for (const id of changedIds) {
624
+ const oldEdge = this.dependencyEdgeEndpoints.get(id);
625
+ const edge = this.state.entities.edgesById.get(id);
626
+ if (oldEdge && (!edge || oldEdge[0] !== edge.source && JSON.stringify(oldEdge[0]) !== JSON.stringify(edge.source) || oldEdge[1] !== edge.target && JSON.stringify(oldEdge[1]) !== JSON.stringify(edge.target))) {
627
+ this.removeEdgeDependencies(id, oldEdge);
628
+ this.dependencyEdgeEndpoints.delete(id);
629
+ }
630
+ if (edge && !this.dependencyEdgeEndpoints.has(id)) {
631
+ const endpoints = [edge.source, edge.target];
632
+ this.addEdgeDependencies(id, endpoints);
633
+ this.dependencyEdgeEndpoints.set(id, endpoints);
634
+ }
635
+ const oldOwner = this.dependencyPortOwners.get(id);
636
+ const port = this.state.entities.portsById.get(id);
637
+ if (oldOwner !== (port === null || port === void 0 ? void 0 : port.nodeId)) {
638
+ const attachedEdges = [...((_a = this.edgeIdsByPort.get(id)) !== null && _a !== void 0 ? _a : [])];
639
+ for (const edgeId of attachedEdges) {
640
+ const endpoints = this.dependencyEdgeEndpoints.get(edgeId);
641
+ if (endpoints)
642
+ this.removeEdgeDependencies(edgeId, endpoints);
643
+ }
644
+ if (oldOwner)
645
+ removeDependency(this.portIdsByNode, oldOwner, id);
646
+ if (!port)
647
+ this.dependencyPortOwners.delete(id);
648
+ else {
649
+ this.dependencyPortOwners.set(id, port.nodeId);
650
+ addDependency(this.portIdsByNode, port.nodeId, id);
651
+ }
652
+ for (const edgeId of attachedEdges) {
653
+ const endpoints = this.dependencyEdgeEndpoints.get(edgeId);
654
+ if (endpoints)
655
+ this.addEdgeDependencies(edgeId, endpoints);
656
+ }
657
+ }
658
+ const exists = this.hasEntity(id);
659
+ if (exists)
660
+ this.dependencyEntityIds.add(id);
661
+ else
662
+ this.dependencyEntityIds.delete(id);
663
+ }
664
+ return;
488
665
  }
489
666
  }
490
- if (!rebuild) {
491
- return;
492
- }
667
+ this.dependencyIndexRebuildCount += 1;
493
668
  this.dependencyEntityIds = new Set([
494
669
  ...this.state.entities.nodesById.keys(),
495
670
  ...this.state.entities.edgesById.keys(),
@@ -500,28 +675,46 @@ export class DiagramEngine {
500
675
  this.portIdsByNode = new Map();
501
676
  this.edgeIdsByNode = new Map();
502
677
  this.edgeIdsByPort = new Map();
678
+ this.dependencyEdgeEndpoints.clear();
679
+ this.dependencyPortOwners.clear();
503
680
  for (const port of this.state.entities.portsById.values()) {
681
+ this.dependencyPortOwners.set(port.id, port.nodeId);
504
682
  addDependency(this.portIdsByNode, port.nodeId, port.id);
505
683
  }
506
684
  for (const edge of this.state.entities.edgesById.values()) {
507
- for (const endpoint of [edge.source, edge.target]) {
508
- if (endpoint.kind === "node") {
509
- addDependency(this.edgeIdsByNode, endpoint.nodeId, edge.id);
510
- }
511
- else if (endpoint.kind === "port") {
512
- addDependency(this.edgeIdsByPort, endpoint.portId, edge.id);
513
- const port = this.state.entities.portsById.get(endpoint.portId);
514
- if (port) {
515
- addDependency(this.edgeIdsByNode, port.nodeId, edge.id);
516
- }
517
- }
518
- }
685
+ const endpoints = [edge.source, edge.target];
686
+ this.dependencyEdgeEndpoints.set(edge.id, endpoints);
687
+ this.addEdgeDependencies(edge.id, endpoints);
519
688
  }
520
689
  this.dependencyIndexReady = true;
521
690
  }
691
+ addEdgeDependencies(id, endpoints) {
692
+ for (const endpoint of endpoints) {
693
+ if (endpoint.kind === "node")
694
+ addDependency(this.edgeIdsByNode, endpoint.nodeId, id);
695
+ else if (endpoint.kind === "port") {
696
+ addDependency(this.edgeIdsByPort, endpoint.portId, id);
697
+ const owner = this.dependencyPortOwners.get(endpoint.portId);
698
+ if (owner)
699
+ addDependency(this.edgeIdsByNode, owner, id);
700
+ }
701
+ }
702
+ }
703
+ removeEdgeDependencies(id, endpoints) {
704
+ for (const endpoint of endpoints) {
705
+ if (endpoint.kind === "node")
706
+ removeDependency(this.edgeIdsByNode, endpoint.nodeId, id);
707
+ else if (endpoint.kind === "port") {
708
+ removeDependency(this.edgeIdsByPort, endpoint.portId, id);
709
+ const owner = this.dependencyPortOwners.get(endpoint.portId);
710
+ if (owner)
711
+ removeDependency(this.edgeIdsByNode, owner, id);
712
+ }
713
+ }
714
+ }
522
715
  getGeometry(id) {
523
716
  var _a;
524
- return this.geometryService.get(id, this.store.getSnapshot().entities, (_a = this.state.versions.get(id)) !== null && _a !== void 0 ? _a : 0);
717
+ return this.geometryService.get(id, this.state.entities, (_a = this.state.versions.get(id)) !== null && _a !== void 0 ? _a : 0);
525
718
  }
526
719
  rebuildIndexGeometries() {
527
720
  return this.createOrderedIds()
@@ -538,6 +731,14 @@ export class DiagramEngine {
538
731
  return createMovePatch(this.state, command.ids, command.delta);
539
732
  case "moveNode":
540
733
  return createMovePatch(this.state, [command.id], command.delta);
734
+ case "createNode":
735
+ return createCreateEntityPatch(this.state, command.node);
736
+ case "createPort":
737
+ return createCreatePortPatch(this.state, command.port);
738
+ case "deleteEntities":
739
+ return createDeleteEntitiesCommandPatch(this.state, command.ids);
740
+ case "reconnectEdgeEndpoint":
741
+ return createReconnectEdgeEndpointPatch(this.state, command.id, command.endpoint, command.connection);
541
742
  case "moveEdgeEndpoint":
542
743
  return createMoveEdgeEndpointPatch(this.state, command.id, command.endpoint, command.point);
543
744
  case "insertEdgeWaypoint":
@@ -553,6 +754,12 @@ export class DiagramEngine {
553
754
  case "duplicateSelection":
554
755
  return this.clipboardService.createPastePatch(this.state, this.clipboardService.exportSubgraph(this.state, this.state.selection.ids, normalizeSelection), (_a = command.offset) !== null && _a !== void 0 ? _a : { x: 24, y: 24 }, createDeleteEntitiesPatch, normalizeSelection);
555
756
  case "pasteClipboard":
757
+ try {
758
+ validateSceneInput(command.clipboard);
759
+ }
760
+ catch {
761
+ return null;
762
+ }
556
763
  return this.clipboardService.createPastePatch(this.state, command.clipboard, (_b = command.offset) !== null && _b !== void 0 ? _b : { x: 24, y: 24 }, createDeleteEntitiesPatch, normalizeSelection);
557
764
  case "resizeEntities":
558
765
  return createResizePatch(this.state, command.entries);
@@ -603,8 +810,123 @@ export class DiagramEngine {
603
810
  }
604
811
  return null;
605
812
  }
813
+ findTranslationAlignment(sourceBounds, targetOrigin, radius, excludeIds) {
814
+ var _a, _b, _c;
815
+ const moving = { ...sourceBounds, x: targetOrigin.x, y: targetOrigin.y };
816
+ let bestX = null;
817
+ let bestY = null;
818
+ const searchBounds = inflateRect(moving, radius);
819
+ for (const fixedId of this.queryEntities({ bounds: searchBounds, kinds: ["node", "shape", "text"] })) {
820
+ if (excludeIds.has(fixedId))
821
+ continue;
822
+ const fixed = (_a = this.getGeometry(fixedId)) === null || _a === void 0 ? void 0 : _a.bounds;
823
+ if (!fixed)
824
+ continue;
825
+ const movingX = [moving.x, moving.x + moving.width / 2, moving.x + moving.width];
826
+ const fixedX = [fixed.x, fixed.x + fixed.width / 2, fixed.x + fixed.width];
827
+ for (const [index, value] of movingX.entries()) {
828
+ for (const coordinate of fixedX) {
829
+ const delta = coordinate - value;
830
+ if (Math.abs(delta) <= radius && (!bestX || Math.abs(delta) < Math.abs(bestX.delta))) {
831
+ bestX = { delta, coordinate, start: Math.min(moving.y, fixed.y), end: Math.max(moving.y + moving.height, fixed.y + fixed.height), startIsMoving: moving.y <= fixed.y, endIsMoving: moving.y + moving.height >= fixed.y + fixed.height };
832
+ }
833
+ }
834
+ }
835
+ const movingY = [moving.y, moving.y + moving.height / 2, moving.y + moving.height];
836
+ const fixedY = [fixed.y, fixed.y + fixed.height / 2, fixed.y + fixed.height];
837
+ for (const value of movingY) {
838
+ for (const coordinate of fixedY) {
839
+ const delta = coordinate - value;
840
+ if (Math.abs(delta) <= radius && (!bestY || Math.abs(delta) < Math.abs(bestY.delta))) {
841
+ bestY = { delta, coordinate, start: Math.min(moving.x, fixed.x), end: Math.max(moving.x + moving.width, fixed.x + fixed.width), startIsMoving: moving.x <= fixed.x, endIsMoving: moving.x + moving.width >= fixed.x + fixed.width };
842
+ }
843
+ }
844
+ }
845
+ }
846
+ if (!bestX && !bestY)
847
+ return null;
848
+ const dx = (_b = bestX === null || bestX === void 0 ? void 0 : bestX.delta) !== null && _b !== void 0 ? _b : 0;
849
+ const dy = (_c = bestY === null || bestY === void 0 ? void 0 : bestY.delta) !== null && _c !== void 0 ? _c : 0;
850
+ const guides = [];
851
+ if (bestX)
852
+ guides.push({ kind: "alignment", axis: "x", start: { x: bestX.coordinate, y: bestX.start + (bestX.startIsMoving ? dy : 0) }, end: { x: bestX.coordinate, y: bestX.end + (bestX.endIsMoving ? dy : 0) } });
853
+ if (bestY)
854
+ guides.push({ kind: "alignment", axis: "y", start: { x: bestY.start + (bestY.startIsMoving ? dx : 0), y: bestY.coordinate }, end: { x: bestY.end + (bestY.endIsMoving ? dx : 0), y: bestY.coordinate } });
855
+ return { dx, dy, guides };
856
+ }
857
+ findEqualSpacing(sourceBounds, targetOrigin, radius, excludeIds, excludeAxes) {
858
+ var _a;
859
+ const moving = { ...sourceBounds, x: targetOrigin.x, y: targetOrigin.y };
860
+ const reach = Math.max(128, radius * 16, sourceBounds.width * 8, sourceBounds.height * 8);
861
+ const searchBounds = { x: moving.x - reach, y: moving.y - reach, width: moving.width + reach * 2, height: moving.height + reach * 2 };
862
+ const order = this.createOrderIndex();
863
+ let xBefore = null;
864
+ let xAfter = null;
865
+ let yBefore = null;
866
+ let yAfter = null;
867
+ const earlier = (candidate, current) => { var _a, _b; return ((_a = order.get(candidate)) !== null && _a !== void 0 ? _a : 0) < ((_b = order.get(current)) !== null && _b !== void 0 ? _b : 0); };
868
+ for (const id of this.spatialIndex.queryVisible(searchBounds)) {
869
+ if (excludeIds.has(id))
870
+ continue;
871
+ const kind = this.getEntityKind(id);
872
+ if (kind !== "node" && kind !== "shape" && kind !== "text")
873
+ continue;
874
+ const bounds = (_a = this.getGeometry(id)) === null || _a === void 0 ? void 0 : _a.bounds;
875
+ if (!bounds)
876
+ continue;
877
+ if (rangesOverlap(bounds.y, bounds.y + bounds.height, moving.y, moving.y + moving.height)) {
878
+ if (bounds.x + bounds.width <= moving.x && (!xBefore || bounds.x + bounds.width > xBefore.bounds.x + xBefore.bounds.width || (bounds.x + bounds.width === xBefore.bounds.x + xBefore.bounds.width && earlier(id, xBefore.id))))
879
+ xBefore = { id, bounds };
880
+ if (bounds.x >= moving.x + moving.width && (!xAfter || bounds.x < xAfter.bounds.x || (bounds.x === xAfter.bounds.x && earlier(id, xAfter.id))))
881
+ xAfter = { id, bounds };
882
+ }
883
+ if (rangesOverlap(bounds.x, bounds.x + bounds.width, moving.x, moving.x + moving.width)) {
884
+ if (bounds.y + bounds.height <= moving.y && (!yBefore || bounds.y + bounds.height > yBefore.bounds.y + yBefore.bounds.height || (bounds.y + bounds.height === yBefore.bounds.y + yBefore.bounds.height && earlier(id, yBefore.id))))
885
+ yBefore = { id, bounds };
886
+ if (bounds.y >= moving.y + moving.height && (!yAfter || bounds.y < yAfter.bounds.y || (bounds.y === yAfter.bounds.y && earlier(id, yAfter.id))))
887
+ yAfter = { id, bounds };
888
+ }
889
+ }
890
+ let best = null;
891
+ if (!excludeAxes.has("x")) {
892
+ if (xBefore && xAfter) {
893
+ const delta = ((xAfter.bounds.x - moving.x - moving.width) - (moving.x - xBefore.bounds.x - xBefore.bounds.width)) / 2;
894
+ if (Math.abs(delta) <= radius)
895
+ best = { axis: "x", delta, before: xBefore.bounds, after: xAfter.bounds };
896
+ }
897
+ }
898
+ if (!excludeAxes.has("y")) {
899
+ if (yBefore && yAfter) {
900
+ const delta = ((yAfter.bounds.y - moving.y - moving.height) - (moving.y - yBefore.bounds.y - yBefore.bounds.height)) / 2;
901
+ if (Math.abs(delta) <= radius && (!best || Math.abs(delta) < Math.abs(best.delta)))
902
+ best = { axis: "y", delta, before: yBefore.bounds, after: yAfter.bounds };
903
+ }
904
+ }
905
+ if (!best)
906
+ return null;
907
+ if (best.axis === "x") {
908
+ const centerY = moving.y + moving.height / 2;
909
+ return {
910
+ dx: best.delta,
911
+ dy: 0,
912
+ guides: [
913
+ { kind: "equal-spacing", axis: "x", start: { x: best.before.x + best.before.width, y: centerY }, end: { x: moving.x + best.delta, y: centerY } },
914
+ { kind: "equal-spacing", axis: "x", start: { x: moving.x + moving.width + best.delta, y: centerY }, end: { x: best.after.x, y: centerY } },
915
+ ],
916
+ };
917
+ }
918
+ const centerX = moving.x + moving.width / 2;
919
+ return {
920
+ dx: 0,
921
+ dy: best.delta,
922
+ guides: [
923
+ { kind: "equal-spacing", axis: "y", start: { x: centerX, y: best.before.y + best.before.height }, end: { x: centerX, y: moving.y + best.delta } },
924
+ { kind: "equal-spacing", axis: "y", start: { x: centerX, y: moving.y + moving.height + best.delta }, end: { x: centerX, y: best.after.y } },
925
+ ],
926
+ };
927
+ }
606
928
  createOrderedIds() {
607
- if (this.orderedIdsRevision === this.state.revision) {
929
+ if (this.orderedIdsRevision === this.state.orderRevision) {
608
930
  return this.orderedIdsCache;
609
931
  }
610
932
  const ids = [
@@ -624,13 +946,13 @@ export class DiagramEngine {
624
946
  const zDelta = zIndex(this.getEntityMetadata(a)) - zIndex(this.getEntityMetadata(b));
625
947
  return zDelta || (((_a = baseOrder.get(a)) !== null && _a !== void 0 ? _a : 0) - ((_b = baseOrder.get(b)) !== null && _b !== void 0 ? _b : 0));
626
948
  });
627
- this.orderedIdsRevision = this.state.revision;
949
+ this.orderedIdsRevision = this.state.orderRevision;
628
950
  return this.orderedIdsCache;
629
951
  }
630
952
  createOrderIndex() {
631
- if (this.orderIndexRevision !== this.state.revision) {
953
+ if (this.orderIndexRevision !== this.state.orderRevision) {
632
954
  this.orderIndexCache = new Map(this.createOrderedIds().map((id, index) => [id, index]));
633
- this.orderIndexRevision = this.state.revision;
955
+ this.orderIndexRevision = this.state.orderRevision;
634
956
  }
635
957
  return this.orderIndexCache;
636
958
  }
@@ -662,6 +984,29 @@ export class DiagramEngine {
662
984
  var _a;
663
985
  return ((_a = this.getEntityMetadata(id)) === null || _a === void 0 ? void 0 : _a.nonDeletable) === true;
664
986
  }
987
+ isEntityTranslatable(id) {
988
+ var _a;
989
+ if (this.state.entities.portsById.has(id))
990
+ return false;
991
+ const edge = this.state.entities.edgesById.get(id);
992
+ if (edge)
993
+ return edge.source.kind === "point" || edge.target.kind === "point" || Boolean((_a = edge.points) === null || _a === void 0 ? void 0 : _a.length);
994
+ return this.state.entities.nodesById.has(id) || this.state.entities.textsById.has(id) || this.state.entities.shapesById.has(id);
995
+ }
996
+ }
997
+ function isBatchNoOp(state, command) {
998
+ var _a;
999
+ if (command.type === "updateEntities" && command.updates.every((update) => {
1000
+ var _a;
1001
+ if (!hasEntity(state, update.id))
1002
+ return false;
1003
+ const current = (_a = getEntityMetadata(state, update.id)) !== null && _a !== void 0 ? _a : {};
1004
+ return update.metadata === undefined || Object.entries(update.metadata).every(([key, value]) => Object.is(current[key], value));
1005
+ }))
1006
+ return true;
1007
+ if (command.type === "setSelection" && command.selection.ids.length === state.selection.ids.length && command.selection.ids.every((id, index) => id === state.selection.ids[index]) && ((_a = command.selection.primaryId) !== null && _a !== void 0 ? _a : null) === state.selection.primaryId)
1008
+ return true;
1009
+ return false;
665
1010
  }
666
1011
  function geometryMatchesBounds(candidate, bounds, mode) {
667
1012
  return mode === "contains" ? rectContainsRect(bounds, candidate) : rectIntersects(candidate, bounds);
@@ -672,6 +1017,9 @@ function rectContainsRect(container, candidate) {
672
1017
  && candidate.x + candidate.width <= container.x + container.width
673
1018
  && candidate.y + candidate.height <= container.y + container.height;
674
1019
  }
1020
+ function rangesOverlap(aStart, aEnd, bStart, bEnd) {
1021
+ return aStart <= bEnd && aEnd >= bStart;
1022
+ }
675
1023
  function normalizeSearchText(value) {
676
1024
  var _a;
677
1025
  return (_a = value === null || value === void 0 ? void 0 : value.trim().toLocaleLowerCase()) !== null && _a !== void 0 ? _a : "";
@@ -742,70 +1090,128 @@ export function serializeScene(scene) {
742
1090
  export function deserializeScene(scene) {
743
1091
  return scene;
744
1092
  }
1093
+ export function deserializeDiagramDocument(input) {
1094
+ var _a;
1095
+ if (!input || typeof input !== "object")
1096
+ throw new TypeError("Invalid diagram document");
1097
+ if ("format" in input) {
1098
+ if (input.format !== "affino-diagram" || input.version !== 1 || !input.content || ![input.content.nodes, input.content.edges, input.content.texts, input.content.shapes, input.content.ports].every(Array.isArray)) {
1099
+ throw new TypeError("Unsupported or invalid diagram document");
1100
+ }
1101
+ const view = (_a = input.view) !== null && _a !== void 0 ? _a : {};
1102
+ return validateSceneInput({ ...input.content, ...(view.selection ? { selection: view.selection } : {}), ...(view.viewport ? { viewport: view.viewport } : {}) });
1103
+ }
1104
+ return validateSceneInput(input);
1105
+ }
1106
+ function validateSceneInput(scene) {
1107
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
1108
+ const nodesInput = (_a = scene.nodes) !== null && _a !== void 0 ? _a : [];
1109
+ const edgesInput = (_b = scene.edges) !== null && _b !== void 0 ? _b : [];
1110
+ const textsInput = (_c = scene.texts) !== null && _c !== void 0 ? _c : [];
1111
+ const shapesInput = (_d = scene.shapes) !== null && _d !== void 0 ? _d : [];
1112
+ const portsInput = (_e = scene.ports) !== null && _e !== void 0 ? _e : [];
1113
+ if (![nodesInput, edgesInput, textsInput, shapesInput, portsInput].every(Array.isArray))
1114
+ throw new TypeError("Invalid diagram scene collections");
1115
+ const ids = new Set();
1116
+ for (const entity of [...nodesInput, ...edgesInput, ...textsInput, ...shapesInput, ...portsInput]) {
1117
+ if (!entity || typeof entity.id !== "string" || !entity.id || ids.has(entity.id))
1118
+ throw new TypeError("Diagram entity IDs must be non-empty and globally unique");
1119
+ ids.add(entity.id);
1120
+ }
1121
+ const nodes = new Set(nodesInput.map((node) => node.id));
1122
+ const ports = new Map(portsInput.map((port) => [port.id, port]));
1123
+ for (const node of nodesInput)
1124
+ if (![node.x, node.y, node.width, node.height, (_f = node.rotation) !== null && _f !== void 0 ? _f : 0].every(Number.isFinite) || node.width < 0 || node.height < 0)
1125
+ throw new TypeError(`Invalid geometry for node ${node.id}`);
1126
+ for (const port of portsInput)
1127
+ if (!nodes.has(port.nodeId) || ![port.x, port.y, (_g = port.radius) !== null && _g !== void 0 ? _g : 0].every(Number.isFinite))
1128
+ throw new TypeError(`Invalid port ${port.id}`);
1129
+ for (const node of nodesInput)
1130
+ if (((_h = node.portIds) !== null && _h !== void 0 ? _h : []).some((id) => { var _a; return ((_a = ports.get(id)) === null || _a === void 0 ? void 0 : _a.nodeId) !== node.id; }))
1131
+ throw new TypeError(`Invalid port reference on node ${node.id}`);
1132
+ for (const text of textsInput)
1133
+ if (![text.x, text.y, (_j = text.width) !== null && _j !== void 0 ? _j : 0, (_k = text.height) !== null && _k !== void 0 ? _k : 0, (_l = text.fontSize) !== null && _l !== void 0 ? _l : 0, (_m = text.rotation) !== null && _m !== void 0 ? _m : 0].every(Number.isFinite))
1134
+ throw new TypeError(`Invalid geometry for text ${text.id}`);
1135
+ for (const shape of shapesInput)
1136
+ if (![shape.x, shape.y, shape.width, shape.height, (_o = shape.rotation) !== null && _o !== void 0 ? _o : 0].every(Number.isFinite) || shape.width < 0 || shape.height < 0)
1137
+ throw new TypeError(`Invalid geometry for shape ${shape.id}`);
1138
+ for (const edge of edgesInput) {
1139
+ const validEndpoint = (endpoint) => endpoint.kind === "point" ? Number.isFinite(endpoint.point.x) && Number.isFinite(endpoint.point.y) : endpoint.kind === "node" ? nodes.has(endpoint.nodeId) : endpoint.kind === "port" && ports.has(endpoint.portId);
1140
+ if (!validEndpoint(edge.source) || !validEndpoint(edge.target) || !((_p = edge.points) !== null && _p !== void 0 ? _p : []).every((point) => Number.isFinite(point.x) && Number.isFinite(point.y)))
1141
+ throw new TypeError(`Invalid edge ${edge.id}`);
1142
+ }
1143
+ if (scene.viewport && (![scene.viewport.x, scene.viewport.y, scene.viewport.width, scene.viewport.height, scene.viewport.zoom].filter((value) => value !== undefined).every(Number.isFinite) || (scene.viewport.zoom !== undefined && scene.viewport.zoom <= 0)))
1144
+ throw new TypeError("Invalid diagram viewport");
1145
+ const selectionIds = (_r = (_q = scene.selection) === null || _q === void 0 ? void 0 : _q.ids) !== null && _r !== void 0 ? _r : [];
1146
+ if (selectionIds.some((id) => !ids.has(id)))
1147
+ throw new TypeError("Diagram selection contains an unknown entity");
1148
+ return { ...scene, nodes: nodesInput, edges: edgesInput, texts: textsInput, shapes: shapesInput, ports: portsInput };
1149
+ }
745
1150
  function createMovePatch(state, ids, delta) {
746
1151
  if (delta.x === 0 && delta.y === 0) {
747
1152
  return null;
748
1153
  }
749
- const movableIds = ids.filter((id) => !isEntityLockedOrReadOnly(state, id) && (state.entities.nodesById.has(id) || state.entities.textsById.has(id) || state.entities.shapesById.has(id)));
1154
+ const movableIds = ids.filter((id) => !isEntityLockedOrReadOnly(state, id) && (state.entities.nodesById.has(id)
1155
+ || isEdgeTranslatable(state.entities.edgesById.get(id))
1156
+ || state.entities.textsById.has(id)
1157
+ || state.entities.shapesById.has(id)));
750
1158
  if (!movableIds.length) {
751
1159
  return null;
752
1160
  }
753
1161
  return {
754
- apply: (next) => {
755
- const changed = new Set();
756
- for (const id of movableIds) {
757
- const node = next.entities.nodesById.get(id);
758
- if (node) {
759
- next.entities.nodesById.set(id, { ...node, x: node.x + delta.x, y: node.y + delta.y });
760
- changed.add(id);
761
- continue;
762
- }
763
- const text = next.entities.textsById.get(id);
764
- if (text) {
765
- next.entities.textsById.set(id, { ...text, x: text.x + delta.x, y: text.y + delta.y });
766
- changed.add(id);
767
- continue;
768
- }
769
- const shape = next.entities.shapesById.get(id);
770
- if (shape) {
771
- next.entities.shapesById.set(id, { ...shape, x: shape.x + delta.x, y: shape.y + delta.y });
772
- changed.add(id);
773
- }
774
- }
775
- return changed;
776
- },
1162
+ apply: (next) => applyMoveDelta(next, movableIds, delta),
777
1163
  inverse: createMovePatchUnchecked(movableIds, { x: -delta.x, y: -delta.y }),
778
1164
  };
779
1165
  }
1166
+ function isEdgeTranslatable(edge) {
1167
+ var _a;
1168
+ return Boolean(edge && (edge.source.kind === "point" || edge.target.kind === "point" || ((_a = edge.points) === null || _a === void 0 ? void 0 : _a.length)));
1169
+ }
780
1170
  function createMovePatchUnchecked(ids, delta) {
781
1171
  return {
782
- apply: (next) => {
783
- const changed = new Set();
784
- for (const id of ids) {
785
- const node = next.entities.nodesById.get(id);
786
- if (node) {
787
- next.entities.nodesById.set(id, { ...node, x: node.x + delta.x, y: node.y + delta.y });
788
- changed.add(id);
789
- }
790
- const text = next.entities.textsById.get(id);
791
- if (text) {
792
- next.entities.textsById.set(id, { ...text, x: text.x + delta.x, y: text.y + delta.y });
793
- changed.add(id);
794
- }
795
- const shape = next.entities.shapesById.get(id);
796
- if (shape) {
797
- next.entities.shapesById.set(id, { ...shape, x: shape.x + delta.x, y: shape.y + delta.y });
798
- changed.add(id);
799
- }
800
- }
801
- return changed;
802
- },
1172
+ apply: (next) => applyMoveDelta(next, ids, delta),
803
1173
  inverse: undefined,
804
1174
  };
805
1175
  }
1176
+ function applyMoveDelta(state, ids, delta) {
1177
+ var _a;
1178
+ const changed = new Set();
1179
+ const translate = (point) => ({ x: point.x + delta.x, y: point.y + delta.y });
1180
+ for (const id of ids) {
1181
+ const node = state.entities.nodesById.get(id);
1182
+ if (node) {
1183
+ state.entities.nodesById.set(id, { ...node, x: node.x + delta.x, y: node.y + delta.y });
1184
+ changed.add(id);
1185
+ continue;
1186
+ }
1187
+ const edge = state.entities.edgesById.get(id);
1188
+ if (edge) {
1189
+ state.entities.edgesById.set(id, {
1190
+ ...edge,
1191
+ source: edge.source.kind === "point" ? { kind: "point", point: translate(edge.source.point) } : edge.source,
1192
+ target: edge.target.kind === "point" ? { kind: "point", point: translate(edge.target.point) } : edge.target,
1193
+ points: (_a = edge.points) === null || _a === void 0 ? void 0 : _a.map(translate),
1194
+ });
1195
+ changed.add(id);
1196
+ continue;
1197
+ }
1198
+ const text = state.entities.textsById.get(id);
1199
+ if (text) {
1200
+ state.entities.textsById.set(id, { ...text, x: text.x + delta.x, y: text.y + delta.y });
1201
+ changed.add(id);
1202
+ continue;
1203
+ }
1204
+ const shape = state.entities.shapesById.get(id);
1205
+ if (shape) {
1206
+ state.entities.shapesById.set(id, { ...shape, x: shape.x + delta.x, y: shape.y + delta.y });
1207
+ changed.add(id);
1208
+ }
1209
+ }
1210
+ return changed;
1211
+ }
806
1212
  function createMoveEdgeEndpointPatch(state, id, endpoint, point) {
807
1213
  const edge = state.entities.edgesById.get(id);
808
- if (!edge) {
1214
+ if (!edge || isEntityLockedOrReadOnly(state, id) || !Number.isFinite(point.x) || !Number.isFinite(point.y)) {
809
1215
  return null;
810
1216
  }
811
1217
  const previous = edge[endpoint];
@@ -1123,12 +1529,14 @@ function metadataEqual(first, second) {
1123
1529
  }
1124
1530
  function createMetadataSnapshotPatch(ids, previous, nextMetadata) {
1125
1531
  return {
1532
+ orderChanged: true,
1126
1533
  apply: (state) => {
1127
1534
  for (const id of ids)
1128
1535
  setEntityMetadata(state, id, nextMetadata.get(id));
1129
1536
  return new Set(ids);
1130
1537
  },
1131
1538
  inverse: {
1539
+ orderChanged: true,
1132
1540
  apply: (state) => {
1133
1541
  for (const id of ids)
1134
1542
  setEntityMetadata(state, id, previous.get(id));
@@ -1140,11 +1548,13 @@ function createMetadataSnapshotPatch(ids, previous, nextMetadata) {
1140
1548
  }
1141
1549
  function createOrderPatchUnchecked(previous, nextOrder) {
1142
1550
  return {
1551
+ orderChanged: true,
1143
1552
  apply: (state) => {
1144
1553
  state.order = cloneOrder(nextOrder);
1145
1554
  return new Set([...nextOrder.nodeIds, ...nextOrder.edgeIds, ...nextOrder.textIds, ...nextOrder.shapeIds]);
1146
1555
  },
1147
1556
  inverse: {
1557
+ orderChanged: true,
1148
1558
  apply: (state) => {
1149
1559
  state.order = cloneOrder(previous);
1150
1560
  return new Set([...previous.nodeIds, ...previous.edgeIds, ...previous.textIds, ...previous.shapeIds]);
@@ -1191,10 +1601,11 @@ function createKeyboardPatch(state, command, options) {
1191
1601
  return createMovePatch(state, state.selection.ids, (_c = deltaByCommand[command]) !== null && _c !== void 0 ? _c : { x: 0, y: 0 });
1192
1602
  }
1193
1603
  function createCreateEdgePatch(state, edge) {
1194
- if (state.entities.edgesById.has(edge.id)) {
1604
+ if (!isUniqueId(state, edge.id) || !isValidEdge(state, edge)) {
1195
1605
  return null;
1196
1606
  }
1197
1607
  return {
1608
+ orderChanged: true,
1198
1609
  apply: (next) => {
1199
1610
  next.entities.edgesById.set(edge.id, edge);
1200
1611
  next.order.edgeIds.push(edge.id);
@@ -1204,14 +1615,138 @@ function createCreateEdgePatch(state, edge) {
1204
1615
  inverse: createDeleteEntitiesPatch([edge.id]),
1205
1616
  };
1206
1617
  }
1618
+ function createCreateEntityPatch(state, node) {
1619
+ var _a, _b;
1620
+ if (!isUniqueId(state, node.id) || Boolean((_a = node.portIds) === null || _a === void 0 ? void 0 : _a.length) || ![node.x, node.y, node.width, node.height, (_b = node.rotation) !== null && _b !== void 0 ? _b : 0].every(Number.isFinite) || node.width < 0 || node.height < 0)
1621
+ return null;
1622
+ return {
1623
+ orderChanged: true,
1624
+ apply: (next) => { next.entities.nodesById.set(node.id, node); next.order.nodeIds.push(node.id); next.versions.set(node.id, 0); return new Set([node.id]); },
1625
+ inverse: createDeleteEntitiesPatch([node.id]),
1626
+ };
1627
+ }
1628
+ function createCreatePortPatch(state, port) {
1629
+ var _a;
1630
+ const owner = state.entities.nodesById.get(port.nodeId);
1631
+ if (!owner || isEntityLockedOrReadOnly(state, owner.id) || !isUniqueId(state, port.id) || !Number.isFinite(port.x) || !Number.isFinite(port.y) || (port.radius !== undefined && (!Number.isFinite(port.radius) || port.radius < 0)))
1632
+ return null;
1633
+ const previousPorts = [...((_a = owner.portIds) !== null && _a !== void 0 ? _a : [])];
1634
+ return {
1635
+ orderChanged: true,
1636
+ apply: (next) => {
1637
+ next.entities.portsById.set(port.id, port);
1638
+ next.entities.nodesById.set(owner.id, { ...next.entities.nodesById.get(owner.id), portIds: [...new Set([...previousPorts, port.id])] });
1639
+ next.versions.set(port.id, 0);
1640
+ return new Set([port.id, owner.id]);
1641
+ },
1642
+ inverse: {
1643
+ orderChanged: true,
1644
+ apply: (next) => { next.entities.portsById.delete(port.id); next.entities.nodesById.set(owner.id, { ...next.entities.nodesById.get(owner.id), portIds: previousPorts }); return new Set([port.id, owner.id]); },
1645
+ inverse: undefined,
1646
+ },
1647
+ };
1648
+ }
1649
+ function createDeleteEntitiesCommandPatch(state, ids) {
1650
+ if (!ids.length || ids.some((id) => !hasEntity(state, id)))
1651
+ return null;
1652
+ const cascade = expandDeletedIds(state, ids);
1653
+ const deleting = new Set(cascade);
1654
+ for (const id of deleting) {
1655
+ if (state.entities.nodesById.has(id)) {
1656
+ for (const port of state.entities.portsById.values())
1657
+ if (port.nodeId === id && !deleting.has(port.id))
1658
+ return null;
1659
+ for (const edge of state.entities.edgesById.values())
1660
+ if (endpointDeleted(edge.source, deleting) || endpointDeleted(edge.target, deleting))
1661
+ if (!deleting.has(edge.id))
1662
+ return null;
1663
+ }
1664
+ }
1665
+ if (cascade.length !== new Set(cascade).size || cascade.some((id) => isEntityNonDeletable(state, id) || isEntityLockedOrReadOnly(state, id)))
1666
+ return null;
1667
+ if (ids.some((id) => isEntityNonDeletable(state, id) || isEntityLockedOrReadOnly(state, id)))
1668
+ return null;
1669
+ return createDeleteEntitiesPatch(cascade);
1670
+ }
1671
+ function createReconnectEdgeEndpointPatch(state, id, endpoint, connection) {
1672
+ const edge = state.entities.edgesById.get(id);
1673
+ if (!edge || isEntityLockedOrReadOnly(state, id) || !isValidEndpoint(state, connection))
1674
+ return null;
1675
+ const previous = edge[endpoint];
1676
+ if (JSON.stringify(previous) === JSON.stringify(connection))
1677
+ return null;
1678
+ return {
1679
+ apply: (next) => { const current = next.entities.edgesById.get(id); if (!current)
1680
+ return new Set(); next.entities.edgesById.set(id, { ...current, [endpoint]: connection }); return new Set([id]); },
1681
+ inverse: { apply: (next) => { const current = next.entities.edgesById.get(id); if (!current)
1682
+ return new Set(); next.entities.edgesById.set(id, { ...current, [endpoint]: previous }); return new Set([id]); }, inverse: undefined },
1683
+ };
1684
+ }
1685
+ function isUniqueId(state, id) { return typeof id === "string" && id.length > 0 && !hasEntity(state, id); }
1686
+ function isValidEndpoint(state, endpoint) {
1687
+ if (endpoint.kind === "point")
1688
+ return Number.isFinite(endpoint.point.x) && Number.isFinite(endpoint.point.y);
1689
+ if (endpoint.kind === "node")
1690
+ return state.entities.nodesById.has(endpoint.nodeId);
1691
+ const port = state.entities.portsById.get(endpoint.portId);
1692
+ return Boolean(port && state.entities.nodesById.has(port.nodeId));
1693
+ }
1694
+ function isValidEdge(state, edge) {
1695
+ var _a;
1696
+ return isValidEndpoint(state, edge.source) && isValidEndpoint(state, edge.target) && ((_a = edge.points) !== null && _a !== void 0 ? _a : []).every((point) => Number.isFinite(point.x) && Number.isFinite(point.y));
1697
+ }
1698
+ function commandIds(command) {
1699
+ if ("id" in command)
1700
+ return [command.id];
1701
+ if ("ids" in command)
1702
+ return [...command.ids];
1703
+ if (command.type === "createEdge")
1704
+ return [command.edge.id];
1705
+ if (command.type === "createNode")
1706
+ return [command.node.id];
1707
+ if (command.type === "createPort")
1708
+ return [command.port.id, command.port.nodeId];
1709
+ if (command.type === "updateEntities")
1710
+ return command.updates.map((update) => update.id);
1711
+ return [];
1712
+ }
1207
1713
  function createDeleteSelectionPatch(state) {
1208
- return createDeleteEntitiesPatch(expandDeletedIds(state, state.selection.ids));
1714
+ const candidates = state.selection.ids.filter((id) => hasEntity(state, id) && !isEntityNonDeletable(state, id) && !isEntityLockedOrReadOnly(state, id));
1715
+ const safe = candidates.filter((id) => {
1716
+ const node = state.entities.nodesById.get(id);
1717
+ if (node) {
1718
+ if ([...state.entities.portsById.values()].some((port) => port.nodeId === id && (isEntityNonDeletable(state, port.id) || isEntityLockedOrReadOnly(state, port.id))))
1719
+ return false;
1720
+ if ([...state.entities.edgesById.values()].some((edge) => (endpointDeleted(edge.source, new Set([id])) || endpointDeleted(edge.target, new Set([id]))) && (isEntityNonDeletable(state, edge.id) || isEntityLockedOrReadOnly(state, edge.id))))
1721
+ return false;
1722
+ }
1723
+ return true;
1724
+ });
1725
+ const deleted = expandDeletedIds(state, safe);
1726
+ return deleted.length ? createDeleteEntitiesPatch(deleted) : null;
1209
1727
  }
1210
1728
  function createDeleteEntitiesPatch(ids) {
1211
1729
  let deleted = null;
1730
+ let deletedOrder = null;
1731
+ let deletedPortOrder = null;
1732
+ let deletedPortOwners = new Map();
1212
1733
  const patch = {
1734
+ orderChanged: true,
1213
1735
  apply: (next) => {
1736
+ var _a;
1214
1737
  const changed = new Set();
1738
+ deletedOrder = cloneOrder(next.order);
1739
+ deletedPortOrder = [...next.entities.portsById.keys()];
1740
+ deletedPortOwners = new Map();
1741
+ for (const id of ids) {
1742
+ const port = next.entities.portsById.get(id);
1743
+ const owner = port && next.entities.nodesById.get(port.nodeId);
1744
+ if (port && owner) {
1745
+ deletedPortOwners.set(owner.id, owner);
1746
+ next.entities.nodesById.set(owner.id, { ...owner, portIds: ((_a = owner.portIds) !== null && _a !== void 0 ? _a : []).filter((portId) => portId !== id) });
1747
+ changed.add(owner.id);
1748
+ }
1749
+ }
1215
1750
  deleted = serializeScene({
1216
1751
  entities: {
1217
1752
  nodesById: pick(next.entities.nodesById, ids),
@@ -1239,11 +1774,21 @@ function createDeleteEntitiesPatch(ids) {
1239
1774
  return changed;
1240
1775
  },
1241
1776
  inverse: {
1777
+ orderChanged: true,
1242
1778
  apply: (next) => {
1243
1779
  if (!deleted) {
1244
1780
  return new Set();
1245
1781
  }
1246
- return restoreSerialized(next, deleted);
1782
+ const restored = restoreSerialized(next, deleted);
1783
+ for (const [id, node] of deletedPortOwners) {
1784
+ next.entities.nodesById.set(id, node);
1785
+ restored.add(id);
1786
+ }
1787
+ if (deletedOrder)
1788
+ next.order = cloneOrder(deletedOrder);
1789
+ if (deletedPortOrder)
1790
+ next.entities.portsById = new Map(deletedPortOrder.flatMap((id) => { const port = next.entities.portsById.get(id); return port ? [[id, port]] : []; }));
1791
+ return restored;
1247
1792
  },
1248
1793
  inverse: undefined,
1249
1794
  },
@@ -1256,6 +1801,7 @@ function createSelectionPatch(previous, selection, mode = "replace") {
1256
1801
  return null;
1257
1802
  }
1258
1803
  return {
1804
+ documentChanged: false,
1259
1805
  apply: (next) => {
1260
1806
  next.selection = nextSelection;
1261
1807
  return new Set([...previous.ids, ...nextSelection.ids, "selection"]);
@@ -1307,6 +1853,7 @@ function createViewportPatch(previous, viewport) {
1307
1853
  return null;
1308
1854
  }
1309
1855
  return {
1856
+ documentChanged: false,
1310
1857
  apply: (next) => {
1311
1858
  next.viewport = nextViewport;
1312
1859
  return new Set(["viewport"]);
@@ -1322,6 +1869,7 @@ function createViewportPatch(previous, viewport) {
1322
1869
  }
1323
1870
  function createReplaceScenePatch(next, previous) {
1324
1871
  return {
1872
+ orderChanged: true,
1325
1873
  apply: (state) => {
1326
1874
  const previousIds = allEntityIds(state);
1327
1875
  const replacement = createInternalState(next);
@@ -1366,7 +1914,7 @@ function expandDeletedIds(state, ids) {
1366
1914
  for (const id of [...deleted]) {
1367
1915
  if (state.entities.nodesById.has(id)) {
1368
1916
  for (const port of state.entities.portsById.values()) {
1369
- if (port.nodeId === id) {
1917
+ if (port.nodeId === id && !isEntityNonDeletable(state, port.id) && !isEntityLockedOrReadOnly(state, port.id)) {
1370
1918
  deleted.add(port.id);
1371
1919
  }
1372
1920
  }
@@ -1376,7 +1924,7 @@ function expandDeletedIds(state, ids) {
1376
1924
  if (deleted.has(edge.id)) {
1377
1925
  continue;
1378
1926
  }
1379
- if (endpointDeleted(edge.source, deleted) || endpointDeleted(edge.target, deleted)) {
1927
+ if ((endpointDeleted(edge.source, deleted) || endpointDeleted(edge.target, deleted)) && !isEntityNonDeletable(state, edge.id) && !isEntityLockedOrReadOnly(state, edge.id)) {
1380
1928
  deleted.add(edge.id);
1381
1929
  }
1382
1930
  }
@@ -1398,6 +1946,8 @@ function composePatches(first, second) {
1398
1946
  ...((_b = second.steps) !== null && _b !== void 0 ? _b : [second]),
1399
1947
  ];
1400
1948
  return {
1949
+ documentChanged: first.documentChanged !== false || second.documentChanged !== false,
1950
+ orderChanged: first.orderChanged === true || second.orderChanged === true,
1401
1951
  apply: (state) => {
1402
1952
  const changed = new Set();
1403
1953
  for (const step of steps) {
@@ -1584,6 +2134,14 @@ function addDependency(index, ownerId, dependentId) {
1584
2134
  }
1585
2135
  dependents.add(dependentId);
1586
2136
  }
2137
+ function removeDependency(index, ownerId, dependentId) {
2138
+ const dependents = index.get(ownerId);
2139
+ if (!dependents)
2140
+ return;
2141
+ dependents.delete(dependentId);
2142
+ if (!dependents.size)
2143
+ index.delete(ownerId);
2144
+ }
1587
2145
  function hitDistanceForGeometry(geometry, point, radius) {
1588
2146
  var _a, _b;
1589
2147
  if (geometry.kind === "edge") {