@statelyai/flow 0.12.0 → 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).
@@ -7700,6 +7997,17 @@ function immutableConfiguration(configuration) {
7700
7997
  };
7701
7998
  return clone(configuration);
7702
7999
  }
8000
+ /** Final layout positions align to whole CSS pixels. */
8001
+ function roundLayoutPosition(value) {
8002
+ const rounded = Math.round(value);
8003
+ return rounded === 0 ? 0 : rounded;
8004
+ }
8005
+ function roundLayoutPoint(point) {
8006
+ return {
8007
+ x: roundLayoutPosition(point.x),
8008
+ y: roundLayoutPosition(point.y)
8009
+ };
8010
+ }
7703
8011
  /**
7704
8012
  * Create an owning Flow controller from an optional initial graph.
7705
8013
  *
@@ -7789,15 +8097,22 @@ function createFlow(options = {}) {
7789
8097
  if (event.reconnectedEdgeId) return;
7790
8098
  if (event.target.kind !== "node") return;
7791
8099
  if (event.connection.isValid === false) return;
7792
- edges.create({
8100
+ edges.create(normalizeConnection({
7793
8101
  sourceId: event.source.nodeId,
7794
8102
  targetId: event.target.nodeId,
7795
8103
  sourcePort: event.source.port,
7796
8104
  targetPort: event.target.port
7797
- });
8105
+ }, store.getSnapshot().context.graph));
7798
8106
  });
7799
8107
  cleanup.add(() => connectionSubscription.unsubscribe());
8108
+ let destroyed = false;
8109
+ const destroyListeners = /* @__PURE__ */ new Set();
7800
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();
7801
8116
  activeLayoutAbort?.abort();
7802
8117
  activeLayoutAnimation?.stop(true);
7803
8118
  activeViewportAnimation?.cancel();
@@ -8149,14 +8464,14 @@ function createFlow(options = {}) {
8149
8464
  const position = result.positions.get(node.id);
8150
8465
  const size = result.nodeSizes?.get(node.id);
8151
8466
  if (bounds) {
8152
- node.x = bounds.x;
8153
- node.y = bounds.y;
8467
+ node.x = roundLayoutPosition(bounds.x);
8468
+ node.y = roundLayoutPosition(bounds.y);
8154
8469
  node.width = bounds.width;
8155
8470
  node.height = bounds.height;
8156
8471
  }
8157
8472
  if (position) {
8158
- node.x = position.x;
8159
- node.y = position.y;
8473
+ node.x = roundLayoutPosition(position.x);
8474
+ node.y = roundLayoutPosition(position.y);
8160
8475
  }
8161
8476
  if (size) {
8162
8477
  node.width = size.width;
@@ -8179,30 +8494,30 @@ function createFlow(options = {}) {
8179
8494
  const route = result.edgeRoutes?.get(edge.id);
8180
8495
  if (route || affectedNodeIds.has(edge.sourceId) || affectedNodeIds.has(edge.targetId)) invalidateAuthoritativeEdgePath(edge);
8181
8496
  if (edge.label && labelBounds) {
8182
- edge.label.x = labelBounds.x;
8183
- edge.label.y = labelBounds.y;
8497
+ edge.label.x = roundLayoutPosition(labelBounds.x);
8498
+ edge.label.y = roundLayoutPosition(labelBounds.y);
8184
8499
  edge.label.width = labelBounds.width;
8185
8500
  edge.label.height = labelBounds.height;
8186
- edge.x = labelBounds.x;
8187
- edge.y = labelBounds.y;
8501
+ edge.x = roundLayoutPosition(labelBounds.x);
8502
+ edge.y = roundLayoutPosition(labelBounds.y);
8188
8503
  edge.width = labelBounds.width;
8189
8504
  edge.height = labelBounds.height;
8190
8505
  }
8191
8506
  if (edge.label && labelPosition) {
8192
- edge.label.x = labelPosition.x;
8193
- edge.label.y = labelPosition.y;
8194
- edge.x = labelPosition.x;
8195
- edge.y = labelPosition.y;
8507
+ edge.label.x = roundLayoutPosition(labelPosition.x);
8508
+ edge.label.y = roundLayoutPosition(labelPosition.y);
8509
+ edge.x = roundLayoutPosition(labelPosition.x);
8510
+ edge.y = roundLayoutPosition(labelPosition.y);
8196
8511
  }
8197
8512
  if (edge.label && (labelBounds || labelPosition)) {
8198
8513
  delete edge.label.dx;
8199
8514
  delete edge.label.dy;
8200
8515
  }
8201
8516
  if (route) if (hasAuthoritativeLayoutPoints(route)) {
8202
- edge.points = route.points.map((point) => ({ ...point }));
8517
+ edge.points = route.points.map(roundLayoutPoint);
8203
8518
  edge.routing = route.routing ?? "polyline";
8204
8519
  delete edge.waypoints;
8205
- } else edge.waypoints = layoutWaypoints(route).map((point) => ({ ...point }));
8520
+ } else edge.waypoints = layoutWaypoints(route).map(roundLayoutPoint);
8206
8521
  }
8207
8522
  const initialOffsets = /* @__PURE__ */ new Map();
8208
8523
  if (animate) {
@@ -8521,20 +8836,39 @@ function createFlow(options = {}) {
8521
8836
  depth: scope.depth
8522
8837
  });
8523
8838
  }
