@statelyai/flow 0.1.0 → 0.4.2

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.
package/dist/esm/index.js CHANGED
@@ -1,6 +1,18 @@
1
1
  import { createStore } from "@xstate/store";
2
2
  import { undoRedo } from "@xstate/store/undo";
3
- import { enableMapSet, produce } from "immer";
3
+ import { current, enableMapSet, isDraft, produce, setAutoFreeze } from "immer";
4
+ //#region src/profile.ts
5
+ function defineFlowProfile(profile) {
6
+ return profile;
7
+ }
8
+ const defaultFlowProfile = defineFlowProfile({
9
+ defaultMode: "interactive",
10
+ modes: {
11
+ interactive: {},
12
+ readonly: {}
13
+ }
14
+ });
15
+ //#endregion
4
16
  //#region src/viewport/index.ts
5
17
  /** Create a default viewport (origin, no zoom) */
6
18
  function createViewport(x = 0, y = 0, zoom = 1) {
@@ -97,6 +109,14 @@ function zoomTo(viewport, zoom, center) {
97
109
  function clampZoom(zoom, minZoom, maxZoom) {
98
110
  return Math.min(Math.max(zoom, minZoom), maxZoom);
99
111
  }
112
+ /** Viewport that places the given canvas point at the center of the screen. */
113
+ function viewportCenteredOn(center, size, zoom) {
114
+ return {
115
+ x: size.width / 2 - center.x * zoom,
116
+ y: size.height / 2 - center.y * zoom,
117
+ zoom
118
+ };
119
+ }
100
120
  //#endregion
101
121
  //#region src/spatial.ts
102
122
  /** Resolved visual position: layout position + drag offset */
@@ -108,12 +128,25 @@ function resolvedPosition(node) {
108
128
  }
109
129
  /** Resolved visual bounds: layout position + drag offset + dimensions.
110
130
  * Uses style.customWidth/customHeight when set (from resize), otherwise inherent width/height. */
131
+ /** Size the geometry should use, in priority order:
132
+ * 1. `style.customWidth/customHeight` (an explicit resize override),
133
+ * 2. for `autoSize` nodes, the DOM-`measured` size (the renderer owns it),
134
+ * 3. the authored `width/height`.
135
+ * Authored `width/height` are never mutated — measured size lives on
136
+ * `node.measured`, so this is the single place that reconciles the two. */
137
+ function resolvedSize(node) {
138
+ return {
139
+ width: node.style?.customWidth ?? (node.autoSize ? node.measured?.width ?? node.width : node.width),
140
+ height: node.style?.customHeight ?? (node.autoSize ? node.measured?.height ?? node.height : node.height)
141
+ };
142
+ }
111
143
  function resolvedBounds(node) {
144
+ const size = resolvedSize(node);
112
145
  return {
113
146
  x: node.x + (node.dx ?? 0),
114
147
  y: node.y + (node.dy ?? 0),
115
- width: node.style?.customWidth ?? node.width,
116
- height: node.style?.customHeight ?? node.height
148
+ width: size.width,
149
+ height: size.height
117
150
  };
118
151
  }
119
152
  /** Resolved bounds with visual snap — for rendering during drag.
@@ -129,11 +162,12 @@ function snappedBounds(node, grid, snapOffset) {
129
162
  x = snapToGrid(x, grid[0]);
130
163
  y = snapToGrid(y, grid[1]);
131
164
  }
165
+ const size = resolvedSize(node);
132
166
  return {
133
167
  x,
134
168
  y,
135
- width: node.style?.customWidth ?? node.width,
136
- height: node.style?.customHeight ?? node.height
169
+ width: size.width,
170
+ height: size.height
137
171
  };
138
172
  }
139
173
  /** Compute bounding rect of all nodes + edge labels (resolved positions) */
@@ -172,6 +206,17 @@ function getGraphBounds(nodes, edges) {
172
206
  function rectsIntersect(a, b) {
173
207
  return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;
174
208
  }
209
+ /** Smallest axis-aligned rect containing both `a` and `b`. */
210
+ function unionRect(a, b) {
211
+ const x = Math.min(a.x, b.x);
212
+ const y = Math.min(a.y, b.y);
213
+ return {
214
+ x,
215
+ y,
216
+ width: Math.max(a.x + a.width, b.x + b.width) - x,
217
+ height: Math.max(a.y + a.height, b.y + b.height) - y
218
+ };
219
+ }
175
220
  /** Snap a value to the nearest grid increment */
176
221
  function snapToGrid(value, gridSize) {
177
222
  return Math.round(value / gridSize) * gridSize;
@@ -690,6 +735,29 @@ function isPointNearPath(point, path, tolerance) {
690
735
  }
691
736
  return false;
692
737
  }
738
+ /**
739
+ * Axis-aligned bounding box of a path's control/anchor points. A cubic bezier
740
+ * lies within the convex hull of its control points, so this is a conservative
741
+ * superset of the rendered curve — exact enough for viewport culling (no false
742
+ * negatives) and ~O(points) instead of sampling the curve. Returns null for an
743
+ * empty path.
744
+ */
745
+ function pathBounds(path) {
746
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
747
+ for (const point of path.points) {
748
+ if (point.x < minX) minX = point.x;
749
+ if (point.y < minY) minY = point.y;
750
+ if (point.x > maxX) maxX = point.x;
751
+ if (point.y > maxY) maxY = point.y;
752
+ }
753
+ if (!isFinite(minX)) return null;
754
+ return {
755
+ x: minX,
756
+ y: minY,
757
+ width: maxX - minX,
758
+ height: maxY - minY
759
+ };
760
+ }
693
761
  function rectIntersectsPath(rect, path) {
694
762
  const samplePoints = samplePathPoints(path);
695
763
  for (const point of samplePoints) if (pointInRect(point, rect)) return true;
@@ -798,8 +866,246 @@ function onSegment(a, b, c) {
798
866
  return Math.min(a.x, b.x) <= c.x && c.x <= Math.max(a.x, b.x) && Math.min(a.y, b.y) <= c.y && c.y <= Math.max(a.y, b.y);
799
867
  }
800
868
  //#endregion
869
+ //#region src/graph-index.ts
870
+ const nodeIndexCache = /* @__PURE__ */ new WeakMap();
871
+ const edgeIndexCache = /* @__PURE__ */ new WeakMap();
872
+ function indexNodes(nodes) {
873
+ let index = nodeIndexCache.get(nodes);
874
+ if (!index) {
875
+ index = /* @__PURE__ */ new Map();
876
+ for (const node of nodes) if (!index.has(node.id)) index.set(node.id, node);
877
+ nodeIndexCache.set(nodes, index);
878
+ }
879
+ return index;
880
+ }
881
+ function indexEdges(edges) {
882
+ let index = edgeIndexCache.get(edges);
883
+ if (!index) {
884
+ index = /* @__PURE__ */ new Map();
885
+ for (const edge of edges) if (!index.has(edge.id)) index.set(edge.id, edge);
886
+ edgeIndexCache.set(edges, index);
887
+ }
888
+ return index;
889
+ }
890
+ const childrenIndexCache = /* @__PURE__ */ new WeakMap();
891
+ /** parentId → child nodes, cached on array identity. Self-parents ignored. */
892
+ function indexChildren(nodes) {
893
+ let index = childrenIndexCache.get(nodes);
894
+ if (!index) {
895
+ index = /* @__PURE__ */ new Map();
896
+ for (const node of nodes) {
897
+ const parentId = node.parentId ?? null;
898
+ if (parentId == null || parentId === node.id) continue;
899
+ const children = index.get(parentId);
900
+ if (children) children.push(node);
901
+ else index.set(parentId, [node]);
902
+ }
903
+ childrenIndexCache.set(nodes, index);
904
+ }
905
+ return index;
906
+ }
907
+ const depthCache = /* @__PURE__ */ new WeakMap();
908
+ /**
909
+ * Hierarchy depth per node id (roots = 0), cached on array identity.
910
+ * Cycle-safe; missing parents count as roots. Renderers can sort by this so
911
+ * parents paint beneath children regardless of array order.
912
+ */
913
+ function nodeDepths(nodes) {
914
+ let depths = depthCache.get(nodes);
915
+ if (!depths) {
916
+ const index = indexNodes(nodes);
917
+ const resolved = /* @__PURE__ */ new Map();
918
+ const depthOf = (node, seen) => {
919
+ const existing = resolved.get(node.id);
920
+ if (existing !== void 0) return existing;
921
+ const parentId = node.parentId ?? null;
922
+ if (parentId == null || parentId === node.id || seen.has(node.id)) {
923
+ resolved.set(node.id, 0);
924
+ return 0;
925
+ }
926
+ seen.add(node.id);
927
+ const parent = index.get(parentId);
928
+ const depth = parent ? depthOf(parent, seen) + 1 : 0;
929
+ resolved.set(node.id, depth);
930
+ return depth;
931
+ };
932
+ for (const node of nodes) depthOf(node, /* @__PURE__ */ new Set());
933
+ depths = resolved;
934
+ depthCache.set(nodes, depths);
935
+ }
936
+ return depths;
937
+ }
938
+ //#endregion
939
+ //#region src/hierarchy.ts
940
+ function resolveGroupPadding(padding) {
941
+ if (typeof padding === "number") return {
942
+ top: padding,
943
+ right: padding,
944
+ bottom: padding,
945
+ left: padding
946
+ };
947
+ return {
948
+ top: padding?.top ?? 16,
949
+ right: padding?.right ?? 16,
950
+ bottom: padding?.bottom ?? 16,
951
+ left: padding?.left ?? 16
952
+ };
953
+ }
954
+ function isGroup(node) {
955
+ return node.group !== void 0;
956
+ }
957
+ function isDerivedGroup(node) {
958
+ return node.group?.type === "derived";
959
+ }
960
+ /**
961
+ * Derive a `derived` group's geometry from its content size and the union of
962
+ * its children's bounds (pass null when the group has no children — the
963
+ * anchor point then places the group's top-left).
964
+ */
965
+ function deriveGroupGeometry(contentSize, childrenBounds, layout, anchor = {
966
+ x: 0,
967
+ y: 0
968
+ }) {
969
+ const side = layout.content ?? "top";
970
+ const padding = resolveGroupPadding(layout.padding);
971
+ const minArea = layout.minChildArea ?? {
972
+ width: 0,
973
+ height: 0
974
+ };
975
+ let childArea;
976
+ if (childrenBounds) childArea = {
977
+ x: childrenBounds.x - padding.left,
978
+ y: childrenBounds.y - padding.top,
979
+ width: Math.max(childrenBounds.width + padding.left + padding.right, minArea.width),
980
+ height: Math.max(childrenBounds.height + padding.top + padding.bottom, minArea.height)
981
+ };
982
+ else {
983
+ const horizontal = side === "top" || side === "bottom";
984
+ childArea = {
985
+ x: anchor.x,
986
+ y: anchor.y,
987
+ width: Math.max(minArea.width, padding.left + padding.right, horizontal ? contentSize.width : 0),
988
+ height: Math.max(minArea.height, padding.top + padding.bottom, horizontal ? 0 : contentSize.height)
989
+ };
990
+ if (side === "top") childArea.y += contentSize.height;
991
+ if (side === "left") childArea.x += contentSize.width;
992
+ }
993
+ return composeGeometry(contentSize, childArea, side);
994
+ }
995
+ /**
996
+ * Geometry for a `fixed` group: stored bounds are authoritative; the content
997
+ * block is carved from the configured side and the child area is the
998
+ * remainder inset by padding.
999
+ */
1000
+ function fixedGroupGeometry(bounds, contentSize, layout) {
1001
+ const side = layout.content ?? "top";
1002
+ const padding = resolveGroupPadding(layout.padding);
1003
+ let contentBounds;
1004
+ let childArea;
1005
+ if (side === "top" || side === "bottom") {
1006
+ const contentHeight = Math.min(contentSize.height, bounds.height);
1007
+ contentBounds = {
1008
+ x: bounds.x,
1009
+ y: side === "top" ? bounds.y : bounds.y + bounds.height - contentHeight,
1010
+ width: bounds.width,
1011
+ height: contentHeight
1012
+ };
1013
+ childArea = {
1014
+ x: bounds.x + padding.left,
1015
+ y: (side === "top" ? bounds.y + contentHeight : bounds.y) + padding.top,
1016
+ width: Math.max(bounds.width - padding.left - padding.right, 0),
1017
+ height: Math.max(bounds.height - contentHeight - padding.top - padding.bottom, 0)
1018
+ };
1019
+ } else {
1020
+ const contentWidth = Math.min(contentSize.width, bounds.width);
1021
+ contentBounds = {
1022
+ x: side === "left" ? bounds.x : bounds.x + bounds.width - contentWidth,
1023
+ y: bounds.y,
1024
+ width: contentWidth,
1025
+ height: bounds.height
1026
+ };
1027
+ childArea = {
1028
+ x: (side === "left" ? bounds.x + contentWidth : bounds.x) + padding.left,
1029
+ y: bounds.y + padding.top,
1030
+ width: Math.max(bounds.width - contentWidth - padding.left - padding.right, 0),
1031
+ height: Math.max(bounds.height - padding.top - padding.bottom, 0)
1032
+ };
1033
+ }
1034
+ return {
1035
+ bounds,
1036
+ contentBounds,
1037
+ childArea
1038
+ };
1039
+ }
1040
+ function composeGeometry(contentSize, childArea, side) {
1041
+ if (side === "top" || side === "bottom") {
1042
+ const width = Math.max(childArea.width, contentSize.width);
1043
+ const x = childArea.x - (width - childArea.width) / 2;
1044
+ const contentY = side === "top" ? childArea.y - contentSize.height : childArea.y + childArea.height;
1045
+ return {
1046
+ bounds: {
1047
+ x,
1048
+ y: side === "top" ? contentY : childArea.y,
1049
+ width,
1050
+ height: contentSize.height + childArea.height
1051
+ },
1052
+ contentBounds: {
1053
+ x,
1054
+ y: contentY,
1055
+ width,
1056
+ height: contentSize.height
1057
+ },
1058
+ childArea
1059
+ };
1060
+ }
1061
+ const height = Math.max(childArea.height, contentSize.height);
1062
+ const y = childArea.y - (height - childArea.height) / 2;
1063
+ const contentX = side === "left" ? childArea.x - contentSize.width : childArea.x + childArea.width;
1064
+ return {
1065
+ bounds: {
1066
+ x: side === "left" ? contentX : childArea.x,
1067
+ y,
1068
+ width: contentSize.width + childArea.width,
1069
+ height
1070
+ },
1071
+ contentBounds: {
1072
+ x: contentX,
1073
+ y,
1074
+ width: contentSize.width,
1075
+ height
1076
+ },
1077
+ childArea
1078
+ };
1079
+ }
1080
+ /**
1081
+ * The id of the node that contains this edge, or null for the root.
1082
+ * Override per engine via `FlowEngineOptions.edgeOwner`.
1083
+ */
1084
+ function getEdgeOwner(edge, nodes) {
1085
+ const index = indexNodes(nodes);
1086
+ const source = index.get(edge.sourceId);
1087
+ const target = index.get(edge.targetId);
1088
+ if (!source) return null;
1089
+ if (!target || source.id === target.id) return source.parentId ?? null;
1090
+ const sourceChain = new Set([source.id]);
1091
+ let marker = source.parentId ?? null;
1092
+ while (marker && !sourceChain.has(marker)) {
1093
+ sourceChain.add(marker);
1094
+ marker = index.get(marker)?.parentId ?? null;
1095
+ }
1096
+ let candidate = target.id;
1097
+ const seen = /* @__PURE__ */ new Set();
1098
+ while (candidate && !seen.has(candidate)) {
1099
+ if (sourceChain.has(candidate)) return candidate;
1100
+ seen.add(candidate);
1101
+ candidate = index.get(candidate)?.parentId ?? null;
1102
+ }
1103
+ return null;
1104
+ }
1105
+ //#endregion
801
1106
  //#region src/store/index.ts
802
1107
  enableMapSet();
1108
+ if (process.env.NODE_ENV === "production") setAutoFreeze(false);
803
1109
  const UNDOABLE_EVENT_TYPES = [
804
1110
  "createNode",
805
1111
  "deleteNode",
@@ -809,9 +1115,10 @@ const UNDOABLE_EVENT_TYPES = [
809
1115
  "updateEdgeData",
810
1116
  "deleteSelected",
811
1117
  "reparentNode",
812
- "commitDrag",
813
- "resizeEnd",
1118
+ "dragStart",
1119
+ "resizeStart",
814
1120
  "reconnectEdge",
1121
+ "moveNodes",
815
1122
  "applyLayoutResult",
816
1123
  "bakeLabelPositions"
817
1124
  ];
@@ -838,20 +1145,230 @@ function applyBeforeDelete(options, draft, reason, nodes, edges) {
838
1145
  }
839
1146
  return false;
840
1147
  }
1148
+ /**
1149
+ * Validate an edge about to be inserted. Returns an actionable error message,
1150
+ * or null when the edge is valid. Used by `createEdge` and undo tracking.
1151
+ */
1152
+ function validateNewEdge(ctx, edge) {
1153
+ if (ctx.graph.edges.some((e) => e.id === edge.id)) return `createEdge rejected: an edge with id "${edge.id}" already exists. Edge ids must be unique — use reconnectEdge or updateEdgeData to modify the existing edge, or create the edge with a different id.`;
1154
+ const missing = [];
1155
+ if (!ctx.graph.nodes.some((n) => n.id === edge.sourceId)) missing.push(`source node "${edge.sourceId}"`);
1156
+ if (!ctx.graph.nodes.some((n) => n.id === edge.targetId)) missing.push(`target node "${edge.targetId}"`);
1157
+ if (missing.length > 0) return `createEdge rejected: edge "${edge.id}" references ${missing.join(" and ")}, which ${missing.length === 1 ? "does" : "do"} not exist in the graph. Create the node(s) first, then the edge.`;
1158
+ return null;
1159
+ }
1160
+ /**
1161
+ * Validate a reparent operation. Returns an error message or null when valid.
1162
+ * Rejects self-parenting, non-existent parents, and cycles (parentId is a
1163
+ * descendant of nodeId).
1164
+ */
1165
+ function reparentProblem(graph, nodeId, parentId) {
1166
+ if (parentId === null) return null;
1167
+ if (parentId === nodeId) return `reparentNode rejected: node "${nodeId}" cannot be its own parent.`;
1168
+ if (!graph.nodes.some((n) => n.id === parentId)) return `reparentNode rejected: parent node "${parentId}" does not exist in the graph.`;
1169
+ const nodeIndex = new Map(graph.nodes.map((n) => [n.id, n]));
1170
+ let candidate = parentId;
1171
+ const seen = /* @__PURE__ */ new Set();
1172
+ while (candidate && !seen.has(candidate)) {
1173
+ if (candidate === nodeId) return `reparentNode rejected: node "${parentId}" is a descendant of "${nodeId}", which would create a cycle.`;
1174
+ seen.add(candidate);
1175
+ candidate = nodeIndex.get(candidate)?.parentId ?? null;
1176
+ }
1177
+ return null;
1178
+ }
1179
+ /** Drop hover/highlight references to entities that no longer exist. */
1180
+ function pruneVisualState(draft, deletedIds) {
1181
+ for (const id of deletedIds) draft.hoveredEntityIds.delete(id);
1182
+ for (const [kind, bucket] of draft.highlights) {
1183
+ for (const id of deletedIds) bucket.delete(id);
1184
+ if (bucket.size === 0) draft.highlights.delete(kind);
1185
+ }
1186
+ }
841
1187
  function isUndoableEventType(type) {
842
1188
  return UNDOABLE_EVENT_TYPES.includes(type);
843
1189
  }
1190
+ function planNodeMovement(ctx, dx, dy, options = {}) {
1191
+ const nodes = ctx.graph.nodes;
1192
+ const edges = ctx.graph.edges;
1193
+ const nodeIndex = indexNodes(nodes);
1194
+ const edgeIndex = indexEdges(edges);
1195
+ const movingNodeIds = /* @__PURE__ */ new Set();
1196
+ const labelEdgeIds = /* @__PURE__ */ new Set();
1197
+ for (const id of ctx.selection) {
1198
+ const node = nodeIndex.get(id);
1199
+ if (node) {
1200
+ if (node.draggable !== false) movingNodeIds.add(id);
1201
+ continue;
1202
+ }
1203
+ if (options.includeLabels) {
1204
+ const edge = edgeIndex.get(id);
1205
+ if (edge && edge.draggable !== false && edge.label) labelEdgeIds.add(id);
1206
+ }
1207
+ }
1208
+ if (movingNodeIds.size === 0 && labelEdgeIds.size === 0) return null;
1209
+ let childrenByParent = null;
1210
+ for (const node of nodes) {
1211
+ const parentId = node.parentId ?? null;
1212
+ if (parentId == null || parentId === node.id) continue;
1213
+ if (!childrenByParent) childrenByParent = /* @__PURE__ */ new Map();
1214
+ const children = childrenByParent.get(parentId);
1215
+ if (children) children.push(node.id);
1216
+ else childrenByParent.set(parentId, [node.id]);
1217
+ }
1218
+ const deltasById = /* @__PURE__ */ new Map();
1219
+ for (const id of movingNodeIds) {
1220
+ const node = nodeIndex.get(id);
1221
+ const oldDx = node.dx ?? 0;
1222
+ const oldDy = node.dy ?? 0;
1223
+ let newDx = oldDx + dx;
1224
+ let newDy = oldDy + dy;
1225
+ if (ctx.nodeExtent) {
1226
+ const nodeSize = resolvedSize(node);
1227
+ const clampedX = Math.max(ctx.nodeExtent[0].x, Math.min(node.x + newDx, ctx.nodeExtent[1].x - nodeSize.width));
1228
+ const clampedY = Math.max(ctx.nodeExtent[0].y, Math.min(node.y + newDy, ctx.nodeExtent[1].y - nodeSize.height));
1229
+ newDx = clampedX - node.x;
1230
+ newDy = clampedY - node.y;
1231
+ }
1232
+ const parent = node.parentId ? nodeIndex.get(node.parentId) : void 0;
1233
+ if (parent?.group?.type === "fixed") {
1234
+ const axes = parent.group.clampChildren ?? "none";
1235
+ if (axes !== "none") {
1236
+ const area = fixedGroupGeometry({
1237
+ x: parent.x + (parent.dx ?? 0),
1238
+ y: parent.y + (parent.dy ?? 0),
1239
+ width: parent.style?.customWidth ?? parent.width,
1240
+ height: parent.style?.customHeight ?? parent.height
1241
+ }, parent.group.contentSize ?? {
1242
+ width: 0,
1243
+ height: 0
1244
+ }, parent.group).childArea;
1245
+ const { width: nodeWidth, height: nodeHeight } = resolvedSize(node);
1246
+ if (axes === "x" || axes === "both") newDx = Math.max(area.x, Math.min(node.x + newDx, area.x + area.width - nodeWidth)) - node.x;
1247
+ if (axes === "y" || axes === "both") newDy = Math.max(area.y, Math.min(node.y + newDy, area.y + area.height - nodeHeight)) - node.y;
1248
+ }
1249
+ }
1250
+ if (ctx.constrainNodeMovement) {
1251
+ const adjusted = ctx.constrainNodeMovement(node, {
1252
+ x: node.x + newDx,
1253
+ y: node.y + newDy
1254
+ }, ctx);
1255
+ if (adjusted) {
1256
+ newDx = adjusted.x - node.x;
1257
+ newDy = adjusted.y - node.y;
1258
+ }
1259
+ }
1260
+ const applied = {
1261
+ x: newDx - oldDx,
1262
+ y: newDy - oldDy
1263
+ };
1264
+ if (applied.x === 0 && applied.y === 0) continue;
1265
+ deltasById.set(id, applied);
1266
+ if (childrenByParent) collectDescendantDeltas(childrenByParent, id, applied, movingNodeIds, deltasById);
1267
+ }
1268
+ const nodeDeltasByIndex = /* @__PURE__ */ new Map();
1269
+ if (deltasById.size > 0) for (let i = 0; i < nodes.length; i++) {
1270
+ const delta = deltasById.get(nodes[i].id);
1271
+ if (delta) nodeDeltasByIndex.set(i, delta);
1272
+ }
1273
+ const labelEdgeIndexes = [];
1274
+ if (labelEdgeIds.size > 0) {
1275
+ for (let i = 0; i < edges.length; i++) if (labelEdgeIds.has(edges[i].id)) labelEdgeIndexes.push(i);
1276
+ }
1277
+ const labelDeltasByIndex = /* @__PURE__ */ new Map();
1278
+ if (deltasById.size > 0) for (let i = 0; i < edges.length; i++) {
1279
+ const edge = edges[i];
1280
+ if (!edge.label || edge.draggable === false) continue;
1281
+ if (labelEdgeIds.has(edge.id)) continue;
1282
+ if (edge.sourceId !== edge.targetId && movingNodeIds.has(edge.sourceId) && movingNodeIds.has(edge.targetId)) continue;
1283
+ const source = deltasById.get(edge.sourceId);
1284
+ if (!source) continue;
1285
+ const target = edge.targetId === edge.sourceId ? source : deltasById.get(edge.targetId);
1286
+ if (!target || target.x !== source.x || target.y !== source.y) continue;
1287
+ labelDeltasByIndex.set(i, source);
1288
+ }
1289
+ if (nodeDeltasByIndex.size === 0 && labelEdgeIndexes.length === 0 && labelDeltasByIndex.size === 0) return null;
1290
+ return {
1291
+ nodeDeltasByIndex,
1292
+ labelEdgeIndexes,
1293
+ labelDeltasByIndex
1294
+ };
1295
+ }
1296
+ function collectDescendantDeltas(childrenByParent, parentId, delta, movingIds, out, visited = new Set([parentId])) {
1297
+ const children = childrenByParent.get(parentId);
1298
+ if (!children) return;
1299
+ for (const childId of children) {
1300
+ if (visited.has(childId) || movingIds.has(childId)) continue;
1301
+ visited.add(childId);
1302
+ if (!out.has(childId)) out.set(childId, delta);
1303
+ collectDescendantDeltas(childrenByParent, childId, delta, movingIds, out, visited);
1304
+ }
1305
+ }
1306
+ function applyMovementPlan(draft, plan, labelDx, labelDy) {
1307
+ for (const [index, delta] of plan.nodeDeltasByIndex) {
1308
+ const node = draft.graph.nodes[index];
1309
+ if (!node) continue;
1310
+ node.dx = (node.dx ?? 0) + delta.x;
1311
+ node.dy = (node.dy ?? 0) + delta.y;
1312
+ }
1313
+ for (const index of plan.labelEdgeIndexes) {
1314
+ const edge = draft.graph.edges[index];
1315
+ if (!edge?.label) continue;
1316
+ edge.label.dx = (edge.label.dx ?? 0) + labelDx;
1317
+ edge.label.dy = (edge.label.dy ?? 0) + labelDy;
1318
+ }
1319
+ for (const [index, delta] of plan.labelDeltasByIndex) {
1320
+ const edge = draft.graph.edges[index];
1321
+ if (!edge?.label) continue;
1322
+ edge.label.dx = (edge.label.dx ?? 0) + delta.x;
1323
+ edge.label.dy = (edge.label.dy ?? 0) + delta.y;
1324
+ }
1325
+ }
1326
+ /**
1327
+ * Remove nodes from the draft graph and resolve connected edges according to
1328
+ * the configured `onDeleteNodes` strategy. Shared by `deleteNode` and
1329
+ * `deleteSelected` so both events always agree on edge handling.
1330
+ *
1331
+ * `edgesToDelete` are edge ids that must be removed regardless of strategy
1332
+ * (explicitly selected/targeted edges).
1333
+ */
1334
+ function applyNodeDeletionStrategy(draft, nodesToDelete, edgesToDelete, strategy) {
1335
+ if (typeof strategy === "function") {
1336
+ const result = strategy({
1337
+ ...draft.graph,
1338
+ nodes: [...draft.graph.nodes],
1339
+ edges: [...draft.graph.edges]
1340
+ }, nodesToDelete);
1341
+ draft.graph.nodes = result.nodes;
1342
+ draft.graph.edges = result.edges;
1343
+ return;
1344
+ }
1345
+ draft.graph.nodes = draft.graph.nodes.filter((n) => !nodesToDelete.has(n.id));
1346
+ if (strategy === "retarget") {
1347
+ const kept = [];
1348
+ for (const edge of draft.graph.edges) {
1349
+ if (edgesToDelete.has(edge.id)) continue;
1350
+ const srcDel = nodesToDelete.has(edge.sourceId);
1351
+ const tgtDel = nodesToDelete.has(edge.targetId);
1352
+ if (srcDel && tgtDel) continue;
1353
+ if (srcDel) edge.sourceId = edge.targetId;
1354
+ else if (tgtDel) edge.targetId = edge.sourceId;
1355
+ kept.push(edge);
1356
+ }
1357
+ draft.graph.edges = kept;
1358
+ return;
1359
+ }
1360
+ draft.graph.edges = draft.graph.edges.filter((e) => !edgesToDelete.has(e.id) && !nodesToDelete.has(e.sourceId) && !nodesToDelete.has(e.targetId));
1361
+ }
844
1362
  function hasSelectedEntitiesToDelete(ctx) {
845
1363
  for (const id of ctx.selection) if (ctx.graph.nodes.some((node) => node.id === id) || ctx.graph.edges.some((edge) => edge.id === id)) return true;
846
1364
  return false;
847
1365
  }
848
- function hasPendingDragDelta(ctx) {
849
- return ctx.graph.nodes.some((node) => (node.dx ?? 0) !== 0 || (node.dy ?? 0) !== 0) || ctx.graph.edges.some((edge) => !!edge.label && ((edge.label.dx ?? 0) !== 0 || (edge.label.dy ?? 0) !== 0));
850
- }
851
1366
  function shouldTrackUndoEvent(event, snapshot) {
852
1367
  if (!isUndoableEventType(event.type)) return false;
853
1368
  const ctx = snapshot.context;
854
1369
  switch (event.type) {
1370
+ case "createNode": return !ctx.graph.nodes.some((node) => node.id === event.node.id);
1371
+ case "createEdge": return validateNewEdge(ctx, event.edge) === null;
855
1372
  case "deleteNode": return ctx.graph.nodes.some((node) => node.id === event.id);
856
1373
  case "deleteEdge": return ctx.graph.edges.some((edge) => edge.id === event.id);
857
1374
  case "updateNodeData": {
@@ -867,8 +1384,9 @@ function shouldTrackUndoEvent(event, snapshot) {
867
1384
  const node = ctx.graph.nodes.find((candidate) => candidate.id === event.id);
868
1385
  return !!node && (node.parentId ?? null) !== event.parentId;
869
1386
  }
870
- case "commitDrag": return hasPendingDragDelta(ctx);
871
- case "resizeEnd": return !!ctx.resizingEntityId && !!ctx.resizeCorners;
1387
+ case "dragStart": return !!event.transactionId && (ctx.graph.nodes.some((node) => node.id === event.id) || ctx.graph.edges.some((edge) => edge.id === event.id));
1388
+ case "moveNodes": return (event.direction.x !== 0 || event.direction.y !== 0) && [...ctx.selection].some((id) => isExplicitlyDraggable(id, ctx.graph) && ctx.graph.nodes.some((node) => node.id === id));
1389
+ case "resizeStart": return !!event.transactionId && ctx.graph.nodes.some((node) => node.id === event.id);
872
1390
  case "reconnectEdge": {
873
1391
  const edge = ctx.graph.edges.find((candidate) => candidate.id === event.edgeId);
874
1392
  if (!edge) return false;
@@ -879,11 +1397,65 @@ function shouldTrackUndoEvent(event, snapshot) {
879
1397
  default: return true;
880
1398
  }
881
1399
  }
1400
+ /**
1401
+ * Snapshot a (possibly drafted) graph into plain data for emission — immer
1402
+ * drafts are revoked before listeners run. Plain values (e.g. right after
1403
+ * `draft.graph = event.graph`) pass through untouched.
1404
+ */
1405
+ function snapshotGraph(graph) {
1406
+ return isDraft(graph) ? current(graph) : graph;
1407
+ }
1408
+ /** Copy a (possibly drafted) viewport into plain data for emission. */
1409
+ function plainViewport(viewport) {
1410
+ return {
1411
+ x: viewport.x,
1412
+ y: viewport.y,
1413
+ zoom: viewport.zoom
1414
+ };
1415
+ }
1416
+ function createEventObject(type, event) {
1417
+ return {
1418
+ type,
1419
+ ...event ?? {}
1420
+ };
1421
+ }
1422
+ function isExplicitlyVisibleNode(node) {
1423
+ return !node.hidden;
1424
+ }
1425
+ function isExplicitlyVisibleEdge(edge, nodes) {
1426
+ if (edge.hidden) return false;
1427
+ const source = nodes.find((node) => node.id === edge.sourceId);
1428
+ const target = nodes.find((node) => node.id === edge.targetId);
1429
+ return !!source && !!target && isExplicitlyVisibleNode(source) && isExplicitlyVisibleNode(target);
1430
+ }
1431
+ function isExplicitlyDraggable(id, graph) {
1432
+ const node = graph.nodes.find((candidate) => candidate.id === id);
1433
+ if (node) return node.draggable !== false;
1434
+ const edge = graph.edges.find((candidate) => candidate.id === id);
1435
+ if (edge) return edge.draggable !== false;
1436
+ return false;
1437
+ }
1438
+ function getMode(profile, mode) {
1439
+ return profile.modes[mode] ? mode : profile.defaultMode;
1440
+ }
1441
+ function setModeTransition(profile) {
1442
+ return (ctx, event) => produce(ctx, (draft) => {
1443
+ draft.mode = getMode(profile, event.mode);
1444
+ });
1445
+ }
1446
+ function dispatchProfile(profile, ctx, event, enqueue, fallback) {
1447
+ const mode = getMode(profile, ctx.mode);
1448
+ const transition = profile.modes[mode]?.on?.[event.type] ?? profile.on?.[event.type] ?? fallback;
1449
+ if (!transition) return ctx;
1450
+ return transition(ctx, event, enqueue);
1451
+ }
882
1452
  function createFlowStore(initialGraph = {
883
1453
  nodes: [],
884
1454
  edges: [],
885
1455
  direction: "down"
886
1456
  }, options = {}) {
1457
+ const profile = options.profile ?? defaultFlowProfile;
1458
+ const initialMode = getMode(profile, options.mode ?? profile.defaultMode);
887
1459
  const initialContext = {
888
1460
  graph: initialGraph,
889
1461
  parentNodeId: null,
@@ -900,11 +1472,14 @@ function createFlowStore(initialGraph = {
900
1472
  nodeExtent: options.nodeExtent ?? null,
901
1473
  selection: /* @__PURE__ */ new Set(),
902
1474
  selectionBox: null,
903
- highlights: /* @__PURE__ */ new Set(),
1475
+ hoveredEntityIds: /* @__PURE__ */ new Set(),
1476
+ highlights: /* @__PURE__ */ new Map(),
904
1477
  focusedEntityId: null,
1478
+ measurements: /* @__PURE__ */ new Map(),
905
1479
  canvasState: "idle",
906
1480
  draggedEntityId: null,
907
1481
  dragThreshold: options.dragThreshold ?? 3,
1482
+ constrainNodeMovement: options.constrainNodeMovement ?? null,
908
1483
  autoPanOnDrag: options.autoPanOnDrag ?? true,
909
1484
  autoPanThreshold: options.autoPanThreshold ?? 40,
910
1485
  autoPanSpeed: options.autoPanSpeed ?? 15,
@@ -916,7 +1491,7 @@ function createFlowStore(initialGraph = {
916
1491
  resizingEntityId: null,
917
1492
  resizeHandle: null,
918
1493
  resizeCorners: null,
919
- interactionMode: "default",
1494
+ mode: initialMode,
920
1495
  selectionMode: options.selectionMode ?? "partial",
921
1496
  snapToGrid: options.snapToGrid ?? false,
922
1497
  snapGrid: options.snapGrid ?? [10, 10],
@@ -926,45 +1501,110 @@ function createFlowStore(initialGraph = {
926
1501
  autoLayout: {
927
1502
  status: "idle",
928
1503
  algorithm: null
929
- }
1504
+ },
1505
+ colorMode: options.colorMode ?? "system"
930
1506
  };
931
1507
  return createStore({
932
1508
  context: initialContext,
933
- emits: {
934
- layoutRequested: (_event) => {},
935
- connectionEnded: (_event) => {}
936
- },
937
1509
  on: {
938
- createNode: (ctx, event) => produce(ctx, (draft) => {
1510
+ createNode: (ctx, event, enqueue) => produce(ctx, (draft) => {
1511
+ if (draft.graph.nodes.some((n) => n.id === event.node.id)) {
1512
+ enqueue.emit.error({
1513
+ error: /* @__PURE__ */ new Error(`createNode rejected: a node with id "${event.node.id}" already exists. Node ids must be unique — use updateNodeData to modify the existing node, or create the node with a different id.`),
1514
+ event: createEventObject("createNode", event)
1515
+ });
1516
+ return;
1517
+ }
939
1518
  draft.graph.nodes.push(event.node);
1519
+ enqueue.emit.graphChanged({
1520
+ graph: snapshotGraph(draft.graph),
1521
+ event: createEventObject("createNode", event)
1522
+ });
940
1523
  }),
941
- deleteNode: (ctx, event) => produce(ctx, (draft) => {
1524
+ deleteNode: (ctx, event, enqueue) => produce(ctx, (draft) => {
942
1525
  const node = draft.graph.nodes.find((n) => n.id === event.id);
943
1526
  const edges = draft.graph.edges.filter((e) => e.sourceId === event.id || e.targetId === event.id);
944
1527
  if (node && applyBeforeDelete(options, draft, "deleteNode", [node], edges)) return;
945
- draft.graph.nodes = draft.graph.nodes.filter((n) => n.id !== event.id);
946
- draft.graph.edges = draft.graph.edges.filter((e) => e.sourceId !== event.id && e.targetId !== event.id);
1528
+ const edgeIdsBefore = draft.graph.edges.map((e) => e.id);
1529
+ applyNodeDeletionStrategy(draft, new Set([event.id]), /* @__PURE__ */ new Set(), options.onDeleteNodes ?? "cascade");
1530
+ const remainingEdgeIds = new Set(draft.graph.edges.map((e) => e.id));
1531
+ const deletedEdgeIds = edgeIdsBefore.filter((id) => !remainingEdgeIds.has(id));
947
1532
  draft.selection.delete(event.id);
1533
+ draft.measurements.delete(event.id);
1534
+ for (const edgeId of deletedEdgeIds) draft.measurements.delete(edgeId);
948
1535
  if (draft.focusedEntityId === event.id) draft.focusedEntityId = null;
1536
+ pruneVisualState(draft, [event.id, ...deletedEdgeIds]);
1537
+ enqueue.emit.entitiesDeleted({
1538
+ ids: [event.id, ...deletedEdgeIds],
1539
+ event: createEventObject("deleteNode", event)
1540
+ });
1541
+ enqueue.emit.graphChanged({
1542
+ graph: snapshotGraph(draft.graph),
1543
+ event: createEventObject("deleteNode", event)
1544
+ });
1545
+ enqueue.emit.selectionChanged({
1546
+ selection: new Set(draft.selection),
1547
+ event: createEventObject("deleteNode", event)
1548
+ });
949
1549
  }),
950
- updateNodeData: (ctx, event) => produce(ctx, (draft) => {
1550
+ updateNodeData: (ctx, event, enqueue) => produce(ctx, (draft) => {
951
1551
  const node = draft.graph.nodes.find((n) => n.id === event.id);
952
- if (node) Object.assign(node.data, event.data);
1552
+ if (node) {
1553
+ if (!node.data) node.data = {};
1554
+ Object.assign(node.data, event.data);
1555
+ enqueue.emit.graphChanged({
1556
+ graph: snapshotGraph(draft.graph),
1557
+ event: createEventObject("updateNodeData", event)
1558
+ });
1559
+ }
953
1560
  }),
954
- createEdge: (ctx, event) => produce(ctx, (draft) => {
1561
+ createEdge: (ctx, event, enqueue) => produce(ctx, (draft) => {
1562
+ const problem = validateNewEdge(draft, event.edge);
1563
+ if (problem) {
1564
+ enqueue.emit.error({
1565
+ error: new Error(problem),
1566
+ event: createEventObject("createEdge", event)
1567
+ });
1568
+ return;
1569
+ }
955
1570
  draft.graph.edges.push(event.edge);
1571
+ enqueue.emit.graphChanged({
1572
+ graph: snapshotGraph(draft.graph),
1573
+ event: createEventObject("createEdge", event)
1574
+ });
956
1575
  }),
957
- deleteEdge: (ctx, event) => produce(ctx, (draft) => {
1576
+ deleteEdge: (ctx, event, enqueue) => produce(ctx, (draft) => {
958
1577
  const edge = draft.graph.edges.find((e) => e.id === event.id);
959
1578
  if (edge && applyBeforeDelete(options, draft, "deleteEdge", [], [edge])) return;
960
1579
  draft.graph.edges = draft.graph.edges.filter((e) => e.id !== event.id);
961
1580
  draft.selection.delete(event.id);
1581
+ draft.measurements.delete(event.id);
1582
+ pruneVisualState(draft, [event.id]);
1583
+ enqueue.emit.entitiesDeleted({
1584
+ ids: [event.id],
1585
+ event: createEventObject("deleteEdge", event)
1586
+ });
1587
+ enqueue.emit.graphChanged({
1588
+ graph: snapshotGraph(draft.graph),
1589
+ event: createEventObject("deleteEdge", event)
1590
+ });
1591
+ enqueue.emit.selectionChanged({
1592
+ selection: new Set(draft.selection),
1593
+ event: createEventObject("deleteEdge", event)
1594
+ });
962
1595
  }),
963
- updateEdgeData: (ctx, event) => produce(ctx, (draft) => {
1596
+ updateEdgeData: (ctx, event, enqueue) => produce(ctx, (draft) => {
964
1597
  const edge = draft.graph.edges.find((e) => e.id === event.id);
965
- if (edge) Object.assign(edge.data, event.data);
1598
+ if (edge) {
1599
+ if (!edge.data) edge.data = {};
1600
+ Object.assign(edge.data, event.data);
1601
+ enqueue.emit.graphChanged({
1602
+ graph: snapshotGraph(draft.graph),
1603
+ event: createEventObject("updateEdgeData", event)
1604
+ });
1605
+ }
966
1606
  }),
967
- deleteSelected: (ctx) => produce(ctx, (draft) => {
1607
+ deleteSelected: (ctx, _event, enqueue) => produce(ctx, (draft) => {
968
1608
  const sel = draft.selection;
969
1609
  const nodesToDelete = /* @__PURE__ */ new Set();
970
1610
  const edgesToDelete = /* @__PURE__ */ new Set();
@@ -972,90 +1612,100 @@ function createFlowStore(initialGraph = {
972
1612
  if (draft.graph.nodes.some((n) => n.id === id)) nodesToDelete.add(id);
973
1613
  if (draft.graph.edges.some((e) => e.id === id)) edgesToDelete.add(id);
974
1614
  }
975
- if (applyBeforeDelete(options, draft, "deleteSelected", draft.graph.nodes.filter((node) => nodesToDelete.has(node.id)), draft.graph.edges.filter((edge) => edgesToDelete.has(edge.id) || nodesToDelete.has(edge.sourceId) || nodesToDelete.has(edge.targetId)))) return;
976
- const strategy = options.onDeleteNodes ?? "cascade";
977
- if (typeof strategy === "function") {
978
- const result = strategy({
979
- ...draft.graph,
980
- nodes: [...draft.graph.nodes],
981
- edges: [...draft.graph.edges]
982
- }, nodesToDelete);
983
- draft.graph.nodes = result.nodes;
984
- draft.graph.edges = result.edges;
985
- } else if (strategy === "retarget") {
986
- draft.graph.nodes = draft.graph.nodes.filter((n) => !nodesToDelete.has(n.id));
987
- draft.graph.edges = draft.graph.edges.filter((e) => !sel.has(e.id));
988
- for (const edge of draft.graph.edges) {
989
- const srcDel = nodesToDelete.has(edge.sourceId);
990
- const tgtDel = nodesToDelete.has(edge.targetId);
991
- if (srcDel && tgtDel) draft.graph.edges = draft.graph.edges.filter((e) => e.id !== edge.id);
992
- else if (srcDel) edge.sourceId = edge.targetId;
993
- else if (tgtDel) edge.targetId = edge.sourceId;
994
- }
995
- } else {
996
- draft.graph.nodes = draft.graph.nodes.filter((n) => !nodesToDelete.has(n.id));
997
- draft.graph.edges = draft.graph.edges.filter((e) => !sel.has(e.id) && !nodesToDelete.has(e.sourceId) && !nodesToDelete.has(e.targetId));
998
- }
1615
+ const selectedNodes = draft.graph.nodes.filter((node) => nodesToDelete.has(node.id));
1616
+ const selectedEdges = draft.graph.edges.filter((edge) => edgesToDelete.has(edge.id) || nodesToDelete.has(edge.sourceId) || nodesToDelete.has(edge.targetId));
1617
+ if (applyBeforeDelete(options, draft, "deleteSelected", selectedNodes, selectedEdges)) return;
1618
+ applyNodeDeletionStrategy(draft, nodesToDelete, edgesToDelete, options.onDeleteNodes ?? "cascade");
999
1619
  draft.selection.clear();
1000
1620
  draft.focusedEntityId = null;
1621
+ for (const node of selectedNodes) draft.measurements.delete(node.id);
1622
+ for (const edge of selectedEdges) draft.measurements.delete(edge.id);
1623
+ pruneVisualState(draft, [...selectedNodes.map((node) => node.id), ...selectedEdges.map((edge) => edge.id)]);
1624
+ enqueue.emit.entitiesDeleted({
1625
+ ids: [...selectedNodes.map((node) => node.id), ...selectedEdges.map((edge) => edge.id)],
1626
+ event: createEventObject("deleteSelected", _event)
1627
+ });
1628
+ enqueue.emit.graphChanged({
1629
+ graph: snapshotGraph(draft.graph),
1630
+ event: createEventObject("deleteSelected", _event)
1631
+ });
1632
+ enqueue.emit.selectionChanged({
1633
+ selection: new Set(draft.selection),
1634
+ event: createEventObject("deleteSelected", _event)
1635
+ });
1001
1636
  }),
1002
- setGraph: (ctx, event) => produce(ctx, (draft) => {
1637
+ setGraph: (ctx, event, enqueue) => produce(ctx, (draft) => {
1003
1638
  draft.graph = event.graph;
1004
1639
  draft.selection.clear();
1640
+ draft.hoveredEntityIds = /* @__PURE__ */ new Set();
1641
+ draft.highlights = /* @__PURE__ */ new Map();
1005
1642
  draft.focusedEntityId = null;
1006
1643
  draft.canvasState = "idle";
1007
1644
  draft.draggedEntityId = null;
1008
1645
  draft.connection = null;
1009
1646
  draft.selectionBox = null;
1647
+ draft.measurements.clear();
1648
+ enqueue.emit.graphChanged({
1649
+ graph: snapshotGraph(draft.graph),
1650
+ event: createEventObject("setGraph", event)
1651
+ });
1652
+ enqueue.emit.selectionChanged({
1653
+ selection: new Set(draft.selection),
1654
+ event: createEventObject("setGraph", event)
1655
+ });
1010
1656
  }),
1011
- reset: (ctx) => produce(ctx, (draft) => {
1657
+ reset: (ctx, _event, enqueue) => produce(ctx, (draft) => {
1012
1658
  Object.assign(draft, {
1013
1659
  ...initialContext,
1014
1660
  viewportSize: draft.viewportSize
1015
1661
  });
1662
+ enqueue.emit.graphChanged({
1663
+ graph: snapshotGraph(draft.graph),
1664
+ event: createEventObject("reset", _event)
1665
+ });
1666
+ enqueue.emit.selectionChanged({
1667
+ selection: new Set(draft.selection),
1668
+ event: createEventObject("reset", _event)
1669
+ });
1016
1670
  }),
1017
- reparentNode: (ctx, event) => produce(ctx, (draft) => {
1671
+ reparentNode: (ctx, event, enqueue) => produce(ctx, (draft) => {
1018
1672
  const node = draft.graph.nodes.find((n) => n.id === event.id);
1019
- if (node) node.parentId = event.parentId;
1673
+ if (!node) return;
1674
+ const problem = reparentProblem(draft.graph, event.id, event.parentId);
1675
+ if (problem) {
1676
+ enqueue.emit.error({
1677
+ error: new Error(problem),
1678
+ event: createEventObject("reparentNode", event)
1679
+ });
1680
+ return;
1681
+ }
1682
+ node.parentId = event.parentId;
1683
+ enqueue.emit.graphChanged({
1684
+ graph: snapshotGraph(draft.graph),
1685
+ event: createEventObject("reparentNode", event)
1686
+ });
1020
1687
  }),
1021
1688
  dragStart: (ctx, event) => produce(ctx, (draft) => {
1689
+ if (!isExplicitlyDraggable(event.id, draft.graph)) return;
1022
1690
  draft.canvasState = "dragging";
1023
1691
  draft.draggedEntityId = event.id;
1024
1692
  draft.selection.add(event.id);
1025
1693
  }),
1026
- dragMove: (ctx, event) => produce(ctx, (draft) => {
1027
- if (draft.canvasState !== "dragging") return;
1694
+ dragMove: (ctx, event) => {
1695
+ if (ctx.canvasState !== "dragging") return ctx;
1028
1696
  const { dx, dy } = event;
1029
- if (dx === 0 && dy === 0) return;
1030
- for (const id of draft.selection) {
1031
- const node = draft.graph.nodes.find((n) => n.id === id);
1032
- if (node) {
1033
- let newDx = (node.dx ?? 0) + dx;
1034
- let newDy = (node.dy ?? 0) + dy;
1035
- if (draft.nodeExtent) {
1036
- const newX = node.x + newDx;
1037
- const newY = node.y + newDy;
1038
- const clampedX = Math.max(draft.nodeExtent[0].x, Math.min(newX, draft.nodeExtent[1].x - node.width));
1039
- const clampedY = Math.max(draft.nodeExtent[0].y, Math.min(newY, draft.nodeExtent[1].y - node.height));
1040
- newDx = clampedX - node.x;
1041
- newDy = clampedY - node.y;
1042
- }
1043
- node.dx = newDx;
1044
- node.dy = newDy;
1045
- continue;
1046
- }
1047
- const edge = draft.graph.edges.find((e) => e.id === id);
1048
- if (edge?.label) {
1049
- edge.label.dx = (edge.label.dx ?? 0) + dx;
1050
- edge.label.dy = (edge.label.dy ?? 0) + dy;
1051
- }
1052
- }
1053
- }),
1697
+ if (dx === 0 && dy === 0) return ctx;
1698
+ const plan = planNodeMovement(ctx, dx, dy, { includeLabels: true });
1699
+ if (!plan) return ctx;
1700
+ return produce(ctx, (draft) => {
1701
+ applyMovementPlan(draft, plan, dx, dy);
1702
+ });
1703
+ },
1054
1704
  dragEnd: (ctx) => produce(ctx, (draft) => {
1055
1705
  draft.canvasState = "idle";
1056
1706
  draft.draggedEntityId = null;
1057
1707
  }),
1058
- commitDrag: (ctx) => produce(ctx, (draft) => {
1708
+ commitDrag: (ctx, _event, enqueue) => produce(ctx, (draft) => {
1059
1709
  let snapOffX = 0;
1060
1710
  let snapOffY = 0;
1061
1711
  if (draft.enableSnapLines && draft.selection.size > 0) {
@@ -1111,23 +1761,49 @@ function createFlowStore(initialGraph = {
1111
1761
  edge.label.dy = 0;
1112
1762
  }
1113
1763
  }
1764
+ enqueue.emit.graphChanged({
1765
+ graph: snapshotGraph(draft.graph),
1766
+ event: createEventObject("commitDrag", _event)
1767
+ });
1114
1768
  }),
1115
- select: (ctx, event) => produce(ctx, (draft) => {
1769
+ select: (ctx, event, enqueue) => produce(ctx, (draft) => {
1116
1770
  const mode = event.mode ?? "single";
1117
1771
  if (mode === "single") draft.selection.clear();
1118
1772
  if (mode === "multi" && event.ids.every((id) => draft.selection.has(id))) for (const id of event.ids) draft.selection.delete(id);
1119
1773
  else for (const id of event.ids) draft.selection.add(id);
1774
+ enqueue.emit.selectionChanged({
1775
+ selection: new Set(draft.selection),
1776
+ event: createEventObject("select", event)
1777
+ });
1120
1778
  }),
1121
- selectAll: (ctx) => produce(ctx, (draft) => {
1122
- for (const node of draft.graph.nodes) draft.selection.add(node.id);
1123
- for (const edge of draft.graph.edges) draft.selection.add(edge.id);
1779
+ selectAll: (ctx, _event, enqueue) => produce(ctx, (draft) => {
1780
+ for (const node of draft.graph.nodes) {
1781
+ if (!isExplicitlyVisibleNode(node)) continue;
1782
+ draft.selection.add(node.id);
1783
+ }
1784
+ for (const edge of draft.graph.edges) {
1785
+ if (!isExplicitlyVisibleEdge(edge, draft.graph.nodes)) continue;
1786
+ draft.selection.add(edge.id);
1787
+ }
1788
+ enqueue.emit.selectionChanged({
1789
+ selection: new Set(draft.selection),
1790
+ event: createEventObject("selectAll", _event)
1791
+ });
1124
1792
  }),
1125
- clearSelection: (ctx) => produce(ctx, (draft) => {
1793
+ clearSelection: (ctx, _event, enqueue) => produce(ctx, (draft) => {
1126
1794
  draft.selection.clear();
1795
+ enqueue.emit.selectionChanged({
1796
+ selection: new Set(draft.selection),
1797
+ event: createEventObject("clearSelection", _event)
1798
+ });
1127
1799
  }),
1128
- selectionBoxStart: (ctx, event) => produce(ctx, (draft) => {
1800
+ selectionBoxStart: (ctx, event, enqueue) => produce(ctx, (draft) => {
1129
1801
  draft.canvasState = "selecting";
1130
1802
  if ((event.mode ?? "single") === "single") draft.selection.clear();
1803
+ enqueue.emit.selectionChanged({
1804
+ selection: new Set(draft.selection),
1805
+ event: createEventObject("selectionBoxStart", event)
1806
+ });
1131
1807
  draft.selectionBox = [{
1132
1808
  x: event.point.x,
1133
1809
  y: event.point.y
@@ -1143,12 +1819,16 @@ function createFlowStore(initialGraph = {
1143
1819
  y: event.point.y
1144
1820
  };
1145
1821
  }),
1146
- selectionBoxEnd: (ctx) => produce(ctx, (draft) => {
1822
+ selectionBoxEnd: (ctx, _event, enqueue) => produce(ctx, (draft) => {
1147
1823
  if (!draft.selectionBox) return;
1148
1824
  const rect = boxToRect(draft.selectionBox[0], draft.selectionBox[1]);
1149
1825
  const contains = draft.selectionMode === "full" ? rectContains : rectsIntersect;
1150
- for (const node of draft.graph.nodes) if (contains(rect, resolvedBounds(node))) draft.selection.add(node.id);
1826
+ for (const node of draft.graph.nodes) {
1827
+ if (!isExplicitlyVisibleNode(node)) continue;
1828
+ if (contains(rect, resolvedBounds(node))) draft.selection.add(node.id);
1829
+ }
1151
1830
  for (const edge of draft.graph.edges) {
1831
+ if (!isExplicitlyVisibleEdge(edge, draft.graph.nodes)) continue;
1152
1832
  if (edge.label) {
1153
1833
  if (contains(rect, {
1154
1834
  x: edge.label.x + (edge.label.dx ?? 0),
@@ -1169,6 +1849,10 @@ function createFlowStore(initialGraph = {
1169
1849
  }
1170
1850
  draft.selectionBox = null;
1171
1851
  draft.canvasState = "idle";
1852
+ enqueue.emit.selectionChanged({
1853
+ selection: new Set(draft.selection),
1854
+ event: createEventObject("selectionBoxEnd", _event)
1855
+ });
1172
1856
  }),
1173
1857
  focus: (ctx, event) => produce(ctx, (draft) => {
1174
1858
  draft.focusedEntityId = event.entityId;
@@ -1176,24 +1860,68 @@ function createFlowStore(initialGraph = {
1176
1860
  clearFocus: (ctx) => produce(ctx, (draft) => {
1177
1861
  draft.focusedEntityId = null;
1178
1862
  }),
1863
+ setHover: (ctx, event) => {
1864
+ if (ctx.hoveredEntityIds.size === event.ids.length && event.ids.every((id) => ctx.hoveredEntityIds.has(id))) return ctx;
1865
+ return produce(ctx, (draft) => {
1866
+ draft.hoveredEntityIds = new Set(event.ids);
1867
+ });
1868
+ },
1869
+ clearHover: (ctx) => {
1870
+ if (ctx.hoveredEntityIds.size === 0) return ctx;
1871
+ return produce(ctx, (draft) => {
1872
+ draft.hoveredEntityIds = /* @__PURE__ */ new Set();
1873
+ });
1874
+ },
1875
+ setHighlights: (ctx, event) => produce(ctx, (draft) => {
1876
+ const bucket = /* @__PURE__ */ new Map();
1877
+ for (const entry of event.entries) bucket.set(entry.id, entry.meta);
1878
+ if (bucket.size === 0) draft.highlights.delete(event.kind);
1879
+ else draft.highlights.set(event.kind, bucket);
1880
+ }),
1881
+ addHighlights: (ctx, event) => produce(ctx, (draft) => {
1882
+ let bucket = draft.highlights.get(event.kind);
1883
+ if (!bucket) {
1884
+ bucket = /* @__PURE__ */ new Map();
1885
+ draft.highlights.set(event.kind, bucket);
1886
+ }
1887
+ for (const entry of event.entries) bucket.set(entry.id, entry.meta);
1888
+ }),
1889
+ removeHighlights: (ctx, event) => produce(ctx, (draft) => {
1890
+ const bucket = draft.highlights.get(event.kind);
1891
+ if (!bucket) return;
1892
+ for (const id of event.ids) bucket.delete(id);
1893
+ if (bucket.size === 0) draft.highlights.delete(event.kind);
1894
+ }),
1895
+ clearHighlights: (ctx, event) => produce(ctx, (draft) => {
1896
+ if (event?.kind !== void 0) draft.highlights.delete(event.kind);
1897
+ else draft.highlights.clear();
1898
+ }),
1179
1899
  updateParentNodeId: (ctx, event) => produce(ctx, (draft) => {
1180
1900
  draft.parentNodeId = event.parentNodeId;
1181
1901
  draft.selection.clear();
1182
1902
  draft.focusedEntityId = null;
1183
1903
  }),
1184
- setViewport: (ctx, event) => produce(ctx, (draft) => {
1904
+ setViewport: (ctx, event, enqueue) => produce(ctx, (draft) => {
1185
1905
  draft.viewport = {
1186
1906
  x: event.x,
1187
1907
  y: event.y,
1188
1908
  zoom: event.zoom
1189
1909
  };
1910
+ enqueue.emit.viewportChanged({
1911
+ viewport: plainViewport(draft.viewport),
1912
+ event: createEventObject("setViewport", event)
1913
+ });
1190
1914
  }),
1191
- panBy: (ctx, event) => produce(ctx, (draft) => {
1915
+ panBy: (ctx, event, enqueue) => produce(ctx, (draft) => {
1192
1916
  draft.viewport.x += event.x;
1193
1917
  draft.viewport.y += event.y;
1194
1918
  if (draft.translateExtent) draft.viewport = constrainViewport(draft.viewport, draft.viewportSize, draft.translateExtent);
1919
+ enqueue.emit.viewportChanged({
1920
+ viewport: plainViewport(draft.viewport),
1921
+ event: createEventObject("panBy", event)
1922
+ });
1195
1923
  }),
1196
- zoomTo: (ctx, event) => produce(ctx, (draft) => {
1924
+ zoomTo: (ctx, event, enqueue) => produce(ctx, (draft) => {
1197
1925
  const clamped = Math.min(Math.max(event.zoom, draft.minZoom), draft.maxZoom);
1198
1926
  const ratio = clamped / draft.viewport.zoom;
1199
1927
  draft.viewport = {
@@ -1202,6 +1930,28 @@ function createFlowStore(initialGraph = {
1202
1930
  zoom: clamped
1203
1931
  };
1204
1932
  if (draft.translateExtent) draft.viewport = constrainViewport(draft.viewport, draft.viewportSize, draft.translateExtent);
1933
+ enqueue.emit.viewportChanged({
1934
+ viewport: plainViewport(draft.viewport),
1935
+ event: createEventObject("zoomTo", event)
1936
+ });
1937
+ }),
1938
+ zoomBy: (ctx, event, enqueue) => produce(ctx, (draft) => {
1939
+ const center = event.center ?? {
1940
+ x: draft.viewportSize.width / 2,
1941
+ y: draft.viewportSize.height / 2
1942
+ };
1943
+ const clamped = Math.min(Math.max(draft.viewport.zoom * event.factor, draft.minZoom), draft.maxZoom);
1944
+ const ratio = clamped / draft.viewport.zoom;
1945
+ draft.viewport = {
1946
+ x: center.x - (center.x - draft.viewport.x) * ratio,
1947
+ y: center.y - (center.y - draft.viewport.y) * ratio,
1948
+ zoom: clamped
1949
+ };
1950
+ if (draft.translateExtent) draft.viewport = constrainViewport(draft.viewport, draft.viewportSize, draft.translateExtent);
1951
+ enqueue.emit.viewportChanged({
1952
+ viewport: plainViewport(draft.viewport),
1953
+ event: createEventObject("zoomBy", event)
1954
+ });
1205
1955
  }),
1206
1956
  setMinZoom: (ctx, event) => produce(ctx, (draft) => {
1207
1957
  draft.minZoom = event.minZoom;
@@ -1231,20 +1981,32 @@ function createFlowStore(initialGraph = {
1231
1981
  height: event.height
1232
1982
  };
1233
1983
  }),
1234
- fitView: (ctx, event) => produce(ctx, (draft) => {
1984
+ fitView: (ctx, event, enqueue) => produce(ctx, (draft) => {
1235
1985
  if (draft.viewportSize.width === 0 || draft.viewportSize.height === 0) return;
1236
- const nodeIds = event?.nodes?.map((node) => typeof node === "string" ? node : node.id);
1237
- const bounds = getGraphBounds(nodeIds && nodeIds.length > 0 ? draft.graph.nodes.filter((node) => nodeIds.includes(node.id) && !node.hidden) : draft.graph.nodes.filter((node) => !node.hidden), nodeIds && nodeIds.length > 0 ? void 0 : draft.graph.edges.filter((edge) => !edge.hidden));
1986
+ const ids = event?.nodes?.map((node) => typeof node === "string" ? node : node.id);
1987
+ const hasIds = ids && ids.length > 0;
1988
+ const idSet = hasIds ? new Set(ids) : null;
1989
+ const bounds = getGraphBounds(hasIds ? draft.graph.nodes.filter((node) => idSet.has(node.id) && isExplicitlyVisibleNode(node)) : draft.graph.nodes.filter((node) => isExplicitlyVisibleNode(node)), hasIds ? draft.graph.edges.filter((edge) => idSet.has(edge.id) && isExplicitlyVisibleEdge(edge, draft.graph.nodes)) : draft.graph.edges.filter((edge) => isExplicitlyVisibleEdge(edge, draft.graph.nodes)));
1238
1990
  if (bounds.width === 0 && bounds.height === 0) return;
1239
1991
  const { nodes: _nodes, ...options } = event ?? {};
1240
1992
  draft.viewport = viewportForBounds(bounds, draft.viewportSize, options);
1993
+ enqueue.emit.viewportChanged({
1994
+ viewport: plainViewport(draft.viewport),
1995
+ event: createEventObject("fitView", event)
1996
+ });
1241
1997
  }),
1242
1998
  pushViewport: (ctx) => produce(ctx, (draft) => {
1243
1999
  draft.viewportStack.push({ ...draft.viewport });
1244
2000
  }),
1245
- popViewport: (ctx) => produce(ctx, (draft) => {
2001
+ popViewport: (ctx, _event, enqueue) => produce(ctx, (draft) => {
1246
2002
  const prev = draft.viewportStack.pop();
1247
- if (prev) draft.viewport = prev;
2003
+ if (prev) {
2004
+ draft.viewport = prev;
2005
+ enqueue.emit.viewportChanged({
2006
+ viewport: plainViewport(draft.viewport),
2007
+ event: createEventObject("popViewport", _event)
2008
+ });
2009
+ }
1248
2010
  }),
1249
2011
  panStart: (ctx, event) => produce(ctx, (draft) => {
1250
2012
  draft.canvasState = "panning";
@@ -1254,7 +2016,7 @@ function createFlowStore(initialGraph = {
1254
2016
  };
1255
2017
  draft.panViewportOrigin = { ...draft.viewport };
1256
2018
  }),
1257
- pan: (ctx, event) => produce(ctx, (draft) => {
2019
+ pan: (ctx, event, enqueue) => produce(ctx, (draft) => {
1258
2020
  if (!draft.panOrigin || !draft.panViewportOrigin) return;
1259
2021
  let newX = draft.panViewportOrigin.x + (event.x - draft.panOrigin.x);
1260
2022
  let newY = draft.panViewportOrigin.y + (event.y - draft.panOrigin.y);
@@ -1268,6 +2030,10 @@ function createFlowStore(initialGraph = {
1268
2030
  y: newY,
1269
2031
  zoom: draft.panViewportOrigin.zoom
1270
2032
  };
2033
+ enqueue.emit.viewportChanged({
2034
+ viewport: plainViewport(draft.viewport),
2035
+ event: createEventObject("pan", event)
2036
+ });
1271
2037
  }),
1272
2038
  panEnd: (ctx) => produce(ctx, (draft) => {
1273
2039
  draft.canvasState = "idle";
@@ -1302,13 +2068,14 @@ function createFlowStore(initialGraph = {
1302
2068
  if (!draft.connection.active && Math.hypot(dx, dy) >= threshold) draft.connection.active = true;
1303
2069
  }),
1304
2070
  connectionEnd: (ctx, event, enqueue) => produce(ctx, (draft) => {
1305
- if (draft.connection) enqueue.emit.connectionEnded({
2071
+ const connection = ctx.connection;
2072
+ if (connection) enqueue.emit.connectionEnded({
1306
2073
  source: {
1307
- nodeId: draft.connection.sourceId,
1308
- port: draft.connection.sourcePort
2074
+ nodeId: connection.sourceId,
2075
+ port: connection.sourcePort
1309
2076
  },
1310
2077
  target: event?.target ?? { kind: "none" },
1311
- connection: draft.connection
2078
+ connection
1312
2079
  });
1313
2080
  draft.canvasState = "idle";
1314
2081
  draft.connection = null;
@@ -1329,8 +2096,7 @@ function createFlowStore(initialGraph = {
1329
2096
  draft.resizeHandle = event.handle;
1330
2097
  const x = node.x + (node.dx ?? 0);
1331
2098
  const y = node.y + (node.dy ?? 0);
1332
- const w = node.style?.customWidth ?? node.width;
1333
- const h = node.style?.customHeight ?? node.height;
2099
+ const { width: w, height: h } = resolvedSize(node);
1334
2100
  const tl = {
1335
2101
  x,
1336
2102
  y
@@ -1389,7 +2155,7 @@ function createFlowStore(initialGraph = {
1389
2155
  y: event.y
1390
2156
  };
1391
2157
  }),
1392
- resizeEnd: (ctx) => produce(ctx, (draft) => {
2158
+ resizeEnd: (ctx, _event, enqueue) => produce(ctx, (draft) => {
1393
2159
  if (draft.resizingEntityId && draft.resizeCorners) {
1394
2160
  const node = draft.graph.nodes.find((n) => n.id === draft.resizingEntityId);
1395
2161
  if (node) {
@@ -1411,6 +2177,10 @@ function createFlowStore(initialGraph = {
1411
2177
  draft.resizingEntityId = null;
1412
2178
  draft.resizeHandle = null;
1413
2179
  draft.resizeCorners = null;
2180
+ enqueue.emit.graphChanged({
2181
+ graph: snapshotGraph(draft.graph),
2182
+ event: createEventObject("resizeEnd", _event)
2183
+ });
1414
2184
  }),
1415
2185
  resizeCancel: (ctx) => produce(ctx, (draft) => {
1416
2186
  draft.canvasState = "idle";
@@ -1418,30 +2188,31 @@ function createFlowStore(initialGraph = {
1418
2188
  draft.resizeHandle = null;
1419
2189
  draft.resizeCorners = null;
1420
2190
  }),
1421
- reconnectEdge: (ctx, event) => produce(ctx, (draft) => {
2191
+ reconnectEdge: (ctx, event, enqueue) => produce(ctx, (draft) => {
1422
2192
  const edge = draft.graph.edges.find((e) => e.id === event.edgeId);
1423
2193
  if (!edge) return;
2194
+ const resultingSourceId = event.newSourceId ?? edge.sourceId;
2195
+ const resultingTargetId = event.newTargetId ?? edge.targetId;
2196
+ const missing = [];
2197
+ if (!draft.graph.nodes.some((n) => n.id === resultingSourceId)) missing.push(`source node "${resultingSourceId}"`);
2198
+ if (!draft.graph.nodes.some((n) => n.id === resultingTargetId)) missing.push(`target node "${resultingTargetId}"`);
2199
+ if (missing.length > 0) {
2200
+ enqueue.emit.error({
2201
+ error: /* @__PURE__ */ new Error(`reconnectEdge rejected: edge "${event.edgeId}" references ${missing.join(" and ")}, which ${missing.length === 1 ? "does" : "do"} not exist in the graph.`),
2202
+ event: createEventObject("reconnectEdge", event)
2203
+ });
2204
+ return;
2205
+ }
1424
2206
  if (event.newSourceId !== void 0) edge.sourceId = event.newSourceId;
1425
2207
  if (event.newTargetId !== void 0) edge.targetId = event.newTargetId;
1426
2208
  if (event.newSourcePort !== void 0) edge.sourcePort = event.newSourcePort;
1427
2209
  if (event.newTargetPort !== void 0) edge.targetPort = event.newTargetPort;
2210
+ enqueue.emit.graphChanged({
2211
+ graph: snapshotGraph(draft.graph),
2212
+ event: createEventObject("reconnectEdge", event)
2213
+ });
1428
2214
  }),
1429
- reportPortMeasurements: (ctx, event) => produce(ctx, (draft) => {
1430
- for (const m of event.measurements) {
1431
- const node = draft.graph.nodes.find((n) => n.id === m.nodeId);
1432
- if (!node?.ports) continue;
1433
- const port = node.ports.find((p) => p.name === m.portName);
1434
- if (port) {
1435
- port.x = m.x;
1436
- port.y = m.y;
1437
- port.width = m.width;
1438
- port.height = m.height;
1439
- }
1440
- }
1441
- }),
1442
- setInteractionMode: (ctx, event) => produce(ctx, (draft) => {
1443
- draft.interactionMode = event.mode;
1444
- }),
2215
+ setMode: (ctx, event, enqueue) => dispatchProfile(profile, ctx, createEventObject("setMode", event), enqueue, setModeTransition(profile)),
1445
2216
  setSnapToGrid: (ctx, event) => produce(ctx, (draft) => {
1446
2217
  draft.snapToGrid = event.enabled;
1447
2218
  if (event.grid) draft.snapGrid = event.grid;
@@ -1451,22 +2222,24 @@ function createFlowStore(initialGraph = {
1451
2222
  if (event.threshold !== void 0) draft.snapThreshold = event.threshold;
1452
2223
  if (event.spacing !== void 0) draft.enableSpacingGuides = event.spacing;
1453
2224
  }),
1454
- moveNodes: (ctx, event) => produce(ctx, (draft) => {
2225
+ setColorMode: (ctx, event) => produce(ctx, (draft) => {
2226
+ draft.colorMode = event.colorMode;
2227
+ }),
2228
+ moveNodes: (ctx, event) => {
1455
2229
  const f = event.factor ?? 1;
1456
2230
  let dx = event.direction.x * f;
1457
2231
  let dy = event.direction.y * f;
1458
- if (draft.snapToGrid) {
1459
- dx = dx !== 0 ? Math.sign(dx) * draft.snapGrid[0] : 0;
1460
- dy = dy !== 0 ? Math.sign(dy) * draft.snapGrid[1] : 0;
1461
- }
1462
- for (const id of draft.selection) {
1463
- const node = draft.graph.nodes.find((n) => n.id === id);
1464
- if (node) {
1465
- node.dx = (node.dx ?? 0) + dx;
1466
- node.dy = (node.dy ?? 0) + dy;
1467
- }
2232
+ if (ctx.snapToGrid) {
2233
+ dx = dx !== 0 ? Math.sign(dx) * ctx.snapGrid[0] : 0;
2234
+ dy = dy !== 0 ? Math.sign(dy) * ctx.snapGrid[1] : 0;
1468
2235
  }
1469
- }),
2236
+ if (dx === 0 && dy === 0) return ctx;
2237
+ const plan = planNodeMovement(ctx, dx, dy, { includeLabels: true });
2238
+ if (!plan) return ctx;
2239
+ return produce(ctx, (draft) => {
2240
+ applyMovementPlan(draft, plan, dx, dy);
2241
+ });
2242
+ },
1470
2243
  requestLayout: (ctx, event, enqueue) => produce(ctx, (draft) => {
1471
2244
  if (draft.canvasState === "dragging") return;
1472
2245
  const algorithm = event.algorithm ?? draft.autoLayout.algorithm;
@@ -1480,7 +2253,7 @@ function createFlowStore(initialGraph = {
1480
2253
  graph: ctx.graph
1481
2254
  });
1482
2255
  }),
1483
- applyLayoutResult: (ctx, event) => produce(ctx, (draft) => {
2256
+ applyLayoutResult: (ctx, event, enqueue) => produce(ctx, (draft) => {
1484
2257
  for (const [id, pos] of event.positions) {
1485
2258
  const node = draft.graph.nodes.find((n) => n.id === id);
1486
2259
  if (node) {
@@ -1500,23 +2273,44 @@ function createFlowStore(initialGraph = {
1500
2273
  }
1501
2274
  }
1502
2275
  draft.autoLayout.status = "idle";
2276
+ enqueue.emit.graphChanged({
2277
+ graph: snapshotGraph(draft.graph),
2278
+ event: createEventObject("applyLayoutResult", event)
2279
+ });
1503
2280
  }),
1504
- reportMeasurements: (ctx, event) => produce(ctx, (draft) => {
1505
- for (const [id, dims] of event.measurements) {
1506
- const node = draft.graph.nodes.find((n) => n.id === id);
2281
+ updateMeasurements: (ctx, event) => produce(ctx, (draft) => {
2282
+ for (const measurement of event.measurements) {
2283
+ draft.measurements.set(measurement.id, measurement.rect);
2284
+ const node = draft.graph.nodes.find((n) => n.id === measurement.id);
1507
2285
  if (node) {
1508
- node.width = dims.width;
1509
- node.height = dims.height;
2286
+ if (node.autoSize) node.measured = {
2287
+ width: measurement.rect.width,
2288
+ height: measurement.rect.height
2289
+ };
1510
2290
  continue;
1511
2291
  }
1512
- const edge = draft.graph.edges.find((e) => e.id === id);
2292
+ const edge = draft.graph.edges.find((e) => e.id === measurement.id);
1513
2293
  if (edge?.label) {
1514
- edge.label.width = dims.width;
1515
- edge.label.height = dims.height;
2294
+ edge.label.width = measurement.rect.width;
2295
+ edge.label.height = measurement.rect.height;
2296
+ continue;
2297
+ }
2298
+ for (const candidate of draft.graph.nodes) {
2299
+ const port = candidate.ports?.find((p) => p.id === measurement.id || `${candidate.id}:${p.name}` === measurement.id);
2300
+ if (port) {
2301
+ port.x = measurement.rect.x - (candidate.x + (candidate.dx ?? 0));
2302
+ port.y = measurement.rect.y - (candidate.y + (candidate.dy ?? 0));
2303
+ port.width = measurement.rect.width;
2304
+ port.height = measurement.rect.height;
2305
+ break;
2306
+ }
1516
2307
  }
1517
2308
  }
1518
2309
  }),
1519
- bakeLabelPositions: (ctx, event) => produce(ctx, (draft) => {
2310
+ removeMeasurements: (ctx, event) => produce(ctx, (draft) => {
2311
+ for (const id of event.ids) draft.measurements.delete(id);
2312
+ }),
2313
+ bakeLabelPositions: (ctx, event, enqueue) => produce(ctx, (draft) => {
1520
2314
  for (const [edgeId, center] of event.positions) {
1521
2315
  const edge = draft.graph.edges.find((e) => e.id === edgeId);
1522
2316
  if (edge?.label) {
@@ -1526,6 +2320,10 @@ function createFlowStore(initialGraph = {
1526
2320
  edge.label.dy = 0;
1527
2321
  }
1528
2322
  }
2323
+ enqueue.emit.graphChanged({
2324
+ graph: snapshotGraph(draft.graph),
2325
+ event: createEventObject("bakeLabelPositions", event)
2326
+ });
1529
2327
  })
1530
2328
  }
1531
2329
  }).with(undoRedo({
@@ -1817,16 +2615,150 @@ function createFlowEngine(store, options = {}) {
1817
2615
  function ctx() {
1818
2616
  return store.getSnapshot().context;
1819
2617
  }
1820
- function getNode(id) {
1821
- return ctx().graph.nodes.find((n) => n.id === id);
2618
+ const edgePathsCache = /* @__PURE__ */ new WeakMap();
2619
+ const snapOffsetCache = /* @__PURE__ */ new WeakMap();
2620
+ const renderableCache = /* @__PURE__ */ new WeakMap();
2621
+ const groupGeometryCache = /* @__PURE__ */ new WeakMap();
2622
+ const edgeOwnerCache = /* @__PURE__ */ new WeakMap();
2623
+ function ownedEdges(c) {
2624
+ let index = edgeOwnerCache.get(c);
2625
+ if (!index) {
2626
+ index = /* @__PURE__ */ new Map();
2627
+ for (const edge of c.graph.edges) {
2628
+ const custom = options.edgeOwner?.(edge, c);
2629
+ const owner = options.edgeOwner && custom !== void 0 ? custom : getEdgeOwner(edge, c.graph.nodes);
2630
+ if (owner == null) continue;
2631
+ let bucket = index.get(owner);
2632
+ if (!bucket) index.set(owner, bucket = []);
2633
+ bucket.push(edge);
2634
+ }
2635
+ edgeOwnerCache.set(c, index);
2636
+ }
2637
+ return index;
1822
2638
  }
1823
- function getEdge(id) {
1824
- return ctx().graph.edges.find((e) => e.id === id);
2639
+ const highlightIndexCache = /* @__PURE__ */ new WeakMap();
2640
+ const NO_HIGHLIGHTS = [];
2641
+ /**
2642
+ * Group geometry per snapshot, derived bottom-up. `derived` groups are a
2643
+ * pure function of their children's (visual) bounds — recomputed per
2644
+ * transition, so containment can't drift and sizing is reversible.
2645
+ */
2646
+ function groupGeometryFor(c, node, visiting) {
2647
+ if (!node.group) return null;
2648
+ let byId = groupGeometryCache.get(c);
2649
+ const cached = byId?.get(node.id);
2650
+ if (cached !== void 0) return cached;
2651
+ const geometry = computeGroupGeometryRaw(c, node, visiting, void 0);
2652
+ if (!byId) {
2653
+ byId = /* @__PURE__ */ new Map();
2654
+ groupGeometryCache.set(c, byId);
2655
+ }
2656
+ byId.set(node.id, geometry);
2657
+ return geometry;
1825
2658
  }
1826
- function getEntity(id) {
1827
- return getNode(id) ?? getEdge(id);
2659
+ function computeGroupGeometryRaw(c, node, visiting, excludeChildren) {
2660
+ const contentSize = resolvedSize(node);
2661
+ if (node.group.type === "fixed") return fixedGroupGeometry(resolvedBounds(node), node.group.contentSize ?? {
2662
+ width: 0,
2663
+ height: 0
2664
+ }, node.group);
2665
+ const seen = visiting ?? /* @__PURE__ */ new Set();
2666
+ seen.add(node.id);
2667
+ let union = null;
2668
+ const children = indexChildren(c.graph.nodes).get(node.id);
2669
+ for (const child of children ?? []) {
2670
+ if (child.hidden || seen.has(child.id)) continue;
2671
+ if (excludeChildren?.has(child.id)) continue;
2672
+ const b = isDerivedGroup(child) ? excludeChildren ? computeGroupGeometryRaw(c, child, seen, excludeChildren).bounds : groupGeometryFor(c, child, seen)?.bounds ?? resolvedBounds(child) : hierarchyBounds(child, c);
2673
+ union = uniteRects(union, b);
2674
+ }
2675
+ for (const edge of ownedEdges(c).get(node.id) ?? []) {
2676
+ if (edge.hidden || !edge.label) continue;
2677
+ if (edge.sourceId === node.id && edge.targetId === node.id) continue;
2678
+ const label = edge.label;
2679
+ if (!label.width && !label.height) continue;
2680
+ union = uniteRects(union, {
2681
+ x: label.x + (label.dx ?? 0),
2682
+ y: label.y + (label.dy ?? 0),
2683
+ width: label.width,
2684
+ height: label.height
2685
+ });
2686
+ }
2687
+ return deriveGroupGeometry(contentSize, union, node.group, resolvedPosition(node));
1828
2688
  }
1829
- function screenToCanvas$1(screenPoint) {
2689
+ function uniteRects(union, b) {
2690
+ return union ? unionRect(union, b) : { ...b };
2691
+ }
2692
+ /** Bounds with group hierarchy applied (derived groups wrap their children). */
2693
+ function hierarchyBounds(node, c) {
2694
+ if (isDerivedGroup(node)) {
2695
+ const geometry = groupGeometryFor(c, node);
2696
+ if (geometry) return geometry.bounds;
2697
+ }
2698
+ return resolvedBounds(node);
2699
+ }
2700
+ const edgePathMemo = /* @__PURE__ */ new Map();
2701
+ let edgePathMemoInputs = null;
2702
+ function getNode(id) {
2703
+ return indexNodes(ctx().graph.nodes).get(id);
2704
+ }
2705
+ function getEdge(id) {
2706
+ return indexEdges(ctx().graph.edges).get(id);
2707
+ }
2708
+ function getEntity(id) {
2709
+ return getNode(id) ?? getEdge(id);
2710
+ }
2711
+ function isNodeVisible(node, c, viewport = c.viewport) {
2712
+ if (node.hidden) return false;
2713
+ if (globalConfig.visible && !resolveBehavior(globalConfig.visible, node, c)) return false;
2714
+ if (isVisibleHook && !isVisibleHook(node, viewport)) return false;
2715
+ return true;
2716
+ }
2717
+ function isEdgeVisible(edge, graph, c, viewport = c.viewport) {
2718
+ if (edge.hidden) return false;
2719
+ const nodeIndex = indexNodes(graph.nodes);
2720
+ const source = nodeIndex.get(edge.sourceId);
2721
+ const target = nodeIndex.get(edge.targetId);
2722
+ if (!source || !target) return false;
2723
+ if (!isNodeVisible(source, c, viewport) || !isNodeVisible(target, c, viewport)) return false;
2724
+ if (globalConfig.visible && !resolveBehavior(globalConfig.visible, edge, c)) return false;
2725
+ if (isVisibleHook && !isVisibleHook(edge, viewport)) return false;
2726
+ return true;
2727
+ }
2728
+ function getAddressable(id) {
2729
+ const node = getNode(id);
2730
+ if (node) return {
2731
+ kind: "node",
2732
+ id,
2733
+ node
2734
+ };
2735
+ const edge = getEdge(id);
2736
+ if (edge) return {
2737
+ kind: "edge",
2738
+ id,
2739
+ edge
2740
+ };
2741
+ for (const candidate of ctx().graph.nodes) {
2742
+ const port = candidate.ports?.find((p) => p.id === id || `${candidate.id}:${p.name}` === id);
2743
+ if (port) return {
2744
+ kind: "port",
2745
+ id,
2746
+ nodeId: candidate.id,
2747
+ portName: port.name,
2748
+ port
2749
+ };
2750
+ }
2751
+ return null;
2752
+ }
2753
+ function getOwnerEntity(id) {
2754
+ const addressable = getAddressable(id);
2755
+ if (!addressable) return null;
2756
+ if (addressable.kind === "node") return addressable.node;
2757
+ if (addressable.kind === "edge") return addressable.edge;
2758
+ if (addressable.kind === "port") return getNode(addressable.nodeId) ?? null;
2759
+ return getEntity(addressable.ownerId) ?? null;
2760
+ }
2761
+ function screenToCanvas$1(screenPoint) {
1830
2762
  return screenToCanvas(screenPoint, ctx().viewport);
1831
2763
  }
1832
2764
  function canvasToScreen$1(canvasPoint) {
@@ -1834,10 +2766,11 @@ function createFlowEngine(store, options = {}) {
1834
2766
  }
1835
2767
  function entityAtPoint(canvasPoint) {
1836
2768
  const { graph } = ctx();
2769
+ const c = ctx();
1837
2770
  for (let i = graph.nodes.length - 1; i >= 0; i--) {
1838
2771
  const node = graph.nodes[i];
1839
2772
  if (!node) continue;
1840
- const bounds = resolvedBounds(node);
2773
+ const bounds = hierarchyBounds(node, c);
1841
2774
  if (getShapeOrDefault(node.shape ?? "rect").hitTest(canvasPoint, bounds)) return node;
1842
2775
  }
1843
2776
  const nodeMap = /* @__PURE__ */ new Map();
@@ -1863,10 +2796,11 @@ function createFlowEngine(store, options = {}) {
1863
2796
  }
1864
2797
  function getEdgePath(edgeId) {
1865
2798
  const { graph } = ctx();
1866
- const edge = graph.edges.find((e) => e.id === edgeId);
2799
+ const edge = indexEdges(graph.edges).get(edgeId);
1867
2800
  if (!edge) return null;
1868
- const sourceNode = graph.nodes.find((n) => n.id === edge.sourceId);
1869
- const targetNode = graph.nodes.find((n) => n.id === edge.targetId);
2801
+ const nodeIndex = indexNodes(graph.nodes);
2802
+ const sourceNode = nodeIndex.get(edge.sourceId);
2803
+ const targetNode = nodeIndex.get(edge.targetId);
1870
2804
  if (!sourceNode || !targetNode) return null;
1871
2805
  const srcBounds = resolvedBounds(sourceNode);
1872
2806
  const tgtBounds = resolvedBounds(targetNode);
@@ -1882,6 +2816,40 @@ function createFlowEngine(store, options = {}) {
1882
2816
  obstacles: []
1883
2817
  });
1884
2818
  }
2819
+ function getEdgePathBounds(edgeId) {
2820
+ const path = getAllEdgePaths().get(edgeId);
2821
+ if (!path) return null;
2822
+ return boundsForPoints(path.segments.flatMap((segment) => segment.points));
2823
+ }
2824
+ function getEdgeLabelBounds(edgeId) {
2825
+ const measured = ctx().measurements.get(edgeId);
2826
+ if (measured) return measured;
2827
+ const edge = getEdge(edgeId);
2828
+ if (!edge?.label) return null;
2829
+ const nodeMap = /* @__PURE__ */ new Map();
2830
+ for (const n of ctx().graph.nodes) nodeMap.set(n.id, n);
2831
+ return resolveEdgeLabelBounds(edge, nodeMap);
2832
+ }
2833
+ function getBounds(id) {
2834
+ const measured = ctx().measurements.get(id);
2835
+ if (measured) return measured;
2836
+ const addressable = getAddressable(id);
2837
+ if (!addressable) return null;
2838
+ if (addressable.kind === "node") return resolvedBounds(addressable.node);
2839
+ if (addressable.kind === "edge") return getEdgeLabelBounds(id) ?? getEdgePathBounds(id);
2840
+ if (addressable.kind === "port") {
2841
+ const owner = getNode(addressable.nodeId);
2842
+ if (!owner) return null;
2843
+ const ownerPosition = resolvedPosition(owner);
2844
+ return {
2845
+ x: ownerPosition.x + addressable.port.x,
2846
+ y: ownerPosition.y + addressable.port.y,
2847
+ width: addressable.port.width,
2848
+ height: addressable.port.height
2849
+ };
2850
+ }
2851
+ return null;
2852
+ }
1885
2853
  /** Resolve edge label bounds using committed (static) node positions */
1886
2854
  function resolveEdgeLabelBounds(edge, nodeMap) {
1887
2855
  if (!edge.label) return null;
@@ -1965,16 +2933,20 @@ function createFlowEngine(store, options = {}) {
1965
2933
  }
1966
2934
  return rects;
1967
2935
  }
1968
- /** Check if rect `a` fully contains rect `b` */
1969
- function rectContains(a, b) {
1970
- return b.x >= a.x && b.y >= a.y && b.x + b.width <= a.x + a.width && b.y + b.height <= a.y + a.height;
1971
- }
1972
2936
  /**
1973
2937
  * Compute visual snap offset for edge routing.
1974
2938
  * Returns the offset to apply to selected nodes so edges follow the snapped visual position.
2939
+ * Memoized per store snapshot — callers invoke this once per node per frame.
1975
2940
  */
1976
2941
  function getVisualSnapOffset() {
1977
2942
  const c = ctx();
2943
+ const cached = snapOffsetCache.get(c);
2944
+ if (cached) return cached;
2945
+ const result = computeVisualSnapOffset(c);
2946
+ snapOffsetCache.set(c, result);
2947
+ return result;
2948
+ }
2949
+ function computeVisualSnapOffset(c) {
1978
2950
  const selection = c.selection;
1979
2951
  const grid = c.snapToGrid ? c.snapGrid : null;
1980
2952
  let offset = {
@@ -2004,9 +2976,37 @@ function createFlowEngine(store, options = {}) {
2004
2976
  }
2005
2977
  /** Get visual bounds for a node — applies snap offset for selected nodes during drag */
2006
2978
  function visualBounds(node, snap) {
2979
+ const c = ctx();
2980
+ if (c.canvasState === "resizing" && c.resizingEntityId === node.id) {
2981
+ const resizeBounds = getResizeBoundsFromContext(c);
2982
+ if (resizeBounds) return resizeBounds;
2983
+ }
2984
+ if (isDerivedGroup(node)) {
2985
+ const geometry = groupGeometryFor(c, node);
2986
+ if (geometry) return geometry.bounds;
2987
+ }
2007
2988
  const entityOffset = snap.selection.has(node.id) ? snap.offset : null;
2008
2989
  return snappedBounds(node, snap.grid, entityOffset);
2009
2990
  }
2991
+ function visualLabelBounds(edge, basePos, snap) {
2992
+ const isSelected = snap.selection.has(edge.id);
2993
+ let x = basePos.x + (edge.label?.dx ?? 0);
2994
+ let y = basePos.y + (edge.label?.dy ?? 0);
2995
+ if (isSelected) {
2996
+ x += snap.offset.x;
2997
+ y += snap.offset.y;
2998
+ if (snap.grid) {
2999
+ x = snapToGrid(x, snap.grid[0]);
3000
+ y = snapToGrid(y, snap.grid[1]);
3001
+ }
3002
+ }
3003
+ return {
3004
+ x,
3005
+ y,
3006
+ width: edge.label?.width ?? 0,
3007
+ height: edge.label?.height ?? 0
3008
+ };
3009
+ }
2010
3010
  /** Get visual position for a node — applies snap offset for selected nodes during drag */
2011
3011
  function visualPosition(node, snap) {
2012
3012
  const b = visualBounds(node, snap);
@@ -2032,6 +3032,10 @@ function createFlowEngine(store, options = {}) {
2032
3032
  if (snap) return visualBounds(node, snap);
2033
3033
  return resolvedBounds(node);
2034
3034
  }
3035
+ function portSideOf(node, portName) {
3036
+ if (!portName || portName === "*" || !node.ports) return null;
3037
+ return node.ports.find((p) => p.name === portName)?.side ?? null;
3038
+ }
2035
3039
  function getShapeAnchor(node, bounds, direction) {
2036
3040
  return getShapeOrDefault(node.shape ?? "rect").edgeAnchor(bounds, direction);
2037
3041
  }
@@ -2052,70 +3056,121 @@ function createFlowEngine(store, options = {}) {
2052
3056
  }
2053
3057
  return getShapeAnchor(node, nodeBounds, fallbackDirection);
2054
3058
  }
2055
- function getAllEdgePaths() {
2056
- const { graph } = ctx();
3059
+ /**
3060
+ * Resolve the geometry shared by edge rendering and endpoint queries: the
3061
+ * endpoint bounds, the facing direction of each end, and the anchor points.
3062
+ * Single source of truth so rendered paths and `getEdgeEndpoints` can never
3063
+ * disagree on which side of a node an edge attaches to.
3064
+ */
3065
+ function resolveEdgeGeometry(edge, source, target, snap) {
3066
+ const sourceBounds = getEndpointBounds(source, edge.sourcePort, snap);
3067
+ const targetBounds = getEndpointBounds(target, edge.targetPort, snap);
3068
+ const sourceDirection = portSideOf(source, edge.sourcePort) ?? bestDirection(sourceBounds, targetBounds);
3069
+ const targetDirection = portSideOf(target, edge.targetPort) ?? bestDirection(targetBounds, sourceBounds);
3070
+ return {
3071
+ sourceBounds,
3072
+ targetBounds,
3073
+ sourceDirection,
3074
+ targetDirection,
3075
+ sourcePoint: resolveEndpointPoint(source, sourceBounds, edge.sourcePort, targetBounds, sourceDirection, snap),
3076
+ targetPoint: resolveEndpointPoint(target, targetBounds, edge.targetPort, sourceBounds, targetDirection, snap)
3077
+ };
3078
+ }
3079
+ /**
3080
+ * Route all edges. Memoized per (store snapshot, graph) pair — repeated
3081
+ * calls within one transition (edge layer, label layer, hit testing) reuse
3082
+ * the same Map. Callers must treat the result as read-only.
3083
+ */
3084
+ function getAllEdgePaths(options = {}) {
3085
+ const c = ctx();
3086
+ const graph = options.graph ?? c.graph;
3087
+ let byGraph = edgePathsCache.get(c);
3088
+ const cached = byGraph?.get(graph);
3089
+ if (cached) return cached;
3090
+ const paths = computeAllEdgePaths(c, graph);
3091
+ if (!byGraph) {
3092
+ byGraph = /* @__PURE__ */ new WeakMap();
3093
+ edgePathsCache.set(c, byGraph);
3094
+ }
3095
+ byGraph.set(graph, paths);
3096
+ return paths;
3097
+ }
3098
+ function computeAllEdgePaths(c, graph) {
2057
3099
  const paths = /* @__PURE__ */ new Map();
2058
3100
  const snap = getVisualSnapOffset();
2059
- const nodeMap = /* @__PURE__ */ new Map();
2060
- for (const n of graph.nodes) nodeMap.set(n.id, n);
3101
+ const nodeMap = indexNodes(graph.nodes);
3102
+ const memoUsable = !isVisibleHook && !globalConfig.visible;
3103
+ if (memoUsable) {
3104
+ const inputs = edgePathMemoInputs;
3105
+ if (!inputs || inputs.canvasState !== c.canvasState || inputs.selection !== c.selection || inputs.offsetX !== snap.offset.x || inputs.offsetY !== snap.offset.y || inputs.grid !== snap.grid || inputs.resizingEntityId !== c.resizingEntityId || inputs.resizeCorners !== c.resizeCorners) {
3106
+ edgePathMemo.clear();
3107
+ edgePathMemoInputs = {
3108
+ canvasState: c.canvasState,
3109
+ selection: c.selection,
3110
+ offsetX: snap.offset.x,
3111
+ offsetY: snap.offset.y,
3112
+ grid: snap.grid,
3113
+ resizingEntityId: c.resizingEntityId,
3114
+ resizeCorners: c.resizeCorners
3115
+ };
3116
+ }
3117
+ }
2061
3118
  for (const edge of graph.edges) {
2062
3119
  const source = nodeMap.get(edge.sourceId);
2063
3120
  const target = nodeMap.get(edge.targetId);
2064
3121
  if (!source || !target) continue;
2065
- const sourceBounds = getEndpointBounds(source, edge.sourcePort, snap);
2066
- const targetBounds = getEndpointBounds(target, edge.targetPort, snap);
2067
- const sourceDirection = bestDirection(sourceBounds, targetBounds);
2068
- const targetDirection = bestDirection(targetBounds, sourceBounds);
2069
- const sourcePoint = resolveEndpointPoint(source, sourceBounds, edge.sourcePort, targetBounds, targetDirection, snap);
2070
- const targetPoint = resolveEndpointPoint(target, targetBounds, edge.targetPort, sourceBounds, sourceDirection, snap);
3122
+ if (!isEdgeVisible(edge, graph, c)) continue;
3123
+ const memoizableEdge = memoUsable && !isDerivedGroup(source) && !isDerivedGroup(target);
3124
+ if (memoizableEdge) {
3125
+ const entry = edgePathMemo.get(edge.id);
3126
+ if (entry && entry.edge === edge && entry.source === source && entry.target === target) {
3127
+ paths.set(edge.id, entry.path);
3128
+ continue;
3129
+ }
3130
+ }
3131
+ const { sourceBounds, targetBounds, sourcePoint, targetPoint } = resolveEdgeGeometry(edge, source, target, snap);
3132
+ let pathData;
2071
3133
  if (edge.label) {
2072
- const basePos = resolveLabelAnchor(edge.labelAnchor ?? defaultLabelAnchor, edge.label, sourceBounds, targetBounds);
2073
- const snapOff = snap.selection.has(edge.id) ? snap.offset : {
2074
- x: 0,
2075
- y: 0
2076
- };
2077
- const labelBounds = {
2078
- x: basePos.x + (edge.label.dx ?? 0) + snapOff.x,
2079
- y: basePos.y + (edge.label.dy ?? 0) + snapOff.y,
2080
- width: edge.label.width,
2081
- height: edge.label.height
2082
- };
2083
- const seg1 = router(edge, {
2084
- sourceBounds,
2085
- targetBounds: labelBounds,
2086
- sourceDirection: bestDirection(sourceBounds, labelBounds),
2087
- targetDirection: bestDirection(labelBounds, sourceBounds),
2088
- sourcePoint,
2089
- obstacles: []
2090
- });
2091
- const seg2 = router(edge, {
2092
- sourceBounds: labelBounds,
2093
- targetBounds,
2094
- sourceDirection: bestDirection(labelBounds, targetBounds),
2095
- targetDirection: bestDirection(targetBounds, labelBounds),
2096
- targetPoint,
2097
- obstacles: []
2098
- });
2099
- paths.set(edge.id, {
2100
- segments: [seg1, seg2],
3134
+ const labelBounds = visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? defaultLabelAnchor, edge.label, sourceBounds, targetBounds), snap);
3135
+ pathData = {
3136
+ segments: [router(edge, {
3137
+ sourceBounds,
3138
+ targetBounds: labelBounds,
3139
+ sourceDirection: portSideOf(source, edge.sourcePort) ?? bestDirection(sourceBounds, labelBounds),
3140
+ targetDirection: bestDirection(labelBounds, sourceBounds),
3141
+ sourcePoint,
3142
+ obstacles: []
3143
+ }), router(edge, {
3144
+ sourceBounds: labelBounds,
3145
+ targetBounds,
3146
+ sourceDirection: bestDirection(labelBounds, targetBounds),
3147
+ targetDirection: portSideOf(target, edge.targetPort) ?? bestDirection(targetBounds, labelBounds),
3148
+ targetPoint,
3149
+ obstacles: []
3150
+ })],
2101
3151
  labelBounds
2102
- });
2103
- } else {
2104
- const path = router(edge, {
3152
+ };
3153
+ } else pathData = {
3154
+ segments: [router(edge, {
2105
3155
  sourceBounds,
2106
3156
  targetBounds,
2107
- sourceDirection: bestDirection(sourceBounds, targetBounds),
2108
- targetDirection: bestDirection(targetBounds, sourceBounds),
3157
+ sourceDirection: portSideOf(source, edge.sourcePort) ?? bestDirection(sourceBounds, targetBounds),
3158
+ targetDirection: portSideOf(target, edge.targetPort) ?? bestDirection(targetBounds, sourceBounds),
2109
3159
  sourcePoint,
2110
3160
  targetPoint,
2111
3161
  obstacles: []
2112
- });
2113
- paths.set(edge.id, {
2114
- segments: [path],
2115
- labelBounds: null
2116
- });
2117
- }
3162
+ })],
3163
+ labelBounds: null
3164
+ };
3165
+ paths.set(edge.id, pathData);
3166
+ if (memoizableEdge) edgePathMemo.set(edge.id, {
3167
+ edge,
3168
+ source,
3169
+ target,
3170
+ path: pathData
3171
+ });
2118
3172
  }
3173
+ if (memoUsable && edgePathMemo.size > graph.edges.length * 2 + 16) edgePathMemo.clear();
2119
3174
  return paths;
2120
3175
  }
2121
3176
  function subscribe(listener) {
@@ -2124,6 +3179,46 @@ function createFlowEngine(store, options = {}) {
2124
3179
  });
2125
3180
  return () => subscription.unsubscribe();
2126
3181
  }
3182
+ function computeRenderableEntities(c, options) {
3183
+ const vp = c.viewport;
3184
+ const overscan = options.overscan ?? 0;
3185
+ const visibleRect = getVisibleBounds(vp, c.viewportSize);
3186
+ const cullRect = {
3187
+ x: visibleRect.x - overscan,
3188
+ y: visibleRect.y - overscan,
3189
+ width: visibleRect.width + overscan * 2,
3190
+ height: visibleRect.height + overscan * 2
3191
+ };
3192
+ const cullMode = options.cull === "viewport" && rectContains(cullRect, getGraphBounds(c.graph.nodes, c.graph.edges)) ? "none" : options.cull;
3193
+ const nodes = c.graph.nodes.filter((n) => {
3194
+ if (!isNodeVisible(n, c, vp)) return false;
3195
+ if (cullMode === "viewport" && !rectsIntersect(hierarchyBounds(n, c), cullRect)) return false;
3196
+ return true;
3197
+ });
3198
+ const edgePaths = getAllEdgePaths();
3199
+ return {
3200
+ nodes,
3201
+ edges: c.graph.edges.filter((e) => {
3202
+ if (!isEdgeVisible(e, c.graph, c, vp)) return false;
3203
+ if (cullMode !== "viewport") return true;
3204
+ if (e.label) {
3205
+ if (rectsIntersect({
3206
+ x: e.label.x + (e.label.dx ?? 0),
3207
+ y: e.label.y + (e.label.dy ?? 0),
3208
+ width: e.label.width,
3209
+ height: e.label.height
3210
+ }, cullRect)) return true;
3211
+ }
3212
+ if (edgePaths.get(e.id)?.segments.some((segment) => {
3213
+ const bounds = pathBounds(segment);
3214
+ return bounds !== null && rectsIntersect(bounds, cullRect);
3215
+ })) return true;
3216
+ const srcNode = getNode(e.sourceId);
3217
+ const tgtNode = getNode(e.targetId);
3218
+ return !!srcNode && !!tgtNode && (rectsIntersect(resolvedBounds(srcNode), cullRect) || rectsIntersect(resolvedBounds(tgtNode), cullRect));
3219
+ })
3220
+ };
3221
+ }
2127
3222
  return {
2128
3223
  store,
2129
3224
  trigger: store.trigger,
@@ -2131,11 +3226,16 @@ function createFlowEngine(store, options = {}) {
2131
3226
  getNode,
2132
3227
  getEdge,
2133
3228
  getEntity,
3229
+ getAddressable,
3230
+ getOwnerEntity,
3231
+ getBounds,
2134
3232
  screenToCanvas: screenToCanvas$1,
2135
3233
  canvasToScreen: canvasToScreen$1,
2136
3234
  entityAtPoint,
2137
3235
  entityIdAtPoint,
2138
3236
  getEdgePath,
3237
+ getEdgePathBounds,
3238
+ getEdgeLabelBounds,
2139
3239
  getAllEdgePaths,
2140
3240
  resolvedPosition: (nodeOrId) => {
2141
3241
  const node = typeof nodeOrId === "string" ? getNode(nodeOrId) : nodeOrId;
@@ -2153,18 +3253,154 @@ function createFlowEngine(store, options = {}) {
2153
3253
  width: 0,
2154
3254
  height: 0
2155
3255
  };
3256
+ const c = ctx();
3257
+ if (isDerivedGroup(node)) return hierarchyBounds(node, c);
3258
+ if (c.canvasState === "dragging" && c.selection.has(node.id) && ((node.dx ?? 0) !== 0 || (node.dy ?? 0) !== 0)) return visualBounds(node, getVisualSnapOffset());
2156
3259
  return resolvedBounds(node);
2157
3260
  },
3261
+ /**
3262
+ * All highlights on an entity as `{ kind, meta }` entries. Returns a
3263
+ * referentially stable array (the same empty array when none), so
3264
+ * subscribers can use identity equality.
3265
+ */
3266
+ getHighlights: (entityId) => {
3267
+ const highlights = ctx().highlights;
3268
+ if (highlights.size === 0) return NO_HIGHLIGHTS;
3269
+ let index = highlightIndexCache.get(highlights);
3270
+ if (!index) {
3271
+ index = /* @__PURE__ */ new Map();
3272
+ for (const [kind, bucket] of highlights) for (const [id, meta] of bucket) {
3273
+ let entries = index.get(id);
3274
+ if (!entries) index.set(id, entries = []);
3275
+ entries.push({
3276
+ kind,
3277
+ meta
3278
+ });
3279
+ }
3280
+ highlightIndexCache.set(highlights, index);
3281
+ }
3282
+ return index.get(entityId) ?? NO_HIGHLIGHTS;
3283
+ },
3284
+ /** Whether the entity is currently hovered. */
3285
+ isHovered: (entityId) => ctx().hoveredEntityIds.has(entityId),
3286
+ /**
3287
+ * Deepest group whose child area intersects `bounds`, with the overlap
3288
+ * ratio (intersection / bounds area). Groups in `exclude` (and groups
3289
+ * inside excluded subtrees) are skipped, and excluded nodes do not
3290
+ * contribute to derived child areas — i.e. each group is evaluated as it
3291
+ * would be without the moving nodes. Drives reparent-on-drop.
3292
+ */
3293
+ getGroupDropTarget: (bounds, options = {}) => {
3294
+ const c = ctx();
3295
+ const excluded = new Set(options.exclude ?? []);
3296
+ const nodeIndex = indexNodes(c.graph.nodes);
3297
+ const depths = nodeDepths(c.graph.nodes);
3298
+ const area = Math.max(bounds.width * bounds.height, 1);
3299
+ let best = null;
3300
+ for (const node of c.graph.nodes) {
3301
+ if (!node.group || node.hidden || excluded.has(node.id)) continue;
3302
+ let ancestorId = node.parentId ?? null;
3303
+ let insideExcluded = false;
3304
+ const seen = /* @__PURE__ */ new Set();
3305
+ while (ancestorId && !seen.has(ancestorId)) {
3306
+ if (excluded.has(ancestorId)) {
3307
+ insideExcluded = true;
3308
+ break;
3309
+ }
3310
+ seen.add(ancestorId);
3311
+ ancestorId = nodeIndex.get(ancestorId)?.parentId ?? null;
3312
+ }
3313
+ if (insideExcluded) continue;
3314
+ const childArea = computeGroupGeometryRaw(c, node, void 0, excluded).childArea;
3315
+ const overlap = Math.max(0, Math.min(bounds.x + bounds.width, childArea.x + childArea.width) - Math.max(bounds.x, childArea.x)) * Math.max(0, Math.min(bounds.y + bounds.height, childArea.y + childArea.height) - Math.max(bounds.y, childArea.y)) / area;
3316
+ if (overlap <= 0) continue;
3317
+ const depth = depths.get(node.id) ?? 0;
3318
+ if (!best || depth > best.depth || depth === best.depth && overlap > best.overlap) best = {
3319
+ id: node.id,
3320
+ overlap,
3321
+ childArea,
3322
+ depth
3323
+ };
3324
+ }
3325
+ return best ? {
3326
+ id: best.id,
3327
+ overlap: best.overlap,
3328
+ childArea: best.childArea
3329
+ } : null;
3330
+ },
3331
+ /**
3332
+ * Canvas-space anchor rect for toolbars: a node's (hierarchy-aware)
3333
+ * bounds, an edge's label bounds — or, with no label, an assumed 1×1
3334
+ * label at the path midpoint — and, given several ids (e.g. the
3335
+ * selection), the union of their anchors. Null when nothing resolves.
3336
+ */
3337
+ getToolbarAnchor: (idOrIds) => {
3338
+ const ids = typeof idOrIds === "string" ? [idOrIds] : [...idOrIds];
3339
+ const c = ctx();
3340
+ let union = null;
3341
+ for (const id of ids) {
3342
+ let rect = null;
3343
+ const node = getNode(id);
3344
+ if (node) rect = hierarchyBounds(node, c);
3345
+ else {
3346
+ const edge = getEdge(id);
3347
+ if (edge?.label && (edge.label.width || edge.label.height)) rect = {
3348
+ x: edge.label.x + (edge.label.dx ?? 0),
3349
+ y: edge.label.y + (edge.label.dy ?? 0),
3350
+ width: edge.label.width,
3351
+ height: edge.label.height
3352
+ };
3353
+ else if (edge) {
3354
+ const points = getAllEdgePaths().get(id)?.segments[0]?.points ?? [];
3355
+ if (points.length > 0) {
3356
+ const mid = points.length % 2 === 1 ? points[(points.length - 1) / 2] : {
3357
+ x: (points[points.length / 2 - 1].x + points[points.length / 2].x) / 2,
3358
+ y: (points[points.length / 2 - 1].y + points[points.length / 2].y) / 2
3359
+ };
3360
+ rect = {
3361
+ x: mid.x,
3362
+ y: mid.y,
3363
+ width: 1,
3364
+ height: 1
3365
+ };
3366
+ }
3367
+ }
3368
+ }
3369
+ if (!rect) continue;
3370
+ union = union ? uniteRects(union, rect) : rect;
3371
+ }
3372
+ return union;
3373
+ },
3374
+ /** The node containing this edge (null = root). See `edgeOwner` option. */
3375
+ getEdgeOwner: (edgeId) => {
3376
+ const c = ctx();
3377
+ const edge = indexEdges(c.graph.edges).get(edgeId);
3378
+ if (!edge) return null;
3379
+ const custom = options.edgeOwner?.(edge, c);
3380
+ return options.edgeOwner && custom !== void 0 ? custom : getEdgeOwner(edge, c.graph.nodes);
3381
+ },
3382
+ /** Group geometry (overall bounds, content block, child area), or null. */
3383
+ getGroupGeometry: (nodeOrId) => {
3384
+ const node = typeof nodeOrId === "string" ? getNode(nodeOrId) : nodeOrId;
3385
+ if (!node) return null;
3386
+ return groupGeometryFor(ctx(), node);
3387
+ },
2158
3388
  getGraphBounds: () => getGraphBounds(ctx().graph.nodes, ctx().graph.edges),
2159
3389
  getSelectionBounds: () => {
2160
3390
  const c = ctx();
2161
3391
  return getSelectionBounds(c.graph.nodes, c.graph.edges, c.selection);
2162
3392
  },
2163
3393
  entitiesInRect: (rect) => {
2164
- const { graph } = ctx();
3394
+ const c = ctx();
3395
+ const { graph } = c;
2165
3396
  const ids = [];
2166
- for (const n of graph.nodes) if (rectsIntersect(rect, resolvedBounds(n))) ids.push(n.id);
3397
+ const edgePaths = getAllEdgePaths();
3398
+ for (const n of graph.nodes) {
3399
+ if (!isNodeVisible(n, c)) continue;
3400
+ if (rectsIntersect(rect, resolvedBounds(n))) ids.push(n.id);
3401
+ }
2167
3402
  for (const e of graph.edges) {
3403
+ if (!isEdgeVisible(e, graph, c)) continue;
2168
3404
  if (e.label) {
2169
3405
  if (rectsIntersect(rect, {
2170
3406
  x: e.label.x + (e.label.dx ?? 0),
@@ -2174,7 +3410,7 @@ function createFlowEngine(store, options = {}) {
2174
3410
  })) ids.push(e.id);
2175
3411
  continue;
2176
3412
  }
2177
- const path = getAllEdgePaths().get(e.id);
3413
+ const path = edgePaths.get(e.id);
2178
3414
  if (path && path.segments.some((segment) => rectIntersectsPath(rect, segment))) ids.push(e.id);
2179
3415
  }
2180
3416
  return ids;
@@ -2208,48 +3444,10 @@ function createFlowEngine(store, options = {}) {
2208
3444
  const srcNode = graph.nodes.find((n) => n.id === edge.sourceId);
2209
3445
  const tgtNode = graph.nodes.find((n) => n.id === edge.targetId);
2210
3446
  if (!srcNode || !tgtNode) return null;
2211
- const snap = getVisualSnapOffset();
2212
- const srcBounds = visualBounds(srcNode, snap);
2213
- const tgtBounds = visualBounds(tgtNode, snap);
2214
- let source;
2215
- if (edge.sourcePort === "*" && srcNode.ports?.length) source = closestPortPosition(srcNode, {
2216
- x: tgtBounds.x + tgtBounds.width / 2,
2217
- y: tgtBounds.y + tgtBounds.height / 2
2218
- });
2219
- else if (edge.sourcePort && srcNode.ports) {
2220
- const port = srcNode.ports.find((p) => p.name === edge.sourcePort);
2221
- if (port) {
2222
- const np = visualPosition(srcNode, snap);
2223
- source = {
2224
- x: np.x + port.x + port.width / 2,
2225
- y: np.y + port.y + port.height / 2
2226
- };
2227
- } else source = {
2228
- x: srcBounds.x + srcBounds.width / 2,
2229
- y: srcBounds.y + srcBounds.height / 2
2230
- };
2231
- } else source = getShapeAnchor(srcNode, srcBounds, bestDirection(srcBounds, tgtBounds));
2232
- let target;
2233
- if (edge.targetPort === "*" && tgtNode.ports?.length) target = closestPortPosition(tgtNode, {
2234
- x: srcBounds.x + srcBounds.width / 2,
2235
- y: srcBounds.y + srcBounds.height / 2
2236
- });
2237
- else if (edge.targetPort && tgtNode.ports) {
2238
- const port = tgtNode.ports.find((p) => p.name === edge.targetPort);
2239
- if (port) {
2240
- const np = visualPosition(tgtNode, snap);
2241
- target = {
2242
- x: np.x + port.x + port.width / 2,
2243
- y: np.y + port.y + port.height / 2
2244
- };
2245
- } else target = {
2246
- x: tgtBounds.x + tgtBounds.width / 2,
2247
- y: tgtBounds.y + tgtBounds.height / 2
2248
- };
2249
- } else target = getShapeAnchor(tgtNode, tgtBounds, bestDirection(tgtBounds, srcBounds));
3447
+ const { sourcePoint, targetPoint } = resolveEdgeGeometry(edge, srcNode, tgtNode, getVisualSnapOffset());
2250
3448
  return {
2251
- source,
2252
- target
3449
+ source: sourcePoint,
3450
+ target: targetPoint
2253
3451
  };
2254
3452
  },
2255
3453
  validateConnection: (proposed) => {
@@ -2281,7 +3479,7 @@ function createFlowEngine(store, options = {}) {
2281
3479
  };
2282
3480
  const c = ctx();
2283
3481
  return {
2284
- hidden: entity.hidden ?? (globalConfig.visible ? !resolveBehavior(globalConfig.visible, entity, c) : false),
3482
+ hidden: entity.type === "edge" ? !isEdgeVisible(entity, c.graph, c) : !isNodeVisible(entity, c),
2285
3483
  selectable: entity.selectable ?? resolveBehavior(globalConfig.selectable, entity, c, true),
2286
3484
  draggable: entity.draggable ?? resolveBehavior(globalConfig.draggable, entity, c, true),
2287
3485
  connectable: entity.connectable ?? resolveBehavior(globalConfig.connectable, entity, c, true),
@@ -2291,61 +3489,30 @@ function createFlowEngine(store, options = {}) {
2291
3489
  };
2292
3490
  },
2293
3491
  getVisibleEntities: () => {
3492
+ const c = ctx();
2294
3493
  return {
2295
- nodes: ctx().graph.nodes.filter((n) => {
2296
- if (n.hidden) return false;
2297
- if (globalConfig.visible && !resolveBehavior(globalConfig.visible, n, ctx())) return false;
2298
- if (isVisibleHook && !isVisibleHook(n, ctx().viewport)) return false;
2299
- return true;
2300
- }),
2301
- edges: ctx().graph.edges.filter((e) => {
2302
- if (e.hidden) return false;
2303
- if (globalConfig.visible && !resolveBehavior(globalConfig.visible, e, ctx())) return false;
2304
- if (isVisibleHook && !isVisibleHook(e, ctx().viewport)) return false;
2305
- return true;
2306
- })
3494
+ nodes: c.graph.nodes.filter((n) => isNodeVisible(n, c)),
3495
+ edges: c.graph.edges.filter((e) => isEdgeVisible(e, c.graph, c))
2307
3496
  };
2308
3497
  },
3498
+ /**
3499
+ * Renderable (visible, optionally viewport-culled) entities. Memoized per
3500
+ * (store snapshot, cull/overscan) so several render layers can share one
3501
+ * computation per frame. Treat the result as read-only.
3502
+ */
2309
3503
  getRenderableEntities: (options = {}) => {
2310
3504
  const c = ctx();
2311
- const vp = c.viewport;
2312
- const overscan = options.overscan ?? 0;
2313
- const visibleRect = getVisibleBounds(vp, c.viewportSize);
2314
- const cullRect = {
2315
- x: visibleRect.x - overscan,
2316
- y: visibleRect.y - overscan,
2317
- width: visibleRect.width + overscan * 2,
2318
- height: visibleRect.height + overscan * 2
2319
- };
2320
- const nodes = c.graph.nodes.filter((n) => {
2321
- if (n.hidden) return false;
2322
- if (globalConfig.visible && !resolveBehavior(globalConfig.visible, n, c)) return false;
2323
- if (isVisibleHook && !isVisibleHook(n, vp)) return false;
2324
- if (options.cull === "viewport" && !rectsIntersect(resolvedBounds(n), cullRect)) return false;
2325
- return true;
2326
- });
2327
- const edgePaths = getAllEdgePaths();
2328
- return {
2329
- nodes,
2330
- edges: c.graph.edges.filter((e) => {
2331
- if (e.hidden) return false;
2332
- if (globalConfig.visible && !resolveBehavior(globalConfig.visible, e, c)) return false;
2333
- if (isVisibleHook && !isVisibleHook(e, vp)) return false;
2334
- if (options.cull !== "viewport") return true;
2335
- if (e.label) {
2336
- if (rectsIntersect({
2337
- x: e.label.x + (e.label.dx ?? 0),
2338
- y: e.label.y + (e.label.dy ?? 0),
2339
- width: e.label.width,
2340
- height: e.label.height
2341
- }, cullRect)) return true;
2342
- }
2343
- if (edgePaths.get(e.id)?.segments.some((segment) => rectIntersectsPath(cullRect, segment))) return true;
2344
- const srcNode = getNode(e.sourceId);
2345
- const tgtNode = getNode(e.targetId);
2346
- return !!srcNode && !!tgtNode && (rectsIntersect(resolvedBounds(srcNode), cullRect) || rectsIntersect(resolvedBounds(tgtNode), cullRect));
2347
- })
2348
- };
3505
+ const cacheKey = `${options.cull ?? "none"}:${options.overscan ?? 0}`;
3506
+ let byKey = renderableCache.get(c);
3507
+ const cached = byKey?.get(cacheKey);
3508
+ if (cached) return cached;
3509
+ const result = computeRenderableEntities(c, options);
3510
+ if (!byKey) {
3511
+ byKey = /* @__PURE__ */ new Map();
3512
+ renderableCache.set(c, byKey);
3513
+ }
3514
+ byKey.set(cacheKey, result);
3515
+ return result;
2349
3516
  },
2350
3517
  getIntersectingNodes: (nodeId) => {
2351
3518
  const node = getNode(nodeId);
@@ -2386,19 +3553,41 @@ function createFlowEngine(store, options = {}) {
2386
3553
  },
2387
3554
  /** Get in-progress resize bounds, or null if not resizing */
2388
3555
  getResizeBounds: () => {
2389
- const c = ctx();
2390
- if (!c.resizeCorners || !c.resizingEntityId) return null;
2391
- const [a, b] = c.resizeCorners;
2392
- return {
2393
- x: Math.min(a.x, b.x),
2394
- y: Math.min(a.y, b.y),
2395
- width: Math.max(10, Math.abs(b.x - a.x)),
2396
- height: Math.max(10, Math.abs(b.y - a.y))
2397
- };
3556
+ return getResizeBoundsFromContext(ctx());
2398
3557
  },
2399
3558
  subscribe
2400
3559
  };
2401
3560
  }
3561
+ function getResizeBoundsFromContext(c) {
3562
+ if (!c.resizeCorners || !c.resizingEntityId) return null;
3563
+ const [a, b] = c.resizeCorners;
3564
+ return {
3565
+ x: Math.min(a.x, b.x),
3566
+ y: Math.min(a.y, b.y),
3567
+ width: Math.max(10, Math.abs(b.x - a.x)),
3568
+ height: Math.max(10, Math.abs(b.y - a.y))
3569
+ };
3570
+ }
3571
+ function boundsForPoints(points) {
3572
+ if (points.length === 0) return null;
3573
+ let minX = Infinity;
3574
+ let minY = Infinity;
3575
+ let maxX = -Infinity;
3576
+ let maxY = -Infinity;
3577
+ for (const point of points) {
3578
+ minX = Math.min(minX, point.x);
3579
+ minY = Math.min(minY, point.y);
3580
+ maxX = Math.max(maxX, point.x);
3581
+ maxY = Math.max(maxY, point.y);
3582
+ }
3583
+ if (!isFinite(minX)) return null;
3584
+ return {
3585
+ x: minX,
3586
+ y: minY,
3587
+ width: maxX - minX,
3588
+ height: maxY - minY
3589
+ };
3590
+ }
2402
3591
  function closestPortPosition(node, target) {
2403
3592
  if (!node.ports?.length) {
2404
3593
  const b = resolvedBounds(node);
@@ -2457,6 +3646,13 @@ function resolveLabelAnchor(anchor, label, sourceBounds, targetBounds) {
2457
3646
  }
2458
3647
  //#endregion
2459
3648
  //#region src/createFlow.ts
3649
+ /**
3650
+ * The undoRedo store extension keeps `past`/`future` history on the snapshot
3651
+ * at runtime without exposing them in its public types — read them defensively.
3652
+ */
3653
+ function getHistory(store) {
3654
+ return store.getSnapshot();
3655
+ }
2460
3656
  function createFlow(options = {}) {
2461
3657
  const store = createFlowStore(options.graph, options.store);
2462
3658
  const engine = createFlowEngine(store, options.engine);
@@ -2470,7 +3666,7 @@ function createFlow(options = {}) {
2470
3666
  cleanup.clear();
2471
3667
  }
2472
3668
  async function runLayout(layout = options.layout ?? void 0) {
2473
- if (!layout) throw new Error("No layout algorithm was provided");
3669
+ if (!layout) throw new Error("runLayout() was called without a layout algorithm. Pass one to createFlow({ layout }) or call flow.runLayout(myLayout) directly.");
2474
3670
  const positions = await layout(store.getSnapshot().context.graph);
2475
3671
  store.trigger.applyLayoutResult({ positions });
2476
3672
  }
@@ -2478,19 +3674,27 @@ function createFlow(options = {}) {
2478
3674
  store,
2479
3675
  engine,
2480
3676
  trigger: store.trigger,
3677
+ on: store.on,
2481
3678
  destroy,
2482
3679
  getContext: engine.getContext,
2483
3680
  subscribe: engine.subscribe,
2484
3681
  getNode: engine.getNode,
2485
3682
  getEdge: engine.getEdge,
2486
3683
  getEntity: engine.getEntity,
3684
+ getAddressable: engine.getAddressable,
3685
+ getOwnerEntity: engine.getOwnerEntity,
3686
+ getBounds: engine.getBounds,
2487
3687
  screenToCanvas: engine.screenToCanvas,
2488
3688
  canvasToScreen: engine.canvasToScreen,
2489
3689
  getAllEdgePaths: engine.getAllEdgePaths,
2490
3690
  getGraphBounds: engine.getGraphBounds,
2491
3691
  getSelectionBounds: engine.getSelectionBounds,
2492
3692
  getRenderableEntities: engine.getRenderableEntities,
2493
- runLayout
3693
+ runLayout,
3694
+ undo: () => store.trigger.undo(),
3695
+ redo: () => store.trigger.redo(),
3696
+ canUndo: () => (getHistory(store).past?.length ?? 0) > 0,
3697
+ canRedo: () => (getHistory(store).future?.length ?? 0) > 0
2494
3698
  };
2495
3699
  }
2496
3700
  //#endregion
@@ -2530,5 +3734,1008 @@ function createGraph(opts) {
2530
3734
  ...opts
2531
3735
  };
2532
3736
  }
3737
+ function createPort(opts) {
3738
+ return {
3739
+ x: 0,
3740
+ y: 0,
3741
+ width: 12,
3742
+ height: 12,
3743
+ data: {},
3744
+ ...opts
3745
+ };
3746
+ }
3747
+ //#endregion
3748
+ //#region src/connectionPreview.ts
3749
+ const CONNECTION_PREVIEW_NODE_ID = "flow:connection-preview-node";
3750
+ const CONNECTION_PREVIEW_EDGE_ID = "flow:connection-preview-edge";
3751
+ function createConnectionPreviewGraph(graph, connection, options = {}) {
3752
+ if (!connection?.active) return graph;
3753
+ const nodeId = options.nodeId ?? "flow:connection-preview-node";
3754
+ const edgeId = options.edgeId ?? "flow:connection-preview-edge";
3755
+ const nodeSize = options.nodeSize ?? 2;
3756
+ const targetId = connection.targetId ?? nodeId;
3757
+ const nodes = connection.targetId ? [...graph.nodes] : [...graph.nodes, createPreviewNode(nodeId, connection.pointerPosition, nodeSize)];
3758
+ const edges = [...graph.edges, createEdge({
3759
+ id: edgeId,
3760
+ sourceId: connection.sourceId,
3761
+ targetId,
3762
+ sourcePort: connection.sourcePort ?? void 0,
3763
+ targetPort: connection.targetPort ?? void 0,
3764
+ selectable: false,
3765
+ draggable: false,
3766
+ deletable: false,
3767
+ data: {
3768
+ temp: { kind: "connection-preview" },
3769
+ isValid: connection.isValid
3770
+ }
3771
+ })];
3772
+ return {
3773
+ ...graph,
3774
+ nodes,
3775
+ edges
3776
+ };
3777
+ }
3778
+ function createPreviewNode(id, point, size) {
3779
+ return createNode({
3780
+ id,
3781
+ x: point.x - size / 2,
3782
+ y: point.y - size / 2,
3783
+ width: size,
3784
+ height: size,
3785
+ selectable: false,
3786
+ draggable: false,
3787
+ deletable: false,
3788
+ data: { temp: { kind: "connection-preview" } }
3789
+ });
3790
+ }
3791
+ //#endregion
3792
+ //#region src/toolbar.ts
3793
+ function getToolbarPlacement(input) {
3794
+ const offset = input.offset ?? 10;
3795
+ const padding = input.padding ?? 8;
3796
+ const { toolbarWidth: tw, toolbarHeight: th, anchor } = input;
3797
+ const topPlacementTop = anchor.y - offset - th;
3798
+ const bottomPlacementTop = anchor.y + anchor.height + offset;
3799
+ const topFits = topPlacementTop >= padding;
3800
+ const bottomFits = bottomPlacementTop + th <= input.viewportHeight - padding;
3801
+ let side;
3802
+ if (topFits) side = "top";
3803
+ else if (bottomFits) side = "bottom";
3804
+ else side = anchor.y >= input.viewportHeight - (anchor.y + anchor.height) ? "top" : "bottom";
3805
+ let top = side === "top" ? topPlacementTop : bottomPlacementTop;
3806
+ const maxTop = Math.max(input.viewportHeight - padding - th, padding);
3807
+ top = Math.min(Math.max(top, padding), maxTop);
3808
+ let left = anchor.x + anchor.width / 2 - tw / 2;
3809
+ const maxLeft = Math.max(input.viewportWidth - padding - tw, padding);
3810
+ left = Math.min(Math.max(left, padding), maxLeft);
3811
+ return {
3812
+ left,
3813
+ top,
3814
+ side
3815
+ };
3816
+ }
3817
+ //#endregion
3818
+ //#region src/minimap.ts
3819
+ function getMinimapProjection(options) {
3820
+ const padding = options.padding ?? .1;
3821
+ const content = options.contentBounds;
3822
+ const visible = getVisibleBounds(options.viewport, options.viewportSize);
3823
+ const padX = content.width * padding;
3824
+ const padY = content.height * padding;
3825
+ let bounds = {
3826
+ x: content.x - padX,
3827
+ y: content.y - padY,
3828
+ width: content.width + padX * 2,
3829
+ height: content.height + padY * 2
3830
+ };
3831
+ if (visible.width > 0 && visible.height > 0) bounds = unionRect(bounds, visible);
3832
+ if (bounds.width <= 0 || bounds.height <= 0) bounds = {
3833
+ x: bounds.x,
3834
+ y: bounds.y,
3835
+ width: 1,
3836
+ height: 1
3837
+ };
3838
+ const scale = Math.min(options.width / bounds.width, options.height / bounds.height);
3839
+ const offsetX = (options.width - bounds.width * scale) / 2;
3840
+ const offsetY = (options.height - bounds.height * scale) / 2;
3841
+ const toMinimap = (point) => ({
3842
+ x: (point.x - bounds.x) * scale + offsetX,
3843
+ y: (point.y - bounds.y) * scale + offsetY
3844
+ });
3845
+ const toCanvas = (point) => ({
3846
+ x: (point.x - offsetX) / scale + bounds.x,
3847
+ y: (point.y - offsetY) / scale + bounds.y
3848
+ });
3849
+ const rectToMinimap = (rect) => {
3850
+ const origin = toMinimap(rect);
3851
+ return {
3852
+ x: origin.x,
3853
+ y: origin.y,
3854
+ width: rect.width * scale,
3855
+ height: rect.height * scale
3856
+ };
3857
+ };
3858
+ return {
3859
+ scale,
3860
+ bounds,
3861
+ viewportRect: rectToMinimap(visible),
3862
+ toMinimap,
3863
+ toCanvas,
3864
+ rectToMinimap
3865
+ };
3866
+ }
3867
+ //#endregion
3868
+ //#region src/input/modes.ts
3869
+ const preventDefault$1 = { type: "preventDefault" };
3870
+ function distance(a, b) {
3871
+ return Math.hypot(b.x - a.x, b.y - a.y);
3872
+ }
3873
+ function isMulti(event) {
3874
+ return event.modifiers.shift || event.modifiers.meta || event.modifiers.ctrl;
3875
+ }
3876
+ function keyboardMode(options = {}) {
3877
+ const allowDelete = options.allowDelete ?? true;
3878
+ const allowUndo = options.allowUndo ?? true;
3879
+ return {
3880
+ id: "keyboard",
3881
+ priority: 100,
3882
+ start(event, { context }) {
3883
+ if (event.kind !== "key.down") return null;
3884
+ if (event.editableTarget) return null;
3885
+ if (event.key === " ") return { commands: [preventDefault$1] };
3886
+ if (event.key === "Escape") return { commands: context.canvasState === "idle" ? [
3887
+ trigger("cancelConnection"),
3888
+ trigger("clearSelection"),
3889
+ trigger("clearFocus")
3890
+ ] : [trigger("cancelConnection")] };
3891
+ const mod = event.modifiers.meta || event.modifiers.ctrl;
3892
+ if (allowUndo && mod && event.key.toLowerCase() === "z") return { commands: [preventDefault$1, event.modifiers.shift ? trigger("redo") : trigger("undo")] };
3893
+ if (allowDelete && (event.key === "Delete" || event.key === "Backspace")) {
3894
+ if (context.selection.size === 0) return null;
3895
+ return { commands: [preventDefault$1, trigger("deleteSelected")] };
3896
+ }
3897
+ return null;
3898
+ }
3899
+ };
3900
+ }
3901
+ const ARROW_DIRECTIONS = {
3902
+ ArrowLeft: {
3903
+ x: -1,
3904
+ y: 0
3905
+ },
3906
+ ArrowRight: {
3907
+ x: 1,
3908
+ y: 0
3909
+ },
3910
+ ArrowUp: {
3911
+ x: 0,
3912
+ y: -1
3913
+ },
3914
+ ArrowDown: {
3915
+ x: 0,
3916
+ y: 1
3917
+ }
3918
+ };
3919
+ function keyboardNavMode(options = {}) {
3920
+ const allowMove = options.allowMove ?? true;
3921
+ const step = options.step ?? 5;
3922
+ const shiftStep = options.shiftStep ?? 20;
3923
+ return {
3924
+ id: "keyboard-nav",
3925
+ priority: 95,
3926
+ start(event, { context }) {
3927
+ if (event.kind !== "key.down" || event.editableTarget) return null;
3928
+ if (event.key === "Enter" && context.focusedEntityId) return { commands: [preventDefault$1, trigger("select", {
3929
+ ids: [context.focusedEntityId],
3930
+ mode: event.modifiers.shift ? "multi" : "single"
3931
+ })] };
3932
+ if (!allowMove) return null;
3933
+ const direction = ARROW_DIRECTIONS[event.key];
3934
+ if (!direction || context.selection.size === 0) return null;
3935
+ return { commands: [
3936
+ preventDefault$1,
3937
+ trigger("moveNodes", {
3938
+ direction,
3939
+ factor: event.modifiers.shift ? shiftStep : step
3940
+ }),
3941
+ trigger("commitDrag")
3942
+ ] };
3943
+ }
3944
+ };
3945
+ }
3946
+ function wheelMode() {
3947
+ return {
3948
+ id: "wheel",
3949
+ priority: 90,
3950
+ start(event, { context }) {
3951
+ if (event.kind !== "wheel") return null;
3952
+ if (isTrackpadPinch({
3953
+ ctrlKey: event.modifiers.ctrl,
3954
+ metaKey: event.modifiers.meta
3955
+ })) return { commands: [preventDefault$1, trigger("zoomTo", {
3956
+ zoom: context.viewport.zoom * Math.pow(2, wheelZoomDelta({
3957
+ deltaY: event.deltaY,
3958
+ deltaMode: event.deltaMode,
3959
+ ctrlKey: event.modifiers.ctrl
3960
+ })),
3961
+ center: event.screenPoint
3962
+ })] };
3963
+ return { commands: [preventDefault$1, trigger("panBy", normalizeWheelPan({
3964
+ deltaX: event.deltaX,
3965
+ deltaY: event.deltaY,
3966
+ deltaMode: event.deltaMode
3967
+ }))] };
3968
+ }
3969
+ };
3970
+ }
3971
+ function panMode() {
3972
+ return {
3973
+ id: "pan",
3974
+ priority: 80,
3975
+ start(event, { input }) {
3976
+ if (event.kind !== "pointer.down") return null;
3977
+ const middle = event.button === 1;
3978
+ const space = input.spaceHeld && event.button === 0;
3979
+ if (!middle && !space) return null;
3980
+ return {
3981
+ commands: [trigger("panStart", event.screenPoint)],
3982
+ session: panSession()
3983
+ };
3984
+ }
3985
+ };
3986
+ }
3987
+ function panSession() {
3988
+ return {
3989
+ update(event) {
3990
+ if (event.kind === "pointer.move") return { commands: [trigger("pan", event.screenPoint)] };
3991
+ if (event.kind === "pointer.up" || event.kind === "pointer.cancel") return {
3992
+ commands: [trigger("panEnd")],
3993
+ status: "end"
3994
+ };
3995
+ return {};
3996
+ },
3997
+ cancel() {
3998
+ return [trigger("panEnd")];
3999
+ }
4000
+ };
4001
+ }
4002
+ const REPARENT_HIGHLIGHT_KIND = "drop-target";
4003
+ function entityPressMode(options = {}) {
4004
+ const allowDrag = options.drag ?? true;
4005
+ const reparent = options.reparent === true ? {} : typeof options.reparent === "object" ? options.reparent : null;
4006
+ return {
4007
+ id: "entity-press",
4008
+ priority: 50,
4009
+ start(event, { context, engine }) {
4010
+ if (event.kind !== "pointer.down" || event.button !== 0) return null;
4011
+ if (event.target.kind !== "entity") return null;
4012
+ const id = event.target.id;
4013
+ const entity = engine.getEntity(id);
4014
+ if (!entity) return null;
4015
+ const config = engine.resolveEntityConfig(entity);
4016
+ const commands = [];
4017
+ if (config.selectable) {
4018
+ const selection = context.selection;
4019
+ if (!(selection.size > 1 && selection.has(id))) commands.push(trigger("select", {
4020
+ ids: [id],
4021
+ mode: isMulti(event) ? "multi" : "single"
4022
+ }));
4023
+ }
4024
+ const draggablePart = entity.type === "node" || event.target.part === "label";
4025
+ const handleAllows = !event.target.entityHasDragHandle || event.target.pressedDragHandle === true;
4026
+ if (!allowDrag || !draggablePart || !handleAllows || !config.draggable) return { commands };
4027
+ return {
4028
+ commands,
4029
+ session: dragSession(id, event, entity.type === "node" ? reparent : null)
4030
+ };
4031
+ }
4032
+ };
4033
+ }
4034
+ function dragSession(id, down, reparent) {
4035
+ const transactionId = `drag:${id}:${down.pointerId}:${Date.now()}`;
4036
+ let dragging = false;
4037
+ let baseOffset = {
4038
+ x: 0,
4039
+ y: 0
4040
+ };
4041
+ let candidateId = null;
4042
+ let candidateOverlap = 0;
4043
+ let candidateSince = 0;
4044
+ const minOverlap = reparent?.minOverlap ?? .5;
4045
+ const unparentModifier = reparent?.unparentModifier === void 0 ? "alt" : reparent.unparentModifier;
4046
+ /**
4047
+ * Currently applied drag offset of the primary entity. The session anchors
4048
+ * requests to the virtual pointer (`base + pointerTravel`) and asks the
4049
+ * store for the difference — so store-side clamping (extents, fixed-group
4050
+ * child areas) is idempotent against pointer position: overshoot stays
4051
+ * virtual and the entity doesn't move again until the pointer returns.
4052
+ */
4053
+ function appliedOffset(ctx) {
4054
+ const node = ctx.engine.getNode(id);
4055
+ if (node) return {
4056
+ x: node.dx ?? 0,
4057
+ y: node.dy ?? 0
4058
+ };
4059
+ const edge = ctx.engine.getEdge(id);
4060
+ if (edge?.label) return {
4061
+ x: edge.label.dx ?? 0,
4062
+ y: edge.label.dy ?? 0
4063
+ };
4064
+ return {
4065
+ x: 0,
4066
+ y: 0
4067
+ };
4068
+ }
4069
+ /** Top-level moving nodes + the full excluded (moving) subtree. */
4070
+ function movingInfo(ctx) {
4071
+ const { context, engine } = ctx;
4072
+ const nodes = context.graph.nodes;
4073
+ const nodeIndex = indexNodes(nodes);
4074
+ const childrenIndex = indexChildren(nodes);
4075
+ const movingIds = /* @__PURE__ */ new Set();
4076
+ for (const selectedId of context.selection) {
4077
+ const node = nodeIndex.get(selectedId);
4078
+ if (node && node.draggable !== false) movingIds.add(selectedId);
4079
+ }
4080
+ const topLevel = [];
4081
+ for (const movingId of movingIds) {
4082
+ let ancestor = nodeIndex.get(movingId)?.parentId ?? null;
4083
+ let nested = false;
4084
+ const seen = /* @__PURE__ */ new Set();
4085
+ while (ancestor && !seen.has(ancestor)) {
4086
+ if (movingIds.has(ancestor)) {
4087
+ nested = true;
4088
+ break;
4089
+ }
4090
+ seen.add(ancestor);
4091
+ ancestor = nodeIndex.get(ancestor)?.parentId ?? null;
4092
+ }
4093
+ if (!nested) topLevel.push(nodeIndex.get(movingId));
4094
+ }
4095
+ const exclude = new Set(movingIds);
4096
+ const queue = [...movingIds];
4097
+ while (queue.length > 0) {
4098
+ const current = queue.pop();
4099
+ for (const child of childrenIndex.get(current) ?? []) if (!exclude.has(child.id)) {
4100
+ exclude.add(child.id);
4101
+ queue.push(child.id);
4102
+ }
4103
+ }
4104
+ let bounds = null;
4105
+ for (const node of topLevel) {
4106
+ const b = engine.resolvedBounds(node.id);
4107
+ bounds = bounds ? {
4108
+ x: Math.min(bounds.x, b.x),
4109
+ y: Math.min(bounds.y, b.y),
4110
+ width: Math.max(bounds.x + bounds.width, b.x + b.width) - Math.min(bounds.x, b.x),
4111
+ height: Math.max(bounds.y + bounds.height, b.y + b.height) - Math.min(bounds.y, b.y)
4112
+ } : { ...b };
4113
+ }
4114
+ return {
4115
+ topLevel,
4116
+ exclude,
4117
+ bounds
4118
+ };
4119
+ }
4120
+ function trackCandidate(ctx, pending) {
4121
+ const { exclude, bounds } = movingInfo(ctx);
4122
+ const projected = bounds ? {
4123
+ ...bounds,
4124
+ x: bounds.x + pending.x,
4125
+ y: bounds.y + pending.y
4126
+ } : null;
4127
+ const found = projected ? ctx.engine.getGroupDropTarget(projected, { exclude }) : null;
4128
+ const nextId = found && found.overlap >= minOverlap ? found.id : null;
4129
+ candidateOverlap = found?.overlap ?? 0;
4130
+ if (nextId === candidateId) return [];
4131
+ const commands = [];
4132
+ if (candidateId) commands.push(trigger("removeHighlights", {
4133
+ kind: REPARENT_HIGHLIGHT_KIND,
4134
+ ids: [candidateId]
4135
+ }));
4136
+ if (nextId) commands.push(trigger("addHighlights", {
4137
+ kind: REPARENT_HIGHLIGHT_KIND,
4138
+ entries: [{ id: nextId }]
4139
+ }));
4140
+ candidateId = nextId;
4141
+ candidateSince = Date.now();
4142
+ return commands;
4143
+ }
4144
+ function decideAndApply(event, ctx) {
4145
+ const commands = [];
4146
+ if (candidateId) commands.push(trigger("removeHighlights", {
4147
+ kind: REPARENT_HIGHLIGHT_KIND,
4148
+ ids: [candidateId]
4149
+ }));
4150
+ if (event.kind !== "pointer.up" || !reparent) return commands;
4151
+ const { topLevel, exclude, bounds } = movingInfo(ctx);
4152
+ if (!bounds || topLevel.length === 0) return commands;
4153
+ const found = ctx.engine.getGroupDropTarget(bounds, { exclude });
4154
+ const finalId = found && found.overlap >= minOverlap ? found.id : null;
4155
+ const hoverMs = finalId && finalId === candidateId ? Date.now() - candidateSince : 0;
4156
+ candidateId = finalId;
4157
+ candidateOverlap = found?.overlap ?? 0;
4158
+ const drop = {
4159
+ nodes: topLevel,
4160
+ bounds,
4161
+ candidate: candidateId ? {
4162
+ id: candidateId,
4163
+ overlap: candidateOverlap
4164
+ } : null,
4165
+ hoverMs,
4166
+ modifiers: event.modifiers
4167
+ };
4168
+ let decision;
4169
+ if (reparent.decide) decision = reparent.decide(drop, ctx);
4170
+ else if (unparentModifier && event.modifiers[unparentModifier]) decision = null;
4171
+ else if (candidateId && hoverMs >= (reparent.delayMs ?? 0)) decision = candidateId;
4172
+ else if (!candidateId && (reparent.unparent ?? true)) decision = topLevel.some((node) => {
4173
+ if (!node.parentId) return false;
4174
+ const geometry = ctx.engine.getGroupGeometry(node.parentId);
4175
+ return geometry ? !rectsIntersect(bounds, geometry.childArea) : false;
4176
+ }) ? null : void 0;
4177
+ if (decision !== void 0) for (const node of topLevel) {
4178
+ if ((node.parentId ?? null) === decision || node.id === decision) continue;
4179
+ commands.push(trigger("reparentNode", {
4180
+ id: node.id,
4181
+ parentId: decision,
4182
+ transactionId
4183
+ }));
4184
+ }
4185
+ return commands;
4186
+ }
4187
+ return {
4188
+ update(event, ctx) {
4189
+ const { context } = ctx;
4190
+ if (event.kind === "pointer.move") {
4191
+ if (!dragging) {
4192
+ if (distance(down.screenPoint, event.screenPoint) < context.dragThreshold) return {};
4193
+ dragging = true;
4194
+ baseOffset = appliedOffset(ctx);
4195
+ }
4196
+ const applied = appliedOffset(ctx);
4197
+ const dx = baseOffset.x + (event.point.x - down.point.x) - applied.x;
4198
+ const dy = baseOffset.y + (event.point.y - down.point.y) - applied.y;
4199
+ return { commands: [
4200
+ ...!context.draggedEntityId ? [trigger("dragStart", {
4201
+ id,
4202
+ transactionId
4203
+ })] : [],
4204
+ trigger("dragMove", {
4205
+ dx,
4206
+ dy
4207
+ }),
4208
+ ...reparent ? trackCandidate(ctx, {
4209
+ x: dx,
4210
+ y: dy
4211
+ }) : []
4212
+ ] };
4213
+ }
4214
+ if (event.kind === "pointer.up" || event.kind === "pointer.cancel") return {
4215
+ commands: dragging ? [
4216
+ trigger("dragEnd"),
4217
+ trigger("commitDrag"),
4218
+ ...reparent ? decideAndApply(event, ctx) : []
4219
+ ] : [],
4220
+ status: "end"
4221
+ };
4222
+ return {};
4223
+ },
4224
+ cancel() {
4225
+ const commands = dragging ? [trigger("dragEnd"), trigger("commitDrag")] : [];
4226
+ if (candidateId) commands.push(trigger("removeHighlights", {
4227
+ kind: REPARENT_HIGHLIGHT_KIND,
4228
+ ids: [candidateId]
4229
+ }));
4230
+ return commands;
4231
+ }
4232
+ };
4233
+ }
4234
+ function connectMode(options = {}) {
4235
+ return {
4236
+ id: "connect",
4237
+ priority: 60,
4238
+ start(event, { engine }) {
4239
+ if (event.kind !== "pointer.down" || event.button !== 0) return null;
4240
+ if (event.target.kind !== "port") return null;
4241
+ const { nodeId, portName } = event.target;
4242
+ const node = engine.getNode(nodeId);
4243
+ if (!node?.ports?.some((port) => port.name === portName)) return null;
4244
+ if (!engine.resolveEntityConfig(node).connectable) return null;
4245
+ return {
4246
+ commands: [trigger("connectionStart", {
4247
+ sourceId: nodeId,
4248
+ sourcePort: portName,
4249
+ position: event.point
4250
+ })],
4251
+ session: connectSession({
4252
+ nodeId,
4253
+ port: portName
4254
+ }, options)
4255
+ };
4256
+ }
4257
+ };
4258
+ }
4259
+ function defaultConnectionValidity(args, ctx) {
4260
+ const { source, target } = args;
4261
+ if (target.kind === "port") {
4262
+ if (target.nodeId === source.nodeId) return false;
4263
+ return ctx.engine.validateConnection({
4264
+ sourceId: source.nodeId,
4265
+ sourcePort: source.port,
4266
+ targetId: target.nodeId,
4267
+ targetPort: target.portName
4268
+ });
4269
+ }
4270
+ if (target.kind === "entity") {
4271
+ if (target.id === source.nodeId) return false;
4272
+ if (!ctx.engine.getNode(target.id)) return false;
4273
+ return ctx.engine.validateConnection({
4274
+ sourceId: source.nodeId,
4275
+ sourcePort: source.port,
4276
+ targetId: target.id,
4277
+ targetPort: null
4278
+ });
4279
+ }
4280
+ return false;
4281
+ }
4282
+ function connectEndTargetFor(target, point, ctx) {
4283
+ if (target.kind === "port") return {
4284
+ kind: "node",
4285
+ nodeId: target.nodeId,
4286
+ port: target.portName
4287
+ };
4288
+ if (target.kind === "entity") {
4289
+ const entity = ctx.engine.getEntity(target.id);
4290
+ if (entity?.type === "node") return {
4291
+ kind: "node",
4292
+ nodeId: target.id,
4293
+ port: null
4294
+ };
4295
+ if (entity?.type === "edge") return {
4296
+ kind: "edge",
4297
+ edgeId: target.id
4298
+ };
4299
+ }
4300
+ if (target.kind === "pane") return {
4301
+ kind: "canvas",
4302
+ position: point
4303
+ };
4304
+ return { kind: "none" };
4305
+ }
4306
+ function connectSession(source, options) {
4307
+ const isValid = options.isValid ?? defaultConnectionValidity;
4308
+ return {
4309
+ update(event, ctx) {
4310
+ if (!ctx.context.connection) return { status: "end" };
4311
+ if (event.kind === "pointer.move") {
4312
+ const target = event.target;
4313
+ let targetId = null;
4314
+ let targetPort = null;
4315
+ if (target.kind === "port") {
4316
+ targetId = target.nodeId;
4317
+ targetPort = target.portName;
4318
+ } else if (target.kind === "entity" && ctx.engine.getNode(target.id)) targetId = target.id;
4319
+ return { commands: [trigger("connectionMove", {
4320
+ position: event.point,
4321
+ targetId,
4322
+ targetPort,
4323
+ isValid: isValid({
4324
+ source,
4325
+ target,
4326
+ point: event.point
4327
+ }, ctx)
4328
+ })] };
4329
+ }
4330
+ if (event.kind === "pointer.up") return {
4331
+ commands: [trigger("connectionEnd", { target: connectEndTargetFor(event.target, event.point, ctx) })],
4332
+ status: "end"
4333
+ };
4334
+ if (event.kind === "pointer.cancel") return {
4335
+ commands: [trigger("cancelConnection")],
4336
+ status: "end"
4337
+ };
4338
+ return {};
4339
+ },
4340
+ cancel() {
4341
+ return [trigger("cancelConnection")];
4342
+ }
4343
+ };
4344
+ }
4345
+ function hoverMode() {
4346
+ return {
4347
+ id: "hover",
4348
+ priority: 5,
4349
+ start(event, { context }) {
4350
+ if (event.kind !== "pointer.move") return null;
4351
+ const target = event.target;
4352
+ const id = target.kind === "entity" ? target.id : target.kind === "port" ? target.nodeId : null;
4353
+ const current = context.hoveredEntityIds;
4354
+ if (id) {
4355
+ if (current.size === 1 && current.has(id)) return null;
4356
+ return { commands: [trigger("setHover", { ids: [id] })] };
4357
+ }
4358
+ if (current.size === 0) return null;
4359
+ return { commands: [trigger("clearHover")] };
4360
+ }
4361
+ };
4362
+ }
4363
+ function panePressMode() {
4364
+ return {
4365
+ id: "pane-press",
4366
+ priority: 10,
4367
+ start(event) {
4368
+ if (event.kind !== "pointer.down" || event.button !== 0) return null;
4369
+ if (event.target.kind !== "pane") return null;
4370
+ return { session: panePressSession(event) };
4371
+ }
4372
+ };
4373
+ }
4374
+ function panePressSession(down) {
4375
+ let panning = false;
4376
+ return {
4377
+ update(event, { context }) {
4378
+ if (event.kind === "pointer.move") {
4379
+ if (!panning) {
4380
+ if (distance(down.screenPoint, event.screenPoint) < context.dragThreshold) return {};
4381
+ panning = true;
4382
+ return { commands: [
4383
+ trigger("clearSelection"),
4384
+ trigger("clearFocus"),
4385
+ trigger("panStart", down.screenPoint),
4386
+ trigger("pan", event.screenPoint)
4387
+ ] };
4388
+ }
4389
+ return { commands: [trigger("pan", event.screenPoint)] };
4390
+ }
4391
+ if (event.kind === "pointer.up") return {
4392
+ commands: panning ? [trigger("panEnd")] : [trigger("clearSelection"), trigger("clearFocus")],
4393
+ status: "end"
4394
+ };
4395
+ if (event.kind === "pointer.cancel") return {
4396
+ commands: panning ? [trigger("panEnd")] : [],
4397
+ status: "end"
4398
+ };
4399
+ return {};
4400
+ },
4401
+ cancel() {
4402
+ return panning ? [trigger("panEnd")] : [];
4403
+ }
4404
+ };
4405
+ }
4406
+ /** Interactive default: full editing gestures. */
4407
+ const defaultInputModes = [
4408
+ keyboardMode(),
4409
+ keyboardNavMode(),
4410
+ wheelMode(),
4411
+ panMode(),
4412
+ connectMode(),
4413
+ entityPressMode(),
4414
+ panePressMode(),
4415
+ hoverMode()
4416
+ ];
4417
+ /** Readonly: select and navigate, no mutation gestures. */
4418
+ const readonlyInputModes = [
4419
+ keyboardMode({
4420
+ allowDelete: false,
4421
+ allowUndo: false
4422
+ }),
4423
+ keyboardNavMode({ allowMove: false }),
4424
+ wheelMode(),
4425
+ panMode(),
4426
+ entityPressMode({ drag: false }),
4427
+ panePressMode(),
4428
+ hoverMode()
4429
+ ];
4430
+ //#endregion
4431
+ //#region src/input/index.ts
4432
+ /** Typed constructor for trigger commands. */
4433
+ function trigger(name, ...params) {
4434
+ return {
4435
+ type: "trigger",
4436
+ name,
4437
+ params: params[0]
4438
+ };
4439
+ }
4440
+ const preventDefault = { type: "preventDefault" };
4441
+ function createFlowInputRuntime(options) {
4442
+ const { store, engine } = options;
4443
+ const resolveModes = typeof options.modes === "function" ? options.modes : options.modes ? () => options.modes : defaultModesForContext;
4444
+ const input = { spaceHeld: false };
4445
+ let session = null;
4446
+ function modeContext() {
4447
+ return {
4448
+ context: store.getSnapshot().context,
4449
+ engine,
4450
+ input
4451
+ };
4452
+ }
4453
+ function apply(commands, effects) {
4454
+ if (!commands) return;
4455
+ for (const command of commands) if (command.type === "preventDefault") effects.preventDefault = true;
4456
+ else if (command.type === "stopPropagation") effects.stopPropagation = true;
4457
+ else {
4458
+ const fire = store.trigger[command.name];
4459
+ fire?.(command.params);
4460
+ }
4461
+ }
4462
+ function send(event) {
4463
+ const effects = {
4464
+ preventDefault: false,
4465
+ stopPropagation: false,
4466
+ sessionStarted: false,
4467
+ sessionEnded: false,
4468
+ handledBy: null
4469
+ };
4470
+ if (event.kind === "key.down" && event.key === " " && !event.editableTarget) input.spaceHeld = true;
4471
+ else if (event.kind === "key.up" && event.key === " ") input.spaceHeld = false;
4472
+ const isPointer = event.kind === "pointer.down" || event.kind === "pointer.move" || event.kind === "pointer.up" || event.kind === "pointer.cancel";
4473
+ if (session && isPointer) {
4474
+ const pointer = event;
4475
+ if (session.pointerId === null || pointer.pointerId === session.pointerId) {
4476
+ const result = session.handlers.update(event, modeContext());
4477
+ apply(result?.commands, effects);
4478
+ effects.handledBy = session.modeId;
4479
+ if (result?.status === "end") {
4480
+ session = null;
4481
+ effects.sessionEnded = true;
4482
+ }
4483
+ return effects;
4484
+ }
4485
+ if (event.kind === "pointer.down") {
4486
+ effects.handledBy = session.modeId;
4487
+ return effects;
4488
+ }
4489
+ return effects;
4490
+ }
4491
+ const ctx = modeContext();
4492
+ const modes = [...resolveModes(ctx.context)].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
4493
+ for (const mode of modes) {
4494
+ const reaction = mode.start(event, ctx);
4495
+ if (!reaction) continue;
4496
+ apply(reaction.commands, effects);
4497
+ effects.handledBy = mode.id;
4498
+ if (reaction.session) {
4499
+ session = {
4500
+ handlers: reaction.session,
4501
+ modeId: mode.id,
4502
+ pointerId: isPointer ? event.pointerId : null
4503
+ };
4504
+ effects.sessionStarted = true;
4505
+ }
4506
+ break;
4507
+ }
4508
+ return effects;
4509
+ }
4510
+ function cancelSession() {
4511
+ if (!session) return;
4512
+ const effects = {
4513
+ preventDefault: false,
4514
+ stopPropagation: false,
4515
+ sessionStarted: false,
4516
+ sessionEnded: true,
4517
+ handledBy: session.modeId
4518
+ };
4519
+ const commands = session.handlers.cancel?.(modeContext());
4520
+ session = null;
4521
+ apply(commands ?? void 0, effects);
4522
+ }
4523
+ return {
4524
+ send,
4525
+ cancelSession,
4526
+ getActiveSession: () => session?.modeId ?? null
4527
+ };
4528
+ }
4529
+ /** Default mode resolution: follow the store's `context.mode`. */
4530
+ function defaultModesForContext(context) {
4531
+ return context.mode === "readonly" ? readonlyInputModes : defaultInputModes;
4532
+ }
4533
+ /**
4534
+ * Mode resolution driven by a store profile: the active store mode's
4535
+ * `input.modes` wins, then the profile-level `input.modes`, then the
4536
+ * built-in defaults.
4537
+ */
4538
+ function profileModesForContext(profile) {
4539
+ return (context) => {
4540
+ const mode = profile.modes[context.mode] ? context.mode : profile.defaultMode;
4541
+ return profile.modes[mode]?.input?.modes ?? profile.input?.modes ?? defaultModesForContext(context);
4542
+ };
4543
+ }
4544
+ /**
4545
+ * Per-frame auto-pan step while a drag or connection gesture is near the
4546
+ * container edge. Returns the `calcAutoPan` screen-space delta (negate it for
4547
+ * `panBy`), or null when auto-pan should not run. Adapters call this from a
4548
+ * frame ticker while a gesture session is active and re-send the stationary
4549
+ * pointer afterwards so the dragged entity follows the panned canvas.
4550
+ */
4551
+ function getAutoPanDelta(context, screenPoint, engine) {
4552
+ if (!context.autoPanOnDrag) return null;
4553
+ if (context.canvasState !== "dragging" && context.canvasState !== "connecting") return null;
4554
+ const size = context.viewportSize;
4555
+ if (size.width === 0 || size.height === 0) return null;
4556
+ const delta = calcAutoPan(screenPoint, size, context.autoPanThreshold, context.autoPanSpeed);
4557
+ if (delta.x === 0 && delta.y === 0) return null;
4558
+ if (engine && context.canvasState === "dragging") {
4559
+ let union = null;
4560
+ for (const selectedId of context.selection) {
4561
+ const node = engine.getNode(selectedId);
4562
+ if (!node || node.draggable === false) continue;
4563
+ const b = engine.resolvedBounds(selectedId);
4564
+ const x0 = b.x * context.viewport.zoom + context.viewport.x;
4565
+ const y0 = b.y * context.viewport.zoom + context.viewport.y;
4566
+ const x1 = x0 + b.width * context.viewport.zoom;
4567
+ const y1 = y0 + b.height * context.viewport.zoom;
4568
+ union = union ? {
4569
+ x0: Math.min(union.x0, x0),
4570
+ y0: Math.min(union.y0, y0),
4571
+ x1: Math.max(union.x1, x1),
4572
+ y1: Math.max(union.y1, y1)
4573
+ } : {
4574
+ x0,
4575
+ y0,
4576
+ x1,
4577
+ y1
4578
+ };
4579
+ }
4580
+ if (union) {
4581
+ const edge = context.autoPanThreshold;
4582
+ if (delta.x < 0 && union.x0 > edge) delta.x = 0;
4583
+ if (delta.x > 0 && union.x1 < size.width - edge) delta.x = 0;
4584
+ if (delta.y < 0 && union.y0 > edge) delta.y = 0;
4585
+ if (delta.y > 0 && union.y1 < size.height - edge) delta.y = 0;
4586
+ if (delta.x === 0 && delta.y === 0) return null;
4587
+ }
4588
+ }
4589
+ return delta;
4590
+ }
4591
+ //#endregion
4592
+ //#region src/entity-changes.ts
4593
+ const adjacencyCache = /* @__PURE__ */ new WeakMap();
4594
+ function adjacency(edges) {
4595
+ let index = adjacencyCache.get(edges);
4596
+ if (!index) {
4597
+ index = /* @__PURE__ */ new Map();
4598
+ for (const edge of edges) {
4599
+ let source = index.get(edge.sourceId);
4600
+ if (!source) index.set(edge.sourceId, source = []);
4601
+ source.push(edge.id);
4602
+ if (edge.targetId !== edge.sourceId) {
4603
+ let target = index.get(edge.targetId);
4604
+ if (!target) index.set(edge.targetId, target = []);
4605
+ target.push(edge.id);
4606
+ }
4607
+ }
4608
+ adjacencyCache.set(edges, index);
4609
+ }
4610
+ return index;
4611
+ }
4612
+ function computeDirty(prev, next) {
4613
+ if (next.canvasState !== prev.canvasState) return "all";
4614
+ if (next.mode !== prev.mode) return "all";
4615
+ if (next.enableSnapLines && next.canvasState === "dragging") return "all";
4616
+ const dirty = /* @__PURE__ */ new Set();
4617
+ const markIncidentEdges = (nodeId, edges) => {
4618
+ const incident = adjacency(edges).get(nodeId);
4619
+ if (incident) for (const edgeId of incident) dirty.add(edgeId);
4620
+ };
4621
+ const markAncestors = (node) => {
4622
+ const nextIndex = indexNodes(next.graph.nodes);
4623
+ const seen = /* @__PURE__ */ new Set();
4624
+ let parentId = node.parentId ?? null;
4625
+ while (parentId && !seen.has(parentId)) {
4626
+ seen.add(parentId);
4627
+ dirty.add(parentId);
4628
+ markIncidentEdges(parentId, next.graph.edges);
4629
+ parentId = nextIndex.get(parentId)?.parentId ?? null;
4630
+ }
4631
+ };
4632
+ if (next.graph.nodes !== prev.graph.nodes) {
4633
+ const prevIndex = indexNodes(prev.graph.nodes);
4634
+ const nextIndex = indexNodes(next.graph.nodes);
4635
+ for (const node of next.graph.nodes) {
4636
+ const before = prevIndex.get(node.id);
4637
+ if (before !== node) {
4638
+ dirty.add(node.id);
4639
+ markIncidentEdges(node.id, next.graph.edges);
4640
+ markAncestors(node);
4641
+ if (before && (before.parentId ?? null) !== (node.parentId ?? null)) markAncestors(before);
4642
+ }
4643
+ }
4644
+ for (const node of prev.graph.nodes) if (!nextIndex.has(node.id)) {
4645
+ dirty.add(node.id);
4646
+ markIncidentEdges(node.id, prev.graph.edges);
4647
+ markAncestors(node);
4648
+ }
4649
+ }
4650
+ if (next.graph.edges !== prev.graph.edges) {
4651
+ const prevIndex = indexEdges(prev.graph.edges);
4652
+ const nextIndex = indexEdges(next.graph.edges);
4653
+ const nodeIndex = indexNodes(next.graph.nodes);
4654
+ const markEndpointAncestors = (edge) => {
4655
+ const source = nodeIndex.get(edge.sourceId);
4656
+ const target = nodeIndex.get(edge.targetId);
4657
+ markAncestors(source ?? {});
4658
+ markAncestors(target ?? {});
4659
+ if (source?.group) dirty.add(source.id);
4660
+ if (target?.group) dirty.add(target.id);
4661
+ };
4662
+ for (const edge of next.graph.edges) if (prevIndex.get(edge.id) !== edge) {
4663
+ dirty.add(edge.id);
4664
+ markEndpointAncestors(edge);
4665
+ }
4666
+ for (const edge of prev.graph.edges) if (!nextIndex.has(edge.id)) {
4667
+ dirty.add(edge.id);
4668
+ markEndpointAncestors(edge);
4669
+ }
4670
+ }
4671
+ if (next.selection !== prev.selection) {
4672
+ for (const id of next.selection) if (!prev.selection.has(id)) dirty.add(id);
4673
+ for (const id of prev.selection) if (!next.selection.has(id)) dirty.add(id);
4674
+ }
4675
+ if (next.hoveredEntityIds !== prev.hoveredEntityIds) {
4676
+ for (const id of next.hoveredEntityIds) if (!prev.hoveredEntityIds.has(id)) dirty.add(id);
4677
+ for (const id of prev.hoveredEntityIds) if (!next.hoveredEntityIds.has(id)) dirty.add(id);
4678
+ }
4679
+ if (next.highlights !== prev.highlights) {
4680
+ const kinds = new Set([...prev.highlights.keys(), ...next.highlights.keys()]);
4681
+ for (const kind of kinds) {
4682
+ const before = prev.highlights.get(kind);
4683
+ const after = next.highlights.get(kind);
4684
+ if (before === after) continue;
4685
+ if (before) for (const id of before.keys()) dirty.add(id);
4686
+ if (after) for (const id of after.keys()) dirty.add(id);
4687
+ }
4688
+ }
4689
+ const idPairs = [
4690
+ [prev.draggedEntityId, next.draggedEntityId],
4691
+ [prev.focusedEntityId, next.focusedEntityId],
4692
+ [prev.resizingEntityId, next.resizingEntityId]
4693
+ ];
4694
+ for (const [before, after] of idPairs) if (before !== after) {
4695
+ if (before) dirty.add(before);
4696
+ if (after) dirty.add(after);
4697
+ }
4698
+ if (next.resizeCorners !== prev.resizeCorners && next.resizingEntityId) {
4699
+ dirty.add(next.resizingEntityId);
4700
+ markIncidentEdges(next.resizingEntityId, next.graph.edges);
4701
+ }
4702
+ return dirty;
4703
+ }
4704
+ function createEntityChangeNotifier(store) {
4705
+ const listeners = /* @__PURE__ */ new Map();
4706
+ let prev = store.getSnapshot().context;
4707
+ const subscription = store.subscribe((snapshot) => {
4708
+ const next = snapshot.context;
4709
+ if (next === prev) return;
4710
+ const dirty = computeDirty(prev, next);
4711
+ prev = next;
4712
+ if (dirty === "all") {
4713
+ for (const set of listeners.values()) for (const listener of [...set]) listener();
4714
+ return;
4715
+ }
4716
+ for (const id of dirty) {
4717
+ const set = listeners.get(id);
4718
+ if (set) for (const listener of [...set]) listener();
4719
+ }
4720
+ });
4721
+ return {
4722
+ subscribe(id, listener) {
4723
+ let set = listeners.get(id);
4724
+ if (!set) {
4725
+ set = /* @__PURE__ */ new Set();
4726
+ listeners.set(id, set);
4727
+ }
4728
+ set.add(listener);
4729
+ return () => {
4730
+ set.delete(listener);
4731
+ if (set.size === 0) listeners.delete(id);
4732
+ };
4733
+ },
4734
+ destroy() {
4735
+ subscription.unsubscribe();
4736
+ listeners.clear();
4737
+ }
4738
+ };
4739
+ }
2533
4740
  //#endregion
2534
- export { bestDirection, bezierRouter, boxToRect, calcAutoPan, canvasToScreen, clampZoom, constrainViewport, createEdge, createFlow, createFlowEngine, createFlowStore, createGraph, createNode, createViewport, defaultConfig, getAnchorTransform, getGraphBounds, getSelectionBounds, getShape, getShapeOrDefault, getSnapLines, getVisibleBounds, isTrackpadPinch, normalizeWheelPan, panBy, pathToSVG, readonlyConfig, rectContains, rectsIntersect, registerShape, resolveBehavior, resolvedBounds, resolvedPosition, screenToCanvas, selectMode, snapPointToGrid, snapToGrid, snappedBounds, stepRouter, straightRouter, toSVGTransform, toViewBox, viewportForBounds, wheelInteraction, wheelZoomDelta, zoomTo };
4741
+ export { CONNECTION_PREVIEW_EDGE_ID, CONNECTION_PREVIEW_NODE_ID, bestDirection, bezierRouter, boxToRect, calcAutoPan, canvasToScreen, clampZoom, connectMode, constrainViewport, createConnectionPreviewGraph, createEdge, createEntityChangeNotifier, createFlow, createFlowEngine, createFlowInputRuntime, createFlowStore, createGraph, createNode, createPort, createViewport, defaultConfig, defaultFlowProfile, defaultInputModes, defaultModesForContext, defineFlowProfile, deriveGroupGeometry, entityPressMode, fixedGroupGeometry, getAnchorTransform, getAutoPanDelta, getEdgeOwner, getGraphBounds, getMinimapProjection, getSelectionBounds, getShape, getShapeOrDefault, getSnapLines, getToolbarPlacement, getVisibleBounds, hoverMode, indexChildren, indexEdges, indexNodes, isDerivedGroup, isGroup, isTrackpadPinch, keyboardMode, keyboardNavMode, nodeDepths, normalizeWheelPan, panBy, panMode, panePressMode, pathToSVG, preventDefault, profileModesForContext, readonlyConfig, readonlyInputModes, rectContains, rectsIntersect, registerShape, resolveBehavior, resolveGroupPadding, resolvedBounds, resolvedPosition, screenToCanvas, selectMode, snapPointToGrid, snapToGrid, snappedBounds, stepRouter, straightRouter, toSVGTransform, toViewBox, trigger, unionRect, viewportCenteredOn, viewportForBounds, wheelInteraction, wheelMode, wheelZoomDelta, zoomTo };