@statelyai/flow 0.13.1 → 0.13.3

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/README.md CHANGED
@@ -802,7 +802,7 @@ await animation.done;
802
802
 
803
803
  <!-- edge routers from src/routing/index.ts -->
804
804
 
805
- Four built-in routers. All return `PathData` (points + source/target direction). A custom router may also return `svgPath` to preserve rounded or otherwise custom SVG geometry; `points` remain required for bounds and endpoint handles, and exported `pathToSVG` safely prefers a finite override containing only SVG path commands and numeric parameters. Canonical graph `edge.points` are different from `waypoints`: they are a complete authoritative endpoint-to-endpoint route, interpreted by `edge.routing` (`polyline`, `orthogonal`, or chained `splines`) and never sent through a Flow router or split around a label. An optional edge `svgPath` preserves exact SVG paint while the authoritative points drive endpoints, bounds, hit testing, culling, transient DOM updates, and export. Core endpoint-geometry mutations invalidate precomputed route fields; layout results may atomically replace them with either interior router waypoints or complete `points` plus `routing`. Edge `waypoints` remain ordered interior router inputs passed through `EdgeRouterContext`; built-in routers honor them. Custom `EdgeRouter`s receive the full typed edge plus the exact canonical or projection `graph` currently being routed and a detached, read-only `getEntityBounds(id)` lookup for live node/edge-label geometry. The lookup never routes another edge. Use `configureBezierRouter(options)`, `configureStepRouter(options)`, and `configureAvoidRouter(options)` for customized built-in router variants. `avoidRouter` is opt-in and routes orthogonal polylines around sibling node obstacles. Set `engine.edgeRouterDependencies: 'endpoints'` only when a custom router does not inspect unrelated graph entities, bounds, or obstacles; Flow can then retain unaffected routes after local geometry changes. The safe default is `'graph'`.
805
+ Four built-in routers. All return `PathData` (points + source/target direction). A custom router may also return `svgPath` to preserve rounded or otherwise custom SVG geometry; `points` remain required for bounds and endpoint handles, and exported `pathToSVG` safely prefers a finite override containing only SVG path commands and numeric parameters. Canonical graph `edge.points` are different from `waypoints`: they are a complete authoritative endpoint-to-endpoint route, interpreted by `edge.routing` (`polyline`, `orthogonal`, or chained `splines`) and never sent through a Flow router or split around a label. An optional edge `svgPath` preserves exact SVG paint while the authoritative points drive endpoints, bounds, hit testing, culling, transient DOM updates, and export. Core endpoint-geometry mutations invalidate precomputed route fields; layout results may atomically replace them with either interior router waypoints or complete `points` plus `routing`. Edge `waypoints` remain ordered interior router inputs passed through `EdgeRouterContext`; built-in routers honor them. Custom `EdgeRouter`s receive the full typed edge plus the exact canonical or projection `graph` currently being routed and a detached, read-only `getEntityBounds(id)` lookup for live node/edge-label geometry. The lookup never routes another edge. Use `configureBezierRouter(options)`, `configureStepRouter(options)`, and `configureAvoidRouter(options)` for customized built-in router variants. `avoidRouter` is opt-in and routes orthogonal polylines around sibling node obstacles. Set `engine.edgeRouterDependencies: 'endpoints'` only when a custom router does not inspect unrelated graph entities, bounds, or obstacles; Flow can then retain unaffected routes after local geometry changes. The safe default is `'graph'`: Flow records the edge and graph fields a router reads, the bounds it looks up, and whether it reads obstacles, and skips routing when none of them and no call's geometry changed. Edits a router never reads, such as node `data`, then do not reroute.
806
806
 
807
807
  Router obstacles exclude the source, target, and their ancestor groups, so an
808
808
  edge crossing a hierarchy boundary can pass through its endpoint container.