8524
- 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);
8525
8857
  const validated = validateAndCloneGraph(graph, options.dataSchemas);
8526
8858
  if (activeTransaction) {
8527
8859
  activeTransaction.graph = validated;
8528
8860
  return null;
8529
8861
  }
8862
+ if (!replacementOptions) validateDraftConnections(validated);
8530
8863
  const changeSet = createFlowChangeSet(currentGraph(), validated, {
8531
8864
  revision: graphRevision + 1,
8532
8865
  ...transactionOptions
8533
8866
  });
8534
- if (!changeSet && !replacementOptions && !layoutAnimationOffsets) return null;
8867
+ if (!changeSet && !replacementOptions && !layoutAnimationOffsets && !resetMeasurementIds.length) return null;
8535
8868
  store.trigger.replaceGraph({
8536
8869
  graph: validated,
8537
8870
  graphChanged: changeSet !== null,
8871
+ resetMeasurementIds,
8538
8872
  ...transactionOptions,
8539
8873
  ...replacementOptions,
8540
8874
  ...layoutAnimationOffsets ? { layoutAnimationOffsets } : {}
@@ -8556,6 +8890,7 @@ function createFlow(options = {}) {
8556
8890
  });
8557
8891
  }
8558
8892
  function mutateGraph(mutate, transactionOptions) {
8893
+ assertTransactionOptions(transactionOptions);
8559
8894
  const previous = currentGraph();
8560
8895
  const draft = validateAndCloneGraph(previous, options.dataSchemas);
8561
8896
  const result = mutate(draft);
@@ -8584,6 +8919,10 @@ function createFlow(options = {}) {
8584
8919
  if (pointsUnchanged && !routeAuthoredInTransaction && (endpointChanged || affectedNodeIds.has(edge.sourceId) || affectedNodeIds.has(edge.targetId))) invalidateAuthoritativeEdgePath(edge);
8585
8920
  }
8586
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
+ }
8587
8926
  return result;
8588
8927
  }
8589
8928
  function pointsEqual(previous, next) {
@@ -8650,8 +8989,153 @@ function createFlow(options = {}) {
8650
8989
  ...input
8651
8990
  };
8652
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
+ };
8653
9053
  function createNodeApi() {
8654
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
+ },
8655
9139
  create: (input, transactionOptions) => {
8656
9140
  assertCommandAllowed("create");
8657
9141
  const id = resolveId(input.id, {
@@ -8732,7 +9216,6 @@ function createFlow(options = {}) {
8732
9216
  ...withDefaults,
8733
9217
  id
8734
9218
  });
8735
- if (!activeTransaction && !engine.validateConnection(edge)) throw new Error(`Connection for edge "${edge.id}" is not allowed.`);
8736
9219
  mutateGraph((graph) => graph.edges.push(edge), transactionOptions);
8737
9220
  return edge;
8738
9221
  },
@@ -8779,10 +9262,9 @@ function createFlow(options = {}) {
8779
9262
  ...edge,
8780
9263
  sourceId: patch.newSourceId ?? edge.sourceId,
8781
9264
  targetId: patch.newTargetId ?? edge.targetId,
8782
- sourcePort: patch.newSourcePort ?? edge.sourcePort,
8783
- 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
8784
9267
  };
8785
- if (!activeTransaction && !engine.validateConnection(proposed)) throw new Error(`Connection for edge "${edgeId}" is not allowed.`);
8786
9268
  return createEdgeApi().update(edgeId, proposed, transactionOptions);
8787
9269
  }
