@statelyai/flow 0.8.2 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -561,6 +561,15 @@ function visualBounds(node) {
561
561
  }
562
562
  /** @deprecated Use `visualBounds`. */
563
563
  const resolvedBounds = visualBounds;
564
+ /** Bounds used by marquee selection, including transient node movement. */
565
+ function resolvedSelectionBounds(node) {
566
+ if (!node.selectionBounds) return visualBounds(node);
567
+ return {
568
+ ...node.selectionBounds,
569
+ x: node.selectionBounds.x + (node.dx ?? 0),
570
+ y: node.selectionBounds.y + (node.dy ?? 0)
571
+ };
572
+ }
564
573
  /**
565
574
  * Size used for edge-label geometry. `autoSize` labels retain authored
566
575
  * dimensions as a fallback while a transient DOM measurement owns the live
@@ -1244,41 +1253,71 @@ function getSnapLines(rect, otherRects, { threshold = 5, enableSpacing = false }
1244
1253
  //#endregion
1245
1254
  //#region src/graph-index.ts
1246
1255
  const nodeIndexCache = /* @__PURE__ */ new WeakMap();
1256
+ const nodePositionCache = /* @__PURE__ */ new WeakMap();
1257
+ const childrenIndexCache = /* @__PURE__ */ new WeakMap();
1247
1258
  const edgeIndexCache = /* @__PURE__ */ new WeakMap();
1259
+ const edgePositionCache = /* @__PURE__ */ new WeakMap();
1248
1260
  const edgeAdjacencyCache = /* @__PURE__ */ new WeakMap();
1249
1261
  function indexNodes(nodes) {
1250
1262
  let index = nodeIndexCache.get(nodes);
1251
1263
  if (!index) {
1252
1264
  index = /* @__PURE__ */ new Map();
1253
- for (const node of nodes) if (!index.has(node.id)) index.set(node.id, node);
1265
+ const positions = /* @__PURE__ */ new Map();
1266
+ const children = /* @__PURE__ */ new Map();
1267
+ for (let position = 0; position < nodes.length; position++) {
1268
+ const node = nodes[position];
1269
+ if (!index.has(node.id)) index.set(node.id, node);
1270
+ if (!positions.has(node.id)) positions.set(node.id, position);
1271
+ const parentId = node.parentId ?? null;
1272
+ if (parentId == null || parentId === node.id) continue;
1273
+ const bucket = children.get(parentId);
1274
+ if (bucket) bucket.push(node);
1275
+ else children.set(parentId, [node]);
1276
+ }
1254
1277
  nodeIndexCache.set(nodes, index);
1278
+ nodePositionCache.set(nodes, positions);
1279
+ childrenIndexCache.set(nodes, children);
1255
1280
  }
1256
1281
  return index;
1257
1282
  }
1283
+ function indexNodePositions(nodes) {
1284
+ if (!nodePositionCache.has(nodes)) indexNodes(nodes);
1285
+ return nodePositionCache.get(nodes);
1286
+ }
1258
1287
  function indexEdges(edges) {
1259
1288
  let index = edgeIndexCache.get(edges);
1260
1289
  if (!index) {
1261
1290
  index = /* @__PURE__ */ new Map();
1262
- for (const edge of edges) if (!index.has(edge.id)) index.set(edge.id, edge);
1291
+ const positions = /* @__PURE__ */ new Map();
1292
+ const adjacency = {
1293
+ bySource: /* @__PURE__ */ new Map(),
1294
+ byTarget: /* @__PURE__ */ new Map(),
1295
+ byNode: /* @__PURE__ */ new Map()
1296
+ };
1297
+ for (let position = 0; position < edges.length; position++) {
1298
+ const edge = edges[position];
1299
+ if (!index.has(edge.id)) index.set(edge.id, edge);
1300
+ if (!positions.has(edge.id)) positions.set(edge.id, position);
1301
+ pushEdge(adjacency.bySource, edge.sourceId, edge);
1302
+ pushEdge(adjacency.byTarget, edge.targetId, edge);
1303
+ pushEdge(adjacency.byNode, edge.sourceId, edge);
1304
+ if (edge.targetId !== edge.sourceId) pushEdge(adjacency.byNode, edge.targetId, edge);
1305
+ }
1263
1306
  edgeIndexCache.set(edges, index);
1307
+ edgePositionCache.set(edges, positions);
1308
+ edgeAdjacencyCache.set(edges, adjacency);
1264
1309
  }
1265
1310
  return index;
1266
1311
  }
1312
+ function indexEdgePositions(edges) {
1313
+ if (!edgePositionCache.has(edges)) indexEdges(edges);
1314
+ return edgePositionCache.get(edges);
1315
+ }
1267
1316
  function indexEdgeAdjacency(edges) {
1268
1317
  let index = edgeAdjacencyCache.get(edges);
1269
1318
  if (!index) {
1270
- index = {
1271
- bySource: /* @__PURE__ */ new Map(),
1272
- byTarget: /* @__PURE__ */ new Map(),
1273
- byNode: /* @__PURE__ */ new Map()
1274
- };
1275
- for (const edge of edges) {
1276
- pushEdge(index.bySource, edge.sourceId, edge);
1277
- pushEdge(index.byTarget, edge.targetId, edge);
1278
- pushEdge(index.byNode, edge.sourceId, edge);
1279
- if (edge.targetId !== edge.sourceId) pushEdge(index.byNode, edge.targetId, edge);
1280
- }
1281
- edgeAdjacencyCache.set(edges, index);
1319
+ indexEdges(edges);
1320
+ index = edgeAdjacencyCache.get(edges);
1282
1321
  }
1283
1322
  return index;
1284
1323
  }
@@ -1310,20 +1349,12 @@ function getNeighbors(graph, nodeId) {
1310
1349
  for (const node of getOutgoers(graph, nodeId)) neighborIds.add(node.id);
1311
1350
  return graph.nodes.filter((node) => neighborIds.has(node.id));
1312
1351
  }
1313
- const childrenIndexCache = /* @__PURE__ */ new WeakMap();
1314
1352
  /** parentId → child nodes, cached on array identity. Self-parents ignored. */
1315
1353
  function indexChildren(nodes) {
1316
1354
  let index = childrenIndexCache.get(nodes);
1317
1355
  if (!index) {
1318
- index = /* @__PURE__ */ new Map();
1319
- for (const node of nodes) {
1320
- const parentId = node.parentId ?? null;
1321
- if (parentId == null || parentId === node.id) continue;
1322
- const children = index.get(parentId);
1323
- if (children) children.push(node);
1324
- else index.set(parentId, [node]);
1325
- }
1326
- childrenIndexCache.set(nodes, index);
1356
+ indexNodes(nodes);
1357
+ index = childrenIndexCache.get(nodes);
1327
1358
  }
1328
1359
  return index;
1329
1360
  }
