@statelyai/flow 0.14.0 → 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.
- package/README.md +2 -1
- package/dist/esm/index.d.ts +5 -2
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +19 -14
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/layout/dagre.d.ts +2 -1
- package/dist/esm/layout/dagre.d.ts.map +1 -0
- package/dist/esm/layout/dagre.js +2 -0
- package/dist/esm/layout/dagre.js.map +1 -0
- package/dist/esm/layout/elk.d.ts +2 -1
- package/dist/esm/layout/elk.d.ts.map +1 -0
- package/dist/esm/layout/elk.js +2 -0
- package/dist/esm/layout/elk.js.map +1 -0
- package/dist/esm/layout/stately.d.ts +2 -1
- package/dist/esm/layout/stately.d.ts.map +1 -0
- package/dist/esm/layout/stately.js +2 -0
- package/dist/esm/layout/stately.js.map +1 -0
- package/dist/esm/shared.d.ts +2 -1
- package/dist/esm/shared.d.ts.map +1 -0
- package/dist/esm/shared.js +2 -0
- package/dist/esm/shared.js.map +1 -0
- package/package.json +4 -3
- package/src/__fixtures__/nested.ts +106 -0
- package/src/appearances.test.ts +428 -0
- package/src/appearances.ts +144 -0
- package/src/authoritative-route.ts +14 -0
- package/src/changeSet.test.ts +132 -0
- package/src/changeSet.ts +337 -0
- package/src/config.ts +41 -0
- package/src/configure.test.ts +212 -0
- package/src/connection-lifetime.ts +1 -0
- package/src/connectionPreview.test.ts +102 -0
- package/src/connectionPreview.ts +82 -0
- package/src/content.ts +203 -0
- package/src/createFlow.fit-frame.test.ts +256 -0
- package/src/createFlow.modern.test.ts +743 -0
- package/src/createFlow.test.ts +632 -0
- package/src/createFlow.ts +3463 -0
- package/src/createFlow.view.test.ts +212 -0
- package/src/createFlow.viewport-controls.test.ts +221 -0
- package/src/edge-geometry.ts +318 -0
- package/src/engine.cache.test.ts +728 -0
- package/src/engine.hierarchy.test.ts +1023 -0
- package/src/engine.test.ts +1965 -0
- package/src/engine.ts +3385 -0
- package/src/entity-changes.test.ts +309 -0
- package/src/entity-changes.ts +395 -0
- package/src/examples/flow-based-math.test.ts +25 -0
- package/src/examples/flow-based-math.ts +210 -0
- package/src/external-edit.test.ts +337 -0
- package/src/external-edit.ts +358 -0
- package/src/factories.test.ts +104 -0
- package/src/factories.ts +70 -0
- package/src/geometry.ts +13 -0
- package/src/graph-index.test.ts +56 -0
- package/src/graph-index.ts +194 -0
- package/src/hierarchy.test.ts +175 -0
- package/src/hierarchy.ts +330 -0
- package/src/highlights.test.ts +130 -0
- package/src/index.ts +469 -0
- package/src/input/index.ts +615 -0
- package/src/input/input.test.ts +2577 -0
- package/src/input/keymap.ts +111 -0
- package/src/input/modes.ts +1715 -0
- package/src/input/reparent.test.ts +214 -0
- package/src/layout/dagre.ts +138 -0
- package/src/layout/elk.ts +1382 -0
- package/src/layout/index.ts +12 -0
- package/src/layout/layout.test.ts +1248 -0
- package/src/layout/shared.ts +260 -0
- package/src/layout/stately-globals.d.ts +9 -0
- package/src/layout/stately.test.ts +246 -0
- package/src/layout/stately.ts +528 -0
- package/src/layout-animation.test.ts +223 -0
- package/src/layout-contract.test.ts +414 -0
- package/src/marker.test.ts +23 -0
- package/src/marker.ts +23 -0
- package/src/measurement-anchor.test.ts +232 -0
- package/src/minimap.test.ts +96 -0
- package/src/minimap.ts +137 -0
- package/src/nested-fixture.test.ts +178 -0
- package/src/port-measurement.test.ts +27 -0
- package/src/port-measurements.test.ts +187 -0
- package/src/profile.ts +124 -0
- package/src/projections.test.ts +103 -0
- package/src/projections.ts +295 -0
- package/src/render-invalidation.test.ts +62 -0
- package/src/render-invalidation.ts +55 -0
- package/src/renderer-geometry.test.ts +356 -0
- package/src/renderer-transactions.test.ts +234 -0
- package/src/routing/avoid.ts +417 -0
- package/src/routing/index.test.ts +361 -0
- package/src/routing/index.ts +366 -0
- package/src/routing/readTracking.test.ts +103 -0
- package/src/routing/readTracking.ts +233 -0
- package/src/selection-commands.test.ts +355 -0
- package/src/serialize.test.ts +167 -0
- package/src/serialize.ts +254 -0
- package/src/shapes/index.test.ts +45 -0
- package/src/shapes/index.ts +142 -0
- package/src/snap.test.ts +123 -0
- package/src/snap.ts +395 -0
- package/src/spatial.test.ts +676 -0
- package/src/spatial.ts +457 -0
- package/src/store/index.ts +4121 -0
- package/src/store.test.ts +2903 -0
- package/src/toolbar.test.ts +31 -0
- package/src/toolbar.ts +62 -0
- package/src/types.test.ts +15 -0
- package/src/types.ts +487 -0
- package/src/validation.ts +558 -0
- package/src/view.ts +172 -0
- package/src/viewport/animate.ts +285 -0
- package/src/viewport/index.ts +296 -0
- package/src/viewport.test.ts +569 -0
package/src/engine.ts
ADDED
|
@@ -0,0 +1,3385 @@
|
|
|
1
|
+
import { resolveAppearance, appearanceAllowsPort, appearanceDirection, appearanceMeasurementId, type FlowAppearances } from './appearances';
|
|
2
|
+
import type {
|
|
3
|
+
Direction,
|
|
4
|
+
EdgePathData,
|
|
5
|
+
FlowConfig,
|
|
6
|
+
FlowEdge,
|
|
7
|
+
FlowEdgeLabel,
|
|
8
|
+
FlowGraph,
|
|
9
|
+
FlowEntityRef,
|
|
10
|
+
FlowNode,
|
|
11
|
+
LabelAnchor,
|
|
12
|
+
PathData,
|
|
13
|
+
Point,
|
|
14
|
+
Rect,
|
|
15
|
+
Viewport,
|
|
16
|
+
VisualPort,
|
|
17
|
+
} from './types';
|
|
18
|
+
import type { FlowStore, FlowStoreContext } from './store';
|
|
19
|
+
import { screenToCanvas as _screenToCanvas, canvasToScreen as _canvasToScreen, getVisibleBounds } from './viewport';
|
|
20
|
+
import { getShapeOrDefault } from './shapes';
|
|
21
|
+
import type { EdgeRouter, EdgeRouterContext } from './routing';
|
|
22
|
+
import { bezierRouter, bestDirection, pathToSVG } from './routing';
|
|
23
|
+
import {
|
|
24
|
+
createRouterReadTracker,
|
|
25
|
+
routerReadsUnchanged,
|
|
26
|
+
type RouterReadLog,
|
|
27
|
+
} from './routing/readTracking';
|
|
28
|
+
import { resolvedPosition, resolvedBounds as baseResolvedBounds, resolvedSelectionBounds, resolvedSize as baseResolvedSize, resolvedEdgeLabelSize as baseResolvedEdgeLabelSize, snappedBounds as baseSnappedBounds, getGraphBounds, rectsIntersect, rectContains, snapToGrid, unionRect } from './spatial';
|
|
29
|
+
import { resolveBehavior } from './config';
|
|
30
|
+
import { getSnapLines } from './snap';
|
|
31
|
+
import type { SnapResult } from './snap';
|
|
32
|
+
import {
|
|
33
|
+
authoritativeEdgePath,
|
|
34
|
+
isPointNearPath,
|
|
35
|
+
pathBounds,
|
|
36
|
+
} from './edge-geometry';
|
|
37
|
+
import {
|
|
38
|
+
getConnectedEdges as getGraphConnectedEdges,
|
|
39
|
+
getIncomers as getGraphIncomers,
|
|
40
|
+
getNeighbors as getGraphNeighbors,
|
|
41
|
+
getOutgoers as getGraphOutgoers,
|
|
42
|
+
indexNodes,
|
|
43
|
+
indexEdges,
|
|
44
|
+
indexChildren,
|
|
45
|
+
nodeDepths,
|
|
46
|
+
} from './graph-index';
|
|
47
|
+
import {
|
|
48
|
+
deriveGroupGeometry,
|
|
49
|
+
fixedGroupGeometry,
|
|
50
|
+
getEdgeOwnerFromIndex as defaultEdgeOwnerFromIndex,
|
|
51
|
+
isDerivedGroup,
|
|
52
|
+
type GroupGeometry,
|
|
53
|
+
} from './hierarchy';
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
// Shared, immutable "no folded edges" result. Returned by `foldedEdgesFor`
|
|
57
|
+
// when nothing is collapsed, avoiding a per-snapshot O(E) loop + Map alloc.
|
|
58
|
+
// Callers only read (spread `.edges` / `.byId.get`), never mutate.
|
|
59
|
+
const EMPTY_FOLDED: { edges: FlowEdge[]; byId: Map<string, FlowEdge> } =
|
|
60
|
+
Object.freeze({
|
|
61
|
+
edges: Object.freeze([]) as unknown as FlowEdge[],
|
|
62
|
+
byId: new Map<string, FlowEdge>(),
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
function offsetEdgeWaypoints(
|
|
66
|
+
edge: FlowEdge,
|
|
67
|
+
offset: Point = { x: edge.dx ?? 0, y: edge.dy ?? 0 },
|
|
68
|
+
): Point[] | undefined {
|
|
69
|
+
if (!edge.waypoints?.length) return edge.waypoints;
|
|
70
|
+
const { x: dx, y: dy } = offset;
|
|
71
|
+
if (dx === 0 && dy === 0) return edge.waypoints;
|
|
72
|
+
return edge.waypoints.map((point) => ({
|
|
73
|
+
x: point.x + dx,
|
|
74
|
+
y: point.y + dy,
|
|
75
|
+
}));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
// FlowEngine — purely derived projection over FlowStore
|
|
80
|
+
//
|
|
81
|
+
// No mutable state. All interaction state lives in the store.
|
|
82
|
+
// The engine provides computed queries and convenience accessors.
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
export type ProposedConnection = {
|
|
86
|
+
sourceId: string;
|
|
87
|
+
targetId: string;
|
|
88
|
+
sourcePort?: string | null;
|
|
89
|
+
targetPort?: string | null;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export function normalizeConnection(proposed: ProposedConnection, graph: FlowGraph): ProposedConnection {
|
|
93
|
+
const source = graph.nodes.find((node) => node.id === proposed.sourceId);
|
|
94
|
+
const port = source?.ports?.find((port) => port.name === proposed.sourcePort);
|
|
95
|
+
if (port?.direction !== 'in') return proposed;
|
|
96
|
+
return {
|
|
97
|
+
sourceId: proposed.targetId,
|
|
98
|
+
sourcePort: proposed.targetPort,
|
|
99
|
+
targetId: proposed.sourceId,
|
|
100
|
+
targetPort: proposed.sourcePort,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export type FlowConnectionMode = 'strict' | 'loose';
|
|
105
|
+
|
|
106
|
+
export type EdgeRouterDependencies = 'graph' | 'endpoints' | 'snapshot';
|
|
107
|
+
|
|
108
|
+
export type FlowConnectionOptions = {
|
|
109
|
+
/** Magnet radius in canvas pixels. Default 24. */
|
|
110
|
+
radius?: number;
|
|
111
|
+
/**
|
|
112
|
+
* In strict mode only ports can be connection targets. Loose mode, the
|
|
113
|
+
* default/current behavior, falls back to node body targets.
|
|
114
|
+
*/
|
|
115
|
+
mode?: FlowConnectionMode;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
export type ConnectionCandidateSource = {
|
|
119
|
+
nodeId: string;
|
|
120
|
+
port: string | null;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
export type ConnectionCandidate = {
|
|
124
|
+
nodeId: string;
|
|
125
|
+
portName: string | null;
|
|
126
|
+
position: Point;
|
|
127
|
+
isValid: boolean;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
export type ConnectionCandidateOptions = FlowConnectionOptions & {
|
|
131
|
+
source?: ConnectionCandidateSource;
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
export type ConnectionValidationContext = {
|
|
135
|
+
graph: FlowStoreContext['graph'];
|
|
136
|
+
context: FlowStoreContext;
|
|
137
|
+
source: FlowNode;
|
|
138
|
+
target: FlowNode;
|
|
139
|
+
sourcePort: VisualPort | null;
|
|
140
|
+
targetPort: VisualPort | null;
|
|
141
|
+
connection: FlowStoreContext['connection'];
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
export type ConnectionValidationResult = boolean | { valid: boolean; reason?: string };
|
|
145
|
+
|
|
146
|
+
export type FlowEngineOptions = {
|
|
147
|
+
appearances?: FlowAppearances;
|
|
148
|
+
/** Default edge router (default: bezierRouter) */
|
|
149
|
+
edgeRouter?: EdgeRouter;
|
|
150
|
+
/**
|
|
151
|
+
* Geometry read by a custom edge router. Defaults to `graph`: Flow records
|
|
152
|
+
* what the router reads from the edge, the graph, `getEntityBounds`, and
|
|
153
|
+
* `obstacles` during a routing pass, and reroutes every edge when any of it,
|
|
154
|
+
* any call's geometry, or any other routing state (measurements,
|
|
155
|
+
* appearances, selection, connection, snapping) changes. Use `snapshot`
|
|
156
|
+
* when the router also reads state those views don't cover, such as
|
|
157
|
+
* `flow.getNode()` or measurements through a closure: Flow then reroutes on
|
|
158
|
+
* every graph or routing state change. Use `endpoints` only
|
|
159
|
+
* when the router depends on the edge and its endpoint/label inputs, not
|
|
160
|
+
* arbitrary `graph`, `getEntityBounds`, or `obstacles` reads. That contract
|
|
161
|
+
* lets Flow retain unaffected custom routes by identity.
|
|
162
|
+
*/
|
|
163
|
+
edgeRouterDependencies?: EdgeRouterDependencies;
|
|
164
|
+
/** Default label anchor (default: 'fixed' — labels use their own x/y) */
|
|
165
|
+
labelAnchor?: LabelAnchor;
|
|
166
|
+
/**
|
|
167
|
+
* Override the rect an edge routes from while preserving its graph source.
|
|
168
|
+
* Return null/undefined to keep the normal source node/port bounds.
|
|
169
|
+
*/
|
|
170
|
+
resolveEdgeSourceBounds?: (context: EdgeSourceBoundsContext) => Rect | null | undefined;
|
|
171
|
+
/** Connection validation hook */
|
|
172
|
+
canConnect?: (
|
|
173
|
+
proposed: ProposedConnection,
|
|
174
|
+
context: ConnectionValidationContext,
|
|
175
|
+
) => ConnectionValidationResult;
|
|
176
|
+
/** Connection magnet radius and port-strict/loose targeting behavior. */
|
|
177
|
+
connection?: FlowConnectionOptions;
|
|
178
|
+
/** Elevate selected entities above same-depth/same-zIndex siblings. */
|
|
179
|
+
elevateOnSelect?: { nodes?: boolean; edges?: boolean };
|
|
180
|
+
/** Global behavior config */
|
|
181
|
+
config?: Partial<FlowConfig>;
|
|
182
|
+
/** Custom visibility function */
|
|
183
|
+
isVisible?: (entity: FlowNode | FlowEdge, viewport: Viewport) => boolean;
|
|
184
|
+
/**
|
|
185
|
+
* Which node an edge belongs to (its labels contribute to that group's
|
|
186
|
+
* derived child bounds). Return a node id, null for the root, or undefined
|
|
187
|
+
* to fall back to the default rule: the deepest node containing both
|
|
188
|
+
* endpoints (an endpoint contains itself; self-edges go to the source's
|
|
189
|
+
* parent) — Stately-editor semantics.
|
|
190
|
+
*/
|
|
191
|
+
edgeOwner?: (
|
|
192
|
+
edge: FlowEdge,
|
|
193
|
+
context: FlowStoreContext,
|
|
194
|
+
) => string | null | undefined;
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
export type EdgeSourceBoundsContext = {
|
|
198
|
+
edge: FlowEdge;
|
|
199
|
+
graph: FlowStoreContext['graph'];
|
|
200
|
+
context: FlowStoreContext;
|
|
201
|
+
source: FlowNode;
|
|
202
|
+
target: FlowNode;
|
|
203
|
+
sourceBounds: Rect;
|
|
204
|
+
targetBounds: Rect;
|
|
205
|
+
getEdgeLabelBounds: (edgeId: string) => Rect | null;
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
export type RenderableEntitiesOptions = {
|
|
209
|
+
cull?: 'none' | 'viewport';
|
|
210
|
+
overscan?: number;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
export type EntityOrderOptions = {
|
|
214
|
+
/** Include configured selection elevation. Defaults to true. */
|
|
215
|
+
elevateSelected?: boolean;
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
export type EdgePathOptions = {
|
|
219
|
+
graph?: FlowStoreContext['graph'];
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
type VisualSnapInfo = {
|
|
223
|
+
offset: Point;
|
|
224
|
+
grid: [number, number] | null;
|
|
225
|
+
selection: Set<string>;
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
type EdgePathsCacheInputs = {
|
|
229
|
+
appearances: FlowStoreContext['appearances'];
|
|
230
|
+
canonicalGraph: FlowStoreContext['graph'];
|
|
231
|
+
selection: Set<string>;
|
|
232
|
+
collapsedNodeIds: Set<string>;
|
|
233
|
+
connection: FlowStoreContext['connection'];
|
|
234
|
+
offsetX: number;
|
|
235
|
+
offsetY: number;
|
|
236
|
+
gridX: number | null;
|
|
237
|
+
gridY: number | null;
|
|
238
|
+
resizingEntityId: string | null;
|
|
239
|
+
resizeCorners: FlowStoreContext['resizeCorners'];
|
|
240
|
+
measurements: FlowStoreContext['measurements'];
|
|
241
|
+
layoutOffsets: FlowStoreContext['layoutAnimation']['offsets'];
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
type EntityOrderCache = {
|
|
245
|
+
nodesInput: FlowStoreContext['graph']['nodes'];
|
|
246
|
+
edgesInput: FlowStoreContext['graph']['edges'];
|
|
247
|
+
selectionInput: FlowStoreContext['selection'] | null;
|
|
248
|
+
collapsedInput: FlowStoreContext['collapsedNodeIds'];
|
|
249
|
+
value: { nodes: FlowNode[]; edges: FlowEdge[] };
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
type PaintZIndices = {
|
|
253
|
+
nodes: Map<string, number>;
|
|
254
|
+
edges: Map<string, number>;
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
type RenderableSpatialIndex = {
|
|
258
|
+
nodesInput: FlowStoreContext['graph']['nodes'];
|
|
259
|
+
pathsInput: Map<string, EdgePathData>;
|
|
260
|
+
measurementsInput: FlowStoreContext['measurements'];
|
|
261
|
+
layoutOffsetsInput: FlowStoreContext['layoutAnimation']['offsets'];
|
|
262
|
+
collapsedInput: FlowStoreContext['collapsedNodeIds'];
|
|
263
|
+
nodeCells: Map<string, string[]>;
|
|
264
|
+
edgeCells: Map<string, string[]>;
|
|
265
|
+
globalNodeIds: string[];
|
|
266
|
+
globalEdgeIds: string[];
|
|
267
|
+
nodeBounds: Map<string, Rect>;
|
|
268
|
+
edgeBounds: Map<string, Rect>;
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
const SPATIAL_CELL_SIZE = 512;
|
|
272
|
+
const MAX_ENTITY_SPATIAL_CELLS = 4_096;
|
|
273
|
+
|
|
274
|
+
type RouterCallValues = Omit<EdgeRouterContext, 'graph' | 'getEntityBounds' | 'obstacles'>;
|
|
275
|
+
|
|
276
|
+
type RouteEdge = (
|
|
277
|
+
edge: FlowEdge,
|
|
278
|
+
key: string,
|
|
279
|
+
values: RouterCallValues,
|
|
280
|
+
getObstacles: () => Rect[],
|
|
281
|
+
) => PathData;
|
|
282
|
+
|
|
283
|
+
// `edgeObstacles` is a function of the owner's obstacle list and the
|
|
284
|
+
// endpoints' lineage, so those stand in for the obstacles a call read.
|
|
285
|
+
type RouterCallObstacles = { owner: string | null; lineage: string };
|
|
286
|
+
|
|
287
|
+
type RoutingRecord = {
|
|
288
|
+
router: EdgeRouter;
|
|
289
|
+
inputs: EdgePathsCacheInputs;
|
|
290
|
+
log: RouterReadLog;
|
|
291
|
+
owners: Map<string | null, ReadonlyArray<{ id: string; bounds: Rect }>>;
|
|
292
|
+
calls: {
|
|
293
|
+
key: string;
|
|
294
|
+
values: RouterCallValues;
|
|
295
|
+
obstacles?: RouterCallObstacles;
|
|
296
|
+
result: PathData;
|
|
297
|
+
}[];
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
const REPLAY_MISS = Symbol('replay miss');
|
|
301
|
+
|
|
302
|
+
/** Structural equality for plain path data (objects, arrays, primitives). */
|
|
303
|
+
function plainDataEqual(a: unknown, b: unknown): boolean {
|
|
304
|
+
if (a === b) return true;
|
|
305
|
+
if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;
|
|
306
|
+
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
|
307
|
+
const aRecord = a as Record<string, unknown>;
|
|
308
|
+
const bRecord = b as Record<string, unknown>;
|
|
309
|
+
const aKeys = Object.keys(aRecord);
|
|
310
|
+
return (
|
|
311
|
+
aKeys.length === Object.keys(bRecord).length &&
|
|
312
|
+
aKeys.every((key) => plainDataEqual(aRecord[key], bRecord[key]))
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Create the framework-agnostic derived-geometry and query layer for a store.
|
|
318
|
+
*
|
|
319
|
+
* The engine owns memoized graph indices, paint order, bounds, routing, and
|
|
320
|
+
* hit-testing. Returned collections are read-only views and may retain identity
|
|
321
|
+
* while their semantic inputs are unchanged.
|
|
322
|
+
*/
|
|
323
|
+
export function createFlowEngine(store: FlowStore, initialOptions: FlowEngineOptions = {}) {
|
|
324
|
+
let engineOptions = initialOptions;
|
|
325
|
+
let optionsVersion = 0;
|
|
326
|
+
const edgeHitTolerance = 8;
|
|
327
|
+
|
|
328
|
+
function ctx(): FlowStoreContext {
|
|
329
|
+
return store.getSnapshot().context;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Exact per-snapshot cache plus a graph-keyed cache for snapshots whose
|
|
333
|
+
// routing inputs are unchanged (notably every frame of a viewport pan).
|
|
334
|
+
let snapshotEdgePathsCache = new WeakMap<
|
|
335
|
+
FlowStoreContext,
|
|
336
|
+
WeakMap<object, Map<string, EdgePathData>>
|
|
337
|
+
>();
|
|
338
|
+
let stableEdgePathsCache = new WeakMap<
|
|
339
|
+
object,
|
|
340
|
+
{
|
|
341
|
+
inputs: EdgePathsCacheInputs;
|
|
342
|
+
paths: Map<string, EdgePathData>;
|
|
343
|
+
context: FlowStoreContext;
|
|
344
|
+
contextReads: ReadonlySet<PropertyKey>;
|
|
345
|
+
}
|
|
346
|
+
>();
|
|
347
|
+
// Store-context keys `resolveEdgeSourceBounds` reads while the paths being
|
|
348
|
+
// cached are computed. Null outside that computation.
|
|
349
|
+
let edgeSourceBoundsContextReads: Set<PropertyKey> | null = null;
|
|
350
|
+
const snapOffsetCache = new WeakMap<FlowStoreContext, VisualSnapInfo>();
|
|
351
|
+
let renderableCache = new WeakMap<
|
|
352
|
+
FlowStoreContext,
|
|
353
|
+
Map<string, { nodes: FlowNode[]; edges: FlowEdge[] }>
|
|
354
|
+
>();
|
|
355
|
+
let entityOrderCache: EntityOrderCache | null = null;
|
|
356
|
+
let baseEntityOrderCache: EntityOrderCache | null = null;
|
|
357
|
+
let paintZIndicesCache = new WeakMap<
|
|
358
|
+
FlowStoreContext,
|
|
359
|
+
Map<string, PaintZIndices>
|
|
360
|
+
>();
|
|
361
|
+
let entityRankCache: {
|
|
362
|
+
order: EntityOrderCache['value'];
|
|
363
|
+
nodes: Map<string, number>;
|
|
364
|
+
edges: Map<string, number>;
|
|
365
|
+
} | null = null;
|
|
366
|
+
let renderableSpatialIndex: RenderableSpatialIndex | null = null;
|
|
367
|
+
let graphBoundsCache: {
|
|
368
|
+
nodesInput: FlowStoreContext['graph']['nodes'];
|
|
369
|
+
edgesInput: FlowStoreContext['graph']['edges'];
|
|
370
|
+
measurementsInput: FlowStoreContext['measurements'];
|
|
371
|
+
value: Rect;
|
|
372
|
+
} | null = null;
|
|
373
|
+
let groupGeometryCache = new WeakMap<
|
|
374
|
+
FlowStoreContext,
|
|
375
|
+
Map<string, GroupGeometry | null>
|
|
376
|
+
>();
|
|
377
|
+
let visualGroupGeometryCache = new WeakMap<
|
|
378
|
+
FlowStoreContext,
|
|
379
|
+
Map<string, GroupGeometry | null>
|
|
380
|
+
>();
|
|
381
|
+
let foldedEdgesCache = new WeakMap<
|
|
382
|
+
FlowStoreContext,
|
|
383
|
+
{ edges: FlowEdge[]; byId: Map<string, FlowEdge> }
|
|
384
|
+
>();
|
|
385
|
+
// Edge ownership (containment) per snapshot: owner node id → edges.
|
|
386
|
+
let edgeOwnerCache = new WeakMap<
|
|
387
|
+
FlowStoreContext,
|
|
388
|
+
Map<string, FlowEdge[]>
|
|
389
|
+
>();
|
|
390
|
+
let edgeOwnerByEdgeCache = new WeakMap<
|
|
391
|
+
FlowStoreContext,
|
|
392
|
+
WeakMap<FlowEdge, string | null>
|
|
393
|
+
>();
|
|
394
|
+
let nodeIndexCache = new WeakMap<
|
|
395
|
+
FlowStoreContext,
|
|
396
|
+
ReadonlyMap<string, FlowNode>
|
|
397
|
+
>();
|
|
398
|
+
// Edge-routing obstacles per snapshot: owner id → visible sibling nodes
|
|
399
|
+
// (id + bounds). Identical for every edge sharing an owner, so it's computed
|
|
400
|
+
// once per owner per snapshot; `edgeObstacles` then just drops the edge's own
|
|
401
|
+
// endpoints. Keyed by context (WeakMap) so it auto-invalidates each snapshot.
|
|
402
|
+
let obstacleCache = new WeakMap<
|
|
403
|
+
FlowStoreContext,
|
|
404
|
+
Map<string, ReadonlyArray<{ id: string; bounds: Rect }>>
|
|
405
|
+
>();
|
|
406
|
+
// Sentinel owner key for root-level edges (owner == null).
|
|
407
|
+
const ROOT_OWNER_KEY = '\0root';
|
|
408
|
+
let edgeSourceDependents = new Map<string, Set<string>>();
|
|
409
|
+
|
|
410
|
+
function ownedEdges(c: FlowStoreContext): Map<string, FlowEdge[]> {
|
|
411
|
+
let index = edgeOwnerCache.get(c);
|
|
412
|
+
if (!index) {
|
|
413
|
+
index = new Map();
|
|
414
|
+
for (const edge of c.graph.edges) {
|
|
415
|
+
const owner = edgeOwnerOf(edge as FlowEdge, c);
|
|
416
|
+
if (owner == null) continue;
|
|
417
|
+
let bucket = index.get(owner);
|
|
418
|
+
if (!bucket) index.set(owner, (bucket = []));
|
|
419
|
+
bucket.push(edge as FlowEdge);
|
|
420
|
+
}
|
|
421
|
+
edgeOwnerCache.set(c, index);
|
|
422
|
+
}
|
|
423
|
+
return index;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function edgeOwnerOf(edge: FlowEdge, c: FlowStoreContext): string | null {
|
|
427
|
+
let owners = edgeOwnerByEdgeCache.get(c);
|
|
428
|
+
if (!owners) {
|
|
429
|
+
owners = new WeakMap();
|
|
430
|
+
edgeOwnerByEdgeCache.set(c, owners);
|
|
431
|
+
}
|
|
432
|
+
if (owners.has(edge)) return owners.get(edge)!;
|
|
433
|
+
|
|
434
|
+
// null means "root" (no owner); only undefined falls back.
|
|
435
|
+
const custom = engineOptions.edgeOwner?.(edge, c);
|
|
436
|
+
const owner = engineOptions.edgeOwner && custom !== undefined
|
|
437
|
+
? custom
|
|
438
|
+
: defaultEdgeOwnerFromIndex(edge, nodesById(c));
|
|
439
|
+
owners.set(edge, owner);
|
|
440
|
+
return owner;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function nodesById(c: FlowStoreContext): ReadonlyMap<string, FlowNode> {
|
|
444
|
+
let index = nodeIndexCache.get(c);
|
|
445
|
+
if (!index) {
|
|
446
|
+
index = indexNodes(c.graph.nodes);
|
|
447
|
+
nodeIndexCache.set(c, index);
|
|
448
|
+
}
|
|
449
|
+
return index;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
let appearanceSettings = ctx().appearances;
|
|
453
|
+
let appearanceCache = new WeakMap<
|
|
454
|
+
FlowNode | FlowEdgeLabel,
|
|
455
|
+
ReturnType<typeof resolveAppearance>
|
|
456
|
+
>();
|
|
457
|
+
let sizedNodeCache = new WeakMap<FlowNode, FlowNode>();
|
|
458
|
+
if (
|
|
459
|
+
initialOptions.appearances &&
|
|
460
|
+
initialOptions.appearances !== appearanceSettings
|
|
461
|
+
) {
|
|
462
|
+
store.trigger.configure({ appearances: initialOptions.appearances });
|
|
463
|
+
}
|
|
464
|
+
function appearanceFor(entity: FlowNode | FlowEdgeLabel) {
|
|
465
|
+
if (appearanceSettings !== ctx().appearances) {
|
|
466
|
+
appearanceSettings = ctx().appearances;
|
|
467
|
+
appearanceCache = new WeakMap();
|
|
468
|
+
sizedNodeCache = new WeakMap();
|
|
469
|
+
}
|
|
470
|
+
let appearance = appearanceCache.get(entity);
|
|
471
|
+
if (!appearance) {
|
|
472
|
+
appearance = resolveAppearance(entity, appearanceSettings);
|
|
473
|
+
appearanceCache.set(entity, appearance);
|
|
474
|
+
}
|
|
475
|
+
return appearance;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function sizedNode(node: FlowNode): FlowNode {
|
|
479
|
+
const autoSize = appearanceFor(node).autoSize;
|
|
480
|
+
const cached = sizedNodeCache.get(node);
|
|
481
|
+
if (cached) return cached;
|
|
482
|
+
const measured =
|
|
483
|
+
node.measured?.appearanceKey !== undefined &&
|
|
484
|
+
node.measured.appearanceKey !== JSON.stringify(node.appearance ?? null)
|
|
485
|
+
? undefined
|
|
486
|
+
: node.measured;
|
|
487
|
+
const sized =
|
|
488
|
+
(node.autoSize === autoSize ||
|
|
489
|
+
(!autoSize && !node.autoSize && !node.measured?.appearanceAutoSize)) &&
|
|
490
|
+
measured === node.measured
|
|
491
|
+
? node
|
|
492
|
+
: { ...node, autoSize, measured };
|
|
493
|
+
sizedNodeCache.set(node, sized);
|
|
494
|
+
return sized;
|
|
495
|
+
}
|
|
496
|
+
const resolvedSize = (node: FlowNode) => baseResolvedSize(sizedNode(node));
|
|
497
|
+
const resolvedBounds = (node: FlowNode) => baseResolvedBounds(sizedNode(node));
|
|
498
|
+
const snappedBounds = (
|
|
499
|
+
node: FlowNode,
|
|
500
|
+
grid: [number, number] | null,
|
|
501
|
+
offset?: Point | null
|
|
502
|
+
) => baseSnappedBounds(sizedNode(node), grid, offset);
|
|
503
|
+
const resolvedEdgeLabelSize = (label: FlowEdgeLabel, measurement?: Rect) =>
|
|
504
|
+
baseResolvedEdgeLabelSize(
|
|
505
|
+
{ ...label, autoSize: appearanceFor(label).autoSize },
|
|
506
|
+
measurement
|
|
507
|
+
);
|
|
508
|
+
|
|
509
|
+
function connectionBounds(
|
|
510
|
+
id: string,
|
|
511
|
+
entity: FlowNode | FlowEdgeLabel,
|
|
512
|
+
visual: Rect
|
|
513
|
+
): Rect {
|
|
514
|
+
const appearance = appearanceFor(entity);
|
|
515
|
+
const local =
|
|
516
|
+
appearance.connectionBounds ??
|
|
517
|
+
(appearance.registered
|
|
518
|
+
? ctx().measurements.get(appearanceMeasurementId(id, appearance))
|
|
519
|
+
: undefined);
|
|
520
|
+
return local
|
|
521
|
+
? { ...local, x: visual.x + local.x, y: visual.y + local.y }
|
|
522
|
+
: visual;
|
|
523
|
+
}
|
|
524
|
+
/** A constrained presentation must not be bypassed by graph-owned route points. */
|
|
525
|
+
function resolvedAuthoritativePath(
|
|
526
|
+
edge: FlowEdge,
|
|
527
|
+
source = getNode(edge.sourceId),
|
|
528
|
+
target = getNode(edge.targetId)
|
|
529
|
+
): PathData | null {
|
|
530
|
+
const path = authoritativeEdgePath(edge);
|
|
531
|
+
if (!path) return null;
|
|
532
|
+
const constrained = (
|
|
533
|
+
id: string,
|
|
534
|
+
entity: FlowNode | FlowEdgeLabel | undefined
|
|
535
|
+
) => {
|
|
536
|
+
if (!entity) return false;
|
|
537
|
+
const appearance = appearanceFor(entity);
|
|
538
|
+
return (
|
|
539
|
+
!!appearance.connectionBounds ||
|
|
540
|
+
appearance.ports !== undefined ||
|
|
541
|
+
['top', 'right', 'bottom', 'left'].some(
|
|
542
|
+
(side) => !appearance.sides.includes(side as Direction)
|
|
543
|
+
) ||
|
|
544
|
+
(appearance.registered &&
|
|
545
|
+
ctx().measurements.has(appearanceMeasurementId(id, appearance)))
|
|
546
|
+
);
|
|
547
|
+
};
|
|
548
|
+
return constrained(edge.sourceId, source) ||
|
|
549
|
+
constrained(edge.targetId, target) ||
|
|
550
|
+
constrained(edge.id, edge.label ?? undefined)
|
|
551
|
+
? null
|
|
552
|
+
: path;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function connectionDirection(
|
|
556
|
+
entity: FlowNode | FlowEdgeLabel,
|
|
557
|
+
bounds: Rect,
|
|
558
|
+
other: Rect
|
|
559
|
+
): Direction {
|
|
560
|
+
return appearanceDirection(
|
|
561
|
+
bounds,
|
|
562
|
+
other,
|
|
563
|
+
bestDirection(bounds, other),
|
|
564
|
+
appearanceFor(entity).sides
|
|
565
|
+
);
|
|
566
|
+
}
|
|
567
|
+
function isPortAllowed(nodeOrId: FlowNode | string, portName: string): boolean {
|
|
568
|
+
const node = typeof nodeOrId === 'string' ? getNode(nodeOrId) : nodeOrId;
|
|
569
|
+
return !!node && appearanceAllowsPort(node, portName, appearanceFor(node));
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function setOptions(partial: Partial<FlowEngineOptions>, replace = false): void {
|
|
573
|
+
const previousAppearances = engineOptions.appearances;
|
|
574
|
+
engineOptions = replace
|
|
575
|
+
? { ...partial }
|
|
576
|
+
: {
|
|
577
|
+
...engineOptions,
|
|
578
|
+
...partial,
|
|
579
|
+
config: partial.config
|
|
580
|
+
? { ...(engineOptions.config ?? {}), ...partial.config }
|
|
581
|
+
: engineOptions.config,
|
|
582
|
+
connection: partial.connection
|
|
583
|
+
? { ...(engineOptions.connection ?? {}), ...partial.connection }
|
|
584
|
+
: engineOptions.connection,
|
|
585
|
+
};
|
|
586
|
+
optionsVersion++;
|
|
587
|
+
snapshotEdgePathsCache = new WeakMap();
|
|
588
|
+
stableEdgePathsCache = new WeakMap();
|
|
589
|
+
renderableCache = new WeakMap();
|
|
590
|
+
entityOrderCache = null;
|
|
591
|
+
baseEntityOrderCache = null;
|
|
592
|
+
paintZIndicesCache = new WeakMap();
|
|
593
|
+
entityRankCache = null;
|
|
594
|
+
renderableSpatialIndex = null;
|
|
595
|
+
graphBoundsCache = null;
|
|
596
|
+
groupGeometryCache = new WeakMap();
|
|
597
|
+
visualGroupGeometryCache = new WeakMap();
|
|
598
|
+
foldedEdgesCache = new WeakMap();
|
|
599
|
+
edgeOwnerCache = new WeakMap();
|
|
600
|
+
edgeOwnerByEdgeCache = new WeakMap();
|
|
601
|
+
nodeIndexCache = new WeakMap();
|
|
602
|
+
obstacleCache = new WeakMap();
|
|
603
|
+
edgePathMemo.clear();
|
|
604
|
+
lastCanonicalEdgePaths = null;
|
|
605
|
+
lastRouting = null;
|
|
606
|
+
routerReadTrackingDisabled = false;
|
|
607
|
+
const appearances = replace ? partial.appearances ?? {} : partial.appearances;
|
|
608
|
+
if (appearances !== undefined && appearances !== previousAppearances) store.trigger.configure({ appearances });
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
function invalidateRoutes(): void {
|
|
612
|
+
snapshotEdgePathsCache = new WeakMap();
|
|
613
|
+
stableEdgePathsCache = new WeakMap();
|
|
614
|
+
renderableCache = new WeakMap();
|
|
615
|
+
renderableSpatialIndex = null;
|
|
616
|
+
edgePathMemo.clear();
|
|
617
|
+
lastRouting = null;
|
|
618
|
+
// Keep canonical paths: identical router output must retain its identity.
|
|
619
|
+
store.trigger.bumpRoutingRevision();
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// Visible sibling nodes (id + bounds) under an owner, memoized per snapshot.
|
|
623
|
+
// The set is identical for all edges sharing an owner — the only per-edge
|
|
624
|
+
// difference is dropping the edge's own endpoints, done cheaply in
|
|
625
|
+
// `edgeObstacles`. This lifts the O(siblings) visibility + bounds work to once
|
|
626
|
+
// per owner per snapshot instead of once per edge.
|
|
627
|
+
function ownerObstacles(
|
|
628
|
+
owner: string | null,
|
|
629
|
+
c: FlowStoreContext,
|
|
630
|
+
): ReadonlyArray<{ id: string; bounds: Rect }> {
|
|
631
|
+
let byOwner = obstacleCache.get(c);
|
|
632
|
+
if (!byOwner) {
|
|
633
|
+
byOwner = new Map();
|
|
634
|
+
obstacleCache.set(c, byOwner);
|
|
635
|
+
}
|
|
636
|
+
const key = owner ?? ROOT_OWNER_KEY;
|
|
637
|
+
let obstacles = byOwner.get(key);
|
|
638
|
+
if (obstacles) return obstacles;
|
|
639
|
+
|
|
640
|
+
const nodes = c.graph.nodes as FlowNode[];
|
|
641
|
+
const siblings = owner == null
|
|
642
|
+
? nodes.filter((node) => node.parentId == null)
|
|
643
|
+
: indexChildren(nodes).get(owner) ?? [];
|
|
644
|
+
obstacles = siblings
|
|
645
|
+
.filter((node) => isNodeVisible(node, c))
|
|
646
|
+
.map((node) => ({ id: node.id, bounds: hierarchyBounds(node, c) }));
|
|
647
|
+
byOwner.set(key, obstacles);
|
|
648
|
+
return obstacles;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/** Both endpoints and their ancestors: never obstacles for their own edge. */
|
|
652
|
+
function edgeEndpointLineage(edge: FlowEdge, c: FlowStoreContext): Set<string> {
|
|
653
|
+
const nodeIndex = indexNodes(c.graph.nodes as FlowNode[]);
|
|
654
|
+
const endpointLineage = new Set<string>();
|
|
655
|
+
for (const endpointId of [edge.sourceId, edge.targetId]) {
|
|
656
|
+
let node = nodeIndex.get(endpointId);
|
|
657
|
+
while (node) {
|
|
658
|
+
endpointLineage.add(node.id);
|
|
659
|
+
node = node.parentId ? nodeIndex.get(node.parentId) : undefined;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return endpointLineage;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function edgeObstacles(edge: FlowEdge, c: FlowStoreContext): Rect[] {
|
|
666
|
+
const owner = edgeOwnerOf(edge, c);
|
|
667
|
+
const endpointLineage = edgeEndpointLineage(edge, c);
|
|
668
|
+
const result: Rect[] = [];
|
|
669
|
+
for (const { id, bounds } of ownerObstacles(owner, c)) {
|
|
670
|
+
if (endpointLineage.has(id)) continue;
|
|
671
|
+
result.push(bounds);
|
|
672
|
+
}
|
|
673
|
+
return result;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
// Inverted highlight index, keyed by the highlights Map identity — stable
|
|
677
|
+
// across snapshots that don't touch highlights, so per-entity results keep
|
|
678
|
+
// referential equality and subscribers can bail with Object.is.
|
|
679
|
+
const highlightIndexCache = new WeakMap<
|
|
680
|
+
FlowStoreContext['highlights'],
|
|
681
|
+
Map<string, Array<{ kind: string; meta: unknown }>>
|
|
682
|
+
>();
|
|
683
|
+
const NO_HIGHLIGHTS: ReadonlyArray<{ kind: string; meta: unknown }> = [];
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* Group geometry per snapshot, derived bottom-up. `derived` groups are a
|
|
687
|
+
* pure function of their children's (visual) bounds — recomputed per
|
|
688
|
+
* transition, so containment can't drift and sizing is reversible.
|
|
689
|
+
*/
|
|
690
|
+
function groupGeometryFor(
|
|
691
|
+
c: FlowStoreContext,
|
|
692
|
+
node: FlowNode,
|
|
693
|
+
visiting?: Set<string>,
|
|
694
|
+
): GroupGeometry | null {
|
|
695
|
+
if (!node.group) return null;
|
|
696
|
+
let byId = groupGeometryCache.get(c);
|
|
697
|
+
const cached = byId?.get(node.id);
|
|
698
|
+
if (cached !== undefined) return cached;
|
|
699
|
+
|
|
700
|
+
const geometry = computeGroupGeometryRaw(c, node, visiting, undefined);
|
|
701
|
+
|
|
702
|
+
if (!byId) {
|
|
703
|
+
byId = new Map();
|
|
704
|
+
groupGeometryCache.set(c, byId);
|
|
705
|
+
}
|
|
706
|
+
byId.set(node.id, geometry);
|
|
707
|
+
return geometry;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function visualGroupGeometryFor(
|
|
711
|
+
c: FlowStoreContext,
|
|
712
|
+
node: FlowNode,
|
|
713
|
+
snap: VisualSnapInfo,
|
|
714
|
+
): GroupGeometry | null {
|
|
715
|
+
if (!node.group) return null;
|
|
716
|
+
let byId = visualGroupGeometryCache.get(c);
|
|
717
|
+
const cached = byId?.get(node.id);
|
|
718
|
+
if (cached !== undefined) return cached;
|
|
719
|
+
|
|
720
|
+
const geometry = computeGroupGeometryRaw(
|
|
721
|
+
c,
|
|
722
|
+
node,
|
|
723
|
+
undefined,
|
|
724
|
+
undefined,
|
|
725
|
+
snap,
|
|
726
|
+
);
|
|
727
|
+
if (!byId) {
|
|
728
|
+
byId = new Map();
|
|
729
|
+
visualGroupGeometryCache.set(c, byId);
|
|
730
|
+
}
|
|
731
|
+
byId.set(node.id, geometry);
|
|
732
|
+
return geometry;
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
function computeGroupGeometryRaw(
|
|
736
|
+
c: FlowStoreContext,
|
|
737
|
+
node: FlowNode,
|
|
738
|
+
visiting: Set<string> | undefined,
|
|
739
|
+
excludeChildren: ReadonlySet<string> | undefined,
|
|
740
|
+
visualSnap?: VisualSnapInfo,
|
|
741
|
+
): GroupGeometry {
|
|
742
|
+
const contentSize = resolvedSize(node);
|
|
743
|
+
if (node.group!.type === 'fixed') {
|
|
744
|
+
return fixedGroupGeometry(
|
|
745
|
+
withLayoutOffset(resolvedBounds(node), node.id, c),
|
|
746
|
+
node.group!.contentSize ?? { width: 0, height: 0 },
|
|
747
|
+
node.group!,
|
|
748
|
+
);
|
|
749
|
+
}
|
|
750
|
+
const seen = visiting ?? new Set<string>();
|
|
751
|
+
seen.add(node.id);
|
|
752
|
+
let union: Rect | null = null;
|
|
753
|
+
const children = indexChildren(c.graph.nodes as FlowNode[]).get(node.id);
|
|
754
|
+
for (const child of children ?? []) {
|
|
755
|
+
if (child.hidden || seen.has(child.id)) continue;
|
|
756
|
+
// A collapsed group hides its descendants; they must not count toward its
|
|
757
|
+
// derived bounds either, or the box stays full-size while empty. Excluding
|
|
758
|
+
// them shrinks a collapsed group to its content block.
|
|
759
|
+
if (isHiddenByCollapsedAncestor(child.id, c)) continue;
|
|
760
|
+
if (excludeChildren?.has(child.id)) continue;
|
|
761
|
+
// If this child is the one currently being resized, union its LIVE
|
|
762
|
+
// resize bounds (the in-progress gesture rect) rather than its committed
|
|
763
|
+
// `resolvedBounds`, so the parent group grows/shrinks live during the
|
|
764
|
+
// drag — mirroring how dragging a child updates the group live. Committed
|
|
765
|
+
// bounds are used again once the resize is committed.
|
|
766
|
+
const liveResize =
|
|
767
|
+
c.canvasState === 'resizing' && c.resizingEntityId === child.id
|
|
768
|
+
? getResizeBoundsFromContext(c)
|
|
769
|
+
: null;
|
|
770
|
+
const b = liveResize
|
|
771
|
+
? liveResize
|
|
772
|
+
: visualSnap
|
|
773
|
+
? visualBounds(child, visualSnap)
|
|
774
|
+
: isDerivedGroup(child)
|
|
775
|
+
? excludeChildren
|
|
776
|
+
? computeGroupGeometryRaw(c, child, seen, excludeChildren).bounds
|
|
777
|
+
: groupGeometryFor(c, child, seen)?.bounds ??
|
|
778
|
+
withLayoutOffset(resolvedBounds(child), child.id, c)
|
|
779
|
+
: hierarchyBounds(child, c);
|
|
780
|
+
union = uniteRects(union, b);
|
|
781
|
+
}
|
|
782
|
+
// Contained edge labels count as content (Stately-editor semantics) —
|
|
783
|
+
// except a self-edge on this group itself, which may hang outside.
|
|
784
|
+
const nodeMap = indexNodes(c.graph.nodes);
|
|
785
|
+
for (const edge of ownedEdges(c).get(node.id) ?? []) {
|
|
786
|
+
if (edge.hidden || !edge.label) continue;
|
|
787
|
+
if (edge.sourceId === node.id && edge.targetId === node.id) continue;
|
|
788
|
+
let labelBounds = resolveEdgeLabelBounds(
|
|
789
|
+
edge,
|
|
790
|
+
nodeMap,
|
|
791
|
+
c.measurements.get(edge.id),
|
|
792
|
+
);
|
|
793
|
+
if (!labelBounds || (!labelBounds.width && !labelBounds.height)) continue;
|
|
794
|
+
if (
|
|
795
|
+
visualSnap &&
|
|
796
|
+
((edge.dx ?? 0) !== 0 || (edge.dy ?? 0) !== 0)
|
|
797
|
+
) {
|
|
798
|
+
const visualOffset = visualOwnedEdgeOffset(edge, visualSnap);
|
|
799
|
+
labelBounds = {
|
|
800
|
+
...labelBounds,
|
|
801
|
+
x: labelBounds.x + visualOffset.x - (edge.dx ?? 0),
|
|
802
|
+
y: labelBounds.y + visualOffset.y - (edge.dy ?? 0),
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
union = uniteRects(union, labelBounds);
|
|
806
|
+
}
|
|
807
|
+
return deriveGroupGeometry(
|
|
808
|
+
contentSize,
|
|
809
|
+
union,
|
|
810
|
+
node.group as Extract<NonNullable<FlowNode['group']>, { type: 'derived' }>,
|
|
811
|
+
layoutPosition(node, c),
|
|
812
|
+
);
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
function uniteRects(union: Rect | null, b: Rect): Rect {
|
|
816
|
+
return union ? unionRect(union, b) : { ...b };
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/** Bounds with group hierarchy applied (derived groups wrap their children). */
|
|
820
|
+
function hierarchyBounds(node: FlowNode, c: FlowStoreContext): Rect {
|
|
821
|
+
if (isDerivedGroup(node)) {
|
|
822
|
+
const geometry = groupGeometryFor(c, node);
|
|
823
|
+
if (geometry) return geometry.bounds;
|
|
824
|
+
}
|
|
825
|
+
return withLayoutOffset(resolvedBounds(node), node.id, c);
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
// Cross-snapshot per-edge path memo. Immer's structural sharing makes an
|
|
829
|
+
// entity's object identity a precise dirty flag: an edge's path can only
|
|
830
|
+
// change if the edge, one of its endpoint nodes, or one of the global
|
|
831
|
+
// inputs below changed. During a drag this recomputes only the edges
|
|
832
|
+
// attached to moving nodes instead of every edge in the graph.
|
|
833
|
+
// The last paths routed for the store graph. A recomputed path that equals
|
|
834
|
+
// its previous value keeps the previous object, so views keyed on path
|
|
835
|
+
// identity skip edges whose geometry did not change.
|
|
836
|
+
let lastCanonicalEdgePaths: Map<string, EdgePathData> | null = null;
|
|
837
|
+
// What the custom router read during the last store-graph routing pass, and
|
|
838
|
+
// each call's inputs and result. See `computeAllEdgePaths`.
|
|
839
|
+
let lastRouting: RoutingRecord | null = null;
|
|
840
|
+
let routerReadTrackingDisabled = false;
|
|
841
|
+
const edgePathMemo = new Map<
|
|
842
|
+
string,
|
|
843
|
+
{ edge: FlowEdge; source: FlowNode; target: FlowNode; path: EdgePathData }
|
|
844
|
+
>();
|
|
845
|
+
let edgePathMemoInputs: {
|
|
846
|
+
appearances: FlowStoreContext['appearances'];
|
|
847
|
+
selection: Set<string>;
|
|
848
|
+
offsetX: number;
|
|
849
|
+
offsetY: number;
|
|
850
|
+
grid: [number, number] | null;
|
|
851
|
+
resizingEntityId: string | null;
|
|
852
|
+
resizeCorners: FlowStoreContext['resizeCorners'];
|
|
853
|
+
measurements: FlowStoreContext['measurements'];
|
|
854
|
+
layoutOffsets: FlowStoreContext['layoutAnimation']['offsets'];
|
|
855
|
+
} | null = null;
|
|
856
|
+
|
|
857
|
+
function layoutOffset(id: string, c = ctx()): Point {
|
|
858
|
+
return c.layoutAnimation.offsets.get(id) ?? { x: 0, y: 0 };
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
function withLayoutOffset(rect: Rect, id: string, c = ctx()): Rect {
|
|
862
|
+
const offset = layoutOffset(id, c);
|
|
863
|
+
return {
|
|
864
|
+
...rect,
|
|
865
|
+
x: rect.x + offset.x,
|
|
866
|
+
y: rect.y + offset.y,
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
function layoutPosition(node: FlowNode, c = ctx()): Point {
|
|
871
|
+
const position = resolvedPosition(node);
|
|
872
|
+
const offset = layoutOffset(node.id, c);
|
|
873
|
+
return { x: position.x + offset.x, y: position.y + offset.y };
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// Entity accessors
|
|
877
|
+
|
|
878
|
+
function getNode(id: string): FlowNode | undefined {
|
|
879
|
+
return indexNodes(ctx().graph.nodes).get(id);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
function getEdge(id: string): FlowEdge | undefined {
|
|
883
|
+
const c = ctx();
|
|
884
|
+
return indexEdges(c.graph.edges).get(id) ?? foldedEdgesFor(c).byId.get(id);
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
function getEntity(id: string): FlowNode | FlowEdge | undefined {
|
|
888
|
+
return getNode(id) ?? getEdge(id);
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
function isNodeVisible(node: FlowNode, c: FlowStoreContext, viewport = c.viewport): boolean {
|
|
892
|
+
if (node.hidden) return false;
|
|
893
|
+
if (isHiddenByCollapsedAncestor(node.id, c)) return false;
|
|
894
|
+
const globalConfig = engineOptions.config ?? {};
|
|
895
|
+
if (globalConfig.visible && !resolveBehavior(globalConfig.visible, node, c)) return false;
|
|
896
|
+
if (engineOptions.isVisible && !engineOptions.isVisible(node, viewport)) return false;
|
|
897
|
+
return true;
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
function isHiddenByCollapsedAncestor(nodeId: string, c: FlowStoreContext): boolean {
|
|
901
|
+
if (c.collapsedNodeIds.size === 0) return false;
|
|
902
|
+
const nodeIndex = indexNodes(c.graph.nodes as FlowNode[]);
|
|
903
|
+
let parentId = nodeIndex.get(nodeId)?.parentId;
|
|
904
|
+
while (parentId) {
|
|
905
|
+
if (c.collapsedNodeIds.has(parentId)) return true;
|
|
906
|
+
parentId = nodeIndex.get(parentId)?.parentId;
|
|
907
|
+
}
|
|
908
|
+
return false;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
function visibleEndpointId(nodeId: string, c: FlowStoreContext): string | null {
|
|
912
|
+
const nodeIndex = indexNodes(c.graph.nodes as FlowNode[]);
|
|
913
|
+
const node = nodeIndex.get(nodeId);
|
|
914
|
+
if (!node) return null;
|
|
915
|
+
if (!isHiddenByCollapsedAncestor(nodeId, c)) return nodeId;
|
|
916
|
+
|
|
917
|
+
let parentId = node.parentId;
|
|
918
|
+
let visibleCollapsedAncestor: string | null = null;
|
|
919
|
+
while (parentId) {
|
|
920
|
+
if (c.collapsedNodeIds.has(parentId)) visibleCollapsedAncestor = parentId;
|
|
921
|
+
parentId = nodeIndex.get(parentId)?.parentId;
|
|
922
|
+
}
|
|
923
|
+
return visibleCollapsedAncestor;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
function foldedEdgesFor(c: FlowStoreContext): { edges: FlowEdge[]; byId: Map<string, FlowEdge> } {
|
|
927
|
+
const cached = foldedEdgesCache.get(c);
|
|
928
|
+
if (cached) return cached;
|
|
929
|
+
|
|
930
|
+
// Fast path: nothing collapsed ⇒ no edges can fold. Skip the O(E) loop and
|
|
931
|
+
// Map allocation and share a frozen empty result. Callers only read
|
|
932
|
+
// `.edges`/`.byId` (spread or `.get`), never mutate, so sharing is safe.
|
|
933
|
+
if (c.collapsedNodeIds.size === 0) {
|
|
934
|
+
foldedEdgesCache.set(c, EMPTY_FOLDED);
|
|
935
|
+
return EMPTY_FOLDED;
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
const merged = new Map<string, FlowEdge & { data: { foldedEdgeIds: string[] } }>();
|
|
939
|
+
for (const edge of c.graph.edges as FlowEdge[]) {
|
|
940
|
+
if (edge.hidden) continue;
|
|
941
|
+
const sourceId = visibleEndpointId(edge.sourceId, c);
|
|
942
|
+
const targetId = visibleEndpointId(edge.targetId, c);
|
|
943
|
+
if (!sourceId || !targetId || sourceId === targetId) continue;
|
|
944
|
+
if (sourceId === edge.sourceId && targetId === edge.targetId) continue;
|
|
945
|
+
|
|
946
|
+
const key = `${sourceId}->${targetId}`;
|
|
947
|
+
const existing = merged.get(key);
|
|
948
|
+
if (existing) {
|
|
949
|
+
existing.data.foldedEdgeIds.push(edge.id);
|
|
950
|
+
continue;
|
|
951
|
+
}
|
|
952
|
+
merged.set(key, {
|
|
953
|
+
...edge,
|
|
954
|
+
id: `flow:folded:${edge.id}`,
|
|
955
|
+
sourceId,
|
|
956
|
+
targetId,
|
|
957
|
+
sourcePort: undefined,
|
|
958
|
+
targetPort: undefined,
|
|
959
|
+
label: undefined,
|
|
960
|
+
waypoints: undefined,
|
|
961
|
+
points: undefined,
|
|
962
|
+
routing: undefined,
|
|
963
|
+
svgPath: undefined,
|
|
964
|
+
selectable: false,
|
|
965
|
+
connectable: false,
|
|
966
|
+
reconnectable: false,
|
|
967
|
+
deletable: false,
|
|
968
|
+
data: { foldedEdgeIds: [edge.id] },
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
const edges = [...merged.values()];
|
|
973
|
+
const byId = new Map(edges.map((edge) => [edge.id, edge]));
|
|
974
|
+
const result = { edges, byId };
|
|
975
|
+
foldedEdgesCache.set(c, result);
|
|
976
|
+
return result;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
function isEdgeVisible(
|
|
980
|
+
edge: FlowEdge,
|
|
981
|
+
graph: FlowStoreContext['graph'],
|
|
982
|
+
c: FlowStoreContext,
|
|
983
|
+
viewport = c.viewport,
|
|
984
|
+
): boolean {
|
|
985
|
+
if (edge.hidden) return false;
|
|
986
|
+
if (
|
|
987
|
+
c.connection?.preview !== false &&
|
|
988
|
+
c.connection?.reconnectingEdgeId === edge.id
|
|
989
|
+
) return false;
|
|
990
|
+
const nodeIndex = indexNodes(graph.nodes);
|
|
991
|
+
const source = nodeIndex.get(edge.sourceId);
|
|
992
|
+
const target = nodeIndex.get(edge.targetId);
|
|
993
|
+
if (!source || !target) return false;
|
|
994
|
+
if (!isNodeVisible(source, c, viewport) || !isNodeVisible(target, c, viewport)) return false;
|
|
995
|
+
const globalConfig = engineOptions.config ?? {};
|
|
996
|
+
if (globalConfig.visible && !resolveBehavior(globalConfig.visible, edge, c)) return false;
|
|
997
|
+
if (engineOptions.isVisible && !engineOptions.isVisible(edge, viewport)) return false;
|
|
998
|
+
return true;
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
function getEntityRef(id: string): FlowEntityRef | undefined {
|
|
1002
|
+
const node = getNode(id);
|
|
1003
|
+
if (node) {
|
|
1004
|
+
return { kind: 'node', id, node };
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
const edge = getEdge(id);
|
|
1008
|
+
if (edge) {
|
|
1009
|
+
return { kind: 'edge', id, edge };
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
for (const candidate of ctx().graph.nodes) {
|
|
1013
|
+
const port = candidate.ports?.find(
|
|
1014
|
+
(p) => (p as { id?: string }).id === id || `${candidate.id}:${p.name}` === id,
|
|
1015
|
+
);
|
|
1016
|
+
if (port) {
|
|
1017
|
+
return {
|
|
1018
|
+
kind: 'port',
|
|
1019
|
+
id,
|
|
1020
|
+
nodeId: candidate.id,
|
|
1021
|
+
portName: port.name,
|
|
1022
|
+
port,
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
return undefined;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
const getAddressable = getEntityRef;
|
|
1031
|
+
|
|
1032
|
+
function getOwnerEntity(id: string): FlowNode | FlowEdge | undefined {
|
|
1033
|
+
const addressable = getEntityRef(id);
|
|
1034
|
+
if (!addressable) return undefined;
|
|
1035
|
+
if (addressable.kind === 'node') return addressable.node;
|
|
1036
|
+
if (addressable.kind === 'edge') return addressable.edge;
|
|
1037
|
+
if (addressable.kind === 'port') return getNode(addressable.nodeId);
|
|
1038
|
+
return getEntity(addressable.ownerId);
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
// Coordinate conversion
|
|
1042
|
+
|
|
1043
|
+
function screenToCanvas(screenPoint: Point): Point {
|
|
1044
|
+
return _screenToCanvas(screenPoint, ctx().viewport);
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
function canvasToScreen(canvasPoint: Point): Point {
|
|
1048
|
+
return _canvasToScreen(canvasPoint, ctx().viewport);
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
// Hit testing
|
|
1052
|
+
|
|
1053
|
+
function entityAtPoint(canvasPoint: Point): FlowNode | FlowEdge | null {
|
|
1054
|
+
const c = ctx();
|
|
1055
|
+
const { graph } = c;
|
|
1056
|
+
const order = getEntityOrderFor(c);
|
|
1057
|
+
// Reverse paint order (topmost first) so the returned entity matches the
|
|
1058
|
+
// rendered scene. Skip invisible nodes/edges (collapse-hidden or `hidden`)
|
|
1059
|
+
// — consistent with entitiesInRect and what the user actually sees.
|
|
1060
|
+
for (let i = order.nodes.length - 1; i >= 0; i--) {
|
|
1061
|
+
const node = order.nodes[i];
|
|
1062
|
+
if (!node) continue;
|
|
1063
|
+
if (!isNodeVisible(node, c)) continue;
|
|
1064
|
+
const bounds = hierarchyBounds(node, c);
|
|
1065
|
+
const shape = getShapeOrDefault(node.shape ?? 'rect');
|
|
1066
|
+
if (shape.hitTest(canvasPoint, bounds)) {
|
|
1067
|
+
return node;
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
// Edge labels (treated like nodes for hit testing)
|
|
1071
|
+
const nodeMap = new Map<string, FlowNode>();
|
|
1072
|
+
for (const n of graph.nodes) nodeMap.set(n.id, n);
|
|
1073
|
+
for (let i = order.edges.length - 1; i >= 0; i--) {
|
|
1074
|
+
const edge = order.edges[i];
|
|
1075
|
+
if (!edge) continue;
|
|
1076
|
+
if (!isEdgeVisible(edge, graph, c)) continue;
|
|
1077
|
+
const lb = resolveEdgeLabelBounds(edge as FlowEdge, nodeMap);
|
|
1078
|
+
if (lb && canvasPoint.x >= lb.x && canvasPoint.x <= lb.x + lb.width &&
|
|
1079
|
+
canvasPoint.y >= lb.y && canvasPoint.y <= lb.y + lb.height) {
|
|
1080
|
+
return edge as FlowEdge;
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
const edgePaths = getAllEdgePaths();
|
|
1084
|
+
for (let i = order.edges.length - 1; i >= 0; i--) {
|
|
1085
|
+
const edge = order.edges[i];
|
|
1086
|
+
if (!edge) continue;
|
|
1087
|
+
if (!isEdgeVisible(edge, graph, c)) continue;
|
|
1088
|
+
const path = edgePaths.get(edge.id);
|
|
1089
|
+
if (!path) continue;
|
|
1090
|
+
if (path.segments.some((segment) => isPointNearPath(canvasPoint, segment, edgeHitTolerance))) {
|
|
1091
|
+
return edge;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
return null;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
function entityIdAtPoint(canvasPoint: Point): string | null {
|
|
1098
|
+
return entityAtPoint(canvasPoint)?.id ?? null;
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
function validateConnectionDetailed(proposed: ProposedConnection, context: FlowStoreContext = ctx()): { valid: boolean; reason?: string } {
|
|
1102
|
+
// Check direction compatibility
|
|
1103
|
+
const { graph } = context;
|
|
1104
|
+
const srcNode = graph.nodes.find((n) => n.id === proposed.sourceId);
|
|
1105
|
+
const tgtNode = graph.nodes.find((n) => n.id === proposed.targetId);
|
|
1106
|
+
if (!srcNode || !tgtNode) return { valid: false, reason: 'missing-endpoint' };
|
|
1107
|
+
if (context.mode === 'readonly') return { valid: false, reason: 'readonly' };
|
|
1108
|
+
if ([srcNode, tgtNode].some(node => !(node.connectable ?? resolveBehavior(engineOptions.config?.connectable, node, context, true)))) {
|
|
1109
|
+
return { valid: false, reason: 'connectable' };
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
const sourcePort =
|
|
1113
|
+
proposed.sourcePort && srcNode.ports
|
|
1114
|
+
? srcNode.ports.find((p) => p.name === proposed.sourcePort) ?? null
|
|
1115
|
+
: null;
|
|
1116
|
+
const targetPort =
|
|
1117
|
+
proposed.targetPort && tgtNode.ports
|
|
1118
|
+
? tgtNode.ports.find((p) => p.name === proposed.targetPort) ?? null
|
|
1119
|
+
: null;
|
|
1120
|
+
|
|
1121
|
+
if (proposed.sourcePort && proposed.sourcePort !== '*' && !sourcePort) {
|
|
1122
|
+
return { valid: false, reason: 'missing-source-port' };
|
|
1123
|
+
}
|
|
1124
|
+
if (proposed.targetPort && proposed.targetPort !== '*' && !targetPort) {
|
|
1125
|
+
return { valid: false, reason: 'missing-target-port' };
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
if ((proposed.sourcePort && proposed.sourcePort !== '*' && appearanceFor(srcNode).registered && !isPortAllowed(srcNode, proposed.sourcePort)) ||
|
|
1129
|
+
(proposed.targetPort && proposed.targetPort !== '*' && appearanceFor(tgtNode).registered && !isPortAllowed(tgtNode, proposed.targetPort))) {
|
|
1130
|
+
return { valid: false, reason: 'appearance-port' };
|
|
1131
|
+
}
|
|
1132
|
+
if (!appearanceFor(srcNode).sides.length || !appearanceFor(tgtNode).sides.length) return { valid: false, reason: 'appearance-sides' };
|
|
1133
|
+
if (sourcePort) {
|
|
1134
|
+
if (sourcePort.direction === 'in') return { valid: false, reason: 'source-port-direction' };
|
|
1135
|
+
}
|
|
1136
|
+
if (targetPort) {
|
|
1137
|
+
if (targetPort.direction === 'out') return { valid: false, reason: 'target-port-direction' };
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
// User hook
|
|
1141
|
+
if (engineOptions.canConnect) {
|
|
1142
|
+
const result = engineOptions.canConnect(proposed, {
|
|
1143
|
+
graph,
|
|
1144
|
+
context,
|
|
1145
|
+
source: srcNode,
|
|
1146
|
+
target: tgtNode,
|
|
1147
|
+
sourcePort,
|
|
1148
|
+
targetPort,
|
|
1149
|
+
connection: context.connection,
|
|
1150
|
+
});
|
|
1151
|
+
if (typeof result === 'boolean') {
|
|
1152
|
+
if (!result) return { valid: false };
|
|
1153
|
+
} else if (!result.valid) {
|
|
1154
|
+
return { valid: false, reason: result.reason };
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
return { valid: true };
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
function validateConnection(proposed: ProposedConnection): boolean {
|
|
1162
|
+
return validateConnectionDetailed(proposed).valid;
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
function connectionOptions(
|
|
1166
|
+
options: ConnectionCandidateOptions = {},
|
|
1167
|
+
): Required<FlowConnectionOptions> {
|
|
1168
|
+
return {
|
|
1169
|
+
radius: options.radius ?? engineOptions.connection?.radius ?? 24,
|
|
1170
|
+
mode: options.mode ?? engineOptions.connection?.mode ?? 'loose',
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
function isConnectionCandidateValid(
|
|
1175
|
+
source: ConnectionCandidateSource | undefined,
|
|
1176
|
+
nodeId: string,
|
|
1177
|
+
portName: string | null,
|
|
1178
|
+
): boolean {
|
|
1179
|
+
if (!source) return true;
|
|
1180
|
+
if (nodeId === source.nodeId) return false;
|
|
1181
|
+
return validateConnection(normalizeConnection({
|
|
1182
|
+
sourceId: source.nodeId,
|
|
1183
|
+
sourcePort: source.port,
|
|
1184
|
+
targetId: nodeId,
|
|
1185
|
+
targetPort: portName,
|
|
1186
|
+
}, ctx().graph));
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
function resolveEntityConfig(entityOrId: FlowNode | FlowEdge | string): {
|
|
1190
|
+
hidden: boolean;
|
|
1191
|
+
selectable: boolean;
|
|
1192
|
+
focusable: boolean;
|
|
1193
|
+
draggable: boolean;
|
|
1194
|
+
connectable: boolean;
|
|
1195
|
+
reconnectable: boolean;
|
|
1196
|
+
deletable: boolean;
|
|
1197
|
+
resizable: boolean;
|
|
1198
|
+
} {
|
|
1199
|
+
const entity = typeof entityOrId === 'string' ? getEntity(entityOrId) : entityOrId;
|
|
1200
|
+
if (!entity) {
|
|
1201
|
+
return { hidden: false, selectable: true, focusable: true, draggable: true, connectable: true, reconnectable: true, deletable: true, resizable: true };
|
|
1202
|
+
}
|
|
1203
|
+
const c = ctx();
|
|
1204
|
+
return {
|
|
1205
|
+
hidden:
|
|
1206
|
+
entity.type === 'edge'
|
|
1207
|
+
? !isEdgeVisible(entity as FlowEdge, c.graph, c)
|
|
1208
|
+
: !isNodeVisible(entity as FlowNode, c),
|
|
1209
|
+
selectable: entity.selectable ?? resolveBehavior((engineOptions.config ?? {}).selectable, entity, c, true),
|
|
1210
|
+
focusable: entity.focusable ?? resolveBehavior((engineOptions.config ?? {}).focusable, entity, c, true),
|
|
1211
|
+
draggable: entity.draggable ?? resolveBehavior((engineOptions.config ?? {}).draggable, entity, c, true),
|
|
1212
|
+
connectable: entity.connectable ?? resolveBehavior((engineOptions.config ?? {}).connectable, entity, c, true),
|
|
1213
|
+
reconnectable: (entity as FlowEdge).reconnectable ?? resolveBehavior((engineOptions.config ?? {}).reconnectable, entity, c, true),
|
|
1214
|
+
deletable: entity.deletable ?? resolveBehavior((engineOptions.config ?? {}).deletable, entity, c, true),
|
|
1215
|
+
resizable: (entity as FlowNode).resizable ?? resolveBehavior((engineOptions.config ?? {}).resizable, entity, c, false),
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
function distanceToRect(point: Point, rect: Rect): number {
|
|
1220
|
+
const dx =
|
|
1221
|
+
point.x < rect.x ? rect.x - point.x :
|
|
1222
|
+
point.x > rect.x + rect.width ? point.x - (rect.x + rect.width) :
|
|
1223
|
+
0;
|
|
1224
|
+
const dy =
|
|
1225
|
+
point.y < rect.y ? rect.y - point.y :
|
|
1226
|
+
point.y > rect.y + rect.height ? point.y - (rect.y + rect.height) :
|
|
1227
|
+
0;
|
|
1228
|
+
return Math.hypot(dx, dy);
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
function groupConnectionDistance(
|
|
1232
|
+
point: Point,
|
|
1233
|
+
node: FlowNode,
|
|
1234
|
+
c: FlowStoreContext,
|
|
1235
|
+
): number {
|
|
1236
|
+
const bounds = hierarchyBounds(node, c);
|
|
1237
|
+
const boundaryWidth = node.group?.connectionBoundaryWidth;
|
|
1238
|
+
if (boundaryWidth === undefined) return distanceToRect(point, bounds);
|
|
1239
|
+
|
|
1240
|
+
const geometry = groupGeometryFor(c, node);
|
|
1241
|
+
if (!geometry) return distanceToRect(point, bounds);
|
|
1242
|
+
if (distanceToRect(point, geometry.contentBounds) === 0) return 0;
|
|
1243
|
+
|
|
1244
|
+
const side = node.group?.content ?? 'top';
|
|
1245
|
+
const childSurface: Rect =
|
|
1246
|
+
side === 'top'
|
|
1247
|
+
? {
|
|
1248
|
+
x: bounds.x,
|
|
1249
|
+
y: geometry.contentBounds.y + geometry.contentBounds.height,
|
|
1250
|
+
width: bounds.width,
|
|
1251
|
+
height:
|
|
1252
|
+
bounds.y + bounds.height -
|
|
1253
|
+
geometry.contentBounds.y -
|
|
1254
|
+
geometry.contentBounds.height,
|
|
1255
|
+
}
|
|
1256
|
+
: side === 'bottom'
|
|
1257
|
+
? {
|
|
1258
|
+
x: bounds.x,
|
|
1259
|
+
y: bounds.y,
|
|
1260
|
+
width: bounds.width,
|
|
1261
|
+
height: geometry.contentBounds.y - bounds.y,
|
|
1262
|
+
}
|
|
1263
|
+
: side === 'left'
|
|
1264
|
+
? {
|
|
1265
|
+
x: geometry.contentBounds.x + geometry.contentBounds.width,
|
|
1266
|
+
y: bounds.y,
|
|
1267
|
+
width:
|
|
1268
|
+
bounds.x + bounds.width -
|
|
1269
|
+
geometry.contentBounds.x -
|
|
1270
|
+
geometry.contentBounds.width,
|
|
1271
|
+
height: bounds.height,
|
|
1272
|
+
}
|
|
1273
|
+
: {
|
|
1274
|
+
x: bounds.x,
|
|
1275
|
+
y: bounds.y,
|
|
1276
|
+
width: geometry.contentBounds.x - bounds.x,
|
|
1277
|
+
height: bounds.height,
|
|
1278
|
+
};
|
|
1279
|
+
|
|
1280
|
+
const childDistance = distanceToRect(point, childSurface);
|
|
1281
|
+
if (childDistance > 0) return distanceToRect(point, bounds);
|
|
1282
|
+
|
|
1283
|
+
const inset = Math.max(0, boundaryWidth);
|
|
1284
|
+
const distanceFromBoundary = Math.min(
|
|
1285
|
+
point.x - childSurface.x,
|
|
1286
|
+
childSurface.x + childSurface.width - point.x,
|
|
1287
|
+
point.y - childSurface.y,
|
|
1288
|
+
childSurface.y + childSurface.height - point.y,
|
|
1289
|
+
);
|
|
1290
|
+
return distanceFromBoundary <= inset ? 0 : Number.POSITIVE_INFINITY;
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
function getConnectionCandidate(
|
|
1294
|
+
pointer: Point,
|
|
1295
|
+
options: ConnectionCandidateOptions = {},
|
|
1296
|
+
): ConnectionCandidate | null {
|
|
1297
|
+
const c = ctx();
|
|
1298
|
+
const snap = getVisualSnapOffset();
|
|
1299
|
+
const { radius, mode } = connectionOptions(options);
|
|
1300
|
+
let bestPort:
|
|
1301
|
+
| (ConnectionCandidate & { distance: number })
|
|
1302
|
+
| null = null;
|
|
1303
|
+
let bestNode:
|
|
1304
|
+
| (ConnectionCandidate & { distance: number })
|
|
1305
|
+
| null = null;
|
|
1306
|
+
|
|
1307
|
+
// Iterate in paint order (later == painted on top) so ties resolve to the
|
|
1308
|
+
// visually-topmost node. Accepting equal distances with `<=` lets a child
|
|
1309
|
+
// painted over an overlapping parent group win the tie-break.
|
|
1310
|
+
for (const node of getEntityOrderFor(c).nodes) {
|
|
1311
|
+
if (!isNodeVisible(node, c)) continue;
|
|
1312
|
+
if (!resolveEntityConfig(node).connectable) continue;
|
|
1313
|
+
|
|
1314
|
+
for (const port of node.ports ?? []) {
|
|
1315
|
+
if (!isPortAllowed(node, port.name)) continue;
|
|
1316
|
+
const position = portCenter(node, port, snap);
|
|
1317
|
+
const distance = Math.hypot(pointer.x - position.x, pointer.y - position.y);
|
|
1318
|
+
if (distance > radius) continue;
|
|
1319
|
+
const isValid = isConnectionCandidateValid(options.source, node.id, port.name);
|
|
1320
|
+
if (!isValid) continue;
|
|
1321
|
+
if (!bestPort || distance <= bestPort.distance) {
|
|
1322
|
+
bestPort = {
|
|
1323
|
+
nodeId: node.id,
|
|
1324
|
+
portName: port.name,
|
|
1325
|
+
position,
|
|
1326
|
+
isValid,
|
|
1327
|
+
distance,
|
|
1328
|
+
};
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
if (mode !== 'loose') continue;
|
|
1333
|
+
const bounds = connectionBounds(node.id, node, hierarchyBounds(node, c));
|
|
1334
|
+
const sides = appearanceFor(node).sides;
|
|
1335
|
+
if (!sides.length) continue;
|
|
1336
|
+
// Only permitted boundary segments attract a connection. Preserve unrestricted body targeting.
|
|
1337
|
+
const boundaryDistance = Math.min(...sides.map((side) => distanceToRect(pointer, {
|
|
1338
|
+
x: side === 'right' ? bounds.x + bounds.width : bounds.x,
|
|
1339
|
+
y: side === 'bottom' ? bounds.y + bounds.height : bounds.y,
|
|
1340
|
+
width: side === 'left' || side === 'right' ? 0 : bounds.width,
|
|
1341
|
+
height: side === 'top' || side === 'bottom' ? 0 : bounds.height,
|
|
1342
|
+
})));
|
|
1343
|
+
const distance = sides.length < 4 ? boundaryDistance : node.group
|
|
1344
|
+
? groupConnectionDistance(pointer, node, c)
|
|
1345
|
+
: distanceToRect(pointer, bounds);
|
|
1346
|
+
if (distance > radius) continue;
|
|
1347
|
+
const isValid = isConnectionCandidateValid(options.source, node.id, null);
|
|
1348
|
+
if (!isValid) continue;
|
|
1349
|
+
if (!bestNode || distance <= bestNode.distance) {
|
|
1350
|
+
bestNode = {
|
|
1351
|
+
nodeId: node.id,
|
|
1352
|
+
portName: null,
|
|
1353
|
+
position: {
|
|
1354
|
+
x: bounds.x + bounds.width / 2,
|
|
1355
|
+
y: bounds.y + bounds.height / 2,
|
|
1356
|
+
},
|
|
1357
|
+
isValid,
|
|
1358
|
+
distance,
|
|
1359
|
+
};
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
const best = bestPort ?? bestNode;
|
|
1364
|
+
if (!best) return null;
|
|
1365
|
+
return {
|
|
1366
|
+
nodeId: best.nodeId,
|
|
1367
|
+
portName: best.portName,
|
|
1368
|
+
position: best.position,
|
|
1369
|
+
isValid: best.isValid,
|
|
1370
|
+
};
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
// Edge routing
|
|
1374
|
+
|
|
1375
|
+
function createRouterEntityBoundsLookup(
|
|
1376
|
+
graph: FlowStoreContext['graph'],
|
|
1377
|
+
snap: VisualSnapInfo,
|
|
1378
|
+
nodeMap = indexNodes(graph.nodes),
|
|
1379
|
+
edgeMap = indexEdges(graph.edges),
|
|
1380
|
+
): EdgeRouterContext['getEntityBounds'] {
|
|
1381
|
+
return (id) => {
|
|
1382
|
+
const node = nodeMap.get(id);
|
|
1383
|
+
if (node) return { ...visualBounds(node, snap) };
|
|
1384
|
+
|
|
1385
|
+
const edge = edgeMap.get(id);
|
|
1386
|
+
if (!edge?.label) return undefined;
|
|
1387
|
+
const source = nodeMap.get(edge.sourceId);
|
|
1388
|
+
const target = nodeMap.get(edge.targetId);
|
|
1389
|
+
if (!source || !target) return undefined;
|
|
1390
|
+
const sourceBounds = visualBounds(source, snap);
|
|
1391
|
+
const targetBounds = visualBounds(target, snap);
|
|
1392
|
+
const anchor = edge.labelAnchor ?? engineOptions.labelAnchor ?? 'fixed';
|
|
1393
|
+
const basePos = resolveLabelAnchor(
|
|
1394
|
+
anchor,
|
|
1395
|
+
edge.label,
|
|
1396
|
+
sourceBounds,
|
|
1397
|
+
targetBounds,
|
|
1398
|
+
edge,
|
|
1399
|
+
resolvedEdgeLabelSize(edge.label, ctx().measurements.get(edge.id)),
|
|
1400
|
+
);
|
|
1401
|
+
return { ...visualLabelBounds(edge, basePos, snap) };
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
function getEdgePath(edgeId: string): PathData | null {
|
|
1406
|
+
const segments = getAllEdgePaths().get(edgeId)?.segments;
|
|
1407
|
+
if (!segments?.length) return null;
|
|
1408
|
+
if (segments.length === 1) return segments[0];
|
|
1409
|
+
return {
|
|
1410
|
+
points: segments.flatMap((segment) => segment.points),
|
|
1411
|
+
sourceDirection: segments[0].sourceDirection,
|
|
1412
|
+
targetDirection: segments.at(-1)!.targetDirection,
|
|
1413
|
+
routing: 'polyline',
|
|
1414
|
+
svgPath: segments.map(pathToSVG).join(' '),
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
function getEdgePathBounds(edgeId: string): Rect | null {
|
|
1419
|
+
const path = getAllEdgePaths().get(edgeId);
|
|
1420
|
+
if (!path) return null;
|
|
1421
|
+
return boundsForPoints(path.segments.flatMap((segment) => segment.points));
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
function getEdgeLabelBounds(edgeId: string): Rect | null {
|
|
1425
|
+
const c = ctx();
|
|
1426
|
+
const edge = getEdge(edgeId);
|
|
1427
|
+
if (!edge?.label) return null;
|
|
1428
|
+
const measured = c.measurements.get(edgeId);
|
|
1429
|
+
|
|
1430
|
+
const nodeMap = indexNodes(c.graph.nodes as FlowNode[]);
|
|
1431
|
+
return resolveEdgeLabelBounds(edge, nodeMap, measured);
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
function getBounds(id: string): Rect | undefined {
|
|
1435
|
+
const c = ctx();
|
|
1436
|
+
|
|
1437
|
+
const addressable = getEntityRef(id);
|
|
1438
|
+
if (!addressable) return undefined;
|
|
1439
|
+
|
|
1440
|
+
if (addressable.kind === 'node') {
|
|
1441
|
+
const bounds = hierarchyBounds(addressable.node, c);
|
|
1442
|
+
if (isDerivedGroup(addressable.node)) return bounds;
|
|
1443
|
+
const measured = c.measurements.get(id);
|
|
1444
|
+
if (!measured) return bounds;
|
|
1445
|
+
// ResizeObserver does not fire for position-only changes. Its x/y can
|
|
1446
|
+
// therefore describe the node's pre-layout position even though the
|
|
1447
|
+
// rendered node has moved. Position always comes from core geometry;
|
|
1448
|
+
// the live measurement contributes only the DOM border-box size.
|
|
1449
|
+
return { ...bounds, width: addressable.node.style?.customWidth ?? measured.width, height: addressable.node.style?.customHeight ?? measured.height };
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
if (addressable.kind === 'edge') {
|
|
1453
|
+
const labelBounds = getEdgeLabelBounds(id);
|
|
1454
|
+
if (resolvedAuthoritativePath(addressable.edge)) {
|
|
1455
|
+
const edgePathBounds = getEdgePathBounds(id);
|
|
1456
|
+
if (edgePathBounds) {
|
|
1457
|
+
return labelBounds
|
|
1458
|
+
? unionRect(edgePathBounds, labelBounds)
|
|
1459
|
+
: edgePathBounds;
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
return labelBounds ?? getEdgePathBounds(id) ?? undefined;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
if (addressable.kind === 'port') {
|
|
1466
|
+
const owner = getNode(addressable.nodeId);
|
|
1467
|
+
return owner ? portBounds(owner, addressable.port) : undefined;
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
return undefined;
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
/** Resolve edge label bounds using committed (static) node positions */
|
|
1474
|
+
function resolveEdgeLabelBounds(
|
|
1475
|
+
edge: FlowEdge,
|
|
1476
|
+
nodeMap: Map<string, FlowNode>,
|
|
1477
|
+
measurement?: Rect,
|
|
1478
|
+
): Rect | null {
|
|
1479
|
+
if (!edge.label) return null;
|
|
1480
|
+
const src = nodeMap.get(edge.sourceId);
|
|
1481
|
+
const tgt = nodeMap.get(edge.targetId);
|
|
1482
|
+
if (!src || !tgt) return null;
|
|
1483
|
+
const srcB = withLayoutOffset(
|
|
1484
|
+
{ x: src.x, y: src.y, width: src.style?.customWidth ?? src.width, height: src.style?.customHeight ?? src.height },
|
|
1485
|
+
src.id,
|
|
1486
|
+
);
|
|
1487
|
+
const tgtB = withLayoutOffset(
|
|
1488
|
+
{ x: tgt.x, y: tgt.y, width: tgt.style?.customWidth ?? tgt.width, height: tgt.style?.customHeight ?? tgt.height },
|
|
1489
|
+
tgt.id,
|
|
1490
|
+
);
|
|
1491
|
+
const anchor = edge.labelAnchor ?? engineOptions.labelAnchor ?? 'fixed';
|
|
1492
|
+
const size = resolvedEdgeLabelSize(edge.label, measurement);
|
|
1493
|
+
const basePos = resolveLabelAnchor(
|
|
1494
|
+
anchor,
|
|
1495
|
+
edge.label,
|
|
1496
|
+
srcB,
|
|
1497
|
+
tgtB,
|
|
1498
|
+
edge,
|
|
1499
|
+
size,
|
|
1500
|
+
);
|
|
1501
|
+
return withLayoutOffset({
|
|
1502
|
+
x: basePos.x + (edge.label.dx ?? 0),
|
|
1503
|
+
y: basePos.y + (edge.label.dy ?? 0),
|
|
1504
|
+
...size,
|
|
1505
|
+
}, edge.id);
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
/** Build selection bounding rect with properly resolved edge labels */
|
|
1509
|
+
function getSelectionSnapBounds(
|
|
1510
|
+
c: FlowStoreContext,
|
|
1511
|
+
includeEdgePoints = false,
|
|
1512
|
+
): Rect | null {
|
|
1513
|
+
let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
|
|
1514
|
+
const nodeMap = new Map<string, FlowNode>();
|
|
1515
|
+
for (const n of c.graph.nodes) nodeMap.set(n.id, n);
|
|
1516
|
+
|
|
1517
|
+
for (const n of c.graph.nodes) {
|
|
1518
|
+
if (!c.selection.has(n.id)) continue;
|
|
1519
|
+
const b = hierarchyBounds(n, c);
|
|
1520
|
+
minX = Math.min(minX, b.x);
|
|
1521
|
+
minY = Math.min(minY, b.y);
|
|
1522
|
+
maxX = Math.max(maxX, b.x + b.width);
|
|
1523
|
+
maxY = Math.max(maxY, b.y + b.height);
|
|
1524
|
+
}
|
|
1525
|
+
for (const e of c.graph.edges) {
|
|
1526
|
+
if (!c.selection.has(e.id)) continue;
|
|
1527
|
+
if (includeEdgePoints) {
|
|
1528
|
+
for (const point of resolvedAuthoritativePath(e)?.points ?? []) {
|
|
1529
|
+
minX = Math.min(minX, point.x);
|
|
1530
|
+
minY = Math.min(minY, point.y);
|
|
1531
|
+
maxX = Math.max(maxX, point.x);
|
|
1532
|
+
maxY = Math.max(maxY, point.y);
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
const lb = resolveEdgeLabelBounds(e, nodeMap, c.measurements.get(e.id));
|
|
1536
|
+
if (!lb) continue;
|
|
1537
|
+
minX = Math.min(minX, lb.x);
|
|
1538
|
+
minY = Math.min(minY, lb.y);
|
|
1539
|
+
maxX = Math.max(maxX, lb.x + lb.width);
|
|
1540
|
+
maxY = Math.max(maxY, lb.y + lb.height);
|
|
1541
|
+
}
|
|
1542
|
+
if (!isFinite(minX)) return null;
|
|
1543
|
+
return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
/** Collect visible snap targets outside the moving selection subtree. */
|
|
1547
|
+
function getSnapTargetRects(c: FlowStoreContext, selection: Set<string>): Rect[] {
|
|
1548
|
+
// Compute visible canvas area from viewport
|
|
1549
|
+
const vp = c.viewport;
|
|
1550
|
+
const vs = c.viewportSize;
|
|
1551
|
+
const viewRect: Rect = {
|
|
1552
|
+
x: -vp.x / vp.zoom,
|
|
1553
|
+
y: -vp.y / vp.zoom,
|
|
1554
|
+
width: vs.width / vp.zoom,
|
|
1555
|
+
height: vs.height / vp.zoom,
|
|
1556
|
+
};
|
|
1557
|
+
|
|
1558
|
+
const rects: Rect[] = [];
|
|
1559
|
+
const nodeMap = new Map<string, FlowNode>();
|
|
1560
|
+
const selectedDerivedAncestorIds = new Set<string>();
|
|
1561
|
+
const visitedAncestorIds = new Set<string>();
|
|
1562
|
+
const nodeIndex = nodesById(c);
|
|
1563
|
+
const selectedSubtreeIds = new Set(selection);
|
|
1564
|
+
const childrenByParent = indexChildren(c.graph.nodes);
|
|
1565
|
+
const pendingDescendantIds = [...selection];
|
|
1566
|
+
while (pendingDescendantIds.length > 0) {
|
|
1567
|
+
const parentId = pendingDescendantIds.pop()!;
|
|
1568
|
+
for (const child of childrenByParent.get(parentId) ?? []) {
|
|
1569
|
+
if (selectedSubtreeIds.has(child.id)) continue;
|
|
1570
|
+
selectedSubtreeIds.add(child.id);
|
|
1571
|
+
pendingDescendantIds.push(child.id);
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
for (const id of selection) {
|
|
1575
|
+
let parentId = nodeIndex.get(id)?.parentId;
|
|
1576
|
+
while (parentId && !visitedAncestorIds.has(parentId)) {
|
|
1577
|
+
visitedAncestorIds.add(parentId);
|
|
1578
|
+
const parent = nodeIndex.get(parentId);
|
|
1579
|
+
if (!parent) break;
|
|
1580
|
+
if (isDerivedGroup(parent)) {
|
|
1581
|
+
selectedDerivedAncestorIds.add(parentId);
|
|
1582
|
+
}
|
|
1583
|
+
parentId = parent.parentId;
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
for (const n of c.graph.nodes) {
|
|
1587
|
+
nodeMap.set(n.id, n);
|
|
1588
|
+
if (
|
|
1589
|
+
!selectedSubtreeIds.has(n.id) &&
|
|
1590
|
+
!selectedDerivedAncestorIds.has(n.id) &&
|
|
1591
|
+
!n.hidden
|
|
1592
|
+
) {
|
|
1593
|
+
const b = hierarchyBounds(n, c);
|
|
1594
|
+
if (rectsIntersect(b, viewRect)) {
|
|
1595
|
+
rects.push(b);
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
for (const edge of c.graph.edges) {
|
|
1600
|
+
if (selection.has(edge.id)) continue;
|
|
1601
|
+
const ownerId = edgeOwnerOf(edge, c);
|
|
1602
|
+
if (ownerId && selectedSubtreeIds.has(ownerId)) continue;
|
|
1603
|
+
const lb = resolveEdgeLabelBounds(
|
|
1604
|
+
edge,
|
|
1605
|
+
nodeMap,
|
|
1606
|
+
c.measurements.get(edge.id),
|
|
1607
|
+
);
|
|
1608
|
+
if (lb && rectsIntersect(lb, viewRect)) {
|
|
1609
|
+
rects.push(lb);
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
return rects;
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
/**
|
|
1616
|
+
* Compute visual snap offset for edge routing.
|
|
1617
|
+
* Returns the offset to apply to selected nodes so edges follow the snapped visual position.
|
|
1618
|
+
* Memoized per store snapshot — callers invoke this once per node per frame.
|
|
1619
|
+
*/
|
|
1620
|
+
function getVisualSnapOffset(): VisualSnapInfo {
|
|
1621
|
+
const c = ctx();
|
|
1622
|
+
const cached = snapOffsetCache.get(c);
|
|
1623
|
+
if (cached) return cached;
|
|
1624
|
+
const result = computeVisualSnapOffset(c);
|
|
1625
|
+
snapOffsetCache.set(c, result);
|
|
1626
|
+
return result;
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1629
|
+
function computeVisualSnapOffset(c: FlowStoreContext): VisualSnapInfo {
|
|
1630
|
+
const selection = c.selection;
|
|
1631
|
+
const grid = c.snapToGrid ? c.snapGrid as [number, number] : null;
|
|
1632
|
+
let offset: Point = { x: 0, y: 0 };
|
|
1633
|
+
const nodesMoved = c.canvasState === 'dragging' && c.graph.nodes.some(
|
|
1634
|
+
(n) => selection.has(n.id) && ((n.dx ?? 0) !== 0 || (n.dy ?? 0) !== 0),
|
|
1635
|
+
);
|
|
1636
|
+
const edgesMoved = c.canvasState === 'dragging' && c.graph.edges.some(
|
|
1637
|
+
(e) => selection.has(e.id) && e.label && ((e.label.dx ?? 0) !== 0 || (e.label.dy ?? 0) !== 0),
|
|
1638
|
+
);
|
|
1639
|
+
if ((nodesMoved || edgesMoved) && c.enableSnapLines) {
|
|
1640
|
+
const selBounds = getSelectionSnapBounds(c);
|
|
1641
|
+
if (selBounds) {
|
|
1642
|
+
const snapResult = getSnapLines(
|
|
1643
|
+
selBounds,
|
|
1644
|
+
getSnapTargetRects(c, selection),
|
|
1645
|
+
{ threshold: c.snapThreshold / c.viewport.zoom, enableSpacing: c.enableSpacingGuides },
|
|
1646
|
+
);
|
|
1647
|
+
if (snapResult) {
|
|
1648
|
+
offset = { x: snapResult.snapRect.x - selBounds.x, y: snapResult.snapRect.y - selBounds.y };
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
return { offset, grid, selection };
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
function visualOwnedEdgeOffset(edge: FlowEdge, snap: VisualSnapInfo): Point {
|
|
1656
|
+
const raw = { x: edge.dx ?? 0, y: edge.dy ?? 0 };
|
|
1657
|
+
if (raw.x === 0 && raw.y === 0) return raw;
|
|
1658
|
+
const offset = {
|
|
1659
|
+
x: raw.x + snap.offset.x,
|
|
1660
|
+
y: raw.y + snap.offset.y,
|
|
1661
|
+
};
|
|
1662
|
+
if (!snap.grid) return offset;
|
|
1663
|
+
|
|
1664
|
+
const c = ctx();
|
|
1665
|
+
const ownerId = edgeOwnerOf(edge, c);
|
|
1666
|
+
const owner = ownerId ? nodesById(c).get(ownerId) : undefined;
|
|
1667
|
+
if (!owner) return offset;
|
|
1668
|
+
return {
|
|
1669
|
+
x:
|
|
1670
|
+
snapToGrid(owner.x + (owner.dx ?? 0) + snap.offset.x, snap.grid[0]) -
|
|
1671
|
+
owner.x,
|
|
1672
|
+
y:
|
|
1673
|
+
snapToGrid(owner.y + (owner.dy ?? 0) + snap.offset.y, snap.grid[1]) -
|
|
1674
|
+
owner.y,
|
|
1675
|
+
};
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
/** Get visual bounds for a node — applies snap offset to the drag cohort. */
|
|
1679
|
+
function visualBounds(node: FlowNode, snap: VisualSnapInfo): Rect {
|
|
1680
|
+
const c = ctx();
|
|
1681
|
+
if (c.canvasState === 'resizing' && c.resizingEntityId === node.id) {
|
|
1682
|
+
const resizeBounds = getResizeBoundsFromContext(c);
|
|
1683
|
+
if (resizeBounds) return resizeBounds;
|
|
1684
|
+
}
|
|
1685
|
+
if (isDerivedGroup(node)) {
|
|
1686
|
+
const geometry = visualGroupGeometryFor(c, node, snap);
|
|
1687
|
+
if (geometry) {
|
|
1688
|
+
return geometry.bounds;
|
|
1689
|
+
}
|
|
1690
|
+
}
|
|
1691
|
+
const entityOffset =
|
|
1692
|
+
(node.dx ?? 0) !== 0 || (node.dy ?? 0) !== 0 ? snap.offset : null;
|
|
1693
|
+
return withLayoutOffset(
|
|
1694
|
+
snappedBounds(node, snap.grid, entityOffset),
|
|
1695
|
+
node.id,
|
|
1696
|
+
c,
|
|
1697
|
+
);
|
|
1698
|
+
}
|
|
1699
|
+
|
|
1700
|
+
function visualLabelBounds(edge: FlowEdge, basePos: Point, snap: VisualSnapInfo): Rect {
|
|
1701
|
+
const isSelected = snap.selection.has(edge.id);
|
|
1702
|
+
const isMoved =
|
|
1703
|
+
(edge.dx ?? 0) !== 0 ||
|
|
1704
|
+
(edge.dy ?? 0) !== 0 ||
|
|
1705
|
+
(edge.label?.dx ?? 0) !== 0 ||
|
|
1706
|
+
(edge.label?.dy ?? 0) !== 0;
|
|
1707
|
+
const ownedOffset =
|
|
1708
|
+
!isSelected && ((edge.dx ?? 0) !== 0 || (edge.dy ?? 0) !== 0)
|
|
1709
|
+
? visualOwnedEdgeOffset(edge, snap)
|
|
1710
|
+
: null;
|
|
1711
|
+
let x = basePos.x + (ownedOffset?.x ?? edge.label?.dx ?? 0);
|
|
1712
|
+
let y = basePos.y + (ownedOffset?.y ?? edge.label?.dy ?? 0);
|
|
1713
|
+
const layout = layoutOffset(edge.id);
|
|
1714
|
+
x += layout.x;
|
|
1715
|
+
y += layout.y;
|
|
1716
|
+
if (isMoved && !ownedOffset) {
|
|
1717
|
+
x += snap.offset.x;
|
|
1718
|
+
y += snap.offset.y;
|
|
1719
|
+
}
|
|
1720
|
+
if (isSelected) {
|
|
1721
|
+
if (snap.grid) {
|
|
1722
|
+
x = snapToGrid(x, snap.grid[0]);
|
|
1723
|
+
y = snapToGrid(y, snap.grid[1]);
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
const size = edge.label
|
|
1727
|
+
? resolvedEdgeLabelSize(edge.label, ctx().measurements.get(edge.id))
|
|
1728
|
+
: { width: 0, height: 0 };
|
|
1729
|
+
return {
|
|
1730
|
+
x,
|
|
1731
|
+
y,
|
|
1732
|
+
...size,
|
|
1733
|
+
};
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
/** Get visual position for a node — applies snap offset to the drag cohort. */
|
|
1737
|
+
function visualPosition(node: FlowNode, snap: VisualSnapInfo): Point {
|
|
1738
|
+
const b = visualBounds(node, snap);
|
|
1739
|
+
return { x: b.x, y: b.y };
|
|
1740
|
+
}
|
|
1741
|
+
|
|
1742
|
+
function portBounds(node: FlowNode, port: Rect & { name: string; id?: string }, snap?: VisualSnapInfo): Rect {
|
|
1743
|
+
const c = ctx();
|
|
1744
|
+
const id = port.id && c.measurements.has(port.id) ? port.id : `${node.id}:${port.name}`;
|
|
1745
|
+
const local = c.derivedPortMeasurements.get(id);
|
|
1746
|
+
// Measurements normalize into node-local port geometry in the store.
|
|
1747
|
+
// Their captured world coordinates become stale when the node moves.
|
|
1748
|
+
const position = visualPosition(node, snap ?? getVisualSnapOffset());
|
|
1749
|
+
const rect = local ?? port;
|
|
1750
|
+
return { x: position.x + rect.x, y: position.y + rect.y, width: rect.width, height: rect.height };
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
function portCenter(node: FlowNode, port: Rect & { name: string }, snap?: VisualSnapInfo): Point {
|
|
1754
|
+
const bounds = portBounds(node, port, snap);
|
|
1755
|
+
return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
/** Get bounds for edge endpoint — port bounds if specified, otherwise node bounds */
|
|
1759
|
+
function getEndpointBounds(node: FlowNode, portName: string | null | undefined, snap?: VisualSnapInfo): Rect {
|
|
1760
|
+
if (portName && portName !== '*' && node.ports && isPortAllowed(node, portName)) {
|
|
1761
|
+
const port = node.ports.find((p) => p.name === portName);
|
|
1762
|
+
if (port) {
|
|
1763
|
+
return portBounds(node, port, snap);
|
|
1764
|
+
}
|
|
1765
|
+
}
|
|
1766
|
+
const visual = snap ? visualBounds(node, snap) : hierarchyBounds(node, ctx());
|
|
1767
|
+
return connectionBounds(node.id, node, visual);
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
function portSideOf(node: FlowNode, portName: string | null | undefined): Direction | null {
|
|
1771
|
+
if (!portName || portName === '*' || !node.ports) return null;
|
|
1772
|
+
const port = node.ports.find((p) => p.name === portName) as
|
|
1773
|
+
| { side?: Direction }
|
|
1774
|
+
| undefined;
|
|
1775
|
+
return port && isPortAllowed(node, portName) ? port.side ?? null : null;
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
function getShapeAnchor(node: FlowNode, bounds: Rect, direction: Direction): Point {
|
|
1779
|
+
const appearance = appearanceFor(node);
|
|
1780
|
+
if (appearance.connectionBounds || (appearance.registered && ctx().measurements.has(appearanceMeasurementId(node.id, appearance)))) return rectEdgeAnchor(bounds, direction);
|
|
1781
|
+
const shape = getShapeOrDefault(node.shape ?? 'rect');
|
|
1782
|
+
return shape.edgeAnchor(bounds, direction);
|
|
1783
|
+
}
|
|
1784
|
+
|
|
1785
|
+
function resolveEndpointPoint(
|
|
1786
|
+
node: FlowNode,
|
|
1787
|
+
nodeBounds: Rect,
|
|
1788
|
+
portName: string | null | undefined,
|
|
1789
|
+
otherBounds: Rect,
|
|
1790
|
+
fallbackDirection: Direction,
|
|
1791
|
+
snap?: VisualSnapInfo,
|
|
1792
|
+
): Point {
|
|
1793
|
+
if (portName === '*' && node.ports?.some((port) => isPortAllowed(node, port.name))) {
|
|
1794
|
+
const otherCenter = {
|
|
1795
|
+
x: otherBounds.x + otherBounds.width / 2,
|
|
1796
|
+
y: otherBounds.y + otherBounds.height / 2,
|
|
1797
|
+
};
|
|
1798
|
+
let closest = { x: nodeBounds.x, y: nodeBounds.y };
|
|
1799
|
+
let distance = Infinity;
|
|
1800
|
+
for (const port of node.ports) {
|
|
1801
|
+
if (!isPortAllowed(node, port.name)) continue;
|
|
1802
|
+
const point = portCenter(node, port, snap);
|
|
1803
|
+
const nextDistance = (point.x - otherCenter.x) ** 2 + (point.y - otherCenter.y) ** 2;
|
|
1804
|
+
if (nextDistance < distance) {
|
|
1805
|
+
closest = point;
|
|
1806
|
+
distance = nextDistance;
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
return closest;
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
if (portName && portName !== '*' && node.ports && isPortAllowed(node, portName)) {
|
|
1813
|
+
const port = node.ports.find((p) => p.name === portName);
|
|
1814
|
+
if (port) {
|
|
1815
|
+
const bounds = getEndpointBounds(node, portName, snap);
|
|
1816
|
+
return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
|
|
1820
|
+
return getShapeAnchor(node, nodeBounds, fallbackDirection);
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
function rectEdgeAnchor(bounds: Rect, direction: Direction): Point {
|
|
1824
|
+
switch (direction) {
|
|
1825
|
+
case 'top':
|
|
1826
|
+
return { x: bounds.x + bounds.width / 2, y: bounds.y };
|
|
1827
|
+
case 'bottom':
|
|
1828
|
+
return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height };
|
|
1829
|
+
case 'left':
|
|
1830
|
+
return { x: bounds.x, y: bounds.y + bounds.height / 2 };
|
|
1831
|
+
case 'right':
|
|
1832
|
+
return { x: bounds.x + bounds.width, y: bounds.y + bounds.height / 2 };
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
|
|
1836
|
+
/**
|
|
1837
|
+
* Resolve the geometry shared by edge rendering and endpoint queries: the
|
|
1838
|
+
* endpoint bounds, the facing direction of each end, and the anchor points.
|
|
1839
|
+
* Single source of truth so rendered paths and `getEdgeEndpoints` can never
|
|
1840
|
+
* disagree on which side of a node an edge attaches to.
|
|
1841
|
+
*/
|
|
1842
|
+
function resolveEdgeGeometry(
|
|
1843
|
+
edge: FlowEdge,
|
|
1844
|
+
source: FlowNode,
|
|
1845
|
+
target: FlowNode,
|
|
1846
|
+
snap: VisualSnapInfo,
|
|
1847
|
+
getEdgeLabelBounds: (edgeId: string) => Rect | null,
|
|
1848
|
+
graph: FlowStoreContext['graph'],
|
|
1849
|
+
context: FlowStoreContext,
|
|
1850
|
+
) {
|
|
1851
|
+
const naturalSourceBounds = getEndpointBounds(source, edge.sourcePort, snap);
|
|
1852
|
+
const targetBounds = getEndpointBounds(target, edge.targetPort, snap);
|
|
1853
|
+
const resolvedSourceBounds = engineOptions.resolveEdgeSourceBounds?.({
|
|
1854
|
+
edge,
|
|
1855
|
+
graph,
|
|
1856
|
+
context: edgeSourceBoundsContextReads
|
|
1857
|
+
? trackContextReads(context, edgeSourceBoundsContextReads)
|
|
1858
|
+
: context,
|
|
1859
|
+
source,
|
|
1860
|
+
target,
|
|
1861
|
+
sourceBounds: naturalSourceBounds,
|
|
1862
|
+
targetBounds,
|
|
1863
|
+
getEdgeLabelBounds,
|
|
1864
|
+
});
|
|
1865
|
+
const sourceBounds = resolvedSourceBounds ?? naturalSourceBounds;
|
|
1866
|
+
// Ports have sides: the edge leaves/enters perpendicular through the
|
|
1867
|
+
// port's side. Portless endpoints face the other endpoint.
|
|
1868
|
+
const sourceDirection =
|
|
1869
|
+
portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, targetBounds);
|
|
1870
|
+
const targetDirection =
|
|
1871
|
+
portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, sourceBounds);
|
|
1872
|
+
const sourcePoint = resolvedSourceBounds
|
|
1873
|
+
? rectEdgeAnchor(sourceBounds, sourceDirection)
|
|
1874
|
+
: resolveEndpointPoint(source, sourceBounds, edge.sourcePort, targetBounds, sourceDirection, snap);
|
|
1875
|
+
const targetPoint = resolveEndpointPoint(target, targetBounds, edge.targetPort, sourceBounds, targetDirection, snap);
|
|
1876
|
+
return { sourceBounds, targetBounds, sourceDirection, targetDirection, sourcePoint, targetPoint };
|
|
1877
|
+
}
|
|
1878
|
+
|
|
1879
|
+
function edgePathsCacheInputs(
|
|
1880
|
+
c: FlowStoreContext,
|
|
1881
|
+
snap: VisualSnapInfo,
|
|
1882
|
+
): EdgePathsCacheInputs {
|
|
1883
|
+
return {
|
|
1884
|
+
appearances: c.appearances,
|
|
1885
|
+
canonicalGraph: c.graph,
|
|
1886
|
+
selection: c.selection,
|
|
1887
|
+
collapsedNodeIds: c.collapsedNodeIds,
|
|
1888
|
+
connection: c.connection,
|
|
1889
|
+
offsetX: snap.offset.x,
|
|
1890
|
+
offsetY: snap.offset.y,
|
|
1891
|
+
gridX: snap.grid?.[0] ?? null,
|
|
1892
|
+
gridY: snap.grid?.[1] ?? null,
|
|
1893
|
+
resizingEntityId: c.resizingEntityId,
|
|
1894
|
+
resizeCorners: c.resizeCorners,
|
|
1895
|
+
measurements: c.measurements,
|
|
1896
|
+
layoutOffsets: c.layoutAnimation.offsets,
|
|
1897
|
+
};
|
|
1898
|
+
}
|
|
1899
|
+
|
|
1900
|
+
function trackContextReads(
|
|
1901
|
+
context: FlowStoreContext,
|
|
1902
|
+
reads: Set<PropertyKey>,
|
|
1903
|
+
): FlowStoreContext {
|
|
1904
|
+
return new Proxy(context, {
|
|
1905
|
+
get(target, key, receiver) {
|
|
1906
|
+
reads.add(key);
|
|
1907
|
+
return Reflect.get(target, key, receiver);
|
|
1908
|
+
},
|
|
1909
|
+
});
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
function sameContextReads(
|
|
1913
|
+
previous: FlowStoreContext,
|
|
1914
|
+
next: FlowStoreContext,
|
|
1915
|
+
reads: ReadonlySet<PropertyKey>,
|
|
1916
|
+
): boolean {
|
|
1917
|
+
for (const key of reads) {
|
|
1918
|
+
if (
|
|
1919
|
+
(previous as Record<PropertyKey, unknown>)[key] !==
|
|
1920
|
+
(next as Record<PropertyKey, unknown>)[key]
|
|
1921
|
+
) {
|
|
1922
|
+
return false;
|
|
1923
|
+
}
|
|
1924
|
+
}
|
|
1925
|
+
return true;
|
|
1926
|
+
}
|
|
1927
|
+
|
|
1928
|
+
function sameEdgePathsCacheInputs(
|
|
1929
|
+
a: EdgePathsCacheInputs,
|
|
1930
|
+
b: EdgePathsCacheInputs,
|
|
1931
|
+
): boolean {
|
|
1932
|
+
return (
|
|
1933
|
+
a.appearances === b.appearances &&
|
|
1934
|
+
a.canonicalGraph === b.canonicalGraph &&
|
|
1935
|
+
a.selection === b.selection &&
|
|
1936
|
+
a.collapsedNodeIds === b.collapsedNodeIds &&
|
|
1937
|
+
a.connection === b.connection &&
|
|
1938
|
+
a.offsetX === b.offsetX &&
|
|
1939
|
+
a.offsetY === b.offsetY &&
|
|
1940
|
+
a.gridX === b.gridX &&
|
|
1941
|
+
a.gridY === b.gridY &&
|
|
1942
|
+
a.resizingEntityId === b.resizingEntityId &&
|
|
1943
|
+
a.resizeCorners === b.resizeCorners &&
|
|
1944
|
+
a.measurements === b.measurements &&
|
|
1945
|
+
a.layoutOffsets === b.layoutOffsets
|
|
1946
|
+
);
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
/**
|
|
1950
|
+
* Whether routing state outside the graph is unchanged. Graph updates
|
|
1951
|
+
* replace idle layout offsets with a new empty map, so empty maps match.
|
|
1952
|
+
*/
|
|
1953
|
+
function sameRoutingState(
|
|
1954
|
+
a: EdgePathsCacheInputs,
|
|
1955
|
+
b: EdgePathsCacheInputs,
|
|
1956
|
+
): boolean {
|
|
1957
|
+
return sameEdgePathsCacheInputs(a, {
|
|
1958
|
+
...b,
|
|
1959
|
+
canonicalGraph: a.canonicalGraph,
|
|
1960
|
+
layoutOffsets:
|
|
1961
|
+
a.layoutOffsets.size === 0 && b.layoutOffsets.size === 0
|
|
1962
|
+
? a.layoutOffsets
|
|
1963
|
+
: b.layoutOffsets,
|
|
1964
|
+
});
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
/** Route all edges. Callers must treat the returned Map as read-only. */
|
|
1968
|
+
function getAllEdgePaths(options: EdgePathOptions = {}): Map<string, EdgePathData> {
|
|
1969
|
+
const c = ctx();
|
|
1970
|
+
const graph = options.graph ?? c.graph;
|
|
1971
|
+
|
|
1972
|
+
let byGraph = snapshotEdgePathsCache.get(c);
|
|
1973
|
+
const cached = byGraph?.get(graph);
|
|
1974
|
+
if (cached) return cached;
|
|
1975
|
+
|
|
1976
|
+
const snap = getVisualSnapOffset();
|
|
1977
|
+
// These hooks receive viewport or the full store context, so they may
|
|
1978
|
+
// intentionally make routing viewport-dependent. Keep exact snapshot
|
|
1979
|
+
// semantics when any of them is configured. `resolveEdgeSourceBounds`
|
|
1980
|
+
// is tracked instead: paths are reused only while every context key it
|
|
1981
|
+
// read keeps its value.
|
|
1982
|
+
const canReuseAcrossSnapshots =
|
|
1983
|
+
!engineOptions.isVisible &&
|
|
1984
|
+
!engineOptions.config?.visible &&
|
|
1985
|
+
!engineOptions.edgeOwner;
|
|
1986
|
+
const inputs = edgePathsCacheInputs(c, snap);
|
|
1987
|
+
const stableCached = canReuseAcrossSnapshots
|
|
1988
|
+
? stableEdgePathsCache.get(graph)
|
|
1989
|
+
: undefined;
|
|
1990
|
+
let paths: Map<string, EdgePathData>;
|
|
1991
|
+
if (
|
|
1992
|
+
stableCached &&
|
|
1993
|
+
sameEdgePathsCacheInputs(stableCached.inputs, inputs) &&
|
|
1994
|
+
sameContextReads(stableCached.context, c, stableCached.contextReads)
|
|
1995
|
+
) {
|
|
1996
|
+
paths = stableCached.paths;
|
|
1997
|
+
} else {
|
|
1998
|
+
const outerReads = edgeSourceBoundsContextReads;
|
|
1999
|
+
const contextReads = new Set<PropertyKey>();
|
|
2000
|
+
edgeSourceBoundsContextReads = contextReads;
|
|
2001
|
+
try {
|
|
2002
|
+
paths = computeAllEdgePaths(c, graph, snap);
|
|
2003
|
+
} finally {
|
|
2004
|
+
edgeSourceBoundsContextReads = outerReads;
|
|
2005
|
+
for (const key of contextReads) outerReads?.add(key);
|
|
2006
|
+
}
|
|
2007
|
+
if (canReuseAcrossSnapshots) {
|
|
2008
|
+
stableEdgePathsCache.set(graph, { inputs, paths, context: c, contextReads });
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
if (!byGraph) {
|
|
2013
|
+
byGraph = new WeakMap();
|
|
2014
|
+
snapshotEdgePathsCache.set(c, byGraph);
|
|
2015
|
+
}
|
|
2016
|
+
byGraph.set(graph, paths);
|
|
2017
|
+
return paths;
|
|
2018
|
+
}
|
|
2019
|
+
|
|
2020
|
+
/**
|
|
2021
|
+
* Route every edge. A custom router that has not declared `endpoints`
|
|
2022
|
+
* dependencies reads through tracked views of the edge and graph. When a
|
|
2023
|
+
* later pass finds every logged read unchanged and the same calls with the
|
|
2024
|
+
* same inputs, it reuses the previous results instead of calling the router,
|
|
2025
|
+
* so edits the router never looked at (a node's color, say) skip routing.
|
|
2026
|
+
* Replay only bridges graph changes: any other routing state change
|
|
2027
|
+
* (measurements, appearances, selection, ...) reroutes, because a router
|
|
2028
|
+
* may read that state through a closure. Any difference reroutes the whole
|
|
2029
|
+
* pass, which keeps routers that share work across calls exact.
|
|
2030
|
+
*/
|
|
2031
|
+
function computeAllEdgePaths(
|
|
2032
|
+
c: FlowStoreContext,
|
|
2033
|
+
graph: FlowStoreContext['graph'],
|
|
2034
|
+
snap = getVisualSnapOffset(),
|
|
2035
|
+
): Map<string, EdgePathData> {
|
|
2036
|
+
const router = engineOptions.edgeRouter;
|
|
2037
|
+
if (
|
|
2038
|
+
!router ||
|
|
2039
|
+
(engineOptions.edgeRouterDependencies ?? 'graph') !== 'graph' ||
|
|
2040
|
+
graph !== c.graph ||
|
|
2041
|
+
routerReadTrackingDisabled
|
|
2042
|
+
) {
|
|
2043
|
+
return computeEdgePathsPass(c, graph, snap, 'plain');
|
|
2044
|
+
}
|
|
2045
|
+
const previous =
|
|
2046
|
+
lastRouting?.router === router &&
|
|
2047
|
+
sameRoutingState(lastRouting.inputs, edgePathsCacheInputs(c, snap))
|
|
2048
|
+
? lastRouting
|
|
2049
|
+
: null;
|
|
2050
|
+
if (previous) {
|
|
2051
|
+
try {
|
|
2052
|
+
return computeEdgePathsPass(c, graph, snap, previous);
|
|
2053
|
+
} catch (error) {
|
|
2054
|
+
if (error !== REPLAY_MISS) throw error;
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
try {
|
|
2058
|
+
return computeEdgePathsPass(c, graph, snap, 'record');
|
|
2059
|
+
} catch {
|
|
2060
|
+
// The router rejected the tracked views (it mutates or clones them, for
|
|
2061
|
+
// example). Route without tracking from now on.
|
|
2062
|
+
routerReadTrackingDisabled = true;
|
|
2063
|
+
lastRouting = null;
|
|
2064
|
+
return computeEdgePathsPass(c, graph, snap, 'plain');
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
|
|
2068
|
+
function createRoute(
|
|
2069
|
+
c: FlowStoreContext,
|
|
2070
|
+
graph: FlowStoreContext['graph'],
|
|
2071
|
+
edgeMap: ReadonlyMap<string, FlowEdge>,
|
|
2072
|
+
getEntityBounds: EdgeRouterContext['getEntityBounds'],
|
|
2073
|
+
snap: VisualSnapInfo,
|
|
2074
|
+
mode: 'plain' | 'record' | RoutingRecord,
|
|
2075
|
+
): { route: RouteEdge; finish: () => void } {
|
|
2076
|
+
const router = engineOptions.edgeRouter ?? bezierRouter;
|
|
2077
|
+
if (mode === 'plain') {
|
|
2078
|
+
return {
|
|
2079
|
+
route: (edge, _key, values, getObstacles) =>
|
|
2080
|
+
router(edge, {
|
|
2081
|
+
graph,
|
|
2082
|
+
getEntityBounds,
|
|
2083
|
+
...values,
|
|
2084
|
+
get obstacles() {
|
|
2085
|
+
return getObstacles();
|
|
2086
|
+
},
|
|
2087
|
+
}),
|
|
2088
|
+
finish: () => {},
|
|
2089
|
+
};
|
|
2090
|
+
}
|
|
2091
|
+
if (mode === 'record') {
|
|
2092
|
+
const tracker = createRouterReadTracker(graph, getEntityBounds);
|
|
2093
|
+
const calls: RoutingRecord['calls'] = [];
|
|
2094
|
+
const owners: RoutingRecord['owners'] = new Map();
|
|
2095
|
+
return {
|
|
2096
|
+
route: (edge, key, values, getObstacles) => {
|
|
2097
|
+
const call: RoutingRecord['calls'][number] = { key, values, result: undefined! };
|
|
2098
|
+
call.result = tracker.release(router(tracker.edge(edge), {
|
|
2099
|
+
graph: tracker.graph,
|
|
2100
|
+
getEntityBounds: tracker.getEntityBounds,
|
|
2101
|
+
...values,
|
|
2102
|
+
get obstacles() {
|
|
2103
|
+
if (!call.obstacles) {
|
|
2104
|
+
const owner = edgeOwnerOf(edge, c);
|
|
2105
|
+
if (!owners.has(owner)) owners.set(owner, ownerObstacles(owner, c));
|
|
2106
|
+
call.obstacles = { owner, lineage: [...edgeEndpointLineage(edge, c)].join('\u0000') };
|
|
2107
|
+
}
|
|
2108
|
+
return getObstacles();
|
|
2109
|
+
},
|
|
2110
|
+
}));
|
|
2111
|
+
calls.push(call);
|
|
2112
|
+
return call.result;
|
|
2113
|
+
},
|
|
2114
|
+
finish: () => {
|
|
2115
|
+
lastRouting = {
|
|
2116
|
+
router,
|
|
2117
|
+
inputs: edgePathsCacheInputs(c, snap),
|
|
2118
|
+
log: tracker.log,
|
|
2119
|
+
owners,
|
|
2120
|
+
calls,
|
|
2121
|
+
};
|
|
2122
|
+
},
|
|
2123
|
+
};
|
|
2124
|
+
}
|
|
2125
|
+
const edgesById = new Map([...edgeMap, ...foldedEdgesFor(c).byId]);
|
|
2126
|
+
if (!routerReadsUnchanged(mode.log, graph, edgesById, getEntityBounds, plainDataEqual)) {
|
|
2127
|
+
throw REPLAY_MISS;
|
|
2128
|
+
}
|
|
2129
|
+
const ownersUnchanged = new Map<string | null, boolean>();
|
|
2130
|
+
const obstaclesUnchanged = (edge: FlowEdge, recorded: RouterCallObstacles): boolean => {
|
|
2131
|
+
const owner = edgeOwnerOf(edge, c);
|
|
2132
|
+
if (owner !== recorded.owner) return false;
|
|
2133
|
+
let unchanged = ownersUnchanged.get(owner);
|
|
2134
|
+
if (unchanged === undefined) {
|
|
2135
|
+
unchanged = plainDataEqual(mode.owners.get(owner), ownerObstacles(owner, c));
|
|
2136
|
+
ownersUnchanged.set(owner, unchanged);
|
|
2137
|
+
}
|
|
2138
|
+
return unchanged && [...edgeEndpointLineage(edge, c)].join('\u0000') === recorded.lineage;
|
|
2139
|
+
};
|
|
2140
|
+
let index = 0;
|
|
2141
|
+
return {
|
|
2142
|
+
route: (edge, key, values) => {
|
|
2143
|
+
const call = mode.calls[index++];
|
|
2144
|
+
if (
|
|
2145
|
+
!call ||
|
|
2146
|
+
call.key !== key ||
|
|
2147
|
+
!plainDataEqual(call.values, values) ||
|
|
2148
|
+
(call.obstacles && !obstaclesUnchanged(edge, call.obstacles))
|
|
2149
|
+
) {
|
|
2150
|
+
throw REPLAY_MISS;
|
|
2151
|
+
}
|
|
2152
|
+
return call.result;
|
|
2153
|
+
},
|
|
2154
|
+
finish: () => {
|
|
2155
|
+
if (index !== mode.calls.length) throw REPLAY_MISS;
|
|
2156
|
+
},
|
|
2157
|
+
};
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
function computeEdgePathsPass(
|
|
2161
|
+
c: FlowStoreContext,
|
|
2162
|
+
graph: FlowStoreContext['graph'],
|
|
2163
|
+
snap: VisualSnapInfo,
|
|
2164
|
+
mode: 'plain' | 'record' | RoutingRecord,
|
|
2165
|
+
): Map<string, EdgePathData> {
|
|
2166
|
+
const paths = new Map<string, EdgePathData>();
|
|
2167
|
+
|
|
2168
|
+
const nodeMap = indexNodes(graph.nodes);
|
|
2169
|
+
const edgeMap = indexEdges(graph.edges);
|
|
2170
|
+
const getEntityBounds = createRouterEntityBoundsLookup(
|
|
2171
|
+
graph,
|
|
2172
|
+
snap,
|
|
2173
|
+
nodeMap,
|
|
2174
|
+
edgeMap,
|
|
2175
|
+
);
|
|
2176
|
+
const { route, finish: finishRouting } = createRoute(c, graph, edgeMap, getEntityBounds, snap, mode);
|
|
2177
|
+
const computing = new Set<string>();
|
|
2178
|
+
const trackSourceDependencies = graph === c.graph;
|
|
2179
|
+
const nextEdgeSourceDependents = trackSourceDependencies
|
|
2180
|
+
? new Map<string, Set<string>>()
|
|
2181
|
+
: edgeSourceDependents;
|
|
2182
|
+
|
|
2183
|
+
// Custom visibility hooks can change a path set in ways entity identity
|
|
2184
|
+
// can't track — disable the cross-snapshot memo when they're configured.
|
|
2185
|
+
const globalConfig = engineOptions.config ?? {};
|
|
2186
|
+
const memoUsable = !engineOptions.isVisible && !globalConfig.visible && !engineOptions.resolveEdgeSourceBounds;
|
|
2187
|
+
if (memoUsable) {
|
|
2188
|
+
const inputs = edgePathMemoInputs;
|
|
2189
|
+
if (
|
|
2190
|
+
!inputs ||
|
|
2191
|
+
inputs.appearances !== c.appearances ||
|
|
2192
|
+
inputs.selection !== c.selection ||
|
|
2193
|
+
inputs.offsetX !== snap.offset.x ||
|
|
2194
|
+
inputs.offsetY !== snap.offset.y ||
|
|
2195
|
+
inputs.grid !== snap.grid ||
|
|
2196
|
+
inputs.resizingEntityId !== c.resizingEntityId ||
|
|
2197
|
+
inputs.resizeCorners !== c.resizeCorners ||
|
|
2198
|
+
inputs.measurements !== c.measurements ||
|
|
2199
|
+
inputs.layoutOffsets !== c.layoutAnimation.offsets
|
|
2200
|
+
) {
|
|
2201
|
+
edgePathMemo.clear();
|
|
2202
|
+
edgePathMemoInputs = {
|
|
2203
|
+
appearances: c.appearances,
|
|
2204
|
+
selection: c.selection,
|
|
2205
|
+
offsetX: snap.offset.x,
|
|
2206
|
+
offsetY: snap.offset.y,
|
|
2207
|
+
grid: snap.grid,
|
|
2208
|
+
resizingEntityId: c.resizingEntityId,
|
|
2209
|
+
resizeCorners: c.resizeCorners,
|
|
2210
|
+
measurements: c.measurements,
|
|
2211
|
+
layoutOffsets: c.layoutAnimation.offsets,
|
|
2212
|
+
};
|
|
2213
|
+
}
|
|
2214
|
+
}
|
|
2215
|
+
|
|
2216
|
+
const getComputedEdgeLabelBounds = (dependentEdgeId: string, edgeId: string): Rect | null => {
|
|
2217
|
+
if (trackSourceDependencies && edgeId !== dependentEdgeId) {
|
|
2218
|
+
let dependents = nextEdgeSourceDependents.get(edgeId);
|
|
2219
|
+
if (!dependents) {
|
|
2220
|
+
nextEdgeSourceDependents.set(edgeId, (dependents = new Set()));
|
|
2221
|
+
}
|
|
2222
|
+
dependents.add(dependentEdgeId);
|
|
2223
|
+
}
|
|
2224
|
+
const existing = paths.get(edgeId);
|
|
2225
|
+
if (existing) return existing.labelBounds;
|
|
2226
|
+
const edge = edgeMap.get(edgeId);
|
|
2227
|
+
if (!edge || computing.has(edgeId)) return null;
|
|
2228
|
+
return computeEdgePath(edge)?.labelBounds ?? null;
|
|
2229
|
+
};
|
|
2230
|
+
|
|
2231
|
+
const computeEdgePath = (edge: FlowEdge): EdgePathData | null => {
|
|
2232
|
+
if (computing.has(edge.id)) return null;
|
|
2233
|
+
computing.add(edge.id);
|
|
2234
|
+
const source = nodeMap.get(edge.sourceId);
|
|
2235
|
+
const target = nodeMap.get(edge.targetId);
|
|
2236
|
+
if (!source || !target || !isEdgeVisible(edge, graph, c)) {
|
|
2237
|
+
computing.delete(edge.id);
|
|
2238
|
+
return null;
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2241
|
+
// Derived groups change bounds without changing identity (their
|
|
2242
|
+
// geometry follows their children), so edges touching them can't be
|
|
2243
|
+
// memoized on endpoint identity.
|
|
2244
|
+
const memoizableEdge =
|
|
2245
|
+
memoUsable &&
|
|
2246
|
+
(!engineOptions.edgeRouter ||
|
|
2247
|
+
engineOptions.edgeRouterDependencies === 'endpoints') &&
|
|
2248
|
+
!isDerivedGroup(source) &&
|
|
2249
|
+
!isDerivedGroup(target);
|
|
2250
|
+
if (memoizableEdge) {
|
|
2251
|
+
const entry = edgePathMemo.get(edge.id);
|
|
2252
|
+
if (
|
|
2253
|
+
entry &&
|
|
2254
|
+
entry.edge === edge &&
|
|
2255
|
+
entry.source === source &&
|
|
2256
|
+
entry.target === target
|
|
2257
|
+
) {
|
|
2258
|
+
paths.set(edge.id, entry.path);
|
|
2259
|
+
computing.delete(edge.id);
|
|
2260
|
+
return entry.path;
|
|
2261
|
+
}
|
|
2262
|
+
}
|
|
2263
|
+
|
|
2264
|
+
// Use visual (snapped) bounds so edges follow the snapped position
|
|
2265
|
+
const { sourceBounds, targetBounds, sourcePoint, targetPoint } =
|
|
2266
|
+
resolveEdgeGeometry(
|
|
2267
|
+
edge,
|
|
2268
|
+
source,
|
|
2269
|
+
target,
|
|
2270
|
+
snap,
|
|
2271
|
+
(edgeId) => getComputedEdgeLabelBounds(edge.id, edgeId),
|
|
2272
|
+
graph,
|
|
2273
|
+
c,
|
|
2274
|
+
);
|
|
2275
|
+
// Lazy + memoized within this edge's computation: obstacles are only
|
|
2276
|
+
// computed if a router reads them (avoidRouter). Built-in routers never
|
|
2277
|
+
// do, so the default path skips edgeObstacles. Cached so the two-segment
|
|
2278
|
+
// (labeled) case doesn't compute twice.
|
|
2279
|
+
let obstaclesCache: Rect[] | undefined;
|
|
2280
|
+
const getObstacles = (): Rect[] =>
|
|
2281
|
+
(obstaclesCache ??= edgeObstacles(edge, c));
|
|
2282
|
+
const waypoints = offsetEdgeWaypoints(
|
|
2283
|
+
edge,
|
|
2284
|
+
visualOwnedEdgeOffset(edge, snap),
|
|
2285
|
+
);
|
|
2286
|
+
|
|
2287
|
+
let pathData: EdgePathData;
|
|
2288
|
+
const authoritative = resolvedAuthoritativePath(edge, source, target);
|
|
2289
|
+
if (authoritative) {
|
|
2290
|
+
pathData = {
|
|
2291
|
+
segments: [authoritative],
|
|
2292
|
+
labelBounds: edge.label
|
|
2293
|
+
? visualLabelBounds(
|
|
2294
|
+
edge,
|
|
2295
|
+
resolveLabelAnchor(
|
|
2296
|
+
edge.labelAnchor ?? engineOptions.labelAnchor ?? 'fixed',
|
|
2297
|
+
edge.label,
|
|
2298
|
+
sourceBounds,
|
|
2299
|
+
targetBounds,
|
|
2300
|
+
edge,
|
|
2301
|
+
resolvedEdgeLabelSize(edge.label, c.measurements.get(edge.id)),
|
|
2302
|
+
),
|
|
2303
|
+
snap,
|
|
2304
|
+
)
|
|
2305
|
+
: null,
|
|
2306
|
+
};
|
|
2307
|
+
} else if (edge.label) {
|
|
2308
|
+
// Resolve label anchor: edge-level overrides engine-level
|
|
2309
|
+
const anchor = edge.labelAnchor ?? engineOptions.labelAnchor ?? 'fixed';
|
|
2310
|
+
const basePos = resolveLabelAnchor(
|
|
2311
|
+
anchor,
|
|
2312
|
+
edge.label,
|
|
2313
|
+
sourceBounds,
|
|
2314
|
+
targetBounds,
|
|
2315
|
+
edge,
|
|
2316
|
+
resolvedEdgeLabelSize(edge.label, c.measurements.get(edge.id)),
|
|
2317
|
+
);
|
|
2318
|
+
const labelBounds = visualLabelBounds(edge, basePos, snap);
|
|
2319
|
+
|
|
2320
|
+
const labelConnectionBounds = connectionBounds(edge.id, edge.label, labelBounds);
|
|
2321
|
+
|
|
2322
|
+
// Segment 1: source → label (port sides win at the node end)
|
|
2323
|
+
const srcDir =
|
|
2324
|
+
portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, labelConnectionBounds);
|
|
2325
|
+
const lblDir1 = connectionDirection(edge.label, labelConnectionBounds, sourceBounds);
|
|
2326
|
+
const seg1 = route(edge, `${edge.id}:0`, {
|
|
2327
|
+
sourceBounds,
|
|
2328
|
+
targetBounds: labelConnectionBounds,
|
|
2329
|
+
sourceDirection: srcDir,
|
|
2330
|
+
targetDirection: lblDir1,
|
|
2331
|
+
sourcePoint: resolveEndpointPoint(source, sourceBounds, edge.sourcePort, labelConnectionBounds, srcDir, snap),
|
|
2332
|
+
waypoints,
|
|
2333
|
+
}, getObstacles);
|
|
2334
|
+
|
|
2335
|
+
// Segment 2: label → target
|
|
2336
|
+
const lblDir2 = connectionDirection(edge.label, labelConnectionBounds, targetBounds);
|
|
2337
|
+
const tgtDir =
|
|
2338
|
+
portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, labelConnectionBounds);
|
|
2339
|
+
const seg2 = route(edge, `${edge.id}:1`, {
|
|
2340
|
+
sourceBounds: labelConnectionBounds,
|
|
2341
|
+
targetBounds,
|
|
2342
|
+
sourceDirection: lblDir2,
|
|
2343
|
+
targetDirection: tgtDir,
|
|
2344
|
+
targetPoint: resolveEndpointPoint(target, targetBounds, edge.targetPort, labelConnectionBounds, tgtDir, snap),
|
|
2345
|
+
waypoints,
|
|
2346
|
+
}, getObstacles);
|
|
2347
|
+
|
|
2348
|
+
pathData = { segments: [seg1, seg2], labelBounds };
|
|
2349
|
+
} else {
|
|
2350
|
+
// No label — single segment; port sides override auto directions
|
|
2351
|
+
const srcDir =
|
|
2352
|
+
portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, targetBounds);
|
|
2353
|
+
const tgtDir =
|
|
2354
|
+
portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, sourceBounds);
|
|
2355
|
+
const path = route(edge, `${edge.id}:0`, {
|
|
2356
|
+
sourceBounds,
|
|
2357
|
+
targetBounds,
|
|
2358
|
+
sourceDirection: srcDir,
|
|
2359
|
+
targetDirection: tgtDir,
|
|
2360
|
+
sourcePoint,
|
|
2361
|
+
targetPoint,
|
|
2362
|
+
waypoints,
|
|
2363
|
+
}, getObstacles);
|
|
2364
|
+
pathData = { segments: [path], labelBounds: null };
|
|
2365
|
+
}
|
|
2366
|
+
|
|
2367
|
+
const previousPath = trackSourceDependencies
|
|
2368
|
+
? lastCanonicalEdgePaths?.get(edge.id)
|
|
2369
|
+
: undefined;
|
|
2370
|
+
if (previousPath && plainDataEqual(previousPath, pathData)) {
|
|
2371
|
+
pathData = previousPath;
|
|
2372
|
+
}
|
|
2373
|
+
paths.set(edge.id, pathData);
|
|
2374
|
+
if (memoizableEdge) {
|
|
2375
|
+
edgePathMemo.set(edge.id, { edge, source, target, path: pathData });
|
|
2376
|
+
}
|
|
2377
|
+
computing.delete(edge.id);
|
|
2378
|
+
return pathData;
|
|
2379
|
+
};
|
|
2380
|
+
|
|
2381
|
+
for (const edge of [...graph.edges, ...foldedEdgesFor(c).edges]) {
|
|
2382
|
+
computeEdgePath(edge);
|
|
2383
|
+
}
|
|
2384
|
+
finishRouting();
|
|
2385
|
+
|
|
2386
|
+
if (trackSourceDependencies) {
|
|
2387
|
+
edgeSourceDependents = nextEdgeSourceDependents;
|
|
2388
|
+
lastCanonicalEdgePaths = paths;
|
|
2389
|
+
}
|
|
2390
|
+
|
|
2391
|
+
// Bound memo growth across graph swaps (entries for removed edge ids).
|
|
2392
|
+
if (memoUsable && edgePathMemo.size > graph.edges.length * 2 + 16) {
|
|
2393
|
+
edgePathMemo.clear();
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2396
|
+
return paths;
|
|
2397
|
+
}
|
|
2398
|
+
|
|
2399
|
+
// Subscribe
|
|
2400
|
+
|
|
2401
|
+
function subscribe(listener: (ctx: FlowStoreContext) => void): () => void {
|
|
2402
|
+
const subscription = store.subscribe((snapshot) => {
|
|
2403
|
+
listener(snapshot.context);
|
|
2404
|
+
});
|
|
2405
|
+
return () => subscription.unsubscribe();
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
function graphBoundsFor(c: FlowStoreContext): Rect {
|
|
2409
|
+
if (
|
|
2410
|
+
graphBoundsCache?.nodesInput === c.graph.nodes &&
|
|
2411
|
+
graphBoundsCache.edgesInput === c.graph.edges &&
|
|
2412
|
+
graphBoundsCache.measurementsInput === c.measurements
|
|
2413
|
+
) {
|
|
2414
|
+
return graphBoundsCache.value;
|
|
2415
|
+
}
|
|
2416
|
+
const value = c.appearances ? getGraphBounds(
|
|
2417
|
+
c.graph.nodes.map(sizedNode),
|
|
2418
|
+
c.graph.edges.map((edge) => edge.label ? { ...edge, label: { ...edge.label, autoSize: appearanceFor(edge.label).autoSize } } : edge),
|
|
2419
|
+
c.measurements,
|
|
2420
|
+
) : getGraphBounds(c.graph.nodes, c.graph.edges, c.measurements);
|
|
2421
|
+
graphBoundsCache = {
|
|
2422
|
+
nodesInput: c.graph.nodes,
|
|
2423
|
+
edgesInput: c.graph.edges,
|
|
2424
|
+
measurementsInput: c.measurements,
|
|
2425
|
+
value,
|
|
2426
|
+
};
|
|
2427
|
+
return value;
|
|
2428
|
+
}
|
|
2429
|
+
|
|
2430
|
+
function spatialCells(rect: Rect): string[] | null {
|
|
2431
|
+
const minX = Math.floor(rect.x / SPATIAL_CELL_SIZE);
|
|
2432
|
+
const minY = Math.floor(rect.y / SPATIAL_CELL_SIZE);
|
|
2433
|
+
const maxX = Math.floor((rect.x + Math.max(0, rect.width)) / SPATIAL_CELL_SIZE);
|
|
2434
|
+
const maxY = Math.floor((rect.y + Math.max(0, rect.height)) / SPATIAL_CELL_SIZE);
|
|
2435
|
+
const count = (maxX - minX + 1) * (maxY - minY + 1);
|
|
2436
|
+
if (count > MAX_ENTITY_SPATIAL_CELLS) return null;
|
|
2437
|
+
const cells: string[] = [];
|
|
2438
|
+
for (let y = minY; y <= maxY; y++) {
|
|
2439
|
+
for (let x = minX; x <= maxX; x++) cells.push(`${x}:${y}`);
|
|
2440
|
+
}
|
|
2441
|
+
return cells;
|
|
2442
|
+
}
|
|
2443
|
+
|
|
2444
|
+
function addSpatialEntry(
|
|
2445
|
+
cells: Map<string, string[]>,
|
|
2446
|
+
globalIds: string[],
|
|
2447
|
+
id: string,
|
|
2448
|
+
bounds: Rect,
|
|
2449
|
+
): void {
|
|
2450
|
+
const keys = spatialCells(bounds);
|
|
2451
|
+
if (!keys) {
|
|
2452
|
+
globalIds.push(id);
|
|
2453
|
+
return;
|
|
2454
|
+
}
|
|
2455
|
+
for (const key of keys) {
|
|
2456
|
+
const ids = cells.get(key);
|
|
2457
|
+
if (ids) ids.push(id);
|
|
2458
|
+
else cells.set(key, [id]);
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
function edgeSpatialBounds(
|
|
2463
|
+
edge: FlowEdge,
|
|
2464
|
+
path: EdgePathData | undefined,
|
|
2465
|
+
c: FlowStoreContext,
|
|
2466
|
+
): Rect | null {
|
|
2467
|
+
let bounds: Rect | null = path?.labelBounds ?? null;
|
|
2468
|
+
for (const segment of path?.segments ?? []) {
|
|
2469
|
+
const segmentBounds = pathBounds(segment);
|
|
2470
|
+
if (segmentBounds) bounds = bounds ? unionRect(bounds, segmentBounds) : segmentBounds;
|
|
2471
|
+
}
|
|
2472
|
+
if (bounds) return bounds;
|
|
2473
|
+
const source = getNode(edge.sourceId);
|
|
2474
|
+
const target = getNode(edge.targetId);
|
|
2475
|
+
if (!source || !target) return null;
|
|
2476
|
+
return unionRect(
|
|
2477
|
+
withLayoutOffset(resolvedBounds(source), source.id, c),
|
|
2478
|
+
withLayoutOffset(resolvedBounds(target), target.id, c),
|
|
2479
|
+
);
|
|
2480
|
+
}
|
|
2481
|
+
|
|
2482
|
+
/**
|
|
2483
|
+
* Viewport-query index keyed by geometry identities, never viewport. Building
|
|
2484
|
+
* is O(n + m); subsequent pan/zoom queries visit occupied viewport cells and
|
|
2485
|
+
* visible candidates instead of scanning the graph. Very large entities stay
|
|
2486
|
+
* in a small global list to cap cell fanout and retained memory.
|
|
2487
|
+
*/
|
|
2488
|
+
function spatialIndexFor(
|
|
2489
|
+
c: FlowStoreContext,
|
|
2490
|
+
order: EntityOrderCache['value'],
|
|
2491
|
+
paths: Map<string, EdgePathData>,
|
|
2492
|
+
): RenderableSpatialIndex {
|
|
2493
|
+
const cached = renderableSpatialIndex;
|
|
2494
|
+
if (
|
|
2495
|
+
cached?.nodesInput === c.graph.nodes &&
|
|
2496
|
+
cached.pathsInput === paths &&
|
|
2497
|
+
cached.measurementsInput === c.measurements &&
|
|
2498
|
+
cached.layoutOffsetsInput === c.layoutAnimation.offsets &&
|
|
2499
|
+
cached.collapsedInput === c.collapsedNodeIds
|
|
2500
|
+
) {
|
|
2501
|
+
return cached;
|
|
2502
|
+
}
|
|
2503
|
+
|
|
2504
|
+
const next: RenderableSpatialIndex = {
|
|
2505
|
+
nodesInput: c.graph.nodes,
|
|
2506
|
+
pathsInput: paths,
|
|
2507
|
+
measurementsInput: c.measurements,
|
|
2508
|
+
layoutOffsetsInput: c.layoutAnimation.offsets,
|
|
2509
|
+
collapsedInput: c.collapsedNodeIds,
|
|
2510
|
+
nodeCells: new Map(),
|
|
2511
|
+
edgeCells: new Map(),
|
|
2512
|
+
globalNodeIds: [],
|
|
2513
|
+
globalEdgeIds: [],
|
|
2514
|
+
nodeBounds: new Map(),
|
|
2515
|
+
edgeBounds: new Map(),
|
|
2516
|
+
};
|
|
2517
|
+
for (const node of order.nodes) {
|
|
2518
|
+
const bounds = hierarchyBounds(node, c);
|
|
2519
|
+
next.nodeBounds.set(node.id, bounds);
|
|
2520
|
+
addSpatialEntry(next.nodeCells, next.globalNodeIds, node.id, bounds);
|
|
2521
|
+
}
|
|
2522
|
+
for (const edge of order.edges) {
|
|
2523
|
+
const bounds = edgeSpatialBounds(edge, paths.get(edge.id), c);
|
|
2524
|
+
if (!bounds) continue;
|
|
2525
|
+
next.edgeBounds.set(edge.id, bounds);
|
|
2526
|
+
addSpatialEntry(next.edgeCells, next.globalEdgeIds, edge.id, bounds);
|
|
2527
|
+
}
|
|
2528
|
+
renderableSpatialIndex = next;
|
|
2529
|
+
return next;
|
|
2530
|
+
}
|
|
2531
|
+
|
|
2532
|
+
function spatialCandidates(
|
|
2533
|
+
cells: Map<string, string[]>,
|
|
2534
|
+
globalIds: string[],
|
|
2535
|
+
rect: Rect,
|
|
2536
|
+
): Set<string> | null {
|
|
2537
|
+
const keys = spatialCells(rect);
|
|
2538
|
+
if (!keys) return null;
|
|
2539
|
+
const ids = new Set(globalIds);
|
|
2540
|
+
for (const key of keys) {
|
|
2541
|
+
for (const id of cells.get(key) ?? []) ids.add(id);
|
|
2542
|
+
}
|
|
2543
|
+
return ids;
|
|
2544
|
+
}
|
|
2545
|
+
|
|
2546
|
+
function entityRanks(order: EntityOrderCache['value']): {
|
|
2547
|
+
nodes: Map<string, number>;
|
|
2548
|
+
edges: Map<string, number>;
|
|
2549
|
+
} {
|
|
2550
|
+
if (entityRankCache?.order === order) return entityRankCache;
|
|
2551
|
+
const ranks = {
|
|
2552
|
+
order,
|
|
2553
|
+
nodes: new Map(order.nodes.map((node, index) => [node.id, index])),
|
|
2554
|
+
edges: new Map(order.edges.map((edge, index) => [edge.id, index])),
|
|
2555
|
+
};
|
|
2556
|
+
entityRankCache = ranks;
|
|
2557
|
+
return ranks;
|
|
2558
|
+
}
|
|
2559
|
+
|
|
2560
|
+
function computeRenderableEntities(
|
|
2561
|
+
c: FlowStoreContext,
|
|
2562
|
+
options: RenderableEntitiesOptions,
|
|
2563
|
+
): { nodes: FlowNode[]; edges: FlowEdge[] } {
|
|
2564
|
+
const vp = c.viewport;
|
|
2565
|
+
const overscan = options.overscan ?? 0;
|
|
2566
|
+
const visibleRect = getVisibleBounds(vp, c.viewportSize);
|
|
2567
|
+
const cullRect: Rect = {
|
|
2568
|
+
x: visibleRect.x - overscan,
|
|
2569
|
+
y: visibleRect.y - overscan,
|
|
2570
|
+
width: visibleRect.width + overscan * 2,
|
|
2571
|
+
height: visibleRect.height + overscan * 2,
|
|
2572
|
+
};
|
|
2573
|
+
|
|
2574
|
+
// Fast path: when the whole graph already fits inside the cull rect (e.g.
|
|
2575
|
+
// fully zoomed out), every entity trivially passes the viewport test —
|
|
2576
|
+
// every node's hierarchy bounds and every edge's endpoints lie within
|
|
2577
|
+
// getGraphBounds, which is ⊆ cullRect — so the per-entity geometry tests
|
|
2578
|
+
// would all return "visible". Skip them and cull by visibility only.
|
|
2579
|
+
// Identical result; avoids ~2N intersection tests per frame at scale.
|
|
2580
|
+
const cullMode: RenderableEntitiesOptions['cull'] =
|
|
2581
|
+
options.cull === 'viewport' &&
|
|
2582
|
+
rectContains(
|
|
2583
|
+
cullRect,
|
|
2584
|
+
graphBoundsFor(c),
|
|
2585
|
+
)
|
|
2586
|
+
? 'none'
|
|
2587
|
+
: options.cull;
|
|
2588
|
+
|
|
2589
|
+
const order = getEntityOrderFor(c);
|
|
2590
|
+
if (
|
|
2591
|
+
cullMode === 'viewport' &&
|
|
2592
|
+
(c.canvasState === 'idle' || c.canvasState === 'panning')
|
|
2593
|
+
) {
|
|
2594
|
+
const edgePaths = getAllEdgePaths();
|
|
2595
|
+
const spatial = spatialIndexFor(c, order, edgePaths);
|
|
2596
|
+
const nodeIds = spatialCandidates(
|
|
2597
|
+
spatial.nodeCells,
|
|
2598
|
+
spatial.globalNodeIds,
|
|
2599
|
+
cullRect,
|
|
2600
|
+
);
|
|
2601
|
+
const edgeIds = spatialCandidates(
|
|
2602
|
+
spatial.edgeCells,
|
|
2603
|
+
spatial.globalEdgeIds,
|
|
2604
|
+
cullRect,
|
|
2605
|
+
);
|
|
2606
|
+
if (nodeIds && edgeIds) {
|
|
2607
|
+
const ranks = entityRanks(order);
|
|
2608
|
+
const nodes = [...nodeIds]
|
|
2609
|
+
.sort(
|
|
2610
|
+
(left, right) =>
|
|
2611
|
+
(ranks.nodes.get(left) ?? 0) - (ranks.nodes.get(right) ?? 0),
|
|
2612
|
+
)
|
|
2613
|
+
.flatMap((id) => {
|
|
2614
|
+
const node = getNode(id);
|
|
2615
|
+
const bounds = spatial.nodeBounds.get(id);
|
|
2616
|
+
return node &&
|
|
2617
|
+
bounds &&
|
|
2618
|
+
isNodeVisible(node, c, vp) &&
|
|
2619
|
+
rectsIntersect(bounds, cullRect)
|
|
2620
|
+
? [node]
|
|
2621
|
+
: [];
|
|
2622
|
+
});
|
|
2623
|
+
const edges = [...edgeIds]
|
|
2624
|
+
.sort(
|
|
2625
|
+
(left, right) =>
|
|
2626
|
+
(ranks.edges.get(left) ?? 0) - (ranks.edges.get(right) ?? 0),
|
|
2627
|
+
)
|
|
2628
|
+
.flatMap((id) => {
|
|
2629
|
+
const edge = getEdge(id);
|
|
2630
|
+
const bounds = spatial.edgeBounds.get(id);
|
|
2631
|
+
return edge &&
|
|
2632
|
+
bounds &&
|
|
2633
|
+
isEdgeVisible(edge, c.graph, c, vp) &&
|
|
2634
|
+
rectsIntersect(bounds, cullRect)
|
|
2635
|
+
? [edge]
|
|
2636
|
+
: [];
|
|
2637
|
+
});
|
|
2638
|
+
return { nodes, edges };
|
|
2639
|
+
}
|
|
2640
|
+
}
|
|
2641
|
+
|
|
2642
|
+
const nodes = order.nodes.filter((n) => {
|
|
2643
|
+
if (!isNodeVisible(n, c, vp)) return false;
|
|
2644
|
+
if (
|
|
2645
|
+
cullMode === 'viewport' &&
|
|
2646
|
+
!rectsIntersect(hierarchyBounds(n, c), cullRect)
|
|
2647
|
+
) {
|
|
2648
|
+
return false;
|
|
2649
|
+
}
|
|
2650
|
+
return true;
|
|
2651
|
+
});
|
|
2652
|
+
|
|
2653
|
+
// Only the viewport cull reads edge geometry; skip routing otherwise.
|
|
2654
|
+
const edgePaths = cullMode === 'viewport' ? getAllEdgePaths() : undefined;
|
|
2655
|
+
const edges = order.edges.filter((e) => {
|
|
2656
|
+
if (!isEdgeVisible(e, c.graph, c, vp)) return false;
|
|
2657
|
+
if (cullMode !== 'viewport') {
|
|
2658
|
+
return true;
|
|
2659
|
+
}
|
|
2660
|
+
|
|
2661
|
+
const path = edgePaths?.get(e.id);
|
|
2662
|
+
if (e.label) {
|
|
2663
|
+
const labelRect = path?.labelBounds ?? getEdgeLabelBounds(e.id);
|
|
2664
|
+
if (!labelRect) return false;
|
|
2665
|
+
if (rectsIntersect(labelRect, cullRect)) {
|
|
2666
|
+
return true;
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
|
|
2670
|
+
// Cull by the path's bounding box rather than sampling the curve: a
|
|
2671
|
+
// bezier is contained in its control points' AABB, so this is a
|
|
2672
|
+
// conservative (no false-negative) test that avoids re-sampling every
|
|
2673
|
+
// edge's curve on every frame — the dominant drag-frame cost at scale.
|
|
2674
|
+
if (
|
|
2675
|
+
path?.segments.some((segment) => {
|
|
2676
|
+
const bounds = pathBounds(segment);
|
|
2677
|
+
return bounds !== null && rectsIntersect(bounds, cullRect);
|
|
2678
|
+
})
|
|
2679
|
+
) {
|
|
2680
|
+
return true;
|
|
2681
|
+
}
|
|
2682
|
+
|
|
2683
|
+
const srcNode = getNode(e.sourceId);
|
|
2684
|
+
const tgtNode = getNode(e.targetId);
|
|
2685
|
+
return !!srcNode && !!tgtNode && (
|
|
2686
|
+
rectsIntersect(withLayoutOffset(resolvedBounds(srcNode), srcNode.id, c), cullRect) ||
|
|
2687
|
+
rectsIntersect(withLayoutOffset(resolvedBounds(tgtNode), tgtNode.id, c), cullRect)
|
|
2688
|
+
);
|
|
2689
|
+
});
|
|
2690
|
+
|
|
2691
|
+
return { nodes, edges };
|
|
2692
|
+
}
|
|
2693
|
+
|
|
2694
|
+
function selectedBoostEnabled(kind: 'node' | 'edge'): boolean {
|
|
2695
|
+
if (kind === 'node') return engineOptions.elevateOnSelect?.nodes ?? true;
|
|
2696
|
+
return engineOptions.elevateOnSelect?.edges ?? false;
|
|
2697
|
+
}
|
|
2698
|
+
|
|
2699
|
+
function getEntityOrderFor(
|
|
2700
|
+
c: FlowStoreContext,
|
|
2701
|
+
options: EntityOrderOptions = {},
|
|
2702
|
+
): { nodes: FlowNode[]; edges: FlowEdge[] } {
|
|
2703
|
+
const elevateSelected = options.elevateSelected ?? true;
|
|
2704
|
+
const selectionInput =
|
|
2705
|
+
elevateSelected &&
|
|
2706
|
+
(selectedBoostEnabled('node') || selectedBoostEnabled('edge'))
|
|
2707
|
+
? c.selection
|
|
2708
|
+
: null;
|
|
2709
|
+
const cache = elevateSelected ? entityOrderCache : baseEntityOrderCache;
|
|
2710
|
+
if (
|
|
2711
|
+
cache?.nodesInput === c.graph.nodes &&
|
|
2712
|
+
cache.edgesInput === c.graph.edges &&
|
|
2713
|
+
cache.selectionInput === selectionInput &&
|
|
2714
|
+
cache.collapsedInput === c.collapsedNodeIds
|
|
2715
|
+
) {
|
|
2716
|
+
return cache.value;
|
|
2717
|
+
}
|
|
2718
|
+
|
|
2719
|
+
const depths = nodeDepths(c.graph.nodes as FlowNode[]);
|
|
2720
|
+
const foldedEdges = foldedEdgesFor(c).edges;
|
|
2721
|
+
const elevateNodes = elevateSelected && selectedBoostEnabled('node');
|
|
2722
|
+
const elevateEdges = elevateSelected && selectedBoostEnabled('edge');
|
|
2723
|
+
const nodes = [...(c.graph.nodes as FlowNode[])].sort((a, b) => {
|
|
2724
|
+
const depthDelta = (depths.get(a.id) ?? 0) - (depths.get(b.id) ?? 0);
|
|
2725
|
+
if (depthDelta !== 0) return depthDelta;
|
|
2726
|
+
const zDelta = (a.zIndex ?? 0) - (b.zIndex ?? 0);
|
|
2727
|
+
if (zDelta !== 0) return zDelta;
|
|
2728
|
+
const selectedDelta =
|
|
2729
|
+
Number(elevateNodes && c.selection.has(a.id)) -
|
|
2730
|
+
Number(elevateNodes && c.selection.has(b.id));
|
|
2731
|
+
if (selectedDelta !== 0) return selectedDelta;
|
|
2732
|
+
// Array#sort is stable: equal entities retain canonical graph order.
|
|
2733
|
+
return 0;
|
|
2734
|
+
});
|
|
2735
|
+
|
|
2736
|
+
const edges = [...(c.graph.edges as FlowEdge[]), ...foldedEdges].sort((a, b) => {
|
|
2737
|
+
const aDepth = Math.max(depths.get(a.sourceId) ?? 0, depths.get(a.targetId) ?? 0);
|
|
2738
|
+
const bDepth = Math.max(depths.get(b.sourceId) ?? 0, depths.get(b.targetId) ?? 0);
|
|
2739
|
+
const depthDelta = aDepth - bDepth;
|
|
2740
|
+
if (depthDelta !== 0) return depthDelta;
|
|
2741
|
+
const zDelta = (a.zIndex ?? 0) - (b.zIndex ?? 0);
|
|
2742
|
+
if (zDelta !== 0) return zDelta;
|
|
2743
|
+
const selectedDelta =
|
|
2744
|
+
Number(elevateEdges && c.selection.has(a.id)) -
|
|
2745
|
+
Number(elevateEdges && c.selection.has(b.id));
|
|
2746
|
+
if (selectedDelta !== 0) return selectedDelta;
|
|
2747
|
+
return 0;
|
|
2748
|
+
});
|
|
2749
|
+
|
|
2750
|
+
const value = { nodes, edges };
|
|
2751
|
+
const nextCache = {
|
|
2752
|
+
nodesInput: c.graph.nodes,
|
|
2753
|
+
edgesInput: c.graph.edges,
|
|
2754
|
+
selectionInput,
|
|
2755
|
+
collapsedInput: c.collapsedNodeIds,
|
|
2756
|
+
value,
|
|
2757
|
+
};
|
|
2758
|
+
if (elevateSelected) entityOrderCache = nextCache;
|
|
2759
|
+
else baseEntityOrderCache = nextCache;
|
|
2760
|
+
return value;
|
|
2761
|
+
}
|
|
2762
|
+
|
|
2763
|
+
function getPaintZIndicesFor(
|
|
2764
|
+
c: FlowStoreContext,
|
|
2765
|
+
options: EntityOrderOptions = {},
|
|
2766
|
+
): PaintZIndices {
|
|
2767
|
+
const elevateSelected = options.elevateSelected ?? true;
|
|
2768
|
+
const cacheKey = `${optionsVersion}:${elevateSelected}`;
|
|
2769
|
+
const snapshotCache = paintZIndicesCache.get(c);
|
|
2770
|
+
const cached = snapshotCache?.get(cacheKey);
|
|
2771
|
+
if (cached) {
|
|
2772
|
+
return cached;
|
|
2773
|
+
}
|
|
2774
|
+
|
|
2775
|
+
const baseOrder = getEntityOrderFor(c, { elevateSelected: false });
|
|
2776
|
+
const depths = nodeDepths(c.graph.nodes as FlowNode[]);
|
|
2777
|
+
const visibleNodes = baseOrder.nodes.filter((node) =>
|
|
2778
|
+
isNodeVisible(node, c),
|
|
2779
|
+
);
|
|
2780
|
+
const visibleEdges = baseOrder.edges.filter((edge) =>
|
|
2781
|
+
isEdgeVisible(edge, c.graph, c),
|
|
2782
|
+
);
|
|
2783
|
+
const nodes = new Map<string, number>();
|
|
2784
|
+
const edges = new Map<string, number>();
|
|
2785
|
+
|
|
2786
|
+
for (let start = 0; start < visibleNodes.length; ) {
|
|
2787
|
+
const first = visibleNodes[start]!;
|
|
2788
|
+
const depth = depths.get(first.id) ?? 0;
|
|
2789
|
+
const zIndex = first.zIndex ?? 0;
|
|
2790
|
+
let end = start + 1;
|
|
2791
|
+
while (end < visibleNodes.length) {
|
|
2792
|
+
const node = visibleNodes[end]!;
|
|
2793
|
+
if (
|
|
2794
|
+
(depths.get(node.id) ?? 0) !== depth ||
|
|
2795
|
+
(node.zIndex ?? 0) !== zIndex
|
|
2796
|
+
) {
|
|
2797
|
+
break;
|
|
2798
|
+
}
|
|
2799
|
+
end++;
|
|
2800
|
+
}
|
|
2801
|
+
const elevatedZIndex = 2 * (end - 1) + 1;
|
|
2802
|
+
for (let index = start; index < end; index++) {
|
|
2803
|
+
const node = visibleNodes[index]!;
|
|
2804
|
+
nodes.set(
|
|
2805
|
+
node.id,
|
|
2806
|
+
elevateSelected &&
|
|
2807
|
+
selectedBoostEnabled('node') &&
|
|
2808
|
+
c.selection.has(node.id)
|
|
2809
|
+
? elevatedZIndex
|
|
2810
|
+
: 2 * index,
|
|
2811
|
+
);
|
|
2812
|
+
}
|
|
2813
|
+
start = end;
|
|
2814
|
+
}
|
|
2815
|
+
|
|
2816
|
+
for (let start = 0; start < visibleEdges.length; ) {
|
|
2817
|
+
const first = visibleEdges[start]!;
|
|
2818
|
+
const depth = Math.max(
|
|
2819
|
+
depths.get(first.sourceId) ?? 0,
|
|
2820
|
+
depths.get(first.targetId) ?? 0,
|
|
2821
|
+
);
|
|
2822
|
+
const zIndex = first.zIndex ?? 0;
|
|
2823
|
+
let end = start + 1;
|
|
2824
|
+
while (end < visibleEdges.length) {
|
|
2825
|
+
const edge = visibleEdges[end]!;
|
|
2826
|
+
if (
|
|
2827
|
+
Math.max(
|
|
2828
|
+
depths.get(edge.sourceId) ?? 0,
|
|
2829
|
+
depths.get(edge.targetId) ?? 0,
|
|
2830
|
+
) !== depth ||
|
|
2831
|
+
(edge.zIndex ?? 0) !== zIndex
|
|
2832
|
+
) {
|
|
2833
|
+
break;
|
|
2834
|
+
}
|
|
2835
|
+
end++;
|
|
2836
|
+
}
|
|
2837
|
+
const elevatedZIndex = 2 * (end - 1) + 1;
|
|
2838
|
+
for (let index = start; index < end; index++) {
|
|
2839
|
+
const edge = visibleEdges[index]!;
|
|
2840
|
+
edges.set(
|
|
2841
|
+
edge.id,
|
|
2842
|
+
elevateSelected &&
|
|
2843
|
+
selectedBoostEnabled('edge') &&
|
|
2844
|
+
c.selection.has(edge.id)
|
|
2845
|
+
? elevatedZIndex
|
|
2846
|
+
: 2 * index,
|
|
2847
|
+
);
|
|
2848
|
+
}
|
|
2849
|
+
start = end;
|
|
2850
|
+
}
|
|
2851
|
+
|
|
2852
|
+
const value = { nodes, edges };
|
|
2853
|
+
const nextSnapshotCache =
|
|
2854
|
+
snapshotCache ?? new Map<string, PaintZIndices>();
|
|
2855
|
+
nextSnapshotCache.set(cacheKey, value);
|
|
2856
|
+
if (!snapshotCache) paintZIndicesCache.set(c, nextSnapshotCache);
|
|
2857
|
+
return value;
|
|
2858
|
+
}
|
|
2859
|
+
|
|
2860
|
+
// Public API (purely derived — no mutable state)
|
|
2861
|
+
|
|
2862
|
+
function getPublicVisualBounds(nodeOrId: FlowNode | string): Rect {
|
|
2863
|
+
const node = typeof nodeOrId === 'string' ? getNode(nodeOrId) : nodeOrId;
|
|
2864
|
+
if (!node) return { x: 0, y: 0, width: 0, height: 0 };
|
|
2865
|
+
return visualBounds(node, getVisualSnapOffset());
|
|
2866
|
+
}
|
|
2867
|
+
|
|
2868
|
+
function getPublicVisualPosition(nodeOrId: FlowNode | string): Point {
|
|
2869
|
+
const bounds = getPublicVisualBounds(nodeOrId);
|
|
2870
|
+
return { x: bounds.x, y: bounds.y };
|
|
2871
|
+
}
|
|
2872
|
+
|
|
2873
|
+
return {
|
|
2874
|
+
store,
|
|
2875
|
+
trigger: store.trigger,
|
|
2876
|
+
getContext: ctx,
|
|
2877
|
+
setOptions,
|
|
2878
|
+
invalidateRoutes,
|
|
2879
|
+
|
|
2880
|
+
resolveAppearance: appearanceFor,
|
|
2881
|
+
isPortAllowed,
|
|
2882
|
+
getConnectionBounds: (id: string): Rect | null => {
|
|
2883
|
+
const node = getNode(id);
|
|
2884
|
+
if (node) return connectionBounds(id, node, getPublicVisualBounds(node));
|
|
2885
|
+
const edge = getEdge(id);
|
|
2886
|
+
const bounds = getAllEdgePaths().get(id)?.labelBounds;
|
|
2887
|
+
return edge?.label && bounds ? connectionBounds(id, edge.label, bounds) : null;
|
|
2888
|
+
},
|
|
2889
|
+
// Entity accessors
|
|
2890
|
+
getNode,
|
|
2891
|
+
getEdge,
|
|
2892
|
+
getEntity,
|
|
2893
|
+
getAddressable,
|
|
2894
|
+
getEntityRef,
|
|
2895
|
+
getOwnerEntity,
|
|
2896
|
+
getBounds,
|
|
2897
|
+
|
|
2898
|
+
// Coordinate conversion
|
|
2899
|
+
screenToCanvas,
|
|
2900
|
+
canvasToScreen,
|
|
2901
|
+
|
|
2902
|
+
// Hit testing
|
|
2903
|
+
entityAtPoint,
|
|
2904
|
+
entityIdAtPoint,
|
|
2905
|
+
getConnectionCandidate,
|
|
2906
|
+
|
|
2907
|
+
// Edge routing
|
|
2908
|
+
getEdgePath,
|
|
2909
|
+
getEdgePathBounds,
|
|
2910
|
+
getEdgeLabelBounds,
|
|
2911
|
+
getAllEdgePaths,
|
|
2912
|
+
getEdgeSourceDependents: (edgeId: string): readonly string[] => [
|
|
2913
|
+
...(edgeSourceDependents.get(edgeId) ?? []),
|
|
2914
|
+
],
|
|
2915
|
+
|
|
2916
|
+
// Visual positions (accept node or id)
|
|
2917
|
+
visualPosition: getPublicVisualPosition,
|
|
2918
|
+
visualBounds: getPublicVisualBounds,
|
|
2919
|
+
/** @deprecated Use `visualPosition`. */
|
|
2920
|
+
resolvedPosition: getPublicVisualPosition,
|
|
2921
|
+
/** @deprecated Use `visualBounds`. */
|
|
2922
|
+
resolvedBounds: getPublicVisualBounds,
|
|
2923
|
+
|
|
2924
|
+
/**
|
|
2925
|
+
* All highlights on an entity as `{ kind, meta }` entries. Returns a
|
|
2926
|
+
* referentially stable array (the same empty array when none), so
|
|
2927
|
+
* subscribers can use identity equality.
|
|
2928
|
+
*/
|
|
2929
|
+
getHighlights: (entityId: string): ReadonlyArray<{ kind: string; meta: unknown }> => {
|
|
2930
|
+
const highlights = ctx().highlights;
|
|
2931
|
+
if (highlights.size === 0) return NO_HIGHLIGHTS;
|
|
2932
|
+
let index = highlightIndexCache.get(highlights);
|
|
2933
|
+
if (!index) {
|
|
2934
|
+
index = new Map();
|
|
2935
|
+
for (const [kind, bucket] of highlights) {
|
|
2936
|
+
for (const [id, meta] of bucket) {
|
|
2937
|
+
let entries = index.get(id);
|
|
2938
|
+
if (!entries) index.set(id, (entries = []));
|
|
2939
|
+
entries.push({ kind, meta });
|
|
2940
|
+
}
|
|
2941
|
+
}
|
|
2942
|
+
highlightIndexCache.set(highlights, index);
|
|
2943
|
+
}
|
|
2944
|
+
return index.get(entityId) ?? NO_HIGHLIGHTS;
|
|
2945
|
+
},
|
|
2946
|
+
|
|
2947
|
+
/** Whether the entity is currently hovered. */
|
|
2948
|
+
isHovered: (entityId: string): boolean =>
|
|
2949
|
+
ctx().hoveredEntityIds.has(entityId),
|
|
2950
|
+
|
|
2951
|
+
/**
|
|
2952
|
+
* Deepest group whose child area intersects `bounds`, with the overlap
|
|
2953
|
+
* ratio (intersection / bounds area). Groups in `exclude` (and groups
|
|
2954
|
+
* inside excluded subtrees) are skipped, and excluded nodes do not
|
|
2955
|
+
* contribute to derived child areas — i.e. each group is evaluated as it
|
|
2956
|
+
* would be without the moving nodes. Drives reparent-on-drop.
|
|
2957
|
+
*/
|
|
2958
|
+
getGroupDropTarget: (
|
|
2959
|
+
bounds: Rect,
|
|
2960
|
+
options: { exclude?: Iterable<string> } = {},
|
|
2961
|
+
): { id: string; overlap: number; childArea: Rect } | null => {
|
|
2962
|
+
const c = ctx();
|
|
2963
|
+
const excluded = new Set(options.exclude ?? []);
|
|
2964
|
+
const nodeIndex = indexNodes(c.graph.nodes);
|
|
2965
|
+
const depths = nodeDepths(c.graph.nodes as FlowNode[]);
|
|
2966
|
+
const area = Math.max(bounds.width * bounds.height, 1);
|
|
2967
|
+
|
|
2968
|
+
let best:
|
|
2969
|
+
| { id: string; overlap: number; childArea: Rect; depth: number }
|
|
2970
|
+
| null = null;
|
|
2971
|
+
for (const node of c.graph.nodes) {
|
|
2972
|
+
if (!node.group || node.hidden || excluded.has(node.id)) continue;
|
|
2973
|
+
// skip groups inside an excluded (moving) subtree
|
|
2974
|
+
let ancestorId = node.parentId ?? null;
|
|
2975
|
+
let insideExcluded = false;
|
|
2976
|
+
const seen = new Set<string>();
|
|
2977
|
+
while (ancestorId && !seen.has(ancestorId)) {
|
|
2978
|
+
if (excluded.has(ancestorId)) {
|
|
2979
|
+
insideExcluded = true;
|
|
2980
|
+
break;
|
|
2981
|
+
}
|
|
2982
|
+
seen.add(ancestorId);
|
|
2983
|
+
ancestorId = nodeIndex.get(ancestorId)?.parentId ?? null;
|
|
2984
|
+
}
|
|
2985
|
+
if (insideExcluded) continue;
|
|
2986
|
+
|
|
2987
|
+
const childArea = computeGroupGeometryRaw(
|
|
2988
|
+
c,
|
|
2989
|
+
node,
|
|
2990
|
+
undefined,
|
|
2991
|
+
excluded,
|
|
2992
|
+
).childArea;
|
|
2993
|
+
const ix = Math.max(
|
|
2994
|
+
0,
|
|
2995
|
+
Math.min(bounds.x + bounds.width, childArea.x + childArea.width) -
|
|
2996
|
+
Math.max(bounds.x, childArea.x),
|
|
2997
|
+
);
|
|
2998
|
+
const iy = Math.max(
|
|
2999
|
+
0,
|
|
3000
|
+
Math.min(bounds.y + bounds.height, childArea.y + childArea.height) -
|
|
3001
|
+
Math.max(bounds.y, childArea.y),
|
|
3002
|
+
);
|
|
3003
|
+
const overlap = (ix * iy) / area;
|
|
3004
|
+
if (overlap <= 0) continue;
|
|
3005
|
+
const depth = depths.get(node.id) ?? 0;
|
|
3006
|
+
if (
|
|
3007
|
+
!best ||
|
|
3008
|
+
depth > best.depth ||
|
|
3009
|
+
(depth === best.depth && overlap > best.overlap)
|
|
3010
|
+
) {
|
|
3011
|
+
best = { id: node.id, overlap, childArea, depth };
|
|
3012
|
+
}
|
|
3013
|
+
}
|
|
3014
|
+
return best
|
|
3015
|
+
? { id: best.id, overlap: best.overlap, childArea: best.childArea }
|
|
3016
|
+
: null;
|
|
3017
|
+
},
|
|
3018
|
+
|
|
3019
|
+
/**
|
|
3020
|
+
* Canvas-space anchor rect for toolbars: a node's (hierarchy-aware)
|
|
3021
|
+
* bounds, an edge's label bounds — or, with no label, an assumed 1×1
|
|
3022
|
+
* label at the path midpoint — and, given several ids (e.g. the
|
|
3023
|
+
* selection), the union of their anchors. Null when nothing resolves.
|
|
3024
|
+
*/
|
|
3025
|
+
getToolbarAnchor: (idOrIds: string | Iterable<string>): Rect | null => {
|
|
3026
|
+
const ids = typeof idOrIds === 'string' ? [idOrIds] : [...idOrIds];
|
|
3027
|
+
const c = ctx();
|
|
3028
|
+
let union: Rect | null = null;
|
|
3029
|
+
for (const id of ids) {
|
|
3030
|
+
let rect: Rect | null = null;
|
|
3031
|
+
const node = getNode(id);
|
|
3032
|
+
if (node) {
|
|
3033
|
+
rect = hierarchyBounds(node, c);
|
|
3034
|
+
} else {
|
|
3035
|
+
const edge = getEdge(id);
|
|
3036
|
+
if (edge?.label) {
|
|
3037
|
+
const labelBounds = getEdgeLabelBounds(edge.id);
|
|
3038
|
+
if (labelBounds && (labelBounds.width || labelBounds.height)) {
|
|
3039
|
+
rect = labelBounds;
|
|
3040
|
+
}
|
|
3041
|
+
} else if (edge) {
|
|
3042
|
+
const points =
|
|
3043
|
+
getAllEdgePaths().get(id)?.segments[0]?.points ?? [];
|
|
3044
|
+
if (points.length > 0) {
|
|
3045
|
+
const mid =
|
|
3046
|
+
points.length % 2 === 1
|
|
3047
|
+
? points[(points.length - 1) / 2]
|
|
3048
|
+
: {
|
|
3049
|
+
x: (points[points.length / 2 - 1].x + points[points.length / 2].x) / 2,
|
|
3050
|
+
y: (points[points.length / 2 - 1].y + points[points.length / 2].y) / 2,
|
|
3051
|
+
};
|
|
3052
|
+
rect = { x: mid.x, y: mid.y, width: 1, height: 1 };
|
|
3053
|
+
}
|
|
3054
|
+
}
|
|
3055
|
+
}
|
|
3056
|
+
if (!rect) continue;
|
|
3057
|
+
union = union ? uniteRects(union, rect) : rect;
|
|
3058
|
+
}
|
|
3059
|
+
return union;
|
|
3060
|
+
},
|
|
3061
|
+
|
|
3062
|
+
/** The node containing this edge (null = root). See `edgeOwner` option. */
|
|
3063
|
+
getEdgeOwner: (edgeId: string): string | null => {
|
|
3064
|
+
const c = ctx();
|
|
3065
|
+
const edge = indexEdges(c.graph.edges).get(edgeId);
|
|
3066
|
+
if (!edge) return null;
|
|
3067
|
+
return edgeOwnerOf(edge as FlowEdge, c);
|
|
3068
|
+
},
|
|
3069
|
+
|
|
3070
|
+
/** Group geometry (overall bounds, content block, child area), or null. */
|
|
3071
|
+
getGroupGeometry: (nodeOrId: FlowNode | string): GroupGeometry | null => {
|
|
3072
|
+
const node = typeof nodeOrId === 'string' ? getNode(nodeOrId) : nodeOrId;
|
|
3073
|
+
if (!node) return null;
|
|
3074
|
+
return groupGeometryFor(ctx(), node);
|
|
3075
|
+
},
|
|
3076
|
+
|
|
3077
|
+
// Graph bounds
|
|
3078
|
+
getGraphBounds: () => {
|
|
3079
|
+
return graphBoundsFor(ctx());
|
|
3080
|
+
},
|
|
3081
|
+
|
|
3082
|
+
// Graph traversal
|
|
3083
|
+
getIncomers: (nodeId: string): FlowNode[] => getGraphIncomers(ctx().graph, nodeId),
|
|
3084
|
+
getOutgoers: (nodeId: string): FlowNode[] => getGraphOutgoers(ctx().graph, nodeId),
|
|
3085
|
+
getConnectedEdges: (nodeIds: Iterable<string>): FlowEdge[] =>
|
|
3086
|
+
getGraphConnectedEdges(ctx().graph, nodeIds),
|
|
3087
|
+
getNeighbors: (nodeId: string): FlowNode[] => getGraphNeighbors(ctx().graph, nodeId),
|
|
3088
|
+
|
|
3089
|
+
// Selection bounds
|
|
3090
|
+
getSelectionBounds: () => {
|
|
3091
|
+
const c = ctx();
|
|
3092
|
+
return getSelectionSnapBounds(c, true);
|
|
3093
|
+
},
|
|
3094
|
+
|
|
3095
|
+
// Find entities within a rect (for box-select, etc.)
|
|
3096
|
+
entitiesInRect: (rect: Rect): string[] => {
|
|
3097
|
+
const c = ctx();
|
|
3098
|
+
const { graph } = c;
|
|
3099
|
+
const ids: string[] = [];
|
|
3100
|
+
for (const n of graph.nodes) {
|
|
3101
|
+
if (!isNodeVisible(n, c)) continue;
|
|
3102
|
+
const bounds = n.selectionBounds
|
|
3103
|
+
? resolvedSelectionBounds(sizedNode(n))
|
|
3104
|
+
: visualBounds(n, getVisualSnapOffset());
|
|
3105
|
+
if (rectsIntersect(rect, bounds)) {
|
|
3106
|
+
ids.push(n.id);
|
|
3107
|
+
}
|
|
3108
|
+
}
|
|
3109
|
+
for (const e of graph.edges) {
|
|
3110
|
+
if (!isEdgeVisible(e, graph, c)) continue;
|
|
3111
|
+
if (!e.label) continue;
|
|
3112
|
+
const lb = getEdgeLabelBounds(e.id)!;
|
|
3113
|
+
if (rectsIntersect(rect, lb)) ids.push(e.id);
|
|
3114
|
+
}
|
|
3115
|
+
return ids;
|
|
3116
|
+
},
|
|
3117
|
+
|
|
3118
|
+
// Port resolution
|
|
3119
|
+
|
|
3120
|
+
getPortPosition: (nodeId: string, portName: string): Point | null => {
|
|
3121
|
+
const node = getNode(nodeId);
|
|
3122
|
+
if (!node?.ports) return null;
|
|
3123
|
+
const port = node.ports.find((p) => p.name === portName);
|
|
3124
|
+
if (!port) return null;
|
|
3125
|
+
return portCenter(node, port);
|
|
3126
|
+
},
|
|
3127
|
+
|
|
3128
|
+
getPortPositions: (nodeId: string): Map<string, Point> => {
|
|
3129
|
+
const result = new Map<string, Point>();
|
|
3130
|
+
const node = getNode(nodeId);
|
|
3131
|
+
if (!node?.ports) return result;
|
|
3132
|
+
const snap = getVisualSnapOffset();
|
|
3133
|
+
for (const port of node.ports) {
|
|
3134
|
+
result.set(port.name, portCenter(node, port, snap));
|
|
3135
|
+
}
|
|
3136
|
+
return result;
|
|
3137
|
+
},
|
|
3138
|
+
|
|
3139
|
+
getEdgeEndpoints: (edgeId: string): { source: Point; target: Point } | null => {
|
|
3140
|
+
const { graph } = ctx();
|
|
3141
|
+
const edge = graph.edges.find((e) => e.id === edgeId);
|
|
3142
|
+
if (!edge) return null;
|
|
3143
|
+
|
|
3144
|
+
const authoritative = resolvedAuthoritativePath(edge);
|
|
3145
|
+
if (authoritative) {
|
|
3146
|
+
return {
|
|
3147
|
+
source: authoritative.points[0]!,
|
|
3148
|
+
target: authoritative.points.at(-1)!,
|
|
3149
|
+
};
|
|
3150
|
+
}
|
|
3151
|
+
|
|
3152
|
+
if (edge.label) {
|
|
3153
|
+
const path = getAllEdgePaths().get(edgeId);
|
|
3154
|
+
const first = path?.segments[0]?.points[0];
|
|
3155
|
+
const last = path?.segments.at(-1)?.points.at(-1);
|
|
3156
|
+
if (first && last) return { source: first, target: last };
|
|
3157
|
+
}
|
|
3158
|
+
const srcNode = graph.nodes.find((n) => n.id === edge.sourceId);
|
|
3159
|
+
const tgtNode = graph.nodes.find((n) => n.id === edge.targetId);
|
|
3160
|
+
if (!srcNode || !tgtNode) return null;
|
|
3161
|
+
|
|
3162
|
+
const snap = getVisualSnapOffset();
|
|
3163
|
+
const { sourcePoint, targetPoint } = resolveEdgeGeometry(
|
|
3164
|
+
edge,
|
|
3165
|
+
srcNode,
|
|
3166
|
+
tgtNode,
|
|
3167
|
+
snap,
|
|
3168
|
+
(id) => getAllEdgePaths().get(id)?.labelBounds ?? getEdgeLabelBounds(id),
|
|
3169
|
+
graph,
|
|
3170
|
+
ctx(),
|
|
3171
|
+
);
|
|
3172
|
+
return { source: sourcePoint, target: targetPoint };
|
|
3173
|
+
},
|
|
3174
|
+
|
|
3175
|
+
// Connection validation
|
|
3176
|
+
|
|
3177
|
+
validateConnection,
|
|
3178
|
+
validateConnectionDetailed,
|
|
3179
|
+
|
|
3180
|
+
// Entity config resolution
|
|
3181
|
+
|
|
3182
|
+
resolveEntityConfig,
|
|
3183
|
+
|
|
3184
|
+
// Visibility
|
|
3185
|
+
|
|
3186
|
+
getVisibleEntities: (
|
|
3187
|
+
options: EntityOrderOptions = {},
|
|
3188
|
+
): { nodes: FlowNode[]; edges: FlowEdge[] } => {
|
|
3189
|
+
const c = ctx();
|
|
3190
|
+
const order = getEntityOrderFor(c, options);
|
|
3191
|
+
return {
|
|
3192
|
+
nodes: order.nodes.filter((n) => isNodeVisible(n, c)),
|
|
3193
|
+
edges: order.edges.filter((e) => isEdgeVisible(e, c.graph, c)),
|
|
3194
|
+
};
|
|
3195
|
+
},
|
|
3196
|
+
|
|
3197
|
+
/** Deterministic paint order. Later items should paint above earlier ones. */
|
|
3198
|
+
getEntityOrder: (
|
|
3199
|
+
options: EntityOrderOptions = {},
|
|
3200
|
+
): { nodes: FlowNode[]; edges: FlowEdge[] } => getEntityOrderFor(ctx(), options),
|
|
3201
|
+
|
|
3202
|
+
/**
|
|
3203
|
+
* CSS z-indices for the visible entity set. Base values are spaced by 2.
|
|
3204
|
+
* When `elevateOnSelect` allows an entity kind, a selected entity is
|
|
3205
|
+
* raised just above its own depth/zIndex band while remaining below the
|
|
3206
|
+
* next band, so a selected parent never paints over its descendants.
|
|
3207
|
+
* Multiple selected entities in one band tie; the renderer's DOM order
|
|
3208
|
+
* resolves the tie and matches core's elevated order. The result is
|
|
3209
|
+
* memoized per store snapshot so callers can compare it by identity.
|
|
3210
|
+
*/
|
|
3211
|
+
getPaintZIndices: (
|
|
3212
|
+
options: EntityOrderOptions = {},
|
|
3213
|
+
): PaintZIndices => getPaintZIndicesFor(ctx(), options),
|
|
3214
|
+
|
|
3215
|
+
/**
|
|
3216
|
+
* Renderable (visible, optionally viewport-culled) entities. Memoized per
|
|
3217
|
+
* (store snapshot, cull/overscan) so several render layers can share one
|
|
3218
|
+
* computation per frame. Treat the result as read-only.
|
|
3219
|
+
*/
|
|
3220
|
+
getRenderableEntities: (options: RenderableEntitiesOptions = {}): { nodes: FlowNode[]; edges: FlowEdge[] } => {
|
|
3221
|
+
const c = ctx();
|
|
3222
|
+
const cacheKey = `${optionsVersion}:${options.cull ?? 'none'}:${options.overscan ?? 0}`;
|
|
3223
|
+
let byKey = renderableCache.get(c);
|
|
3224
|
+
const cached = byKey?.get(cacheKey);
|
|
3225
|
+
if (cached) return cached;
|
|
3226
|
+
const result = computeRenderableEntities(c, options);
|
|
3227
|
+
if (!byKey) {
|
|
3228
|
+
byKey = new Map();
|
|
3229
|
+
renderableCache.set(c, byKey);
|
|
3230
|
+
}
|
|
3231
|
+
byKey.set(cacheKey, result);
|
|
3232
|
+
return result;
|
|
3233
|
+
},
|
|
3234
|
+
|
|
3235
|
+
// Intersection
|
|
3236
|
+
|
|
3237
|
+
getIntersectingNodes: (nodeId: string): FlowNode[] => {
|
|
3238
|
+
const node = getNode(nodeId);
|
|
3239
|
+
if (!node) return [];
|
|
3240
|
+
const bounds = visualBounds(node, getVisualSnapOffset());
|
|
3241
|
+
return ctx().graph.nodes.filter(
|
|
3242
|
+
(n) =>
|
|
3243
|
+
n.id !== nodeId &&
|
|
3244
|
+
rectsIntersect(bounds, visualBounds(n, getVisualSnapOffset())),
|
|
3245
|
+
);
|
|
3246
|
+
},
|
|
3247
|
+
|
|
3248
|
+
// A11y
|
|
3249
|
+
|
|
3250
|
+
getAriaLabel: (entityId: string): string => {
|
|
3251
|
+
const { graph } = ctx();
|
|
3252
|
+
const node = graph.nodes.find((n) => n.id === entityId);
|
|
3253
|
+
if (node) return `Node: ${node.label ?? node.id}`;
|
|
3254
|
+
const edge = graph.edges.find((e) => e.id === entityId);
|
|
3255
|
+
if (edge) {
|
|
3256
|
+
const customLabel = (edge.data as { ariaLabel?: unknown } | undefined)?.ariaLabel;
|
|
3257
|
+
if (typeof customLabel === 'string') return customLabel;
|
|
3258
|
+
const src = graph.nodes.find((n) => n.id === edge.sourceId);
|
|
3259
|
+
const tgt = graph.nodes.find((n) => n.id === edge.targetId);
|
|
3260
|
+
const label = edge.label ? ` (${(edge.label.data as any)?.text ?? ''})` : '';
|
|
3261
|
+
return `Edge: ${src?.label ?? edge.sourceId} → ${tgt?.label ?? edge.targetId}${label}`;
|
|
3262
|
+
}
|
|
3263
|
+
return entityId;
|
|
3264
|
+
},
|
|
3265
|
+
|
|
3266
|
+
// Snap lines (Figma-style alignment guides — purely derived)
|
|
3267
|
+
|
|
3268
|
+
/** Compute snap result during drag. Returns null if not dragging or snap lines disabled.
|
|
3269
|
+
* Only activates after actual movement (dx/dy != 0) to avoid showing on click. */
|
|
3270
|
+
getSnapResult: (): SnapResult | null => {
|
|
3271
|
+
const c = ctx();
|
|
3272
|
+
if (c.canvasState !== 'dragging' || !c.enableSnapLines) return null;
|
|
3273
|
+
if (c.selection.size === 0) return null;
|
|
3274
|
+
|
|
3275
|
+
// Don't show snap lines until user has actually moved
|
|
3276
|
+
const nodesMoved = c.graph.nodes.some((n) => c.selection.has(n.id) && ((n.dx ?? 0) !== 0 || (n.dy ?? 0) !== 0));
|
|
3277
|
+
const edgesMoved = c.graph.edges.some((e) => c.selection.has(e.id) && e.label && ((e.label.dx ?? 0) !== 0 || (e.label.dy ?? 0) !== 0));
|
|
3278
|
+
if (!nodesMoved && !edgesMoved) return null;
|
|
3279
|
+
|
|
3280
|
+
const selBounds = getSelectionSnapBounds(c);
|
|
3281
|
+
if (!selBounds) return null;
|
|
3282
|
+
|
|
3283
|
+
const otherRects = getSnapTargetRects(c, c.selection);
|
|
3284
|
+
if (otherRects.length === 0) return null;
|
|
3285
|
+
|
|
3286
|
+
// Threshold: screen pixels → canvas pixels
|
|
3287
|
+
const canvasThreshold = c.snapThreshold / c.viewport.zoom;
|
|
3288
|
+
|
|
3289
|
+
return getSnapLines(selBounds, otherRects, {
|
|
3290
|
+
threshold: canvasThreshold,
|
|
3291
|
+
enableSpacing: c.enableSpacingGuides,
|
|
3292
|
+
});
|
|
3293
|
+
},
|
|
3294
|
+
|
|
3295
|
+
// Resize
|
|
3296
|
+
|
|
3297
|
+
/** Get in-progress resize bounds, or null if not resizing */
|
|
3298
|
+
getResizeBounds: (): Rect | null => {
|
|
3299
|
+
return getResizeBoundsFromContext(ctx());
|
|
3300
|
+
},
|
|
3301
|
+
|
|
3302
|
+
// Subscribe
|
|
3303
|
+
subscribe,
|
|
3304
|
+
};
|
|
3305
|
+
}
|
|
3306
|
+
|
|
3307
|
+
export type FlowEngine = ReturnType<typeof createFlowEngine>;
|
|
3308
|
+
|
|
3309
|
+
|
|
3310
|
+
// Helpers
|
|
3311
|
+
|
|
3312
|
+
function getResizeBoundsFromContext(c: FlowStoreContext): Rect | null {
|
|
3313
|
+
if (!c.resizeCorners || !c.resizingEntityId) return null;
|
|
3314
|
+
const [a, b] = c.resizeCorners;
|
|
3315
|
+
return {
|
|
3316
|
+
x: Math.min(a.x, b.x),
|
|
3317
|
+
y: Math.min(a.y, b.y),
|
|
3318
|
+
// Match the store's free-resize commit floor (1px degeneracy guard) so the
|
|
3319
|
+
// live preview never pops at commit time. The store's clampResizeMovingPoint
|
|
3320
|
+
// has already applied any explicit resize.min/max to the corners.
|
|
3321
|
+
width: Math.max(1, Math.abs(b.x - a.x)),
|
|
3322
|
+
height: Math.max(1, Math.abs(b.y - a.y)),
|
|
3323
|
+
};
|
|
3324
|
+
}
|
|
3325
|
+
|
|
3326
|
+
function boundsForPoints(points: Point[]): Rect | null {
|
|
3327
|
+
if (points.length === 0) return null;
|
|
3328
|
+
|
|
3329
|
+
let minX = Infinity;
|
|
3330
|
+
let minY = Infinity;
|
|
3331
|
+
let maxX = -Infinity;
|
|
3332
|
+
let maxY = -Infinity;
|
|
3333
|
+
|
|
3334
|
+
for (const point of points) {
|
|
3335
|
+
minX = Math.min(minX, point.x);
|
|
3336
|
+
minY = Math.min(minY, point.y);
|
|
3337
|
+
maxX = Math.max(maxX, point.x);
|
|
3338
|
+
maxY = Math.max(maxY, point.y);
|
|
3339
|
+
}
|
|
3340
|
+
|
|
3341
|
+
if (!isFinite(minX)) return null;
|
|
3342
|
+
|
|
3343
|
+
return {
|
|
3344
|
+
x: minX,
|
|
3345
|
+
y: minY,
|
|
3346
|
+
width: maxX - minX,
|
|
3347
|
+
height: maxY - minY,
|
|
3348
|
+
};
|
|
3349
|
+
}
|
|
3350
|
+
|
|
3351
|
+
/**
|
|
3352
|
+
* Resolve label anchor position. Returns the TOP-LEFT corner of the label.
|
|
3353
|
+
* For 'fixed': label.x/y IS the top-left (like a node).
|
|
3354
|
+
* For number: interpolates between source/target centers, then offsets to top-left.
|
|
3355
|
+
* For function: calls the function, then offsets to top-left.
|
|
3356
|
+
*/
|
|
3357
|
+
function resolveLabelAnchor(
|
|
3358
|
+
anchor: LabelAnchor,
|
|
3359
|
+
label: FlowEdgeLabel,
|
|
3360
|
+
sourceBounds: Rect,
|
|
3361
|
+
targetBounds: Rect,
|
|
3362
|
+
edge: FlowEdge,
|
|
3363
|
+
size = { width: label.width, height: label.height },
|
|
3364
|
+
): Point {
|
|
3365
|
+
if (anchor === 'fixed') {
|
|
3366
|
+
// label.x/y is top-left, just like a node
|
|
3367
|
+
return { x: label.x, y: label.y };
|
|
3368
|
+
}
|
|
3369
|
+
|
|
3370
|
+
if (typeof anchor === 'function') {
|
|
3371
|
+
const center = anchor(sourceBounds, targetBounds, edge);
|
|
3372
|
+
return { x: center.x - size.width / 2, y: center.y - size.height / 2 };
|
|
3373
|
+
}
|
|
3374
|
+
|
|
3375
|
+
// number: interpolate between source center and target center, return top-left
|
|
3376
|
+
const t = anchor;
|
|
3377
|
+
const srcCx = sourceBounds.x + sourceBounds.width / 2;
|
|
3378
|
+
const srcCy = sourceBounds.y + sourceBounds.height / 2;
|
|
3379
|
+
const tgtCx = targetBounds.x + targetBounds.width / 2;
|
|
3380
|
+
const tgtCy = targetBounds.y + targetBounds.height / 2;
|
|
3381
|
+
return {
|
|
3382
|
+
x: srcCx + (tgtCx - srcCx) * t - size.width / 2,
|
|
3383
|
+
y: srcCy + (tgtCy - srcCy) * t - size.height / 2,
|
|
3384
|
+
};
|
|
3385
|
+
}
|