8788
9270
  };
@@ -9133,6 +9615,7 @@ function createFlow(options = {}) {
9133
9615
  }
9134
9616
  function check(command, input) {
9135
9617
  if ([
9618
+ "edit",
9136
9619
  "create",
9137
9620
  "move",
9138
9621
  "resize",
@@ -9203,7 +9686,7 @@ function createFlow(options = {}) {
9203
9686
  };
9204
9687
  const flag = command === "delete" || command === "cut" ? "deletable" : command === "move" ? "draggable" : command === "resize" ? "resizable" : command === "connect" || command === "reconnect" ? "connectable" : command === "select" ? "selectable" : null;
9205
9688
  if (flag && ids.some((id) => {
9206
- const entity = engine.getEntity(id);
9689
+ const entity = currentGraph().nodes.find((node) => node.id === id) ?? engine.getEntity(id);
9207
9690
  return entity && !engine.resolveEntityConfig(entity)[flag];
9208
9691
  })) return {
9209
9692
  allowed: false,
@@ -9269,14 +9752,30 @@ function createFlow(options = {}) {
9269
9752
  }
9270
9753
  }
9271
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
+ }
9272
9768
  function transaction(callback, transactionOptions) {
9769
+ assertTransactionOptions(transactionOptions);
9273
9770
  const nested = activeTransaction !== null;
9274
9771
  const previousGraph = nested ? validateAndCloneGraph(activeTransaction.graph, options.dataSchemas) : null;
9275
9772
  const previousAuthoredEdgeRouteIds = nested ? new Set(activeTransaction.authoredEdgeRouteIds) : null;
9773
+ const previousRemovedEntityIds = nested ? new Set(activeTransaction.removedEntityIds) : null;
9276
9774
  if (!nested) activeTransaction = {
9277
9775
  graph: validateAndCloneGraph(currentGraph(), options.dataSchemas),
9278
9776
  options: transactionOptions,
9279
- authoredEdgeRouteIds: /* @__PURE__ */ new Set()
9777
+ authoredEdgeRouteIds: /* @__PURE__ */ new Set(),
9778
+ removedEntityIds: /* @__PURE__ */ new Set()
9280
9779
  };
9281
9780
  const transactionState = activeTransaction;
9282
9781
  let draftOpen = true;
@@ -9285,6 +9784,21 @@ function createFlow(options = {}) {
9285
9784
  };
9286
9785
  const { collapse: _collapse, expand: _expand, ...draftNodes } = nodes;
9287
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
+ },
9288
9802
  nodes: scopedTransactionApi(draftNodes, assertDraftOpen),
9289
9803
  edges: scopedTransactionApi(edges, assertDraftOpen)
9290
9804
  };
@@ -9297,16 +9811,19 @@ function createFlow(options = {}) {
9297
9811
  changeSet: null
9298
9812
  };
9299
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));
9300
9816
  activeTransaction = null;
9301
9817
  return {
9302
9818
  value,
9303
- changeSet: commitGraph(next, transactionOptions)
9819
+ changeSet: commitGraph(next, transactionOptions, void 0, void 0, resetMeasurementIds)
9304
9820
  };
9305
9821
  } catch (error) {
9306
9822
  draftOpen = false;
9307
9823
  if (nested) {
9308
9824
  activeTransaction.graph = previousGraph;
9309
9825
  activeTransaction.authoredEdgeRouteIds = previousAuthoredEdgeRouteIds;
9826
+ activeTransaction.removedEntityIds = previousRemovedEntityIds;
9310
9827
  } else activeTransaction = null;
9311
9828
  throw error;
9312
9829
  }
