@statelyai/flow 0.12.1 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -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) => {
@@ -7008,6 +7336,8 @@ function createFlowEngine(store, initialOptions = {}) {
7008
7336
  if (node) return `Node: ${node.label ?? node.id}`;
7009
7337
  const edge = graph.edges.find((e) => e.id === entityId);
7010
7338
  if (edge) {
7339
+ const customLabel = edge.data?.ariaLabel;
7340
+ if (typeof customLabel === "string") return customLabel;
7011
7341
  const src = graph.nodes.find((n) => n.id === edge.sourceId);
7012
7342
  const tgt = graph.nodes.find((n) => n.id === edge.targetId);
7013
7343
  const label = edge.label ? ` (${edge.label.data?.text ?? ""})` : "";
@@ -7070,37 +7400,6 @@ function boundsForPoints(points) {
7070
7400
  height: maxY - minY
7071
7401
  };
7072
7402
  }
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
7403
  /**
7105
7404
  * Resolve label anchor position. Returns the TOP-LEFT corner of the label.
7106
7405
  * For 'fixed': label.x/y IS the top-left (like a node).
@@ -7800,15 +8099,22 @@ function createFlow(options = {}) {
7800
8099
  if (event.reconnectedEdgeId) return;
7801
8100
  if (event.target.kind !== "node") return;
7802
8101
  if (event.connection.isValid === false) return;
7803
- edges.create({
8102
+ edges.create(normalizeConnection({
7804
8103
  sourceId: event.source.nodeId,
7805
8104
  targetId: event.target.nodeId,
7806
8105
  sourcePort: event.source.port,
7807
8106
  targetPort: event.target.port
7808
- });
8107
+ }, store.getSnapshot().context.graph));
7809
8108
  });
7810
8109
  cleanup.add(() => connectionSubscription.unsubscribe());
8110
+ let destroyed = false;
8111
+ const destroyListeners = /* @__PURE__ */ new Set();
7811
8112
  function destroy() {
8113
+ if (destroyed) return;
8114
+ destroyed = true;
8115
+ for (const listener of destroyListeners) listener({ type: "destroy" });
8116
+ destroyListeners.clear();
8117
+ store.trigger.cancelConnection();
7812
8118
  activeLayoutAbort?.abort();
7813
8119
  activeLayoutAnimation?.stop(true);
7814
8120
  activeViewportAnimation?.cancel();
@@ -8532,20 +8838,39 @@ function createFlow(options = {}) {
8532
8838
  depth: scope.depth
8533
8839
  });
8534
8840
  }
8535
- function commitGraph(graph, transactionOptions = {}, replacementOptions, layoutAnimationOffsets) {
8841
+ function validateDraftConnections(graph) {
8842
+ const previousGraph = store.getSnapshot().context.graph;
8843
+ const previousEdges = new Map(previousGraph.edges.map((edge) => [edge.id, edge]));
8844
+ const currentNodeIds = new Set(graph.nodes.map((node) => node.id));
8845
+ const context = {
8846
+ ...store.getSnapshot().context,
8847
+ graph
8848
+ };
8849
+ for (const edge of graph.edges) {
8850
+ const previous = previousEdges.get(edge.id);
8851
+ if (previous && previous.sourceId === edge.sourceId && previous.targetId === edge.targetId && previous.sourcePort === edge.sourcePort && previous.targetPort === edge.targetPort) continue;
8852
+ 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;
8853
+ 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.`);
8854
+ if (!engine.validateConnectionDetailed(edge, context).valid) throw new Error(`Connection for edge "${edge.id}" is not allowed.`);
8855
+ }
8856
+ }
8857
+ function commitGraph(graph, transactionOptions = {}, replacementOptions, layoutAnimationOffsets, resetMeasurementIds = []) {
8858
+ assertTransactionOptions(transactionOptions);
8536
8859
  const validated = validateAndCloneGraph(graph, options.dataSchemas);
8537
8860
  if (activeTransaction) {
8538
8861
  activeTransaction.graph = validated;
8539
8862
  return null;
8540
8863
  }
8864
+ if (!replacementOptions) validateDraftConnections(validated);
8541
8865
  const changeSet = createFlowChangeSet(currentGraph(), validated, {
8542
8866
  revision: graphRevision + 1,
8543
8867
  ...transactionOptions
8544
8868
  });
8545
- if (!changeSet && !replacementOptions && !layoutAnimationOffsets) return null;
8869
+ if (!changeSet && !replacementOptions && !layoutAnimationOffsets && !resetMeasurementIds.length) return null;
8546
8870
  store.trigger.replaceGraph({
8547
8871
  graph: validated,
8548
8872
  graphChanged: changeSet !== null,
8873
+ resetMeasurementIds,
8549
8874
  ...transactionOptions,
8550
8875
  ...replacementOptions,
8551
8876
  ...layoutAnimationOffsets ? { layoutAnimationOffsets } : {}
@@ -8567,6 +8892,7 @@ function createFlow(options = {}) {
8567
8892
  });
8568
8893
  }
8569
8894
  function mutateGraph(mutate, transactionOptions) {
8895
+ assertTransactionOptions(transactionOptions);
8570
8896
  const previous = currentGraph();
8571
8897
  const draft = validateAndCloneGraph(previous, options.dataSchemas);
8572
8898
  const result = mutate(draft);
@@ -8595,6 +8921,10 @@ function createFlow(options = {}) {
8595
8921
  if (pointsUnchanged && !routeAuthoredInTransaction && (endpointChanged || affectedNodeIds.has(edge.sourceId) || affectedNodeIds.has(edge.targetId))) invalidateAuthoritativeEdgePath(edge);
8596
8922
  }
8597
8923
  commitGraph(draft, transactionOptions);
8924
+ if (activeTransaction) {
8925
+ const surviving = new Set([...draft.nodes, ...draft.edges].map((entity) => entity.id));
8926
+ for (const entity of [...previous.nodes, ...previous.edges]) if (!surviving.has(entity.id)) activeTransaction.removedEntityIds.add(entity.id);
8927
+ }
8598
8928
  return result;
8599
8929
  }
8600
8930
  function pointsEqual(previous, next) {
@@ -8661,8 +8991,153 @@ function createFlow(options = {}) {
8661
8991
  ...input
8662
8992
  };
8663
8993
  }
8994
+ function validateGeometry(value, keys = Object.keys(value)) {
8995
+ for (const key of keys) {
8996
+ const number = Reflect.get(value, key);
8997
+ if (!Number.isFinite(number) || (key === "width" || key === "height") && number < 0) throw new TypeError("Geometry must contain finite coordinates and nonnegative sizes.");
8998
+ }
8999
+ }
9000
+ function settled(value, geometryOptions) {
9001
+ return normalizeGeometryPosition(value, geometryOptions?.positionPrecision);
9002
+ }
9003
+ function sizeNode(node, size) {
9004
+ const { measured: _measured, ...authored } = node;
9005
+ return {
9006
+ ...authored,
9007
+ width: size.width,
9008
+ height: size.height,
9009
+ style: {
9010
+ ...node.style,
9011
+ customWidth: size.width,
9012
+ customHeight: size.height
9013
+ }
9014
+ };
9015
+ }
9016
+ function measurementId(id) {
9017
+ const ref = engine.getEntityRef(id);
9018
+ return ref?.kind === "port" ? `${ref.nodeId}:${ref.portName}` : id;
9019
+ }
9020
+ const measurements = {
9021
+ update(batch) {
9022
+ for (const { rect } of batch) validateGeometry(rect, [
9023
+ "x",
9024
+ "y",
9025
+ "width",
9026
+ "height"
9027
+ ]);
9028
+ store.trigger.updateMeasurements({
9029
+ measurements: batch.map(({ id, rect }) => {
9030
+ const ref = engine.getEntityRef(id);
9031
+ const origin = ref?.kind === "port" ? engine.visualBounds(ref.nodeId) : void 0;
9032
+ return {
9033
+ id: measurementId(id),
9034
+ rect: { ...rect },
9035
+ ...origin ? { origin: {
9036
+ x: origin.x,
9037
+ y: origin.y
9038
+ } } : {}
9039
+ };
9040
+ }),
9041
+ derivedOnly: true
9042
+ });
9043
+ },
9044
+ remove(ids) {
9045
+ store.trigger.removeMeasurements({
9046
+ ids: ids.map(measurementId),
9047
+ derivedOnly: true
9048
+ });
9049
+ },
9050
+ get(id) {
9051
+ const rect = store.getSnapshot().context.measurements.get(measurementId(id));
9052
+ return rect ? { ...rect } : void 0;
9053
+ }
9054
+ };
8664
9055
  function createNodeApi() {
8665
9056
  return {
9057
+ move: (id, position, geometryOptions) => {
9058
+ validateGeometry(position, ["x", "y"]);
9059
+ assertCommandAllowed("move", { id });
9060
+ return mutateGraph((graph) => {
9061
+ const node = graph.nodes.find((candidate) => candidate.id === id);
9062
+ if (!node) throw new Error(`Node "${id}" does not exist.`);
9063
+ const context = store.getSnapshot().context;
9064
+ const grid = context.snapToGrid ? context.snapGrid : null;
9065
+ const x = settled(grid ? Math.round(position.x / grid[0]) * grid[0] : position.x, geometryOptions);
9066
+ const y = settled(grid ? Math.round(position.y / grid[1]) * grid[1] : position.y, geometryOptions);
9067
+ const plan = planNodeMovement({
9068
+ ...context,
9069
+ graph,
9070
+ selection: /* @__PURE__ */ new Set([id])
9071
+ }, x - node.x - (node.dx ?? 0), y - node.y - (node.dy ?? 0));
9072
+ if (plan) {
9073
+ for (const [index, delta] of plan.nodeDeltasByIndex) {
9074
+ const moved = graph.nodes[index];
9075
+ moved.x = settled(moved.x + (moved.dx ?? 0) + delta.x, geometryOptions);
9076
+ moved.y = settled(moved.y + (moved.dy ?? 0) + delta.y, geometryOptions);
9077
+ moved.dx = 0;
9078
+ moved.dy = 0;
9079
+ }
9080
+ for (const [index, delta] of plan.edgeDeltasByIndex) {
9081
+ const edge = graph.edges[index];
9082
+ edge.waypoints = edge.waypoints?.map((point) => ({
9083
+ x: point.x + delta.x,
9084
+ y: point.y + delta.y
9085
+ }));
9086
+ }
9087
+ for (const [index, delta] of plan.labelDeltasByIndex) {
9088
+ const label = graph.edges[index].label;
9089
+ if (label) {
9090
+ label.x += delta.x;
9091
+ label.y += delta.y;
9092
+ }
9093
+ }
9094
+ }
9095
+ return node;
9096
+ }, geometryOptions);
9097
+ },
9098
+ resize: (id, bounds, geometryOptions) => {
9099
+ validateGeometry(bounds, [
9100
+ "x",
9101
+ "y",
9102
+ "width",
9103
+ "height"
9104
+ ]);
9105
+ assertCommandAllowed("resize", { id });
9106
+ return createNodeApi().update(id, (node) => {
9107
+ const moving = clampResizeMovingPoint(node, "bottom-right", {
9108
+ x: 0,
9109
+ y: 0
9110
+ }, {
9111
+ x: bounds.width,
9112
+ y: bounds.height
9113
+ });
9114
+ return {
9115
+ ...sizeNode(node, {
9116
+ width: moving.x,
9117
+ height: moving.y
9118
+ }),
9119
+ x: settled(bounds.x, geometryOptions),
9120
+ y: settled(bounds.y, geometryOptions),
9121
+ dx: 0,
9122
+ dy: 0
9123
+ };
9124
+ }, geometryOptions);
9125
+ },
9126
+ setContentSize: (id, size, geometryOptions) => {
9127
+ validateGeometry(size, ["width", "height"]);
9128
+ if (store.getSnapshot().context.mode === "readonly" || policyValue("canEdit") === false) throw new Error("Flow content sizing is not allowed: readonly.");
9129
+ const position = geometryOptions?.position;
9130
+ if (position) validateGeometry(position, ["x", "y"]);
9131
+ return createNodeApi().update(id, (node) => ({
9132
+ ...sizeNode(node, size),
9133
+ ...position ? {
9134
+ x: settled(position.x, geometryOptions),
9135
+ y: settled(position.y, geometryOptions),
9136
+ dx: 0,
9137
+ dy: 0
9138
+ } : {}
9139
+ }), geometryOptions);
9140
+ },
8666
9141
  create: (input, transactionOptions) => {
8667
9142
  assertCommandAllowed("create");
8668
9143
  const id = resolveId(input.id, {
@@ -8743,7 +9218,6 @@ function createFlow(options = {}) {
8743
9218
  ...withDefaults,
8744
9219
  id
8745
9220
  });
8746
- if (!activeTransaction && !engine.validateConnection(edge)) throw new Error(`Connection for edge "${edge.id}" is not allowed.`);
8747
9221
  mutateGraph((graph) => graph.edges.push(edge), transactionOptions);
8748
9222
  return edge;
8749
9223
  },
@@ -8790,10 +9264,9 @@ function createFlow(options = {}) {
8790
9264
  ...edge,
8791
9265
  sourceId: patch.newSourceId ?? edge.sourceId,
8792
9266
  targetId: patch.newTargetId ?? edge.targetId,
8793
- sourcePort: patch.newSourcePort ?? edge.sourcePort,
8794
- targetPort: patch.newTargetPort ?? edge.targetPort
9267
+ sourcePort: patch.newSourcePort === void 0 ? edge.sourcePort : patch.newSourcePort,
9268
+ targetPort: patch.newTargetPort === void 0 ? edge.targetPort : patch.newTargetPort
8795
9269
  };
8796
- if (!activeTransaction && !engine.validateConnection(proposed)) throw new Error(`Connection for edge "${edgeId}" is not allowed.`);
8797
9270
  return createEdgeApi().update(edgeId, proposed, transactionOptions);
8798
9271
  }
8799
9272
  };
@@ -9144,6 +9617,7 @@ function createFlow(options = {}) {
9144
9617
  }
9145
9618
  function check(command, input) {
9146
9619
  if ([
9620
+ "edit",
9147
9621
  "create",
9148
9622
  "move",
9149
9623
  "resize",
@@ -9214,7 +9688,7 @@ function createFlow(options = {}) {
9214
9688
  };
9215
9689
  const flag = command === "delete" || command === "cut" ? "deletable" : command === "move" ? "draggable" : command === "resize" ? "resizable" : command === "connect" || command === "reconnect" ? "connectable" : command === "select" ? "selectable" : null;
9216
9690
  if (flag && ids.some((id) => {
9217
- const entity = engine.getEntity(id);
9691
+ const entity = currentGraph().nodes.find((node) => node.id === id) ?? engine.getEntity(id);
9218
9692
  return entity && !engine.resolveEntityConfig(entity)[flag];
9219
9693
  })) return {
9220
9694
  allowed: false,
@@ -9280,14 +9754,30 @@ function createFlow(options = {}) {
9280
9754
  }
9281
9755
  }
9282
9756
  };
9757
+ function assertTransactionOptions(next) {
9758
+ if (next?.history !== void 0 && next.history !== "record" && next.history !== "ignore") throw new TypeError("Transaction history must be \"record\" or \"ignore\".");
9759
+ if (!activeTransaction || !next) return;
9760
+ const outer = activeTransaction.options;
9761
+ for (const key of [
9762
+ "history",
9763
+ "origin",
9764
+ "transactionId"
9765
+ ]) {
9766
+ const inherited = key === "history" ? outer?.history ?? "record" : outer?.[key];
9767
+ if (next[key] !== void 0 && next[key] !== inherited) throw new Error(`Nested transaction cannot override ${key}.`);
9768
+ }
9769
+ }
9283
9770
  function transaction(callback, transactionOptions) {
9771
+ assertTransactionOptions(transactionOptions);
9284
9772
  const nested = activeTransaction !== null;
9285
9773
  const previousGraph = nested ? validateAndCloneGraph(activeTransaction.graph, options.dataSchemas) : null;
9286
9774
  const previousAuthoredEdgeRouteIds = nested ? new Set(activeTransaction.authoredEdgeRouteIds) : null;
9775
+ const previousRemovedEntityIds = nested ? new Set(activeTransaction.removedEntityIds) : null;
9287
9776
  if (!nested) activeTransaction = {
9288
9777
  graph: validateAndCloneGraph(currentGraph(), options.dataSchemas),
9289
9778
  options: transactionOptions,
9290
- authoredEdgeRouteIds: /* @__PURE__ */ new Set()
9779
+ authoredEdgeRouteIds: /* @__PURE__ */ new Set(),
9780
+ removedEntityIds: /* @__PURE__ */ new Set()
9291
9781
  };
9292
9782
  const transactionState = activeTransaction;
9293
9783
  let draftOpen = true;
@@ -9296,6 +9786,21 @@ function createFlow(options = {}) {
9296
9786
  };
9297
9787
  const { collapse: _collapse, expand: _expand, ...draftNodes } = nodes;
9298
9788
  const draft = {
9789
+ getNode: (id) => {
9790
+ assertDraftOpen();
9791
+ const node = currentGraph().nodes.find((candidate) => candidate.id === id);
9792
+ return node ? cloneJsonSafe(node) : void 0;
9793
+ },
9794
+ getEdge: (id) => {
9795
+ assertDraftOpen();
9796
+ const edge = currentGraph().edges.find((candidate) => candidate.id === id);
9797
+ return edge ? cloneJsonSafe(edge) : void 0;
9798
+ },
9799
+ getNodeBounds: (id) => {
9800
+ assertDraftOpen();
9801
+ const node = currentGraph().nodes.find((candidate) => candidate.id === id);
9802
+ return node ? resolvedBounds(node) : void 0;
9803
+ },
9299
9804
  nodes: scopedTransactionApi(draftNodes, assertDraftOpen),
9300
9805
  edges: scopedTransactionApi(edges, assertDraftOpen)
9301
9806
  };
@@ -9308,16 +9813,19 @@ function createFlow(options = {}) {
9308
9813
  changeSet: null
9309
9814
  };
9310
9815
  const next = activeTransaction.graph;
9816
+ const surviving = new Set([...next.nodes, ...next.edges].map((entity) => entity.id));
9817
+ const resetMeasurementIds = [...activeTransaction.removedEntityIds].filter((id) => surviving.has(id));
9311
9818
  activeTransaction = null;
9312
9819
  return {
9313
9820
  value,
9314
- changeSet: commitGraph(next, transactionOptions)
9821
+ changeSet: commitGraph(next, transactionOptions, void 0, void 0, resetMeasurementIds)
9315
9822
  };
9316
9823
  } catch (error) {
9317
9824
  draftOpen = false;
9318
9825
  if (nested) {
9319
9826
  activeTransaction.graph = previousGraph;
9320
9827
  activeTransaction.authoredEdgeRouteIds = previousAuthoredEdgeRouteIds;
9828
+ activeTransaction.removedEntityIds = previousRemovedEntityIds;
9321
9829
  } else activeTransaction = null;
9322
9830
  throw error;
9323
9831
  }
@@ -9333,7 +9841,8 @@ function createFlow(options = {}) {
9333
9841
  ok: true,
9334
9842
  value: commitGraph(result.value, {
9335
9843
  origin: applyOptions.origin ?? "applyChangeSet",
9336
- transactionId: applyOptions.transactionId
9844
+ transactionId: applyOptions.transactionId,
9845
+ history: applyOptions.history
9337
9846
  })
9338
9847
  };
9339
9848
  } catch (error) {
@@ -9348,6 +9857,13 @@ function createFlow(options = {}) {
9348
9857
  }
9349
9858
  }
9350
9859
  const on = ((type, listener) => {
9860
+ if (type === "destroy") {
9861
+ const destroyListener = listener;
9862
+ if (!destroyed) destroyListeners.add(destroyListener);
9863
+ return { unsubscribe: () => {
9864
+ destroyListeners.delete(destroyListener);
9865
+ } };
9866
+ }
9351
9867
  if (type === "commit") {
9352
9868
  commitListeners.add(listener);
9353
9869
  return { unsubscribe: () => {
@@ -9377,11 +9893,16 @@ function createFlow(options = {}) {
9377
9893
  });
9378
9894
  return () => subscription.unsubscribe();
9379
9895
  });
9380
- return {
9896
+ const controller = {
9381
9897
  internals: {
9382
9898
  store,
9383
9899
  engine
9384
9900
  },
9901
+ beginExternalEdit: (editOptions) => {
9902
+ if (destroyed) throw new Error("Flow controller is destroyed.");
9903
+ return createFlowExternalEdit(controller, editOptions);
9904
+ },
9905
+ subscribeRender: (listener) => renderApi.subscribe(listener),
9385
9906
  on,
9386
9907
  destroy,
9387
9908
  getContext: engine.getContext,
@@ -9420,6 +9941,7 @@ function createFlow(options = {}) {
9420
9941
  set: (mode) => store.trigger.setMode({ mode })
9421
9942
  },
9422
9943
  nodes,
9944
+ measurements,
9423
9945
  edges,
9424
9946
  selection,
9425
9947
  view,
@@ -9431,6 +9953,8 @@ function createFlow(options = {}) {
9431
9953
  connections,
9432
9954
  content
9433
9955
  };
9956
+ const renderApi = createFlowRenderApi(controller);
9957
+ return controller;
9434
9958
  }
9435
9959
  /**
9436
9960
  * Parse a persisted Flow document and create a controller from it.
@@ -9678,12 +10202,23 @@ function keyboardMode(options = {}) {
9678
10202
  if (event.kind !== "key.down") return null;
9679
10203
  if (event.editableTarget) return null;
9680
10204
  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")] };
10205
+ if (matchesKeyBinding(event, keymap.cancel)) {
10206
+ const commands = [trigger("cancelConnection"), trigger("resizeCancel")];
10207
+ if (context.canvasState === "idle" && !context.connection && !context.connectionClickStartHandle) switch (options.escapeSelection ?? "all") {
10208
+ case "all":
10209
+ commands.push(trigger("clearSelection"), trigger("clearFocus"));
10210
+ break;
10211
+ case "focused":
10212
+ if (context.focusedEntityId && context.selection.has(context.focusedEntityId)) commands.push(trigger("select", {
10213
+ ids: [...context.selection].filter((id) => id !== context.focusedEntityId),
10214
+ mode: "single"
10215
+ }));
10216
+ commands.push(trigger("clearFocus"));
10217
+ break;
10218
+ case "none": break;
10219
+ }
10220
+ return { commands };
10221
+ }
9687
10222
  if (matchesKeyBinding(event, keymap.redo)) return { commands: [preventDefault$1, trigger("redo")] };
9688
10223
  if (matchesKeyBinding(event, keymap.undo)) return { commands: [preventDefault$1, trigger("undo")] };
9689
10224
  if (matchesKeyBinding(event, keymap.selectAll)) return { commands: [preventDefault$1, trigger("selectAll")] };
@@ -9718,16 +10253,27 @@ function keyboardNavMode(options = {}) {
9718
10253
  const step = options.step ?? 5;
9719
10254
  const shiftStep = options.shiftStep ?? 20;
9720
10255
  const keymap = resolveKeymap(options.keymap);
10256
+ const activationKeys = options.activationKeys === void 0 ? [
10257
+ "Enter",
10258
+ " ",
10259
+ "Spacebar"
10260
+ ] : options.activationKeys;
9721
10261
  return {
9722
10262
  id: "keyboard-nav",
9723
10263
  priority: 95,
9724
- start(event, { context }) {
10264
+ start(event, { context, engine }) {
9725
10265
  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
- })] };
10266
+ if (activationKeys?.includes(event.key) && context.focusedEntityId) {
10267
+ const multiSelect = matchesMultiSelect(event.modifiers, keymap);
10268
+ const commands = options.preventDefault === false ? [] : [preventDefault$1];
10269
+ if (multiSelect || options.selectionBehavior !== "preserve" || !context.selection.has(context.focusedEntityId)) commands.push(trigger("select", {
10270
+ ids: [context.focusedEntityId],
10271
+ mode: multiSelect ? "multi" : "single"
10272
+ }));
10273
+ return { commands };
10274
+ }
9730
10275
  if (!allowMove) return null;
10276
+ if (options.nudge === "focused-selection" && (!context.focusedEntityId || !context.selection.has(context.focusedEntityId) || !engine.getNode(context.focusedEntityId))) return null;
9731
10277
  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
10278
  if (!direction || context.selection.size === 0) return null;
9733
10279
  return { commands: [
@@ -9824,36 +10370,40 @@ function pinchMode() {
9824
10370
  return {
9825
10371
  id: "pinch",
9826
10372
  priority: 85,
9827
- start(event) {
10373
+ start(event, { context }) {
9828
10374
  if (event.kind !== "pinch.start") return null;
9829
10375
  return {
9830
10376
  commands: [preventDefault$1],
9831
- session: pinchSession(event)
10377
+ session: pinchSession(event, context.viewport)
9832
10378
  };
9833
10379
  }
9834
10380
  };
9835
10381
  }
9836
- function pinchSession(down) {
9837
- let lastDistance = down.distance || 1;
9838
- let lastCenter = down.screenCenter;
10382
+ function pinchSession(down, viewport) {
10383
+ let initialDistance = down.distance > 0 ? down.distance : null;
10384
+ const anchor = {
10385
+ x: (down.screenCenter.x - viewport.x) / viewport.zoom,
10386
+ y: (down.screenCenter.y - viewport.y) / viewport.zoom
10387
+ };
9839
10388
  return {
9840
- update(event) {
10389
+ update(event, { context }) {
9841
10390
  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
10391
+ if (initialDistance === null && event.distance > 0) initialDistance = event.distance;
10392
+ const zoom = initialDistance !== null ? Math.max(context.minZoom, Math.min(context.maxZoom, viewport.zoom * event.distance / initialDistance)) : context.viewport.zoom;
10393
+ const center = {
10394
+ x: context.viewport.x + anchor.x * context.viewport.zoom,
10395
+ y: context.viewport.y + anchor.y * context.viewport.zoom
9847
10396
  };
9848
- lastDistance = distance;
9849
- lastCenter = event.screenCenter;
9850
10397
  return { commands: [
9851
10398
  preventDefault$1,
9852
- trigger("zoomBy", {
9853
- factor,
9854
- center: event.screenCenter
10399
+ trigger("zoomTo", {
10400
+ zoom,
10401
+ center
9855
10402
  }),
9856
- trigger("panBy", delta)
10403
+ trigger("panBy", {
10404
+ x: event.screenCenter.x - center.x,
10405
+ y: event.screenCenter.y - center.y
10406
+ })
9857
10407
  ] };
9858
10408
  }
9859
10409
  if (event.kind === "pinch.end") return {
@@ -10148,7 +10698,24 @@ function connectMode(options = {}) {
10148
10698
  return {
10149
10699
  id: "connect",
10150
10700
  priority: 60,
10151
- start(event, { engine }) {
10701
+ start(event, ctx) {
10702
+ const { engine, context } = ctx;
10703
+ const pending = context.connectionClickStartHandle;
10704
+ if (pending && context.connection) {
10705
+ if (!context.connectOnClick || event.kind === "pointer.cancel") return { commands: [trigger("cancelConnection")] };
10706
+ if (pending.port === null) return { commands: [trigger("cancelConnection")] };
10707
+ const source = {
10708
+ nodeId: pending.nodeId,
10709
+ port: pending.port
10710
+ };
10711
+ if (event.kind === "pointer.move") return { commands: [connectionMoveCommand(resolveConnectionTarget(event, source, ctx, options.isValid), true)] };
10712
+ if (event.kind !== "pointer.down" || event.button !== 0) return null;
10713
+ const target = event.target;
10714
+ const completesOnPort = target.kind === "port" && target.interaction !== "inspect" && (target.nodeId !== source.nodeId || target.portName !== source.port);
10715
+ const completesOnNode = target.kind === "entity" && target.id !== source.nodeId && engine.getNode(target.id) !== void 0;
10716
+ if (!completesOnPort && !completesOnNode) return { commands: [trigger("cancelConnection")] };
10717
+ return { session: connectSession(source, options, { kind: "completing" }) };
10718
+ }
10152
10719
  if (event.kind !== "pointer.down" || event.button !== 0) return null;
10153
10720
  if (event.target.kind !== "port") return null;
10154
10721
  if (event.target.interaction === "inspect") return null;
@@ -10166,7 +10733,10 @@ function connectMode(options = {}) {
10166
10733
  session: connectSession({
10167
10734
  nodeId,
10168
10735
  port: portName
10169
- }, options)
10736
+ }, options, {
10737
+ kind: "pressed",
10738
+ screenPoint: event.screenPoint
10739
+ })
10170
10740
  };
10171
10741
  }
10172
10742
  };
@@ -10213,12 +10783,12 @@ function defaultConnectionValidityDetailed(args, ctx) {
10213
10783
  valid: false,
10214
10784
  reason: "same-node"
10215
10785
  };
10216
- return ctx.engine.validateConnectionDetailed({
10786
+ return ctx.engine.validateConnectionDetailed(normalizeConnection({
10217
10787
  sourceId: source.nodeId,
10218
10788
  sourcePort: source.port,
10219
10789
  targetId: target.nodeId,
10220
10790
  targetPort: target.portName
10221
- });
10791
+ }, ctx.context.graph));
10222
10792
  }
10223
10793
  if (target.kind === "entity") {
10224
10794
  if (target.id === source.nodeId) return {
@@ -10234,12 +10804,12 @@ function defaultConnectionValidityDetailed(args, ctx) {
10234
10804
  valid: false,
10235
10805
  reason: "outside-connection-radius"
10236
10806
  };
10237
- return ctx.engine.validateConnectionDetailed({
10807
+ return ctx.engine.validateConnectionDetailed(normalizeConnection({
10238
10808
  sourceId: source.nodeId,
10239
10809
  sourcePort: source.port,
10240
10810
  targetId: target.id,
10241
10811
  targetPort: null
10242
- });
10812
+ }, ctx.context.graph));
10243
10813
  }
10244
10814
  return {
10245
10815
  valid: false,
@@ -10296,7 +10866,7 @@ function targetIdsFor(target, ctx) {
10296
10866
  }
10297
10867
  function resolveConnectionTarget(event, source, ctx, isValid) {
10298
10868
  const candidate = ctx.engine.getConnectionCandidate(event.point, { source });
10299
- if (candidate) {
10869
+ if (candidate && (event.target.kind !== "port" || candidate.nodeId === event.target.nodeId && candidate.portName === event.target.portName)) {
10300
10870
  const target = targetFromConnectionCandidate(candidate);
10301
10871
  const validity = isValid ? isValid({
10302
10872
  source,
@@ -10332,24 +10902,39 @@ function resolveConnectionTarget(event, source, ctx, isValid) {
10332
10902
  endTarget: connectEndTargetFor(event.target, event.point, ctx)
10333
10903
  };
10334
10904
  }
10335
- function connectSession(source, options) {
10905
+ function connectionMoveCommand(target, active) {
10906
+ return trigger("connectionMove", {
10907
+ position: target.position,
10908
+ targetId: target.targetId,
10909
+ targetPort: target.targetPort,
10910
+ isValid: target.isValid,
10911
+ invalidReason: target.invalidReason,
10912
+ ...active === void 0 ? {} : { active }
10913
+ });
10914
+ }
10915
+ function connectSession(source, options, phase) {
10336
10916
  return {
10337
10917
  update(event, ctx) {
10338
10918
  if (!ctx.context.connection) return { status: "end" };
10339
10919
  if (event.kind === "pointer.move") {
10340
10920
  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
- })] };
10921
+ const travel = phase.kind === "pressed" ? distance(phase.screenPoint, event.screenPoint) : 0;
10922
+ return { commands: [connectionMoveCommand(target, ctx.context.connection.active || phase.kind === "completing" || travel > 0 && travel >= ctx.context.connectionDragThreshold)] };
10923
+ }
10924
+ if (event.kind === "pointer.up") {
10925
+ 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 {
10926
+ commands: [trigger("setConnectionClickStartHandle", source), trigger("connectionMove", {
10927
+ position: event.point,
10928
+ active: true
10929
+ })],
10930
+ status: "end"
10931
+ };
10932
+ const target = resolveConnectionTarget(event, source, ctx, options.isValid);
10933
+ return {
10934
+ commands: [connectionMoveCommand(target), trigger("connectionEnd", { target: target.endTarget })],
10935
+ status: "end"
10936
+ };
10348
10937
  }
10349
- if (event.kind === "pointer.up") return {
10350
- commands: [trigger("connectionEnd", { target: resolveConnectionTarget(event, source, ctx, options.isValid).endTarget })],
10351
- status: "end"
10352
- };
10353
10938
  if (event.kind === "pointer.cancel") return {
10354
10939
  commands: [trigger("cancelConnection")],
10355
10940
  status: "end"
@@ -10808,6 +11393,14 @@ function createFlowInputRuntime(options) {
10808
11393
  if (name === "setHover" && policies.canHover === false) return false;
10809
11394
  return true;
10810
11395
  }
11396
+ function cancelPendingConnection(previous) {
11397
+ const current = store.getSnapshot().context;
11398
+ if (previous.connectionClickStartHandle && current.connectionClickStartHandle === previous.connectionClickStartHandle && (previous.connection?.[connectionLifetime] ? current.connection?.[connectionLifetime] === previous.connection[connectionLifetime] : current.connection === previous.connection)) store.trigger.cancelConnection();
11399
+ }
11400
+ function reconcileModes() {
11401
+ const context = store.getSnapshot().context;
11402
+ if (!session && context.connectionClickStartHandle && !resolveModes(context).some((mode) => mode.id === "connect")) store.trigger.cancelConnection();
11403
+ }
10811
11404
  function send(event) {
10812
11405
  const effects = {
10813
11406
  preventDefault: false,
@@ -10817,11 +11410,13 @@ function createFlowInputRuntime(options) {
10817
11410
  handledBy: null
10818
11411
  };
10819
11412
  if (session && event.kind === "key.down" && !event.editableTarget && matchesKeyBinding(event, keymap.cancel)) {
11413
+ const previous = store.getSnapshot().context;
10820
11414
  const commands = session.handlers.cancel?.(modeContext());
10821
11415
  effects.handledBy = session.modeId;
10822
11416
  effects.sessionEnded = true;
10823
11417
  session = null;
10824
11418
  apply(commands ?? void 0, effects);
11419
+ cancelPendingConnection(previous);
10825
11420
  return effects;
10826
11421
  }
10827
11422
  if (event.kind === "key.down" && !event.editableTarget && matchesKeyBinding(event, keymap.panActivation)) {
@@ -10881,7 +11476,11 @@ function createFlowInputRuntime(options) {
10881
11476
  return effects;
10882
11477
  }
10883
11478
  function cancelSession() {
10884
- if (!session) return;
11479
+ const previous = store.getSnapshot().context;
11480
+ if (!session) {
11481
+ cancelPendingConnection(previous);
11482
+ return;
11483
+ }
10885
11484
  const effects = {
10886
11485
  preventDefault: false,
10887
11486
  stopPropagation: false,
@@ -10892,9 +11491,11 @@ function createFlowInputRuntime(options) {
10892
11491
  const commands = session.handlers.cancel?.(modeContext());
10893
11492
  session = null;
10894
11493
  apply(commands ?? void 0, effects);
11494
+ cancelPendingConnection(previous);
10895
11495
  }
10896
11496
  return {
10897
11497
  send,
11498
+ reconcileModes,
10898
11499
  cancelSession,
10899
11500
  getActiveSession: () => session?.modeId ?? null
10900
11501
  };