@statelyai/flow 0.10.0 → 0.12.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
@@ -1,6 +1,6 @@
1
1
  import { createStore } from "@xstate/store";
2
2
  import { undoRedo } from "@xstate/store/undo";
3
- import { current, enableMapSet, isDraft, produce } from "immer";
3
+ import { castDraft, current, enableMapSet, isDraft, produce } from "immer";
4
4
  import { getPatches } from "@statelyai/graph";
5
5
  //#region src/marker.ts
6
6
  const BUILT_IN_MARKERS = /* @__PURE__ */ new Set([
@@ -147,6 +147,58 @@ function toDecorationArray(value) {
147
147
  return Array.isArray(value) ? [...value] : [value];
148
148
  }
149
149
  //#endregion
150
+ //#region src/appearances.ts
151
+ const appearanceSides = [
152
+ "top",
153
+ "right",
154
+ "bottom",
155
+ "left"
156
+ ];
157
+ function resolveAppearance(entity, appearances = {}) {
158
+ const reference = entity.appearance ?? appearances.defaults?.["type" in entity ? "node" : "edgeLabel"];
159
+ const definition = reference && Object.prototype.hasOwnProperty.call(appearances.definitions ?? {}, reference.name) ? appearances.definitions?.[reference.name] : void 0;
160
+ const policy = typeof definition === "function" ? definition({
161
+ entity,
162
+ options: reference?.options ?? {}
163
+ }) : definition ?? {};
164
+ return {
165
+ ...policy,
166
+ reference,
167
+ registered: definition !== void 0,
168
+ renderer: definition ? policy.renderer ?? reference?.name : void 0,
169
+ autoSize: entity.autoSize ?? policy.sizing === "content",
170
+ connectionBounds: policy.connection?.bounds && !("selector" in policy.connection.bounds) ? policy.connection.bounds : policy.connection?.bounds ? void 0 : policy.connectionBounds,
171
+ connectionSelector: policy.connection?.bounds && "selector" in policy.connection.bounds ? policy.connection.bounds.selector : void 0,
172
+ sides: policy.connection?.sides ?? policy.sides ?? appearanceSides,
173
+ ports: policy.connection?.ports ?? policy.ports
174
+ };
175
+ }
176
+ /** Keyed by authored reference, so stale local measurements cannot follow appearance switches. */
177
+ function appearanceMeasurementId(id, appearance) {
178
+ return JSON.stringify([
179
+ "flow-appearance-boundary",
180
+ id,
181
+ appearance.reference ?? null,
182
+ appearance.connectionSelector ?? null
183
+ ]);
184
+ }
185
+ function appearanceAllowsPort(node, portName, appearance) {
186
+ const port = node.ports?.find((candidate) => candidate.name === portName);
187
+ const side = port?.side;
188
+ return !!port && (side ? appearance.sides.includes(side) : appearance.sides.length === 4) && (!appearance.ports || appearance.ports.includes(portName));
189
+ }
190
+ /** Preserve the usual facing side; otherwise choose the closest permitted side anchor. */
191
+ function appearanceDirection(bounds, other, preferred, sides) {
192
+ if (sides.includes(preferred)) return preferred;
193
+ const cx = other.x + other.width / 2, cy = other.y + other.height / 2;
194
+ const distance = (side) => {
195
+ const x = side === "left" ? bounds.x : side === "right" ? bounds.x + bounds.width : bounds.x + bounds.width / 2;
196
+ const y = side === "top" ? bounds.y : side === "bottom" ? bounds.y + bounds.height : bounds.y + bounds.height / 2;
197
+ return Math.hypot(cx - x, cy - y);
198
+ };
199
+ return sides.reduce((best, side) => distance(side) < distance(best) ? side : best, sides[0] ?? preferred);
200
+ }
201
+ //#endregion
150
202
  //#region src/profile.ts
151
203
  function defineFlowProfile(profile) {
152
204
  return profile;
@@ -545,9 +597,11 @@ const resolvedPosition = visualPosition;
545
597
  * Authored `width/height` are never mutated — measured size lives on
546
598
  * `node.measured`, so this is the single place that reconciles the two. */
547
599
  function resolvedSize(node) {
600
+ const measuredAppearance = node.measured?.appearanceKey !== void 0 && node.measured.appearanceKey === JSON.stringify(node.appearance ?? null);
601
+ const autoSize = node.autoSize ?? (measuredAppearance && node.measured?.appearanceAutoSize);
548
602
  return {
549
- width: node.style?.customWidth ?? (node.autoSize ? node.measured?.width ?? node.width : node.width),
550
- height: node.style?.customHeight ?? (node.autoSize ? node.measured?.height ?? node.height : node.height)
603
+ width: node.style?.customWidth ?? (autoSize ? node.measured?.width ?? node.width : node.width),
604
+ height: node.style?.customHeight ?? (autoSize ? node.measured?.height ?? node.height : node.height)
551
605
  };
552
606
  }
553
607
  function visualBounds(node) {
@@ -2289,6 +2343,15 @@ function validateEdgeData(edge, index, schemas, issues) {
2289
2343
  edge.label.data = validateData(edge.label.data, schemas?.label, `$.graph.edges[${index}].label.data`, issues);
2290
2344
  }
2291
2345
  }
2346
+ function validateAppearance(value, path, issues) {
2347
+ if (value === void 0) return;
2348
+ if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.name !== "string" || !value.name.length) {
2349
+ issue(issues, "invalid_appearance", path, "expected an appearance with a non-empty name");
2350
+ return;
2351
+ }
2352
+ const options = value.options;
2353
+ if (options !== void 0 && (!options || typeof options !== "object" || Array.isArray(options))) issue(issues, "invalid_appearance", `${path}.options`, "expected an options object");
2354
+ }
2292
2355
  function validateAndCloneGraph(input, schemas) {
2293
2356
  const issues = [];
2294
2357
  const cloned = cloneJsonValue(input, "$.graph", issues, /* @__PURE__ */ new Set());
@@ -2315,6 +2378,7 @@ function validateAndCloneGraph(input, schemas) {
2315
2378
  nodesById.set(node.id, node);
2316
2379
  }
2317
2380
  validateFiniteGeometry(node, path, issues);
2381
+ validateAppearance(node.appearance, `${path}.appearance`, issues);
2318
2382
  validateAutoSizeAnchor(node.autoSizeAnchor, `${path}.autoSizeAnchor`, issues);
2319
2383
  validateNodeData(node, index, schemas?.node, issues);
2320
2384
  if (node.ports !== void 0) {
@@ -2361,6 +2425,7 @@ function validateAndCloneGraph(input, schemas) {
2361
2425
  const node = nodesById.get(nodeId);
2362
2426
  if (!Array.isArray(node?.ports) || !node.ports.some((port) => !!port && typeof port === "object" && !Array.isArray(port) && port.name === portName)) issue(issues, "missing_port", `${path}.${key}`, `port "${portName}" does not exist on node "${nodeId}"`);
2363
2427
  }
2428
+ if (edge.label && typeof edge.label === "object") validateAppearance(edge.label.appearance, `${path}.label.appearance`, issues);
2364
2429
  if (edge.label && typeof edge.label === "object" && !Array.isArray(edge.label)) validateFiniteGeometry(edge.label, `${path}.label`, issues);
2365
2430
  if (edge.waypoints !== void 0) if (!Array.isArray(edge.waypoints)) issue(issues, "invalid_waypoints", `${path}.waypoints`, "expected an array");
2366
2431
  else edge.waypoints.forEach((point, pointIndex) => {
@@ -2448,6 +2513,7 @@ function invalidateAuthoritativeEdgePath(edge) {
2448
2513
  }
2449
2514
  /** Whether a node mutation changes any position an incident edge can anchor to. */
2450
2515
  function nodeEndpointGeometryChanged(previous, next) {
2516
+ if (JSON.stringify(previous.appearance) !== JSON.stringify(next.appearance)) return true;
2451
2517
  const previousBounds = resolvedBounds(previous);
2452
2518
  const nextBounds = resolvedBounds(next);
2453
2519
  if (previousBounds.x !== nextBounds.x || previousBounds.y !== nextBounds.y || previousBounds.width !== nextBounds.width || previousBounds.height !== nextBounds.height) return true;
@@ -3230,6 +3296,7 @@ function createFlowStore(initialGraph = {
3230
3296
  const initialMode = getMode(profile, options.mode ?? profile.defaultMode);
3231
3297
  const initialContext = {
3232
3298
  graph: validatedInitialGraph,
3299
+ appearances: options.appearances,
3233
3300
  parentNodeId: null,
3234
3301
  depth: null,
3235
3302
  viewport: createViewport(),
@@ -3367,7 +3434,15 @@ function createFlowStore(initialGraph = {
3367
3434
  });
3368
3435
  return;
3369
3436
  }
3370
- draft.graph.nodes[index] = next;
3437
+ draft.graph.nodes[index] = { ...next };
3438
+ if (JSON.stringify(previous.appearance) !== JSON.stringify(next.appearance)) {
3439
+ draft.measurements.delete(appearanceMeasurementId(previous.id, resolveAppearance(previous, ctx.appearances)));
3440
+ const node = draft.graph.nodes[index];
3441
+ node.x -= previous.measured?.anchorOffset?.x ?? 0;
3442
+ node.y -= previous.measured?.anchorOffset?.y ?? 0;
3443
+ delete node.measured;
3444
+ draft.measurements.delete(node.id);
3445
+ }
3371
3446
  if (nodeEndpointGeometryChanged(previous, next)) invalidatePathsForNodeGeometry(draft, /* @__PURE__ */ new Set([event.id]));
3372
3447
  enqueue.emit.graphChanged({
3373
3448
  graph: snapshotGraph(draft.graph),
@@ -3473,6 +3548,11 @@ function createFlowStore(initialGraph = {
3473
3548
  return;
3474
3549
  }
3475
3550
  draft.graph.edges[index] = next;
3551
+ if (JSON.stringify(previous.label?.appearance) !== JSON.stringify(next.label?.appearance)) {
3552
+ if (previous.label) draft.measurements.delete(appearanceMeasurementId(previous.id, resolveAppearance(previous.label, ctx.appearances)));
3553
+ draft.measurements.delete(previous.id);
3554
+ invalidateAuthoritativeEdgePath(draft.graph.edges[index]);
3555
+ }
3476
3556
  enqueue.emit.graphChanged({
3477
3557
  graph: snapshotGraph(draft.graph),
3478
3558
  event: createEventObject("updateEdge", event)
@@ -3551,7 +3631,25 @@ function createFlowStore(initialGraph = {
3551
3631
  },
3552
3632
  replaceGraph: (ctx, event, enqueue) => event.graphChanged === false && event.retention !== "reset" && !event.layoutAnimationOffsets ? ctx : produce(ctx, (draft) => {
3553
3633
  const previousSelection = new Set(draft.selection);
3554
- draft.graph = event.graph;
3634
+ const previousNodes = new Map(ctx.graph.nodes.map((node) => [node.id, node]));
3635
+ const changedAppearances = /* @__PURE__ */ new Set();
3636
+ draft.graph = {
3637
+ ...event.graph,
3638
+ nodes: event.graph.nodes.map((node) => {
3639
+ const previous = previousNodes.get(node.id);
3640
+ if (!previous || JSON.stringify(previous.appearance) === JSON.stringify(node.appearance)) return node;
3641
+ const next = {
3642
+ ...node,
3643
+ x: node.x - (node.measured?.anchorOffset?.x ?? 0),
3644
+ y: node.y - (node.measured?.anchorOffset?.y ?? 0)
3645
+ };
3646
+ delete next.measured;
3647
+ draft.measurements.delete(node.id);
3648
+ changedAppearances.add(node.id);
3649
+ return next;
3650
+ })
3651
+ };
3652
+ if (changedAppearances.size) invalidatePathsForNodeGeometry(draft, changedAppearances);
3555
3653
  draft.layoutAnimation = event.layoutAnimationOffsets?.size ? {
3556
3654
  status: "running",
3557
3655
  offsets: new Map(event.layoutAnimationOffsets)
@@ -3592,11 +3690,15 @@ function createFlowStore(initialGraph = {
3592
3690
  draft.focusedEntityId = draft.focusedEntityId && ids.has(draft.focusedEntityId) ? draft.focusedEntityId : null;
3593
3691
  draft.parentNodeId = draft.parentNodeId && nodeIds.has(draft.parentNodeId) ? draft.parentNodeId : null;
3594
3692
  const measurementIds = new Set(ids);
3595
- for (const node of draft.graph.nodes) for (const port of node.ports ?? []) {
3596
- const portId = port.id;
3597
- if (portId) measurementIds.add(portId);
3598
- measurementIds.add(`${node.id}:${port.name}`);
3693
+ for (const node of draft.graph.nodes) {
3694
+ measurementIds.add(appearanceMeasurementId(node.id, resolveAppearance(node, ctx.appearances)));
3695
+ for (const port of node.ports ?? []) {
3696
+ const portId = port.id;
3697
+ if (portId) measurementIds.add(portId);
3698
+ measurementIds.add(`${node.id}:${port.name}`);
3699
+ }
3599
3700
  }
3701
+ for (const edge of draft.graph.edges) if (edge.label) measurementIds.add(appearanceMeasurementId(edge.id, resolveAppearance(edge.label, ctx.appearances)));
3600
3702
  for (const id of draft.measurements.keys()) if (!measurementIds.has(id)) draft.measurements.delete(id);
3601
3703
  if (draft.draggedEntityId && !ids.has(draft.draggedEntityId)) {
3602
3704
  draft.draggedEntityId = null;
@@ -4172,6 +4274,7 @@ function createFlowStore(initialGraph = {
4172
4274
  }),
4173
4275
  configure: (ctx, event) => {
4174
4276
  if (event.profile) profile = event.profile;
4277
+ const previousAppearances = ctx.appearances;
4175
4278
  return produce(ctx, (draft) => {
4176
4279
  if (event.minZoom !== void 0) draft.minZoom = Math.max(.01, event.minZoom);
4177
4280
  if (event.maxZoom !== void 0) draft.maxZoom = Math.max(draft.minZoom, event.maxZoom);
@@ -4195,6 +4298,24 @@ function createFlowStore(initialGraph = {
4195
4298
  if (event.selectionMode !== void 0) draft.selectionMode = event.selectionMode;
4196
4299
  if (event.labelAnchor !== void 0) draft.labelAnchor = event.labelAnchor;
4197
4300
  if (event.profile || event.mode !== void 0) draft.mode = getMode(profile, event.mode ?? draft.mode);
4301
+ if (event.appearances !== void 0 && event.appearances !== previousAppearances) {
4302
+ draft.appearances = castDraft(event.appearances);
4303
+ const appearanceNodes = /* @__PURE__ */ new Set();
4304
+ for (const node of draft.graph.nodes) {
4305
+ if (!resolveAppearance(node, previousAppearances).reference && !resolveAppearance(node, draft.appearances).reference) continue;
4306
+ node.x -= node.measured?.anchorOffset?.x ?? 0;
4307
+ node.y -= node.measured?.anchorOffset?.y ?? 0;
4308
+ delete node.measured;
4309
+ draft.measurements.delete(node.id);
4310
+ appearanceNodes.add(node.id);
4311
+ }
4312
+ if (appearanceNodes.size) invalidatePathsForNodeGeometry(draft, appearanceNodes);
4313
+ for (const edge of draft.graph.edges) if (edge.label && (resolveAppearance(edge.label, previousAppearances).reference || resolveAppearance(edge.label, draft.appearances).reference)) {
4314
+ draft.measurements.delete(edge.id);
4315
+ invalidateAuthoritativeEdgePath(edge);
4316
+ }
4317
+ for (const id of draft.measurements.keys()) if (id.startsWith("[\"flow-appearance-boundary\",")) draft.measurements.delete(id);
4318
+ }
4198
4319
  draft.configRevision += 1;
4199
4320
  });
4200
4321
  },
@@ -4655,11 +4776,14 @@ function createFlowStore(initialGraph = {
4655
4776
  }
4656
4777
  }
4657
4778
  return produce(ctx, (draft) => {
4779
+ const boundaryNodes = /* @__PURE__ */ new Set();
4780
+ const candidateNodes = /* @__PURE__ */ new Set();
4658
4781
  for (const measurement of event.measurements) {
4659
4782
  const nodeIndex = nodeIndices.get(measurement.id);
4660
4783
  if (nodeIndex !== void 0) {
4661
4784
  const node = draft.graph.nodes[nodeIndex];
4662
- if (node.autoSize) {
4785
+ candidateNodes.add(node.id);
4786
+ if (resolveAppearance(node, draft.appearances).autoSize) {
4663
4787
  const previousSize = resolvedSize(node);
4664
4788
  const previousOffset = node.measured?.anchorOffset ?? {
4665
4789
  x: 0,
@@ -4685,10 +4809,12 @@ function createFlowStore(initialGraph = {
4685
4809
  height: measurement.rect.height
4686
4810
  };
4687
4811
  const existing = draft.measurements.get(measurement.id);
4688
- if (delta.x === 0 && delta.y === 0 && node.measured?.width === measurement.rect.width && node.measured?.height === measurement.rect.height && previousOffset.x === anchorOffset.x && previousOffset.y === anchorOffset.y && existing?.x === normalizedRect.x && existing.y === normalizedRect.y && existing.width === normalizedRect.width && existing.height === normalizedRect.height) continue;
4812
+ if (delta.x === 0 && delta.y === 0 && node.measured?.appearanceKey === JSON.stringify(node.appearance ?? null) && node.measured?.width === measurement.rect.width && node.measured?.height === measurement.rect.height && previousOffset.x === anchorOffset.x && previousOffset.y === anchorOffset.y && existing?.x === normalizedRect.x && existing.y === normalizedRect.y && existing.width === normalizedRect.width && existing.height === normalizedRect.height) continue;
4689
4813
  node.measured = {
4690
4814
  width: measurement.rect.width,
4691
4815
  height: measurement.rect.height,
4816
+ appearanceAutoSize: resolveAppearance(node, draft.appearances).autoSize,
4817
+ appearanceKey: JSON.stringify(node.appearance ?? null),
4692
4818
  ...anchorOffset.x !== 0 || anchorOffset.y !== 0 ? { anchorOffset } : {}
4693
4819
  };
4694
4820
  node.x += delta.x;
@@ -4698,10 +4824,17 @@ function createFlowStore(initialGraph = {
4698
4824
  continue;
4699
4825
  }
4700
4826
  draft.measurements.set(measurement.id, measurement.rect);
4827
+ if (measurement.id.startsWith("[\"flow-appearance-boundary\",")) {
4828
+ const [, id] = JSON.parse(measurement.id);
4829
+ if (nodeIndices.has(id)) boundaryNodes.add(id);
4830
+ const labelIndex = edgeIndices.get(id);
4831
+ if (labelIndex !== void 0) invalidateAuthoritativeEdgePath(draft.graph.edges[labelIndex]);
4832
+ }
4701
4833
  const edgeIndex = edgeIndices.get(measurement.id);
4702
4834
  const edge = edgeIndex === void 0 ? void 0 : draft.graph.edges[edgeIndex];
4703
4835
  if (edge?.label) {
4704
- if (!edge.label.autoSize) {
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) {
4705
4838
  edge.label.width = measurement.rect.width;
4706
4839
  edge.label.height = measurement.rect.height;
4707
4840
  }
@@ -4710,18 +4843,35 @@ function createFlowStore(initialGraph = {
4710
4843
  const portTarget = portIndices.get(measurement.id);
4711
4844
  if (portTarget) {
4712
4845
  const candidate = draft.graph.nodes[portTarget.nodeIndex];
4846
+ candidateNodes.add(candidate.id);
4713
4847
  const port = candidate.ports?.[portTarget.portIndex];
4714
4848
  if (!port) continue;
4715
- port.x = measurement.rect.x - (candidate.x + (candidate.dx ?? 0));
4716
- port.y = measurement.rect.y - (candidate.y + (candidate.dy ?? 0));
4849
+ const origin = snappedBounds(candidate, draft.snapToGrid ? draft.snapGrid : null);
4850
+ port.x = measurement.rect.x - origin.x;
4851
+ port.y = measurement.rect.y - origin.y;
4717
4852
  port.width = measurement.rect.width;
4718
4853
  port.height = measurement.rect.height;
4719
4854
  }
4720
4855
  }
4856
+ for (const id of candidateNodes) {
4857
+ const index = nodeIndices.get(id);
4858
+ if (nodeEndpointGeometryChanged(ctx.graph.nodes[index], draft.graph.nodes[index])) boundaryNodes.add(id);
4859
+ }
4860
+ if (boundaryNodes.size) invalidatePathsForNodeGeometry(draft, boundaryNodes);
4721
4861
  });
4722
4862
  },
4723
4863
  removeMeasurements: (ctx, event) => produce(ctx, (draft) => {
4724
- for (const id of event.ids) draft.measurements.delete(id);
4864
+ const boundaryNodes = /* @__PURE__ */ new Set();
4865
+ for (const id of event.ids) {
4866
+ if (!draft.measurements.delete(id)) continue;
4867
+ if (id.startsWith("[\"flow-appearance-boundary\",")) {
4868
+ const [, entityId] = JSON.parse(id);
4869
+ boundaryNodes.add(entityId);
4870
+ const edge = draft.graph.edges.find((candidate) => candidate.id === entityId);
4871
+ if (edge) invalidateAuthoritativeEdgePath(edge);
4872
+ }
4873
+ }
4874
+ if (boundaryNodes.size) invalidatePathsForNodeGeometry(draft, boundaryNodes);
4725
4875
  }),
4726
4876
  bakeLabelPositions: (ctx, event, enqueue) => produce(ctx, (draft) => {
4727
4877
  for (const [edgeId, center] of event.positions) {
@@ -4765,7 +4915,7 @@ function createFlowStore(initialGraph = {
4765
4915
  }
4766
4916
  function areNodesMeasured(context) {
4767
4917
  return context.graph.nodes.every((node) => {
4768
- if (node.hidden || !node.autoSize) return true;
4918
+ if (node.hidden || !resolveAppearance(node, context.appearances).autoSize) return true;
4769
4919
  return context.measurements.has(node.id) || node.measured !== void 0;
4770
4920
  });
4771
4921
  }
@@ -5092,7 +5242,77 @@ function createFlowEngine(store, initialOptions = {}) {
5092
5242
  }
5093
5243
  return index;
5094
5244
  }
5245
+ let appearanceSettings = ctx().appearances;
5246
+ let appearanceCache = /* @__PURE__ */ new WeakMap();
5247
+ let sizedNodeCache = /* @__PURE__ */ new WeakMap();
5248
+ if (initialOptions.appearances && initialOptions.appearances !== appearanceSettings) store.trigger.configure({ appearances: initialOptions.appearances });
5249
+ function appearanceFor(entity) {
5250
+ if (appearanceSettings !== ctx().appearances) {
5251
+ appearanceSettings = ctx().appearances;
5252
+ appearanceCache = /* @__PURE__ */ new WeakMap();
5253
+ sizedNodeCache = /* @__PURE__ */ new WeakMap();
5254
+ }
5255
+ let appearance = appearanceCache.get(entity);
5256
+ if (!appearance) {
5257
+ appearance = resolveAppearance(entity, appearanceSettings);
5258
+ appearanceCache.set(entity, appearance);
5259
+ }
5260
+ return appearance;
5261
+ }
5262
+ function sizedNode(node) {
5263
+ const autoSize = appearanceFor(node).autoSize;
5264
+ const cached = sizedNodeCache.get(node);
5265
+ if (cached) return cached;
5266
+ const measured = node.measured?.appearanceKey !== void 0 && node.measured.appearanceKey !== JSON.stringify(node.appearance ?? null) ? void 0 : node.measured;
5267
+ const sized = (node.autoSize === autoSize || !autoSize && !node.autoSize && !node.measured?.appearanceAutoSize) && measured === node.measured ? node : {
5268
+ ...node,
5269
+ autoSize,
5270
+ measured
5271
+ };
5272
+ sizedNodeCache.set(node, sized);
5273
+ return sized;
5274
+ }
5275
+ const resolvedSize$1 = (node) => resolvedSize(sizedNode(node));
5276
+ const resolvedBounds$1 = (node) => resolvedBounds(sizedNode(node));
5277
+ const snappedBounds$1 = (node, grid, offset) => snappedBounds(sizedNode(node), grid, offset);
5278
+ const resolvedEdgeLabelSize$1 = (label, measurement) => resolvedEdgeLabelSize({
5279
+ ...label,
5280
+ autoSize: appearanceFor(label).autoSize
5281
+ }, measurement);
5282
+ function connectionBounds(id, entity, visual) {
5283
+ const appearance = appearanceFor(entity);
5284
+ const local = appearance.connectionBounds ?? (appearance.registered ? ctx().measurements.get(appearanceMeasurementId(id, appearance)) : void 0);
5285
+ return local ? {
5286
+ ...local,
5287
+ x: visual.x + local.x,
5288
+ y: visual.y + local.y
5289
+ } : visual;
5290
+ }
5291
+ /** A constrained presentation must not be bypassed by graph-owned route points. */
5292
+ function resolvedAuthoritativePath(edge, source = getNode(edge.sourceId), target = getNode(edge.targetId)) {
5293
+ const path = authoritativeEdgePath(edge);
5294
+ if (!path) return null;
5295
+ const constrained = (id, entity) => {
5296
+ if (!entity) return false;
5297
+ const appearance = appearanceFor(entity);
5298
+ return !!appearance.connectionBounds || appearance.ports !== void 0 || [
5299
+ "top",
5300
+ "right",
5301
+ "bottom",
5302
+ "left"
5303
+ ].some((side) => !appearance.sides.includes(side)) || appearance.registered && ctx().measurements.has(appearanceMeasurementId(id, appearance));
5304
+ };
5305
+ return constrained(edge.sourceId, source) || constrained(edge.targetId, target) || constrained(edge.id, edge.label ?? void 0) ? null : path;
5306
+ }
5307
+ function connectionDirection(entity, bounds, other) {
5308
+ return appearanceDirection(bounds, other, bestDirection(bounds, other), appearanceFor(entity).sides);
5309
+ }
5310
+ function isPortAllowed(nodeOrId, portName) {
5311
+ const node = typeof nodeOrId === "string" ? getNode(nodeOrId) : nodeOrId;
5312
+ return !!node && appearanceAllowsPort(node, portName, appearanceFor(node));
5313
+ }
5095
5314
  function setOptions(partial, replace = false) {
5315
+ const previousAppearances = engineOptions.appearances;
5096
5316
  engineOptions = replace ? { ...partial } : {
5097
5317
  ...engineOptions,
5098
5318
  ...partial,
@@ -5123,6 +5343,8 @@ function createFlowEngine(store, initialOptions = {}) {
5123
5343
  nodeIndexCache = /* @__PURE__ */ new WeakMap();
5124
5344
  obstacleCache = /* @__PURE__ */ new WeakMap();
5125
5345
  edgePathMemo.clear();
5346
+ const appearances = replace ? partial.appearances ?? {} : partial.appearances;
5347
+ if (appearances !== void 0 && appearances !== previousAppearances) store.trigger.configure({ appearances });
5126
5348
  }
5127
5349
  function ownerObstacles(owner, c) {
5128
5350
  let byOwner = obstacleCache.get(c);
@@ -5193,8 +5415,8 @@ function createFlowEngine(store, initialOptions = {}) {
5193
5415
  return geometry;
5194
5416
  }
5195
5417
  function computeGroupGeometryRaw(c, node, visiting, excludeChildren, visualSnap) {
5196
- const contentSize = resolvedSize(node);
5197
- if (node.group.type === "fixed") return fixedGroupGeometry(withLayoutOffset(resolvedBounds(node), node.id, c), node.group.contentSize ?? {
5418
+ const contentSize = resolvedSize$1(node);
5419
+ if (node.group.type === "fixed") return fixedGroupGeometry(withLayoutOffset(resolvedBounds$1(node), node.id, c), node.group.contentSize ?? {
5198
5420
  width: 0,
5199
5421
  height: 0
5200
5422
  }, node.group);
@@ -5207,7 +5429,7 @@ function createFlowEngine(store, initialOptions = {}) {
5207
5429
  if (isHiddenByCollapsedAncestor(child.id, c)) continue;
5208
5430
  if (excludeChildren?.has(child.id)) continue;
5209
5431
  const liveResize = c.canvasState === "resizing" && c.resizingEntityId === child.id ? getResizeBoundsFromContext(c) : null;
5210
- const b = liveResize ? liveResize : visualSnap ? visualBounds(child, visualSnap) : isDerivedGroup(child) ? excludeChildren ? computeGroupGeometryRaw(c, child, seen, excludeChildren).bounds : groupGeometryFor(c, child, seen)?.bounds ?? withLayoutOffset(resolvedBounds(child), child.id, c) : hierarchyBounds(child, c);
5432
+ const b = liveResize ? liveResize : visualSnap ? visualBounds(child, visualSnap) : isDerivedGroup(child) ? excludeChildren ? computeGroupGeometryRaw(c, child, seen, excludeChildren).bounds : groupGeometryFor(c, child, seen)?.bounds ?? withLayoutOffset(resolvedBounds$1(child), child.id, c) : hierarchyBounds(child, c);
5211
5433
  union = uniteRects(union, b);
5212
5434
  }
5213
5435
  const nodeMap = indexNodes(c.graph.nodes);
@@ -5237,7 +5459,7 @@ function createFlowEngine(store, initialOptions = {}) {
5237
5459
  const geometry = groupGeometryFor(c, node);
5238
5460
  if (geometry) return geometry.bounds;
5239
5461
  }
5240
- return withLayoutOffset(resolvedBounds(node), node.id, c);
5462
+ return withLayoutOffset(resolvedBounds$1(node), node.id, c);
5241
5463
  }
5242
5464
  const edgePathMemo = /* @__PURE__ */ new Map();
5243
5465
  let edgePathMemoInputs = null;
@@ -5447,6 +5669,14 @@ function createFlowEngine(store, initialOptions = {}) {
5447
5669
  };
5448
5670
  const sourcePort = proposed.sourcePort && srcNode.ports ? srcNode.ports.find((p) => p.name === proposed.sourcePort) ?? null : null;
5449
5671
  const targetPort = proposed.targetPort && tgtNode.ports ? tgtNode.ports.find((p) => p.name === proposed.targetPort) ?? null : null;
5672
+ 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
+ valid: false,
5674
+ reason: "appearance-port"
5675
+ };
5676
+ if (!appearanceFor(srcNode).sides.length || !appearanceFor(tgtNode).sides.length) return {
5677
+ valid: false,
5678
+ reason: "appearance-sides"
5679
+ };
5450
5680
  if (sourcePort) {
5451
5681
  if (sourcePort.direction === "in") return {
5452
5682
  valid: false,
@@ -5569,6 +5799,7 @@ function createFlowEngine(store, initialOptions = {}) {
5569
5799
  if (!resolveEntityConfig(node).connectable) continue;
5570
5800
  const nodePosition = layoutPosition(node, c);
5571
5801
  for (const port of node.ports ?? []) {
5802
+ if (!isPortAllowed(node, port.name)) continue;
5572
5803
  const position = {
5573
5804
  x: nodePosition.x + port.x + port.width / 2,
5574
5805
  y: nodePosition.y + port.y + port.height / 2
@@ -5586,8 +5817,16 @@ function createFlowEngine(store, initialOptions = {}) {
5586
5817
  };
5587
5818
  }
5588
5819
  if (mode !== "loose") continue;
5589
- const bounds = hierarchyBounds(node, c);
5590
- const distance = node.group ? groupConnectionDistance(pointer, node, c) : distanceToRect(pointer, bounds);
5820
+ const bounds = connectionBounds(node.id, node, hierarchyBounds(node, c));
5821
+ const sides = appearanceFor(node).sides;
5822
+ if (!sides.length) continue;
5823
+ const boundaryDistance = Math.min(...sides.map((side) => distanceToRect(pointer, {
5824
+ x: side === "right" ? bounds.x + bounds.width : bounds.x,
5825
+ y: side === "bottom" ? bounds.y + bounds.height : bounds.y,
5826
+ width: side === "left" || side === "right" ? 0 : bounds.width,
5827
+ height: side === "top" || side === "bottom" ? 0 : bounds.height
5828
+ })));
5829
+ const distance = sides.length < 4 ? boundaryDistance : node.group ? groupConnectionDistance(pointer, node, c) : distanceToRect(pointer, bounds);
5591
5830
  if (distance > radius) continue;
5592
5831
  const isValid = isConnectionCandidateValid(options.source, node.id, null);
5593
5832
  if (!isValid) continue;
@@ -5622,40 +5861,20 @@ function createFlowEngine(store, initialOptions = {}) {
5622
5861
  if (!source || !target) return void 0;
5623
5862
  const sourceBounds = visualBounds(source, snap);
5624
5863
  const targetBounds = visualBounds(target, snap);
5625
- return { ...visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed", edge.label, sourceBounds, targetBounds, edge, resolvedEdgeLabelSize(edge.label, ctx().measurements.get(edge.id))), snap) };
5864
+ return { ...visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed", edge.label, sourceBounds, targetBounds, edge, resolvedEdgeLabelSize$1(edge.label, ctx().measurements.get(edge.id))), snap) };
5626
5865
  };
5627
5866
  }
5628
5867
  function getEdgePath(edgeId) {
5629
- const c = ctx();
5630
- const { graph } = c;
5631
- const edge = indexEdges(graph.edges).get(edgeId) ?? foldedEdgesFor(c).byId.get(edgeId);
5632
- if (!edge) return null;
5633
- const authoritative = authoritativeEdgePath(edge);
5634
- if (authoritative) return authoritative;
5635
- const nodeIndex = indexNodes(graph.nodes);
5636
- const sourceNode = nodeIndex.get(edge.sourceId);
5637
- const targetNode = nodeIndex.get(edge.targetId);
5638
- if (!sourceNode || !targetNode) return null;
5639
- const srcBounds = withLayoutOffset(resolvedBounds(sourceNode), sourceNode.id, c);
5640
- const tgtBounds = withLayoutOffset(resolvedBounds(targetNode), targetNode.id, c);
5641
- const sourceDirection = bestDirection(srcBounds, tgtBounds);
5642
- const targetDirection = bestDirection(tgtBounds, srcBounds);
5643
- const snap = getVisualSnapOffset();
5644
- const routerCtx = {
5645
- graph,
5646
- getEntityBounds: createRouterEntityBoundsLookup(graph, snap, nodeIndex, indexEdges(graph.edges)),
5647
- sourceBounds: srcBounds,
5648
- targetBounds: tgtBounds,
5649
- sourceDirection,
5650
- targetDirection,
5651
- sourcePoint: getShapeAnchor(sourceNode, srcBounds, sourceDirection),
5652
- targetPoint: getShapeAnchor(targetNode, tgtBounds, targetDirection),
5653
- waypoints: offsetEdgeWaypoints(edge, visualOwnedEdgeOffset(edge, snap)),
5654
- get obstacles() {
5655
- return edgeObstacles(edge, c);
5656
- }
5868
+ const segments = getAllEdgePaths().get(edgeId)?.segments;
5869
+ if (!segments?.length) return null;
5870
+ if (segments.length === 1) return segments[0];
5871
+ return {
5872
+ points: segments.flatMap((segment) => segment.points),
5873
+ sourceDirection: segments[0].sourceDirection,
5874
+ targetDirection: segments.at(-1).targetDirection,
5875
+ routing: "polyline",
5876
+ svgPath: segments.map(pathToSVG).join(" ")
5657
5877
  };
5658
- return (engineOptions.edgeRouter ?? bezierRouter)(edge, routerCtx);
5659
5878
  }
5660
5879
  function getEdgePathBounds(edgeId) {
5661
5880
  const path = getAllEdgePaths().get(edgeId);
@@ -5686,7 +5905,7 @@ function createFlowEngine(store, initialOptions = {}) {
5686
5905
  }
5687
5906
  if (addressable.kind === "edge") {
5688
5907
  const labelBounds = getEdgeLabelBounds(id);
5689
- if (authoritativeEdgePath(addressable.edge)) {
5908
+ if (resolvedAuthoritativePath(addressable.edge)) {
5690
5909
  const edgePathBounds = getEdgePathBounds(id);
5691
5910
  if (edgePathBounds) return labelBounds ? unionRect(edgePathBounds, labelBounds) : edgePathBounds;
5692
5911
  }
@@ -5725,7 +5944,7 @@ function createFlowEngine(store, initialOptions = {}) {
5725
5944
  height: tgt.style?.customHeight ?? tgt.height
5726
5945
  }, tgt.id);
5727
5946
  const anchor = edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed";
5728
- const size = resolvedEdgeLabelSize(edge.label, measurement);
5947
+ const size = resolvedEdgeLabelSize$1(edge.label, measurement);
5729
5948
  const basePos = resolveLabelAnchor(anchor, edge.label, srcB, tgtB, edge, size);
5730
5949
  return withLayoutOffset({
5731
5950
  x: basePos.x + (edge.label.dx ?? 0),
@@ -5748,7 +5967,7 @@ function createFlowEngine(store, initialOptions = {}) {
5748
5967
  }
5749
5968
  for (const e of c.graph.edges) {
5750
5969
  if (!c.selection.has(e.id)) continue;
5751
- if (includeEdgePoints) for (const point of authoritativeEdgePath(e)?.points ?? []) {
5970
+ if (includeEdgePoints) for (const point of resolvedAuthoritativePath(e)?.points ?? []) {
5752
5971
  minX = Math.min(minX, point.x);
5753
5972
  minY = Math.min(minY, point.y);
5754
5973
  maxX = Math.max(maxX, point.x);
@@ -5894,7 +6113,7 @@ function createFlowEngine(store, initialOptions = {}) {
5894
6113
  if (geometry) return geometry.bounds;
5895
6114
  }
5896
6115
  const entityOffset = (node.dx ?? 0) !== 0 || (node.dy ?? 0) !== 0 ? snap.offset : null;
5897
- return withLayoutOffset(snappedBounds(node, snap.grid, entityOffset), node.id, c);
6116
+ return withLayoutOffset(snappedBounds$1(node, snap.grid, entityOffset), node.id, c);
5898
6117
  }
5899
6118
  function visualLabelBounds(edge, basePos, snap) {
5900
6119
  const isSelected = snap.selection.has(edge.id);
@@ -5915,7 +6134,7 @@ function createFlowEngine(store, initialOptions = {}) {
5915
6134
  y = snapToGrid(y, snap.grid[1]);
5916
6135
  }
5917
6136
  }
5918
- const size = edge.label ? resolvedEdgeLabelSize(edge.label, ctx().measurements.get(edge.id)) : {
6137
+ const size = edge.label ? resolvedEdgeLabelSize$1(edge.label, ctx().measurements.get(edge.id)) : {
5919
6138
  width: 0,
5920
6139
  height: 0
5921
6140
  };
@@ -5935,7 +6154,7 @@ function createFlowEngine(store, initialOptions = {}) {
5935
6154
  }
5936
6155
  /** Get bounds for edge endpoint — port bounds if specified, otherwise node bounds */
5937
6156
  function getEndpointBounds(node, portName, snap) {
5938
- if (portName && portName !== "*" && node.ports) {
6157
+ if (portName && portName !== "*" && node.ports && isPortAllowed(node, portName)) {
5939
6158
  const port = node.ports.find((p) => p.name === portName);
5940
6159
  if (port) {
5941
6160
  const np = snap ? visualPosition(node, snap) : layoutPosition(node);
@@ -5947,22 +6166,31 @@ function createFlowEngine(store, initialOptions = {}) {
5947
6166
  };
5948
6167
  }
5949
6168
  }
5950
- if (snap) return visualBounds(node, snap);
5951
- return withLayoutOffset(resolvedBounds(node), node.id);
6169
+ const visual = snap ? visualBounds(node, snap) : hierarchyBounds(node, ctx());
6170
+ return connectionBounds(node.id, node, visual);
5952
6171
  }
5953
6172
  function portSideOf(node, portName) {
5954
6173
  if (!portName || portName === "*" || !node.ports) return null;
5955
- return node.ports.find((p) => p.name === portName)?.side ?? null;
6174
+ const port = node.ports.find((p) => p.name === portName);
6175
+ return port && isPortAllowed(node, portName) ? port.side ?? null : null;
5956
6176
  }
5957
6177
  function getShapeAnchor(node, bounds, direction) {
6178
+ const appearance = appearanceFor(node);
6179
+ if (appearance.connectionBounds || appearance.registered && ctx().measurements.has(appearanceMeasurementId(node.id, appearance))) return rectEdgeAnchor(bounds, direction);
5958
6180
  return getShapeOrDefault(node.shape ?? "rect").edgeAnchor(bounds, direction);
5959
6181
  }
5960
6182
  function resolveEndpointPoint(node, nodeBounds, portName, otherBounds, fallbackDirection, snap) {
5961
- if (portName === "*" && node.ports?.length) return closestPortPosition(node, {
5962
- x: otherBounds.x + otherBounds.width / 2,
5963
- y: otherBounds.y + otherBounds.height / 2
5964
- }, snap ? visualPosition(node, snap) : layoutPosition(node));
5965
- if (portName && portName !== "*" && node.ports) {
6183
+ if (portName === "*" && node.ports?.some((port) => isPortAllowed(node, port.name))) {
6184
+ const otherCenter = {
6185
+ x: otherBounds.x + otherBounds.width / 2,
6186
+ y: otherBounds.y + otherBounds.height / 2
6187
+ };
6188
+ return closestPortPosition({
6189
+ ...node,
6190
+ ports: node.ports.filter((port) => isPortAllowed(node, port.name))
6191
+ }, otherCenter, snap ? visualPosition(node, snap) : layoutPosition(node));
6192
+ }
6193
+ if (portName && portName !== "*" && node.ports && isPortAllowed(node, portName)) {
5966
6194
  const port = node.ports.find((p) => p.name === portName);
5967
6195
  if (port) {
5968
6196
  const position = snap ? visualPosition(node, snap) : layoutPosition(node);
@@ -6014,8 +6242,8 @@ function createFlowEngine(store, initialOptions = {}) {
6014
6242
  getEdgeLabelBounds
6015
6243
  });
6016
6244
  const sourceBounds = resolvedSourceBounds ?? naturalSourceBounds;
6017
- const sourceDirection = portSideOf(source, edge.sourcePort) ?? bestDirection(sourceBounds, targetBounds);
6018
- const targetDirection = portSideOf(target, edge.targetPort) ?? bestDirection(targetBounds, sourceBounds);
6245
+ const sourceDirection = portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, targetBounds);
6246
+ const targetDirection = portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, sourceBounds);
6019
6247
  return {
6020
6248
  sourceBounds,
6021
6249
  targetBounds,
@@ -6027,6 +6255,7 @@ function createFlowEngine(store, initialOptions = {}) {
6027
6255
  }
6028
6256
  function edgePathsCacheInputs(c, snap) {
6029
6257
  return {
6258
+ appearances: c.appearances,
6030
6259
  canonicalGraph: c.graph,
6031
6260
  selection: c.selection,
6032
6261
  collapsedNodeIds: c.collapsedNodeIds,
@@ -6042,7 +6271,7 @@ function createFlowEngine(store, initialOptions = {}) {
6042
6271
  };
6043
6272
  }
6044
6273
  function sameEdgePathsCacheInputs(a, b) {
6045
- return a.canonicalGraph === b.canonicalGraph && a.selection === b.selection && a.collapsedNodeIds === b.collapsedNodeIds && a.connection === b.connection && a.offsetX === b.offsetX && a.offsetY === b.offsetY && a.gridX === b.gridX && a.gridY === b.gridY && a.resizingEntityId === b.resizingEntityId && a.resizeCorners === b.resizeCorners && a.measurements === b.measurements && a.layoutOffsets === b.layoutOffsets;
6274
+ return a.appearances === b.appearances && a.canonicalGraph === b.canonicalGraph && a.selection === b.selection && a.collapsedNodeIds === b.collapsedNodeIds && a.connection === b.connection && a.offsetX === b.offsetX && a.offsetY === b.offsetY && a.gridX === b.gridX && a.gridY === b.gridY && a.resizingEntityId === b.resizingEntityId && a.resizeCorners === b.resizeCorners && a.measurements === b.measurements && a.layoutOffsets === b.layoutOffsets;
6046
6275
  }
6047
6276
  /** Route all edges. Callers must treat the returned Map as read-only. */
6048
6277
  function getAllEdgePaths(options = {}) {
@@ -6079,9 +6308,10 @@ function createFlowEngine(store, initialOptions = {}) {
6079
6308
  const memoUsable = !engineOptions.isVisible && !globalConfig.visible && !engineOptions.resolveEdgeSourceBounds;
6080
6309
  if (memoUsable) {
6081
6310
  const inputs = edgePathMemoInputs;
6082
- if (!inputs || inputs.selection !== c.selection || inputs.offsetX !== snap.offset.x || inputs.offsetY !== snap.offset.y || inputs.grid !== snap.grid || inputs.resizingEntityId !== c.resizingEntityId || inputs.resizeCorners !== c.resizeCorners || inputs.measurements !== c.measurements || inputs.layoutOffsets !== c.layoutAnimation.offsets) {
6311
+ if (!inputs || inputs.appearances !== c.appearances || inputs.selection !== c.selection || inputs.offsetX !== snap.offset.x || inputs.offsetY !== snap.offset.y || inputs.grid !== snap.grid || inputs.resizingEntityId !== c.resizingEntityId || inputs.resizeCorners !== c.resizeCorners || inputs.measurements !== c.measurements || inputs.layoutOffsets !== c.layoutAnimation.offsets) {
6083
6312
  edgePathMemo.clear();
6084
6313
  edgePathMemoInputs = {
6314
+ appearances: c.appearances,
6085
6315
  selection: c.selection,
6086
6316
  offsetX: snap.offset.x,
6087
6317
  offsetY: snap.offset.y,
@@ -6128,39 +6358,40 @@ function createFlowEngine(store, initialOptions = {}) {
6128
6358
  const getObstacles = () => obstaclesCache ??= edgeObstacles(edge, c);
6129
6359
  const waypoints = offsetEdgeWaypoints(edge, visualOwnedEdgeOffset(edge, snap));
6130
6360
  let pathData;
6131
- const authoritative = authoritativeEdgePath(edge);
6361
+ const authoritative = resolvedAuthoritativePath(edge, source, target);
6132
6362
  if (authoritative) pathData = {
6133
6363
  segments: [authoritative],
6134
- labelBounds: edge.label ? visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed", edge.label, sourceBounds, targetBounds, edge, resolvedEdgeLabelSize(edge.label, c.measurements.get(edge.id))), snap) : null
6364
+ labelBounds: edge.label ? visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed", edge.label, sourceBounds, targetBounds, edge, resolvedEdgeLabelSize$1(edge.label, c.measurements.get(edge.id))), snap) : null
6135
6365
  };
6136
6366
  else if (edge.label) {
6137
- const labelBounds = visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed", edge.label, sourceBounds, targetBounds, edge, resolvedEdgeLabelSize(edge.label, c.measurements.get(edge.id))), snap);
6138
- const srcDir = portSideOf(source, edge.sourcePort) ?? bestDirection(sourceBounds, labelBounds);
6139
- const lblDir1 = bestDirection(labelBounds, sourceBounds);
6367
+ const labelBounds = visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed", edge.label, sourceBounds, targetBounds, edge, resolvedEdgeLabelSize$1(edge.label, c.measurements.get(edge.id))), snap);
6368
+ const labelConnectionBounds = connectionBounds(edge.id, edge.label, labelBounds);
6369
+ const srcDir = portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, labelConnectionBounds);
6370
+ const lblDir1 = connectionDirection(edge.label, labelConnectionBounds, sourceBounds);
6140
6371
  const seg1 = (engineOptions.edgeRouter ?? bezierRouter)(edge, {
6141
6372
  graph,
6142
6373
  getEntityBounds,
6143
6374
  sourceBounds,
6144
- targetBounds: labelBounds,
6375
+ targetBounds: labelConnectionBounds,
6145
6376
  sourceDirection: srcDir,
6146
6377
  targetDirection: lblDir1,
6147
- sourcePoint,
6378
+ sourcePoint: resolveEndpointPoint(source, sourceBounds, edge.sourcePort, labelConnectionBounds, srcDir, snap),
6148
6379
  waypoints,
6149
6380
  get obstacles() {
6150
6381
  return getObstacles();
6151
6382
  }
6152
6383
  });
6153
- const lblDir2 = bestDirection(labelBounds, targetBounds);
6154
- const tgtDir = portSideOf(target, edge.targetPort) ?? bestDirection(targetBounds, labelBounds);
6384
+ const lblDir2 = connectionDirection(edge.label, labelConnectionBounds, targetBounds);
6385
+ const tgtDir = portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, labelConnectionBounds);
6155
6386
  pathData = {
6156
6387
  segments: [seg1, (engineOptions.edgeRouter ?? bezierRouter)(edge, {
6157
6388
  graph,
6158
6389
  getEntityBounds,
6159
- sourceBounds: labelBounds,
6390
+ sourceBounds: labelConnectionBounds,
6160
6391
  targetBounds,
6161
6392
  sourceDirection: lblDir2,
6162
6393
  targetDirection: tgtDir,
6163
- targetPoint,
6394
+ targetPoint: resolveEndpointPoint(target, targetBounds, edge.targetPort, labelConnectionBounds, tgtDir, snap),
6164
6395
  waypoints,
6165
6396
  get obstacles() {
6166
6397
  return getObstacles();
@@ -6169,8 +6400,8 @@ function createFlowEngine(store, initialOptions = {}) {
6169
6400
  labelBounds
6170
6401
  };
6171
6402
  } else {
6172
- const srcDir = portSideOf(source, edge.sourcePort) ?? bestDirection(sourceBounds, targetBounds);
6173
- const tgtDir = portSideOf(target, edge.targetPort) ?? bestDirection(targetBounds, sourceBounds);
6403
+ const srcDir = portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, targetBounds);
6404
+ const tgtDir = portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, sourceBounds);
6174
6405
  pathData = {
6175
6406
  segments: [(engineOptions.edgeRouter ?? bezierRouter)(edge, {
6176
6407
  graph,
@@ -6212,7 +6443,13 @@ function createFlowEngine(store, initialOptions = {}) {
6212
6443
  }
6213
6444
  function graphBoundsFor(c) {
6214
6445
  if (graphBoundsCache?.nodesInput === c.graph.nodes && graphBoundsCache.edgesInput === c.graph.edges && graphBoundsCache.measurementsInput === c.measurements) return graphBoundsCache.value;
6215
- const value = getGraphBounds(c.graph.nodes, c.graph.edges, c.measurements);
6446
+ const value = c.appearances ? getGraphBounds(c.graph.nodes.map(sizedNode), c.graph.edges.map((edge) => edge.label ? {
6447
+ ...edge,
6448
+ label: {
6449
+ ...edge.label,
6450
+ autoSize: appearanceFor(edge.label).autoSize
6451
+ }
6452
+ } : edge), c.measurements) : getGraphBounds(c.graph.nodes, c.graph.edges, c.measurements);
6216
6453
  graphBoundsCache = {
6217
6454
  nodesInput: c.graph.nodes,
6218
6455
  edgesInput: c.graph.edges,
@@ -6253,7 +6490,7 @@ function createFlowEngine(store, initialOptions = {}) {
6253
6490
  const source = getNode(edge.sourceId);
6254
6491
  const target = getNode(edge.targetId);
6255
6492
  if (!source || !target) return null;
6256
- return unionRect(withLayoutOffset(resolvedBounds(source), source.id, c), withLayoutOffset(resolvedBounds(target), target.id, c));
6493
+ return unionRect(withLayoutOffset(resolvedBounds$1(source), source.id, c), withLayoutOffset(resolvedBounds$1(target), target.id, c));
6257
6494
  }
6258
6495
  /**
6259
6496
  * Viewport-query index keyed by geometry identities, never viewport. Building
@@ -6363,7 +6600,7 @@ function createFlowEngine(store, initialOptions = {}) {
6363
6600
  })) return true;
6364
6601
  const srcNode = getNode(e.sourceId);
6365
6602
  const tgtNode = getNode(e.targetId);
6366
- return !!srcNode && !!tgtNode && (rectsIntersect(withLayoutOffset(resolvedBounds(srcNode), srcNode.id, c), cullRect) || rectsIntersect(withLayoutOffset(resolvedBounds(tgtNode), tgtNode.id, c), cullRect));
6603
+ return !!srcNode && !!tgtNode && (rectsIntersect(withLayoutOffset(resolvedBounds$1(srcNode), srcNode.id, c), cullRect) || rectsIntersect(withLayoutOffset(resolvedBounds$1(tgtNode), tgtNode.id, c), cullRect));
6367
6604
  })
6368
6605
  };
6369
6606
  }
@@ -6488,6 +6725,15 @@ function createFlowEngine(store, initialOptions = {}) {
6488
6725
  trigger: store.trigger,
6489
6726
  getContext: ctx,
6490
6727
  setOptions,
6728
+ resolveAppearance: appearanceFor,
6729
+ isPortAllowed,
6730
+ getConnectionBounds: (id) => {
6731
+ const node = getNode(id);
6732
+ if (node) return connectionBounds(id, node, getPublicVisualBounds(node));
6733
+ const edge = getEdge(id);
6734
+ const bounds = getAllEdgePaths().get(id)?.labelBounds;
6735
+ return edge?.label && bounds ? connectionBounds(id, edge.label, bounds) : null;
6736
+ },
6491
6737
  getNode,
6492
6738
  getEdge,
6493
6739
  getEntity,
@@ -6650,7 +6896,7 @@ function createFlowEngine(store, initialOptions = {}) {
6650
6896
  const ids = [];
6651
6897
  for (const n of graph.nodes) {
6652
6898
  if (!isNodeVisible(n, c)) continue;
6653
- if (rectsIntersect(rect, n.selectionBounds ? resolvedSelectionBounds(n) : visualBounds(n, getVisualSnapOffset()))) ids.push(n.id);
6899
+ if (rectsIntersect(rect, n.selectionBounds ? resolvedSelectionBounds(sizedNode(n)) : visualBounds(n, getVisualSnapOffset()))) ids.push(n.id);
6654
6900
  }
6655
6901
  for (const e of graph.edges) {
6656
6902
  if (!isEdgeVisible(e, graph, c)) continue;
@@ -6685,11 +6931,20 @@ function createFlowEngine(store, initialOptions = {}) {
6685
6931
  const { graph } = ctx();
6686
6932
  const edge = graph.edges.find((e) => e.id === edgeId);
6687
6933
  if (!edge) return null;
6688
- const authoritative = authoritativeEdgePath(edge);
6934
+ const authoritative = resolvedAuthoritativePath(edge);
6689
6935
  if (authoritative) return {
6690
6936
  source: authoritative.points[0],
6691
6937
  target: authoritative.points.at(-1)
6692
6938
  };
6939
+ if (edge.label) {
6940
+ const path = getAllEdgePaths().get(edgeId);
6941
+ const first = path?.segments[0]?.points[0];
6942
+ const last = path?.segments.at(-1)?.points.at(-1);
6943
+ if (first && last) return {
6944
+ source: first,
6945
+ target: last
6946
+ };
6947
+ }
6693
6948
  const srcNode = graph.nodes.find((n) => n.id === edge.sourceId);
6694
6949
  const tgtNode = graph.nodes.find((n) => n.id === edge.targetId);
6695
6950
  if (!srcNode || !tgtNode) return null;
@@ -7418,6 +7673,12 @@ function insertFlowContent(graph, content, options) {
7418
7673
  }
7419
7674
  //#endregion
7420
7675
  //#region src/createFlow.ts
7676
+ function hasAuthoritativeLayoutPoints(route) {
7677
+ return !Array.isArray(route) && "points" in route;
7678
+ }
7679
+ function layoutWaypoints(route) {
7680
+ return Array.isArray(route) ? route : route.waypoints;
7681
+ }
7421
7682
  function immutableConfiguration(configuration) {
7422
7683
  const seen = /* @__PURE__ */ new WeakMap();
7423
7684
  const clone = (value) => {
@@ -7454,6 +7715,7 @@ function createFlow(options = {}) {
7454
7715
  }, options.dataSchemas);
7455
7716
  const store = createFlowStore(initialGraph, {
7456
7717
  ...options.store,
7718
+ appearances: options.engine?.appearances ?? options.store?.appearances,
7457
7719
  labelAnchor: options.store?.labelAnchor ?? options.engine?.labelAnchor
7458
7720
  });
7459
7721
  const engine = createFlowEngine(store, options.engine);
@@ -7580,10 +7842,19 @@ function createFlow(options = {}) {
7580
7842
  ...value.nodeBounds ? { nodeBounds: rects(value.nodeBounds) } : {},
7581
7843
  ...value.edgeLabelPositions ? { edgeLabelPositions: points(value.edgeLabelPositions) } : {},
7582
7844
  ...value.edgeLabelBounds ? { edgeLabelBounds: rects(value.edgeLabelBounds) } : {},
7583
- ...value.edgeRoutes ? { edgeRoutes: new Map([...value.edgeRoutes].map(([id, route]) => [id, { waypoints: ("waypoints" in route ? route.waypoints : route).map((point) => ({
7584
- x: point.x,
7585
- y: point.y
7586
- })) }])) } : {},
7845
+ ...value.edgeRoutes ? { edgeRoutes: new Map([...value.edgeRoutes].map(([id, route]) => {
7846
+ if (hasAuthoritativeLayoutPoints(route)) return [id, {
7847
+ points: route.points.map((point) => ({
7848
+ x: point.x,
7849
+ y: point.y
7850
+ })),
7851
+ ...route.routing ? { routing: route.routing } : {}
7852
+ }];
7853
+ return [id, { waypoints: layoutWaypoints(route).map((point) => ({
7854
+ x: point.x,
7855
+ y: point.y
7856
+ })) }];
7857
+ })) } : {},
7587
7858
  ...value.diagnostics ? { diagnostics: value.diagnostics.map((entry) => ({ ...entry })) } : {},
7588
7859
  ...value.quality ? { quality: cloneJsonSafe(value.quality, "$.layout.quality") } : {},
7589
7860
  ...value.metadata ? { metadata: cloneJsonSafe(value.metadata, "$.layout.metadata") } : {},
@@ -7839,7 +8110,7 @@ function createFlow(options = {}) {
7839
8110
  finiteSize(rect, path);
7840
8111
  });
7841
8112
  validateMap("edgeRoutes", result.edgeRoutes, edgeIds, (route, path) => {
7842
- ("waypoints" in route ? route.waypoints : route).forEach((point, index) => finitePoint(point, `${path}.waypoints[${index}]`));
8113
+ (hasAuthoritativeLayoutPoints(route) ? route.points : layoutWaypoints(route)).forEach((point, index) => finitePoint(point, `${path}.points[${index}]`));
7843
8114
  });
7844
8115
  for (const [field, ids] of [
7845
8116
  ["fixedEntityIds", applyOptions.fixedEntityIds],
@@ -7927,7 +8198,11 @@ function createFlow(options = {}) {
7927
8198
  delete edge.label.dx;
7928
8199
  delete edge.label.dy;
7929
8200
  }
7930
- if (route) edge.waypoints = ("waypoints" in route ? route.waypoints : route).map((point) => ({ ...point }));
8201
+ if (route) if (hasAuthoritativeLayoutPoints(route)) {
8202
+ edge.points = route.points.map((point) => ({ ...point }));
8203
+ edge.routing = route.routing ?? "polyline";
8204
+ delete edge.waypoints;
8205
+ } else edge.waypoints = layoutWaypoints(route).map((point) => ({ ...point }));
7931
8206
  }
7932
8207
  const initialOffsets = /* @__PURE__ */ new Map();
7933
8208
  if (animate) {
@@ -8140,7 +8415,13 @@ function createFlow(options = {}) {
8140
8415
  autoSize: false,
8141
8416
  style: void 0
8142
8417
  } : node;
8143
- }), edges, context.measurements);
8418
+ }), edges.map((edge) => edge.label ? {
8419
+ ...edge,
8420
+ label: {
8421
+ ...edge.label,
8422
+ autoSize: engine.resolveAppearance(edge.label).autoSize
8423
+ }
8424
+ } : edge), context.measurements);
8144
8425
  if (bounds.width === 0 && bounds.height === 0) return null;
8145
8426
  const { nodes: _nodes, includeHidden: _includeHidden, ...viewportOptions } = fitOptions ?? {};
8146
8427
  return viewportForBounds(bounds, context.viewportSize, {
@@ -9863,6 +10144,7 @@ function connectMode(options = {}) {
9863
10144
  const { nodeId, portName } = event.target;
9864
10145
  const node = engine.getNode(nodeId);
9865
10146
  if (!node?.ports?.some((port) => port.name === portName)) return null;
10147
+ if (!engine.isPortAllowed(node, portName)) return null;
9866
10148
  if (!engine.resolveEntityConfig(node).connectable) return null;
9867
10149
  return {
9868
10150
  commands: [trigger("connectionStart", {
@@ -10876,4 +11158,4 @@ function createEntityChangeNotifier(store, options = {}) {
10876
11158
  };
10877
11159
  }
10878
11160
  //#endregion
10879
- export { CONNECTION_PREVIEW_EDGE_ID, CONNECTION_PREVIEW_NODE_ID, FlowGraphValidationError, animateViewport, applyFlowPatches, areNodesMeasured, avoidRouter, bestDirection, bezierRouter, boxSelectMode, boxToRect, calcAutoPan, canvasToScreen, clampZoom, cloneJsonSafe, composeGraphProjectionAttrs, configureAvoidRouter, configureBezierRouter, configureStepRouter, connectMode, constrainViewport, createConnectionPreviewGraph, createEdge, createEntityChangeNotifier, createFlow, createFlowChangeSet, createFlowEngine, createFlowInputRuntime, createFlowStore, createGraph, createNode, createPort, createViewport, defaultConfig, defaultFlowProfile, defaultInputModes, defaultInputModesForKeymap, defaultKeymap, defaultModesForContext, defineFlowProfile, deriveFlowView, deriveGroupGeometry, entityPressMode, extractFlowContent, fitFrameAroundExclusions, fixedGroupGeometry, fromJSON, getAnchorTransform, getAutoPanDelta, getConnectedEdges, getEdgeOwner, getGraphBounds, getIncomers, getMinimapProjection, getMinimapViewportCenter, getNeighbors, getOutgoers, getProjectedEdgeAttrs, getProjectedNodeAttrs, getSelectionBounds, getShape, getShapeOrDefault, getSnapLines, getToolbarPlacement, getVisibleBounds, hoverMode, indexChildren, indexEdgeAdjacency, indexEdges, indexNodes, insertFlowContent, isDerivedGroup, isGroup, isTrackpadPinch, keyboardMode, keyboardNavMode, markerToSVG, matchesKeyBinding, mergeGraphEdgeAttrs, mergeGraphNodeAttrs, nodeDepths, normalizeWheelPan, panBy, panMode, panePressMode, parseFlowSerialized, pathToSVG, pinchMode, portPressMode, preventDefault, profileModesForContext, profilePoliciesForContext, readonlyConfig, readonlyInputModes, readonlyInputModesForKeymap, reconnectMode, rectContains, rectsIntersect, registerShape, resolveBehavior, resolveGroupPadding, resolveKeymap, resolvedBounds, resolvedEdgeLabelBounds, resolvedEdgeLabelSize, resolvedPosition, resolvedSelectionBounds, screenToCanvas, selectMode, serializeFlowGraph, snapPointToGrid, snapToGrid, snappedBounds, sortActiveGraphProjections, stepRouter, straightRouter, toSVGTransform, toViewBox, trigger, unionRect, validateAndCloneGraph, validateFitFrame, validateViewport, viewportCenteredOn, viewportForBounds, visualBounds, visualPosition, wheelInteraction, wheelMode, wheelZoomDelta, zoomTo };
11161
+ export { CONNECTION_PREVIEW_EDGE_ID, CONNECTION_PREVIEW_NODE_ID, FlowGraphValidationError, animateViewport, appearanceAllowsPort, appearanceDirection, appearanceMeasurementId, appearanceSides, applyFlowPatches, areNodesMeasured, avoidRouter, bestDirection, bezierRouter, boxSelectMode, boxToRect, calcAutoPan, canvasToScreen, clampZoom, cloneJsonSafe, composeGraphProjectionAttrs, configureAvoidRouter, configureBezierRouter, configureStepRouter, connectMode, constrainViewport, createConnectionPreviewGraph, createEdge, createEntityChangeNotifier, createFlow, createFlowChangeSet, createFlowEngine, createFlowInputRuntime, createFlowStore, createGraph, createNode, createPort, createViewport, defaultConfig, defaultFlowProfile, defaultInputModes, defaultInputModesForKeymap, defaultKeymap, defaultModesForContext, defineFlowProfile, deriveFlowView, deriveGroupGeometry, entityPressMode, extractFlowContent, fitFrameAroundExclusions, fixedGroupGeometry, fromJSON, getAnchorTransform, getAutoPanDelta, getConnectedEdges, getEdgeOwner, getGraphBounds, getIncomers, getMinimapProjection, getMinimapViewportCenter, getNeighbors, getOutgoers, getProjectedEdgeAttrs, getProjectedNodeAttrs, getSelectionBounds, getShape, getShapeOrDefault, getSnapLines, getToolbarPlacement, getVisibleBounds, hoverMode, indexChildren, indexEdgeAdjacency, indexEdges, indexNodes, insertFlowContent, isDerivedGroup, isGroup, isTrackpadPinch, keyboardMode, keyboardNavMode, markerToSVG, matchesKeyBinding, mergeGraphEdgeAttrs, mergeGraphNodeAttrs, nodeDepths, normalizeWheelPan, panBy, panMode, panePressMode, parseFlowSerialized, pathToSVG, pinchMode, portPressMode, preventDefault, profileModesForContext, profilePoliciesForContext, readonlyConfig, readonlyInputModes, readonlyInputModesForKeymap, reconnectMode, rectContains, rectsIntersect, registerShape, resolveAppearance, resolveBehavior, resolveGroupPadding, resolveKeymap, resolvedBounds, resolvedEdgeLabelBounds, resolvedEdgeLabelSize, resolvedPosition, resolvedSelectionBounds, screenToCanvas, selectMode, serializeFlowGraph, snapPointToGrid, snapToGrid, snappedBounds, sortActiveGraphProjections, stepRouter, straightRouter, toSVGTransform, toViewBox, trigger, unionRect, validateAndCloneGraph, validateFitFrame, validateViewport, viewportCenteredOn, viewportForBounds, visualBounds, visualPosition, wheelInteraction, wheelMode, wheelZoomDelta, zoomTo };