@statelyai/flow 0.13.4 → 0.15.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.
Files changed (115) hide show
  1. package/README.md +5 -1
  2. package/dist/esm/index.d.ts +13 -2
  3. package/dist/esm/index.d.ts.map +1 -0
  4. package/dist/esm/index.js +39 -14
  5. package/dist/esm/index.js.map +1 -0
  6. package/dist/esm/layout/dagre.d.ts +2 -1
  7. package/dist/esm/layout/dagre.d.ts.map +1 -0
  8. package/dist/esm/layout/dagre.js +2 -0
  9. package/dist/esm/layout/dagre.js.map +1 -0
  10. package/dist/esm/layout/elk.d.ts +2 -1
  11. package/dist/esm/layout/elk.d.ts.map +1 -0
  12. package/dist/esm/layout/elk.js +2 -0
  13. package/dist/esm/layout/elk.js.map +1 -0
  14. package/dist/esm/layout/stately.d.ts +2 -1
  15. package/dist/esm/layout/stately.d.ts.map +1 -0
  16. package/dist/esm/layout/stately.js +2 -0
  17. package/dist/esm/layout/stately.js.map +1 -0
  18. package/dist/esm/shared.d.ts +2 -1
  19. package/dist/esm/shared.d.ts.map +1 -0
  20. package/dist/esm/shared.js +2 -0
  21. package/dist/esm/shared.js.map +1 -0
  22. package/package.json +4 -3
  23. package/src/__fixtures__/nested.ts +106 -0
  24. package/src/appearances.test.ts +428 -0
  25. package/src/appearances.ts +144 -0
  26. package/src/authoritative-route.ts +14 -0
  27. package/src/changeSet.test.ts +132 -0
  28. package/src/changeSet.ts +337 -0
  29. package/src/config.ts +41 -0
  30. package/src/configure.test.ts +212 -0
  31. package/src/connection-lifetime.ts +1 -0
  32. package/src/connectionPreview.test.ts +102 -0
  33. package/src/connectionPreview.ts +82 -0
  34. package/src/content.ts +203 -0
  35. package/src/createFlow.fit-frame.test.ts +256 -0
  36. package/src/createFlow.modern.test.ts +743 -0
  37. package/src/createFlow.test.ts +632 -0
  38. package/src/createFlow.ts +3463 -0
  39. package/src/createFlow.view.test.ts +212 -0
  40. package/src/createFlow.viewport-controls.test.ts +221 -0
  41. package/src/edge-geometry.ts +318 -0
  42. package/src/engine.cache.test.ts +728 -0
  43. package/src/engine.hierarchy.test.ts +1023 -0
  44. package/src/engine.test.ts +1965 -0
  45. package/src/engine.ts +3385 -0
  46. package/src/entity-changes.test.ts +309 -0
  47. package/src/entity-changes.ts +395 -0
  48. package/src/examples/flow-based-math.test.ts +25 -0
  49. package/src/examples/flow-based-math.ts +210 -0
  50. package/src/external-edit.test.ts +337 -0
  51. package/src/external-edit.ts +358 -0
  52. package/src/factories.test.ts +104 -0
  53. package/src/factories.ts +70 -0
  54. package/src/geometry.ts +13 -0
  55. package/src/graph-index.test.ts +56 -0
  56. package/src/graph-index.ts +194 -0
  57. package/src/hierarchy.test.ts +175 -0
  58. package/src/hierarchy.ts +330 -0
  59. package/src/highlights.test.ts +130 -0
  60. package/src/index.ts +469 -0
  61. package/src/input/index.ts +615 -0
  62. package/src/input/input.test.ts +2577 -0
  63. package/src/input/keymap.ts +111 -0
  64. package/src/input/modes.ts +1715 -0
  65. package/src/input/reparent.test.ts +214 -0
  66. package/src/layout/dagre.ts +138 -0
  67. package/src/layout/elk.ts +1382 -0
  68. package/src/layout/index.ts +12 -0
  69. package/src/layout/layout.test.ts +1248 -0
  70. package/src/layout/shared.ts +260 -0
  71. package/src/layout/stately-globals.d.ts +9 -0
  72. package/src/layout/stately.test.ts +246 -0
  73. package/src/layout/stately.ts +528 -0
  74. package/src/layout-animation.test.ts +223 -0
  75. package/src/layout-contract.test.ts +414 -0
  76. package/src/marker.test.ts +23 -0
  77. package/src/marker.ts +23 -0
  78. package/src/measurement-anchor.test.ts +232 -0
  79. package/src/minimap.test.ts +96 -0
  80. package/src/minimap.ts +137 -0
  81. package/src/nested-fixture.test.ts +178 -0
  82. package/src/port-measurement.test.ts +27 -0
  83. package/src/port-measurements.test.ts +187 -0
  84. package/src/profile.ts +124 -0
  85. package/src/projections.test.ts +103 -0
  86. package/src/projections.ts +295 -0
  87. package/src/render-invalidation.test.ts +62 -0
  88. package/src/render-invalidation.ts +55 -0
  89. package/src/renderer-geometry.test.ts +356 -0
  90. package/src/renderer-transactions.test.ts +234 -0
  91. package/src/routing/avoid.ts +417 -0
  92. package/src/routing/index.test.ts +361 -0
  93. package/src/routing/index.ts +366 -0
  94. package/src/routing/readTracking.test.ts +103 -0
  95. package/src/routing/readTracking.ts +233 -0
  96. package/src/selection-commands.test.ts +355 -0
  97. package/src/serialize.test.ts +167 -0
  98. package/src/serialize.ts +254 -0
  99. package/src/shapes/index.test.ts +45 -0
  100. package/src/shapes/index.ts +142 -0
  101. package/src/snap.test.ts +123 -0
  102. package/src/snap.ts +395 -0
  103. package/src/spatial.test.ts +676 -0
  104. package/src/spatial.ts +457 -0
  105. package/src/store/index.ts +4121 -0
  106. package/src/store.test.ts +2903 -0
  107. package/src/toolbar.test.ts +31 -0
  108. package/src/toolbar.ts +62 -0
  109. package/src/types.test.ts +15 -0
  110. package/src/types.ts +487 -0
  111. package/src/validation.ts +558 -0
  112. package/src/view.ts +172 -0
  113. package/src/viewport/animate.ts +285 -0
  114. package/src/viewport/index.ts +296 -0
  115. package/src/viewport.test.ts +569 -0
