@affino/diagram-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +133 -0
  2. package/dist/DiagramEngine.d.ts +72 -0
  3. package/dist/DiagramEngine.d.ts.map +1 -0
  4. package/dist/DiagramEngine.js +1545 -0
  5. package/dist/geometry.d.ts +14 -0
  6. package/dist/geometry.d.ts.map +1 -0
  7. package/dist/geometry.js +131 -0
  8. package/dist/index.d.ts +6 -0
  9. package/dist/index.d.ts.map +1 -0
  10. package/dist/index.js +4 -0
  11. package/dist/interaction.d.ts +48 -0
  12. package/dist/interaction.d.ts.map +1 -0
  13. package/dist/interaction.js +462 -0
  14. package/dist/internal/DiagramClipboardService.d.ts +10 -0
  15. package/dist/internal/DiagramClipboardService.d.ts.map +1 -0
  16. package/dist/internal/DiagramClipboardService.js +103 -0
  17. package/dist/internal/DiagramGeometryService.d.ts +9 -0
  18. package/dist/internal/DiagramGeometryService.d.ts.map +1 -0
  19. package/dist/internal/DiagramGeometryService.js +38 -0
  20. package/dist/internal/DiagramHistory.d.ts +15 -0
  21. package/dist/internal/DiagramHistory.d.ts.map +1 -0
  22. package/dist/internal/DiagramHistory.js +53 -0
  23. package/dist/internal/DiagramSceneStore.d.ts +18 -0
  24. package/dist/internal/DiagramSceneStore.d.ts.map +1 -0
  25. package/dist/internal/DiagramSceneStore.js +159 -0
  26. package/dist/internal/DiagramSpatialIndex.d.ts +13 -0
  27. package/dist/internal/DiagramSpatialIndex.d.ts.map +1 -0
  28. package/dist/internal/DiagramSpatialIndex.js +51 -0
  29. package/dist/internal/DiagramViewportService.d.ts +5 -0
  30. package/dist/internal/DiagramViewportService.d.ts.map +1 -0
  31. package/dist/internal/DiagramViewportService.js +16 -0
  32. package/dist/internal/model.d.ts +43 -0
  33. package/dist/internal/model.d.ts.map +1 -0
  34. package/dist/internal/model.js +2 -0
  35. package/dist/spatialIndex.d.ts +12 -0
  36. package/dist/spatialIndex.d.ts.map +1 -0
  37. package/dist/spatialIndex.js +71 -0
  38. package/dist/types.d.ts +337 -0
  39. package/dist/types.d.ts.map +1 -0
  40. package/dist/types.js +1 -0
  41. package/package.json +44 -0