@@ -630,8 +630,11 @@ type EdgeRouterContext<TEdgeData = any, TLabelData = any, TNodeData = any> = {
630
630
  * Deterministic edge-routing function.
631
631
  *
632
632
  * Routers should depend only on the edge and supplied routing context. Do not
633
- * read viewport or external mutable state; Flow may reuse a path while graph
634
- * geometry and the router identity are unchanged.
633
+ * read viewport or external mutable state. With the default `graph`
634
+ * dependencies, the edge and `context.graph` are read-only views that record
635
+ * each field the router reads; Flow reuses a pass's paths while every recorded
636
+ * read and every call's inputs are unchanged. A router that freezes or clones
637
+ * those views is routed without tracking.
635
638
  */
636
639
  type EdgeRouter<TEdgeData = any, TLabelData = any, TNodeData = any> = (edge: Readonly<FlowEdge<TEdgeData, TLabelData>>, context: EdgeRouterContext<TEdgeData, TLabelData, TNodeData>) => PathData;
637
640
  type BezierRouterOptions = {
@@ -748,8 +751,10 @@ type FlowEngineOptions = {
748
751
  /** Default edge router (default: bezierRouter) */
749
752
  edgeRouter?: EdgeRouter;
750
753
  /**
751
- * Geometry read by a custom edge router. Defaults to `graph`, which safely
752
- * reroutes every edge after any graph geometry change. Use `endpoints` only
754
+ * Geometry read by a custom edge router. Defaults to `graph`: Flow records
755
+ * what the router reads from the edge, the graph, `getEntityBounds`, and
756
+ * `obstacles` during a routing pass, and reroutes every edge when any of it,
757
+ * or any call's geometry, changes. Use `endpoints` only
753
758
  * when the router depends on the edge and its endpoint/label inputs—not
754
759
  * arbitrary `graph`, `getEntityBounds`, or `obstacles` reads. That contract
755
760
  * lets Flow retain unaffected custom routes by identity.
package/dist/esm/index.js CHANGED
@@ -3676,21 +3676,22 @@ function createFlowStore(initialGraph = {
3676
3676
  const previousSelection = new Set(draft.selection);
3677
3677
  const previousNodes = new Map(ctx.graph.nodes.map((node) => [node.id, node]));
3678
3678
  const changedAppearances = /* @__PURE__ */ new Set();
3679
+ const nodes = event.graph.nodes.map((node) => {
3680
+ const previous = previousNodes.get(node.id);
3681
+ if (!previous || JSON.stringify(previous.appearance) === JSON.stringify(node.appearance)) return node;
3682
+ const next = {
3683
+ ...node,
3684
+ x: node.x - (node.measured?.anchorOffset?.x ?? 0),
3685
+ y: node.y - (node.measured?.anchorOffset?.y ?? 0)
3686
+ };
3687
+ delete next.measured;
3688
+ draft.measurements.delete(node.id);
3689
+ changedAppearances.add(node.id);
3690
+ return next;
3691
+ });
3679
3692
  draft.graph = {
3680
3693
  ...event.graph,
3681
- nodes: event.graph.nodes.map((node) => {
3682
- const previous = previousNodes.get(node.id);
3683
- if (!previous || JSON.stringify(previous.appearance) === JSON.stringify(node.appearance)) return node;
3684
- const next = {
3685
- ...node,
3686
- x: node.x - (node.measured?.anchorOffset?.x ?? 0),
3687
- y: node.y - (node.measured?.anchorOffset?.y ?? 0)
3688
- };
3689
- delete next.measured;
3690
- draft.measurements.delete(node.id);
3691
- changedAppearances.add(node.id);
3692
- return next;
3693
- })
3694
+ nodes: changedAppearances.size ? nodes : event.graph.nodes
3694
3695
  };
3695
3696
  if (changedAppearances.size) invalidatePathsForNodeGeometry(draft, changedAppearances);
3696
3697
  draft.layoutAnimation = event.layoutAnimationOffsets?.size ? {
@@ -3724,9 +3725,9 @@ function createFlowStore(initialGraph = {
3724
3725
  draft.measurements.clear();
3725
3726
  draft.derivedPortMeasurements.clear();
3726
3727
  } else {
3727
- draft.selection = new Set([...draft.selection].filter((id) => ids.has(id)));
3728
- draft.hoveredEntityIds = new Set([...draft.hoveredEntityIds].filter((id) => ids.has(id)));
3729
- draft.collapsedNodeIds = new Set([...draft.collapsedNodeIds].filter((id) => nodeIds.has(id)));
3728
+ if ([...draft.selection].some((id) => !ids.has(id))) draft.selection = new Set([...draft.selection].filter((id) => ids.has(id)));
3729
+ if ([...draft.hoveredEntityIds].some((id) => !ids.has(id))) draft.hoveredEntityIds = new Set([...draft.hoveredEntityIds].filter((id) => ids.has(id)));
3730
+ if ([...draft.collapsedNodeIds].some((id) => !nodeIds.has(id))) draft.collapsedNodeIds = new Set([...draft.collapsedNodeIds].filter((id) => nodeIds.has(id)));
3730
3731
  for (const [kind, bucket] of draft.highlights) {
3731
3732
  for (const id of bucket.keys()) if (!ids.has(id)) bucket.delete(id);
3732
3733
  if (bucket.size === 0) draft.highlights.delete(kind);
@@ -5423,6 +5424,204 @@ registerShape("rounded", roundedHandler);
5423
5424
  registerShape("ellipse", ellipseHandler);
5424
5425
  registerShape("diamond", diamondHandler);
5425
5426
  //#endregion
5427
+ //#region src/routing/readTracking.ts
5428
+ const OBJECT = "[object]";
5429
+ const ARRAY = "[array]";
5430
+ const FUNCTION = "[function]";
5431
+ function entityRootFor(root, path, value) {
5432
+ if (root !== "graph" || path.length !== 1) return null;
5433
+ if (!value || typeof value !== "object") return null;
5434
+ const id = value.id;
5435
+ if (typeof id !== "string") return null;
5436
+ if (path[0] === "nodes") return `node:${id}`;
5437
+ if (path[0] === "edges") return `edge:${id}`;
5438
+ return null;
5439
+ }
5440
+ function classify(root, path, value) {
5441
+ const entityRoot = entityRootFor(root, path, value);
5442
+ if (entityRoot) return entityRoot;
5443
+ if (typeof value === "function") return FUNCTION;
5444
+ if (value && typeof value === "object") return Array.isArray(value) ? ARRAY : OBJECT;
5445
+ return value;
5446
+ }
5447
+ function stringKeys(value) {
5448
+ return Reflect.ownKeys(value).filter((key) => typeof key === "string").join("\0");
5449
+ }
5450
+ /**
5451
+ * Read-only views of `graph` and its entities that log what a router reads.
5452
+ * Views are stable for the tracker's lifetime, so routers that cache by
5453
+ * object identity see the same graph and entity objects across calls.
5454
+ */
5455
+ function createRouterReadTracker(graph, getEntityBounds) {
5456
+ const log = {
5457
+ reads: [],
5458
+ bounds: /* @__PURE__ */ new Map()
5459
+ };
5460
+ const entityViews = /* @__PURE__ */ new Map();
5461
+ const sources = /* @__PURE__ */ new WeakMap();
5462
+ const view = (raw, root, path) => {
5463
+ const children = /* @__PURE__ */ new Map();
5464
+ const logged = /* @__PURE__ */ new Set();
5465
+ const record = (op, key, value) => {
5466
+ const id = `${op}\u0000${key ?? ""}`;
5467
+ if (logged.has(id)) return;
5468
+ logged.add(id);
5469
+ log.reads.push({
5470
+ root,
5471
+ path: key === null ? path : [...path, key],
5472
+ op,
5473
+ value
5474
+ });
5475
+ };
5476
+ const child = (key) => {
5477
+ if (children.has(key)) return children.get(key);
5478
+ const value = raw[key];
5479
+ let result = value;
5480
+ if (value && typeof value === "object") {
5481
+ const entityRoot = entityRootFor(root, path, value);
5482
+ result = entityRoot ? entityView(entityRoot, value) : view(value, root, [...path, key]);
5483
+ }
5484
+ children.set(key, result);
5485
+ return result;
5486
+ };
5487
+ const proxy = new Proxy(Array.isArray(raw) ? [] : {}, {
5488
+ get(_target, key) {
5489
+ if (typeof key === "symbol") return Reflect.get(raw, key);
5490
+ record("get", key, classify(root, path, raw[key]));
5491
+ return child(key);
5492
+ },
5493
+ has(_target, key) {
5494
+ const result = Reflect.has(raw, key);
5495
+ if (typeof key === "string") record("has", key, result);
5496
+ return result;
5497
+ },
5498
+ ownKeys() {
5499
+ record("keys", null, stringKeys(raw));
5500
+ return Reflect.ownKeys(raw);
5501
+ },
5502
+ getOwnPropertyDescriptor(_target, key) {
5503
+ const descriptor = Reflect.getOwnPropertyDescriptor(raw, key);
5504
+ if (typeof key === "string") {
5505
+ record("has", key, descriptor !== void 0);
5506
+ if (descriptor) record("get", key, classify(root, path, raw[key]));
5507
+ }
5508
+ if (!descriptor) return void 0;
5509
+ if (Array.isArray(raw) && key === "length") return {
5510
+ value: raw.length,
5511
+ writable: true,
5512
+ enumerable: false,
5513
+ configurable: false
5514
+ };
5515
+ return {
5516
+ value: typeof key === "string" ? child(key) : Reflect.get(raw, key),
5517
+ writable: false,
5518
+ enumerable: descriptor.enumerable,
5519
+ configurable: true
5520
+ };
5521
+ },
5522
+ getPrototypeOf() {
5523
+ return Reflect.getPrototypeOf(raw);
5524
+ },
5525
+ set() {
5526
+ return false;
5527
+ },
5528
+ defineProperty() {
5529
+ return false;
5530
+ },
5531
+ deleteProperty() {
5532
+ return false;
5533
+ }
5534
+ });
5535
+ sources.set(proxy, {
5536
+ raw,
5537
+ root,
5538
+ path
5539
+ });
5540
+ return proxy;
5541
+ };
5542
+ const release = (value) => {
5543
+ if (!value || typeof value !== "object") return value;
5544
+ const source = sources.get(value);
5545
+ if (source) {
5546
+ log.reads.push({
5547
+ root: source.root,
5548
+ path: source.path,
5549
+ op: "value",
5550
+ value: source.raw
5551
+ });
5552
+ return source.raw;
5553
+ }
5554
+ if (Array.isArray(value)) {
5555
+ const next = value.map(release);
5556
+ return next.some((entry, index) => entry !== value[index]) ? next : value;
5557
+ }
5558
+ if (Object.getPrototypeOf(value) !== Object.prototype) return value;
5559
+ let changed = false;
5560
+ const next = {};
5561
+ for (const [key, entry] of Object.entries(value)) {
5562
+ next[key] = release(entry);
5563
+ if (next[key] !== entry) changed = true;
5564
+ }
5565
+ return changed ? next : value;
5566
+ };
5567
+ const entityView = (root, raw) => {
5568
+ let existing = entityViews.get(root);
5569
+ if (!existing) {
5570
+ existing = view(raw, root, []);
5571
+ entityViews.set(root, existing);
5572
+ }
5573
+ return existing;
5574
+ };
5575
+ return {
5576
+ log,
5577
+ graph: view(graph, "graph", []),
5578
+ edge: (edge) => entityView(`edge:${edge.id}`, edge),
5579
+ /** Swap any views in a router result for raw values, logging them as reads. */
5580
+ release: (result) => release(result),
5581
+ getEntityBounds: (id) => {
5582
+ const bounds = getEntityBounds(id);
5583
+ if (!log.bounds.has(id)) log.bounds.set(id, bounds && { ...bounds });
5584
+ return bounds;
5585
+ }
5586
+ };
5587
+ }
5588
+ /** Whether every logged read resolves to the same value against `graph`. */
5589
+ function routerReadsUnchanged(log, graph, edgesById, getEntityBounds, valuesEqual) {
5590
+ let nodesById;
5591
+ const resolveRoot = (root) => {
5592
+ if (root === "graph") return graph;
5593
+ if (root.startsWith("edge:")) return edgesById.get(root.slice(5));
5594
+ nodesById ??= new Map(graph.nodes.map((node) => [node.id, node]));
5595
+ return nodesById.get(root.slice(5));
5596
+ };
5597
+ for (const read of log.reads) {
5598
+ let current = resolveRoot(read.root);
5599
+ if (current === void 0) return false;
5600
+ if (read.op === "value") {
5601
+ for (const key of read.path) {
5602
+ if (!current || typeof current !== "object") return false;
5603
+ current = current[key];
5604
+ }
5605
+ if (!valuesEqual(current, read.value)) return false;
5606
+ continue;
5607
+ }
5608
+ const parentPath = read.op === "keys" ? read.path : read.path.slice(0, -1);
5609
+ for (const key of parentPath) {
5610
+ if (!current || typeof current !== "object") return false;
5611
+ current = current[key];
5612
+ }
5613
+ if (!current || typeof current !== "object") return false;
5614
+ const key = read.path[read.path.length - 1];
5615
+ if (read.op === "keys") {
5616
+ if (stringKeys(current) !== read.value) return false;
5617
+ } else if (read.op === "has") {
5618
+ if (Reflect.has(current, key) !== read.value) return false;
5619
+ } else if (classify(read.root, parentPath, current[key]) !== read.value) return false;
5620
+ }
5621
+ for (const [id, bounds] of log.bounds) if (!valuesEqual(bounds, getEntityBounds(id))) return false;
5622
+ return true;
5623
+ }
5624
+ //#endregion
5426
5625
  //#region src/config.ts
5427
5626
  /** Default config: supported editing behaviors enabled */
5428
5627
  const defaultConfig = {
@@ -5481,6 +5680,17 @@ function normalizeConnection(proposed, graph) {
5481
5680
  }
5482
5681
  const SPATIAL_CELL_SIZE = 512;
5483
5682
  const MAX_ENTITY_SPATIAL_CELLS = 4096;
5683
+ const REPLAY_MISS = Symbol("replay miss");
5684
+ /** Structural equality for plain path data (objects, arrays, primitives). */
5685
+ function plainDataEqual(a, b) {
5686
+ if (a === b) return true;
5687
+ if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
5688
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
5689
+ const aRecord = a;
5690
+ const bRecord = b;
5691
+ const aKeys = Object.keys(aRecord);
5692
+ return aKeys.length === Object.keys(bRecord).length && aKeys.every((key) => plainDataEqual(aRecord[key], bRecord[key]));
5693
+ }
5484
5694
  /**
5485
5695
  * Create the framework-agnostic derived-geometry and query layer for a store.
5486
5696
  *
@@ -5497,6 +5707,7 @@ function createFlowEngine(store, initialOptions = {}) {
5497
5707
  }
5498
5708
  let snapshotEdgePathsCache = /* @__PURE__ */ new WeakMap();
5499
5709
  let stableEdgePathsCache = /* @__PURE__ */ new WeakMap();
5710
+ let edgeSourceBoundsContextReads = null;
5500
5711
  const snapOffsetCache = /* @__PURE__ */ new WeakMap();
5501
5712
  let renderableCache = /* @__PURE__ */ new WeakMap();
5502
5713
  let entityOrderCache = null;
@@ -5650,6 +5861,9 @@ function createFlowEngine(store, initialOptions = {}) {
5650
5861
  nodeIndexCache = /* @__PURE__ */ new WeakMap();
5651
5862
  obstacleCache = /* @__PURE__ */ new WeakMap();
5652
5863
  edgePathMemo.clear();
5864
+ lastCanonicalEdgePaths = null;
5865
+ lastRouting = null;
5866
+ routerReadTrackingDisabled = false;
5653
5867
  const appearances = replace ? partial.appearances ?? {} : partial.appearances;
5654
5868
  if (appearances !== void 0 && appearances !== previousAppearances) store.trigger.configure({ appearances });
5655
5869
  }
@@ -5670,8 +5884,8 @@ function createFlowEngine(store, initialOptions = {}) {
5670
5884
  byOwner.set(key, obstacles);
5671
5885
  return obstacles;
5672
5886
  }
5673
- function edgeObstacles(edge, c) {
5674
- const owner = edgeOwnerOf(edge, c);
5887
+ /** Both endpoints and their ancestors: never obstacles for their own edge. */
5888
+ function edgeEndpointLineage(edge, c) {
5675
5889
  const nodeIndex = indexNodes(c.graph.nodes);
5676
5890
  const endpointLineage = /* @__PURE__ */ new Set();
5677
5891
  for (const endpointId of [edge.sourceId, edge.targetId]) {
@@ -5681,6 +5895,11 @@ function createFlowEngine(store, initialOptions = {}) {
5681
5895
  node = node.parentId ? nodeIndex.get(node.parentId) : void 0;
5682
5896
  }
5683
5897
  }
5898
+ return endpointLineage;
5899
+ }
5900
+ function edgeObstacles(edge, c) {
5901
+ const owner = edgeOwnerOf(edge, c);
5902
+ const endpointLineage = edgeEndpointLineage(edge, c);
5684
5903
  const result = [];
5685
5904
  for (const { id, bounds } of ownerObstacles(owner, c)) {
5686
5905
  if (endpointLineage.has(id)) continue;
@@ -5768,6 +5987,9 @@ function createFlowEngine(store, initialOptions = {}) {
5768
5987
  }
5769
5988
  return withLayoutOffset(resolvedBounds$1(node), node.id, c);
5770
5989
  }
5990
+ let lastCanonicalEdgePaths = null;
5991
+ let lastRouting = null;
5992
+ let routerReadTrackingDisabled = false;
5771
5993
  const edgePathMemo = /* @__PURE__ */ new Map();
5772
5994
  let edgePathMemoInputs = null;
5773
5995
  function layoutOffset(id, c = ctx()) {
@@ -6569,7 +6791,7 @@ function createFlowEngine(store, initialOptions = {}) {
6569
6791
  const resolvedSourceBounds = engineOptions.resolveEdgeSourceBounds?.({
6570
6792
  edge,
6571
6793
  graph,
6572
- context,
6794
+ context: edgeSourceBoundsContextReads ? trackContextReads(context, edgeSourceBoundsContextReads) : context,
6573
6795
  source,
6574
6796
  target,
6575
6797
  sourceBounds: naturalSourceBounds,
@@ -6605,6 +6827,16 @@ function createFlowEngine(store, initialOptions = {}) {
6605
6827
  layoutOffsets: c.layoutAnimation.offsets
6606
6828
  };
6607
6829
  }
6830
+ function trackContextReads(context, reads) {
6831
+ return new Proxy(context, { get(target, key, receiver) {
6832
+ reads.add(key);
6833
+ return Reflect.get(target, key, receiver);
6834
+ } });
6835
+ }
6836
+ function sameContextReads(previous, next, reads) {
6837
+ for (const key of reads) if (previous[key] !== next[key]) return false;
6838
+ return true;
6839
+ }
6608
6840
  function sameEdgePathsCacheInputs(a, b) {
6609
6841
  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;
6610
6842
  }
@@ -6616,14 +6848,28 @@ function createFlowEngine(store, initialOptions = {}) {
6616
6848
  const cached = byGraph?.get(graph);
6617
6849
  if (cached) return cached;
6618
6850
  const snap = getVisualSnapOffset();
6619
- const canReuseAcrossSnapshots = !engineOptions.isVisible && !engineOptions.config?.visible && !engineOptions.resolveEdgeSourceBounds && !engineOptions.edgeOwner;
6851
+ const canReuseAcrossSnapshots = !engineOptions.isVisible && !engineOptions.config?.visible && !engineOptions.edgeOwner;
6620
6852
  const inputs = edgePathsCacheInputs(c, snap);
6621
6853
  const stableCached = canReuseAcrossSnapshots ? stableEdgePathsCache.get(graph) : void 0;
6622
- const paths = stableCached && sameEdgePathsCacheInputs(stableCached.inputs, inputs) ? stableCached.paths : computeAllEdgePaths(c, graph, snap);
6623
- if (canReuseAcrossSnapshots && paths !== stableCached?.paths) stableEdgePathsCache.set(graph, {
6624
- inputs,
6625
- paths
6626
- });
6854
+ let paths;
6855
+ if (stableCached && sameEdgePathsCacheInputs(stableCached.inputs, inputs) && sameContextReads(stableCached.context, c, stableCached.contextReads)) paths = stableCached.paths;
6856
+ else {
6857
+ const outerReads = edgeSourceBoundsContextReads;
6858
+ const contextReads = /* @__PURE__ */ new Set();
6859
+ edgeSourceBoundsContextReads = contextReads;
6860
+ try {
6861
+ paths = computeAllEdgePaths(c, graph, snap);
6862
+ } finally {
6863
+ edgeSourceBoundsContextReads = outerReads;
6864
+ for (const key of contextReads) outerReads?.add(key);
6865
+ }
6866
+ if (canReuseAcrossSnapshots) stableEdgePathsCache.set(graph, {
6867
+ inputs,
6868
+ paths,
6869
+ context: c,
6870
+ contextReads
6871
+ });
6872
+ }
6627
6873
  if (!byGraph) {
6628
6874
  byGraph = /* @__PURE__ */ new WeakMap();
6629
6875
  snapshotEdgePathsCache.set(c, byGraph);
@@ -6631,11 +6877,115 @@ function createFlowEngine(store, initialOptions = {}) {
6631
6877
  byGraph.set(graph, paths);
6632
6878
  return paths;
6633
6879
  }
6880
+ /**
6881
+ * Route every edge. A custom router that has not declared `endpoints`
6882
+ * dependencies reads through tracked views of the edge and graph. When a
6883
+ * later pass finds every logged read unchanged and the same calls with the
6884
+ * same inputs, it reuses the previous results instead of calling the router,
6885
+ * so edits the router never looked at (a node's color, say) skip routing.
6886
+ * Any difference reroutes the whole pass, which keeps routers that share
6887
+ * work across calls exact.
6888
+ */
6634
6889
  function computeAllEdgePaths(c, graph, snap = getVisualSnapOffset()) {
6890
+ const router = engineOptions.edgeRouter;
6891
+ if (!router || engineOptions.edgeRouterDependencies === "endpoints" || graph !== c.graph || routerReadTrackingDisabled) return computeEdgePathsPass(c, graph, snap, "plain");
6892
+ const previous = lastRouting?.router === router ? lastRouting : null;
6893
+ if (previous) try {
6894
+ return computeEdgePathsPass(c, graph, snap, previous);
6895
+ } catch (error) {
6896
+ if (error !== REPLAY_MISS) throw error;
6897
+ }
6898
+ try {
6899
+ return computeEdgePathsPass(c, graph, snap, "record");
6900
+ } catch {
6901
+ routerReadTrackingDisabled = true;
6902
+ lastRouting = null;
6903
+ return computeEdgePathsPass(c, graph, snap, "plain");
6904
+ }
6905
+ }
6906
+ function createRoute(c, graph, edgeMap, getEntityBounds, mode) {
6907
+ const router = engineOptions.edgeRouter ?? bezierRouter;
6908
+ if (mode === "plain") return {
6909
+ route: (edge, _key, values, getObstacles) => router(edge, {
6910
+ graph,
6911
+ getEntityBounds,
6912
+ ...values,
6913
+ get obstacles() {
6914
+ return getObstacles();
6915
+ }
6916
+ }),
6917
+ finish: () => {}
6918
+ };
6919
+ if (mode === "record") {
6920
+ const tracker = createRouterReadTracker(graph, getEntityBounds);
6921
+ const calls = [];
6922
+ const owners = /* @__PURE__ */ new Map();
6923
+ return {
6924
+ route: (edge, key, values, getObstacles) => {
6925
+ const call = {
6926
+ key,
6927
+ values,
6928
+ result: void 0
6929
+ };
6930
+ call.result = tracker.release(router(tracker.edge(edge), {
6931
+ graph: tracker.graph,
6932
+ getEntityBounds: tracker.getEntityBounds,
6933
+ ...values,
6934
+ get obstacles() {
6935
+ if (!call.obstacles) {
6936
+ const owner = edgeOwnerOf(edge, c);
6937
+ if (!owners.has(owner)) owners.set(owner, ownerObstacles(owner, c));
6938
+ call.obstacles = {
6939
+ owner,
6940
+ lineage: [...edgeEndpointLineage(edge, c)].join("\0")
6941
+ };
6942
+ }
6943
+ return getObstacles();
6944
+ }
6945
+ }));
6946
+ calls.push(call);
6947
+ return call.result;
6948
+ },
6949
+ finish: () => {
6950
+ lastRouting = {
6951
+ router,
6952
+ log: tracker.log,
6953
+ owners,
6954
+ calls
6955
+ };
6956
+ }
6957
+ };
6958
+ }
6959
+ const edgesById = new Map([...edgeMap, ...foldedEdgesFor(c).byId]);
6960
+ if (!routerReadsUnchanged(mode.log, graph, edgesById, getEntityBounds, plainDataEqual)) throw REPLAY_MISS;
6961
+ const ownersUnchanged = /* @__PURE__ */ new Map();
6962
+ const obstaclesUnchanged = (edge, recorded) => {
6963
+ const owner = edgeOwnerOf(edge, c);
6964
+ if (owner !== recorded.owner) return false;
6965
+ let unchanged = ownersUnchanged.get(owner);
6966
+ if (unchanged === void 0) {
6967
+ unchanged = plainDataEqual(mode.owners.get(owner), ownerObstacles(owner, c));
6968
+ ownersUnchanged.set(owner, unchanged);
6969
+ }
6970
+ return unchanged && [...edgeEndpointLineage(edge, c)].join("\0") === recorded.lineage;
6971
+ };
6972
+ let index = 0;
6973
+ return {
6974
+ route: (edge, key, values) => {
6975
+ const call = mode.calls[index++];
6976
+ if (!call || call.key !== key || !plainDataEqual(call.values, values) || call.obstacles && !obstaclesUnchanged(edge, call.obstacles)) throw REPLAY_MISS;
6977
+ return call.result;
6978
+ },
6979
+ finish: () => {
6980
+ if (index !== mode.calls.length) throw REPLAY_MISS;
6981
+ }
6982
+ };
6983
+ }
6984
+ function computeEdgePathsPass(c, graph, snap, mode) {
6635
6985
  const paths = /* @__PURE__ */ new Map();
6636
6986
  const nodeMap = indexNodes(graph.nodes);
6637
6987
  const edgeMap = indexEdges(graph.edges);
6638
- const getEntityBounds = createRouterEntityBoundsLookup(graph, snap, nodeMap, edgeMap);
6988
+ const { route, finish: finishRouting } = createRoute(c, graph, edgeMap, createRouterEntityBoundsLookup(graph, snap, nodeMap, edgeMap), mode);
6639
6989
  const computing = /* @__PURE__ */ new Set();
6640
6990
  const trackSourceDependencies = graph === c.graph;
6641
6991
  const nextEdgeSourceDependents = trackSourceDependencies ? /* @__PURE__ */ new Map() : edgeSourceDependents;
@@ -6703,58 +7053,45 @@ function createFlowEngine(store, initialOptions = {}) {
6703
7053
  const labelConnectionBounds = connectionBounds(edge.id, edge.label, labelBounds);
6704
7054
  const srcDir = portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, labelConnectionBounds);
6705
7055
  const lblDir1 = connectionDirection(edge.label, labelConnectionBounds, sourceBounds);
6706
- const seg1 = (engineOptions.edgeRouter ?? bezierRouter)(edge, {
6707
- graph,
6708
- getEntityBounds,
7056
+ const seg1 = route(edge, `${edge.id}:0`, {
6709
7057
  sourceBounds,
6710
7058
  targetBounds: labelConnectionBounds,
6711
7059
  sourceDirection: srcDir,
6712
7060
  targetDirection: lblDir1,
6713
7061
  sourcePoint: resolveEndpointPoint(source, sourceBounds, edge.sourcePort, labelConnectionBounds, srcDir, snap),
6714
- waypoints,
6715
- get obstacles() {
6716
- return getObstacles();
6717
- }
6718
- });
7062
+ waypoints
7063
+ }, getObstacles);
6719
7064
  const lblDir2 = connectionDirection(edge.label, labelConnectionBounds, targetBounds);
6720
7065
  const tgtDir = portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, labelConnectionBounds);
6721
7066
  pathData = {
6722
- segments: [seg1, (engineOptions.edgeRouter ?? bezierRouter)(edge, {
6723
- graph,
6724
- getEntityBounds,
7067
+ segments: [seg1, route(edge, `${edge.id}:1`, {
6725
7068
  sourceBounds: labelConnectionBounds,
6726
7069
  targetBounds,
6727
7070
  sourceDirection: lblDir2,
6728
7071
  targetDirection: tgtDir,
6729
7072
  targetPoint: resolveEndpointPoint(target, targetBounds, edge.targetPort, labelConnectionBounds, tgtDir, snap),
6730
- waypoints,
6731
- get obstacles() {
6732
- return getObstacles();
6733
- }
6734
- })],
7073
+ waypoints
7074
+ }, getObstacles)],
6735
7075
  labelBounds
6736
7076
  };
6737
7077
  } else {
6738
7078
  const srcDir = portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, targetBounds);
6739
7079
  const tgtDir = portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, sourceBounds);
6740
7080
  pathData = {
6741
- segments: [(engineOptions.edgeRouter ?? bezierRouter)(edge, {
6742
- graph,
6743
- getEntityBounds,
7081
+ segments: [route(edge, `${edge.id}:0`, {
6744
7082
  sourceBounds,
6745
7083
  targetBounds,
6746
7084
  sourceDirection: srcDir,
6747
7085
  targetDirection: tgtDir,
6748
7086
  sourcePoint,
6749
7087
  targetPoint,
6750
- waypoints,
6751
- get obstacles() {
6752
- return getObstacles();
6753
- }
6754
- })],
7088
+ waypoints
7089
+ }, getObstacles)],
6755
7090
  labelBounds: null
6756
7091
  };
6757
7092
  }
7093
+ const previousPath = trackSourceDependencies ? lastCanonicalEdgePaths?.get(edge.id) : void 0;
7094
+ if (previousPath && plainDataEqual(previousPath, pathData)) pathData = previousPath;
6758
7095
  paths.set(edge.id, pathData);
6759
7096
  if (memoizableEdge) edgePathMemo.set(edge.id, {
6760
7097
  edge,
@@ -6766,7 +7103,11 @@ function createFlowEngine(store, initialOptions = {}) {
6766
7103
  return pathData;
6767
7104
  };
6768
7105
  for (const edge of [...graph.edges, ...foldedEdgesFor(c).edges]) computeEdgePath(edge);
6769
- if (trackSourceDependencies) edgeSourceDependents = nextEdgeSourceDependents;
7106
+ finishRouting();
7107
+ if (trackSourceDependencies) {
7108
+ edgeSourceDependents = nextEdgeSourceDependents;
7109
+ lastCanonicalEdgePaths = paths;
7110
+ }
6770
7111
  if (memoUsable && edgePathMemo.size > graph.edges.length * 2 + 16) edgePathMemo.clear();
6771
7112
  return paths;
6772
7113
  }
@@ -6917,13 +7258,13 @@ function createFlowEngine(store, initialOptions = {}) {
6917
7258
  if (cullMode === "viewport" && !rectsIntersect(hierarchyBounds(n, c), cullRect)) return false;
6918
7259
  return true;
6919
7260
  });
6920
- const edgePaths = getAllEdgePaths();
7261
+ const edgePaths = cullMode === "viewport" ? getAllEdgePaths() : void 0;
6921
7262
  return {
6922
7263
  nodes,
6923
7264
  edges: order.edges.filter((e) => {
6924
7265
  if (!isEdgeVisible(e, c.graph, c, vp)) return false;
6925
7266
  if (cullMode !== "viewport") return true;
6926
- const path = edgePaths.get(e.id);
7267
+ const path = edgePaths?.get(e.id);
6927
7268
  if (e.label) {
6928
7269
  const labelRect = path?.labelBounds ?? getEdgeLabelBounds(e.id);
6929
7270
  if (!labelRect) return false;
@@ -7631,8 +7972,8 @@ function equal(a, b) {
7631
7972
  if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((value, index) => equal(value, b[index]));
7632
7973
  const aRecord = a;
7633
7974
  const bRecord = b;
7634
- const aKeys = Object.keys(aRecord);
7635
- const bKeys = Object.keys(bRecord);
7975
+ const aKeys = Object.keys(aRecord).filter((key) => aRecord[key] !== void 0);
7976
+ const bKeys = Object.keys(bRecord).filter((key) => bRecord[key] !== void 0);
7636
7977
  return aKeys.length === bKeys.length && aKeys.every((key) => Object.prototype.hasOwnProperty.call(bRecord, key) && equal(aRecord[key], bRecord[key]));
7637
7978
  }
7638
7979
  function graphAttrs(graph) {
@@ -7780,6 +8121,33 @@ function createFlowChangeSet(before, after, metadata) {
7780
8121
  inverse
7781
8122
  };
7782
8123
  }
8124
+ /**
8125
+ * Swap each entity the change set did not add or update for its object in
8126
+ * `before`, so memoized views keyed on entity identity skip unchanged
8127
+ * entities. An updated edge keeps its previous label object when the label is
8128
+ * unchanged. Arrays whose entries all match `before` are kept too. Mutates and
8129
+ * returns `after`, which must be a fresh clone.
8130
+ */
8131
+ function reuseUnchangedEntities(before, after, changeSet) {
8132
+ const changedNodeIds = /* @__PURE__ */ new Set([...(changeSet?.nodes.added ?? []).map((node) => node.id), ...(changeSet?.nodes.updated ?? []).map((update) => update.id)]);
8133
+ const changedEdgeIds = /* @__PURE__ */ new Set([...(changeSet?.edges.added ?? []).map((edge) => edge.id), ...(changeSet?.edges.updated ?? []).map((update) => update.id)]);
8134
+ const beforeNodes = new Map(before.nodes.map((node) => [node.id, node]));
8135
+ const beforeEdges = new Map(before.edges.map((edge) => [edge.id, edge]));
8136
+ const nodes = after.nodes.map((node) => changedNodeIds.has(node.id) ? node : beforeNodes.get(node.id) ?? node);
8137
+ const edges = after.edges.map((edge) => {
8138
+ const previous = beforeEdges.get(edge.id);
8139
+ if (!previous) return edge;
8140
+ if (!changedEdgeIds.has(edge.id)) return previous;
8141
+ if (previous.label && equal(previous.label, edge.label)) edge.label = previous.label;
8142
+ return edge;
8143
+ });
8144
+ after.nodes = sameEntries(nodes, before.nodes) ? before.nodes : nodes;
8145
+ after.edges = sameEntries(edges, before.edges) ? before.edges : edges;
8146
+ return after;
8147
+ }
8148
+ function sameEntries(left, right) {
8149
+ return left.length === right.length && left.every((value, index) => value === right[index]);
8150
+ }
7783
8151
  function strictConflict(path, message) {
7784
8152
  return new FlowGraphValidationError([{
7785
8153
  code: "change_set_conflict",
@@ -8862,13 +9230,14 @@ function createFlow(options = {}) {
8862
9230
  return null;
8863
9231
  }
8864
9232
  if (!replacementOptions) validateDraftConnections(validated);
8865
- const changeSet = createFlowChangeSet(currentGraph(), validated, {
9233
+ const before = currentGraph();
9234
+ const changeSet = createFlowChangeSet(before, validated, {
8866
9235
  revision: graphRevision + 1,
8867
9236
  ...transactionOptions
8868
9237
  });
8869
9238
  if (!changeSet && !replacementOptions && !layoutAnimationOffsets && !resetMeasurementIds.length) return null;
8870
9239
  store.trigger.replaceGraph({
8871
- graph: validated,
9240
+ graph: reuseUnchangedEntities(before, validated, changeSet),
8872
9241
  graphChanged: changeSet !== null,
8873
9242
  resetMeasurementIds,
8874
9243
  ...transactionOptions,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statelyai/flow",
3
- "version": "0.13.1",
3
+ "version": "0.13.3",
4
4
  "description": "Framework-agnostic flow visualization engine. Builds on @statelyai/graph.",
5
5
  "type": "module",
6
6
  "sideEffects": true,