@@ -9322,7 +9839,8 @@ function createFlow(options = {}) {
9322
9839
  ok: true,
9323
9840
  value: commitGraph(result.value, {
9324
9841
  origin: applyOptions.origin ?? "applyChangeSet",
9325
- transactionId: applyOptions.transactionId
9842
+ transactionId: applyOptions.transactionId,
9843
+ history: applyOptions.history
9326
9844
  })
9327
9845
  };
9328
9846
  } catch (error) {
@@ -9337,6 +9855,13 @@ function createFlow(options = {}) {
9337
9855
  }
9338
9856
  }
9339
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
+ }
9340
9865
  if (type === "commit") {
9341
9866
  commitListeners.add(listener);
9342
9867
  return { unsubscribe: () => {
@@ -9366,11 +9891,16 @@ function createFlow(options = {}) {
9366
9891
  });
9367
9892
  return () => subscription.unsubscribe();
9368
9893
  });
9369
- return {
9894
+ const controller = {
9370
9895
  internals: {
9371
9896
  store,
9372
9897
  engine
9373
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),
9374
9904
  on,
9375
9905
  destroy,
9376
9906
  getContext: engine.getContext,
@@ -9409,6 +9939,7 @@ function createFlow(options = {}) {
9409
9939
  set: (mode) => store.trigger.setMode({ mode })
9410
9940
  },
9411
9941
  nodes,
9942
+ measurements,
9412
9943
  edges,
9413
9944
  selection,
9414
9945
  view,
@@ -9420,6 +9951,8 @@ function createFlow(options = {}) {
9420
9951
  connections,
9421
9952
  content
9422
9953
  };
9954
+ const renderApi = createFlowRenderApi(controller);
9955
+ return controller;
9423
9956
  }
9424
9957
  /**
9425
9958
  * Parse a persisted Flow document and create a controller from it.
@@ -9667,12 +10200,23 @@ function keyboardMode(options = {}) {
9667
10200
  if (event.kind !== "key.down") return null;
9668
10201
  if (event.editableTarget) return null;
9669
10202
  if (matchesKeyBinding(event, keymap.panActivation) && !context.focusedEntityId) return { commands: [preventDefault$1] };
9670
- if (matchesKeyBinding(event, keymap.cancel)) return { commands: context.canvasState === "idle" ? [
9671
- trigger("cancelConnection"),
9672
- trigger("resizeCancel"),
9673
- trigger("clearSelection"),
9674
- trigger("clearFocus")
9675
- ] : [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
+ }
9676
10220
  if (matchesKeyBinding(event, keymap.redo)) return { commands: [preventDefault$1, trigger("redo")] };
9677
10221
  if (matchesKeyBinding(event, keymap.undo)) return { commands: [preventDefault$1, trigger("undo")] };
9678
10222
  if (matchesKeyBinding(event, keymap.selectAll)) return { commands: [preventDefault$1, trigger("selectAll")] };
@@ -9707,16 +10251,27 @@ function keyboardNavMode(options = {}) {
9707
10251
  const step = options.step ?? 5;
9708
10252
  const shiftStep = options.shiftStep ?? 20;
9709
10253
  const keymap = resolveKeymap(options.keymap);
10254
+ const activationKeys = options.activationKeys === void 0 ? [
10255
+ "Enter",
10256
+ " ",
10257
+ "Spacebar"
10258
+ ] : options.activationKeys;
9710
10259
  return {
9711
10260
  id: "keyboard-nav",
9712
10261
  priority: 95,
9713
- start(event, { context }) {
10262
+ start(event, { context, engine }) {
9714
10263
  if (event.kind !== "key.down" || event.editableTarget) return null;
9715
- if ((event.key === "Enter" || event.key === " " || event.key === "Spacebar") && context.focusedEntityId) return { commands: [preventDefault$1, trigger("select", {
9716
- ids: [context.focusedEntityId],
9717
- mode: event.modifiers.shift ? "multi" : "single"
9718
- })] };
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
+ }
9719
10273
  if (!allowMove) return null;
10274
+ if (options.nudge === "focused-selection" && (!context.focusedEntityId || !context.selection.has(context.focusedEntityId) || !engine.getNode(context.focusedEntityId))) return null;
9720
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;
9721
10276
  if (!direction || context.selection.size === 0) return null;
9722
10277
  return { commands: [
@@ -9813,36 +10368,40 @@ function pinchMode() {
9813
10368
  return {
9814
10369
  id: "pinch",
9815
10370
  priority: 85,
9816
- start(event) {
10371
+ start(event, { context }) {
9817
10372
  if (event.kind !== "pinch.start") return null;
9818
10373
  return {
9819
10374
  commands: [preventDefault$1],
9820
- session: pinchSession(event)
10375
+ session: pinchSession(event, context.viewport)
9821
10376
  };
9822
10377
  }
9823
10378
  };
9824
10379
  }
9825
- function pinchSession(down) {
9826
- let lastDistance = down.distance || 1;
9827
- 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
+ };
9828
10386
  return {
9829
- update(event) {
10387
+ update(event, { context }) {
9830
10388
  if (event.kind === "pinch.move") {
9831
- const distance = event.distance || lastDistance;
9832
- const factor = distance / (lastDistance || distance || 1);
9833
- const delta = {
9834
- x: event.screenCenter.x - lastCenter.x,
9835
- 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
9836
10394
  };
9837
- lastDistance = distance;
9838
- lastCenter = event.screenCenter;
9839
10395
  return { commands: [
9840
10396
  preventDefault$1,
9841
- trigger("zoomBy", {
9842
- factor,
9843
- center: event.screenCenter
10397
+ trigger("zoomTo", {
10398
+ zoom,
10399
+ center
9844
10400
  }),
9845
- trigger("panBy", delta)
10401
+ trigger("panBy", {
10402
+ x: event.screenCenter.x - center.x,
10403
+ y: event.screenCenter.y - center.y
10404
+ })
9846
10405
  ] };
9847
10406
  }
9848
10407
  if (event.kind === "pinch.end") return {
@@ -10137,7 +10696,24 @@ function connectMode(options = {}) {
10137
10696
  return {
10138
10697
  id: "connect",
10139
10698
  priority: 60,
10140
- 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
+ }
10141
10717
  if (event.kind !== "pointer.down" || event.button !== 0) return null;
10142
10718
  if (event.target.kind !== "port") return null;
10143
10719
  if (event.target.interaction === "inspect") return null;
@@ -10155,7 +10731,10 @@ function connectMode(options = {}) {
10155
10731
  session: connectSession({
10156
10732
  nodeId,
10157
10733
  port: portName
10158
- }, options)
10734
+ }, options, {
10735
+ kind: "pressed",
10736
+ screenPoint: event.screenPoint
10737
+ })
10159
10738
  };
10160
10739
  }
10161
10740
  };
@@ -10202,12 +10781,12 @@ function defaultConnectionValidityDetailed(args, ctx) {
10202
10781
  valid: false,
10203
10782
  reason: "same-node"
10204
10783
  };
10205
- return ctx.engine.validateConnectionDetailed({
10784
+ return ctx.engine.validateConnectionDetailed(normalizeConnection({
10206
10785
  sourceId: source.nodeId,
10207
10786
  sourcePort: source.port,
10208
10787
  targetId: target.nodeId,
10209
10788
  targetPort: target.portName
10210
- });
10789
+ }, ctx.context.graph));
10211
10790
  }
10212
10791
  if (target.kind === "entity") {
10213
10792
  if (target.id === source.nodeId) return {
@@ -10223,12 +10802,12 @@ function defaultConnectionValidityDetailed(args, ctx) {
10223
10802
  valid: false,
10224
10803
  reason: "outside-connection-radius"
10225
10804
  };
10226
- return ctx.engine.validateConnectionDetailed({
10805
+ return ctx.engine.validateConnectionDetailed(normalizeConnection({
10227
10806
  sourceId: source.nodeId,
10228
10807
  sourcePort: source.port,
10229
10808
  targetId: target.id,
10230
10809
  targetPort: null
10231
- });
10810
+ }, ctx.context.graph));
10232
10811
  }
10233
10812
  return {
10234
10813
  valid: false,
@@ -10285,7 +10864,7 @@ function targetIdsFor(target, ctx) {
10285
10864
  }
10286
10865
  function resolveConnectionTarget(event, source, ctx, isValid) {
10287
10866
  const candidate = ctx.engine.getConnectionCandidate(event.point, { source });
10288
- if (candidate) {
10867
+ if (candidate && (event.target.kind !== "port" || candidate.nodeId === event.target.nodeId && candidate.portName === event.target.portName)) {
10289
10868
  const target = targetFromConnectionCandidate(candidate);
10290
10869
  const validity = isValid ? isValid({
10291
10870
  source,
@@ -10321,24 +10900,39 @@ function resolveConnectionTarget(event, source, ctx, isValid) {
10321
10900
  endTarget: connectEndTargetFor(event.target, event.point, ctx)
10322
10901
  };
10323
10902
  }
10324
- 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) {
10325
10914
  return {
10326
10915
  update(event, ctx) {
10327
10916
  if (!ctx.context.connection) return { status: "end" };
10328
10917
  if (event.kind === "pointer.move") {
10329
10918
  const target = resolveConnectionTarget(event, source, ctx, options.isValid);
10330
- return { commands: [trigger("connectionMove", {
10331
- position: target.position,
10332
- targetId: target.targetId,
10333
- targetPort: target.targetPort,
10334
- isValid: target.isValid,
10335
- invalidReason: target.invalidReason
10336
- })] };
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
+ };
10337
10935
  }
10338
- if (event.kind === "pointer.up") return {
10339
- commands: [trigger("connectionEnd", { target: resolveConnectionTarget(event, source, ctx, options.isValid).endTarget })],
10340
- status: "end"
10341
- };
10342
10936
  if (event.kind === "pointer.cancel") return {
10343
10937
  commands: [trigger("cancelConnection")],
10344
10938
  status: "end"
@@ -10797,6 +11391,14 @@ function createFlowInputRuntime(options) {
10797
11391
  if (name === "setHover" && policies.canHover === false) return false;
10798
11392
  return true;
10799
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
+ }
10800
11402
  function send(event) {
10801
11403
  const effects = {
10802
11404
  preventDefault: false,
@@ -10806,11 +11408,13 @@ function createFlowInputRuntime(options) {
10806
11408
  handledBy: null
10807
11409
  };
10808
11410
  if (session && event.kind === "key.down" && !event.editableTarget && matchesKeyBinding(event, keymap.cancel)) {
11411
+ const previous = store.getSnapshot().context;
10809
11412
  const commands = session.handlers.cancel?.(modeContext());
10810
11413
  effects.handledBy = session.modeId;
10811
11414
  effects.sessionEnded = true;
10812
11415
  session = null;
10813
11416
  apply(commands ?? void 0, effects);
11417
+ cancelPendingConnection(previous);
10814
11418
  return effects;
10815
11419
  }
10816
11420
  if (event.kind === "key.down" && !event.editableTarget && matchesKeyBinding(event, keymap.panActivation)) {
@@ -10870,7 +11474,11 @@ function createFlowInputRuntime(options) {
10870
11474
  return effects;
10871
11475
  }
10872
11476
  function cancelSession() {
10873
- if (!session) return;
11477
+ const previous = store.getSnapshot().context;
11478
+ if (!session) {
11479
+ cancelPendingConnection(previous);
11480
+ return;
11481
+ }
10874
11482
  const effects = {
10875
11483
  preventDefault: false,
10876
11484
  stopPropagation: false,
@@ -10881,9 +11489,11 @@ function createFlowInputRuntime(options) {
10881
11489
  const commands = session.handlers.cancel?.(modeContext());
10882
11490
  session = null;
10883
11491
  apply(commands ?? void 0, effects);
11492
+ cancelPendingConnection(previous);
10884
11493
  }
10885
11494
  return {
10886
11495
  send,
11496
+ reconcileModes,
10887
11497
  cancelSession,
10888
11498
  getActiveSession: () => session?.modeId ?? null
10889
11499
  };