@@ -0,0 +1,366 @@
1
+ import type {
2
+ Direction,
3
+ FlowEdge,
4
+ FlowGraph,
5
+ FlowNode,
6
+ PathData,
7
+ Point,
8
+ Rect,
9
+ } from '../types';
10
+
11
+
12
+ // Edge routing
13
+ //
14
+ // Configurable router functions. Engine provides built-in routers.
15
+ // Renderers convert PathData to SVG/Canvas.
16
+
17
+
18
+ export type EdgeRouterGraph<
19
+ TNodeData = any,
20
+ TEdgeData = any,
21
+ TLabelData = any,
22
+ > = Omit<FlowGraph<TNodeData, TEdgeData, TLabelData>, 'nodes' | 'edges'> & {
23
+ readonly nodes: readonly FlowNode<TNodeData>[];
24
+ readonly edges: readonly FlowEdge<TEdgeData, TLabelData>[];
25
+ };
26
+
27
+ export type EdgeRouterContext<
28
+ TEdgeData = any,
29
+ TLabelData = any,
30
+ TNodeData = any,
31
+ > = {
32
+ /** Exact canonical or caller-provided projection graph currently being routed. */
33
+ graph: EdgeRouterGraph<TNodeData, TEdgeData, TLabelData>;
34
+ /**
35
+ * Current visual bounds for a node or positioned edge label in `graph`.
36
+ * Results are detached read-only values; looking up an edge never routes it.
37
+ */
38
+ getEntityBounds: (id: string) => Readonly<Rect> | undefined;
39
+ sourceBounds: Rect;
40
+ targetBounds: Rect;
41
+ sourceDirection: Direction;
42
+ targetDirection: Direction;
43
+ sourcePoint?: Point;
44
+ targetPoint?: Point;
45
+ waypoints?: readonly Point[];
46
+ /**
47
+ * Sibling node bounds that custom routers can use for obstacle avoidance.
48
+ *
49
+ * @experimental Population rules may change as built-in obstacle routing lands.
50
+ */
51
+ obstacles: Rect[];
52
+ };
53
+
54
+ /**
55
+ * Deterministic edge-routing function.
56
+ *
57
+ * Routers should depend only on the edge and supplied routing context. Do not
58
+ * read viewport or external mutable state. With the default `graph`
59
+ * dependencies, the edge and `context.graph` are read-only views that record
60
+ * each field the router reads; Flow reuses a pass's paths while every recorded
61
+ * read and every call's inputs are unchanged. A router that freezes or clones
62
+ * those views is routed without tracking.
63
+ */
64
+ export type EdgeRouter<
65
+ TEdgeData = any,
66
+ TLabelData = any,
67
+ TNodeData = any,
68
+ > = (
69
+ edge: Readonly<FlowEdge<TEdgeData, TLabelData>>,
70
+ context: EdgeRouterContext<TEdgeData, TLabelData, TNodeData>,
71
+ ) => PathData;
72
+
73
+ export type BezierRouterOptions = {
74
+ curvature?: number;
75
+ minOffset?: number;
76
+ };
77
+
78
+ export type StepRouterOptions = {
79
+ offset?: number;
80
+ };
81
+
82
+ export {
83
+ avoidRouter,
84
+ configureAvoidRouter,
85
+ type AvoidRouterOptions,
86
+ } from './avoid';
87
+
88
+ // Built-in: straight
89
+
90
+
91
+ export const straightRouter: EdgeRouter = (_edge, ctx) => {
92
+ const source = ctx.sourcePoint ?? centerOf(ctx.sourceBounds);
93
+ const target = ctx.targetPoint ?? centerOf(ctx.targetBounds);
94
+ return {
95
+ points: [source, ...(ctx.waypoints ?? []), target],
96
+ sourceDirection: ctx.sourceDirection,
97
+ targetDirection: ctx.targetDirection,
98
+ };
99
+ };
100
+
101
+
102
+ // Built-in: step (orthogonal with one bend)
103
+
104
+
105
+ export const stepRouter: EdgeRouter = (_edge, ctx) => {
106
+ const source = ctx.sourcePoint ?? edgeMidpoint(ctx.sourceBounds, ctx.sourceDirection);
107
+ const target = ctx.targetPoint ?? edgeMidpoint(ctx.targetBounds, ctx.targetDirection);
108
+ if (ctx.waypoints?.length) {
109
+ return {
110
+ points: orthogonalPath(source, [...ctx.waypoints, target], ctx.sourceDirection),
111
+ sourceDirection: ctx.sourceDirection,
112
+ targetDirection: ctx.targetDirection,
113
+ };
114
+ }
115
+ const mid = computeStepMidpoint(source, target, ctx.sourceDirection);
116
+
117
+ return {
118
+ points: [source, mid, target],
119
+ sourceDirection: ctx.sourceDirection,
120
+ targetDirection: ctx.targetDirection,
121
+ };
122
+ };
123
+
124
+
125
+ // Built-in: bezier (cubic bezier control points)
126
+
127
+
128
+ export const bezierRouter: EdgeRouter = (_edge, ctx) => {
129
+ const source = ctx.sourcePoint ?? edgeMidpoint(ctx.sourceBounds, ctx.sourceDirection);
130
+ const target = ctx.targetPoint ?? edgeMidpoint(ctx.targetBounds, ctx.targetDirection);
131
+ return bezierPath(source, target, ctx, {});
132
+ };
133
+
134
+ export function configureBezierRouter(options: BezierRouterOptions = {}): EdgeRouter {
135
+ return (_edge, ctx) => {
136
+ const source = ctx.sourcePoint ?? edgeMidpoint(ctx.sourceBounds, ctx.sourceDirection);
137
+ const target = ctx.targetPoint ?? edgeMidpoint(ctx.targetBounds, ctx.targetDirection);
138
+ return bezierPath(source, target, ctx, options);
139
+ };
140
+ }
141
+
142
+ export function configureStepRouter(options: StepRouterOptions = {}): EdgeRouter {
143
+ return (_edge, ctx) => {
144
+ const source = ctx.sourcePoint ?? edgeMidpoint(ctx.sourceBounds, ctx.sourceDirection);
145
+ const target = ctx.targetPoint ?? edgeMidpoint(ctx.targetBounds, ctx.targetDirection);
146
+ const mid = computeStepMidpoint(source, target, ctx.sourceDirection, options.offset);
147
+
148
+ return {
149
+ points: [source, mid, target],
150
+ sourceDirection: ctx.sourceDirection,
151
+ targetDirection: ctx.targetDirection,
152
+ };
153
+ };
154
+ }
155
+
156
+ function bezierPath(
157
+ source: Point,
158
+ target: Point,
159
+ ctx: EdgeRouterContext,
160
+ options: BezierRouterOptions,
161
+ ): PathData {
162
+ if (ctx.waypoints?.length) {
163
+ return {
164
+ points: [source, ...ctx.waypoints, target],
165
+ sourceDirection: ctx.sourceDirection,
166
+ targetDirection: ctx.targetDirection,
167
+ };
168
+ }
169
+ const curvature = options.curvature ?? 0.25;
170
+ const offset = Math.max(
171
+ options.minOffset ?? 50,
172
+ Math.abs(target.x - source.x) * curvature,
173
+ Math.abs(target.y - source.y) * curvature,
174
+ );
175
+
176
+ const cp1 = offsetPoint(source, ctx.sourceDirection, offset);
177
+ const cp2 = offsetPoint(target, ctx.targetDirection, offset);
178
+
179
+ return {
180
+ points: [source, cp1, cp2, target],
181
+ sourceDirection: ctx.sourceDirection,
182
+ targetDirection: ctx.targetDirection,
183
+ };
184
+ }
185
+
186
+ function orthogonalPath(
187
+ source: Point,
188
+ targets: Point[],
189
+ sourceDir: Direction,
190
+ ): Point[] {
191
+ const points: Point[] = [source];
192
+ let current = source;
193
+ let direction = sourceDir;
194
+ for (const target of targets) {
195
+ const mid = computeStepMidpoint(current, target, direction);
196
+ pushDistinct(points, mid);
197
+ pushDistinct(points, target);
198
+ direction =
199
+ Math.abs(target.x - current.x) > Math.abs(target.y - current.y)
200
+ ? target.x >= current.x ? 'right' : 'left'
201
+ : target.y >= current.y ? 'bottom' : 'top';
202
+ current = target;
203
+ }
204
+ return points;
205
+ }
206
+
207
+ function pushDistinct(points: Point[], point: Point): void {
208
+ const last = points.at(-1);
209
+ if (last && last.x === point.x && last.y === point.y) return;
210
+ points.push(point);
211
+ }
212
+
213
+
214
+ // Helpers
215
+
216
+
217
+ function centerOf(rect: Rect): Point {
218
+ return {
219
+ x: rect.x + rect.width / 2,
220
+ y: rect.y + rect.height / 2,
221
+ };
222
+ }
223
+
224
+ function edgeMidpoint(rect: Rect, direction: Direction): Point {
225
+ switch (direction) {
226
+ case 'top':
227
+ return { x: rect.x + rect.width / 2, y: rect.y };
228
+ case 'bottom':
229
+ return { x: rect.x + rect.width / 2, y: rect.y + rect.height };
230
+ case 'left':
231
+ return { x: rect.x, y: rect.y + rect.height / 2 };
232
+ case 'right':
233
+ return { x: rect.x + rect.width, y: rect.y + rect.height / 2 };
234
+ }
235
+ }
236
+
237
+ function offsetPoint(point: Point, direction: Direction, offset: number): Point {
238
+ switch (direction) {
239
+ case 'top':
240
+ return { x: point.x, y: point.y - offset };
241
+ case 'bottom':
242
+ return { x: point.x, y: point.y + offset };
243
+ case 'left':
244
+ return { x: point.x - offset, y: point.y };
245
+ case 'right':
246
+ return { x: point.x + offset, y: point.y };
247
+ }
248
+ }
249
+
250
+ function computeStepMidpoint(
251
+ source: Point,
252
+ target: Point,
253
+ sourceDir: Direction,
254
+ offset?: number,
255
+ ): Point {
256
+ if (offset !== undefined) {
257
+ if (sourceDir === 'left') return { x: source.x - offset, y: target.y };
258
+ if (sourceDir === 'right') return { x: source.x + offset, y: target.y };
259
+ if (sourceDir === 'top') return { x: target.x, y: source.y - offset };
260
+ return { x: target.x, y: source.y + offset };
261
+ }
262
+ if (sourceDir === 'left' || sourceDir === 'right') {
263
+ return { x: (source.x + target.x) / 2, y: source.y };
264
+ }
265
+ return { x: source.x, y: (source.y + target.y) / 2 };
266
+ }
267
+
268
+ /**
269
+ * Determine the side of `from` that faces `to`, based on relative centers.
270
+ * The returned direction is from the perspective of `from`.
271
+ */
272
+ export function bestDirection(from: Rect, to: Rect): Direction {
273
+ const fromCx = from.x + from.width / 2;
274
+ const fromCy = from.y + from.height / 2;
275
+ const toCx = to.x + to.width / 2;
276
+ const toCy = to.y + to.height / 2;
277
+
278
+ const dx = toCx - fromCx;
279
+ const dy = toCy - fromCy;
280
+
281
+ if (Math.abs(dx) > Math.abs(dy)) {
282
+ return dx > 0 ? 'right' : 'left';
283
+ }
284
+ return dy > 0 ? 'bottom' : 'top';
285
+ }
286
+
287
+ /**
288
+ * Convert PathData to an SVG path `d` attribute. A valid router-provided
289
+ * `svgPath` takes precedence over point-derived geometry.
290
+ * Handles 2 points (line), 3 points (quadratic), 4 points (cubic bezier).
291
+ */
292
+ export function pathToSVG(path: PathData): string {
293
+ const pts = path.points;
294
+ if (
295
+ pts.length < 2 ||
296
+ pts.some(({ x, y }) => !Number.isFinite(x) || !Number.isFinite(y))
297
+ ) {
298
+ return '';
299
+ }
300
+
301
+ const svgPath = validSvgPath(path.svgPath);
302
+ if (svgPath) return svgPath;
303
+
304
+ const [p0, p1, p2, p3] = pts;
305
+ if (!p0) return '';
306
+
307
+ const start = `M ${p0.x} ${p0.y}`;
308
+
309
+ if (path.routing === 'polyline' || path.routing === 'orthogonal') {
310
+ return start + pts.slice(1).map((p) => ` L ${p.x} ${p.y}`).join('');
311
+ }
312
+
313
+ if (
314
+ path.routing === 'splines' &&
315
+ pts.length >= 4 &&
316
+ (pts.length - 1) % 3 === 0
317
+ ) {
318
+ let result = start;
319
+ for (let index = 1; index + 2 < pts.length; index += 3) {
320
+ const p1 = pts[index]!;
321
+ const p2 = pts[index + 1]!;
322
+ const p3 = pts[index + 2]!;
323
+ result += ` C ${p1.x} ${p1.y}, ${p2.x} ${p2.y}, ${p3.x} ${p3.y}`;
324
+ }
325
+ return result;
326
+ }
327
+
328
+ if (pts.length === 2 && p1) {
329
+ return `${start} L ${p1.x} ${p1.y}`;
330
+ }
331
+
332
+ if (pts.length === 3 && p1 && p2) {
333
+ // Orthogonal step: line segments
334
+ return `${start} L ${p1.x} ${p1.y} L ${p2.x} ${p2.y}`;
335
+ }
336
+
337
+ if (pts.length === 4 && p1 && p2 && p3) {
338
+ // Cubic bezier
339
+ return `${start} C ${p1.x} ${p1.y}, ${p2.x} ${p2.y}, ${p3.x} ${p3.y}`;
340
+ }
341
+
342
+ // Fallback: polyline
343
+ return start + pts.slice(1).map((p) => ` L ${p.x} ${p.y}`).join('');
344
+ }
345
+
346
+ const SVG_NUMBER_PATTERN = /[-+]?(?:\d*\.?\d+)(?:[eE][-+]?\d+)?/g;
347
+ const NON_FINITE_SVG_TOKEN = /NaN|[-+]?Infinity/i;
348
+ const SVG_PATH_TOKEN_PATTERN = /[MmZzLlHhVvCcSsQqTtAa]|[-+]?(?:\d*\.?\d+)(?:[eE][-+]?\d+)?/g;
349
+
350
+ export function isValidSvgPath(value: unknown): value is string {
351
+ if (typeof value !== 'string') return false;
352
+ const trimmed = value.trim();
353
+ if (!trimmed || !/^[Mm]/.test(trimmed) || NON_FINITE_SVG_TOKEN.test(trimmed)) {
354
+ return false;
355
+ }
356
+ const numbers = [...trimmed.matchAll(SVG_NUMBER_PATTERN)];
357
+ if (!numbers.length || numbers.some((match) => !Number.isFinite(Number(match[0])))) {
358
+ return false;
359
+ }
360
+ return trimmed.replace(SVG_PATH_TOKEN_PATTERN, '').replace(/[\s,]/g, '') === '';
361
+ }
362
+
363
+ function validSvgPath(svgPath: string | undefined): string | undefined {
364
+ const trimmed = svgPath?.trim();
365
+ return isValidSvgPath(trimmed) ? trimmed : undefined;
366
+ }
@@ -0,0 +1,103 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createEdge, createGraph, createNode } from '../factories';
3
+ import type { FlowGraph, Rect } from '../types';
4
+ import { createRouterReadTracker, routerReadsUnchanged } from './readTracking';
5
+
6
+ function makeGraph(): FlowGraph {
7
+ return createGraph({
8
+ nodes: [
9
+ createNode({ id: 'a', x: 0, data: { color: 'gray', tags: ['x'] } }),
10
+ createNode({ id: 'b', x: 200 }),
11
+ ],
12
+ edges: [createEdge({ id: 'ab', sourceId: 'a', targetId: 'b' })],
13
+ });
14
+ }
15
+
16
+ function withNode(graph: FlowGraph, id: string, patch: object): FlowGraph {
17
+ return {
18
+ ...graph,
19
+ nodes: graph.nodes.map((node) => (node.id === id ? { ...node, ...patch } : node)),
20
+ };
21
+ }
22
+
23
+ const bounds = (): Rect | undefined => undefined;
24
+ const sameRect = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
25
+
26
+ function track(graph: FlowGraph, read: (view: FlowGraph) => unknown) {
27
+ const tracker = createRouterReadTracker(graph, bounds);
28
+ const value = read(tracker.graph);
29
+ const unchanged = (next: FlowGraph) =>
30
+ routerReadsUnchanged(
31
+ tracker.log,
32
+ next,
33
+ new Map(next.edges.map((edge) => [edge.id, edge])),
34
+ bounds,
35
+ sameRect,
36
+ );
37
+ return { value, unchanged };
38
+ }
39
+
40
+ describe('router read tracking', () => {
41
+ it('returns the same values as the graph through common read patterns', () => {
42
+ const graph = makeGraph();
43
+ const { value } = track(graph, (view) => ({
44
+ ids: view.nodes.map((node) => node.id),
45
+ spread: { ...view.nodes[0]!.data },
46
+ keys: Object.keys(view.nodes[1]!),
47
+ json: JSON.parse(JSON.stringify(view.edges)),
48
+ iterated: [...view.nodes].length,
49
+ has: 'data' in view.nodes[0]!,
50
+ isArray: Array.isArray(view.nodes),
51
+ }));
52
+
53
+ expect(value).toEqual({
54
+ ids: ['a', 'b'],
55
+ spread: { color: 'gray', tags: ['x'] },
56
+ keys: Object.keys(graph.nodes[1]!),
57
+ json: JSON.parse(JSON.stringify(graph.edges)),
58
+ iterated: 2,
59
+ has: true,
60
+ isArray: true,
61
+ });
62
+ });
63
+
64
+ it('ignores changes to fields that were not read', () => {
65
+ const graph = makeGraph();
66
+ const { unchanged } = track(graph, (view) => view.nodes.map((node) => node.x));
67
+
68
+ expect(unchanged(withNode(graph, 'a', { data: { color: 'red', tags: ['x'] } }))).toBe(true);
69
+ expect(unchanged(withNode(graph, 'b', { x: 250 }))).toBe(false);
70
+ });
71
+
72
+ it('detects changes to read nested fields, key sets and membership', () => {
73
+ const graph = makeGraph();
74
+ const nested = track(graph, (view) => (view.nodes[0]!.data as { color: string }).color);
75
+ expect(nested.unchanged(withNode(graph, 'a', { data: { color: 'red', tags: ['x'] } }))).toBe(false);
76
+
77
+ const keys = track(graph, (view) => Object.keys(view.nodes[0]!.data as object));
78
+ expect(keys.unchanged(withNode(graph, 'a', { data: { color: 'gray', tags: ['x'], size: 2 } }))).toBe(false);
79
+
80
+ const membership = track(graph, (view) => view.nodes.length);
81
+ expect(membership.unchanged({ ...graph, nodes: [graph.nodes[0]!] })).toBe(false);
82
+
83
+ const order = track(graph, (view) => view.nodes[0]!.id);
84
+ expect(order.unchanged({ ...graph, nodes: [...graph.nodes].reverse() })).toBe(false);
85
+ });
86
+
87
+ it('keeps one view per entity so identity caches stay stable', () => {
88
+ const graph = makeGraph();
89
+ const tracker = createRouterReadTracker(graph, bounds);
90
+
91
+ expect(tracker.graph.nodes[0]).toBe(tracker.graph.nodes[0]);
92
+ expect(tracker.edge(graph.edges[0]!)).toBe(tracker.graph.edges[0]);
93
+ });
94
+
95
+ it('rejects writes', () => {
96
+ const tracker = createRouterReadTracker(makeGraph(), bounds);
97
+
98
+ expect(() => {
99
+ 'use strict';
100
+ (tracker.graph.nodes[0] as { x: number }).x = 5;
101
+ }).toThrow(TypeError);
102
+ });
103
+ });
@@ -0,0 +1,233 @@
1
+ import type { FlowEdge, FlowGraph, Rect } from '../types';
2
+
3
+ // Router read tracking
4
+ //
5
+ // A custom router may read anything on the edge and the routing graph. To
6
+ // reuse its paths across graph changes that it never looked at (a node's
7
+ // color, say), the routing pass hands it read-only proxies that record every
8
+ // field read, `in` check, and key listing, keyed by entity so the check can
9
+ // resolve them in the next graph. Reads are recorded for the whole pass, not
10
+ // per call, because routers may share work across calls (batch caches). A view
11
+ // the router hands back in its result is swapped for the raw value, and its
12
+ // whole value becomes a dependency.
13
+
14
+ export type RouterRead = {
15
+ /** `graph`, `node:<id>`, or `edge:<id>`. */
16
+ root: string;
17
+ path: readonly string[];
18
+ op: 'get' | 'has' | 'keys' | 'value';
19
+ value: unknown;
20
+ };
21
+
22
+ export type RouterReadLog = {
23
+ reads: RouterRead[];
24
+ bounds: Map<string, Rect | undefined>;
25
+ };
26
+
27
+ const OBJECT = '[object]';
28
+ const ARRAY = '[array]';
29
+ const FUNCTION = '[function]';
30
+
31
+ function entityRootFor(root: string, path: readonly string[], value: unknown): string | null {
32
+ if (root !== 'graph' || path.length !== 1) return null;
33
+ if (!value || typeof value !== 'object') return null;
34
+ const id = (value as { id?: unknown }).id;
35
+ if (typeof id !== 'string') return null;
36
+ if (path[0] === 'nodes') return `node:${id}`;
37
+ if (path[0] === 'edges') return `edge:${id}`;
38
+ return null;
39
+ }
40
+
41
+ function classify(root: string, path: readonly string[], value: unknown): unknown {
42
+ const entityRoot = entityRootFor(root, path, value);
43
+ if (entityRoot) return entityRoot;
44
+ if (typeof value === 'function') return FUNCTION;
45
+ if (value && typeof value === 'object') return Array.isArray(value) ? ARRAY : OBJECT;
46
+ return value;
47
+ }
48
+
49
+ function stringKeys(value: object): string {
50
+ return Reflect.ownKeys(value)
51
+ .filter((key): key is string => typeof key === 'string')
52
+ .join('\u0000');
53
+ }
54
+
55
+ /**
56
+ * Read-only views of `graph` and its entities that log what a router reads.
57
+ * Views are stable for the tracker's lifetime, so routers that cache by
58
+ * object identity see the same graph and entity objects across calls.
59
+ */
60
+ export function createRouterReadTracker(
61
+ graph: FlowGraph,
62
+ getEntityBounds: (id: string) => Readonly<Rect> | undefined,
63
+ ) {
64
+ const log: RouterReadLog = { reads: [], bounds: new Map() };
65
+ const entityViews = new Map<string, object>();
66
+ const sources = new WeakMap<object, { raw: object; root: string; path: readonly string[] }>();
67
+
68
+ const view = (raw: object, root: string, path: readonly string[]): object => {
69
+ const children = new Map<string, unknown>();
70
+ const logged = new Set<string>();
71
+ const record = (op: RouterRead['op'], key: string | null, value: unknown) => {
72
+ const id = `${op}\u0000${key ?? ''}`;
73
+ if (logged.has(id)) return;
74
+ logged.add(id);
75
+ log.reads.push({ root, path: key === null ? path : [...path, key], op, value });
76
+ };
77
+ const child = (key: string): unknown => {
78
+ if (children.has(key)) return children.get(key);
79
+ const value = (raw as Record<string, unknown>)[key];
80
+ let result = value;
81
+ if (value && typeof value === 'object') {
82
+ const entityRoot = entityRootFor(root, path, value);
83
+ result = entityRoot
84
+ ? entityView(entityRoot, value)
85
+ : view(value, root, [...path, key]);
86
+ }
87
+ children.set(key, result);
88
+ return result;
89
+ };
90
+ const proxy = new Proxy(Array.isArray(raw) ? [] : {}, {
91
+ get(_target, key) {
92
+ if (typeof key === 'symbol') return Reflect.get(raw, key);
93
+ record('get', key, classify(root, path, (raw as Record<string, unknown>)[key]));
94
+ return child(key);
95
+ },
96
+ has(_target, key) {
97
+ const result = Reflect.has(raw, key);
98
+ if (typeof key === 'string') record('has', key, result);
99
+ return result;
100
+ },
101
+ ownKeys() {
102
+ record('keys', null, stringKeys(raw));
103
+ return Reflect.ownKeys(raw);
104
+ },
105
+ getOwnPropertyDescriptor(_target, key) {
106
+ const descriptor = Reflect.getOwnPropertyDescriptor(raw, key);
107
+ if (typeof key === 'string') {
108
+ // `Object.hasOwn` and descriptor reads skip the `has` and `get` traps.
109
+ record('has', key, descriptor !== undefined);
110
+ if (descriptor) {
111
+ record('get', key, classify(root, path, (raw as Record<string, unknown>)[key]));
112
+ }
113
+ }
114
+ if (!descriptor) return undefined;
115
+ if (Array.isArray(raw) && key === 'length') {
116
+ return { value: raw.length, writable: true, enumerable: false, configurable: false };
117
+ }
118
+ return {
119
+ value: typeof key === 'string' ? child(key) : Reflect.get(raw, key),
120
+ writable: false,
121
+ enumerable: descriptor.enumerable,
122
+ configurable: true,
123
+ };
124
+ },
125
+ getPrototypeOf() {
126
+ return Reflect.getPrototypeOf(raw);
127
+ },
128
+ set() {
129
+ return false;
130
+ },
131
+ defineProperty() {
132
+ return false;
133
+ },
134
+ deleteProperty() {
135
+ return false;
136
+ },
137
+ });
138
+ sources.set(proxy, { raw, root, path });
139
+ return proxy;
140
+ };
141
+
142
+ const release = (value: unknown): unknown => {
143
+ if (!value || typeof value !== 'object') return value;
144
+ const source = sources.get(value);
145
+ if (source) {
146
+ log.reads.push({ root: source.root, path: source.path, op: 'value', value: source.raw });
147
+ return source.raw;
148
+ }
149
+ if (Array.isArray(value)) {
150
+ const next = value.map(release);
151
+ return next.some((entry, index) => entry !== value[index]) ? next : value;
152
+ }
153
+ if (Object.getPrototypeOf(value) !== Object.prototype) return value;
154
+ let changed = false;
155
+ const next: Record<string, unknown> = {};
156
+ for (const [key, entry] of Object.entries(value)) {
157
+ next[key] = release(entry);
158
+ if (next[key] !== entry) changed = true;
159
+ }
160
+ return changed ? next : value;
161
+ };
162
+
163
+ const entityView = (root: string, raw: object): object => {
164
+ let existing = entityViews.get(root);
165
+ if (!existing) {
166
+ existing = view(raw, root, []);
167
+ entityViews.set(root, existing);
168
+ }
169
+ return existing;
170
+ };
171
+
172
+ return {
173
+ log,
174
+ graph: view(graph, 'graph', []) as FlowGraph,
175
+ edge: (edge: FlowEdge): FlowEdge => entityView(`edge:${edge.id}`, edge) as FlowEdge,
176
+ /** Swap any views in a router result for raw values, logging them as reads. */
177
+ release: <T>(result: T): T => release(result) as T,
178
+ getEntityBounds: (id: string): Readonly<Rect> | undefined => {
179
+ const bounds = getEntityBounds(id);
180
+ if (!log.bounds.has(id)) log.bounds.set(id, bounds && { ...bounds });
181
+ return bounds;
182
+ },
183
+ };
184
+ }
185
+
186
+ /** Whether every logged read resolves to the same value against `graph`. */
187
+ export function routerReadsUnchanged(
188
+ log: RouterReadLog,
189
+ graph: FlowGraph,
190
+ edgesById: ReadonlyMap<string, FlowEdge>,
191
+ getEntityBounds: (id: string) => Readonly<Rect> | undefined,
192
+ valuesEqual: (a: unknown, b: unknown) => boolean,
193
+ ): boolean {
194
+ let nodesById: Map<string, unknown> | undefined;
195
+ const resolveRoot = (root: string): unknown => {
196
+ if (root === 'graph') return graph;
197
+ if (root.startsWith('edge:')) return edgesById.get(root.slice(5));
198
+ nodesById ??= new Map(graph.nodes.map((node) => [node.id, node]));
199
+ return nodesById.get(root.slice(5));
200
+ };
201
+ for (const read of log.reads) {
202
+ let current = resolveRoot(read.root);
203
+ if (current === undefined) return false;
204
+ if (read.op === 'value') {
205
+ for (const key of read.path) {
206
+ if (!current || typeof current !== 'object') return false;
207
+ current = (current as Record<string, unknown>)[key];
208
+ }
209
+ if (!valuesEqual(current, read.value)) return false;
210
+ continue;
211
+ }
212
+ const parentPath = read.op === 'keys' ? read.path : read.path.slice(0, -1);
213
+ for (const key of parentPath) {
214
+ if (!current || typeof current !== 'object') return false;
215
+ current = (current as Record<string, unknown>)[key];
216
+ }
217
+ if (!current || typeof current !== 'object') return false;
218
+ const key = read.path[read.path.length - 1]!;
219
+ if (read.op === 'keys') {
220
+ if (stringKeys(current) !== read.value) return false;
221
+ } else if (read.op === 'has') {
222
+ if (Reflect.has(current, key) !== read.value) return false;
223
+ } else if (
224
+ classify(read.root, parentPath, (current as Record<string, unknown>)[key]) !== read.value
225
+ ) {
226
+ return false;
227
+ }
228
+ }
229
+ for (const [id, bounds] of log.bounds) {
230
+ if (!valuesEqual(bounds, getEntityBounds(id))) return false;
231
+ }
232
+ return true;
233
+ }