@@ -2632,37 +2663,53 @@ function invalidatePathsForNodeGeometry(draft, changedNodeIds, topologyNodes = d
2632
2663
  function isUndoableEventType(type) {
2633
2664
  return UNDOABLE_EVENT_TYPES.includes(type);
2634
2665
  }
2635
- function planNodeMovement(ctx, dx, dy, options = {}) {
2666
+ function createMovementTopology(nodes, edges) {
2667
+ const nodeArray = nodes;
2668
+ const edgeArray = edges;
2669
+ const nodeIndices = indexNodePositions(nodeArray);
2670
+ const edgeIndices = indexEdgePositions(edgeArray);
2671
+ const children = indexChildren(nodeArray);
2672
+ return {
2673
+ nodeIndices,
2674
+ edgeIndices,
2675
+ childrenByParent: children.size ? new Map([...children].map(([parentId, childNodes]) => [parentId, childNodes.map((node) => node.id)])) : null,
2676
+ nodeCount: nodes.length,
2677
+ edgeCount: edges.length
2678
+ };
2679
+ }
2680
+ function planNodeMovement(ctx, dx, dy, options = {}, topology) {
2636
2681
  const nodes = ctx.graph.nodes;
2637
2682
  const edges = ctx.graph.edges;
2638
- const nodeIndex = indexNodes(nodes);
2639
- const edgeIndex = indexEdges(edges);
2683
+ const usableTopology = topology?.nodeCount === nodes.length && topology.edgeCount === edges.length ? topology : createMovementTopology(nodes, edges);
2684
+ const nodeAt = (id) => {
2685
+ const index = usableTopology.nodeIndices.get(id);
2686
+ const node = index === void 0 ? void 0 : nodes[index];
2687
+ return node?.id === id ? node : void 0;
2688
+ };
2689
+ const edgeAt = (id) => {
2690
+ const index = usableTopology.edgeIndices.get(id);
2691
+ const edge = index === void 0 ? void 0 : edges[index];
2692
+ return edge?.id === id ? edge : void 0;
2693
+ };
2640
2694
  const movingNodeIds = /* @__PURE__ */ new Set();
2641
2695
  const labelEdgeIds = /* @__PURE__ */ new Set();
2642
2696
  for (const id of ctx.selection) {
2643
- const node = nodeIndex.get(id);
2697
+ const node = nodeAt(id);
2644
2698
  if (node) {
2645
2699
  if (node.draggable !== false) movingNodeIds.add(id);
2646
2700
  continue;
2647
2701
  }
2648
2702
  if (options.includeLabels) {
2649
- const edge = edgeIndex.get(id);
2703
+ const edge = edgeAt(id);
2650
2704
  if (edge && edge.draggable !== false && edge.label) labelEdgeIds.add(id);
2651
2705
  }
2652
2706
  }
2653
2707
  if (movingNodeIds.size === 0 && labelEdgeIds.size === 0) return null;
2654
- let childrenByParent = null;
2655
- for (const node of nodes) {
2656
- const parentId = node.parentId ?? null;
2657
- if (parentId == null || parentId === node.id) continue;
2658
- if (!childrenByParent) childrenByParent = /* @__PURE__ */ new Map();
2659
- const children = childrenByParent.get(parentId);
2660
- if (children) children.push(node.id);
2661
- else childrenByParent.set(parentId, [node.id]);
2662
- }
2708
+ const childrenByParent = usableTopology.childrenByParent;
2709
+ const hierarchyNodeIndex = childrenByParent ? indexNodes(nodes) : null;
2663
2710
  const deltasById = /* @__PURE__ */ new Map();
2664
2711
  for (const id of movingNodeIds) {
2665
- const node = nodeIndex.get(id);
2712
+ const node = nodeAt(id);
2666
2713
  const oldDx = node.dx ?? 0;
2667
2714
  const oldDy = node.dy ?? 0;
2668
2715
  let newDx = oldDx + dx;
@@ -2674,7 +2721,7 @@ function planNodeMovement(ctx, dx, dy, options = {}) {
2674
2721
  newDx = clampedX - node.x;
2675
2722
  newDy = clampedY - node.y;
2676
2723
  }
2677
- const parent = node.parentId ? nodeIndex.get(node.parentId) : void 0;
2724
+ const parent = node.parentId ? hierarchyNodeIndex?.get(node.parentId) : void 0;
2678
2725
  if (parent?.group?.type === "fixed") {
2679
2726
  const axes = parent.group.clampChildren ?? "none";
2680
2727
  if (axes !== "none") {
@@ -2711,9 +2758,9 @@ function planNodeMovement(ctx, dx, dy, options = {}) {
2711
2758
  if (childrenByParent) collectDescendantDeltas(childrenByParent, id, applied, movingNodeIds, deltasById);
2712
2759
  }
2713
2760
  const nodeDeltasByIndex = /* @__PURE__ */ new Map();
2714
- if (deltasById.size > 0) for (let i = 0; i < nodes.length; i++) {
2715
- const delta = deltasById.get(nodes[i].id);
2716
- if (delta) nodeDeltasByIndex.set(i, delta);
2761
+ if (deltasById.size > 0) for (const [id, delta] of deltasById) {
2762
+ const index = usableTopology.nodeIndices.get(id);
2763
+ if (index !== void 0 && nodes[index]?.id === id) nodeDeltasByIndex.set(index, delta);
2717
2764
  }
2718
2765
  const edgeDeltasByIndex = /* @__PURE__ */ new Map();
2719
2766
  const labelDeltasByIndex = /* @__PURE__ */ new Map();
@@ -2723,16 +2770,16 @@ function planNodeMovement(ctx, dx, dy, options = {}) {
2723
2770
  const carriesFixedLabel = !!edge.label && (edge.labelAnchor ?? ctx.labelAnchor) === "fixed";
2724
2771
  if (!carriesWaypoints && !carriesFixedLabel) continue;
2725
2772
  if (!deltasById.has(edge.sourceId) || !deltasById.has(edge.targetId)) continue;
2726
- const ownerId = getEdgeOwnerFromIndex(edge, nodeIndex);
2773
+ const ownerId = getEdgeOwnerFromIndex(edge, hierarchyNodeIndex);
2727
2774
  const ownerDelta = ownerId ? deltasById.get(ownerId) : void 0;
2728
2775
  if (!ownerDelta) continue;
2729
2776
  edgeDeltasByIndex.set(i, ownerDelta);
2730
2777
  if (carriesFixedLabel) labelDeltasByIndex.set(i, ownerDelta);
2731
2778
  }
2732
- if (labelEdgeIds.size > 0) for (let i = 0; i < edges.length; i++) {
2733
- const edge = edges[i];
2734
- if (!labelEdgeIds.has(edge.id) || labelDeltasByIndex.has(i)) continue;
2735
- labelDeltasByIndex.set(i, {
2779
+ if (labelEdgeIds.size > 0) for (const id of labelEdgeIds) {
2780
+ const index = usableTopology.edgeIndices.get(id);
2781
+ if (index === void 0 || edges[index]?.id !== id || labelDeltasByIndex.has(index)) continue;
2782
+ labelDeltasByIndex.set(index, {
2736
2783
  x: dx,
2737
2784
  y: dy
2738
2785
  });
@@ -2933,6 +2980,7 @@ function restoreHistoryContext(currentContext, historicalContext) {
2933
2980
  },
2934
2981
  canvasState: "idle",
2935
2982
  draggedEntityId: null,
2983
+ dragRevision: 0,
2936
2984
  selectionBox: null,
2937
2985
  selectionBoxBase: null,
2938
2986
  connection: null,
@@ -2952,22 +3000,51 @@ function plainViewport(viewport) {
2952
3000
  zoom: viewport.zoom
2953
3001
  };
2954
3002
  }
2955
- function entityPositions(graph, ids) {
3003
+ function entityPositions(graph, ids, movement, topology) {
2956
3004
  const positions = {};
3005
+ const usableTopology = topology?.nodeCount === graph.nodes.length && topology.edgeCount === graph.edges.length ? topology : null;
3006
+ const nodes = usableTopology ? null : indexNodes(graph.nodes);
3007
+ const edges = usableTopology ? null : indexEdges(graph.edges);
3008
+ const nodeAt = (id) => {
3009
+ const index = usableTopology?.nodeIndices.get(id);
3010
+ const node = index === void 0 ? nodes?.get(id) : graph.nodes[index];
3011
+ return node?.id === id ? node : void 0;
3012
+ };
3013
+ const edgeAt = (id) => {
3014
+ const index = usableTopology?.edgeIndices.get(id);
3015
+ const edge = index === void 0 ? edges?.get(id) : graph.edges[index];
3016
+ return edge?.id === id ? edge : void 0;
3017
+ };
3018
+ const nodeDeltas = /* @__PURE__ */ new Map();
3019
+ const labelDeltas = /* @__PURE__ */ new Map();
3020
+ if (movement) {
3021
+ for (const [index, delta] of movement.nodeDeltasByIndex) {
3022
+ const node = graph.nodes[index];
3023
+ if (node) nodeDeltas.set(node.id, delta);
3024
+ }
3025
+ for (const [index, delta] of movement.labelDeltasByIndex) {
3026
+ const edge = graph.edges[index];
3027
+ if (edge) labelDeltas.set(edge.id, delta);
3028
+ }
3029
+ }
2957
3030
  for (const id of ids) {
2958
- const node = graph.nodes.find((candidate) => candidate.id === id);
3031
+ const node = nodeAt(id);
2959
3032
  if (node) {
3033
+ const delta = nodeDeltas.get(id);
2960
3034
  positions[id] = {
2961
- x: node.x + (node.dx ?? 0),
2962
- y: node.y + (node.dy ?? 0)
3035
+ x: node.x + (node.dx ?? 0) + (delta?.x ?? 0),
3036
+ y: node.y + (node.dy ?? 0) + (delta?.y ?? 0)
2963
3037
  };
2964
3038
  continue;
2965
3039
  }
2966
- const edge = graph.edges.find((candidate) => candidate.id === id);
2967
- if (edge?.label) positions[id] = {
2968
- x: edge.label.x + (edge.label.dx ?? 0),
2969
- y: edge.label.y + (edge.label.dy ?? 0)
2970
- };
3040
+ const edge = edgeAt(id);
3041
+ if (edge?.label) {
3042
+ const delta = labelDeltas.get(id);
3043
+ positions[id] = {
3044
+ x: edge.label.x + (edge.label.dx ?? 0) + (delta?.x ?? 0),
3045
+ y: edge.label.y + (edge.label.dy ?? 0) + (delta?.y ?? 0)
3046
+ };
3047
+ }
2971
3048
  }
2972
3049
  return positions;
2973
3050
  }
@@ -3019,6 +3096,21 @@ function createEventObject(type, event) {
3019
3096
  function isExplicitlyVisibleNode(node) {
3020
3097
  return !node.hidden;
3021
3098
  }
3099
+ /**
3100
+ * A collapsed group hides its descendants: they are not selectable and do not
3101
+ * contribute to any group's derived selection geometry. Mirrors the engine's
3102
+ * `isHiddenByCollapsedAncestor`.
3103
+ */
3104
+ function isHiddenByCollapsedAncestor(ctx, nodeId) {
3105
+ if (ctx.collapsedNodeIds.size === 0) return false;
3106
+ const nodeIndex = indexNodes(ctx.graph.nodes);
3107
+ let parentId = nodeIndex.get(nodeId)?.parentId;
3108
+ while (parentId) {
3109
+ if (ctx.collapsedNodeIds.has(parentId)) return true;
3110
+ parentId = nodeIndex.get(parentId)?.parentId;
3111
+ }
3112
+ return false;
3113
+ }
3022
3114
  function isDescendantOf(nodes, nodeId, ancestorId) {
3023
3115
  const byId = new Map(nodes.map((node) => [node.id, node]));
3024
3116
  let parentId = byId.get(nodeId)?.parentId;
@@ -3053,7 +3145,8 @@ function entitiesInBox(ctx, rect) {
3053
3145
  const nodes = ctx.graph.nodes;
3054
3146
  for (const node of nodes) {
3055
3147
  if (!isExplicitlyVisibleNode(node)) continue;
3056
- if (test(rect, resolvedBounds(node))) ids.add(node.id);
3148
+ if (isHiddenByCollapsedAncestor(ctx, node.id)) continue;
3149
+ if (test(rect, nodeSelectionBounds(ctx, node))) ids.add(node.id);
3057
3150
  }
3058
3151
  for (const edge of ctx.graph.edges) {
3059
3152
  if (!isExplicitlyVisibleEdge(edge, nodes)) continue;
@@ -3062,12 +3155,51 @@ function entitiesInBox(ctx, rect) {
3062
3155
  }
3063
3156
  return ids;
3064
3157
  }
3065
- function isExplicitlyDraggable(id, graph) {
3066
- const node = graph.nodes.find((candidate) => candidate.id === id);
3067
- if (node) return node.draggable !== false;
3068
- const edge = graph.edges.find((candidate) => candidate.id === id);
3069
- if (edge) return edge.draggable !== false;
3070
- return false;
3158
+ function nodeSelectionBounds(ctx, node, visiting = /* @__PURE__ */ new Set()) {
3159
+ if (node.selectionBounds) return resolvedSelectionBounds(node);
3160
+ if (!node.group || visiting.has(node.id)) return resolvedBounds(node);
3161
+ return groupGeometryForSelection(ctx, node, visiting).contentBounds;
3162
+ }
3163
+ function groupGeometryForSelection(ctx, node, visiting) {
3164
+ if (node.group.type === "fixed") return fixedGroupGeometry(resolvedBounds(node), node.group.contentSize ?? {
3165
+ width: 0,
3166
+ height: 0
3167
+ }, node.group);
3168
+ const nextVisiting = new Set(visiting).add(node.id);
3169
+ let childrenBounds = null;
3170
+ const addBounds = (bounds) => {
3171
+ if (!childrenBounds) {
3172
+ childrenBounds = bounds;
3173
+ return;
3174
+ }
3175
+ const x = Math.min(childrenBounds.x, bounds.x);
3176
+ const y = Math.min(childrenBounds.y, bounds.y);
3177
+ const right = Math.max(childrenBounds.x + childrenBounds.width, bounds.x + bounds.width);
3178
+ const bottom = Math.max(childrenBounds.y + childrenBounds.height, bounds.y + bounds.height);
3179
+ childrenBounds = {
3180
+ x,
3181
+ y,
3182
+ width: right - x,
3183
+ height: bottom - y
3184
+ };
3185
+ };
3186
+ for (const child of ctx.graph.nodes) {
3187
+ if (child.parentId !== node.id || !isExplicitlyVisibleNode(child)) continue;
3188
+ if (isHiddenByCollapsedAncestor(ctx, child.id)) continue;
3189
+ addBounds(child.group && !nextVisiting.has(child.id) ? groupGeometryForSelection(ctx, child, nextVisiting).bounds : resolvedBounds(child));
3190
+ }
3191
+ const nodeIndex = indexNodes(ctx.graph.nodes);
3192
+ for (const edge of ctx.graph.edges) {
3193
+ if (edge.hidden || !edge.label) continue;
3194
+ if (edge.sourceId === node.id && edge.targetId === node.id) continue;
3195
+ if (getEdgeOwnerFromIndex(edge, nodeIndex) !== node.id) continue;
3196
+ const labelBounds = resolvedEdgeLabelBounds(edge, ctx.measurements.get(edge.id));
3197
+ if (labelBounds) addBounds(labelBounds);
3198
+ }
3199
+ return deriveGroupGeometry(resolvedSize(node), childrenBounds, node.group, {
3200
+ x: node.x + (node.dx ?? 0),
3201
+ y: node.y + (node.dy ?? 0)
3202
+ });
3071
3203
  }
3072
3204
  function getMode(profile, mode) {
3073
3205
  return profile.modes[mode] ? mode : profile.defaultMode;
@@ -3117,6 +3249,7 @@ function createFlowStore(initialGraph = {
3117
3249
  measurements: /* @__PURE__ */ new Map(),
3118
3250
  canvasState: "idle",
3119
3251
  draggedEntityId: null,
3252
+ dragRevision: 0,
3120
3253
  dragThreshold: options.dragThreshold ?? 3,
3121
3254
  constrainNodeMovement: options.constrainNodeMovement ?? null,
3122
3255
  autoPanOnDrag: options.autoPanOnDrag ?? true,
@@ -3150,6 +3283,7 @@ function createFlowStore(initialGraph = {
3150
3283
  },
3151
3284
  colorMode: options.colorMode ?? "system"
3152
3285
  };
3286
+ let activeDragMovementTopology = null;
3153
3287
  return createStore({
3154
3288
  context: initialContext,
3155
3289
  on: {
@@ -3588,29 +3722,44 @@ function createFlowStore(initialGraph = {
3588
3722
  event: createEventObject("expandNode", event)
3589
3723
  });
3590
3724
  }),
3591
- dragStart: (ctx, event, enqueue) => produce(ctx, (draft) => {
3592
- if (!isExplicitlyDraggable(event.id, draft.graph)) return;
3593
- draft.canvasState = "dragging";
3594
- draft.draggedEntityId = event.id;
3595
- draft.selection.add(event.id);
3596
- const ids = [...draft.selection];
3597
- enqueue.emit.dragStarted({
3598
- ids,
3599
- positions: entityPositions(draft.graph, ids)
3725
+ dragStart: (ctx, event, enqueue) => {
3726
+ const topology = createMovementTopology(ctx.graph.nodes, ctx.graph.edges);
3727
+ const nodeIndex = topology.nodeIndices.get(event.id);
3728
+ const edgeIndex = topology.edgeIndices.get(event.id);
3729
+ const entity = nodeIndex === void 0 ? edgeIndex === void 0 ? void 0 : ctx.graph.edges[edgeIndex] : ctx.graph.nodes[nodeIndex];
3730
+ if (!entity || entity.draggable === false) {
3731
+ activeDragMovementTopology = null;
3732
+ return ctx;
3733
+ }
3734
+ activeDragMovementTopology = topology;
3735
+ const selectedIds = new Set(ctx.selection);
3736
+ selectedIds.add(event.id);
3737
+ const ids = [...selectedIds];
3738
+ const positions = entityPositions(ctx.graph, ids, void 0, topology);
3739
+ return produce(ctx, (draft) => {
3740
+ draft.canvasState = "dragging";
3741
+ draft.draggedEntityId = event.id;
3742
+ draft.selection.add(event.id);
3743
+ enqueue.emit.dragStarted({
3744
+ ids,
3745
+ positions
3746
+ });
3600
3747
  });
3601
- }),
3748
+ },
3602
3749
  dragMove: (ctx, event, enqueue) => {
3603
3750
  if (ctx.canvasState !== "dragging") return ctx;
3604
3751
  const { dx, dy } = event;
3605
3752
  if (dx === 0 && dy === 0) return ctx;
3606
- const plan = planNodeMovement(ctx, dx, dy, { includeLabels: true });
3753
+ const plan = planNodeMovement(ctx, dx, dy, { includeLabels: true }, activeDragMovementTopology ?? void 0);
3607
3754
  if (!plan) return ctx;
3755
+ const ids = [...ctx.selection];
3756
+ const positions = entityPositions(ctx.graph, ids, plan, activeDragMovementTopology ?? void 0);
3608
3757
  return produce(ctx, (draft) => {
3609
3758
  applyMovementPlan(draft, plan);
3610
- const ids = [...draft.selection];
3759
+ draft.dragRevision++;
3611
3760
  enqueue.emit.dragMoved({
3612
3761
  ids,
3613
- positions: entityPositions(draft.graph, ids),
3762
+ positions,
3614
3763
  delta: {
3615
3764
  x: dx,
3616
3765
  y: dy
@@ -3620,6 +3769,7 @@ function createFlowStore(initialGraph = {
3620
3769
  },
3621
3770
  dragEnd: (ctx, _event, enqueue) => {
3622
3771
  if (ctx.canvasState !== "dragging") return ctx;
3772
+ activeDragMovementTopology = null;
3623
3773
  return produce(ctx, (draft) => {
3624
3774
  const ids = [...draft.selection];
3625
3775
  enqueue.emit.dragEnded({
@@ -3630,22 +3780,25 @@ function createFlowStore(initialGraph = {
3630
3780
  draft.draggedEntityId = null;
3631
3781
  });
3632
3782
  },
3633
- dragCancel: (ctx) => produce(ctx, (draft) => {
3634
- for (const node of draft.graph.nodes) {
3635
- delete node.dx;
3636
- delete node.dy;
3637
- }
3638
- for (const edge of draft.graph.edges) {
3639
- delete edge.dx;
3640
- delete edge.dy;
3641
- if (edge.label) {
3642
- delete edge.label.dx;
3643
- delete edge.label.dy;
3783
+ dragCancel: (ctx) => {
3784
+ activeDragMovementTopology = null;
3785
+ return produce(ctx, (draft) => {
3786
+ for (const node of draft.graph.nodes) {
3787
+ delete node.dx;
3788
+ delete node.dy;
3644
3789
  }
3645
- }
3646
- draft.canvasState = "idle";
3647
- draft.draggedEntityId = null;
3648
- }),
3790
+ for (const edge of draft.graph.edges) {
3791
+ delete edge.dx;
3792
+ delete edge.dy;
3793
+ if (edge.label) {
3794
+ delete edge.label.dx;
3795
+ delete edge.label.dy;
3796
+ }
3797
+ }
3798
+ draft.canvasState = "idle";
3799
+ draft.draggedEntityId = null;
3800
+ });
3801
+ },
3649
3802
  commitDrag: (ctx, _event, enqueue) => produce(ctx, (draft) => {
3650
3803
  let snapOffX = _event?.snapOffset?.x ?? 0;
3651
3804
  let snapOffY = _event?.snapOffset?.y ?? 0;
@@ -4464,69 +4617,101 @@ function createFlowStore(initialGraph = {
4464
4617
  event: createEventObject("applyLayoutResult", event)
4465
4618
  });
4466
4619
  }),
4467
- updateMeasurements: (ctx, event) => produce(ctx, (draft) => {
4468
- for (const measurement of event.measurements) {
4469
- const node = draft.graph.nodes.find((n) => n.id === measurement.id);
4470
- if (node) {
4471
- if (node.autoSize) {
4472
- const previousSize = resolvedSize(node);
4473
- const previousOffset = node.measured?.anchorOffset ?? {
4474
- x: 0,
4475
- y: 0
4476
- };
4477
- const anchor = resolveAutoSizeAnchor(node.autoSizeAnchor);
4478
- const nextSize = {
4479
- width: node.style?.customWidth ?? measurement.rect.width,
4480
- height: node.style?.customHeight ?? measurement.rect.height
4481
- };
4482
- const delta = {
4483
- x: (previousSize.width - nextSize.width) * anchor.x,
4484
- y: (previousSize.height - nextSize.height) * anchor.y
4485
- };
4486
- const anchorOffset = {
4487
- x: previousOffset.x + delta.x,
4488
- y: previousOffset.y + delta.y
4489
- };
4490
- const normalizedRect = {
4491
- x: anchor.x === 0 ? measurement.rect.x : node.x + delta.x + (node.dx ?? 0),
4492
- y: anchor.y === 0 ? measurement.rect.y : node.y + delta.y + (node.dy ?? 0),
4493
- width: measurement.rect.width,
4494
- height: measurement.rect.height
4495
- };
4496
- const existing = draft.measurements.get(measurement.id);
4497
- if (delta.x === 0 && delta.y === 0 && node.measured?.width === measurement.rect.width && node.measured?.height === measurement.rect.height && previousOffset.x === anchorOffset.x && previousOffset.y === anchorOffset.y && existing?.x === normalizedRect.x && existing.y === normalizedRect.y && existing.width === normalizedRect.width && existing.height === normalizedRect.height) continue;
4498
- node.measured = {
4499
- width: measurement.rect.width,
4500
- height: measurement.rect.height,
4501
- ...anchorOffset.x !== 0 || anchorOffset.y !== 0 ? { anchorOffset } : {}
4502
- };
4503
- node.x += delta.x;
4504
- node.y += delta.y;
4505
- draft.measurements.set(measurement.id, normalizedRect);
4506
- } else draft.measurements.set(measurement.id, measurement.rect);
4507
- continue;
4620
+ updateMeasurements: (ctx, event) => {
4621
+ const nodeIndices = /* @__PURE__ */ new Map();
4622
+ for (let index = 0; index < ctx.graph.nodes.length; index++) {
4623
+ const id = ctx.graph.nodes[index].id;
4624
+ if (!nodeIndices.has(id)) nodeIndices.set(id, index);
4625
+ }
4626
+ const needsSecondaryIndices = event.measurements.some((measurement) => !nodeIndices.has(measurement.id));
4627
+ const edgeIndices = /* @__PURE__ */ new Map();
4628
+ const portIndices = /* @__PURE__ */ new Map();
4629
+ if (needsSecondaryIndices) {
4630
+ for (let index = 0; index < ctx.graph.edges.length; index++) {
4631
+ const id = ctx.graph.edges[index].id;
4632
+ if (!edgeIndices.has(id)) edgeIndices.set(id, index);
4508
4633
  }
4509
- draft.measurements.set(measurement.id, measurement.rect);
4510
- const edge = draft.graph.edges.find((e) => e.id === measurement.id);
4511
- if (edge?.label) {
4512
- if (!edge.label.autoSize) {
4513
- edge.label.width = measurement.rect.width;
4514
- edge.label.height = measurement.rect.height;
4634
+ for (let nodeIndex = 0; nodeIndex < ctx.graph.nodes.length; nodeIndex++) {
4635
+ const node = ctx.graph.nodes[nodeIndex];
4636
+ for (let portIndex = 0; portIndex < (node.ports?.length ?? 0); portIndex++) {
4637
+ const port = node.ports[portIndex];
4638
+ const target = {
4639
+ nodeIndex,
4640
+ portIndex
4641
+ };
4642
+ const address = `${node.id}:${port.name}`;
4643
+ if (!portIndices.has(address)) portIndices.set(address, target);
4644
+ const explicitId = port.id;
4645
+ if (explicitId && !portIndices.has(explicitId)) portIndices.set(explicitId, target);
4515
4646
  }
4516
- continue;
4517
4647
  }
4518
- for (const candidate of draft.graph.nodes) {
4519
- const port = candidate.ports?.find((p) => p.id === measurement.id || `${candidate.id}:${p.name}` === measurement.id);
4520
- if (port) {
4648
+ }
4649
+ return produce(ctx, (draft) => {
4650
+ for (const measurement of event.measurements) {
4651
+ const nodeIndex = nodeIndices.get(measurement.id);
4652
+ if (nodeIndex !== void 0) {
4653
+ const node = draft.graph.nodes[nodeIndex];
4654
+ if (node.autoSize) {
4655
+ const previousSize = resolvedSize(node);
4656
+ const previousOffset = node.measured?.anchorOffset ?? {
4657
+ x: 0,
4658
+ y: 0
4659
+ };
4660
+ const anchor = resolveAutoSizeAnchor(node.autoSizeAnchor);
4661
+ const nextSize = {
4662
+ width: node.style?.customWidth ?? measurement.rect.width,
4663
+ height: node.style?.customHeight ?? measurement.rect.height
4664
+ };
4665
+ const delta = {
4666
+ x: (previousSize.width - nextSize.width) * anchor.x,
4667
+ y: (previousSize.height - nextSize.height) * anchor.y
4668
+ };
4669
+ const anchorOffset = {
4670
+ x: previousOffset.x + delta.x,
4671
+ y: previousOffset.y + delta.y
4672
+ };
4673
+ const normalizedRect = {
4674
+ x: anchor.x === 0 ? measurement.rect.x : node.x + delta.x + (node.dx ?? 0),
4675
+ y: anchor.y === 0 ? measurement.rect.y : node.y + delta.y + (node.dy ?? 0),
4676
+ width: measurement.rect.width,
4677
+ height: measurement.rect.height
4678
+ };
4679
+ const existing = draft.measurements.get(measurement.id);
4680
+ if (delta.x === 0 && delta.y === 0 && node.measured?.width === measurement.rect.width && node.measured?.height === measurement.rect.height && previousOffset.x === anchorOffset.x && previousOffset.y === anchorOffset.y && existing?.x === normalizedRect.x && existing.y === normalizedRect.y && existing.width === normalizedRect.width && existing.height === normalizedRect.height) continue;
4681
+ node.measured = {
4682
+ width: measurement.rect.width,
4683
+ height: measurement.rect.height,
4684
+ ...anchorOffset.x !== 0 || anchorOffset.y !== 0 ? { anchorOffset } : {}
4685
+ };
4686
+ node.x += delta.x;
4687
+ node.y += delta.y;
4688
+ draft.measurements.set(measurement.id, normalizedRect);
4689
+ } else draft.measurements.set(measurement.id, measurement.rect);
4690
+ continue;
4691
+ }
4692
+ draft.measurements.set(measurement.id, measurement.rect);
4693
+ const edgeIndex = edgeIndices.get(measurement.id);
4694
+ const edge = edgeIndex === void 0 ? void 0 : draft.graph.edges[edgeIndex];
4695
+ if (edge?.label) {
4696
+ if (!edge.label.autoSize) {
4697
+ edge.label.width = measurement.rect.width;
4698
+ edge.label.height = measurement.rect.height;
4699
+ }
4700
+ continue;
4701
+ }
4702
+ const portTarget = portIndices.get(measurement.id);
4703
+ if (portTarget) {
4704
+ const candidate = draft.graph.nodes[portTarget.nodeIndex];
4705
+ const port = candidate.ports?.[portTarget.portIndex];
4706
+ if (!port) continue;
4521
4707
  port.x = measurement.rect.x - (candidate.x + (candidate.dx ?? 0));
4522
4708
  port.y = measurement.rect.y - (candidate.y + (candidate.dy ?? 0));
4523
4709
  port.width = measurement.rect.width;
4524
4710
  port.height = measurement.rect.height;
4525
- break;
4526
4711
  }
4527
4712
  }
4528
- }
4529
- }),
4713
+ });
4714
+ },
4530
4715
  removeMeasurements: (ctx, event) => produce(ctx, (draft) => {
4531
4716
  for (const id of event.ids) draft.measurements.delete(id);
4532
4717
  }),
@@ -4829,6 +5014,8 @@ function offsetEdgeWaypoints(edge, offset = {
4829
5014
  y: point.y + dy
4830
5015
  }));
4831
5016
  }
5017
+ const SPATIAL_CELL_SIZE = 512;
5018
+ const MAX_ENTITY_SPATIAL_CELLS = 4096;
4832
5019
  /**
4833
5020
  * Create the framework-agnostic derived-geometry and query layer for a store.
4834
5021
  *
@@ -4848,6 +5035,10 @@ function createFlowEngine(store, initialOptions = {}) {
4848
5035
  const snapOffsetCache = /* @__PURE__ */ new WeakMap();
4849
5036
  let renderableCache = /* @__PURE__ */ new WeakMap();
4850
5037
  let entityOrderCache = null;
5038
+ let baseEntityOrderCache = null;
5039
+ let paintZIndicesCache = /* @__PURE__ */ new WeakMap();
5040
+ let entityRankCache = null;
5041
+ let renderableSpatialIndex = null;
4851
5042
  let graphBoundsCache = null;
4852
5043
  let groupGeometryCache = /* @__PURE__ */ new WeakMap();
4853
5044
  let visualGroupGeometryCache = /* @__PURE__ */ new WeakMap();
@@ -4911,6 +5102,10 @@ function createFlowEngine(store, initialOptions = {}) {
4911
5102
  stableEdgePathsCache = /* @__PURE__ */ new WeakMap();
4912
5103
  renderableCache = /* @__PURE__ */ new WeakMap();
4913
5104
  entityOrderCache = null;
5105
+ baseEntityOrderCache = null;
5106
+ paintZIndicesCache = /* @__PURE__ */ new WeakMap();
5107
+ entityRankCache = null;
5108
+ renderableSpatialIndex = null;
4914
5109
  graphBoundsCache = null;
4915
5110
  groupGeometryCache = /* @__PURE__ */ new WeakMap();
4916
5111
  visualGroupGeometryCache = /* @__PURE__ */ new WeakMap();
@@ -4940,9 +5135,18 @@ function createFlowEngine(store, initialOptions = {}) {
4940
5135
  }
4941
5136
  function edgeObstacles(edge, c) {
4942
5137
  const owner = edgeOwnerOf(edge, c);
5138
+ const nodeIndex = indexNodes(c.graph.nodes);
5139
+ const endpointLineage = /* @__PURE__ */ new Set();
5140
+ for (const endpointId of [edge.sourceId, edge.targetId]) {
5141
+ let node = nodeIndex.get(endpointId);
5142
+ while (node) {
5143
+ endpointLineage.add(node.id);
5144
+ node = node.parentId ? nodeIndex.get(node.parentId) : void 0;
5145
+ }
5146
+ }
4943
5147
  const result = [];
4944
5148
  for (const { id, bounds } of ownerObstacles(owner, c)) {
4945
- if (id === edge.sourceId || id === edge.targetId) continue;
5149
+ if (endpointLineage.has(id)) continue;
4946
5150
  result.push(bounds);
4947
5151
  }
4948
5152
  return result;
@@ -5314,6 +5518,39 @@ function createFlowEngine(store, initialOptions = {}) {
5314
5518
  const dy = point.y < rect.y ? rect.y - point.y : point.y > rect.y + rect.height ? point.y - (rect.y + rect.height) : 0;
5315
5519
  return Math.hypot(dx, dy);
5316
5520
  }
5521
+ function groupConnectionDistance(point, node, c) {
5522
+ const bounds = hierarchyBounds(node, c);
5523
+ const boundaryWidth = node.group?.connectionBoundaryWidth;
5524
+ if (boundaryWidth === void 0) return distanceToRect(point, bounds);
5525
+ const geometry = groupGeometryFor(c, node);
5526
+ if (!geometry) return distanceToRect(point, bounds);
5527
+ if (distanceToRect(point, geometry.contentBounds) === 0) return 0;
5528
+ const side = node.group?.content ?? "top";
5529
+ const childSurface = side === "top" ? {
5530
+ x: bounds.x,
5531
+ y: geometry.contentBounds.y + geometry.contentBounds.height,
5532
+ width: bounds.width,
5533
+ height: bounds.y + bounds.height - geometry.contentBounds.y - geometry.contentBounds.height
5534
+ } : side === "bottom" ? {
5535
+ x: bounds.x,
5536
+ y: bounds.y,
5537
+ width: bounds.width,
5538
+ height: geometry.contentBounds.y - bounds.y
5539
+ } : side === "left" ? {
5540
+ x: geometry.contentBounds.x + geometry.contentBounds.width,
5541
+ y: bounds.y,
5542
+ width: bounds.x + bounds.width - geometry.contentBounds.x - geometry.contentBounds.width,
5543
+ height: bounds.height
5544
+ } : {
5545
+ x: bounds.x,
5546
+ y: bounds.y,
5547
+ width: geometry.contentBounds.x - bounds.x,
5548
+ height: bounds.height
5549
+ };
5550
+ if (distanceToRect(point, childSurface) > 0) return distanceToRect(point, bounds);
5551
+ const inset = Math.max(0, boundaryWidth);
5552
+ return Math.min(point.x - childSurface.x, childSurface.x + childSurface.width - point.x, point.y - childSurface.y, childSurface.y + childSurface.height - point.y) <= inset ? 0 : Number.POSITIVE_INFINITY;
5553
+ }
5317
5554
  function getConnectionCandidate(pointer, options = {}) {
5318
5555
  const c = ctx();
5319
5556
  const { radius, mode } = connectionOptions(options);
@@ -5342,7 +5579,7 @@ function createFlowEngine(store, initialOptions = {}) {
5342
5579
  }
5343
5580
  if (mode !== "loose") continue;
5344
5581
  const bounds = hierarchyBounds(node, c);
5345
- const distance = distanceToRect(pointer, bounds);
5582
+ const distance = node.group ? groupConnectionDistance(pointer, node, c) : distanceToRect(pointer, bounds);
5346
5583
  if (distance > radius) continue;
5347
5584
  const isValid = isConnectionCandidateValid(options.source, node.id, null);
5348
5585
  if (!isValid) continue;
@@ -5423,9 +5660,7 @@ function createFlowEngine(store, initialOptions = {}) {
5423
5660
  if (!edge?.label) return null;
5424
5661
  const measured = c.measurements.get(edgeId);
5425
5662
  if (measured && !edge.label.autoSize) return measured;
5426
- const nodeMap = /* @__PURE__ */ new Map();
5427
- for (const n of c.graph.nodes) nodeMap.set(n.id, n);
5428
- return resolveEdgeLabelBounds(edge, nodeMap, measured);
5663
+ return resolveEdgeLabelBounds(edge, indexNodes(c.graph.nodes), measured);
5429
5664
  }
5430
5665
  function getBounds(id) {
5431
5666
  const c = ctx();
@@ -5527,9 +5762,8 @@ function createFlowEngine(store, initialOptions = {}) {
5527
5762
  height: maxY - minY
5528
5763
  };
5529
5764
  }
5530
- /** Collect snap target rects from non-selected nodes + resolved edge label bounds.
5531
- * Filters to entities at least partially in viewport and not overlapped by selection. */
5532
- function getSnapTargetRects(c, selection, selBounds) {
5765
+ /** Collect visible snap targets outside the moving selection subtree. */
5766
+ function getSnapTargetRects(c, selection) {
5533
5767
  const vp = c.viewport;
5534
5768
  const vs = c.viewportSize;
5535
5769
  const viewRect = {
@@ -5543,6 +5777,17 @@ function createFlowEngine(store, initialOptions = {}) {
5543
5777
  const selectedDerivedAncestorIds = /* @__PURE__ */ new Set();
5544
5778
  const visitedAncestorIds = /* @__PURE__ */ new Set();
5545
5779
  const nodeIndex = nodesById(c);
5780
+ const selectedSubtreeIds = new Set(selection);
5781
+ const childrenByParent = indexChildren(c.graph.nodes);
5782
+ const pendingDescendantIds = [...selection];
5783
+ while (pendingDescendantIds.length > 0) {
5784
+ const parentId = pendingDescendantIds.pop();
5785
+ for (const child of childrenByParent.get(parentId) ?? []) {
5786
+ if (selectedSubtreeIds.has(child.id)) continue;
5787
+ selectedSubtreeIds.add(child.id);
5788
+ pendingDescendantIds.push(child.id);
5789
+ }
5790
+ }
5546
5791
  for (const id of selection) {
5547
5792
  let parentId = nodeIndex.get(id)?.parentId;
5548
5793
  while (parentId && !visitedAncestorIds.has(parentId)) {
@@ -5555,15 +5800,17 @@ function createFlowEngine(store, initialOptions = {}) {
5555
5800
  }
5556
5801
  for (const n of c.graph.nodes) {
5557
5802
  nodeMap.set(n.id, n);
5558
- if (!selection.has(n.id) && !selectedDerivedAncestorIds.has(n.id) && !n.hidden) {
5803
+ if (!selectedSubtreeIds.has(n.id) && !selectedDerivedAncestorIds.has(n.id) && !n.hidden) {
5559
5804
  const b = hierarchyBounds(n, c);
5560
- if (rectsIntersect(b, viewRect) && (!selBounds || !rectContains(selBounds, b))) rects.push(b);
5805
+ if (rectsIntersect(b, viewRect)) rects.push(b);
5561
5806
  }
5562
5807
  }
5563
5808
  for (const edge of c.graph.edges) {
5564
5809
  if (selection.has(edge.id)) continue;
5810
+ const ownerId = edgeOwnerOf(edge, c);
5811
+ if (ownerId && selectedSubtreeIds.has(ownerId)) continue;
5565
5812
  const lb = resolveEdgeLabelBounds(edge, nodeMap, c.measurements.get(edge.id));
5566
- if (lb && rectsIntersect(lb, viewRect) && (!selBounds || !rectContains(selBounds, lb))) rects.push(lb);
5813
+ if (lb && rectsIntersect(lb, viewRect)) rects.push(lb);
5567
5814
  }
5568
5815
  return rects;
5569
5816
  }
@@ -5592,7 +5839,7 @@ function createFlowEngine(store, initialOptions = {}) {
5592
5839
  if ((nodesMoved || edgesMoved) && c.enableSnapLines) {
5593
5840
  const selBounds = getSelectionSnapBounds(c);
5594
5841
  if (selBounds) {
5595
- const snapResult = getSnapLines(selBounds, getSnapTargetRects(c, selection, selBounds), {
5842
+ const snapResult = getSnapLines(selBounds, getSnapTargetRects(c, selection), {
5596
5843
  threshold: c.snapThreshold / c.viewport.zoom,
5597
5844
  enableSpacing: c.enableSpacingGuides
5598
5845
  });
@@ -5860,7 +6107,7 @@ function createFlowEngine(store, initialOptions = {}) {
5860
6107
  computing.delete(edge.id);
5861
6108
  return null;
5862
6109
  }
5863
- const memoizableEdge = memoUsable && !engineOptions.edgeRouter && !isDerivedGroup(source) && !isDerivedGroup(target);
6110
+ const memoizableEdge = memoUsable && (!engineOptions.edgeRouter || engineOptions.edgeRouterDependencies === "endpoints") && !isDerivedGroup(source) && !isDerivedGroup(target);
5864
6111
  if (memoizableEdge) {
5865
6112
  const entry = edgePathMemo.get(edge.id);
5866
6113
  if (entry && entry.edge === edge && entry.source === source && entry.target === target) {
@@ -5967,6 +6214,93 @@ function createFlowEngine(store, initialOptions = {}) {
5967
6214
  };
5968
6215
  return value;
5969
6216
  }
6217
+ function spatialCells(rect) {
6218
+ const minX = Math.floor(rect.x / SPATIAL_CELL_SIZE);
6219
+ const minY = Math.floor(rect.y / SPATIAL_CELL_SIZE);
6220
+ const maxX = Math.floor((rect.x + Math.max(0, rect.width)) / SPATIAL_CELL_SIZE);
6221
+ const maxY = Math.floor((rect.y + Math.max(0, rect.height)) / SPATIAL_CELL_SIZE);
6222
+ if ((maxX - minX + 1) * (maxY - minY + 1) > MAX_ENTITY_SPATIAL_CELLS) return null;
6223
+ const cells = [];
6224
+ for (let y = minY; y <= maxY; y++) for (let x = minX; x <= maxX; x++) cells.push(`${x}:${y}`);
6225
+ return cells;
6226
+ }
6227
+ function addSpatialEntry(cells, globalIds, id, bounds) {
6228
+ const keys = spatialCells(bounds);
6229
+ if (!keys) {
6230
+ globalIds.push(id);
6231
+ return;
6232
+ }
6233
+ for (const key of keys) {
6234
+ const ids = cells.get(key);
6235
+ if (ids) ids.push(id);
6236
+ else cells.set(key, [id]);
6237
+ }
6238
+ }
6239
+ function edgeSpatialBounds(edge, path, c) {
6240
+ let bounds = path?.labelBounds ?? null;
6241
+ for (const segment of path?.segments ?? []) {
6242
+ const segmentBounds = pathBounds(segment);
6243
+ if (segmentBounds) bounds = bounds ? unionRect(bounds, segmentBounds) : segmentBounds;
6244
+ }
6245
+ if (bounds) return bounds;
6246
+ const source = getNode(edge.sourceId);
6247
+ const target = getNode(edge.targetId);
6248
+ if (!source || !target) return null;
6249
+ return unionRect(withLayoutOffset(resolvedBounds(source), source.id, c), withLayoutOffset(resolvedBounds(target), target.id, c));
6250
+ }
6251
+ /**
6252
+ * Viewport-query index keyed by geometry identities, never viewport. Building
6253
+ * is O(n + m); subsequent pan/zoom queries visit occupied viewport cells and
6254
+ * visible candidates instead of scanning the graph. Very large entities stay
6255
+ * in a small global list to cap cell fanout and retained memory.
6256
+ */
6257
+ function spatialIndexFor(c, order, paths) {
6258
+ const cached = renderableSpatialIndex;
6259
+ if (cached?.nodesInput === c.graph.nodes && cached.pathsInput === paths && cached.measurementsInput === c.measurements && cached.layoutOffsetsInput === c.layoutAnimation.offsets && cached.collapsedInput === c.collapsedNodeIds) return cached;
6260
+ const next = {
6261
+ nodesInput: c.graph.nodes,
6262
+ pathsInput: paths,
6263
+ measurementsInput: c.measurements,
6264
+ layoutOffsetsInput: c.layoutAnimation.offsets,
6265
+ collapsedInput: c.collapsedNodeIds,
6266
+ nodeCells: /* @__PURE__ */ new Map(),
6267
+ edgeCells: /* @__PURE__ */ new Map(),
6268
+ globalNodeIds: [],
6269
+ globalEdgeIds: [],
6270
+ nodeBounds: /* @__PURE__ */ new Map(),
6271
+ edgeBounds: /* @__PURE__ */ new Map()
6272
+ };
6273
+ for (const node of order.nodes) {
6274
+ const bounds = hierarchyBounds(node, c);
6275
+ next.nodeBounds.set(node.id, bounds);
6276
+ addSpatialEntry(next.nodeCells, next.globalNodeIds, node.id, bounds);
6277
+ }
6278
+ for (const edge of order.edges) {
6279
+ const bounds = edgeSpatialBounds(edge, paths.get(edge.id), c);
6280
+ if (!bounds) continue;
6281
+ next.edgeBounds.set(edge.id, bounds);
6282
+ addSpatialEntry(next.edgeCells, next.globalEdgeIds, edge.id, bounds);
6283
+ }
6284
+ renderableSpatialIndex = next;
6285
+ return next;
6286
+ }
6287
+ function spatialCandidates(cells, globalIds, rect) {
6288
+ const keys = spatialCells(rect);
6289
+ if (!keys) return null;
6290
+ const ids = new Set(globalIds);
6291
+ for (const key of keys) for (const id of cells.get(key) ?? []) ids.add(id);
6292
+ return ids;
6293
+ }
6294
+ function entityRanks(order) {
6295
+ if (entityRankCache?.order === order) return entityRankCache;
6296
+ const ranks = {
6297
+ order,
6298
+ nodes: new Map(order.nodes.map((node, index) => [node.id, index])),
6299
+ edges: new Map(order.edges.map((edge, index) => [edge.id, index]))
6300
+ };
6301
+ entityRankCache = ranks;
6302
+ return ranks;
6303
+ }
5970
6304
  function computeRenderableEntities(c, options) {
5971
6305
  const vp = c.viewport;
5972
6306
  const overscan = options.overscan ?? 0;
@@ -5979,6 +6313,26 @@ function createFlowEngine(store, initialOptions = {}) {
5979
6313
  };
5980
6314
  const cullMode = options.cull === "viewport" && rectContains(cullRect, graphBoundsFor(c)) ? "none" : options.cull;
5981
6315
  const order = getEntityOrderFor(c);
6316
+ if (cullMode === "viewport" && (c.canvasState === "idle" || c.canvasState === "panning")) {
6317
+ const spatial = spatialIndexFor(c, order, getAllEdgePaths());
6318
+ const nodeIds = spatialCandidates(spatial.nodeCells, spatial.globalNodeIds, cullRect);
6319
+ const edgeIds = spatialCandidates(spatial.edgeCells, spatial.globalEdgeIds, cullRect);
6320
+ if (nodeIds && edgeIds) {
6321
+ const ranks = entityRanks(order);
6322
+ return {
6323
+ nodes: [...nodeIds].sort((left, right) => (ranks.nodes.get(left) ?? 0) - (ranks.nodes.get(right) ?? 0)).flatMap((id) => {
6324
+ const node = getNode(id);
6325
+ const bounds = spatial.nodeBounds.get(id);
6326
+ return node && bounds && isNodeVisible(node, c, vp) && rectsIntersect(bounds, cullRect) ? [node] : [];
6327
+ }),
6328
+ edges: [...edgeIds].sort((left, right) => (ranks.edges.get(left) ?? 0) - (ranks.edges.get(right) ?? 0)).flatMap((id) => {
6329
+ const edge = getEdge(id);
6330
+ const bounds = spatial.edgeBounds.get(id);
6331
+ return edge && bounds && isEdgeVisible(edge, c.graph, c, vp) && rectsIntersect(bounds, cullRect) ? [edge] : [];
6332
+ })
6333
+ };
6334
+ }
6335
+ }
5982
6336
  const nodes = order.nodes.filter((n) => {
5983
6337
  if (!isNodeVisible(n, c, vp)) return false;
5984
6338
  if (cullMode === "viewport" && !rectsIntersect(hierarchyBounds(n, c), cullRect)) return false;
@@ -5990,10 +6344,13 @@ function createFlowEngine(store, initialOptions = {}) {
5990
6344
  edges: order.edges.filter((e) => {
5991
6345
  if (!isEdgeVisible(e, c.graph, c, vp)) return false;
5992
6346
  if (cullMode !== "viewport") return true;
6347
+ const path = edgePaths.get(e.id);
5993
6348
  if (e.label) {
5994
- if (rectsIntersect(getEdgeLabelBounds(e.id), cullRect)) return true;
6349
+ const labelRect = path?.labelBounds ?? getEdgeLabelBounds(e.id);
6350
+ if (!labelRect) return false;
6351
+ if (rectsIntersect(labelRect, cullRect)) return true;
5995
6352
  }
5996
- if (edgePaths.get(e.id)?.segments.some((segment) => {
6353
+ if (path?.segments.some((segment) => {
5997
6354
  const bounds = pathBounds(segment);
5998
6355
  return bounds !== null && rectsIntersect(bounds, cullRect);
5999
6356
  })) return true;
@@ -6007,40 +6364,99 @@ function createFlowEngine(store, initialOptions = {}) {
6007
6364
  if (kind === "node") return engineOptions.elevateOnSelect?.nodes ?? true;
6008
6365
  return engineOptions.elevateOnSelect?.edges ?? false;
6009
6366
  }
6010
- function getEntityOrderFor(c) {
6011
- const selectionInput = selectedBoostEnabled("node") || selectedBoostEnabled("edge") ? c.selection : null;
6012
- if (entityOrderCache?.nodesInput === c.graph.nodes && entityOrderCache.edgesInput === c.graph.edges && entityOrderCache.selectionInput === selectionInput && entityOrderCache.collapsedInput === c.collapsedNodeIds) return entityOrderCache.value;
6367
+ function getEntityOrderFor(c, options = {}) {
6368
+ const elevateSelected = options.elevateSelected ?? true;
6369
+ const selectionInput = elevateSelected && (selectedBoostEnabled("node") || selectedBoostEnabled("edge")) ? c.selection : null;
6370
+ const cache = elevateSelected ? entityOrderCache : baseEntityOrderCache;
6371
+ if (cache?.nodesInput === c.graph.nodes && cache.edgesInput === c.graph.edges && cache.selectionInput === selectionInput && cache.collapsedInput === c.collapsedNodeIds) return cache.value;
6013
6372
  const depths = nodeDepths(c.graph.nodes);
6014
- const nodeOrder = new Map(c.graph.nodes.map((node, index) => [node.id, index]));
6015
6373
  const foldedEdges = foldedEdgesFor(c).edges;
6016
- const edgeOrder = new Map([...c.graph.edges, ...foldedEdges].map((edge, index) => [edge.id, index]));
6374
+ const elevateNodes = elevateSelected && selectedBoostEnabled("node");
6375
+ const elevateEdges = elevateSelected && selectedBoostEnabled("edge");
6017
6376
  const value = {
6018
6377
  nodes: [...c.graph.nodes].sort((a, b) => {
6019
6378
  const depthDelta = (depths.get(a.id) ?? 0) - (depths.get(b.id) ?? 0);
6020
6379
  if (depthDelta !== 0) return depthDelta;
6021
6380
  const zDelta = (a.zIndex ?? 0) - (b.zIndex ?? 0);
6022
6381
  if (zDelta !== 0) return zDelta;
6023
- const selectedDelta = Number(selectedBoostEnabled("node") && c.selection.has(a.id)) - Number(selectedBoostEnabled("node") && c.selection.has(b.id));
6382
+ const selectedDelta = Number(elevateNodes && c.selection.has(a.id)) - Number(elevateNodes && c.selection.has(b.id));
6024
6383
  if (selectedDelta !== 0) return selectedDelta;
6025
- return (nodeOrder.get(a.id) ?? 0) - (nodeOrder.get(b.id) ?? 0);
6384
+ return 0;
6026
6385
  }),
6027
6386
  edges: [...c.graph.edges, ...foldedEdges].sort((a, b) => {
6028
6387
  const depthDelta = Math.max(depths.get(a.sourceId) ?? 0, depths.get(a.targetId) ?? 0) - Math.max(depths.get(b.sourceId) ?? 0, depths.get(b.targetId) ?? 0);
6029
6388
  if (depthDelta !== 0) return depthDelta;
6030
6389
  const zDelta = (a.zIndex ?? 0) - (b.zIndex ?? 0);
6031
6390
  if (zDelta !== 0) return zDelta;
6032
- const selectedDelta = Number(selectedBoostEnabled("edge") && c.selection.has(a.id)) - Number(selectedBoostEnabled("edge") && c.selection.has(b.id));
6391
+ const selectedDelta = Number(elevateEdges && c.selection.has(a.id)) - Number(elevateEdges && c.selection.has(b.id));
6033
6392
  if (selectedDelta !== 0) return selectedDelta;
6034
- return (edgeOrder.get(a.id) ?? 0) - (edgeOrder.get(b.id) ?? 0);
6393
+ return 0;
6035
6394
  })
6036
6395
  };
6037
- entityOrderCache = {
6396
+ const nextCache = {
6038
6397
  nodesInput: c.graph.nodes,
6039
6398
  edgesInput: c.graph.edges,
6040
6399
  selectionInput,
6041
6400
  collapsedInput: c.collapsedNodeIds,
6042
6401
  value
6043
6402
  };
6403
+ if (elevateSelected) entityOrderCache = nextCache;
6404
+ else baseEntityOrderCache = nextCache;
6405
+ return value;
6406
+ }
6407
+ function getPaintZIndicesFor(c, options = {}) {
6408
+ const elevateSelected = options.elevateSelected ?? true;
6409
+ const cacheKey = `${optionsVersion}:${elevateSelected}`;
6410
+ const snapshotCache = paintZIndicesCache.get(c);
6411
+ const cached = snapshotCache?.get(cacheKey);
6412
+ if (cached) return cached;
6413
+ const baseOrder = getEntityOrderFor(c, { elevateSelected: false });
6414
+ const depths = nodeDepths(c.graph.nodes);
6415
+ const visibleNodes = baseOrder.nodes.filter((node) => isNodeVisible(node, c));
6416
+ const visibleEdges = baseOrder.edges.filter((edge) => isEdgeVisible(edge, c.graph, c));
6417
+ const nodes = /* @__PURE__ */ new Map();
6418
+ const edges = /* @__PURE__ */ new Map();
6419
+ for (let start = 0; start < visibleNodes.length;) {
6420
+ const first = visibleNodes[start];
6421
+ const depth = depths.get(first.id) ?? 0;
6422
+ const zIndex = first.zIndex ?? 0;
6423
+ let end = start + 1;
6424
+ while (end < visibleNodes.length) {
6425
+ const node = visibleNodes[end];
6426
+ if ((depths.get(node.id) ?? 0) !== depth || (node.zIndex ?? 0) !== zIndex) break;
6427
+ end++;
6428
+ }
6429
+ const elevatedZIndex = 2 * (end - 1) + 1;
6430
+ for (let index = start; index < end; index++) {
6431
+ const node = visibleNodes[index];
6432
+ nodes.set(node.id, elevateSelected && selectedBoostEnabled("node") && c.selection.has(node.id) ? elevatedZIndex : 2 * index);
6433
+ }
6434
+ start = end;
6435
+ }
6436
+ for (let start = 0; start < visibleEdges.length;) {
6437
+ const first = visibleEdges[start];
6438
+ const depth = Math.max(depths.get(first.sourceId) ?? 0, depths.get(first.targetId) ?? 0);
6439
+ const zIndex = first.zIndex ?? 0;
6440
+ let end = start + 1;
6441
+ while (end < visibleEdges.length) {
6442
+ const edge = visibleEdges[end];
6443
+ if (Math.max(depths.get(edge.sourceId) ?? 0, depths.get(edge.targetId) ?? 0) !== depth || (edge.zIndex ?? 0) !== zIndex) break;
6444
+ end++;
6445
+ }
6446
+ const elevatedZIndex = 2 * (end - 1) + 1;
6447
+ for (let index = start; index < end; index++) {
6448
+ const edge = visibleEdges[index];
6449
+ edges.set(edge.id, elevateSelected && selectedBoostEnabled("edge") && c.selection.has(edge.id) ? elevatedZIndex : 2 * index);
6450
+ }
6451
+ start = end;
6452
+ }
6453
+ const value = {
6454
+ nodes,
6455
+ edges
6456
+ };
6457
+ const nextSnapshotCache = snapshotCache ?? /* @__PURE__ */ new Map();
6458
+ nextSnapshotCache.set(cacheKey, value);
6459
+ if (!snapshotCache) paintZIndicesCache.set(c, nextSnapshotCache);
6044
6460
  return value;
6045
6461
  }
6046
6462
  function getPublicVisualBounds(nodeOrId) {
@@ -6227,7 +6643,7 @@ function createFlowEngine(store, initialOptions = {}) {
6227
6643
  const ids = [];
6228
6644
  for (const n of graph.nodes) {
6229
6645
  if (!isNodeVisible(n, c)) continue;
6230
- if (rectsIntersect(rect, visualBounds(n, getVisualSnapOffset()))) ids.push(n.id);
6646
+ if (rectsIntersect(rect, n.selectionBounds ? resolvedSelectionBounds(n) : visualBounds(n, getVisualSnapOffset()))) ids.push(n.id);
6231
6647
  }
6232
6648
  for (const e of graph.edges) {
6233
6649
  if (!isEdgeVisible(e, graph, c)) continue;
@@ -6279,16 +6695,26 @@ function createFlowEngine(store, initialOptions = {}) {
6279
6695
  validateConnection,
6280
6696
  validateConnectionDetailed,
6281
6697
  resolveEntityConfig,
6282
- getVisibleEntities: () => {
6698
+ getVisibleEntities: (options = {}) => {
6283
6699
  const c = ctx();
6284
- const order = getEntityOrderFor(c);
6700
+ const order = getEntityOrderFor(c, options);
6285
6701
  return {
6286
6702
  nodes: order.nodes.filter((n) => isNodeVisible(n, c)),
6287
6703
  edges: order.edges.filter((e) => isEdgeVisible(e, c.graph, c))
6288
6704
  };
6289
6705
  },
6290
6706
  /** Deterministic paint order. Later items should paint above earlier ones. */
6291
- getEntityOrder: () => getEntityOrderFor(ctx()),
6707
+ getEntityOrder: (options = {}) => getEntityOrderFor(ctx(), options),
6708
+ /**
6709
+ * CSS z-indices for the visible entity set. Base values are spaced by 2.
6710
+ * When `elevateOnSelect` allows an entity kind, a selected entity is
6711
+ * raised just above its own depth/zIndex band while remaining below the
6712
+ * next band, so a selected parent never paints over its descendants.
6713
+ * Multiple selected entities in one band tie; the renderer's DOM order
6714
+ * resolves the tie and matches core's elevated order. The result is
6715
+ * memoized per store snapshot so callers can compare it by identity.
6716
+ */
6717
+ getPaintZIndices: (options = {}) => getPaintZIndicesFor(ctx(), options),
6292
6718
  /**
6293
6719
  * Renderable (visible, optionally viewport-culled) entities. Memoized per
6294
6720
  * (store snapshot, cull/overscan) so several render layers can share one
@@ -6338,7 +6764,7 @@ function createFlowEngine(store, initialOptions = {}) {
6338
6764
  if (!nodesMoved && !edgesMoved) return null;
6339
6765
  const selBounds = getSelectionSnapBounds(c);
6340
6766
  if (!selBounds) return null;
6341
- const otherRects = getSnapTargetRects(c, c.selection, selBounds);
6767
+ const otherRects = getSnapTargetRects(c, c.selection);
6342
6768
  if (otherRects.length === 0) return null;
6343
6769
  return getSnapLines(selBounds, otherRects, {
6344
6770
  threshold: c.snapThreshold / c.viewport.zoom,
@@ -7679,7 +8105,19 @@ function createFlow(options = {}) {
7679
8105
  const ids = fitOptions?.nodes?.map((node) => typeof node === "string" ? node : node.id);
7680
8106
  const idSet = ids && ids.length > 0 ? new Set(ids) : null;
7681
8107
  const visible = getViewEntities({ includeHidden: fitOptions?.includeHidden });
7682
- const bounds = getGraphBounds(visible.nodes.filter((node) => !idSet || idSet.has(node.id)), visible.edges.filter((edge) => !idSet || idSet.has(edge.id)), context.measurements);
8108
+ const nodes = visible.nodes.filter((node) => !idSet || idSet.has(node.id));
8109
+ const edges = visible.edges.filter((edge) => !idSet || idSet.has(edge.id));
8110
+ const bounds = getGraphBounds(nodes.map((node) => {
8111
+ const visual = engine.visualBounds(node.id);
8112
+ return visual ? {
8113
+ ...node,
8114
+ ...visual,
8115
+ dx: 0,
8116
+ dy: 0,
8117
+ autoSize: false,
8118
+ style: void 0
8119
+ } : node;
8120
+ }), edges, context.measurements);
7683
8121
  if (bounds.width === 0 && bounds.height === 0) return null;
7684
8122
  const { nodes: _nodes, includeHidden: _includeHidden, ...viewportOptions } = fitOptions ?? {};
7685
8123
  return viewportForBounds(bounds, context.viewportSize, {
@@ -9108,6 +9546,7 @@ function entityPressMode(options = {}) {
9108
9546
  modifiers: event.modifiers
9109
9547
  })] };
9110
9548
  if (event.button !== 0) return null;
9549
+ if (event.target.part === "connection-boundary") return null;
9111
9550
  const entity = engine.getEntity(id);
9112
9551
  if (!entity) return null;
9113
9552
  const config = engine.resolveEntityConfig(entity);
@@ -9585,7 +10024,7 @@ function edgeEndpointFromPart(part) {
9585
10024
  if (part === "edge-endpoint:target") return "target";
9586
10025
  return null;
9587
10026
  }
9588
- function reconnectTarget(target, ctx) {
10027
+ function reconnectTarget(target, ctx, point) {
9589
10028
  if (target.kind === "port") return {
9590
10029
  nodeId: target.nodeId,
9591
10030
  port: target.portName
@@ -9594,10 +10033,17 @@ function reconnectTarget(target, ctx) {
9594
10033
  nodeId: target.id,
9595
10034
  port: null
9596
10035
  };
10036
+ if (point) {
10037
+ const candidate = ctx.engine.getConnectionCandidate(point);
10038
+ if (candidate) return {
10039
+ nodeId: candidate.nodeId,
10040
+ port: candidate.portName
10041
+ };
10042
+ }
9597
10043
  return null;
9598
10044
  }
9599
10045
  function defaultReconnectValidity(args, ctx) {
9600
- const candidate = reconnectTarget(args.target, ctx);
10046
+ const candidate = reconnectTarget(args.target, ctx, args.point);
9601
10047
  if (!candidate) return false;
9602
10048
  if (args.end === "source") return ctx.engine.validateConnection({
9603
10049
  sourceId: candidate.nodeId,
@@ -9655,7 +10101,7 @@ function reconnectSession(reconnect, options) {
9655
10101
  let active = reconnect.threshold === 0;
9656
10102
  function moveCommands(event, ctx, activate = false) {
9657
10103
  const edge = ctx.engine.getEdge(reconnect.edgeId);
9658
- const candidate = reconnectTarget(event.target, ctx);
10104
+ const candidate = reconnectTarget(event.target, ctx, event.point);
9659
10105
  const valid = !!edge && isValid({
9660
10106
  edge,
9661
10107
  end: reconnect.end,
@@ -9696,6 +10142,10 @@ function reconnectSession(reconnect, options) {
9696
10142
  const result = moveCommands(event, ctx);
9697
10143
  const commands = [...result.commands];
9698
10144
  if (result.candidate && result.valid) {
10145
+ const endTarget = connectEndTargetFor(targetFromConnectionCandidate({
10146
+ nodeId: result.candidate.nodeId,
10147
+ portName: result.candidate.port
10148
+ }), event.point, ctx);
9699
10149
  if (options.commit !== false) commands.push(trigger("reconnectEdge", {
9700
10150
  edgeId: reconnect.edgeId,
9701
10151
  ...reconnect.end === "source" ? {
@@ -9708,7 +10158,7 @@ function reconnectSession(reconnect, options) {
9708
10158
  transactionId: reconnect.transactionId
9709
10159
  }));
9710
10160
  commands.push(trigger("connectionEnd", {
9711
- target: connectEndTargetFor(event.target, event.point, ctx),
10161
+ target: endTarget,
9712
10162
  reconnectedEdgeId: reconnect.edgeId
9713
10163
  }));
9714
10164
  } else commands.push(trigger("connectionEnd", {
@@ -10188,31 +10638,13 @@ function getAutoPanDelta(context, screenPoint, engine) {
10188
10638
  }
10189
10639
  //#endregion
10190
10640
  //#region src/entity-changes.ts
10191
- const adjacencyCache = /* @__PURE__ */ new WeakMap();
10192
10641
  function adjacency(edges) {
10193
- let index = adjacencyCache.get(edges);
10194
- if (!index) {
10195
- index = /* @__PURE__ */ new Map();
10196
- for (const edge of edges) {
10197
- let source = index.get(edge.sourceId);
10198
- if (!source) index.set(edge.sourceId, source = []);
10199
- source.push(edge.id);
10200
- if (edge.targetId !== edge.sourceId) {
10201
- let target = index.get(edge.targetId);
10202
- if (!target) index.set(edge.targetId, target = []);
10203
- target.push(edge.id);
10204
- }
10205
- }
10206
- adjacencyCache.set(edges, index);
10207
- }
10208
- return index;
10642
+ return indexEdgeAdjacency(edges).byNode;
10209
10643
  }
10210
- function computeDirty(prev, next, options) {
10211
- if (next.canvasState !== prev.canvasState) return "all";
10644
+ function computeDirty(prev, next, options, dragDirtyIds) {
10212
10645
  if (next.mode !== prev.mode) return "all";
10213
10646
  if (next.configRevision !== prev.configRevision) return "all";
10214
10647
  if (next.collapsedNodeIds !== prev.collapsedNodeIds) return "all";
10215
- if (next.enableSnapLines && next.canvasState === "dragging") return "all";
10216
10648
  const dirty = /* @__PURE__ */ new Set();
10217
10649
  const markEdge = (edgeId) => {
10218
10650
  dirty.add(edgeId);
@@ -10220,7 +10652,7 @@ function computeDirty(prev, next, options) {
10220
10652
  };
10221
10653
  const markIncidentEdges = (nodeId, edges) => {
10222
10654
  const incident = adjacency(edges).get(nodeId);
10223
- if (incident) for (const edgeId of incident) markEdge(edgeId);
10655
+ if (incident) for (const edge of incident) markEdge(edge.id);
10224
10656
  };
10225
10657
  const markAncestors = (node) => {
10226
10658
  const nextIndex = indexNodes(next.graph.nodes);
@@ -10233,6 +10665,21 @@ function computeDirty(prev, next, options) {
10233
10665
  parentId = nextIndex.get(parentId)?.parentId ?? null;
10234
10666
  }
10235
10667
  };
10668
+ if (next.dragRevision !== prev.dragRevision && dragDirtyIds) return new Set(dragDirtyIds);
10669
+ if (next.canvasState !== prev.canvasState && (next.canvasState === "dragging" || prev.canvasState === "dragging")) if (prev.canvasState === "dragging" && dragDirtyIds) for (const id of dragDirtyIds) dirty.add(id);
10670
+ else for (const id of /* @__PURE__ */ new Set([...prev.selection, ...next.selection])) dirty.add(id);
10671
+ if (next.enableSnapLines && next.canvasState === "dragging") {
10672
+ const nodes = indexNodes(next.graph.nodes);
10673
+ const edges = indexEdges(next.graph.edges);
10674
+ for (const id of next.selection) {
10675
+ dirty.add(id);
10676
+ const node = nodes.get(id);
10677
+ if (node) {
10678
+ markIncidentEdges(id, next.graph.edges);
10679
+ markAncestors(node);
10680
+ } else if (edges.has(id)) markEdge(id);
10681
+ }
10682
+ }
10236
10683
  if (next.layoutAnimation.offsets !== prev.layoutAnimation.offsets) {
10237
10684
  const prevNodes = indexNodes(prev.graph.nodes);
10238
10685
  const nextNodes = indexNodes(next.graph.nodes);
@@ -10332,13 +10779,61 @@ function computeDirty(prev, next, options) {
10332
10779
  }
10333
10780
  return dirty;
10334
10781
  }
10782
+ function dirtyIdsForDrag(context, options) {
10783
+ const dirty = /* @__PURE__ */ new Set();
10784
+ const nodes = indexNodes(context.graph.nodes);
10785
+ const edges = indexEdges(context.graph.edges);
10786
+ const children = indexChildren(context.graph.nodes);
10787
+ const markEdge = (id) => {
10788
+ dirty.add(id);
10789
+ for (const dependentId of options.getEdgeDependents?.(id) ?? []) dirty.add(dependentId);
10790
+ };
10791
+ const markIncident = (id) => {
10792
+ for (const edge of adjacency(context.graph.edges).get(id) ?? []) markEdge(edge.id);
10793
+ };
10794
+ const markAncestors = (id) => {
10795
+ const seen = /* @__PURE__ */ new Set();
10796
+ let parentId = nodes.get(id)?.parentId ?? null;
10797
+ while (parentId && !seen.has(parentId)) {
10798
+ seen.add(parentId);
10799
+ dirty.add(parentId);
10800
+ markIncident(parentId);
10801
+ parentId = nodes.get(parentId)?.parentId ?? null;
10802
+ }
10803
+ };
10804
+ const markNodeSubtree = (id, seen = /* @__PURE__ */ new Set()) => {
10805
+ if (seen.has(id)) return;
10806
+ seen.add(id);
10807
+ dirty.add(id);
10808
+ markIncident(id);
10809
+ markAncestors(id);
10810
+ for (const child of children.get(id) ?? []) markNodeSubtree(child.id, seen);
10811
+ };
10812
+ for (const id of context.selection) if (nodes.has(id)) markNodeSubtree(id);
10813
+ else {
10814
+ const edge = edges.get(id);
10815
+ if (!edge) continue;
10816
+ markEdge(id);
10817
+ const source = nodes.get(edge.sourceId);
10818
+ const target = nodes.get(edge.targetId);
10819
+ if (source?.group) dirty.add(source.id);
10820
+ if (target?.group) dirty.add(target.id);
10821
+ markAncestors(edge.sourceId);
10822
+ markAncestors(edge.targetId);
10823
+ }
10824
+ return dirty;
10825
+ }
10335
10826
  function createEntityChangeNotifier(store, options = {}) {
10336
10827
  const listeners = /* @__PURE__ */ new Map();
10337
10828
  let prev = store.getSnapshot().context;
10829
+ let activeDragDirtyIds;
10338
10830
  const subscription = store.subscribe((snapshot) => {
10339
10831
  const next = snapshot.context;
10340
10832
  if (next === prev) return;
10341
- const dirty = computeDirty(prev, next, options);
10833
+ if (next.canvasState === "dragging" && (prev.canvasState !== "dragging" || next.selection !== prev.selection)) activeDragDirtyIds = dirtyIdsForDrag(next, options);
10834
+ const dirty = computeDirty(prev, next, options, activeDragDirtyIds);
10835
+ if (next.canvasState === "dragging" && next.dragRevision === prev.dragRevision && (next.graph.nodes !== prev.graph.nodes || next.graph.edges !== prev.graph.edges)) activeDragDirtyIds = dirtyIdsForDrag(next, options);
10836
+ else if (next.canvasState !== "dragging") activeDragDirtyIds = void 0;
10342
10837
  prev = next;
10343
10838
  if (dirty === "all") {
10344
10839
  for (const set of listeners.values()) for (const listener of [...set]) listener();
@@ -10369,4 +10864,4 @@ function createEntityChangeNotifier(store, options = {}) {
10369
10864
  };
10370
10865
  }
10371
10866
  //#endregion
10372
- export { CONNECTION_PREVIEW_EDGE_ID, CONNECTION_PREVIEW_NODE_ID, FlowGraphValidationError, animateViewport, applyFlowPatches, areNodesMeasured, avoidRouter, bestDirection, bezierRouter, boxSelectMode, boxToRect, calcAutoPan, canvasToScreen, clampZoom, cloneJsonSafe, composeGraphProjectionAttrs, configureAvoidRouter, configureBezierRouter, configureStepRouter, connectMode, constrainViewport, createConnectionPreviewGraph, createEdge, createEntityChangeNotifier, createFlow, createFlowChangeSet, createFlowEngine, createFlowInputRuntime, createFlowStore, createGraph, createNode, createPort, createViewport, defaultConfig, defaultFlowProfile, defaultInputModes, defaultInputModesForKeymap, defaultKeymap, defaultModesForContext, defineFlowProfile, deriveFlowView, deriveGroupGeometry, entityPressMode, extractFlowContent, fitFrameAroundExclusions, fixedGroupGeometry, fromJSON, getAnchorTransform, getAutoPanDelta, getConnectedEdges, getEdgeOwner, getGraphBounds, getIncomers, getMinimapProjection, getNeighbors, getOutgoers, getProjectedEdgeAttrs, getProjectedNodeAttrs, getSelectionBounds, getShape, getShapeOrDefault, getSnapLines, getToolbarPlacement, getVisibleBounds, hoverMode, indexChildren, indexEdgeAdjacency, indexEdges, indexNodes, insertFlowContent, isDerivedGroup, isGroup, isTrackpadPinch, keyboardMode, keyboardNavMode, markerToSVG, matchesKeyBinding, mergeGraphEdgeAttrs, mergeGraphNodeAttrs, nodeDepths, normalizeWheelPan, panBy, panMode, panePressMode, parseFlowSerialized, pathToSVG, pinchMode, portPressMode, preventDefault, profileModesForContext, profilePoliciesForContext, readonlyConfig, readonlyInputModes, readonlyInputModesForKeymap, reconnectMode, rectContains, rectsIntersect, registerShape, resolveBehavior, resolveGroupPadding, resolveKeymap, resolvedBounds, resolvedEdgeLabelBounds, resolvedEdgeLabelSize, resolvedPosition, screenToCanvas, selectMode, serializeFlowGraph, snapPointToGrid, snapToGrid, snappedBounds, sortActiveGraphProjections, stepRouter, straightRouter, toSVGTransform, toViewBox, trigger, unionRect, validateAndCloneGraph, validateFitFrame, validateViewport, viewportCenteredOn, viewportForBounds, visualBounds, visualPosition, wheelInteraction, wheelMode, wheelZoomDelta, zoomTo };
10867
+ export { CONNECTION_PREVIEW_EDGE_ID, CONNECTION_PREVIEW_NODE_ID, FlowGraphValidationError, animateViewport, applyFlowPatches, areNodesMeasured, avoidRouter, bestDirection, bezierRouter, boxSelectMode, boxToRect, calcAutoPan, canvasToScreen, clampZoom, cloneJsonSafe, composeGraphProjectionAttrs, configureAvoidRouter, configureBezierRouter, configureStepRouter, connectMode, constrainViewport, createConnectionPreviewGraph, createEdge, createEntityChangeNotifier, createFlow, createFlowChangeSet, createFlowEngine, createFlowInputRuntime, createFlowStore, createGraph, createNode, createPort, createViewport, defaultConfig, defaultFlowProfile, defaultInputModes, defaultInputModesForKeymap, defaultKeymap, defaultModesForContext, defineFlowProfile, deriveFlowView, deriveGroupGeometry, entityPressMode, extractFlowContent, fitFrameAroundExclusions, fixedGroupGeometry, fromJSON, getAnchorTransform, getAutoPanDelta, getConnectedEdges, getEdgeOwner, getGraphBounds, getIncomers, getMinimapProjection, getNeighbors, getOutgoers, getProjectedEdgeAttrs, getProjectedNodeAttrs, getSelectionBounds, getShape, getShapeOrDefault, getSnapLines, getToolbarPlacement, getVisibleBounds, hoverMode, indexChildren, indexEdgeAdjacency, indexEdges, indexNodes, insertFlowContent, isDerivedGroup, isGroup, isTrackpadPinch, keyboardMode, keyboardNavMode, markerToSVG, matchesKeyBinding, mergeGraphEdgeAttrs, mergeGraphNodeAttrs, nodeDepths, normalizeWheelPan, panBy, panMode, panePressMode, parseFlowSerialized, pathToSVG, pinchMode, portPressMode, preventDefault, profileModesForContext, profilePoliciesForContext, readonlyConfig, readonlyInputModes, readonlyInputModesForKeymap, reconnectMode, rectContains, rectsIntersect, registerShape, resolveBehavior, resolveGroupPadding, resolveKeymap, resolvedBounds, resolvedEdgeLabelBounds, resolvedEdgeLabelSize, resolvedPosition, resolvedSelectionBounds, screenToCanvas, selectMode, serializeFlowGraph, snapPointToGrid, snapToGrid, snappedBounds, sortActiveGraphProjections, stepRouter, straightRouter, toSVGTransform, toViewBox, trigger, unionRect, validateAndCloneGraph, validateFitFrame, validateViewport, viewportCenteredOn, viewportForBounds, visualBounds, visualPosition, wheelInteraction, wheelMode, wheelZoomDelta, zoomTo };