@@ -0,0 +1,1545 @@
1
+ import { createEntityGeometry, distance, rectContainsPoint, rectIntersects } from "./geometry.js";
2
+ import { DiagramClipboardService } from "./internal/DiagramClipboardService.js";
3
+ import { DiagramGeometryService } from "./internal/DiagramGeometryService.js";
4
+ import { DiagramHistory } from "./internal/DiagramHistory.js";
5
+ import { DiagramSceneStore, createInternalState } from "./internal/DiagramSceneStore.js";
6
+ import { DiagramSpatialIndex } from "./internal/DiagramSpatialIndex.js";
7
+ import { DiagramViewportService } from "./internal/DiagramViewportService.js";
8
+ import { EMPTY_SELECTION } from "./internal/model.js";
9
+ export class DiagramEngine {
10
+ constructor(initialScene = {}) {
11
+ Object.defineProperty(this, "store", {
12
+ enumerable: true,
13
+ configurable: true,
14
+ writable: true,
15
+ value: void 0
16
+ });
17
+ Object.defineProperty(this, "state", {
18
+ enumerable: true,
19
+ configurable: true,
20
+ writable: true,
21
+ value: void 0
22
+ });
23
+ Object.defineProperty(this, "geometryService", {
24
+ enumerable: true,
25
+ configurable: true,
26
+ writable: true,
27
+ value: new DiagramGeometryService()
28
+ });
29
+ Object.defineProperty(this, "spatialIndex", {
30
+ enumerable: true,
31
+ configurable: true,
32
+ writable: true,
33
+ value: new DiagramSpatialIndex()
34
+ });
35
+ Object.defineProperty(this, "history", {
36
+ enumerable: true,
37
+ configurable: true,
38
+ writable: true,
39
+ value: new DiagramHistory()
40
+ });
41
+ Object.defineProperty(this, "viewportService", {
42
+ enumerable: true,
43
+ configurable: true,
44
+ writable: true,
45
+ value: new DiagramViewportService()
46
+ });
47
+ Object.defineProperty(this, "clipboardService", {
48
+ enumerable: true,
49
+ configurable: true,
50
+ writable: true,
51
+ value: new DiagramClipboardService()
52
+ });
53
+ Object.defineProperty(this, "visibleQueryCount", {
54
+ enumerable: true,
55
+ configurable: true,
56
+ writable: true,
57
+ value: 0
58
+ });
59
+ Object.defineProperty(this, "entityQueryCount", {
60
+ enumerable: true,
61
+ configurable: true,
62
+ writable: true,
63
+ value: 0
64
+ });
65
+ Object.defineProperty(this, "hitTestCount", {
66
+ enumerable: true,
67
+ configurable: true,
68
+ writable: true,
69
+ value: 0
70
+ });
71
+ Object.defineProperty(this, "lastCommandMs", {
72
+ enumerable: true,
73
+ configurable: true,
74
+ writable: true,
75
+ value: 0
76
+ });
77
+ this.store = new DiagramSceneStore(initialScene);
78
+ this.state = this.store.state;
79
+ this.ensureIndexes();
80
+ }
81
+ getScene() {
82
+ return this.store.getSnapshot();
83
+ }
84
+ getLastChange() {
85
+ return this.store.getLastChange();
86
+ }
87
+ getEntityVersion(id) {
88
+ var _a;
89
+ return (_a = this.state.versions.get(id)) !== null && _a !== void 0 ? _a : 0;
90
+ }
91
+ getGeometryReadCount() {
92
+ return this.geometryService.getReadCount();
93
+ }
94
+ getGeometrySnapshot(id) {
95
+ return this.getGeometry(id);
96
+ }
97
+ dispatch(command) {
98
+ var _a;
99
+ const startedAt = now();
100
+ let result;
101
+ if (command.type === "undo") {
102
+ result = this.undo();
103
+ this.lastCommandMs = now() - startedAt;
104
+ return result;
105
+ }
106
+ if (command.type === "redo") {
107
+ result = this.redo();
108
+ this.lastCommandMs = now() - startedAt;
109
+ return result;
110
+ }
111
+ const patch = this.createPatch(command);
112
+ if (!patch) {
113
+ this.lastCommandMs = now() - startedAt;
114
+ return { changed: false, revision: this.state.revision };
115
+ }
116
+ const transaction = this.commitPatch(patch, true, "historyKey" in command ? (_a = command.historyKey) !== null && _a !== void 0 ? _a : null : null);
117
+ result = { changed: transaction.changedIds.size > 0, revision: this.state.revision };
118
+ this.lastCommandMs = now() - startedAt;
119
+ return result;
120
+ }
121
+ transact(mutator) {
122
+ const next = mutator(this.store.getSnapshot());
123
+ const patch = createReplaceScenePatch(next, serializeScene(this.store.getSnapshot()));
124
+ const result = this.commitPatch(patch, false, null);
125
+ return { changed: result.changedIds.size > 0, revision: this.state.revision };
126
+ }
127
+ queryVisible(bounds) {
128
+ this.visibleQueryCount += 1;
129
+ this.ensureIndexes();
130
+ const ids = this.spatialIndex.queryVisible(bounds);
131
+ const order = this.createOrderIndex();
132
+ return ids.sort((a, b) => { var _a, _b; return ((_a = order.get(a)) !== null && _a !== void 0 ? _a : 0) - ((_b = order.get(b)) !== null && _b !== void 0 ? _b : 0); });
133
+ }
134
+ queryVisibleBruteForce(bounds) {
135
+ const order = this.createOrderedIds();
136
+ return order.filter((id) => {
137
+ const geometry = this.getGeometry(id);
138
+ return geometry ? rectIntersects(geometry.bounds, bounds) : false;
139
+ });
140
+ }
141
+ queryEntities(options = {}) {
142
+ var _a, _b;
143
+ this.entityQueryCount += 1;
144
+ this.ensureIndexes();
145
+ const kinds = options.kinds ? new Set(options.kinds) : null;
146
+ const includePorts = options.includePorts === true || (kinds === null || kinds === void 0 ? void 0 : kinds.has("port")) === true;
147
+ const normalizedText = normalizeSearchText(options.text);
148
+ const metadata = (_a = options.metadata) !== null && _a !== void 0 ? _a : null;
149
+ const order = this.createOrderIndex();
150
+ const sourceIds = options.bounds ? this.spatialIndex.queryVisible(options.bounds) : this.createOrderedIds();
151
+ const result = [];
152
+ const seen = new Set();
153
+ for (const id of sourceIds.sort((a, b) => { var _a, _b; return ((_a = order.get(a)) !== null && _a !== void 0 ? _a : 0) - ((_b = order.get(b)) !== null && _b !== void 0 ? _b : 0); })) {
154
+ if (seen.has(id)) {
155
+ continue;
156
+ }
157
+ seen.add(id);
158
+ const kind = this.getEntityKind(id);
159
+ if (!kind || (!includePorts && kind === "port") || (kinds && !kinds.has(kind))) {
160
+ continue;
161
+ }
162
+ const geometry = this.getGeometry(id);
163
+ if (!geometry) {
164
+ continue;
165
+ }
166
+ if (options.bounds && !geometryMatchesBounds(geometry.bounds, options.bounds, (_b = options.boundsMode) !== null && _b !== void 0 ? _b : "intersects")) {
167
+ continue;
168
+ }
169
+ if (normalizedText && !entityMatchesText(id, this.state, normalizedText)) {
170
+ continue;
171
+ }
172
+ if (metadata && !entityMatchesMetadata(this.getEntityMetadata(id), metadata)) {
173
+ continue;
174
+ }
175
+ result.push(id);
176
+ if (options.limit !== undefined && result.length >= options.limit) {
177
+ break;
178
+ }
179
+ }
180
+ return result;
181
+ }
182
+ hitTest(point, options = {}) {
183
+ var _a, _b;
184
+ this.hitTestCount += 1;
185
+ this.ensureIndexes();
186
+ const radius = (_a = options.radius) !== null && _a !== void 0 ? _a : 0;
187
+ const kinds = options.kinds ? new Set(options.kinds) : null;
188
+ const rect = { x: point.x - radius, y: point.y - radius, width: radius * 2, height: radius * 2 };
189
+ const renderOrder = this.createOrderIndex();
190
+ const candidates = this.spatialIndex.queryHit(rect).sort((a, b) => { var _a, _b; return ((_a = renderOrder.get(b)) !== null && _a !== void 0 ? _a : 0) - ((_b = renderOrder.get(a)) !== null && _b !== void 0 ? _b : 0); });
191
+ let best = null;
192
+ let bestOrder = -1;
193
+ for (const id of candidates) {
194
+ const geometry = this.getGeometry(id);
195
+ if (!geometry || (kinds && !kinds.has(geometry.kind))) {
196
+ continue;
197
+ }
198
+ const hitDistance = hitDistanceForGeometry(geometry, point, radius);
199
+ if (hitDistance === null) {
200
+ continue;
201
+ }
202
+ const order = (_b = renderOrder.get(id)) !== null && _b !== void 0 ? _b : 0;
203
+ if (!best || hitDistance < best.distance || (hitDistance === best.distance && order > bestOrder)) {
204
+ best = { id, kind: geometry.kind, distance: hitDistance };
205
+ bestOrder = order;
206
+ }
207
+ }
208
+ return best;
209
+ }
210
+ nearestPort(point, radius, exclude = new Set()) {
211
+ this.ensureIndexes();
212
+ const rect = { x: point.x - radius, y: point.y - radius, width: radius * 2, height: radius * 2 };
213
+ let best = null;
214
+ for (const id of this.spatialIndex.queryPorts(rect)) {
215
+ if (exclude.has(id)) {
216
+ continue;
217
+ }
218
+ const geometry = this.getGeometry(id);
219
+ if (!(geometry === null || geometry === void 0 ? void 0 : geometry.point)) {
220
+ continue;
221
+ }
222
+ const portDistance = distance(point, geometry.point);
223
+ if (portDistance <= radius && (!best || portDistance < best.distance)) {
224
+ best = { id, kind: "port", distance: portDistance };
225
+ }
226
+ }
227
+ return best;
228
+ }
229
+ nearestPortBruteForce(point, radius, exclude = new Set()) {
230
+ let best = null;
231
+ for (const id of this.state.entities.portsById.keys()) {
232
+ if (exclude.has(id)) {
233
+ continue;
234
+ }
235
+ const geometry = this.getGeometry(id);
236
+ if (!(geometry === null || geometry === void 0 ? void 0 : geometry.point)) {
237
+ continue;
238
+ }
239
+ const portDistance = distance(point, geometry.point);
240
+ if (portDistance <= radius && (!best || portDistance < best.distance)) {
241
+ best = { id, kind: "port", distance: portDistance };
242
+ }
243
+ }
244
+ return best;
245
+ }
246
+ snapPoint(point, context = {}) {
247
+ var _a, _b, _c, _d;
248
+ const custom = (_a = context.custom) === null || _a === void 0 ? void 0 : _a.call(context, point);
249
+ if (custom) {
250
+ return { point: custom, snapped: true, source: "custom" };
251
+ }
252
+ const port = this.nearestPort(point, (_b = context.radius) !== null && _b !== void 0 ? _b : 12, (_c = context.excludeIds) !== null && _c !== void 0 ? _c : new Set());
253
+ if (port) {
254
+ const geometry = this.getGeometry(port.id);
255
+ if (geometry === null || geometry === void 0 ? void 0 : geometry.point) {
256
+ return { point: geometry.point, snapped: true, source: "port" };
257
+ }
258
+ }
259
+ const aligned = this.snapToAlignment(point, (_d = context.radius) !== null && _d !== void 0 ? _d : 6);
260
+ if (aligned) {
261
+ return { point: aligned, snapped: true, source: "alignment" };
262
+ }
263
+ if (context.angleConstraint && context.angleConstraint > 0) {
264
+ return { point: constrainAngle(point, context.angleConstraint), snapped: true, source: "angle" };
265
+ }
266
+ if (context.gridSize && context.gridSize > 0) {
267
+ return {
268
+ point: {
269
+ x: Math.round(point.x / context.gridSize) * context.gridSize,
270
+ y: Math.round(point.y / context.gridSize) * context.gridSize,
271
+ },
272
+ snapped: true,
273
+ source: "grid",
274
+ };
275
+ }
276
+ return { point, snapped: false, source: null };
277
+ }
278
+ snapTranslation(selection, delta, context = {}) {
279
+ var _a;
280
+ const primaryId = (_a = selection.primaryId) !== null && _a !== void 0 ? _a : selection.ids[0];
281
+ const geometry = primaryId ? this.getGeometry(primaryId) : null;
282
+ const origin = geometry ? { x: geometry.bounds.x, y: geometry.bounds.y } : { x: 0, y: 0 };
283
+ const snapped = this.snapPoint({ x: origin.x + delta.x, y: origin.y + delta.y }, context);
284
+ return {
285
+ point: { x: snapped.point.x - origin.x, y: snapped.point.y - origin.y },
286
+ snapped: snapped.snapped,
287
+ source: snapped.source,
288
+ };
289
+ }
290
+ canUndo() {
291
+ return this.history.canUndo();
292
+ }
293
+ canRedo() {
294
+ return this.history.canRedo();
295
+ }
296
+ canDelete(ids = this.state.selection.ids) {
297
+ return ids.some((id) => this.hasEntity(id) && !this.isEntityNonDeletable(id) && !this.isEntityLockedOrReadOnly(id));
298
+ }
299
+ canMove(ids = this.state.selection.ids) {
300
+ return ids.some((id) => this.hasEntity(id) && !this.isEntityLockedOrReadOnly(id));
301
+ }
302
+ canResize(ids = this.state.selection.ids) {
303
+ 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)));
304
+ }
305
+ canRotate(ids = this.state.selection.ids) {
306
+ return this.canResize(ids);
307
+ }
308
+ canAlign(ids = this.state.selection.ids) {
309
+ return ids.filter((id) => !this.isEntityLockedOrReadOnly(id) && (this.state.entities.nodesById.has(id) || this.state.entities.shapesById.has(id) || this.state.entities.textsById.has(id))).length >= 2;
310
+ }
311
+ canEditText(id = this.state.selection.primaryId) {
312
+ return Boolean(id && this.state.entities.textsById.has(id) && !this.isEntityLockedOrReadOnly(id));
313
+ }
314
+ canPaste(clipboard) {
315
+ return Boolean(clipboard && (clipboard.nodes.length || clipboard.edges.length || clipboard.texts.length || clipboard.shapes.length || clipboard.ports.length));
316
+ }
317
+ getDiagnostics() {
318
+ return {
319
+ revision: this.state.revision,
320
+ visibleQueryCount: this.visibleQueryCount,
321
+ entityQueryCount: this.entityQueryCount,
322
+ hitTestCount: this.hitTestCount,
323
+ geometryRecomputeCount: this.geometryService.getReadCount(),
324
+ lastCommandMs: this.lastCommandMs,
325
+ undoDepth: this.history.undoDepth(),
326
+ redoDepth: this.history.redoDepth(),
327
+ };
328
+ }
329
+ getRenderOrder(options = {}) {
330
+ const ids = this.createOrderedIds().filter((id) => options.includePorts || !this.state.entities.portsById.has(id));
331
+ return ids.sort((a, b) => layerRank(this.getEntityMetadata(a)) - layerRank(this.getEntityMetadata(b)));
332
+ }
333
+ exportSelection() {
334
+ return this.clipboardService.exportSubgraph(this.state, this.state.selection.ids, normalizeSelection);
335
+ }
336
+ importClipboard(clipboard, offset = { x: 24, y: 24 }) {
337
+ return this.dispatch({ type: "pasteClipboard", clipboard, offset });
338
+ }
339
+ duplicateSelection(offset = { x: 24, y: 24 }) {
340
+ return this.dispatch({ type: "duplicateSelection", offset });
341
+ }
342
+ dispatchKeyboardCommand(command, options = {}) {
343
+ return this.dispatch({ type: "keyboard", command, options });
344
+ }
345
+ fitBounds(bounds, padding = 24) {
346
+ return this.dispatch({ type: "setViewport", viewport: this.viewportService.fitBounds(this.state.viewport, bounds, padding) });
347
+ }
348
+ fitSelection(padding = 24) {
349
+ const bounds = boundsForIds(this, this.state.selection.ids);
350
+ return bounds ? this.fitBounds(bounds, padding) : { changed: false, revision: this.state.revision };
351
+ }
352
+ fitScene(padding = 24) {
353
+ const bounds = boundsForIds(this, this.createOrderedIds());
354
+ return bounds ? this.fitBounds(bounds, padding) : { changed: false, revision: this.state.revision };
355
+ }
356
+ subscribe(listener) {
357
+ return this.store.subscribe(listener);
358
+ }
359
+ serialize() {
360
+ return serializeScene(this.store.getSnapshot());
361
+ }
362
+ undo() {
363
+ const entry = this.history.popUndo();
364
+ if (!entry) {
365
+ return { changed: false, revision: this.state.revision };
366
+ }
367
+ const result = this.commitPatch(entry.inverse, false, null);
368
+ this.history.pushRedo(entry);
369
+ return { changed: result.changedIds.size > 0, revision: this.state.revision };
370
+ }
371
+ redo() {
372
+ const entry = this.history.popRedo();
373
+ if (!entry) {
374
+ return { changed: false, revision: this.state.revision };
375
+ }
376
+ const result = this.commitPatch(entry.patch, false, null);
377
+ this.history.pushUndo(entry);
378
+ return { changed: result.changedIds.size > 0, revision: this.state.revision };
379
+ }
380
+ commitPatch(patch, recordHistory, historyKey) {
381
+ var _a;
382
+ const changedIds = patch.apply(this.state);
383
+ if (!changedIds.size) {
384
+ return { changedIds, invalidatedIds: new Set() };
385
+ }
386
+ const invalidatedIds = this.collectInvalidatedIds(changedIds);
387
+ for (const id of invalidatedIds) {
388
+ this.state.versions.set(id, ((_a = this.state.versions.get(id)) !== null && _a !== void 0 ? _a : 0) + 1);
389
+ }
390
+ this.state.revision += 1;
391
+ this.geometryService.invalidate(invalidatedIds);
392
+ this.spatialIndex.markDirty();
393
+ this.store.publish(changedIds, invalidatedIds);
394
+ if (recordHistory) {
395
+ this.history.record(patch, historyKey, composePatches);
396
+ }
397
+ return { changedIds, invalidatedIds };
398
+ }
399
+ collectInvalidatedIds(changedIds) {
400
+ const invalidated = new Set(changedIds);
401
+ for (const id of changedIds) {
402
+ if (this.state.entities.nodesById.has(id)) {
403
+ for (const port of this.state.entities.portsById.values()) {
404
+ if (port.nodeId === id) {
405
+ invalidated.add(port.id);
406
+ }
407
+ }
408
+ for (const edge of this.state.entities.edgesById.values()) {
409
+ if (edgeReferencesNode(edge, id, this.state.entities.portsById)) {
410
+ invalidated.add(edge.id);
411
+ }
412
+ }
413
+ }
414
+ if (this.state.entities.portsById.has(id)) {
415
+ for (const edge of this.state.entities.edgesById.values()) {
416
+ if (edge.source.kind === "port" && edge.source.portId === id) {
417
+ invalidated.add(edge.id);
418
+ }
419
+ if (edge.target.kind === "port" && edge.target.portId === id) {
420
+ invalidated.add(edge.id);
421
+ }
422
+ }
423
+ }
424
+ }
425
+ return invalidated;
426
+ }
427
+ getGeometry(id) {
428
+ var _a;
429
+ return this.geometryService.get(id, this.store.getSnapshot().entities, (_a = this.state.versions.get(id)) !== null && _a !== void 0 ? _a : 0);
430
+ }
431
+ rebuildIndexGeometries() {
432
+ return this.createOrderedIds()
433
+ .map((id) => this.getGeometry(id))
434
+ .filter((geometry) => geometry !== null);
435
+ }
436
+ ensureIndexes() {
437
+ this.spatialIndex.ensure(() => this.rebuildIndexGeometries());
438
+ }
439
+ createPatch(command) {
440
+ var _a, _b, _c, _d;
441
+ switch (command.type) {
442
+ case "moveEntities":
443
+ return createMovePatch(this.state, command.ids, command.delta);
444
+ case "moveNode":
445
+ return createMovePatch(this.state, [command.id], command.delta);
446
+ case "moveEdgeEndpoint":
447
+ return createMoveEdgeEndpointPatch(this.state, command.id, command.endpoint, command.point);
448
+ case "insertEdgeWaypoint":
449
+ return createEdgeWaypointPatch(this.state, command.id, command.index, command.point, "insert");
450
+ case "moveEdgeWaypoint":
451
+ return createEdgeWaypointPatch(this.state, command.id, command.index, command.point, "move");
452
+ case "removeEdgeWaypoint":
453
+ return createEdgeWaypointPatch(this.state, command.id, command.index, null, "remove");
454
+ case "createEdge":
455
+ return createCreateEdgePatch(this.state, command.edge);
456
+ case "deleteSelection":
457
+ return createDeleteSelectionPatch(this.state);
458
+ case "duplicateSelection":
459
+ 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);
460
+ case "pasteClipboard":
461
+ return this.clipboardService.createPastePatch(this.state, command.clipboard, (_b = command.offset) !== null && _b !== void 0 ? _b : { x: 24, y: 24 }, createDeleteEntitiesPatch, normalizeSelection);
462
+ case "resizeEntities":
463
+ return createResizePatch(this.state, command.entries);
464
+ case "rotateEntities":
465
+ return createRotatePatch(this.state, command.entries);
466
+ case "alignEntities":
467
+ return createAlignPatch(this.state, command.ids, command.edge);
468
+ case "bringForward":
469
+ return createOrderPatch(this.state, command.ids, "forward");
470
+ case "sendBackward":
471
+ return createOrderPatch(this.state, command.ids, "backward");
472
+ case "bringToFront":
473
+ return createOrderPatch(this.state, command.ids, "front");
474
+ case "sendToBack":
475
+ return createOrderPatch(this.state, command.ids, "back");
476
+ case "setLayer":
477
+ return createLayerPatch(this.state, command.ids, command.layer, command.layerRole);
478
+ case "keyboard":
479
+ return createKeyboardPatch(this.state, command.command, (_c = command.options) !== null && _c !== void 0 ? _c : {});
480
+ case "setSelection":
481
+ return createSelectionPatch(this.state.selection, command.selection, (_d = command.mode) !== null && _d !== void 0 ? _d : "replace");
482
+ case "editText":
483
+ return createEditTextPatch(this.state, command.id, command.text);
484
+ case "setViewport":
485
+ return createViewportPatch(this.state.viewport, command.viewport);
486
+ }
487
+ }
488
+ snapToAlignment(point, radius) {
489
+ for (const id of this.state.order.nodeIds) {
490
+ const geometry = this.getGeometry(id);
491
+ if (!geometry) {
492
+ continue;
493
+ }
494
+ const center = { x: geometry.bounds.x + geometry.bounds.width / 2, y: geometry.bounds.y + geometry.bounds.height / 2 };
495
+ if (Math.abs(center.x - point.x) <= radius) {
496
+ return { x: center.x, y: point.y };
497
+ }
498
+ if (Math.abs(center.y - point.y) <= radius) {
499
+ return { x: point.x, y: center.y };
500
+ }
501
+ }
502
+ return null;
503
+ }
504
+ createOrderedIds() {
505
+ const ids = [
506
+ ...this.state.order.edgeIds,
507
+ ...this.state.order.shapeIds,
508
+ ...this.state.order.nodeIds,
509
+ ...this.state.order.textIds,
510
+ ...this.state.entities.portsById.keys(),
511
+ ];
512
+ const baseOrder = new Map(ids.map((id, index) => [id, index]));
513
+ return ids.sort((a, b) => {
514
+ var _a, _b;
515
+ const layerDelta = layerRank(this.getEntityMetadata(a)) - layerRank(this.getEntityMetadata(b));
516
+ if (layerDelta) {
517
+ return layerDelta;
518
+ }
519
+ const zDelta = zIndex(this.getEntityMetadata(a)) - zIndex(this.getEntityMetadata(b));
520
+ return zDelta || (((_a = baseOrder.get(a)) !== null && _a !== void 0 ? _a : 0) - ((_b = baseOrder.get(b)) !== null && _b !== void 0 ? _b : 0));
521
+ });
522
+ }
523
+ createOrderIndex() {
524
+ return new Map(this.createOrderedIds().map((id, index) => [id, index]));
525
+ }
526
+ hasEntity(id) {
527
+ return hasEntity(this.state, id);
528
+ }
529
+ getEntityKind(id) {
530
+ if (this.state.entities.nodesById.has(id))
531
+ return "node";
532
+ if (this.state.entities.edgesById.has(id))
533
+ return "edge";
534
+ if (this.state.entities.textsById.has(id))
535
+ return "text";
536
+ if (this.state.entities.shapesById.has(id))
537
+ return "shape";
538
+ if (this.state.entities.portsById.has(id))
539
+ return "port";
540
+ return null;
541
+ }
542
+ getEntityMetadata(id) {
543
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
544
+ return (_h = (_f = (_d = (_b = (_a = this.state.entities.nodesById.get(id)) === null || _a === void 0 ? void 0 : _a.metadata) !== null && _b !== void 0 ? _b : (_c = this.state.entities.edgesById.get(id)) === null || _c === void 0 ? void 0 : _c.metadata) !== null && _d !== void 0 ? _d : (_e = this.state.entities.textsById.get(id)) === null || _e === void 0 ? void 0 : _e.metadata) !== null && _f !== void 0 ? _f : (_g = this.state.entities.shapesById.get(id)) === null || _g === void 0 ? void 0 : _g.metadata) !== null && _h !== void 0 ? _h : (_j = this.state.entities.portsById.get(id)) === null || _j === void 0 ? void 0 : _j.metadata;
545
+ }
546
+ isEntityLockedOrReadOnly(id) {
547
+ const metadata = this.getEntityMetadata(id);
548
+ return (metadata === null || metadata === void 0 ? void 0 : metadata.locked) === true || (metadata === null || metadata === void 0 ? void 0 : metadata.readOnly) === true;
549
+ }
550
+ isEntityNonDeletable(id) {
551
+ var _a;
552
+ return ((_a = this.getEntityMetadata(id)) === null || _a === void 0 ? void 0 : _a.nonDeletable) === true;
553
+ }
554
+ }
555
+ function geometryMatchesBounds(candidate, bounds, mode) {
556
+ return mode === "contains" ? rectContainsRect(bounds, candidate) : rectIntersects(candidate, bounds);
557
+ }
558
+ function rectContainsRect(container, candidate) {
559
+ return candidate.x >= container.x
560
+ && candidate.y >= container.y
561
+ && candidate.x + candidate.width <= container.x + container.width
562
+ && candidate.y + candidate.height <= container.y + container.height;
563
+ }
564
+ function normalizeSearchText(value) {
565
+ var _a;
566
+ return (_a = value === null || value === void 0 ? void 0 : value.trim().toLocaleLowerCase()) !== null && _a !== void 0 ? _a : "";
567
+ }
568
+ function entityMatchesText(id, state, normalizedText) {
569
+ var _a;
570
+ if (id.toLocaleLowerCase().includes(normalizedText)) {
571
+ return true;
572
+ }
573
+ const text = (_a = state.entities.textsById.get(id)) === null || _a === void 0 ? void 0 : _a.text;
574
+ if (text === null || text === void 0 ? void 0 : text.toLocaleLowerCase().includes(normalizedText)) {
575
+ return true;
576
+ }
577
+ return searchableMetadataValues(getEntityMetadata(state, id)).some((value) => value.toLocaleLowerCase().includes(normalizedText));
578
+ }
579
+ function searchableMetadataValues(metadata) {
580
+ if (!metadata) {
581
+ return [];
582
+ }
583
+ const values = [];
584
+ for (const value of Object.values(metadata)) {
585
+ collectSearchableValue(value, values);
586
+ }
587
+ return values;
588
+ }
589
+ function collectSearchableValue(value, values) {
590
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
591
+ values.push(String(value));
592
+ return;
593
+ }
594
+ if (Array.isArray(value)) {
595
+ for (const entry of value) {
596
+ collectSearchableValue(entry, values);
597
+ }
598
+ }
599
+ }
600
+ function entityMatchesMetadata(entityMetadata, query) {
601
+ if (!entityMetadata) {
602
+ return false;
603
+ }
604
+ for (const [key, expected] of Object.entries(query)) {
605
+ if (!metadataValueMatches(entityMetadata[key], expected)) {
606
+ return false;
607
+ }
608
+ }
609
+ return true;
610
+ }
611
+ function metadataValueMatches(actual, expected) {
612
+ if (Array.isArray(actual)) {
613
+ return actual.some((value) => Object.is(value, expected));
614
+ }
615
+ return Object.is(actual, expected);
616
+ }
617
+ export function createDiagramEngine(initialScene = {}) {
618
+ return new DiagramEngine(initialScene);
619
+ }
620
+ export function serializeScene(scene) {
621
+ return {
622
+ nodes: scene.order.nodeIds.map((id) => scene.entities.nodesById.get(id)).filter(isDefined),
623
+ edges: scene.order.edgeIds.map((id) => scene.entities.edgesById.get(id)).filter(isDefined),
624
+ texts: scene.order.textIds.map((id) => scene.entities.textsById.get(id)).filter(isDefined),
625
+ shapes: scene.order.shapeIds.map((id) => scene.entities.shapesById.get(id)).filter(isDefined),
626
+ ports: [...scene.entities.portsById.values()],
627
+ selection: scene.selection,
628
+ viewport: scene.viewport,
629
+ };
630
+ }
631
+ export function deserializeScene(scene) {
632
+ return scene;
633
+ }
634
+ function createMovePatch(state, ids, delta) {
635
+ if (delta.x === 0 && delta.y === 0) {
636
+ return null;
637
+ }
638
+ const movableIds = ids.filter((id) => !isEntityLockedOrReadOnly(state, id) && (state.entities.nodesById.has(id) || state.entities.textsById.has(id) || state.entities.shapesById.has(id)));
639
+ if (!movableIds.length) {
640
+ return null;
641
+ }
642
+ return {
643
+ apply: (next) => {
644
+ const changed = new Set();
645
+ for (const id of movableIds) {
646
+ const node = next.entities.nodesById.get(id);
647
+ if (node) {
648
+ next.entities.nodesById.set(id, { ...node, x: node.x + delta.x, y: node.y + delta.y });
649
+ changed.add(id);
650
+ continue;
651
+ }
652
+ const text = next.entities.textsById.get(id);
653
+ if (text) {
654
+ next.entities.textsById.set(id, { ...text, x: text.x + delta.x, y: text.y + delta.y });
655
+ changed.add(id);
656
+ continue;
657
+ }
658
+ const shape = next.entities.shapesById.get(id);
659
+ if (shape) {
660
+ next.entities.shapesById.set(id, { ...shape, x: shape.x + delta.x, y: shape.y + delta.y });
661
+ changed.add(id);
662
+ }
663
+ }
664
+ return changed;
665
+ },
666
+ inverse: createMovePatchUnchecked(movableIds, { x: -delta.x, y: -delta.y }),
667
+ };
668
+ }
669
+ function createMovePatchUnchecked(ids, delta) {
670
+ return {
671
+ apply: (next) => {
672
+ const changed = new Set();
673
+ for (const id of ids) {
674
+ const node = next.entities.nodesById.get(id);
675
+ if (node) {
676
+ next.entities.nodesById.set(id, { ...node, x: node.x + delta.x, y: node.y + delta.y });
677
+ changed.add(id);
678
+ }
679
+ const text = next.entities.textsById.get(id);
680
+ if (text) {
681
+ next.entities.textsById.set(id, { ...text, x: text.x + delta.x, y: text.y + delta.y });
682
+ changed.add(id);
683
+ }
684
+ const shape = next.entities.shapesById.get(id);
685
+ if (shape) {
686
+ next.entities.shapesById.set(id, { ...shape, x: shape.x + delta.x, y: shape.y + delta.y });
687
+ changed.add(id);
688
+ }
689
+ }
690
+ return changed;
691
+ },
692
+ inverse: undefined,
693
+ };
694
+ }
695
+ function createMoveEdgeEndpointPatch(state, id, endpoint, point) {
696
+ const edge = state.entities.edgesById.get(id);
697
+ if (!edge) {
698
+ return null;
699
+ }
700
+ const previous = edge[endpoint];
701
+ const nextEndpoint = { kind: "point", point };
702
+ return {
703
+ apply: (next) => {
704
+ const nextEdge = next.entities.edgesById.get(id);
705
+ if (!nextEdge) {
706
+ return new Set();
707
+ }
708
+ next.entities.edgesById.set(id, { ...nextEdge, [endpoint]: nextEndpoint });
709
+ return new Set([id]);
710
+ },
711
+ inverse: {
712
+ apply: (next) => {
713
+ const nextEdge = next.entities.edgesById.get(id);
714
+ if (!nextEdge) {
715
+ return new Set();
716
+ }
717
+ next.entities.edgesById.set(id, { ...nextEdge, [endpoint]: previous });
718
+ return new Set([id]);
719
+ },
720
+ inverse: undefined,
721
+ },
722
+ };
723
+ }
724
+ function createEdgeWaypointPatch(state, id, index, point, mode) {
725
+ var _a;
726
+ const edge = state.entities.edgesById.get(id);
727
+ if (!edge || isEntityLockedOrReadOnly(state, id)) {
728
+ return null;
729
+ }
730
+ const previousPoints = [...((_a = edge.points) !== null && _a !== void 0 ? _a : [])];
731
+ const nextPoints = [...previousPoints];
732
+ const safeIndex = Math.max(0, Math.min(index, mode === "insert" ? nextPoints.length : nextPoints.length - 1));
733
+ if (mode === "insert" && point) {
734
+ nextPoints.splice(safeIndex, 0, point);
735
+ }
736
+ else if (mode === "move" && point && nextPoints[safeIndex]) {
737
+ nextPoints[safeIndex] = point;
738
+ }
739
+ else if (mode === "remove" && nextPoints[safeIndex]) {
740
+ nextPoints.splice(safeIndex, 1);
741
+ }
742
+ else {
743
+ return null;
744
+ }
745
+ return createEdgePointsPatch(id, previousPoints, nextPoints);
746
+ }
747
+ function createEdgePointsPatch(id, previousPoints, nextPoints) {
748
+ return {
749
+ apply: (next) => {
750
+ const edge = next.entities.edgesById.get(id);
751
+ if (!edge)
752
+ return new Set();
753
+ next.entities.edgesById.set(id, { ...edge, points: [...nextPoints] });
754
+ return new Set([id]);
755
+ },
756
+ inverse: {
757
+ apply: (next) => {
758
+ const edge = next.entities.edgesById.get(id);
759
+ if (!edge)
760
+ return new Set();
761
+ next.entities.edgesById.set(id, { ...edge, points: [...previousPoints] });
762
+ return new Set([id]);
763
+ },
764
+ inverse: undefined,
765
+ },
766
+ };
767
+ }
768
+ function createResizePatch(state, entries) {
769
+ var _a, _b, _c;
770
+ const previous = new Map();
771
+ const nextEntries = [];
772
+ for (const entry of entries) {
773
+ if (isEntityLockedOrReadOnly(state, entry.id))
774
+ continue;
775
+ const node = state.entities.nodesById.get(entry.id);
776
+ const shape = state.entities.shapesById.get(entry.id);
777
+ const text = state.entities.textsById.get(entry.id);
778
+ const entity = (_a = node !== null && node !== void 0 ? node : shape) !== null && _a !== void 0 ? _a : text;
779
+ if (!entity)
780
+ continue;
781
+ previous.set(entry.id, { id: entry.id, x: entity.x, y: entity.y, width: entity.width, height: entity.height });
782
+ nextEntries.push(entry);
783
+ if (node) {
784
+ for (const port of state.entities.portsById.values()) {
785
+ if (port.nodeId !== node.id || isEntityLockedOrReadOnly(state, port.id))
786
+ continue;
787
+ const nextWidth = (_b = entry.width) !== null && _b !== void 0 ? _b : node.width;
788
+ const nextHeight = (_c = entry.height) !== null && _c !== void 0 ? _c : node.height;
789
+ const nextPort = {
790
+ id: port.id,
791
+ x: node.width === 0 ? port.x : port.x * (nextWidth / node.width),
792
+ y: node.height === 0 ? port.y : port.y * (nextHeight / node.height),
793
+ };
794
+ previous.set(port.id, { id: port.id, x: port.x, y: port.y });
795
+ nextEntries.push(nextPort);
796
+ }
797
+ }
798
+ }
799
+ if (!nextEntries.length)
800
+ return null;
801
+ return createResizePatchUnchecked(nextEntries, [...previous.values()]);
802
+ }
803
+ function createResizePatchUnchecked(entries, inverseEntries) {
804
+ return {
805
+ apply: (next) => applyResizeEntries(next, entries),
806
+ inverse: {
807
+ apply: (next) => applyResizeEntries(next, inverseEntries),
808
+ inverse: undefined,
809
+ },
810
+ };
811
+ }
812
+ function applyResizeEntries(state, entries) {
813
+ const changed = new Set();
814
+ for (const entry of entries) {
815
+ const node = state.entities.nodesById.get(entry.id);
816
+ if (node) {
817
+ state.entities.nodesById.set(entry.id, { ...node, ...definedRectPatch(entry) });
818
+ changed.add(entry.id);
819
+ continue;
820
+ }
821
+ const shape = state.entities.shapesById.get(entry.id);
822
+ if (shape) {
823
+ state.entities.shapesById.set(entry.id, { ...shape, ...definedRectPatch(entry) });
824
+ changed.add(entry.id);
825
+ continue;
826
+ }
827
+ const text = state.entities.textsById.get(entry.id);
828
+ if (text) {
829
+ state.entities.textsById.set(entry.id, { ...text, ...definedRectPatch(entry) });
830
+ changed.add(entry.id);
831
+ continue;
832
+ }
833
+ const port = state.entities.portsById.get(entry.id);
834
+ if (port) {
835
+ const patch = Object.fromEntries(Object.entries(entry).filter(([key, value]) => (key === "x" || key === "y") && value !== undefined));
836
+ state.entities.portsById.set(entry.id, { ...port, ...patch });
837
+ changed.add(entry.id);
838
+ }
839
+ }
840
+ return changed;
841
+ }
842
+ function definedRectPatch(entry) {
843
+ return Object.fromEntries(Object.entries(entry).filter(([key, value]) => key !== "id" && value !== undefined));
844
+ }
845
+ function createRotatePatch(state, entries) {
846
+ var _a, _b, _c;
847
+ const previous = [];
848
+ const nextEntries = [];
849
+ for (const entry of entries) {
850
+ if (isEntityLockedOrReadOnly(state, entry.id))
851
+ continue;
852
+ const entity = (_b = (_a = state.entities.nodesById.get(entry.id)) !== null && _a !== void 0 ? _a : state.entities.shapesById.get(entry.id)) !== null && _b !== void 0 ? _b : state.entities.textsById.get(entry.id);
853
+ if (!entity)
854
+ continue;
855
+ previous.push({ id: entry.id, rotation: (_c = entity.rotation) !== null && _c !== void 0 ? _c : 0 });
856
+ nextEntries.push({ id: entry.id, rotation: normalizeRotation(entry.rotation) });
857
+ }
858
+ if (!nextEntries.length)
859
+ return null;
860
+ return createRotatePatchUnchecked(nextEntries, previous);
861
+ }
862
+ function createRotatePatchUnchecked(entries, inverseEntries) {
863
+ return {
864
+ apply: (state) => applyRotateEntries(state, entries),
865
+ inverse: {
866
+ apply: (state) => applyRotateEntries(state, inverseEntries),
867
+ inverse: undefined,
868
+ },
869
+ };
870
+ }
871
+ function applyRotateEntries(state, entries) {
872
+ const changed = new Set();
873
+ for (const entry of entries) {
874
+ const node = state.entities.nodesById.get(entry.id);
875
+ if (node) {
876
+ state.entities.nodesById.set(entry.id, { ...node, rotation: entry.rotation });
877
+ changed.add(entry.id);
878
+ continue;
879
+ }
880
+ const shape = state.entities.shapesById.get(entry.id);
881
+ if (shape) {
882
+ state.entities.shapesById.set(entry.id, { ...shape, rotation: entry.rotation });
883
+ changed.add(entry.id);
884
+ continue;
885
+ }
886
+ const text = state.entities.textsById.get(entry.id);
887
+ if (text) {
888
+ state.entities.textsById.set(entry.id, { ...text, rotation: entry.rotation });
889
+ changed.add(entry.id);
890
+ }
891
+ }
892
+ return changed;
893
+ }
894
+ function createAlignPatch(state, ids, edge) {
895
+ const geometries = ids
896
+ .filter((id) => !isEntityLockedOrReadOnly(state, id))
897
+ .map((id) => createEntityGeometry(id, snapshotEntities(state)))
898
+ .filter((geometry) => geometry !== null && geometry.kind !== "edge" && geometry.kind !== "port");
899
+ if (geometries.length < 2)
900
+ return null;
901
+ const target = alignTarget(geometries, edge);
902
+ const entries = geometries.map((geometry) => {
903
+ const bounds = geometry.bounds;
904
+ if (edge === "left")
905
+ return { id: geometry.id, x: target };
906
+ if (edge === "centerX")
907
+ return { id: geometry.id, x: target - bounds.width / 2 };
908
+ if (edge === "right")
909
+ return { id: geometry.id, x: target - bounds.width };
910
+ if (edge === "top")
911
+ return { id: geometry.id, y: target };
912
+ if (edge === "centerY")
913
+ return { id: geometry.id, y: target - bounds.height / 2 };
914
+ return { id: geometry.id, y: target - bounds.height };
915
+ });
916
+ return createResizePatch(state, entries);
917
+ }
918
+ function alignTarget(geometries, edge) {
919
+ if (edge === "left")
920
+ return Math.min(...geometries.map((geometry) => geometry.bounds.x));
921
+ if (edge === "centerX")
922
+ return geometries[0].bounds.x + geometries[0].bounds.width / 2;
923
+ if (edge === "right")
924
+ return Math.max(...geometries.map((geometry) => geometry.bounds.x + geometry.bounds.width));
925
+ if (edge === "top")
926
+ return Math.min(...geometries.map((geometry) => geometry.bounds.y));
927
+ if (edge === "centerY")
928
+ return geometries[0].bounds.y + geometries[0].bounds.height / 2;
929
+ return Math.max(...geometries.map((geometry) => geometry.bounds.y + geometry.bounds.height));
930
+ }
931
+ function snapshotEntities(state) {
932
+ return {
933
+ nodesById: state.entities.nodesById,
934
+ edgesById: state.entities.edgesById,
935
+ textsById: state.entities.textsById,
936
+ shapesById: state.entities.shapesById,
937
+ portsById: state.entities.portsById,
938
+ };
939
+ }
940
+ function normalizeRotation(rotation) {
941
+ const normalized = rotation % 360;
942
+ return normalized < 0 ? normalized + 360 : normalized;
943
+ }
944
+ function createOrderPatch(state, ids, mode) {
945
+ const existingIds = ids.filter((id) => hasEntity(state, id));
946
+ if (!existingIds.length)
947
+ return null;
948
+ if (mode === "front" || mode === "back") {
949
+ return createZIndexPatch(state, existingIds, mode);
950
+ }
951
+ const previous = cloneOrder(state.order);
952
+ const next = cloneOrder(state.order);
953
+ reorderIds(next.nodeIds, ids, mode);
954
+ reorderIds(next.edgeIds, ids, mode);
955
+ reorderIds(next.textIds, ids, mode);
956
+ reorderIds(next.shapeIds, ids, mode);
957
+ if (ordersEqual(previous, next))
958
+ return null;
959
+ return createOrderPatchUnchecked(previous, next);
960
+ }
961
+ function createZIndexPatch(state, ids, mode) {
962
+ const orderedIds = allEntityIds(state);
963
+ const values = orderedIds.map((id) => zIndex(getEntityMetadata(state, id)));
964
+ const base = mode === "front" ? Math.max(0, ...values) : Math.min(0, ...values);
965
+ const nextMetadata = new Map();
966
+ const previousMetadata = new Map();
967
+ ids.forEach((id, index) => {
968
+ const previous = getEntityMetadata(state, id);
969
+ previousMetadata.set(id, previous);
970
+ nextMetadata.set(id, { ...(previous !== null && previous !== void 0 ? previous : {}), zIndex: mode === "front" ? base + index + 1 : base - ids.length + index });
971
+ });
972
+ return createMetadataSnapshotPatch(ids, previousMetadata, nextMetadata);
973
+ }
974
+ function createMetadataSnapshotPatch(ids, previous, nextMetadata) {
975
+ return {
976
+ apply: (state) => {
977
+ for (const id of ids)
978
+ setEntityMetadata(state, id, nextMetadata.get(id));
979
+ return new Set(ids);
980
+ },
981
+ inverse: {
982
+ apply: (state) => {
983
+ for (const id of ids)
984
+ setEntityMetadata(state, id, previous.get(id));
985
+ return new Set(ids);
986
+ },
987
+ inverse: undefined,
988
+ },
989
+ };
990
+ }
991
+ function createOrderPatchUnchecked(previous, nextOrder) {
992
+ return {
993
+ apply: (state) => {
994
+ state.order = cloneOrder(nextOrder);
995
+ return new Set([...nextOrder.nodeIds, ...nextOrder.edgeIds, ...nextOrder.textIds, ...nextOrder.shapeIds]);
996
+ },
997
+ inverse: {
998
+ apply: (state) => {
999
+ state.order = cloneOrder(previous);
1000
+ return new Set([...previous.nodeIds, ...previous.edgeIds, ...previous.textIds, ...previous.shapeIds]);
1001
+ },
1002
+ inverse: undefined,
1003
+ },
1004
+ };
1005
+ }
1006
+ function createLayerPatch(state, ids, layer, layerRole) {
1007
+ const entries = ids.filter((id) => !isEntityLockedOrReadOnly(state, id) && hasEntity(state, id));
1008
+ if (!entries.length)
1009
+ return null;
1010
+ const previous = new Map(entries.map((id) => [id, getEntityMetadata(state, id)]));
1011
+ return {
1012
+ apply: (next) => applyMetadataPatch(next, entries, { layer, layerRole }),
1013
+ inverse: {
1014
+ apply: (next) => {
1015
+ const changed = new Set();
1016
+ for (const [id, metadata] of previous) {
1017
+ setEntityMetadata(next, id, metadata);
1018
+ changed.add(id);
1019
+ }
1020
+ return changed;
1021
+ },
1022
+ inverse: undefined,
1023
+ },
1024
+ };
1025
+ }
1026
+ function createKeyboardPatch(state, command, options) {
1027
+ var _a, _b, _c;
1028
+ const step = options.shiftKey ? (_a = options.largeStep) !== null && _a !== void 0 ? _a : 10 : (_b = options.step) !== null && _b !== void 0 ? _b : 1;
1029
+ if (command === "delete")
1030
+ return createDeleteSelectionPatch(state);
1031
+ if (command === "escape")
1032
+ return createSelectionPatch(state.selection, { ids: [], primaryId: null });
1033
+ if (command === "undo" || command === "redo")
1034
+ return null;
1035
+ const deltaByCommand = {
1036
+ "nudge-left": { x: -step, y: 0 },
1037
+ "nudge-right": { x: step, y: 0 },
1038
+ "nudge-up": { x: 0, y: -step },
1039
+ "nudge-down": { x: 0, y: step },
1040
+ };
1041
+ return createMovePatch(state, state.selection.ids, (_c = deltaByCommand[command]) !== null && _c !== void 0 ? _c : { x: 0, y: 0 });
1042
+ }
1043
+ function createCreateEdgePatch(state, edge) {
1044
+ if (state.entities.edgesById.has(edge.id)) {
1045
+ return null;
1046
+ }
1047
+ return {
1048
+ apply: (next) => {
1049
+ next.entities.edgesById.set(edge.id, edge);
1050
+ next.order.edgeIds.push(edge.id);
1051
+ next.versions.set(edge.id, 0);
1052
+ return new Set([edge.id]);
1053
+ },
1054
+ inverse: createDeleteEntitiesPatch([edge.id]),
1055
+ };
1056
+ }
1057
+ function createDeleteSelectionPatch(state) {
1058
+ return createDeleteEntitiesPatch(expandDeletedIds(state, state.selection.ids));
1059
+ }
1060
+ function createDeleteEntitiesPatch(ids) {
1061
+ let deleted = null;
1062
+ const patch = {
1063
+ apply: (next) => {
1064
+ const changed = new Set();
1065
+ deleted = serializeScene({
1066
+ entities: {
1067
+ nodesById: pick(next.entities.nodesById, ids),
1068
+ edgesById: pick(next.entities.edgesById, ids),
1069
+ textsById: pick(next.entities.textsById, ids),
1070
+ shapesById: pick(next.entities.shapesById, ids),
1071
+ portsById: pick(next.entities.portsById, ids),
1072
+ },
1073
+ order: {
1074
+ nodeIds: next.order.nodeIds.filter((id) => ids.includes(id)),
1075
+ edgeIds: next.order.edgeIds.filter((id) => ids.includes(id)),
1076
+ textIds: next.order.textIds.filter((id) => ids.includes(id)),
1077
+ shapeIds: next.order.shapeIds.filter((id) => ids.includes(id)),
1078
+ },
1079
+ selection: next.selection,
1080
+ viewport: next.viewport,
1081
+ revision: next.revision,
1082
+ });
1083
+ for (const id of ids) {
1084
+ if (deleteEntity(next, id)) {
1085
+ changed.add(id);
1086
+ }
1087
+ }
1088
+ next.selection = EMPTY_SELECTION;
1089
+ return changed;
1090
+ },
1091
+ inverse: {
1092
+ apply: (next) => {
1093
+ if (!deleted) {
1094
+ return new Set();
1095
+ }
1096
+ return restoreSerialized(next, deleted);
1097
+ },
1098
+ inverse: undefined,
1099
+ },
1100
+ };
1101
+ return patch;
1102
+ }
1103
+ function createSelectionPatch(previous, selection, mode = "replace") {
1104
+ const nextSelection = normalizeSelectionByMode(previous, selection, mode);
1105
+ if (sameIds(previous.ids, nextSelection.ids) && previous.primaryId === nextSelection.primaryId) {
1106
+ return null;
1107
+ }
1108
+ return {
1109
+ apply: (next) => {
1110
+ next.selection = nextSelection;
1111
+ return new Set([...previous.ids, ...nextSelection.ids, "selection"]);
1112
+ },
1113
+ inverse: {
1114
+ apply: (next) => {
1115
+ next.selection = previous;
1116
+ return new Set([...previous.ids, ...nextSelection.ids, "selection"]);
1117
+ },
1118
+ inverse: undefined,
1119
+ },
1120
+ };
1121
+ }
1122
+ function createEditTextPatch(state, id, text) {
1123
+ const previous = state.entities.textsById.get(id);
1124
+ if (!previous || previous.text === text) {
1125
+ return null;
1126
+ }
1127
+ return {
1128
+ apply: (next) => {
1129
+ const entity = next.entities.textsById.get(id);
1130
+ if (!entity) {
1131
+ return new Set();
1132
+ }
1133
+ next.entities.textsById.set(id, { ...entity, text });
1134
+ return new Set([id]);
1135
+ },
1136
+ inverse: createEditTextPatchUnchecked(id, previous.text),
1137
+ };
1138
+ }
1139
+ function createEditTextPatchUnchecked(id, text) {
1140
+ const patch = {
1141
+ apply: (next) => {
1142
+ const entity = next.entities.textsById.get(id);
1143
+ if (!entity) {
1144
+ return new Set();
1145
+ }
1146
+ next.entities.textsById.set(id, { ...entity, text });
1147
+ return new Set([id]);
1148
+ },
1149
+ inverse: undefined,
1150
+ };
1151
+ patch.inverse = patch;
1152
+ return patch;
1153
+ }
1154
+ function createViewportPatch(previous, viewport) {
1155
+ const nextViewport = { ...previous, ...viewport };
1156
+ if (sameViewport(previous, nextViewport)) {
1157
+ return null;
1158
+ }
1159
+ return {
1160
+ apply: (next) => {
1161
+ next.viewport = nextViewport;
1162
+ return new Set(["viewport"]);
1163
+ },
1164
+ inverse: {
1165
+ apply: (next) => {
1166
+ next.viewport = previous;
1167
+ return new Set(["viewport"]);
1168
+ },
1169
+ inverse: undefined,
1170
+ },
1171
+ };
1172
+ }
1173
+ function createReplaceScenePatch(next, previous) {
1174
+ return {
1175
+ apply: (state) => {
1176
+ const replacement = createInternalState(next);
1177
+ state.entities = replacement.entities;
1178
+ state.order = replacement.order;
1179
+ state.selection = replacement.selection;
1180
+ state.viewport = replacement.viewport;
1181
+ state.versions = replacement.versions;
1182
+ return new Set([
1183
+ ...replacement.order.nodeIds,
1184
+ ...replacement.order.edgeIds,
1185
+ ...replacement.order.textIds,
1186
+ ...replacement.order.shapeIds,
1187
+ ...replacement.entities.portsById.keys(),
1188
+ ]);
1189
+ },
1190
+ inverse: {
1191
+ apply: (state) => {
1192
+ const replacement = createInternalState(previous);
1193
+ state.entities = replacement.entities;
1194
+ state.order = replacement.order;
1195
+ state.selection = replacement.selection;
1196
+ state.viewport = replacement.viewport;
1197
+ state.versions = replacement.versions;
1198
+ return new Set([
1199
+ ...replacement.order.nodeIds,
1200
+ ...replacement.order.edgeIds,
1201
+ ...replacement.order.textIds,
1202
+ ...replacement.order.shapeIds,
1203
+ ...replacement.entities.portsById.keys(),
1204
+ ]);
1205
+ },
1206
+ inverse: undefined,
1207
+ },
1208
+ };
1209
+ }
1210
+ function expandDeletedIds(state, ids) {
1211
+ const deleted = new Set(ids.filter((id) => !isEntityNonDeletable(state, id) && !isEntityLockedOrReadOnly(state, id)));
1212
+ for (const id of [...deleted]) {
1213
+ if (state.entities.nodesById.has(id)) {
1214
+ for (const port of state.entities.portsById.values()) {
1215
+ if (port.nodeId === id) {
1216
+ deleted.add(port.id);
1217
+ }
1218
+ }
1219
+ }
1220
+ }
1221
+ for (const edge of state.entities.edgesById.values()) {
1222
+ if (deleted.has(edge.id)) {
1223
+ continue;
1224
+ }
1225
+ if (endpointDeleted(edge.source, deleted) || endpointDeleted(edge.target, deleted)) {
1226
+ deleted.add(edge.id);
1227
+ }
1228
+ }
1229
+ return [...deleted];
1230
+ }
1231
+ function endpointDeleted(endpoint, deleted) {
1232
+ if (endpoint.kind === "point") {
1233
+ return false;
1234
+ }
1235
+ if (endpoint.kind === "node") {
1236
+ return deleted.has(endpoint.nodeId);
1237
+ }
1238
+ return deleted.has(endpoint.portId);
1239
+ }
1240
+ function composePatches(first, second) {
1241
+ return {
1242
+ apply: (state) => {
1243
+ const changed = first.apply(state);
1244
+ for (const id of second.apply(state)) {
1245
+ changed.add(id);
1246
+ }
1247
+ return changed;
1248
+ },
1249
+ inverse: undefined,
1250
+ };
1251
+ }
1252
+ function cloneOrder(order) {
1253
+ return { nodeIds: [...order.nodeIds], edgeIds: [...order.edgeIds], textIds: [...order.textIds], shapeIds: [...order.shapeIds] };
1254
+ }
1255
+ function ordersEqual(a, b) {
1256
+ return sameIds(a.nodeIds, b.nodeIds) && sameIds(a.edgeIds, b.edgeIds) && sameIds(a.textIds, b.textIds) && sameIds(a.shapeIds, b.shapeIds);
1257
+ }
1258
+ function reorderIds(order, ids, mode) {
1259
+ if (order.length < 2 || !ids.length) {
1260
+ return;
1261
+ }
1262
+ const selected = new Set(ids);
1263
+ if (mode === "front") {
1264
+ const moved = order.filter((id) => selected.has(id));
1265
+ order.splice(0, order.length, ...order.filter((id) => !selected.has(id)), ...moved);
1266
+ return;
1267
+ }
1268
+ if (mode === "back") {
1269
+ const moved = order.filter((id) => selected.has(id));
1270
+ order.splice(0, order.length, ...moved, ...order.filter((id) => !selected.has(id)));
1271
+ return;
1272
+ }
1273
+ const movingForward = mode === "forward";
1274
+ const start = movingForward ? order.length - 2 : 1;
1275
+ const end = movingForward ? -1 : order.length;
1276
+ const step = movingForward ? -1 : 1;
1277
+ for (let index = start; index !== end; index += step) {
1278
+ const nextIndex = movingForward ? index + 1 : index - 1;
1279
+ const current = order[index];
1280
+ const next = order[nextIndex];
1281
+ if (current !== undefined && next !== undefined && selected.has(current) && !selected.has(next)) {
1282
+ order[index] = next;
1283
+ order[nextIndex] = current;
1284
+ }
1285
+ }
1286
+ }
1287
+ function applyMetadataPatch(state, ids, patch) {
1288
+ var _a;
1289
+ const changed = new Set();
1290
+ for (const id of ids) {
1291
+ const previous = (_a = getEntityMetadata(state, id)) !== null && _a !== void 0 ? _a : {};
1292
+ setEntityMetadata(state, id, { ...previous, ...patch });
1293
+ changed.add(id);
1294
+ }
1295
+ return changed;
1296
+ }
1297
+ function setEntityMetadata(state, id, metadata) {
1298
+ const node = state.entities.nodesById.get(id);
1299
+ if (node) {
1300
+ state.entities.nodesById.set(id, { ...node, metadata });
1301
+ return;
1302
+ }
1303
+ const edge = state.entities.edgesById.get(id);
1304
+ if (edge) {
1305
+ state.entities.edgesById.set(id, { ...edge, metadata });
1306
+ return;
1307
+ }
1308
+ const text = state.entities.textsById.get(id);
1309
+ if (text) {
1310
+ state.entities.textsById.set(id, { ...text, metadata });
1311
+ return;
1312
+ }
1313
+ const shape = state.entities.shapesById.get(id);
1314
+ if (shape) {
1315
+ state.entities.shapesById.set(id, { ...shape, metadata });
1316
+ return;
1317
+ }
1318
+ const port = state.entities.portsById.get(id);
1319
+ if (port)
1320
+ state.entities.portsById.set(id, { ...port, metadata });
1321
+ }
1322
+ function getEntityMetadata(state, id) {
1323
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1324
+ return (_h = (_f = (_d = (_b = (_a = state.entities.nodesById.get(id)) === null || _a === void 0 ? void 0 : _a.metadata) !== null && _b !== void 0 ? _b : (_c = state.entities.edgesById.get(id)) === null || _c === void 0 ? void 0 : _c.metadata) !== null && _d !== void 0 ? _d : (_e = state.entities.textsById.get(id)) === null || _e === void 0 ? void 0 : _e.metadata) !== null && _f !== void 0 ? _f : (_g = state.entities.shapesById.get(id)) === null || _g === void 0 ? void 0 : _g.metadata) !== null && _h !== void 0 ? _h : (_j = state.entities.portsById.get(id)) === null || _j === void 0 ? void 0 : _j.metadata;
1325
+ }
1326
+ function zIndex(metadata) {
1327
+ return typeof (metadata === null || metadata === void 0 ? void 0 : metadata.zIndex) === "number" && Number.isFinite(metadata.zIndex) ? metadata.zIndex : 0;
1328
+ }
1329
+ function allEntityIds(state) {
1330
+ return [
1331
+ ...state.order.edgeIds,
1332
+ ...state.order.shapeIds,
1333
+ ...state.order.nodeIds,
1334
+ ...state.order.textIds,
1335
+ ...state.entities.portsById.keys(),
1336
+ ];
1337
+ }
1338
+ function hasEntity(state, id) {
1339
+ return state.entities.nodesById.has(id) || state.entities.edgesById.has(id) || state.entities.textsById.has(id) || state.entities.shapesById.has(id) || state.entities.portsById.has(id);
1340
+ }
1341
+ function isEntityLockedOrReadOnly(state, id) {
1342
+ const metadata = getEntityMetadata(state, id);
1343
+ return (metadata === null || metadata === void 0 ? void 0 : metadata.locked) === true || (metadata === null || metadata === void 0 ? void 0 : metadata.readOnly) === true;
1344
+ }
1345
+ function isEntityNonDeletable(state, id) {
1346
+ var _a;
1347
+ return ((_a = getEntityMetadata(state, id)) === null || _a === void 0 ? void 0 : _a.nonDeletable) === true;
1348
+ }
1349
+ function layerRank(metadata) {
1350
+ if ((metadata === null || metadata === void 0 ? void 0 : metadata.layerRole) === "background")
1351
+ return -1;
1352
+ if ((metadata === null || metadata === void 0 ? void 0 : metadata.layerRole) === "foreground")
1353
+ return 1;
1354
+ return 0;
1355
+ }
1356
+ function boundsForIds(engine, ids) {
1357
+ const scene = engine.getScene();
1358
+ const rects = ids.map((id) => { var _a; return (_a = createEntityGeometry(id, scene.entities)) === null || _a === void 0 ? void 0 : _a.bounds; }).filter((rect) => Boolean(rect));
1359
+ if (!rects.length)
1360
+ return null;
1361
+ const minX = Math.min(...rects.map((rect) => rect.x));
1362
+ const minY = Math.min(...rects.map((rect) => rect.y));
1363
+ const maxX = Math.max(...rects.map((rect) => rect.x + rect.width));
1364
+ const maxY = Math.max(...rects.map((rect) => rect.y + rect.height));
1365
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
1366
+ }
1367
+ function now() {
1368
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
1369
+ }
1370
+ function restoreSerialized(state, scene) {
1371
+ const changed = new Set();
1372
+ for (const node of scene.nodes) {
1373
+ state.entities.nodesById.set(node.id, node);
1374
+ pushUnique(state.order.nodeIds, node.id);
1375
+ state.versions.set(node.id, 0);
1376
+ changed.add(node.id);
1377
+ }
1378
+ for (const edge of scene.edges) {
1379
+ state.entities.edgesById.set(edge.id, edge);
1380
+ pushUnique(state.order.edgeIds, edge.id);
1381
+ state.versions.set(edge.id, 0);
1382
+ changed.add(edge.id);
1383
+ }
1384
+ for (const text of scene.texts) {
1385
+ state.entities.textsById.set(text.id, text);
1386
+ pushUnique(state.order.textIds, text.id);
1387
+ state.versions.set(text.id, 0);
1388
+ changed.add(text.id);
1389
+ }
1390
+ for (const shape of scene.shapes) {
1391
+ state.entities.shapesById.set(shape.id, shape);
1392
+ pushUnique(state.order.shapeIds, shape.id);
1393
+ state.versions.set(shape.id, 0);
1394
+ changed.add(shape.id);
1395
+ }
1396
+ for (const port of scene.ports) {
1397
+ state.entities.portsById.set(port.id, port);
1398
+ state.versions.set(port.id, 0);
1399
+ changed.add(port.id);
1400
+ }
1401
+ state.selection = scene.selection;
1402
+ return changed;
1403
+ }
1404
+ function deleteEntity(state, id) {
1405
+ let deleted = state.entities.nodesById.delete(id);
1406
+ deleted = state.entities.edgesById.delete(id) || deleted;
1407
+ deleted = state.entities.textsById.delete(id) || deleted;
1408
+ deleted = state.entities.shapesById.delete(id) || deleted;
1409
+ deleted = state.entities.portsById.delete(id) || deleted;
1410
+ state.order.nodeIds = state.order.nodeIds.filter((value) => value !== id);
1411
+ state.order.edgeIds = state.order.edgeIds.filter((value) => value !== id);
1412
+ state.order.textIds = state.order.textIds.filter((value) => value !== id);
1413
+ state.order.shapeIds = state.order.shapeIds.filter((value) => value !== id);
1414
+ state.versions.delete(id);
1415
+ return deleted;
1416
+ }
1417
+ function edgeReferencesNode(edge, id, ports) {
1418
+ var _a;
1419
+ for (const endpoint of [edge.source, edge.target]) {
1420
+ if (endpoint.kind === "node" && endpoint.nodeId === id) {
1421
+ return true;
1422
+ }
1423
+ if (endpoint.kind === "port" && ((_a = ports.get(endpoint.portId)) === null || _a === void 0 ? void 0 : _a.nodeId) === id) {
1424
+ return true;
1425
+ }
1426
+ }
1427
+ return false;
1428
+ }
1429
+ function hitDistanceForGeometry(geometry, point, radius) {
1430
+ var _a, _b;
1431
+ if (geometry.kind === "edge") {
1432
+ const edgeDistance = distanceToPath(point, (_a = geometry.path) !== null && _a !== void 0 ? _a : []);
1433
+ const tolerance = Math.max(radius, 6);
1434
+ return edgeDistance <= tolerance ? edgeDistance : null;
1435
+ }
1436
+ if ((_b = geometry.corners) === null || _b === void 0 ? void 0 : _b.length) {
1437
+ if (pointInPolygon(point, geometry.corners))
1438
+ return 0;
1439
+ const edgeDistance = distanceToPath(point, [...geometry.corners, geometry.corners[0]]);
1440
+ return edgeDistance <= radius ? edgeDistance : null;
1441
+ }
1442
+ if (!rectContainsPoint(geometry.hitBounds, point, radius)) {
1443
+ return null;
1444
+ }
1445
+ return distance(point, rectPoint(geometry.hitBounds, point));
1446
+ }
1447
+ function pointInPolygon(point, polygon) {
1448
+ let inside = false;
1449
+ for (let index = 0, previous = polygon.length - 1; index < polygon.length; previous = index, index += 1) {
1450
+ const a = polygon[index];
1451
+ const b = polygon[previous];
1452
+ if ((a.y > point.y) !== (b.y > point.y) && point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x) {
1453
+ inside = !inside;
1454
+ }
1455
+ }
1456
+ return inside;
1457
+ }
1458
+ function distanceToPath(point, path) {
1459
+ if (path.length === 0) {
1460
+ return Number.POSITIVE_INFINITY;
1461
+ }
1462
+ if (path.length === 1) {
1463
+ return distance(point, path[0]);
1464
+ }
1465
+ let best = Number.POSITIVE_INFINITY;
1466
+ for (let index = 0; index < path.length - 1; index += 1) {
1467
+ best = Math.min(best, distanceToSegment(point, path[index], path[index + 1]));
1468
+ }
1469
+ return best;
1470
+ }
1471
+ function distanceToSegment(point, start, end) {
1472
+ const dx = end.x - start.x;
1473
+ const dy = end.y - start.y;
1474
+ const lengthSquared = dx * dx + dy * dy;
1475
+ if (lengthSquared === 0) {
1476
+ return distance(point, start);
1477
+ }
1478
+ const t = Math.max(0, Math.min(1, ((point.x - start.x) * dx + (point.y - start.y) * dy) / lengthSquared));
1479
+ return distance(point, { x: start.x + t * dx, y: start.y + t * dy });
1480
+ }
1481
+ function rectPoint(rect, point) {
1482
+ return {
1483
+ x: Math.max(rect.x, Math.min(point.x, rect.x + rect.width)),
1484
+ y: Math.max(rect.y, Math.min(point.y, rect.y + rect.height)),
1485
+ };
1486
+ }
1487
+ function constrainAngle(point, angleDegrees) {
1488
+ const length = Math.hypot(point.x, point.y);
1489
+ if (length === 0) {
1490
+ return point;
1491
+ }
1492
+ const angle = Math.atan2(point.y, point.x);
1493
+ const step = angleDegrees * (Math.PI / 180);
1494
+ const constrained = Math.round(angle / step) * step;
1495
+ return { x: Math.cos(constrained) * length, y: Math.sin(constrained) * length };
1496
+ }
1497
+ function normalizeSelectionByMode(previous, selection, mode) {
1498
+ var _a, _b, _c;
1499
+ if (mode === "replace") {
1500
+ return normalizeSelection(selection);
1501
+ }
1502
+ const ids = new Set(previous.ids);
1503
+ for (const id of selection.ids) {
1504
+ if (mode === "toggle" && ids.has(id)) {
1505
+ ids.delete(id);
1506
+ }
1507
+ else {
1508
+ ids.add(id);
1509
+ }
1510
+ }
1511
+ const nextIds = [...ids];
1512
+ return normalizeSelection({ ids: nextIds, primaryId: (_c = (_b = (_a = selection.primaryId) !== null && _a !== void 0 ? _a : previous.primaryId) !== null && _b !== void 0 ? _b : nextIds[0]) !== null && _c !== void 0 ? _c : null });
1513
+ }
1514
+ function normalizeSelection(selection) {
1515
+ var _a, _b;
1516
+ const ids = [...new Set((_a = selection === null || selection === void 0 ? void 0 : selection.ids) !== null && _a !== void 0 ? _a : [])];
1517
+ return {
1518
+ ids,
1519
+ primaryId: (selection === null || selection === void 0 ? void 0 : selection.primaryId) && ids.includes(selection.primaryId) ? selection.primaryId : (_b = ids[0]) !== null && _b !== void 0 ? _b : null,
1520
+ };
1521
+ }
1522
+ function pick(map, ids) {
1523
+ const picked = new Map();
1524
+ for (const id of ids) {
1525
+ const entity = map.get(id);
1526
+ if (entity) {
1527
+ picked.set(id, entity);
1528
+ }
1529
+ }
1530
+ return picked;
1531
+ }
1532
+ function pushUnique(ids, id) {
1533
+ if (!ids.includes(id)) {
1534
+ ids.push(id);
1535
+ }
1536
+ }
1537
+ function sameIds(a, b) {
1538
+ return a.length === b.length && a.every((id, index) => id === b[index]);
1539
+ }
1540
+ function sameViewport(a, b) {
1541
+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height && a.zoom === b.zoom;
1542
+ }
1543
+ function isDefined(value) {
1544
+ return value !== undefined;
1545
+ }