@statelyai/flow 0.12.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -147,6 +147,9 @@ function toDecorationArray(value) {
147
147
  return Array.isArray(value) ? [...value] : [value];
148
148
  }
149
149
  //#endregion
150
+ //#region src/connection-lifetime.ts
151
+ const connectionLifetime = Symbol("flow.connectionLifetime");
152
+ //#endregion
150
153
  //#region src/appearances.ts
151
154
  const appearanceSides = [
152
155
  "top",
@@ -2697,6 +2700,13 @@ function reparentProblem(graph, nodeId, parentId) {
2697
2700
  }
2698
2701
  /** Drop hover/highlight/collapse references to entities that no longer exist. */
2699
2702
  function pruneVisualState(draft, deletedIds) {
2703
+ const connection = draft.connection;
2704
+ const pending = draft.connectionClickStartHandle;
2705
+ if (connection && deletedIds.some((id) => id === connection.sourceId || connection.sourcePort !== null && id === `${connection.sourceId}:${connection.sourcePort}` || id === connection.targetId || connection.targetId !== null && connection.targetPort !== null && id === `${connection.targetId}:${connection.targetPort}` || id === connection.reconnectingEdgeId) || pending && deletedIds.some((id) => id === pending.nodeId || pending.port !== null && id === `${pending.nodeId}:${pending.port}`)) {
2706
+ draft.connection = null;
2707
+ draft.connectionClickStartHandle = null;
2708
+ if (draft.canvasState === "connecting") draft.canvasState = "idle";
2709
+ }
2700
2710
  for (const id of deletedIds) {
2701
2711
  draft.hoveredEntityIds.delete(id);
2702
2712
  draft.collapsedNodeIds.delete(id);
@@ -2723,6 +2733,7 @@ function pruneDeletedAddressables(draft, deletedIds) {
2723
2733
  for (const id of deleted) {
2724
2734
  draft.selection.delete(id);
2725
2735
  draft.measurements.delete(id);
2736
+ draft.derivedPortMeasurements.delete(id);
2726
2737
  }
2727
2738
  if (draft.focusedEntityId && deleted.has(draft.focusedEntityId)) draft.focusedEntityId = null;
2728
2739
  pruneVisualState(draft, deletedIds);
@@ -3026,6 +3037,7 @@ function graphWithoutTransientOffsets(graph) {
3026
3037
  function restoreHistoryContext(currentContext, historicalContext) {
3027
3038
  const graph = graphWithoutTransientOffsets(historicalContext.graph);
3028
3039
  const entityIds = /* @__PURE__ */ new Set([...graph.nodes.map((node) => node.id), ...graph.edges.map((edge) => edge.id)]);
3040
+ const addressableIds = graphAddressableIds(graph);
3029
3041
  const filterIds = (ids) => new Set([...ids].filter((id) => entityIds.has(id)));
3030
3042
  const collapsedNodeIds = filterIds(historicalContext.collapsedNodeIds);
3031
3043
  const selection = filterIds(currentContext.selection);
@@ -3045,6 +3057,7 @@ function restoreHistoryContext(currentContext, historicalContext) {
3045
3057
  highlights,
3046
3058
  focusedEntityId: currentContext.focusedEntityId && entityIds.has(currentContext.focusedEntityId) ? currentContext.focusedEntityId : null,
3047
3059
  measurements: new Map([...currentContext.measurements].filter(([id]) => entityIds.has(id))),
3060
+ derivedPortMeasurements: new Map([...currentContext.derivedPortMeasurements].filter(([id]) => addressableIds.has(id))),
3048
3061
  layoutAnimation: {
3049
3062
  status: "idle",
3050
3063
  offsets: /* @__PURE__ */ new Map()
@@ -3319,6 +3332,7 @@ function createFlowStore(initialGraph = {
3319
3332
  highlights: /* @__PURE__ */ new Map(),
3320
3333
  focusedEntityId: null,
3321
3334
  measurements: /* @__PURE__ */ new Map(),
3335
+ derivedPortMeasurements: /* @__PURE__ */ new Map(),
3322
3336
  canvasState: "idle",
3323
3337
  draggedEntityId: null,
3324
3338
  dragRevision: 0,
@@ -3435,6 +3449,16 @@ function createFlowStore(initialGraph = {
3435
3449
  return;
3436
3450
  }
3437
3451
  draft.graph.nodes[index] = { ...next };
3452
+ const nextPortIds = new Set(portAddressableIds(next));
3453
+ const removedPortIds = portAddressableIds(previous).filter((id) => !nextPortIds.has(id));
3454
+ if (removedPortIds.length > 0) {
3455
+ const previousSelection = new Set(draft.selection);
3456
+ pruneDeletedAddressables(draft, removedPortIds);
3457
+ if (!setsEqual(previousSelection, draft.selection)) enqueue.emit.selectionChanged({
3458
+ selection: new Set(draft.selection),
3459
+ event: createEventObject("updateNode", event)
3460
+ });
3461
+ }
3438
3462
  if (JSON.stringify(previous.appearance) !== JSON.stringify(next.appearance)) {
3439
3463
  draft.measurements.delete(appearanceMeasurementId(previous.id, resolveAppearance(previous, ctx.appearances)));
3440
3464
  const node = draft.graph.nodes[index];
@@ -3580,7 +3604,10 @@ function createFlowStore(initialGraph = {
3580
3604
  invalidatePathsForNodeGeometry(draft, deletedNodeIdSet, [...nodesBefore.values()]);
3581
3605
  draft.selection.clear();
3582
3606
  draft.focusedEntityId = null;
3583
- for (const id of [...deletedIds, ...deletedPortIds]) draft.measurements.delete(id);
3607
+ for (const id of [...deletedIds, ...deletedPortIds]) {
3608
+ draft.measurements.delete(id);
3609
+ draft.derivedPortMeasurements.delete(id);
3610
+ }
3584
3611
  pruneVisualState(draft, [...deletedIds, ...deletedPortIds]);
3585
3612
  enqueue.emit.entitiesDeleted({
3586
3613
  ids: deletedIds,
@@ -3615,10 +3642,12 @@ function createFlowStore(initialGraph = {
3615
3642
  draft.canvasState = "idle";
3616
3643
  draft.draggedEntityId = null;
3617
3644
  draft.connection = null;
3645
+ draft.connectionClickStartHandle = null;
3618
3646
  draft.selectionBox = null;
3619
3647
  draft.selectionBoxBase = null;
3620
3648
  draft.collapsedNodeIds = /* @__PURE__ */ new Set();
3621
3649
  draft.measurements.clear();
3650
+ draft.derivedPortMeasurements.clear();
3622
3651
  enqueue.emit.graphChanged({
3623
3652
  graph: snapshotGraph(draft.graph),
3624
3653
  event: createEventObject("setGraph", event)
@@ -3629,7 +3658,21 @@ function createFlowStore(initialGraph = {
3629
3658
  });
3630
3659
  });
3631
3660
  },
3632
- replaceGraph: (ctx, event, enqueue) => event.graphChanged === false && event.retention !== "reset" && !event.layoutAnimationOffsets ? ctx : produce(ctx, (draft) => {
3661
+ replaceGraph: (ctx, event, enqueue) => event.graphChanged === false && event.retention !== "reset" && !event.layoutAnimationOffsets && !event.resetMeasurementIds?.length ? ctx : produce(ctx, (draft) => {
3662
+ for (const id of event.resetMeasurementIds ?? []) {
3663
+ for (const key of draft.measurements.keys()) if (key === id || key.startsWith(`${id}:`)) {
3664
+ draft.measurements.delete(key);
3665
+ draft.derivedPortMeasurements.delete(key);
3666
+ }
3667
+ const previous = ctx.graph.nodes.find((node) => node.id === id);
3668
+ if (previous) {
3669
+ for (const key of portAddressableIds(previous)) {
3670
+ draft.measurements.delete(key);
3671
+ draft.derivedPortMeasurements.delete(key);
3672
+ }
3673
+ draft.measurements.delete(appearanceMeasurementId(id, resolveAppearance(previous, ctx.appearances)));
3674
+ }
3675
+ }
3633
3676
  const previousSelection = new Set(draft.selection);
3634
3677
  const previousNodes = new Map(ctx.graph.nodes.map((node) => [node.id, node]));
3635
3678
  const changedAppearances = /* @__PURE__ */ new Set();
@@ -3679,6 +3722,7 @@ function createFlowStore(initialGraph = {
3679
3722
  draft.resizeCorners = null;
3680
3723
  draft.collapsedNodeIds.clear();
3681
3724
  draft.measurements.clear();
3725
+ draft.derivedPortMeasurements.clear();
3682
3726
  } else {
3683
3727
  draft.selection = new Set([...draft.selection].filter((id) => ids.has(id)));
3684
3728
  draft.hoveredEntityIds = new Set([...draft.hoveredEntityIds].filter((id) => ids.has(id)));
@@ -3699,7 +3743,10 @@ function createFlowStore(initialGraph = {
3699
3743
  }
3700
3744
  }
3701
3745
  for (const edge of draft.graph.edges) if (edge.label) measurementIds.add(appearanceMeasurementId(edge.id, resolveAppearance(edge.label, ctx.appearances)));
3702
- for (const id of draft.measurements.keys()) if (!measurementIds.has(id)) draft.measurements.delete(id);
3746
+ for (const id of draft.measurements.keys()) if (!measurementIds.has(id)) {
3747
+ draft.measurements.delete(id);
3748
+ draft.derivedPortMeasurements.delete(id);
3749
+ }
3703
3750
  if (draft.draggedEntityId && !ids.has(draft.draggedEntityId)) {
3704
3751
  draft.draggedEntityId = null;
3705
3752
  if (draft.canvasState === "dragging") draft.canvasState = "idle";
@@ -3713,6 +3760,7 @@ function createFlowStore(initialGraph = {
3713
3760
  const hasPort = (nodeId, portName) => portName === null || draft.graph.nodes.find((node) => node.id === nodeId)?.ports?.some((port) => port.name === portName) === true;
3714
3761
  if (draft.connection && (!nodeIds.has(draft.connection.sourceId) || !hasPort(draft.connection.sourceId, draft.connection.sourcePort) || draft.connection.targetId !== null && (!nodeIds.has(draft.connection.targetId) || !hasPort(draft.connection.targetId, draft.connection.targetPort)) || draft.connection.reconnectingEdgeId != null && !edgeIds.has(draft.connection.reconnectingEdgeId))) {
3715
3762
  draft.connection = null;
3763
+ draft.connectionClickStartHandle = null;
3716
3764
  if (draft.canvasState === "connecting") draft.canvasState = "idle";
3717
3765
  }
3718
3766
  if (draft.connectionClickStartHandle && (!nodeIds.has(draft.connectionClickStartHandle.nodeId) || !hasPort(draft.connectionClickStartHandle.nodeId, draft.connectionClickStartHandle.port))) draft.connectionClickStartHandle = null;
@@ -3750,9 +3798,11 @@ function createFlowStore(initialGraph = {
3750
3798
  draft.highlights.clear();
3751
3799
  draft.focusedEntityId = null;
3752
3800
  draft.measurements.clear();
3801
+ draft.derivedPortMeasurements.clear();
3753
3802
  draft.canvasState = "idle";
3754
3803
  draft.draggedEntityId = null;
3755
3804
  draft.connection = null;
3805
+ draft.connectionClickStartHandle = null;
3756
3806
  draft.selectionBox = null;
3757
3807
  draft.selectionBoxBase = null;
3758
3808
  enqueue.emit.graphChanged({
@@ -4422,6 +4472,7 @@ function createFlowStore(initialGraph = {
4422
4472
  connectionStart: (ctx, event, enqueue) => produce(ctx, (draft) => {
4423
4473
  draft.canvasState = "connecting";
4424
4474
  draft.connection = {
4475
+ [connectionLifetime]: {},
4425
4476
  sourceId: event.sourceId,
4426
4477
  sourcePort: event.sourcePort,
4427
4478
  targetId: null,
@@ -4451,7 +4502,7 @@ function createFlowStore(initialGraph = {
4451
4502
  const dx = event.position.x - draft.connection.startPosition.x;
4452
4503
  const dy = event.position.y - draft.connection.startPosition.y;
4453
4504
  const threshold = draft.connectionDragThreshold;
4454
- if (!draft.connection.active && Math.hypot(dx, dy) >= threshold) draft.connection.active = true;
4505
+ if (event.active === void 0 && !draft.connection.active && Math.hypot(dx, dy) >= threshold) draft.connection.active = true;
4455
4506
  enqueue.emit.connectMoved({
4456
4507
  point: event.position,
4457
4508
  targetId: draft.connection.targetId,
@@ -4478,6 +4529,7 @@ function createFlowStore(initialGraph = {
4478
4529
  }
4479
4530
  draft.canvasState = "idle";
4480
4531
  draft.connection = null;
4532
+ draft.connectionClickStartHandle = null;
4481
4533
  }),
4482
4534
  cancelConnection: (ctx) => produce(ctx, (draft) => {
4483
4535
  draft.connection = null;
@@ -4485,7 +4537,10 @@ function createFlowStore(initialGraph = {
4485
4537
  if (draft.canvasState === "connecting") draft.canvasState = "idle";
4486
4538
  }),
4487
4539
  setConnectionClickStartHandle: (ctx, event) => produce(ctx, (draft) => {
4488
- draft.connectionClickStartHandle = event;
4540
+ draft.connectionClickStartHandle = event?.nodeId !== void 0 ? {
4541
+ nodeId: event.nodeId,
4542
+ port: event.port
4543
+ } : null;
4489
4544
  }),
4490
4545
  resizeStart: (ctx, event, enqueue) => produce(ctx, (draft) => {
4491
4546
  const node = draft.graph.nodes.find((n) => n.id === event.id);
@@ -4828,20 +4883,29 @@ function createFlowStore(initialGraph = {
4828
4883
  const [, id] = JSON.parse(measurement.id);
4829
4884
  if (nodeIndices.has(id)) boundaryNodes.add(id);
4830
4885
  const labelIndex = edgeIndices.get(id);
4831
- if (labelIndex !== void 0) invalidateAuthoritativeEdgePath(draft.graph.edges[labelIndex]);
4886
+ if (!event.derivedOnly && labelIndex !== void 0) invalidateAuthoritativeEdgePath(draft.graph.edges[labelIndex]);
4832
4887
  }
4833
4888
  const edgeIndex = edgeIndices.get(measurement.id);
4834
4889
  const edge = edgeIndex === void 0 ? void 0 : draft.graph.edges[edgeIndex];
4835
4890
  if (edge?.label) {
4836
- if (resolveAppearance(edge.label, draft.appearances).registered) invalidateAuthoritativeEdgePath(edge);
4837
- if (!resolveAppearance(edge.label, draft.appearances).autoSize && !resolveAppearance(edge.label, draft.appearances).registered && !edge.label.appearance) {
4891
+ if (!event.derivedOnly && resolveAppearance(edge.label, draft.appearances).registered) invalidateAuthoritativeEdgePath(edge);
4892
+ if (!event.derivedOnly && !resolveAppearance(edge.label, draft.appearances).autoSize && !resolveAppearance(edge.label, draft.appearances).registered && !edge.label.appearance) {
4838
4893
  edge.label.width = measurement.rect.width;
4839
4894
  edge.label.height = measurement.rect.height;
4840
4895
  }
4841
4896
  continue;
4842
4897
  }
4843
4898
  const portTarget = portIndices.get(measurement.id);
4844
- if (portTarget) {
4899
+ if (portTarget && event.derivedOnly) {
4900
+ const candidate = ctx.graph.nodes[portTarget.nodeIndex];
4901
+ const origin = measurement.origin ?? snappedBounds(candidate, ctx.snapToGrid ? ctx.snapGrid : null);
4902
+ draft.derivedPortMeasurements.set(measurement.id, {
4903
+ ...measurement.rect,
4904
+ x: measurement.rect.x - origin.x,
4905
+ y: measurement.rect.y - origin.y
4906
+ });
4907
+ } else if (portTarget) {
4908
+ draft.derivedPortMeasurements.delete(measurement.id);
4845
4909
  const candidate = draft.graph.nodes[portTarget.nodeIndex];
4846
4910
  candidateNodes.add(candidate.id);
4847
4911
  const port = candidate.ports?.[portTarget.portIndex];
@@ -4857,21 +4921,30 @@ function createFlowStore(initialGraph = {
4857
4921
  const index = nodeIndices.get(id);
4858
4922
  if (nodeEndpointGeometryChanged(ctx.graph.nodes[index], draft.graph.nodes[index])) boundaryNodes.add(id);
4859
4923
  }
4860
- if (boundaryNodes.size) invalidatePathsForNodeGeometry(draft, boundaryNodes);
4924
+ if (!event.derivedOnly && boundaryNodes.size) invalidatePathsForNodeGeometry(draft, boundaryNodes);
4861
4925
  });
4862
4926
  },
4863
4927
  removeMeasurements: (ctx, event) => produce(ctx, (draft) => {
4864
4928
  const boundaryNodes = /* @__PURE__ */ new Set();
4865
4929
  for (const id of event.ids) {
4866
- if (!draft.measurements.delete(id)) continue;
4930
+ const removed = draft.measurements.delete(id);
4931
+ draft.derivedPortMeasurements.delete(id);
4932
+ const node = draft.graph.nodes.find((candidate) => candidate.id === id);
4933
+ if (node?.measured) {
4934
+ node.x -= node.measured.anchorOffset?.x ?? 0;
4935
+ node.y -= node.measured.anchorOffset?.y ?? 0;
4936
+ delete node.measured;
4937
+ boundaryNodes.add(id);
4938
+ }
4939
+ if (!removed) continue;
4867
4940
  if (id.startsWith("[\"flow-appearance-boundary\",")) {
4868
4941
  const [, entityId] = JSON.parse(id);
4869
4942
  boundaryNodes.add(entityId);
4870
4943
  const edge = draft.graph.edges.find((candidate) => candidate.id === entityId);
4871
- if (edge) invalidateAuthoritativeEdgePath(edge);
4944
+ if (!event.derivedOnly && edge) invalidateAuthoritativeEdgePath(edge);
4872
4945
  }
4873
4946
  }
4874
- if (boundaryNodes.size) invalidatePathsForNodeGeometry(draft, boundaryNodes);
4947
+ if (!event.derivedOnly && boundaryNodes.size) invalidatePathsForNodeGeometry(draft, boundaryNodes);
4875
4948
  }),
4876
4949
  bakeLabelPositions: (ctx, event, enqueue) => produce(ctx, (draft) => {
4877
4950
  for (const [edgeId, center] of event.positions) {
@@ -5006,6 +5079,231 @@ function deriveFlowView(graph, scope, options = {}) {
5006
5079
  });
5007
5080
  }
5008
5081
  //#endregion
5082
+ //#region src/geometry.ts
5083
+ function normalizeGeometryPosition(value, precision = 0) {
5084
+ if (!Number.isFinite(value)) throw new TypeError("Position must be finite.");
5085
+ if (precision === null) return value || 0;
5086
+ if (!Number.isInteger(precision) || precision < 0 || precision > 6) throw new TypeError("positionPrecision must be null or an integer from 0 to 6.");
5087
+ return Math.round(value * 10 ** precision) / 10 ** precision || 0;
5088
+ }
5089
+ //#endregion
5090
+ //#region src/external-edit.ts
5091
+ /** Native hosts own previews. Supplied fields differing from the baseline win at commit. */
5092
+ function createFlowExternalEdit(flow, options = {}) {
5093
+ const graph = flow.getContext().graph;
5094
+ const baselineNodes = new Map(graph.nodes.map((node) => [node.id, flow.getBounds(node.id)]));
5095
+ const baselineEdges = new Map(graph.edges.map((edge) => [edge.id, {
5096
+ sourceId: edge.sourceId,
5097
+ targetId: edge.targetId,
5098
+ sourcePort: edge.sourcePort,
5099
+ targetPort: edge.targetPort
5100
+ }]));
5101
+ const removedNodes = /* @__PURE__ */ new Set();
5102
+ const removedEdges = /* @__PURE__ */ new Set();
5103
+ let closed = false;
5104
+ let disposed = false;
5105
+ const commits = flow.on("commit", ({ changeSet }) => {
5106
+ for (const node of changeSet.nodes.removed) removedNodes.add(node.id);
5107
+ for (const edge of changeSet.edges.removed) removedEdges.add(edge.id);
5108
+ });
5109
+ const destruction = flow.on("destroy", () => dispose());
5110
+ function dispose() {
5111
+ if (disposed) return;
5112
+ disposed = true;
5113
+ closed = true;
5114
+ commits.unsubscribe();
5115
+ destruction.unsubscribe();
5116
+ baselineNodes.clear();
5117
+ baselineEdges.clear();
5118
+ removedNodes.clear();
5119
+ removedEdges.clear();
5120
+ }
5121
+ function failure(message) {
5122
+ return {
5123
+ ok: false,
5124
+ error: new FlowGraphValidationError([{
5125
+ code: "external_edit_failed",
5126
+ path: "$",
5127
+ message
5128
+ }])
5129
+ };
5130
+ }
5131
+ return {
5132
+ cancel: dispose,
5133
+ dispose,
5134
+ commit(operations, commitOptions) {
5135
+ if (closed) return failure("Flow external edit session is closed.");
5136
+ closed = true;
5137
+ try {
5138
+ if (operations.length && !flow.can("edit")) return failure("Flow external edits are not allowed.");
5139
+ const finalFields = /* @__PURE__ */ new Map();
5140
+ for (const operation of operations) {
5141
+ const fields = operation.kind === "node.move" ? operation.position : operation.kind === "node.resize" ? operation.bounds : operation.kind === "node.contentSize" ? {
5142
+ ...operation.size,
5143
+ ...operation.position
5144
+ } : operation.kind === "edge.reconnect" ? operation.endpoints : void 0;
5145
+ if (!fields || !("id" in operation)) continue;
5146
+ const kind = operation.kind.startsWith("node.") ? "node" : "edge";
5147
+ for (const [key, value] of Object.entries(fields)) if (value !== void 0) finalFields.set(`${kind}:${operation.id}:${key}`, value);
5148
+ }
5149
+ function reconcile(id, key, value, baseline, current, fresh = false) {
5150
+ if (fresh) return value === void 0 ? current : value;
5151
+ if (value === void 0 || finalFields.get(`${id}:${key}`) === baseline || value === baseline) return current;
5152
+ return value;
5153
+ }
5154
+ return {
5155
+ ok: true,
5156
+ value: flow.transaction((draft) => {
5157
+ const createdNodes = /* @__PURE__ */ new Set();
5158
+ const createdEdges = /* @__PURE__ */ new Set();
5159
+ for (const operation of operations) switch (operation.kind) {
5160
+ case "node.create":
5161
+ if (removedNodes.has(operation.node.id)) break;
5162
+ draft.nodes.create(operation.node);
5163
+ createdNodes.add(operation.node.id);
5164
+ break;
5165
+ case "edge.create":
5166
+ if (removedEdges.has(operation.edge.id)) break;
5167
+ draft.edges.create(operation.edge);
5168
+ createdEdges.add(operation.edge.id);
5169
+ break;
5170
+ case "node.delete":
5171
+ case "node.move":
5172
+ case "node.resize":
5173
+ case "node.contentSize":
5174
+ case "node.data": {
5175
+ const { id } = operation;
5176
+ if (!createdNodes.has(id) && (!baselineNodes.has(id) || removedNodes.has(id))) break;
5177
+ if (!draft.getNode(id)) break;
5178
+ if (operation.kind === "node.delete") {
5179
+ draft.nodes.delete(id);
5180
+ break;
5181
+ }
5182
+ if (operation.kind === "node.data") {
5183
+ draft.nodes.setData(id, operation.update);
5184
+ break;
5185
+ }
5186
+ const current = draft.getNodeBounds(id);
5187
+ if (!current) break;
5188
+ const baseline = createdNodes.has(id) ? current : baselineNodes.get(id) ?? current;
5189
+ const supplied = operation.kind === "node.move" ? operation.position : operation.kind === "node.resize" ? operation.bounds : {
5190
+ ...operation.size,
5191
+ ...operation.position
5192
+ };
5193
+ const next = { ...current };
5194
+ for (const key of [
5195
+ "x",
5196
+ "y",
5197
+ "width",
5198
+ "height"
5199
+ ]) {
5200
+ const raw = supplied[key];
5201
+ const value = baselineNodes.has(id) && !createdNodes.has(id) ? reconcile(`node:${id}`, key, raw, baseline[key], current[key]) : raw ?? current[key];
5202
+ next[key] = raw !== void 0 && raw !== baseline[key] && value !== current[key] && (key === "x" || key === "y") ? normalizeGeometryPosition(value, operation.options?.positionPrecision) : value;
5203
+ }
5204
+ const moved = next.x !== current.x || next.y !== current.y;
5205
+ const resized = next.width !== current.width || next.height !== current.height;
5206
+ const geometryOptions = {
5207
+ ...operation.options,
5208
+ positionPrecision: null
5209
+ };
5210
+ if (operation.kind === "node.move") {
5211
+ if (moved) draft.nodes.move(id, next, geometryOptions);
5212
+ } else if (operation.kind === "node.resize") {
5213
+ if (moved || resized) draft.nodes.resize(id, next, geometryOptions);
5214
+ } else if (moved || resized) draft.nodes.setContentSize(id, next, {
5215
+ ...geometryOptions,
5216
+ ...moved ? { position: {
5217
+ x: next.x,
5218
+ y: next.y
5219
+ } } : {}
5220
+ });
5221
+ break;
5222
+ }
5223
+ case "edge.delete":
5224
+ case "edge.reconnect":
5225
+ case "edge.data": {
5226
+ const { id } = operation;
5227
+ if (!createdEdges.has(id) && (!baselineEdges.has(id) || removedEdges.has(id))) break;
5228
+ const edge = draft.getEdge(id);
5229
+ if (!edge) break;
5230
+ if (operation.kind === "edge.delete") draft.edges.delete(id);
5231
+ else if (operation.kind === "edge.data") draft.edges.setData(id, operation.update);
5232
+ else {
5233
+ const baseline = baselineEdges.get(id) ?? edge;
5234
+ const endpoints = operation.endpoints;
5235
+ const sourceId = reconcile(`edge:${id}`, "sourceId", endpoints.sourceId, baseline.sourceId, edge.sourceId, createdEdges.has(id));
5236
+ const targetId = reconcile(`edge:${id}`, "targetId", endpoints.targetId, baseline.targetId, edge.targetId, createdEdges.has(id));
5237
+ const sourcePort = reconcile(`edge:${id}`, "sourcePort", endpoints.sourcePort, baseline.sourcePort ?? null, edge.sourcePort ?? null, createdEdges.has(id));
5238
+ const targetPort = reconcile(`edge:${id}`, "targetPort", endpoints.targetPort, baseline.targetPort ?? null, edge.targetPort ?? null, createdEdges.has(id));
5239
+ if (sourceId !== edge.sourceId || targetId !== edge.targetId || sourcePort !== (edge.sourcePort ?? null) || targetPort !== (edge.targetPort ?? null)) draft.edges.reconnect(id, {
5240
+ newSourceId: sourceId,
5241
+ newTargetId: targetId,
5242
+ newSourcePort: sourcePort,
5243
+ newTargetPort: targetPort
5244
+ });
5245
+ }
5246
+ break;
5247
+ }
5248
+ default: throw new Error(`Unknown external operation: ${operation}`);
5249
+ }
5250
+ }, {
5251
+ ...options,
5252
+ ...commitOptions
5253
+ }).changeSet
5254
+ };
5255
+ } catch (error) {
5256
+ if (error instanceof FlowGraphValidationError) return {
5257
+ ok: false,
5258
+ error
5259
+ };
5260
+ return failure(error instanceof Error ? error.message : String(error));
5261
+ } finally {
5262
+ dispose();
5263
+ }
5264
+ }
5265
+ };
5266
+ }
5267
+ //#endregion
5268
+ //#region src/render-invalidation.ts
5269
+ /** Synchronous invalidation only; renderers own frame scheduling and coalescing. */
5270
+ function createFlowRenderApi(flow) {
5271
+ const listeners = /* @__PURE__ */ new Set();
5272
+ let revision = 0;
5273
+ let disposed = false;
5274
+ const notify = (reason) => {
5275
+ if (disposed) return;
5276
+ const event = {
5277
+ revision: ++revision,
5278
+ reason,
5279
+ all: true
5280
+ };
5281
+ for (const listener of listeners) listener(event);
5282
+ };
5283
+ const context = flow.subscribe(() => notify("context"));
5284
+ const projection = flow.projections.subscribe(() => notify("projection"));
5285
+ const commits = flow.on("commit", () => notify("commit"));
5286
+ const destruction = flow.on("destroy", () => dispose());
5287
+ function dispose() {
5288
+ if (disposed) return;
5289
+ disposed = true;
5290
+ context();
5291
+ projection();
5292
+ commits.unsubscribe();
5293
+ destruction.unsubscribe();
5294
+ listeners.clear();
5295
+ }
5296
+ return {
5297
+ subscribe(listener) {
5298
+ if (!disposed) listeners.add(listener);
5299
+ return () => {
5300
+ listeners.delete(listener);
5301
+ };
5302
+ },
5303
+ dispose
5304
+ };
5305
+ }
5306
+ //#endregion
5009
5307
  //#region src/shapes/index.ts
5010
5308
  const shapeRegistry = /* @__PURE__ */ new Map();
5011
5309
  function registerShape(name, handler) {
@@ -5172,6 +5470,15 @@ function offsetEdgeWaypoints(edge, offset = {
5172
5470
  y: point.y + dy
5173
5471
  }));
5174
5472
  }
5473
+ function normalizeConnection(proposed, graph) {
5474
+ if ((graph.nodes.find((node) => node.id === proposed.sourceId)?.ports?.find((port) => port.name === proposed.sourcePort))?.direction !== "in") return proposed;
5475
+ return {
5476
+ sourceId: proposed.targetId,
5477
+ sourcePort: proposed.targetPort,
5478
+ targetId: proposed.sourceId,
5479
+ targetPort: proposed.sourcePort
5480
+ };
5481
+ }
5175
5482
  const SPATIAL_CELL_SIZE = 512;
5176
5483
  const MAX_ENTITY_SPATIAL_CELLS = 4096;
5177
5484
  /**
@@ -5659,16 +5966,32 @@ function createFlowEngine(store, initialOptions = {}) {
5659
5966
  function entityIdAtPoint(canvasPoint) {
5660
5967
  return entityAtPoint(canvasPoint)?.id ?? null;
5661
5968
  }
5662
- function validateConnectionDetailed(proposed) {
5663
- const { graph } = ctx();
5969
+ function validateConnectionDetailed(proposed, context = ctx()) {
5970
+ const { graph } = context;
5664
5971
  const srcNode = graph.nodes.find((n) => n.id === proposed.sourceId);
5665
5972
  const tgtNode = graph.nodes.find((n) => n.id === proposed.targetId);
5666
5973
  if (!srcNode || !tgtNode) return {
5667
5974
  valid: false,
5668
5975
  reason: "missing-endpoint"
5669
5976
  };
5977
+ if (context.mode === "readonly") return {
5978
+ valid: false,
5979
+ reason: "readonly"
5980
+ };
5981
+ if ([srcNode, tgtNode].some((node) => !(node.connectable ?? resolveBehavior(engineOptions.config?.connectable, node, context, true)))) return {
5982
+ valid: false,
5983
+ reason: "connectable"
5984
+ };
5670
5985
  const sourcePort = proposed.sourcePort && srcNode.ports ? srcNode.ports.find((p) => p.name === proposed.sourcePort) ?? null : null;
5671
5986
  const targetPort = proposed.targetPort && tgtNode.ports ? tgtNode.ports.find((p) => p.name === proposed.targetPort) ?? null : null;
5987
+ if (proposed.sourcePort && proposed.sourcePort !== "*" && !sourcePort) return {
5988
+ valid: false,
5989
+ reason: "missing-source-port"
5990
+ };
5991
+ if (proposed.targetPort && proposed.targetPort !== "*" && !targetPort) return {
5992
+ valid: false,
5993
+ reason: "missing-target-port"
5994
+ };
5672
5995
  if (proposed.sourcePort && proposed.sourcePort !== "*" && appearanceFor(srcNode).registered && !isPortAllowed(srcNode, proposed.sourcePort) || proposed.targetPort && proposed.targetPort !== "*" && appearanceFor(tgtNode).registered && !isPortAllowed(tgtNode, proposed.targetPort)) return {
5673
5996
  valid: false,
5674
5997
  reason: "appearance-port"
@@ -5692,12 +6015,12 @@ function createFlowEngine(store, initialOptions = {}) {
5692
6015
  if (engineOptions.canConnect) {
5693
6016
  const result = engineOptions.canConnect(proposed, {
5694
6017
  graph,
5695
- context: ctx(),
6018
+ context,
5696
6019
  source: srcNode,
5697
6020
  target: tgtNode,
5698
6021
  sourcePort,
5699
6022
  targetPort,
5700
- connection: ctx().connection
6023
+ connection: context.connection
5701
6024
  });
5702
6025
  if (typeof result === "boolean") {
5703
6026
  if (!result) return { valid: false };
@@ -5720,12 +6043,12 @@ function createFlowEngine(store, initialOptions = {}) {
5720
6043
  function isConnectionCandidateValid(source, nodeId, portName) {
5721
6044
  if (!source) return true;
5722
6045
  if (nodeId === source.nodeId) return false;
5723
- return validateConnection({
6046
+ return validateConnection(normalizeConnection({
5724
6047
  sourceId: source.nodeId,
5725
6048
  sourcePort: source.port,
5726
6049
  targetId: nodeId,
5727
6050
  targetPort: portName
5728
- });
6051
+ }, ctx().graph));
5729
6052
  }
5730
6053
  function resolveEntityConfig(entityOrId) {
5731
6054
  const entity = typeof entityOrId === "string" ? getEntity(entityOrId) : entityOrId;
@@ -5791,19 +6114,16 @@ function createFlowEngine(store, initialOptions = {}) {
5791
6114
  }
5792
6115
  function getConnectionCandidate(pointer, options = {}) {
5793
6116
  const c = ctx();
6117
+ const snap = getVisualSnapOffset();
5794
6118
  const { radius, mode } = connectionOptions(options);
5795
6119
  let bestPort = null;
5796
6120
  let bestNode = null;
5797
6121
  for (const node of getEntityOrderFor(c).nodes) {
5798
6122
  if (!isNodeVisible(node, c)) continue;
5799
6123
  if (!resolveEntityConfig(node).connectable) continue;
5800
- const nodePosition = layoutPosition(node, c);
5801
6124
  for (const port of node.ports ?? []) {
5802
6125
  if (!isPortAllowed(node, port.name)) continue;
5803
- const position = {
5804
- x: nodePosition.x + port.x + port.width / 2,
5805
- y: nodePosition.y + port.y + port.height / 2
5806
- };
6126
+ const position = portCenter(node, port, snap);
5807
6127
  const distance = Math.hypot(pointer.x - position.x, pointer.y - position.y);
5808
6128
  if (distance > radius) continue;
5809
6129
  const isValid = isConnectionCandidateValid(options.source, node.id, port.name);
@@ -5899,8 +6219,8 @@ function createFlowEngine(store, initialOptions = {}) {
5899
6219
  if (!measured) return bounds;
5900
6220
  return {
5901
6221
  ...bounds,
5902
- width: measured.width,
5903
- height: measured.height
6222
+ width: addressable.node.style?.customWidth ?? measured.width,
6223
+ height: addressable.node.style?.customHeight ?? measured.height
5904
6224
  };
5905
6225
  }
5906
6226
  if (addressable.kind === "edge") {
@@ -5912,17 +6232,8 @@ function createFlowEngine(store, initialOptions = {}) {
5912
6232
  return labelBounds ?? getEdgePathBounds(id) ?? void 0;
5913
6233
  }
5914
6234
  if (addressable.kind === "port") {
5915
- const measured = c.measurements.get(id);
5916
- if (measured) return measured;
5917
6235
  const owner = getNode(addressable.nodeId);
5918
- if (!owner) return void 0;
5919
- const ownerPosition = layoutPosition(owner, c);
5920
- return {
5921
- x: ownerPosition.x + addressable.port.x,
5922
- y: ownerPosition.y + addressable.port.y,
5923
- width: addressable.port.width,
5924
- height: addressable.port.height
5925
- };
6236
+ return owner ? portBounds(owner, addressable.port) : void 0;
5926
6237
  }
5927
6238
  }
5928
6239
  /** Resolve edge label bounds using committed (static) node positions */
@@ -6152,19 +6463,33 @@ function createFlowEngine(store, initialOptions = {}) {
6152
6463
  y: b.y
6153
6464
  };
6154
6465
  }
6466
+ function portBounds(node, port, snap) {
6467
+ const c = ctx();
6468
+ const id = port.id && c.measurements.has(port.id) ? port.id : `${node.id}:${port.name}`;
6469
+ const local = c.derivedPortMeasurements.get(id);
6470
+ const measured = c.measurements.get(id);
6471
+ if (measured && !local) return { ...measured };
6472
+ const position = local ? visualPosition(node, snap ?? getVisualSnapOffset()) : snap ? visualPosition(node, snap) : layoutPosition(node);
6473
+ const rect = local ?? port;
6474
+ return {
6475
+ x: position.x + rect.x,
6476
+ y: position.y + rect.y,
6477
+ width: rect.width,
6478
+ height: rect.height
6479
+ };
6480
+ }
6481
+ function portCenter(node, port, snap) {
6482
+ const bounds = portBounds(node, port, snap);
6483
+ return {
6484
+ x: bounds.x + bounds.width / 2,
6485
+ y: bounds.y + bounds.height / 2
6486
+ };
6487
+ }
6155
6488
  /** Get bounds for edge endpoint — port bounds if specified, otherwise node bounds */
6156
6489
  function getEndpointBounds(node, portName, snap) {
6157
6490
  if (portName && portName !== "*" && node.ports && isPortAllowed(node, portName)) {
6158
6491
  const port = node.ports.find((p) => p.name === portName);
6159
- if (port) {
6160
- const np = snap ? visualPosition(node, snap) : layoutPosition(node);
6161
- return {
6162
- x: np.x + port.x,
6163
- y: np.y + port.y,
6164
- width: port.width,
6165
- height: port.height
6166
- };
6167
- }
6492
+ if (port) return portBounds(node, port, snap);
6168
6493
  }
6169
6494
  const visual = snap ? visualBounds(node, snap) : hierarchyBounds(node, ctx());
6170
6495
  return connectionBounds(node.id, node, visual);
@@ -6185,18 +6510,28 @@ function createFlowEngine(store, initialOptions = {}) {
6185
6510
  x: otherBounds.x + otherBounds.width / 2,
6186
6511
  y: otherBounds.y + otherBounds.height / 2
6187
6512
  };
6188
- return closestPortPosition({
6189
- ...node,
6190
- ports: node.ports.filter((port) => isPortAllowed(node, port.name))
6191
- }, otherCenter, snap ? visualPosition(node, snap) : layoutPosition(node));
6513
+ let closest = {
6514
+ x: nodeBounds.x,
6515
+ y: nodeBounds.y
6516
+ };
6517
+ let distance = Infinity;
6518
+ for (const port of node.ports) {
6519
+ if (!isPortAllowed(node, port.name)) continue;
6520
+ const point = portCenter(node, port, snap);
6521
+ const nextDistance = (point.x - otherCenter.x) ** 2 + (point.y - otherCenter.y) ** 2;
6522
+ if (nextDistance < distance) {
6523
+ closest = point;
6524
+ distance = nextDistance;
6525
+ }
6526
+ }
6527
+ return closest;
6192
6528
  }
6193
6529
  if (portName && portName !== "*" && node.ports && isPortAllowed(node, portName)) {
6194
- const port = node.ports.find((p) => p.name === portName);
6195
- if (port) {
6196
- const position = snap ? visualPosition(node, snap) : layoutPosition(node);
6530
+ if (node.ports.find((p) => p.name === portName)) {
6531
+ const bounds = getEndpointBounds(node, portName, snap);
6197
6532
  return {
6198
- x: position.x + port.x + port.width / 2,
6199
- y: position.y + port.y + port.height / 2
6533
+ x: bounds.x + bounds.width / 2,
6534
+ y: bounds.y + bounds.height / 2
6200
6535
  };
6201
6536
  }
6202
6537
  }
@@ -6910,21 +7245,14 @@ function createFlowEngine(store, initialOptions = {}) {
6910
7245
  if (!node?.ports) return null;
6911
7246
  const port = node.ports.find((p) => p.name === portName);
6912
7247
  if (!port) return null;
6913
- const np = layoutPosition(node);
6914
- return {
6915
- x: np.x + port.x + port.width / 2,
6916
- y: np.y + port.y + port.height / 2
6917
- };
7248
+ return portCenter(node, port);
6918
7249
  },
6919
7250
  getPortPositions: (nodeId) => {
6920
7251
  const result = /* @__PURE__ */ new Map();
6921
7252
  const node = getNode(nodeId);
6922
7253
  if (!node?.ports) return result;
6923
- const np = layoutPosition(node);
6924
- for (const port of node.ports) result.set(port.name, {
6925
- x: np.x + port.x + port.width / 2,
6926
- y: np.y + port.y + port.height / 2
6927
- });
7254
+ const snap = getVisualSnapOffset();
7255
+ for (const port of node.ports) result.set(port.name, portCenter(node, port, snap));
6928
7256
  return result;
6929
7257
  },
6930
7258
  getEdgeEndpoints: (edgeId) => {
@@ -7070,37 +7398,6 @@ function boundsForPoints(points) {
7070
7398
  height: maxY - minY
7071
7399
  };
7072
7400
  }
7073
- function closestPortPosition(node, target, position = resolvedPosition(node)) {
7074
- if (!node.ports?.length) {
7075
- const b = {
7076
- ...resolvedBounds(node),
7077
- ...position
7078
- };
7079
- return {
7080
- x: b.x + b.width / 2,
7081
- y: b.y + b.height / 2
7082
- };
7083
- }
7084
- const np = position;
7085
- let best = {
7086
- x: np.x,
7087
- y: np.y
7088
- };
7089
- let bestDist = Infinity;
7090
- for (const port of node.ports) {
7091
- const px = np.x + port.x + port.width / 2;
7092
- const py = np.y + port.y + port.height / 2;
7093
- const d = (px - target.x) ** 2 + (py - target.y) ** 2;
7094
- if (d < bestDist) {
7095
- bestDist = d;
7096
- best = {
7097
- x: px,
7098
- y: py
7099
- };
7100
- }
7101
- }
7102
- return best;
7103
- }
7104
7401
  /**
7105
7402
  * Resolve label anchor position. Returns the TOP-LEFT corner of the label.
7106
7403
  * For 'fixed': label.x/y IS the top-left (like a node).
@@ -7800,15 +8097,22 @@ function createFlow(options = {}) {
7800
8097
  if (event.reconnectedEdgeId) return;
7801
8098
  if (event.target.kind !== "node") return;
7802
8099
  if (event.connection.isValid === false) return;
7803
- edges.create({
8100
+ edges.create(normalizeConnection({
7804
8101
  sourceId: event.source.nodeId,
7805
8102
  targetId: event.target.nodeId,
7806
8103
  sourcePort: event.source.port,
7807
8104
  targetPort: event.target.port
7808
- });
8105
+ }, store.getSnapshot().context.graph));
7809
8106
  });
7810
8107
  cleanup.add(() => connectionSubscription.unsubscribe());
8108
+ let destroyed = false;
8109
+ const destroyListeners = /* @__PURE__ */ new Set();
7811
8110
  function destroy() {
8111
+ if (destroyed) return;
8112
+ destroyed = true;
8113
+ for (const listener of destroyListeners) listener({ type: "destroy" });
8114
+ destroyListeners.clear();
8115
+ store.trigger.cancelConnection();
7812
8116
  activeLayoutAbort?.abort();
7813
8117
  activeLayoutAnimation?.stop(true);
7814
8118
  activeViewportAnimation?.cancel();
@@ -8532,20 +8836,39 @@ function createFlow(options = {}) {
8532
8836
  depth: scope.depth
8533
8837
  });
8534
8838
  }
8535
- function commitGraph(graph, transactionOptions = {}, replacementOptions, layoutAnimationOffsets) {
8839
+ function validateDraftConnections(graph) {
8840
+ const previousGraph = store.getSnapshot().context.graph;
8841
+ const previousEdges = new Map(previousGraph.edges.map((edge) => [edge.id, edge]));
8842
+ const currentNodeIds = new Set(graph.nodes.map((node) => node.id));
8843
+ const context = {
8844
+ ...store.getSnapshot().context,
8845
+ graph
8846
+ };
8847
+ for (const edge of graph.edges) {
8848
+ const previous = previousEdges.get(edge.id);
8849
+ if (previous && previous.sourceId === edge.sourceId && previous.targetId === edge.targetId && previous.sourcePort === edge.sourcePort && previous.targetPort === edge.targetPort) continue;
8850
+ if (configuration.store.onDeleteNodes === "retarget" && previous !== void 0 && (currentNodeIds.has(previous.sourceId) && !currentNodeIds.has(previous.targetId) && edge.sourceId === previous.sourceId && edge.targetId === previous.sourceId && edge.sourcePort === previous.sourcePort && edge.targetPort === null || !currentNodeIds.has(previous.sourceId) && currentNodeIds.has(previous.targetId) && edge.sourceId === previous.targetId && edge.targetId === previous.targetId && edge.sourcePort === null && edge.targetPort === previous.targetPort)) continue;
8851
+ if (context.mode === "readonly" || policyValue("canEdit") === false || policyValue("canConnect") === false || previous && policyValue("canReconnect") === false) throw new Error(`Connection for edge "${edge.id}" is not allowed.`);
8852
+ if (!engine.validateConnectionDetailed(edge, context).valid) throw new Error(`Connection for edge "${edge.id}" is not allowed.`);
8853
+ }
8854
+ }
8855
+ function commitGraph(graph, transactionOptions = {}, replacementOptions, layoutAnimationOffsets, resetMeasurementIds = []) {
8856
+ assertTransactionOptions(transactionOptions);
8536
8857
  const validated = validateAndCloneGraph(graph, options.dataSchemas);
8537
8858
  if (activeTransaction) {
8538
8859
  activeTransaction.graph = validated;
8539
8860
  return null;
8540
8861
  }
8862
+ if (!replacementOptions) validateDraftConnections(validated);
8541
8863
  const changeSet = createFlowChangeSet(currentGraph(), validated, {
8542
8864
  revision: graphRevision + 1,
8543
8865
  ...transactionOptions
8544
8866
  });
8545
- if (!changeSet && !replacementOptions && !layoutAnimationOffsets) return null;
8867
+ if (!changeSet && !replacementOptions && !layoutAnimationOffsets && !resetMeasurementIds.length) return null;
8546
8868
  store.trigger.replaceGraph({
8547
8869
  graph: validated,
8548
8870
  graphChanged: changeSet !== null,
8871
+ resetMeasurementIds,
8549
8872
  ...transactionOptions,
8550
8873
  ...replacementOptions,
8551
8874
  ...layoutAnimationOffsets ? { layoutAnimationOffsets } : {}
@@ -8567,6 +8890,7 @@ function createFlow(options = {}) {
8567
8890
  });
8568
8891
  }
8569
8892
  function mutateGraph(mutate, transactionOptions) {
8893
+ assertTransactionOptions(transactionOptions);
8570
8894
  const previous = currentGraph();
8571
8895
  const draft = validateAndCloneGraph(previous, options.dataSchemas);
8572
8896
  const result = mutate(draft);
@@ -8595,6 +8919,10 @@ function createFlow(options = {}) {
8595
8919
  if (pointsUnchanged && !routeAuthoredInTransaction && (endpointChanged || affectedNodeIds.has(edge.sourceId) || affectedNodeIds.has(edge.targetId))) invalidateAuthoritativeEdgePath(edge);
8596
8920
  }
8597
8921
  commitGraph(draft, transactionOptions);
8922
+ if (activeTransaction) {
8923
+ const surviving = new Set([...draft.nodes, ...draft.edges].map((entity) => entity.id));
8924
+ for (const entity of [...previous.nodes, ...previous.edges]) if (!surviving.has(entity.id)) activeTransaction.removedEntityIds.add(entity.id);
8925
+ }
8598
8926
  return result;
8599
8927
  }
8600
8928
  function pointsEqual(previous, next) {
@@ -8661,8 +8989,153 @@ function createFlow(options = {}) {
8661
8989
  ...input
8662
8990
  };
8663
8991
  }
8992
+ function validateGeometry(value, keys = Object.keys(value)) {
8993
+ for (const key of keys) {
8994
+ const number = Reflect.get(value, key);
8995
+ if (!Number.isFinite(number) || (key === "width" || key === "height") && number < 0) throw new TypeError("Geometry must contain finite coordinates and nonnegative sizes.");
8996
+ }
8997
+ }
8998
+ function settled(value, geometryOptions) {
8999
+ return normalizeGeometryPosition(value, geometryOptions?.positionPrecision);
9000
+ }
9001
+ function sizeNode(node, size) {
9002
+ const { measured: _measured, ...authored } = node;
9003
+ return {
9004
+ ...authored,
9005
+ width: size.width,
9006
+ height: size.height,
9007
+ style: {
9008
+ ...node.style,
9009
+ customWidth: size.width,
9010
+ customHeight: size.height
9011
+ }
9012
+ };
9013
+ }
9014
+ function measurementId(id) {
9015
+ const ref = engine.getEntityRef(id);
9016
+ return ref?.kind === "port" ? `${ref.nodeId}:${ref.portName}` : id;
9017
+ }
9018
+ const measurements = {
9019
+ update(batch) {
9020
+ for (const { rect } of batch) validateGeometry(rect, [
9021
+ "x",
9022
+ "y",
9023
+ "width",
9024
+ "height"
9025
+ ]);
9026
+ store.trigger.updateMeasurements({
9027
+ measurements: batch.map(({ id, rect }) => {
9028
+ const ref = engine.getEntityRef(id);
9029
+ const origin = ref?.kind === "port" ? engine.visualBounds(ref.nodeId) : void 0;
9030
+ return {
9031
+ id: measurementId(id),
9032
+ rect: { ...rect },
9033
+ ...origin ? { origin: {
9034
+ x: origin.x,
9035
+ y: origin.y
9036
+ } } : {}
9037
+ };
9038
+ }),
9039
+ derivedOnly: true
9040
+ });
9041
+ },
9042
+ remove(ids) {
9043
+ store.trigger.removeMeasurements({
9044
+ ids: ids.map(measurementId),
9045
+ derivedOnly: true
9046
+ });
9047
+ },
9048
+ get(id) {
9049
+ const rect = store.getSnapshot().context.measurements.get(measurementId(id));
9050
+ return rect ? { ...rect } : void 0;
9051
+ }
9052
+ };
8664
9053
  function createNodeApi() {
8665
9054
  return {
9055
+ move: (id, position, geometryOptions) => {
9056
+ validateGeometry(position, ["x", "y"]);
9057
+ assertCommandAllowed("move", { id });
9058
+ return mutateGraph((graph) => {
9059
+ const node = graph.nodes.find((candidate) => candidate.id === id);
9060
+ if (!node) throw new Error(`Node "${id}" does not exist.`);
9061
+ const context = store.getSnapshot().context;
9062
+ const grid = context.snapToGrid ? context.snapGrid : null;
9063
+ const x = settled(grid ? Math.round(position.x / grid[0]) * grid[0] : position.x, geometryOptions);
9064
+ const y = settled(grid ? Math.round(position.y / grid[1]) * grid[1] : position.y, geometryOptions);
9065
+ const plan = planNodeMovement({
9066
+ ...context,
9067
+ graph,
9068
+ selection: /* @__PURE__ */ new Set([id])
9069
+ }, x - node.x - (node.dx ?? 0), y - node.y - (node.dy ?? 0));
9070
+ if (plan) {
9071
+ for (const [index, delta] of plan.nodeDeltasByIndex) {
9072
+ const moved = graph.nodes[index];
9073
+ moved.x = settled(moved.x + (moved.dx ?? 0) + delta.x, geometryOptions);
9074
+ moved.y = settled(moved.y + (moved.dy ?? 0) + delta.y, geometryOptions);
9075
+ moved.dx = 0;
9076
+ moved.dy = 0;
9077
+ }
9078
+ for (const [index, delta] of plan.edgeDeltasByIndex) {
9079
+ const edge = graph.edges[index];
9080
+ edge.waypoints = edge.waypoints?.map((point) => ({
9081
+ x: point.x + delta.x,
9082
+ y: point.y + delta.y
9083
+ }));
9084
+ }
9085
+ for (const [index, delta] of plan.labelDeltasByIndex) {
9086
+ const label = graph.edges[index].label;
9087
+ if (label) {
9088
+ label.x += delta.x;
9089
+ label.y += delta.y;
9090
+ }
9091
+ }
9092
+ }
9093
+ return node;
9094
+ }, geometryOptions);
9095
+ },
9096
+ resize: (id, bounds, geometryOptions) => {
9097
+ validateGeometry(bounds, [
9098
+ "x",
9099
+ "y",
9100
+ "width",
9101
+ "height"
9102
+ ]);
9103
+ assertCommandAllowed("resize", { id });
9104
+ return createNodeApi().update(id, (node) => {
9105
+ const moving = clampResizeMovingPoint(node, "bottom-right", {
9106
+ x: 0,
9107
+ y: 0
9108
+ }, {
9109
+ x: bounds.width,
9110
+ y: bounds.height
9111
+ });
9112
+ return {
9113
+ ...sizeNode(node, {
9114
+ width: moving.x,
9115
+ height: moving.y
9116
+ }),
9117
+ x: settled(bounds.x, geometryOptions),
9118
+ y: settled(bounds.y, geometryOptions),
9119
+ dx: 0,
9120
+ dy: 0
9121
+ };
9122
+ }, geometryOptions);
9123
+ },
9124
+ setContentSize: (id, size, geometryOptions) => {
9125
+ validateGeometry(size, ["width", "height"]);
9126
+ if (store.getSnapshot().context.mode === "readonly" || policyValue("canEdit") === false) throw new Error("Flow content sizing is not allowed: readonly.");
9127
+ const position = geometryOptions?.position;
9128
+ if (position) validateGeometry(position, ["x", "y"]);
9129
+ return createNodeApi().update(id, (node) => ({
9130
+ ...sizeNode(node, size),
9131
+ ...position ? {
9132
+ x: settled(position.x, geometryOptions),
9133
+ y: settled(position.y, geometryOptions),
9134
+ dx: 0,
9135
+ dy: 0
9136
+ } : {}
9137
+ }), geometryOptions);
9138
+ },
8666
9139
  create: (input, transactionOptions) => {
8667
9140
  assertCommandAllowed("create");
8668
9141
  const id = resolveId(input.id, {
@@ -8743,7 +9216,6 @@ function createFlow(options = {}) {
8743
9216
  ...withDefaults,
8744
9217
  id
8745
9218
  });
8746
- if (!activeTransaction && !engine.validateConnection(edge)) throw new Error(`Connection for edge "${edge.id}" is not allowed.`);
8747
9219
  mutateGraph((graph) => graph.edges.push(edge), transactionOptions);
8748
9220
  return edge;
8749
9221
  },
@@ -8790,10 +9262,9 @@ function createFlow(options = {}) {
8790
9262
  ...edge,
8791
9263
  sourceId: patch.newSourceId ?? edge.sourceId,
8792
9264
  targetId: patch.newTargetId ?? edge.targetId,
8793
- sourcePort: patch.newSourcePort ?? edge.sourcePort,
8794
- targetPort: patch.newTargetPort ?? edge.targetPort
9265
+ sourcePort: patch.newSourcePort === void 0 ? edge.sourcePort : patch.newSourcePort,
9266
+ targetPort: patch.newTargetPort === void 0 ? edge.targetPort : patch.newTargetPort
8795
9267
  };
8796
- if (!activeTransaction && !engine.validateConnection(proposed)) throw new Error(`Connection for edge "${edgeId}" is not allowed.`);
8797
9268
  return createEdgeApi().update(edgeId, proposed, transactionOptions);
8798
9269
  }
8799
9270
  };
@@ -9144,6 +9615,7 @@ function createFlow(options = {}) {
9144
9615
  }
9145
9616
  function check(command, input) {
9146
9617
  if ([
9618
+ "edit",
9147
9619
  "create",
9148
9620
  "move",
9149
9621
  "resize",
@@ -9214,7 +9686,7 @@ function createFlow(options = {}) {
9214
9686
  };
9215
9687
  const flag = command === "delete" || command === "cut" ? "deletable" : command === "move" ? "draggable" : command === "resize" ? "resizable" : command === "connect" || command === "reconnect" ? "connectable" : command === "select" ? "selectable" : null;
9216
9688
  if (flag && ids.some((id) => {
9217
- const entity = engine.getEntity(id);
9689
+ const entity = currentGraph().nodes.find((node) => node.id === id) ?? engine.getEntity(id);
9218
9690
  return entity && !engine.resolveEntityConfig(entity)[flag];
9219
9691
  })) return {
9220
9692
  allowed: false,
@@ -9280,14 +9752,30 @@ function createFlow(options = {}) {
9280
9752
  }
9281
9753
  }
9282
9754
  };
9755
+ function assertTransactionOptions(next) {
9756
+ if (next?.history !== void 0 && next.history !== "record" && next.history !== "ignore") throw new TypeError("Transaction history must be \"record\" or \"ignore\".");
9757
+ if (!activeTransaction || !next) return;
9758
+ const outer = activeTransaction.options;
9759
+ for (const key of [
9760
+ "history",
9761
+ "origin",
9762
+ "transactionId"
9763
+ ]) {
9764
+ const inherited = key === "history" ? outer?.history ?? "record" : outer?.[key];
9765
+ if (next[key] !== void 0 && next[key] !== inherited) throw new Error(`Nested transaction cannot override ${key}.`);
9766
+ }
9767
+ }
9283
9768
  function transaction(callback, transactionOptions) {
9769
+ assertTransactionOptions(transactionOptions);
9284
9770
  const nested = activeTransaction !== null;
9285
9771
  const previousGraph = nested ? validateAndCloneGraph(activeTransaction.graph, options.dataSchemas) : null;
9286
9772
  const previousAuthoredEdgeRouteIds = nested ? new Set(activeTransaction.authoredEdgeRouteIds) : null;
9773
+ const previousRemovedEntityIds = nested ? new Set(activeTransaction.removedEntityIds) : null;
9287
9774
  if (!nested) activeTransaction = {
9288
9775
  graph: validateAndCloneGraph(currentGraph(), options.dataSchemas),
9289
9776
  options: transactionOptions,
9290
- authoredEdgeRouteIds: /* @__PURE__ */ new Set()
9777
+ authoredEdgeRouteIds: /* @__PURE__ */ new Set(),
9778
+ removedEntityIds: /* @__PURE__ */ new Set()
9291
9779
  };
9292
9780
  const transactionState = activeTransaction;
9293
9781
  let draftOpen = true;
@@ -9296,6 +9784,21 @@ function createFlow(options = {}) {
9296
9784
  };
9297
9785
  const { collapse: _collapse, expand: _expand, ...draftNodes } = nodes;
9298
9786
  const draft = {
9787
+ getNode: (id) => {
9788
+ assertDraftOpen();
9789
+ const node = currentGraph().nodes.find((candidate) => candidate.id === id);
9790
+ return node ? cloneJsonSafe(node) : void 0;
9791
+ },
9792
+ getEdge: (id) => {
9793
+ assertDraftOpen();
9794
+ const edge = currentGraph().edges.find((candidate) => candidate.id === id);
9795
+ return edge ? cloneJsonSafe(edge) : void 0;
9796
+ },
9797
+ getNodeBounds: (id) => {
9798
+ assertDraftOpen();
9799
+ const node = currentGraph().nodes.find((candidate) => candidate.id === id);
9800
+ return node ? resolvedBounds(node) : void 0;
9801
+ },
9299
9802
  nodes: scopedTransactionApi(draftNodes, assertDraftOpen),
9300
9803
  edges: scopedTransactionApi(edges, assertDraftOpen)
9301
9804
  };
@@ -9308,16 +9811,19 @@ function createFlow(options = {}) {
9308
9811
  changeSet: null
9309
9812
  };
9310
9813
  const next = activeTransaction.graph;
9814
+ const surviving = new Set([...next.nodes, ...next.edges].map((entity) => entity.id));
9815
+ const resetMeasurementIds = [...activeTransaction.removedEntityIds].filter((id) => surviving.has(id));
9311
9816
  activeTransaction = null;
9312
9817
  return {
9313
9818
  value,
9314
- changeSet: commitGraph(next, transactionOptions)
9819
+ changeSet: commitGraph(next, transactionOptions, void 0, void 0, resetMeasurementIds)
9315
9820
  };
9316
9821
  } catch (error) {
9317
9822
  draftOpen = false;
9318
9823
  if (nested) {
9319
9824
  activeTransaction.graph = previousGraph;
9320
9825
  activeTransaction.authoredEdgeRouteIds = previousAuthoredEdgeRouteIds;
9826
+ activeTransaction.removedEntityIds = previousRemovedEntityIds;
9321
9827
  } else activeTransaction = null;
9322
9828
  throw error;
9323
9829
  }
@@ -9333,7 +9839,8 @@ function createFlow(options = {}) {
9333
9839
  ok: true,
9334
9840
  value: commitGraph(result.value, {
9335
9841
  origin: applyOptions.origin ?? "applyChangeSet",
9336
- transactionId: applyOptions.transactionId
9842
+ transactionId: applyOptions.transactionId,
9843
+ history: applyOptions.history
9337
9844
  })
9338
9845
  };
9339
9846
  } catch (error) {
@@ -9348,6 +9855,13 @@ function createFlow(options = {}) {
9348
9855
  }
9349
9856
  }
9350
9857
  const on = ((type, listener) => {
9858
+ if (type === "destroy") {
9859
+ const destroyListener = listener;
9860
+ if (!destroyed) destroyListeners.add(destroyListener);
9861
+ return { unsubscribe: () => {
9862
+ destroyListeners.delete(destroyListener);
9863
+ } };
9864
+ }
9351
9865
  if (type === "commit") {
9352
9866
  commitListeners.add(listener);
9353
9867
  return { unsubscribe: () => {
@@ -9377,11 +9891,16 @@ function createFlow(options = {}) {
9377
9891
  });
9378
9892
  return () => subscription.unsubscribe();
9379
9893
  });
9380
- return {
9894
+ const controller = {
9381
9895
  internals: {
9382
9896
  store,
9383
9897
  engine
9384
9898
  },
9899
+ beginExternalEdit: (editOptions) => {
9900
+ if (destroyed) throw new Error("Flow controller is destroyed.");
9901
+ return createFlowExternalEdit(controller, editOptions);
9902
+ },
9903
+ subscribeRender: (listener) => renderApi.subscribe(listener),
9385
9904
  on,
9386
9905
  destroy,
9387
9906
  getContext: engine.getContext,
@@ -9420,6 +9939,7 @@ function createFlow(options = {}) {
9420
9939
  set: (mode) => store.trigger.setMode({ mode })
9421
9940
  },
9422
9941
  nodes,
9942
+ measurements,
9423
9943
  edges,
9424
9944
  selection,
9425
9945
  view,
@@ -9431,6 +9951,8 @@ function createFlow(options = {}) {
9431
9951
  connections,
9432
9952
  content
9433
9953
  };
9954
+ const renderApi = createFlowRenderApi(controller);
9955
+ return controller;
9434
9956
  }
9435
9957
  /**
9436
9958
  * Parse a persisted Flow document and create a controller from it.
@@ -9678,12 +10200,23 @@ function keyboardMode(options = {}) {
9678
10200
  if (event.kind !== "key.down") return null;
9679
10201
  if (event.editableTarget) return null;
9680
10202
  if (matchesKeyBinding(event, keymap.panActivation) && !context.focusedEntityId) return { commands: [preventDefault$1] };
9681
- if (matchesKeyBinding(event, keymap.cancel)) return { commands: context.canvasState === "idle" ? [
9682
- trigger("cancelConnection"),
9683
- trigger("resizeCancel"),
9684
- trigger("clearSelection"),
9685
- trigger("clearFocus")
9686
- ] : [trigger("cancelConnection"), trigger("resizeCancel")] };
10203
+ if (matchesKeyBinding(event, keymap.cancel)) {
10204
+ const commands = [trigger("cancelConnection"), trigger("resizeCancel")];
10205
+ if (context.canvasState === "idle" && !context.connection && !context.connectionClickStartHandle) switch (options.escapeSelection ?? "all") {
10206
+ case "all":
10207
+ commands.push(trigger("clearSelection"), trigger("clearFocus"));
10208
+ break;
10209
+ case "focused":
10210
+ if (context.focusedEntityId && context.selection.has(context.focusedEntityId)) commands.push(trigger("select", {
10211
+ ids: [...context.selection].filter((id) => id !== context.focusedEntityId),
10212
+ mode: "single"
10213
+ }));
10214
+ commands.push(trigger("clearFocus"));
10215
+ break;
10216
+ case "none": break;
10217
+ }
10218
+ return { commands };
10219
+ }
9687
10220
  if (matchesKeyBinding(event, keymap.redo)) return { commands: [preventDefault$1, trigger("redo")] };
9688
10221
  if (matchesKeyBinding(event, keymap.undo)) return { commands: [preventDefault$1, trigger("undo")] };
9689
10222
  if (matchesKeyBinding(event, keymap.selectAll)) return { commands: [preventDefault$1, trigger("selectAll")] };
@@ -9718,16 +10251,27 @@ function keyboardNavMode(options = {}) {
9718
10251
  const step = options.step ?? 5;
9719
10252
  const shiftStep = options.shiftStep ?? 20;
9720
10253
  const keymap = resolveKeymap(options.keymap);
10254
+ const activationKeys = options.activationKeys === void 0 ? [
10255
+ "Enter",
10256
+ " ",
10257
+ "Spacebar"
10258
+ ] : options.activationKeys;
9721
10259
  return {
9722
10260
  id: "keyboard-nav",
9723
10261
  priority: 95,
9724
- start(event, { context }) {
10262
+ start(event, { context, engine }) {
9725
10263
  if (event.kind !== "key.down" || event.editableTarget) return null;
9726
- if ((event.key === "Enter" || event.key === " " || event.key === "Spacebar") && context.focusedEntityId) return { commands: [preventDefault$1, trigger("select", {
9727
- ids: [context.focusedEntityId],
9728
- mode: event.modifiers.shift ? "multi" : "single"
9729
- })] };
10264
+ if (activationKeys?.includes(event.key) && context.focusedEntityId) {
10265
+ const multiSelect = matchesMultiSelect(event.modifiers, keymap);
10266
+ const commands = options.preventDefault === false ? [] : [preventDefault$1];
10267
+ if (multiSelect || options.selectionBehavior !== "preserve" || !context.selection.has(context.focusedEntityId)) commands.push(trigger("select", {
10268
+ ids: [context.focusedEntityId],
10269
+ mode: multiSelect ? "multi" : "single"
10270
+ }));
10271
+ return { commands };
10272
+ }
9730
10273
  if (!allowMove) return null;
10274
+ if (options.nudge === "focused-selection" && (!context.focusedEntityId || !context.selection.has(context.focusedEntityId) || !engine.getNode(context.focusedEntityId))) return null;
9731
10275
  const direction = matchesKeyBinding(event, keymap.nudgeLeft) ? ARROW_DIRECTIONS.ArrowLeft : matchesKeyBinding(event, keymap.nudgeRight) ? ARROW_DIRECTIONS.ArrowRight : matchesKeyBinding(event, keymap.nudgeUp) ? ARROW_DIRECTIONS.ArrowUp : matchesKeyBinding(event, keymap.nudgeDown) ? ARROW_DIRECTIONS.ArrowDown : void 0;
9732
10276
  if (!direction || context.selection.size === 0) return null;
9733
10277
  return { commands: [
@@ -9824,36 +10368,40 @@ function pinchMode() {
9824
10368
  return {
9825
10369
  id: "pinch",
9826
10370
  priority: 85,
9827
- start(event) {
10371
+ start(event, { context }) {
9828
10372
  if (event.kind !== "pinch.start") return null;
9829
10373
  return {
9830
10374
  commands: [preventDefault$1],
9831
- session: pinchSession(event)
10375
+ session: pinchSession(event, context.viewport)
9832
10376
  };
9833
10377
  }
9834
10378
  };
9835
10379
  }
9836
- function pinchSession(down) {
9837
- let lastDistance = down.distance || 1;
9838
- let lastCenter = down.screenCenter;
10380
+ function pinchSession(down, viewport) {
10381
+ let initialDistance = down.distance > 0 ? down.distance : null;
10382
+ const anchor = {
10383
+ x: (down.screenCenter.x - viewport.x) / viewport.zoom,
10384
+ y: (down.screenCenter.y - viewport.y) / viewport.zoom
10385
+ };
9839
10386
  return {
9840
- update(event) {
10387
+ update(event, { context }) {
9841
10388
  if (event.kind === "pinch.move") {
9842
- const distance = event.distance || lastDistance;
9843
- const factor = distance / (lastDistance || distance || 1);
9844
- const delta = {
9845
- x: event.screenCenter.x - lastCenter.x,
9846
- y: event.screenCenter.y - lastCenter.y
10389
+ if (initialDistance === null && event.distance > 0) initialDistance = event.distance;
10390
+ const zoom = initialDistance !== null ? Math.max(context.minZoom, Math.min(context.maxZoom, viewport.zoom * event.distance / initialDistance)) : context.viewport.zoom;
10391
+ const center = {
10392
+ x: context.viewport.x + anchor.x * context.viewport.zoom,
10393
+ y: context.viewport.y + anchor.y * context.viewport.zoom
9847
10394
  };
9848
- lastDistance = distance;
9849
- lastCenter = event.screenCenter;
9850
10395
  return { commands: [
9851
10396
  preventDefault$1,
9852
- trigger("zoomBy", {
9853
- factor,
9854
- center: event.screenCenter
10397
+ trigger("zoomTo", {
10398
+ zoom,
10399
+ center
9855
10400
  }),
9856
- trigger("panBy", delta)
10401
+ trigger("panBy", {
10402
+ x: event.screenCenter.x - center.x,
10403
+ y: event.screenCenter.y - center.y
10404
+ })
9857
10405
  ] };
9858
10406
  }
9859
10407
  if (event.kind === "pinch.end") return {
@@ -10148,7 +10696,24 @@ function connectMode(options = {}) {
10148
10696
  return {
10149
10697
  id: "connect",
10150
10698
  priority: 60,
10151
- start(event, { engine }) {
10699
+ start(event, ctx) {
10700
+ const { engine, context } = ctx;
10701
+ const pending = context.connectionClickStartHandle;
10702
+ if (pending && context.connection) {
10703
+ if (!context.connectOnClick || event.kind === "pointer.cancel") return { commands: [trigger("cancelConnection")] };
10704
+ if (pending.port === null) return { commands: [trigger("cancelConnection")] };
10705
+ const source = {
10706
+ nodeId: pending.nodeId,
10707
+ port: pending.port
10708
+ };
10709
+ if (event.kind === "pointer.move") return { commands: [connectionMoveCommand(resolveConnectionTarget(event, source, ctx, options.isValid), true)] };
10710
+ if (event.kind !== "pointer.down" || event.button !== 0) return null;
10711
+ const target = event.target;
10712
+ const completesOnPort = target.kind === "port" && target.interaction !== "inspect" && (target.nodeId !== source.nodeId || target.portName !== source.port);
10713
+ const completesOnNode = target.kind === "entity" && target.id !== source.nodeId && engine.getNode(target.id) !== void 0;
10714
+ if (!completesOnPort && !completesOnNode) return { commands: [trigger("cancelConnection")] };
10715
+ return { session: connectSession(source, options, { kind: "completing" }) };
10716
+ }
10152
10717
  if (event.kind !== "pointer.down" || event.button !== 0) return null;
10153
10718
  if (event.target.kind !== "port") return null;
10154
10719
  if (event.target.interaction === "inspect") return null;
@@ -10166,7 +10731,10 @@ function connectMode(options = {}) {
10166
10731
  session: connectSession({
10167
10732
  nodeId,
10168
10733
  port: portName
10169
- }, options)
10734
+ }, options, {
10735
+ kind: "pressed",
10736
+ screenPoint: event.screenPoint
10737
+ })
10170
10738
  };
10171
10739
  }
10172
10740
  };
@@ -10213,12 +10781,12 @@ function defaultConnectionValidityDetailed(args, ctx) {
10213
10781
  valid: false,
10214
10782
  reason: "same-node"
10215
10783
  };
10216
- return ctx.engine.validateConnectionDetailed({
10784
+ return ctx.engine.validateConnectionDetailed(normalizeConnection({
10217
10785
  sourceId: source.nodeId,
10218
10786
  sourcePort: source.port,
10219
10787
  targetId: target.nodeId,
10220
10788
  targetPort: target.portName
10221
- });
10789
+ }, ctx.context.graph));
10222
10790
  }
10223
10791
  if (target.kind === "entity") {
10224
10792
  if (target.id === source.nodeId) return {
@@ -10234,12 +10802,12 @@ function defaultConnectionValidityDetailed(args, ctx) {
10234
10802
  valid: false,
10235
10803
  reason: "outside-connection-radius"
10236
10804
  };
10237
- return ctx.engine.validateConnectionDetailed({
10805
+ return ctx.engine.validateConnectionDetailed(normalizeConnection({
10238
10806
  sourceId: source.nodeId,
10239
10807
  sourcePort: source.port,
10240
10808
  targetId: target.id,
10241
10809
  targetPort: null
10242
- });
10810
+ }, ctx.context.graph));
10243
10811
  }
10244
10812
  return {
10245
10813
  valid: false,
@@ -10296,7 +10864,7 @@ function targetIdsFor(target, ctx) {
10296
10864
  }
10297
10865
  function resolveConnectionTarget(event, source, ctx, isValid) {
10298
10866
  const candidate = ctx.engine.getConnectionCandidate(event.point, { source });
10299
- if (candidate) {
10867
+ if (candidate && (event.target.kind !== "port" || candidate.nodeId === event.target.nodeId && candidate.portName === event.target.portName)) {
10300
10868
  const target = targetFromConnectionCandidate(candidate);
10301
10869
  const validity = isValid ? isValid({
10302
10870
  source,
@@ -10332,24 +10900,39 @@ function resolveConnectionTarget(event, source, ctx, isValid) {
10332
10900
  endTarget: connectEndTargetFor(event.target, event.point, ctx)
10333
10901
  };
10334
10902
  }
10335
- function connectSession(source, options) {
10903
+ function connectionMoveCommand(target, active) {
10904
+ return trigger("connectionMove", {
10905
+ position: target.position,
10906
+ targetId: target.targetId,
10907
+ targetPort: target.targetPort,
10908
+ isValid: target.isValid,
10909
+ invalidReason: target.invalidReason,
10910
+ ...active === void 0 ? {} : { active }
10911
+ });
10912
+ }
10913
+ function connectSession(source, options, phase) {
10336
10914
  return {
10337
10915
  update(event, ctx) {
10338
10916
  if (!ctx.context.connection) return { status: "end" };
10339
10917
  if (event.kind === "pointer.move") {
10340
10918
  const target = resolveConnectionTarget(event, source, ctx, options.isValid);
10341
- return { commands: [trigger("connectionMove", {
10342
- position: target.position,
10343
- targetId: target.targetId,
10344
- targetPort: target.targetPort,
10345
- isValid: target.isValid,
10346
- invalidReason: target.invalidReason
10347
- })] };
10919
+ const travel = phase.kind === "pressed" ? distance(phase.screenPoint, event.screenPoint) : 0;
10920
+ return { commands: [connectionMoveCommand(target, ctx.context.connection.active || phase.kind === "completing" || travel > 0 && travel >= ctx.context.connectionDragThreshold)] };
10921
+ }
10922
+ if (event.kind === "pointer.up") {
10923
+ if (phase.kind === "pressed" && ctx.context.connectOnClick && !ctx.context.connection.active && (distance(phase.screenPoint, event.screenPoint) === 0 || distance(phase.screenPoint, event.screenPoint) < ctx.context.connectionDragThreshold)) return {
10924
+ commands: [trigger("setConnectionClickStartHandle", source), trigger("connectionMove", {
10925
+ position: event.point,
10926
+ active: true
10927
+ })],
10928
+ status: "end"
10929
+ };
10930
+ const target = resolveConnectionTarget(event, source, ctx, options.isValid);
10931
+ return {
10932
+ commands: [connectionMoveCommand(target), trigger("connectionEnd", { target: target.endTarget })],
10933
+ status: "end"
10934
+ };
10348
10935
  }
10349
- if (event.kind === "pointer.up") return {
10350
- commands: [trigger("connectionEnd", { target: resolveConnectionTarget(event, source, ctx, options.isValid).endTarget })],
10351
- status: "end"
10352
- };
10353
10936
  if (event.kind === "pointer.cancel") return {
10354
10937
  commands: [trigger("cancelConnection")],
10355
10938
  status: "end"
@@ -10808,6 +11391,14 @@ function createFlowInputRuntime(options) {
10808
11391
  if (name === "setHover" && policies.canHover === false) return false;
10809
11392
  return true;
10810
11393
  }
11394
+ function cancelPendingConnection(previous) {
11395
+ const current = store.getSnapshot().context;
11396
+ if (previous.connectionClickStartHandle && current.connectionClickStartHandle === previous.connectionClickStartHandle && (previous.connection?.[connectionLifetime] ? current.connection?.[connectionLifetime] === previous.connection[connectionLifetime] : current.connection === previous.connection)) store.trigger.cancelConnection();
11397
+ }
11398
+ function reconcileModes() {
11399
+ const context = store.getSnapshot().context;
11400
+ if (!session && context.connectionClickStartHandle && !resolveModes(context).some((mode) => mode.id === "connect")) store.trigger.cancelConnection();
11401
+ }
10811
11402
  function send(event) {
10812
11403
  const effects = {
10813
11404
  preventDefault: false,
@@ -10817,11 +11408,13 @@ function createFlowInputRuntime(options) {
10817
11408
  handledBy: null
10818
11409
  };
10819
11410
  if (session && event.kind === "key.down" && !event.editableTarget && matchesKeyBinding(event, keymap.cancel)) {
11411
+ const previous = store.getSnapshot().context;
10820
11412
  const commands = session.handlers.cancel?.(modeContext());
10821
11413
  effects.handledBy = session.modeId;
10822
11414
  effects.sessionEnded = true;
10823
11415
  session = null;
10824
11416
  apply(commands ?? void 0, effects);
11417
+ cancelPendingConnection(previous);
10825
11418
  return effects;
10826
11419
  }
10827
11420
  if (event.kind === "key.down" && !event.editableTarget && matchesKeyBinding(event, keymap.panActivation)) {
@@ -10881,7 +11474,11 @@ function createFlowInputRuntime(options) {
10881
11474
  return effects;
10882
11475
  }
10883
11476
  function cancelSession() {
10884
- if (!session) return;
11477
+ const previous = store.getSnapshot().context;
11478
+ if (!session) {
11479
+ cancelPendingConnection(previous);
11480
+ return;
11481
+ }
10885
11482
  const effects = {
10886
11483
  preventDefault: false,
10887
11484
  stopPropagation: false,
@@ -10892,9 +11489,11 @@ function createFlowInputRuntime(options) {
10892
11489
  const commands = session.handlers.cancel?.(modeContext());
10893
11490
  session = null;
10894
11491
  apply(commands ?? void 0, effects);
11492
+ cancelPendingConnection(previous);
10895
11493
  }
10896
11494
  return {
10897
11495
  send,
11496
+ reconcileModes,
10898
11497
  cancelSession,
10899
11498
  getActiveSession: () => session?.modeId ?? null
10900
11499
  };