@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
|
@@ -0,0 +1,3463 @@
|
|
|
1
|
+
import { createFlowExternalEdit, type FlowExternalEdit } from './external-edit';
|
|
2
|
+
import { createFlowRenderApi, type FlowRenderInvalidation } from './render-invalidation';
|
|
3
|
+
import { normalizeGeometryPosition } from './geometry';
|
|
4
|
+
import { createFlowEngine, normalizeConnection } from './engine';
|
|
5
|
+
import type {
|
|
6
|
+
FlowEngine,
|
|
7
|
+
FlowEngineOptions,
|
|
8
|
+
ConnectionCandidate,
|
|
9
|
+
ConnectionCandidateOptions,
|
|
10
|
+
EdgePathOptions,
|
|
11
|
+
EntityOrderOptions,
|
|
12
|
+
RenderableEntitiesOptions,
|
|
13
|
+
} from './engine';
|
|
14
|
+
import {
|
|
15
|
+
createFlowStore,
|
|
16
|
+
planNodeMovement,
|
|
17
|
+
clampResizeMovingPoint,
|
|
18
|
+
} from './store';
|
|
19
|
+
import type {
|
|
20
|
+
ConnectionEndedEvent,
|
|
21
|
+
FlowHighlightEntry,
|
|
22
|
+
FlowStore,
|
|
23
|
+
FlowStoreContext,
|
|
24
|
+
FlowEdgePatch,
|
|
25
|
+
FlowEdgeUpdater,
|
|
26
|
+
FlowNodePatch,
|
|
27
|
+
FlowNodeUpdater,
|
|
28
|
+
FlowStoreOptions,
|
|
29
|
+
FlowGraphHistoryPolicy,
|
|
30
|
+
FlowGraphRetentionPolicy,
|
|
31
|
+
} from './store';
|
|
32
|
+
import {
|
|
33
|
+
createEdge,
|
|
34
|
+
createNode,
|
|
35
|
+
} from './factories';
|
|
36
|
+
import type {
|
|
37
|
+
EdgePathData,
|
|
38
|
+
EdgeRouting,
|
|
39
|
+
FlowEntityRef,
|
|
40
|
+
FlowEdge,
|
|
41
|
+
FlowGraph,
|
|
42
|
+
FlowNode,
|
|
43
|
+
FitViewOptions,
|
|
44
|
+
Point,
|
|
45
|
+
Rect,
|
|
46
|
+
Size,
|
|
47
|
+
Viewport,
|
|
48
|
+
ViewportAnimationOptions,
|
|
49
|
+
} from './types';
|
|
50
|
+
import {
|
|
51
|
+
animateViewport,
|
|
52
|
+
fitFrameAroundExclusions,
|
|
53
|
+
panBy as viewportPanBy,
|
|
54
|
+
validateFitFrame,
|
|
55
|
+
viewportCenteredOn,
|
|
56
|
+
viewportForBounds,
|
|
57
|
+
zoomTo as viewportZoomTo,
|
|
58
|
+
type FitViewExclusion,
|
|
59
|
+
type ViewportAnimationControls,
|
|
60
|
+
} from './viewport';
|
|
61
|
+
import {
|
|
62
|
+
serializeFlowGraph,
|
|
63
|
+
parseFlowSerialized,
|
|
64
|
+
type FlowSerialized,
|
|
65
|
+
} from './serialize';
|
|
66
|
+
import {
|
|
67
|
+
cloneJsonSafe,
|
|
68
|
+
validateAndCloneGraph,
|
|
69
|
+
currentDataVersions,
|
|
70
|
+
type FlowDataSchemas,
|
|
71
|
+
type FlowResult,
|
|
72
|
+
FlowGraphValidationError,
|
|
73
|
+
} from './validation';
|
|
74
|
+
import {
|
|
75
|
+
applyFlowPatches,
|
|
76
|
+
createFlowChangeSet,
|
|
77
|
+
reuseUnchangedEntities,
|
|
78
|
+
type FlowChangeSet,
|
|
79
|
+
} from './changeSet';
|
|
80
|
+
import {
|
|
81
|
+
extractFlowContent,
|
|
82
|
+
insertFlowContent,
|
|
83
|
+
type FlowContent,
|
|
84
|
+
} from './content';
|
|
85
|
+
import {
|
|
86
|
+
constrainViewport,
|
|
87
|
+
getGraphBounds,
|
|
88
|
+
resolvedBounds,
|
|
89
|
+
} from './spatial';
|
|
90
|
+
import {
|
|
91
|
+
invalidateAuthoritativeEdgePath,
|
|
92
|
+
nodeEndpointGeometryChanged,
|
|
93
|
+
withDerivedGroupAncestors,
|
|
94
|
+
} from './edge-geometry';
|
|
95
|
+
import {
|
|
96
|
+
composeGraphProjectionAttrs,
|
|
97
|
+
type ActiveGraphProjection,
|
|
98
|
+
type ComposedGraphProjectionAttrs,
|
|
99
|
+
} from './projections';
|
|
100
|
+
import type { FlowPolicies } from './profile';
|
|
101
|
+
import { getNodeIdsWithDescendants } from './hierarchy';
|
|
102
|
+
import { getEdgeOwner as getDefaultEdgeOwner } from './hierarchy';
|
|
103
|
+
import { indexEdgeAdjacency } from './graph-index';
|
|
104
|
+
import { deriveFlowView } from './view';
|
|
105
|
+
import type {
|
|
106
|
+
FlowViewBoundaryEndpoints,
|
|
107
|
+
FlowViewEntities,
|
|
108
|
+
FlowViewScope,
|
|
109
|
+
FlowViewSelectionPolicy,
|
|
110
|
+
} from './view';
|
|
111
|
+
|
|
112
|
+
declare const requestAnimationFrame:
|
|
113
|
+
| ((callback: (time: number) => void) => number)
|
|
114
|
+
| undefined;
|
|
115
|
+
declare const cancelAnimationFrame: ((id: number) => void) | undefined;
|
|
116
|
+
declare const setTimeout: (callback: () => void, ms: number) => number;
|
|
117
|
+
declare const clearTimeout: (id: number) => void;
|
|
118
|
+
|
|
119
|
+
export type LayoutDiagnostic = {
|
|
120
|
+
message: string;
|
|
121
|
+
severity?: 'info' | 'warning' | 'error';
|
|
122
|
+
code?: string;
|
|
123
|
+
entityId?: string;
|
|
124
|
+
entityIds?: readonly string[];
|
|
125
|
+
phase?: string;
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
export type LayoutEdgeRoute =
|
|
129
|
+
| { waypoints: readonly Point[] }
|
|
130
|
+
| { points: readonly Point[]; routing?: EdgeRouting };
|
|
131
|
+
|
|
132
|
+
function hasAuthoritativeLayoutPoints(
|
|
133
|
+
route: LayoutEdgeRoute | readonly Point[],
|
|
134
|
+
): route is Extract<LayoutEdgeRoute, { points: readonly Point[] }> {
|
|
135
|
+
return !Array.isArray(route) && 'points' in route;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function layoutWaypoints(
|
|
139
|
+
route: LayoutEdgeRoute | readonly Point[],
|
|
140
|
+
): readonly Point[] {
|
|
141
|
+
return Array.isArray(route)
|
|
142
|
+
? (route as readonly Point[])
|
|
143
|
+
: (route as Extract<LayoutEdgeRoute, { waypoints: readonly Point[] }>).waypoints;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export type LayoutResult = {
|
|
147
|
+
positions: ReadonlyMap<string, Point>;
|
|
148
|
+
nodeSizes?: ReadonlyMap<string, Size>;
|
|
149
|
+
nodeBounds?: ReadonlyMap<string, Rect>;
|
|
150
|
+
edgeLabelPositions?: ReadonlyMap<string, Point>;
|
|
151
|
+
edgeLabelBounds?: ReadonlyMap<string, Rect>;
|
|
152
|
+
edgeRoutes?: ReadonlyMap<string, LayoutEdgeRoute | readonly Point[]>;
|
|
153
|
+
diagnostics?: readonly LayoutDiagnostic[];
|
|
154
|
+
quality?: Readonly<Record<string, unknown>>;
|
|
155
|
+
metadata?: Readonly<Record<string, unknown>>;
|
|
156
|
+
source?: string;
|
|
157
|
+
/** Fixed entities listed here may be changed by this result. */
|
|
158
|
+
overrideFixedEntityIds?: ReadonlySet<string>;
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
export type LayoutPositions = Map<string, Point>;
|
|
162
|
+
|
|
163
|
+
export type FlowAbortSignal = {
|
|
164
|
+
readonly aborted: boolean;
|
|
165
|
+
addEventListener: (
|
|
166
|
+
type: 'abort',
|
|
167
|
+
listener: () => void,
|
|
168
|
+
options?: { once?: boolean },
|
|
169
|
+
) => void;
|
|
170
|
+
removeEventListener: (type: 'abort', listener: () => void) => void;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
export type LayoutRunOptions = {
|
|
174
|
+
signal?: FlowAbortSignal;
|
|
175
|
+
/** Apply even if the graph changed while the algorithm was running. */
|
|
176
|
+
force?: boolean;
|
|
177
|
+
scope?: FlowViewScope;
|
|
178
|
+
previousResult?: LayoutResult | null;
|
|
179
|
+
fixedEntityIds?: ReadonlySet<string>;
|
|
180
|
+
pinnedEntityIds?: ReadonlySet<string>;
|
|
181
|
+
source?: string;
|
|
182
|
+
metadata?: Readonly<Record<string, unknown>>;
|
|
183
|
+
animation?: LayoutAnimationOptions;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
export type LayoutAnimationOptions = {
|
|
187
|
+
duration?: number;
|
|
188
|
+
easing?: (progress: number) => number;
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
export type LayoutAnimationControls = {
|
|
192
|
+
cancel: () => void;
|
|
193
|
+
done: Promise<void>;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
export type LayoutApplyOptions = FlowTransactionOptions & {
|
|
197
|
+
fixedEntityIds?: ReadonlySet<string>;
|
|
198
|
+
pinnedEntityIds?: ReadonlySet<string>;
|
|
199
|
+
overrideFixedEntityIds?: ReadonlySet<string>;
|
|
200
|
+
animation?: LayoutAnimationOptions;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
export type LayoutRunResult = {
|
|
204
|
+
applied: boolean;
|
|
205
|
+
result: LayoutResult;
|
|
206
|
+
source?: string;
|
|
207
|
+
diagnostics?: readonly LayoutDiagnostic[];
|
|
208
|
+
animation: LayoutAnimationControls;
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
export type LayoutAlgorithm<
|
|
212
|
+
TNodeData = any,
|
|
213
|
+
TEdgeData = any,
|
|
214
|
+
TLabelData = any,
|
|
215
|
+
> = (
|
|
216
|
+
graph: Readonly<FlowGraph<TNodeData, TEdgeData, TLabelData>>,
|
|
217
|
+
options: Readonly<LayoutRunOptions> & { signal: FlowAbortSignal },
|
|
218
|
+
) => Promise<LayoutResult | LayoutPositions>;
|
|
219
|
+
|
|
220
|
+
export type FlowProjectionListener = (
|
|
221
|
+
projections: readonly ActiveGraphProjection[],
|
|
222
|
+
) => void;
|
|
223
|
+
|
|
224
|
+
export type FlowTransactionOptions = { transactionId?: string; origin?: string; history?: 'record' | 'ignore' };
|
|
225
|
+
|
|
226
|
+
export type FlowMeasurement = { id: string; rect: Rect };
|
|
227
|
+
|
|
228
|
+
export type FlowMeasurementsApi = {
|
|
229
|
+
update: (batch: readonly FlowMeasurement[]) => void;
|
|
230
|
+
remove: (ids: readonly string[]) => void;
|
|
231
|
+
get: (id: string) => Rect | undefined;
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
export type FlowGeometryOptions = FlowTransactionOptions & {
|
|
235
|
+
/** Decimal places for settled positions. Defaults to whole CSS pixels; null preserves exact coordinates. Sizes stay precise. */
|
|
236
|
+
positionPrecision?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | null;
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
export type FlowContentSizeOptions = FlowGeometryOptions & {
|
|
240
|
+
/** Settled visual origin when native content growth also shifts the box. */
|
|
241
|
+
position?: Point;
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
export type FlowReplaceGraphOptions = Omit<FlowTransactionOptions, 'history'> & {
|
|
245
|
+
/**
|
|
246
|
+
* `preserve` keeps state addressed to surviving entity ids and prunes stale
|
|
247
|
+
* references. `reset` clears selection and other session-scoped graph state.
|
|
248
|
+
* Defaults to `preserve`.
|
|
249
|
+
*/
|
|
250
|
+
retention?: FlowGraphRetentionPolicy;
|
|
251
|
+
/**
|
|
252
|
+
* `reset` clears controller undo/redo history, `ignore` keeps existing
|
|
253
|
+
* history without recording this replacement, and `record` creates an undo
|
|
254
|
+
* step. Defaults to `reset` for authoritative external synchronization.
|
|
255
|
+
*/
|
|
256
|
+
history?: FlowGraphHistoryPolicy;
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
export type FlowCreateIdContext = {
|
|
260
|
+
kind: 'node' | 'edge';
|
|
261
|
+
reason: 'create' | 'content';
|
|
262
|
+
sourceId?: string;
|
|
263
|
+
attempt: number;
|
|
264
|
+
};
|
|
265
|
+
|
|
266
|
+
export type CreateNodeInput<TNodeData = any> = Omit<
|
|
267
|
+
Parameters<typeof createNode<TNodeData>>[0],
|
|
268
|
+
'id'
|
|
269
|
+
> & { id?: string };
|
|
270
|
+
export type CreateEdgeInput<
|
|
271
|
+
TEdgeData = any,
|
|
272
|
+
TLabelData = any,
|
|
273
|
+
> = Omit<Parameters<typeof createEdge<TEdgeData, TLabelData>>[0], 'id'> & {
|
|
274
|
+
id?: string;
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
export type FlowNodesApi<TNodeData = any> = {
|
|
278
|
+
move: (id: string, position: Point, options?: FlowGeometryOptions) => FlowNode<TNodeData>;
|
|
279
|
+
resize: (id: string, bounds: Rect, options?: FlowGeometryOptions) => FlowNode<TNodeData>;
|
|
280
|
+
setContentSize: (id: string, size: Size, options?: FlowContentSizeOptions) => FlowNode<TNodeData>;
|
|
281
|
+
create: (
|
|
282
|
+
input: CreateNodeInput<TNodeData>,
|
|
283
|
+
options?: FlowTransactionOptions,
|
|
284
|
+
) => FlowNode<TNodeData>;
|
|
285
|
+
delete: (id: string, options?: FlowTransactionOptions) => boolean;
|
|
286
|
+
update: (
|
|
287
|
+
id: string,
|
|
288
|
+
patchOrUpdater: FlowNodePatch | FlowNodeUpdater,
|
|
289
|
+
options?: FlowTransactionOptions,
|
|
290
|
+
) => FlowNode<TNodeData>;
|
|
291
|
+
setData: (
|
|
292
|
+
id: string,
|
|
293
|
+
data:
|
|
294
|
+
| (TNodeData extends object ? Partial<TNodeData> : never)
|
|
295
|
+
| ((current: TNodeData, node: FlowNode<TNodeData>) => TNodeData),
|
|
296
|
+
options?: FlowTransactionOptions,
|
|
297
|
+
) => FlowNode<TNodeData>;
|
|
298
|
+
reparent: (
|
|
299
|
+
id: string,
|
|
300
|
+
parentId: string | null,
|
|
301
|
+
options?: FlowTransactionOptions,
|
|
302
|
+
) => FlowNode<TNodeData>;
|
|
303
|
+
collapse: (id: string, options?: FlowTransactionOptions) => void;
|
|
304
|
+
expand: (id: string, options?: FlowTransactionOptions) => void;
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
export type FlowEdgesApi<TEdgeData = any, TLabelData = any> = {
|
|
308
|
+
create: (
|
|
309
|
+
input: CreateEdgeInput<TEdgeData, TLabelData>,
|
|
310
|
+
options?: FlowTransactionOptions,
|
|
311
|
+
) => FlowEdge<TEdgeData, TLabelData>;
|
|
312
|
+
delete: (id: string, options?: FlowTransactionOptions) => boolean;
|
|
313
|
+
update: (
|
|
314
|
+
id: string,
|
|
315
|
+
patchOrUpdater: FlowEdgePatch | FlowEdgeUpdater,
|
|
316
|
+
options?: FlowTransactionOptions,
|
|
317
|
+
) => FlowEdge<TEdgeData, TLabelData>;
|
|
318
|
+
setData: (
|
|
319
|
+
id: string,
|
|
320
|
+
data:
|
|
321
|
+
| (TEdgeData extends object ? Partial<TEdgeData> : never)
|
|
322
|
+
| ((current: TEdgeData, edge: FlowEdge<TEdgeData, TLabelData>) => TEdgeData),
|
|
323
|
+
options?: FlowTransactionOptions,
|
|
324
|
+
) => FlowEdge<TEdgeData, TLabelData>;
|
|
325
|
+
reconnect: (
|
|
326
|
+
edgeId: string,
|
|
327
|
+
patch: {
|
|
328
|
+
newSourceId?: string;
|
|
329
|
+
newTargetId?: string;
|
|
330
|
+
newSourcePort?: string | null;
|
|
331
|
+
newTargetPort?: string | null;
|
|
332
|
+
},
|
|
333
|
+
options?: FlowTransactionOptions,
|
|
334
|
+
) => FlowEdge<TEdgeData, TLabelData>;
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
export type FlowSelectionAlignment =
|
|
338
|
+
| 'left'
|
|
339
|
+
| 'right'
|
|
340
|
+
| 'top'
|
|
341
|
+
| 'bottom'
|
|
342
|
+
| 'center-x'
|
|
343
|
+
| 'center-y';
|
|
344
|
+
|
|
345
|
+
export type FlowSelectionDistribution = 'horizontal' | 'vertical';
|
|
346
|
+
|
|
347
|
+
export type FlowSelectionDuplicateResult = {
|
|
348
|
+
nodeIds: string[];
|
|
349
|
+
edgeIds: string[];
|
|
350
|
+
idMap: ReadonlyMap<string, string>;
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
export type FlowSelectionApi = {
|
|
354
|
+
set: (ids: string[], mode?: 'single' | 'multi') => void;
|
|
355
|
+
all: (options?: { includeHidden?: boolean }) => void;
|
|
356
|
+
clear: () => void;
|
|
357
|
+
delete: () => boolean;
|
|
358
|
+
duplicate: (options?: { offset?: Point }) => FlowSelectionDuplicateResult | null;
|
|
359
|
+
align: (alignment: FlowSelectionAlignment) => boolean;
|
|
360
|
+
distribute: (distribution: FlowSelectionDistribution) => boolean;
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
export type FlowViewApi<
|
|
364
|
+
TNodeData = any,
|
|
365
|
+
TEdgeData = any,
|
|
366
|
+
TLabelData = any,
|
|
367
|
+
> = {
|
|
368
|
+
getScope: () => FlowViewScope;
|
|
369
|
+
setScope: (
|
|
370
|
+
scope: FlowViewScope,
|
|
371
|
+
options?: { selection?: FlowViewSelectionPolicy },
|
|
372
|
+
) => void;
|
|
373
|
+
getEntities: (options?: {
|
|
374
|
+
includeHidden?: boolean;
|
|
375
|
+
}) => FlowViewEntities<TNodeData, TEdgeData, TLabelData>;
|
|
376
|
+
getBoundaryEndpoints: (
|
|
377
|
+
edgeId: string,
|
|
378
|
+
) => FlowViewBoundaryEndpoints | undefined;
|
|
379
|
+
contains: (id: string, options?: { includeHidden?: boolean }) => boolean;
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
export type FlowViewportApi = {
|
|
383
|
+
set: (
|
|
384
|
+
viewport: FlowStoreContext['viewport'],
|
|
385
|
+
options?: ViewportAnimationOptions,
|
|
386
|
+
) => ViewportAnimationControls;
|
|
387
|
+
panBy: (
|
|
388
|
+
point: Point,
|
|
389
|
+
options?: ViewportAnimationOptions,
|
|
390
|
+
) => ViewportAnimationControls;
|
|
391
|
+
zoomTo: (
|
|
392
|
+
zoom: number,
|
|
393
|
+
center?: Point,
|
|
394
|
+
options?: ViewportAnimationOptions,
|
|
395
|
+
) => ViewportAnimationControls;
|
|
396
|
+
zoomBy: (
|
|
397
|
+
factor: number,
|
|
398
|
+
center?: Point,
|
|
399
|
+
options?: ViewportAnimationOptions,
|
|
400
|
+
) => ViewportAnimationControls;
|
|
401
|
+
fit: (
|
|
402
|
+
options?: FitViewOptions & { includeHidden?: boolean },
|
|
403
|
+
) => ViewportAnimationControls;
|
|
404
|
+
fitBounds: (
|
|
405
|
+
bounds: Rect,
|
|
406
|
+
options?: Omit<FitViewOptions, 'nodes'>,
|
|
407
|
+
) => ViewportAnimationControls;
|
|
408
|
+
centerOn: (
|
|
409
|
+
point: Point,
|
|
410
|
+
options?: Omit<ViewportAnimationOptions, 'center'> & {
|
|
411
|
+
zoom?: number;
|
|
412
|
+
frame?: Rect;
|
|
413
|
+
},
|
|
414
|
+
) => ViewportAnimationControls;
|
|
415
|
+
getFitFrame: () => Readonly<Rect>;
|
|
416
|
+
setFitFrame: (
|
|
417
|
+
frame: Rect | null,
|
|
418
|
+
options?: { preserveCenter?: boolean },
|
|
419
|
+
) => void;
|
|
420
|
+
/** Register a measured screen-space overlay that fit/center commands avoid. */
|
|
421
|
+
registerFitExclusion: (exclusion: FitViewExclusion) => () => void;
|
|
422
|
+
};
|
|
423
|
+
|
|
424
|
+
export type FlowLayoutApi<
|
|
425
|
+
TNodeData = any,
|
|
426
|
+
TEdgeData = any,
|
|
427
|
+
TLabelData = any,
|
|
428
|
+
> = {
|
|
429
|
+
run: (
|
|
430
|
+
layout?: LayoutAlgorithm<TNodeData, TEdgeData, TLabelData>,
|
|
431
|
+
options?: LayoutRunOptions,
|
|
432
|
+
) => Promise<LayoutRunResult>;
|
|
433
|
+
apply: (
|
|
434
|
+
result: LayoutResult,
|
|
435
|
+
options?: LayoutApplyOptions,
|
|
436
|
+
) => LayoutAnimationControls;
|
|
437
|
+
request: (algorithm?: string) => void;
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
export type FlowHistoryApi = {
|
|
441
|
+
undo: () => void;
|
|
442
|
+
redo: () => void;
|
|
443
|
+
canUndo: () => boolean;
|
|
444
|
+
canRedo: () => boolean;
|
|
445
|
+
};
|
|
446
|
+
|
|
447
|
+
export type FlowConnection = {
|
|
448
|
+
edge: FlowEdge;
|
|
449
|
+
source: { nodeId: string; port: string | null };
|
|
450
|
+
target: { nodeId: string; port: string | null };
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
export type FlowConnectionsApi = {
|
|
454
|
+
get: (input: {
|
|
455
|
+
nodeId: string;
|
|
456
|
+
port?: string | null;
|
|
457
|
+
direction?: 'in' | 'out' | 'both';
|
|
458
|
+
}) => FlowConnection[];
|
|
459
|
+
};
|
|
460
|
+
|
|
461
|
+
export type FlowContentApi<
|
|
462
|
+
TNodeData = any,
|
|
463
|
+
TEdgeData = any,
|
|
464
|
+
TLabelData = any,
|
|
465
|
+
> = {
|
|
466
|
+
extract: (targets?: Iterable<string>) => FlowContent<TNodeData, TEdgeData, TLabelData> | null;
|
|
467
|
+
insert: (
|
|
468
|
+
content: unknown,
|
|
469
|
+
options?: { point?: Point; preservePosition?: boolean },
|
|
470
|
+
) => FlowResult<{
|
|
471
|
+
nodeIds: string[];
|
|
472
|
+
edgeIds: string[];
|
|
473
|
+
idMap: ReadonlyMap<string, string>;
|
|
474
|
+
changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData>;
|
|
475
|
+
}>;
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
export type FlowCapabilityCommand =
|
|
479
|
+
| 'edit'
|
|
480
|
+
| 'create'
|
|
481
|
+
| 'move'
|
|
482
|
+
| 'resize'
|
|
483
|
+
| 'connect'
|
|
484
|
+
| 'reconnect'
|
|
485
|
+
| 'reparent'
|
|
486
|
+
| 'delete'
|
|
487
|
+
| 'cut'
|
|
488
|
+
| 'paste'
|
|
489
|
+
| 'undo'
|
|
490
|
+
| 'redo'
|
|
491
|
+
| 'copy'
|
|
492
|
+
| 'export'
|
|
493
|
+
| 'select'
|
|
494
|
+
| 'pan'
|
|
495
|
+
| 'zoom';
|
|
496
|
+
|
|
497
|
+
export type FlowCapabilityResult =
|
|
498
|
+
| { allowed: true }
|
|
499
|
+
| {
|
|
500
|
+
allowed: false;
|
|
501
|
+
reason: { code: 'readonly' | 'policy' | 'entity' | 'empty' | 'history'; command: FlowCapabilityCommand };
|
|
502
|
+
};
|
|
503
|
+
|
|
504
|
+
export type FlowHighlightsApi = {
|
|
505
|
+
set: (kind: string, entries: FlowHighlightEntry[]) => void;
|
|
506
|
+
add: (kind: string, entries: FlowHighlightEntry[]) => void;
|
|
507
|
+
remove: (kind: string, ids: string[]) => void;
|
|
508
|
+
clear: (kind?: string) => void;
|
|
509
|
+
};
|
|
510
|
+
|
|
511
|
+
export type FlowProjectionsApi = {
|
|
512
|
+
get: () => readonly ActiveGraphProjection[];
|
|
513
|
+
set: (projections: readonly ActiveGraphProjection[]) => void;
|
|
514
|
+
add: (projection: ActiveGraphProjection) => void;
|
|
515
|
+
remove: (id: string) => void;
|
|
516
|
+
clear: () => void;
|
|
517
|
+
subscribe: (listener: FlowProjectionListener) => () => void;
|
|
518
|
+
getAttrs: () => ComposedGraphProjectionAttrs;
|
|
519
|
+
};
|
|
520
|
+
|
|
521
|
+
export type FlowConfigureOptions = {
|
|
522
|
+
engine?: Partial<FlowEngineOptions>;
|
|
523
|
+
store?: Partial<FlowStoreOptions>;
|
|
524
|
+
defaultEdgeOptions?: Partial<CreateEdgeInput> | null;
|
|
525
|
+
/**
|
|
526
|
+
* Runtime toggle for auto-creating an edge when a connection gesture ends on a
|
|
527
|
+
* node. See {@link CreateFlowOptions.createEdgeOnConnect}.
|
|
528
|
+
*/
|
|
529
|
+
createEdgeOnConnect?: boolean;
|
|
530
|
+
layout?: LayoutAlgorithm | null;
|
|
531
|
+
historyLimit?: number;
|
|
532
|
+
};
|
|
533
|
+
|
|
534
|
+
export type FlowConfiguration = {
|
|
535
|
+
engine: FlowEngineOptions;
|
|
536
|
+
store: FlowStoreOptions;
|
|
537
|
+
defaultEdgeOptions: Partial<CreateEdgeInput> | null;
|
|
538
|
+
createEdgeOnConnect: boolean;
|
|
539
|
+
layout: LayoutAlgorithm | null;
|
|
540
|
+
historyLimit: number;
|
|
541
|
+
};
|
|
542
|
+
|
|
543
|
+
function immutableConfiguration(
|
|
544
|
+
configuration: FlowConfiguration,
|
|
545
|
+
): Readonly<FlowConfiguration> {
|
|
546
|
+
const seen = new WeakMap<object, unknown>();
|
|
547
|
+
const clone = (value: unknown): unknown => {
|
|
548
|
+
if (!value || typeof value !== 'object') return value;
|
|
549
|
+
const previous = seen.get(value);
|
|
550
|
+
if (previous) return previous;
|
|
551
|
+
if (Array.isArray(value)) {
|
|
552
|
+
const result: unknown[] = [];
|
|
553
|
+
seen.set(value, result);
|
|
554
|
+
for (const entry of value) result.push(clone(entry));
|
|
555
|
+
return Object.freeze(result);
|
|
556
|
+
}
|
|
557
|
+
const prototype = Object.getPrototypeOf(value);
|
|
558
|
+
if (prototype !== Object.prototype && prototype !== null) return value;
|
|
559
|
+
const result: Record<string, unknown> = {};
|
|
560
|
+
seen.set(value, result);
|
|
561
|
+
for (const [key, entry] of Object.entries(value)) result[key] = clone(entry);
|
|
562
|
+
return Object.freeze(result);
|
|
563
|
+
};
|
|
564
|
+
return clone(configuration) as Readonly<FlowConfiguration>;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
export type FlowCommitEvent<
|
|
568
|
+
TNodeData = any,
|
|
569
|
+
TEdgeData = any,
|
|
570
|
+
TLabelData = any,
|
|
571
|
+
> = {
|
|
572
|
+
type: 'commit';
|
|
573
|
+
changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData>;
|
|
574
|
+
origin?: string;
|
|
575
|
+
transactionId?: string;
|
|
576
|
+
revision: number;
|
|
577
|
+
};
|
|
578
|
+
|
|
579
|
+
export type FlowTransactionDraft<
|
|
580
|
+
TNodeData = any,
|
|
581
|
+
TEdgeData = any,
|
|
582
|
+
TLabelData = any,
|
|
583
|
+
> = {
|
|
584
|
+
getNode: (id: string) => FlowNode<TNodeData> | undefined;
|
|
585
|
+
getEdge: (id: string) => FlowEdge<TEdgeData, TLabelData> | undefined;
|
|
586
|
+
/** Intrinsic staged geometry, excluding derived group bounds. */
|
|
587
|
+
getNodeBounds: (id: string) => Rect | undefined;
|
|
588
|
+
nodes: Omit<FlowNodesApi<TNodeData>, 'collapse' | 'expand'>;
|
|
589
|
+
edges: FlowEdgesApi<TEdgeData, TLabelData>;
|
|
590
|
+
};
|
|
591
|
+
|
|
592
|
+
/** Options for creating an owning Flow controller. */
|
|
593
|
+
export interface CreateFlowOptions<
|
|
594
|
+
TNodeData = any,
|
|
595
|
+
TEdgeData = any,
|
|
596
|
+
TLabelData = any,
|
|
597
|
+
> {
|
|
598
|
+
/** Initial graph owned by the controller. */
|
|
599
|
+
graph?: FlowGraph<TNodeData, TEdgeData, TLabelData>;
|
|
600
|
+
/** Construct-only default layout algorithm used by `flow.layout.run()`. */
|
|
601
|
+
layout?: LayoutAlgorithm<TNodeData, TEdgeData, TLabelData> | null;
|
|
602
|
+
/** Store creation options; runtime settings can later change via `flow.configure({ store })`. */
|
|
603
|
+
store?: FlowStoreOptions;
|
|
604
|
+
/** Engine options; runtime-updatable via `flow.configure({ engine })`. */
|
|
605
|
+
engine?: FlowEngineOptions;
|
|
606
|
+
/** Default options merged into controller-created edges; runtime-updatable via `flow.configure`. */
|
|
607
|
+
defaultEdgeOptions?: Partial<CreateEdgeInput<TEdgeData, TLabelData>>;
|
|
608
|
+
/** Initial active visual projections; runtime-updatable via `flow.projections`. */
|
|
609
|
+
projections?: readonly ActiveGraphProjection[];
|
|
610
|
+
/** Optional listener for completed connection gestures. */
|
|
611
|
+
onConnectionEnd?: (event: ConnectionEndedEvent) => void;
|
|
612
|
+
/**
|
|
613
|
+
* When `true`, the controller auto-creates an edge whenever a connection
|
|
614
|
+
* gesture ends on a valid target node (applying {@link CreateFlowOptions.defaultEdgeOptions},
|
|
615
|
+
* and skipping reconnection gestures). Defaults to `false`: `connectionEnded`
|
|
616
|
+
* is then a pure notification (`onConnectionEnd` still fires), leaving edge
|
|
617
|
+
* creation to the consumer via `flow.edges.create(...)`. Runtime-updatable via
|
|
618
|
+
* `flow.configure`.
|
|
619
|
+
*/
|
|
620
|
+
createEdgeOnConnect?: boolean;
|
|
621
|
+
/** Creates opaque entity ids when `create()` is called without an explicit id. */
|
|
622
|
+
createId?: (context: FlowCreateIdContext) => string;
|
|
623
|
+
/** Optional Standard Schema-compatible contracts for application data. */
|
|
624
|
+
dataSchemas?: FlowDataSchemas<TNodeData, TEdgeData, TLabelData>;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* Framework-neutral owner of a Flow graph and its interaction session.
|
|
629
|
+
*
|
|
630
|
+
* Mutations go through the domain APIs (`nodes`, `edges`, `selection`,
|
|
631
|
+
* `viewport`) so validation, history, commit events, and cleanup stay coherent.
|
|
632
|
+
* Call `destroy()` when the controller is no longer used.
|
|
633
|
+
*/
|
|
634
|
+
export interface FlowController<
|
|
635
|
+
TNodeData = any,
|
|
636
|
+
TEdgeData = any,
|
|
637
|
+
TLabelData = any,
|
|
638
|
+
> {
|
|
639
|
+
measurements: FlowMeasurementsApi;
|
|
640
|
+
internals: { store: FlowStore; engine: FlowEngine };
|
|
641
|
+
on: FlowStore['on'] & ((
|
|
642
|
+
type: 'commit',
|
|
643
|
+
listener: (event: FlowCommitEvent<TNodeData, TEdgeData, TLabelData>) => void,
|
|
644
|
+
) => { unsubscribe: () => void }) & ((
|
|
645
|
+
type: 'destroy', listener: (event: { type: 'destroy' }) => void,
|
|
646
|
+
) => { unsubscribe: () => void });
|
|
647
|
+
destroy: () => void;
|
|
648
|
+
beginExternalEdit: (options?: FlowTransactionOptions) => FlowExternalEdit<TNodeData, TEdgeData, TLabelData>;
|
|
649
|
+
subscribeRender: (listener: (event: FlowRenderInvalidation) => void) => () => void;
|
|
650
|
+
|
|
651
|
+
getContext: () => FlowStoreContext;
|
|
652
|
+
getSnapshot: () => FlowStoreContext;
|
|
653
|
+
subscribe: {
|
|
654
|
+
(listener: (context: FlowStoreContext) => void): () => void;
|
|
655
|
+
<TSelected>(
|
|
656
|
+
selector: (context: FlowStoreContext) => TSelected,
|
|
657
|
+
listener: (selected: TSelected, previous: TSelected) => void,
|
|
658
|
+
options?: { equals?: (a: TSelected, b: TSelected) => boolean; emitInitial?: boolean; keys?: readonly (keyof FlowStoreContext)[] },
|
|
659
|
+
): () => void;
|
|
660
|
+
};
|
|
661
|
+
configure: (
|
|
662
|
+
options:
|
|
663
|
+
| FlowConfigureOptions
|
|
664
|
+
| ((current: Readonly<FlowConfiguration>) => FlowConfiguration),
|
|
665
|
+
) => void;
|
|
666
|
+
getConfiguration: () => Readonly<FlowConfiguration>;
|
|
667
|
+
/** Publish changed external router output without changing configuration or history. */
|
|
668
|
+
invalidateRoutes: () => void;
|
|
669
|
+
toJSON: () => FlowSerialized<TNodeData, TEdgeData, TLabelData>;
|
|
670
|
+
load: (data: unknown) => FlowResult<void>;
|
|
671
|
+
replaceGraph: (
|
|
672
|
+
graph: FlowGraph<TNodeData, TEdgeData, TLabelData>,
|
|
673
|
+
options?: FlowReplaceGraphOptions,
|
|
674
|
+
) => FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null;
|
|
675
|
+
transaction: <TValue>(
|
|
676
|
+
callback: (draft: FlowTransactionDraft<TNodeData, TEdgeData, TLabelData>) => TValue,
|
|
677
|
+
options?: FlowTransactionOptions,
|
|
678
|
+
) => { value: TValue; changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null };
|
|
679
|
+
applyChangeSet: (
|
|
680
|
+
changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData>,
|
|
681
|
+
options?: FlowTransactionOptions & { strict?: boolean },
|
|
682
|
+
) => FlowResult<FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null>;
|
|
683
|
+
|
|
684
|
+
getNode: (id: string) => FlowNode<TNodeData> | undefined;
|
|
685
|
+
getEdge: (id: string) => FlowEdge<TEdgeData, TLabelData> | undefined;
|
|
686
|
+
getEntity: (
|
|
687
|
+
id: string,
|
|
688
|
+
) => FlowNode<TNodeData> | FlowEdge<TEdgeData, TLabelData> | undefined;
|
|
689
|
+
getEntityRef: (id: string) => FlowEntityRef | undefined;
|
|
690
|
+
/** @deprecated Use `getEntityRef()`. */
|
|
691
|
+
getAddressable: (id: string) => FlowEntityRef | undefined;
|
|
692
|
+
getOwnerEntity: (
|
|
693
|
+
id: string,
|
|
694
|
+
) => FlowNode<TNodeData> | FlowEdge<TEdgeData, TLabelData> | undefined;
|
|
695
|
+
getBounds: (id: string) => Rect | undefined;
|
|
696
|
+
|
|
697
|
+
screenToCanvas: (point: Point) => Point;
|
|
698
|
+
canvasToScreen: (point: Point) => Point;
|
|
699
|
+
getAllEdgePaths: (options?: EdgePathOptions) => Map<string, EdgePathData>;
|
|
700
|
+
getConnectionCandidate: (
|
|
701
|
+
pointer: Point,
|
|
702
|
+
options?: ConnectionCandidateOptions,
|
|
703
|
+
) => ConnectionCandidate | null;
|
|
704
|
+
getGraphBounds: () => Rect;
|
|
705
|
+
getIncomers: (nodeId: string) => FlowNode[];
|
|
706
|
+
getOutgoers: (nodeId: string) => FlowNode[];
|
|
707
|
+
getConnectedEdges: (nodeIds: Iterable<string>) => FlowEdge[];
|
|
708
|
+
getNeighbors: (nodeId: string) => FlowNode[];
|
|
709
|
+
getSelectionBounds: () => Rect | null;
|
|
710
|
+
getRenderableEntities: (
|
|
711
|
+
options?: RenderableEntitiesOptions,
|
|
712
|
+
) => { nodes: FlowNode[]; edges: FlowEdge[] };
|
|
713
|
+
getEntityOrder: (
|
|
714
|
+
options?: EntityOrderOptions,
|
|
715
|
+
) => { nodes: FlowNode[]; edges: FlowEdge[] };
|
|
716
|
+
check: (command: FlowCapabilityCommand, input?: { id?: string }) => FlowCapabilityResult;
|
|
717
|
+
can: (command: FlowCapabilityCommand, input?: { id?: string }) => boolean;
|
|
718
|
+
mode: { get: () => string; set: (mode: string) => void };
|
|
719
|
+
|
|
720
|
+
nodes: FlowNodesApi<TNodeData>;
|
|
721
|
+
edges: FlowEdgesApi<TEdgeData, TLabelData>;
|
|
722
|
+
selection: FlowSelectionApi;
|
|
723
|
+
view: FlowViewApi<TNodeData, TEdgeData, TLabelData>;
|
|
724
|
+
viewport: FlowViewportApi;
|
|
725
|
+
layout: FlowLayoutApi<TNodeData, TEdgeData, TLabelData>;
|
|
726
|
+
history: FlowHistoryApi;
|
|
727
|
+
highlights: FlowHighlightsApi;
|
|
728
|
+
projections: FlowProjectionsApi;
|
|
729
|
+
connections: FlowConnectionsApi;
|
|
730
|
+
content: FlowContentApi<TNodeData, TEdgeData, TLabelData>;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/** Final layout positions align to whole CSS pixels. */
|
|
734
|
+
function roundLayoutPosition(value: number): number {
|
|
735
|
+
const rounded = Math.round(value);
|
|
736
|
+
return rounded === 0 ? 0 : rounded;
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
function roundLayoutPoint(point: Point): Point {
|
|
740
|
+
return { x: roundLayoutPosition(point.x), y: roundLayoutPosition(point.y) };
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/**
|
|
744
|
+
* Create an owning Flow controller from an optional initial graph.
|
|
745
|
+
*
|
|
746
|
+
* The input graph is validated and cloned. Adapters should subscribe to this
|
|
747
|
+
* controller and delegate behavior to its APIs instead of reimplementing graph
|
|
748
|
+
* or viewport policy.
|
|
749
|
+
*/
|
|
750
|
+
export function createFlow<
|
|
751
|
+
TNodeData = any,
|
|
752
|
+
TEdgeData = any,
|
|
753
|
+
TLabelData = any,
|
|
754
|
+
>(
|
|
755
|
+
options: CreateFlowOptions<TNodeData, TEdgeData, TLabelData> = {},
|
|
756
|
+
): FlowController<TNodeData, TEdgeData, TLabelData> {
|
|
757
|
+
const initialGraph = validateAndCloneGraph(
|
|
758
|
+
options.graph ?? { nodes: [], edges: [], direction: 'down' },
|
|
759
|
+
options.dataSchemas,
|
|
760
|
+
);
|
|
761
|
+
const store = createFlowStore(initialGraph, {
|
|
762
|
+
...options.store,
|
|
763
|
+
appearances: options.engine?.appearances ?? options.store?.appearances,
|
|
764
|
+
// Keep the store's movement planning in sync with the engine's label
|
|
765
|
+
// anchor default (engine owns label geometry; the store needs it to decide
|
|
766
|
+
// which labels auto-follow their endpoints vs. must be carried along).
|
|
767
|
+
labelAnchor: options.store?.labelAnchor ?? options.engine?.labelAnchor,
|
|
768
|
+
});
|
|
769
|
+
const engine = createFlowEngine(store, options.engine);
|
|
770
|
+
const cleanup = new Set<() => void>();
|
|
771
|
+
let projections = [...(options.projections ?? [])];
|
|
772
|
+
let configuration: FlowConfiguration = {
|
|
773
|
+
engine: { ...(options.engine ?? {}) },
|
|
774
|
+
store: { ...(options.store ?? {}) },
|
|
775
|
+
defaultEdgeOptions: options.defaultEdgeOptions
|
|
776
|
+
? { ...options.defaultEdgeOptions }
|
|
777
|
+
: null,
|
|
778
|
+
createEdgeOnConnect: options.createEdgeOnConnect ?? false,
|
|
779
|
+
layout: options.layout ?? null,
|
|
780
|
+
historyLimit: options.store?.historyLimit ?? 100,
|
|
781
|
+
};
|
|
782
|
+
let defaultEdgeOptions = options.defaultEdgeOptions
|
|
783
|
+
? { ...options.defaultEdgeOptions }
|
|
784
|
+
: undefined;
|
|
785
|
+
let createEdgeOnConnect = options.createEdgeOnConnect ?? false;
|
|
786
|
+
const projectionListeners = new Set<FlowProjectionListener>();
|
|
787
|
+
let activeViewportAnimation: ViewportAnimationControls | null = null;
|
|
788
|
+
const fitExclusions = new Set<FitViewExclusion>();
|
|
789
|
+
const pendingInternalViewportWrites: Viewport[] = [];
|
|
790
|
+
let lastViewport = store.getSnapshot().context.viewport;
|
|
791
|
+
let graphRevision = 0;
|
|
792
|
+
let lastCommittedGraph = initialGraph;
|
|
793
|
+
let latestLayoutRun = 0;
|
|
794
|
+
let activeLayoutAbort: { abort: () => void } | null = null;
|
|
795
|
+
let activeLayoutAnimation: {
|
|
796
|
+
controls: LayoutAnimationControls;
|
|
797
|
+
stop: (clear: boolean) => void;
|
|
798
|
+
} | null = null;
|
|
799
|
+
const commitListeners = new Set<
|
|
800
|
+
(event: FlowCommitEvent<TNodeData, TEdgeData, TLabelData>) => void
|
|
801
|
+
>();
|
|
802
|
+
|
|
803
|
+
const viewportSubscription = store.subscribe((snapshot) => {
|
|
804
|
+
const nextViewport = snapshot.context.viewport;
|
|
805
|
+
if (nextViewport === lastViewport) return;
|
|
806
|
+
lastViewport = nextViewport;
|
|
807
|
+
const internalIndex = pendingInternalViewportWrites.findIndex(
|
|
808
|
+
(viewport) =>
|
|
809
|
+
viewport.x === nextViewport.x &&
|
|
810
|
+
viewport.y === nextViewport.y &&
|
|
811
|
+
viewport.zoom === nextViewport.zoom,
|
|
812
|
+
);
|
|
813
|
+
if (internalIndex >= 0) {
|
|
814
|
+
pendingInternalViewportWrites.splice(0, internalIndex + 1);
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
pendingInternalViewportWrites.length = 0;
|
|
818
|
+
if (activeViewportAnimation) {
|
|
819
|
+
activeViewportAnimation.cancel();
|
|
820
|
+
activeViewportAnimation = null;
|
|
821
|
+
}
|
|
822
|
+
});
|
|
823
|
+
cleanup.add(() => viewportSubscription.unsubscribe());
|
|
824
|
+
|
|
825
|
+
const graphEventSubscription = store.on('graphChanged', (event) => {
|
|
826
|
+
if (activeLayoutAnimation && event.event.origin !== 'layout') {
|
|
827
|
+
activeLayoutAnimation.stop(true);
|
|
828
|
+
}
|
|
829
|
+
const metadata = {
|
|
830
|
+
origin: typeof event.event.origin === 'string' ? event.event.origin : event.event.type,
|
|
831
|
+
transactionId:
|
|
832
|
+
typeof event.event.transactionId === 'string'
|
|
833
|
+
? event.event.transactionId
|
|
834
|
+
: undefined,
|
|
835
|
+
};
|
|
836
|
+
const nextGraph = event.graph as FlowGraph<
|
|
837
|
+
TNodeData,
|
|
838
|
+
TEdgeData,
|
|
839
|
+
TLabelData
|
|
840
|
+
>;
|
|
841
|
+
const nextRevision = graphRevision + 1;
|
|
842
|
+
const changeSet = createFlowChangeSet(lastCommittedGraph, nextGraph, {
|
|
843
|
+
revision: nextRevision,
|
|
844
|
+
...metadata,
|
|
845
|
+
});
|
|
846
|
+
lastCommittedGraph = nextGraph;
|
|
847
|
+
if (!changeSet) return;
|
|
848
|
+
graphRevision = nextRevision;
|
|
849
|
+
const commitEvent: FlowCommitEvent<TNodeData, TEdgeData, TLabelData> = {
|
|
850
|
+
type: 'commit',
|
|
851
|
+
changeSet,
|
|
852
|
+
revision: graphRevision,
|
|
853
|
+
origin: changeSet.origin,
|
|
854
|
+
transactionId: changeSet.transactionId,
|
|
855
|
+
};
|
|
856
|
+
for (const listener of commitListeners) listener(commitEvent);
|
|
857
|
+
});
|
|
858
|
+
cleanup.add(() => graphEventSubscription.unsubscribe());
|
|
859
|
+
|
|
860
|
+
const connectionSubscription = store.on('connectionEnded', (event) => {
|
|
861
|
+
options.onConnectionEnd?.(event);
|
|
862
|
+
if (!createEdgeOnConnect) return;
|
|
863
|
+
if (event.reconnectedEdgeId) return;
|
|
864
|
+
if (event.target.kind !== 'node') return;
|
|
865
|
+
if (event.connection.isValid === false) return;
|
|
866
|
+
edges.create(normalizeConnection({
|
|
867
|
+
sourceId: event.source.nodeId,
|
|
868
|
+
targetId: event.target.nodeId,
|
|
869
|
+
sourcePort: event.source.port,
|
|
870
|
+
targetPort: event.target.port,
|
|
871
|
+
}, store.getSnapshot().context.graph) as CreateEdgeInput<TEdgeData, TLabelData>);
|
|
872
|
+
});
|
|
873
|
+
cleanup.add(() => connectionSubscription.unsubscribe());
|
|
874
|
+
|
|
875
|
+
let destroyed = false;
|
|
876
|
+
const destroyListeners = new Set<(event: { type: 'destroy' }) => void>();
|
|
877
|
+
function destroy() {
|
|
878
|
+
if (destroyed) return;
|
|
879
|
+
destroyed = true;
|
|
880
|
+
for (const listener of destroyListeners) listener({ type: 'destroy' });
|
|
881
|
+
destroyListeners.clear();
|
|
882
|
+
store.trigger.cancelConnection();
|
|
883
|
+
activeLayoutAbort?.abort();
|
|
884
|
+
activeLayoutAnimation?.stop(true);
|
|
885
|
+
activeViewportAnimation?.cancel();
|
|
886
|
+
activeViewportAnimation = null;
|
|
887
|
+
for (const dispose of cleanup) {
|
|
888
|
+
dispose();
|
|
889
|
+
}
|
|
890
|
+
cleanup.clear();
|
|
891
|
+
fitExclusions.clear();
|
|
892
|
+
projectionListeners.clear();
|
|
893
|
+
commitListeners.clear();
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
function notifyProjectionListeners() {
|
|
897
|
+
const snapshot = getProjections();
|
|
898
|
+
for (const listener of projectionListeners) {
|
|
899
|
+
listener(snapshot);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
function getProjections(): readonly ActiveGraphProjection[] {
|
|
904
|
+
return projections;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
function setProjections(next: readonly ActiveGraphProjection[]) {
|
|
908
|
+
projections = [...next];
|
|
909
|
+
notifyProjectionListeners();
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
function normalizeLayoutResult(
|
|
913
|
+
result: LayoutResult | LayoutPositions,
|
|
914
|
+
): LayoutResult {
|
|
915
|
+
const value = result instanceof Map ? { positions: result } : result;
|
|
916
|
+
if (!value || !(value.positions instanceof Map)) {
|
|
917
|
+
throw new TypeError('Layout result positions must be a Map.');
|
|
918
|
+
}
|
|
919
|
+
const points = (input: ReadonlyMap<string, Point> | undefined) =>
|
|
920
|
+
input
|
|
921
|
+
? new Map(
|
|
922
|
+
[...input].map(([id, point]) => [id, { x: point.x, y: point.y }]),
|
|
923
|
+
)
|
|
924
|
+
: undefined;
|
|
925
|
+
const sizes = (input: ReadonlyMap<string, Size> | undefined) =>
|
|
926
|
+
input
|
|
927
|
+
? new Map(
|
|
928
|
+
[...input].map(([id, size]) => [
|
|
929
|
+
id,
|
|
930
|
+
{ width: size.width, height: size.height },
|
|
931
|
+
]),
|
|
932
|
+
)
|
|
933
|
+
: undefined;
|
|
934
|
+
const rects = (input: ReadonlyMap<string, Rect> | undefined) =>
|
|
935
|
+
input
|
|
936
|
+
? new Map(
|
|
937
|
+
[...input].map(([id, rect]) => [
|
|
938
|
+
id,
|
|
939
|
+
{
|
|
940
|
+
x: rect.x,
|
|
941
|
+
y: rect.y,
|
|
942
|
+
width: rect.width,
|
|
943
|
+
height: rect.height,
|
|
944
|
+
},
|
|
945
|
+
]),
|
|
946
|
+
)
|
|
947
|
+
: undefined;
|
|
948
|
+
return {
|
|
949
|
+
positions: points(value.positions)!,
|
|
950
|
+
...(value.nodeSizes ? { nodeSizes: sizes(value.nodeSizes) } : {}),
|
|
951
|
+
...(value.nodeBounds ? { nodeBounds: rects(value.nodeBounds) } : {}),
|
|
952
|
+
...(value.edgeLabelPositions
|
|
953
|
+
? { edgeLabelPositions: points(value.edgeLabelPositions) }
|
|
954
|
+
: {}),
|
|
955
|
+
...(value.edgeLabelBounds
|
|
956
|
+
? { edgeLabelBounds: rects(value.edgeLabelBounds) }
|
|
957
|
+
: {}),
|
|
958
|
+
...(value.edgeRoutes
|
|
959
|
+
? {
|
|
960
|
+
edgeRoutes: new Map(
|
|
961
|
+
[...value.edgeRoutes].map(([id, route]): [string, LayoutEdgeRoute] => {
|
|
962
|
+
if (hasAuthoritativeLayoutPoints(route)) {
|
|
963
|
+
return [
|
|
964
|
+
id,
|
|
965
|
+
{
|
|
966
|
+
points: route.points.map((point) => ({
|
|
967
|
+
x: point.x,
|
|
968
|
+
y: point.y,
|
|
969
|
+
})),
|
|
970
|
+
...(route.routing ? { routing: route.routing } : {}),
|
|
971
|
+
},
|
|
972
|
+
];
|
|
973
|
+
}
|
|
974
|
+
return [
|
|
975
|
+
id,
|
|
976
|
+
{
|
|
977
|
+
waypoints: layoutWaypoints(route).map((point) => ({
|
|
978
|
+
x: point.x,
|
|
979
|
+
y: point.y,
|
|
980
|
+
})),
|
|
981
|
+
},
|
|
982
|
+
];
|
|
983
|
+
}),
|
|
984
|
+
),
|
|
985
|
+
}
|
|
986
|
+
: {}),
|
|
987
|
+
...(value.diagnostics
|
|
988
|
+
? { diagnostics: value.diagnostics.map((entry) => ({ ...entry })) }
|
|
989
|
+
: {}),
|
|
990
|
+
...(value.quality
|
|
991
|
+
? { quality: cloneJsonSafe(value.quality, '$.layout.quality') }
|
|
992
|
+
: {}),
|
|
993
|
+
...(value.metadata
|
|
994
|
+
? { metadata: cloneJsonSafe(value.metadata, '$.layout.metadata') }
|
|
995
|
+
: {}),
|
|
996
|
+
...(value.source !== undefined ? { source: value.source } : {}),
|
|
997
|
+
...(value.overrideFixedEntityIds
|
|
998
|
+
? { overrideFixedEntityIds: new Set(value.overrideFixedEntityIds) }
|
|
999
|
+
: {}),
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
function immutableLayoutInput<T>(value: T): T {
|
|
1004
|
+
const seen = new WeakSet<object>();
|
|
1005
|
+
const freeze = (entry: unknown): unknown => {
|
|
1006
|
+
if (!entry || typeof entry !== 'object' || seen.has(entry)) return entry;
|
|
1007
|
+
seen.add(entry);
|
|
1008
|
+
if (Array.isArray(entry)) {
|
|
1009
|
+
for (const item of entry) freeze(item);
|
|
1010
|
+
} else {
|
|
1011
|
+
for (const item of Object.values(entry)) freeze(item);
|
|
1012
|
+
}
|
|
1013
|
+
return Object.freeze(entry);
|
|
1014
|
+
};
|
|
1015
|
+
return freeze(value) as T;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
function immutableLayoutSet(
|
|
1019
|
+
values: ReadonlySet<string> | undefined,
|
|
1020
|
+
): ReadonlySet<string> | undefined {
|
|
1021
|
+
if (!values) return undefined;
|
|
1022
|
+
const target = new Set(values);
|
|
1023
|
+
return new Proxy(target, {
|
|
1024
|
+
get(set, property) {
|
|
1025
|
+
if (property === 'add' || property === 'delete' || property === 'clear') {
|
|
1026
|
+
return () => {
|
|
1027
|
+
throw new TypeError('Layout option sets are readonly.');
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
const value = Reflect.get(set, property, set);
|
|
1031
|
+
return typeof value === 'function' ? value.bind(set) : value;
|
|
1032
|
+
},
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
function immutablePreviousLayoutResult(
|
|
1037
|
+
result: LayoutResult | null | undefined,
|
|
1038
|
+
): LayoutResult | null | undefined {
|
|
1039
|
+
if (result == null) return result;
|
|
1040
|
+
const cloned = normalizeLayoutResult(result);
|
|
1041
|
+
const readonlyMap = <TValue>(map: ReadonlyMap<string, TValue>) =>
|
|
1042
|
+
new Proxy(new Map(map), {
|
|
1043
|
+
get(target, property) {
|
|
1044
|
+
if (property === 'set' || property === 'delete' || property === 'clear') {
|
|
1045
|
+
return () => {
|
|
1046
|
+
throw new TypeError('Previous layout result is readonly.');
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
const value = Reflect.get(target, property, target);
|
|
1050
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
1051
|
+
},
|
|
1052
|
+
}) as ReadonlyMap<string, TValue>;
|
|
1053
|
+
return Object.freeze({
|
|
1054
|
+
...cloned,
|
|
1055
|
+
positions: readonlyMap(cloned.positions),
|
|
1056
|
+
...(cloned.nodeSizes
|
|
1057
|
+
? { nodeSizes: readonlyMap(cloned.nodeSizes) }
|
|
1058
|
+
: {}),
|
|
1059
|
+
...(cloned.nodeBounds
|
|
1060
|
+
? { nodeBounds: readonlyMap(cloned.nodeBounds) }
|
|
1061
|
+
: {}),
|
|
1062
|
+
...(cloned.edgeLabelPositions
|
|
1063
|
+
? { edgeLabelPositions: readonlyMap(cloned.edgeLabelPositions) }
|
|
1064
|
+
: {}),
|
|
1065
|
+
...(cloned.edgeLabelBounds
|
|
1066
|
+
? { edgeLabelBounds: readonlyMap(cloned.edgeLabelBounds) }
|
|
1067
|
+
: {}),
|
|
1068
|
+
...(cloned.edgeRoutes
|
|
1069
|
+
? { edgeRoutes: readonlyMap(cloned.edgeRoutes) }
|
|
1070
|
+
: {}),
|
|
1071
|
+
...(cloned.overrideFixedEntityIds
|
|
1072
|
+
? {
|
|
1073
|
+
overrideFixedEntityIds: immutableLayoutSet(
|
|
1074
|
+
cloned.overrideFixedEntityIds,
|
|
1075
|
+
),
|
|
1076
|
+
}
|
|
1077
|
+
: {}),
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
function configure(
|
|
1082
|
+
update:
|
|
1083
|
+
| FlowConfigureOptions
|
|
1084
|
+
| ((current: Readonly<FlowConfiguration>) => FlowConfiguration),
|
|
1085
|
+
): void {
|
|
1086
|
+
const requested =
|
|
1087
|
+
typeof update === 'function'
|
|
1088
|
+
? update(immutableConfiguration(configuration))
|
|
1089
|
+
: update;
|
|
1090
|
+
const replace = typeof update === 'function';
|
|
1091
|
+
const historyLimit =
|
|
1092
|
+
requested.historyLimit ?? requested.store?.historyLimit;
|
|
1093
|
+
if (
|
|
1094
|
+
historyLimit !== undefined &&
|
|
1095
|
+
historyLimit !== configuration.historyLimit
|
|
1096
|
+
) {
|
|
1097
|
+
throw new TypeError(
|
|
1098
|
+
'flow.configure(): historyLimit cannot be changed after creation.',
|
|
1099
|
+
);
|
|
1100
|
+
}
|
|
1101
|
+
const next = historyLimit === undefined
|
|
1102
|
+
? requested
|
|
1103
|
+
: {
|
|
1104
|
+
...requested,
|
|
1105
|
+
historyLimit,
|
|
1106
|
+
store: { ...requested.store, historyLimit },
|
|
1107
|
+
};
|
|
1108
|
+
if (replace) {
|
|
1109
|
+
for (const key of [
|
|
1110
|
+
'engine',
|
|
1111
|
+
'store',
|
|
1112
|
+
'defaultEdgeOptions',
|
|
1113
|
+
'createEdgeOnConnect',
|
|
1114
|
+
'layout',
|
|
1115
|
+
'historyLimit',
|
|
1116
|
+
] as const) {
|
|
1117
|
+
if (!(key in next)) {
|
|
1118
|
+
throw new TypeError(`flow.configure() replacement is missing "${key}"`);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
if (next.engine) {
|
|
1123
|
+
engine.setOptions(
|
|
1124
|
+
replace ? next.engine : { ...configuration.engine, ...next.engine },
|
|
1125
|
+
replace,
|
|
1126
|
+
);
|
|
1127
|
+
}
|
|
1128
|
+
// `undefined` means "leave as-is" (StatelyFlow always passes the key, often
|
|
1129
|
+
// undefined, and must not clobber options set at instance creation); pass
|
|
1130
|
+
// `null` to explicitly clear.
|
|
1131
|
+
if (next.defaultEdgeOptions !== undefined) {
|
|
1132
|
+
defaultEdgeOptions =
|
|
1133
|
+
next.defaultEdgeOptions === null
|
|
1134
|
+
? undefined
|
|
1135
|
+
: { ...next.defaultEdgeOptions };
|
|
1136
|
+
}
|
|
1137
|
+
if (next.createEdgeOnConnect !== undefined) {
|
|
1138
|
+
createEdgeOnConnect = next.createEdgeOnConnect;
|
|
1139
|
+
}
|
|
1140
|
+
configuration = replace
|
|
1141
|
+
? {
|
|
1142
|
+
...(next as FlowConfiguration),
|
|
1143
|
+
engine: { ...next.engine },
|
|
1144
|
+
store: { ...next.store },
|
|
1145
|
+
defaultEdgeOptions: next.defaultEdgeOptions
|
|
1146
|
+
? { ...next.defaultEdgeOptions }
|
|
1147
|
+
: null,
|
|
1148
|
+
}
|
|
1149
|
+
: {
|
|
1150
|
+
...configuration,
|
|
1151
|
+
...next,
|
|
1152
|
+
engine: { ...configuration.engine, ...next.engine },
|
|
1153
|
+
store: { ...configuration.store, ...next.store },
|
|
1154
|
+
defaultEdgeOptions:
|
|
1155
|
+
next.defaultEdgeOptions === undefined
|
|
1156
|
+
? configuration.defaultEdgeOptions
|
|
1157
|
+
: next.defaultEdgeOptions === null
|
|
1158
|
+
? null
|
|
1159
|
+
: { ...next.defaultEdgeOptions },
|
|
1160
|
+
};
|
|
1161
|
+
const storeSettings: Partial<FlowStoreOptions> = {
|
|
1162
|
+
...next.store,
|
|
1163
|
+
...(next.engine?.labelAnchor !== undefined && next.store?.labelAnchor === undefined
|
|
1164
|
+
? { labelAnchor: next.engine.labelAnchor }
|
|
1165
|
+
: {}),
|
|
1166
|
+
};
|
|
1167
|
+
store.trigger.configure(storeSettings);
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
function toJSON(): FlowSerialized<TNodeData, TEdgeData, TLabelData> {
|
|
1171
|
+
const context = store.getSnapshot().context;
|
|
1172
|
+
return {
|
|
1173
|
+
version: 1,
|
|
1174
|
+
graph: serializeFlowGraph(
|
|
1175
|
+
context.graph as FlowGraph<TNodeData, TEdgeData, TLabelData>,
|
|
1176
|
+
),
|
|
1177
|
+
viewport: { ...context.viewport },
|
|
1178
|
+
collapsedNodeIds: [...context.collapsedNodeIds],
|
|
1179
|
+
...(currentDataVersions(options.dataSchemas)
|
|
1180
|
+
? { dataVersions: currentDataVersions(options.dataSchemas) }
|
|
1181
|
+
: {}),
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
function load(data: unknown): FlowResult<void> {
|
|
1186
|
+
try {
|
|
1187
|
+
const parsed = parseFlowSerialized<TNodeData, TEdgeData, TLabelData>(
|
|
1188
|
+
data,
|
|
1189
|
+
options.dataSchemas,
|
|
1190
|
+
);
|
|
1191
|
+
cancelViewportAnimation();
|
|
1192
|
+
store.trigger.loadDocument({
|
|
1193
|
+
graph: parsed.graph,
|
|
1194
|
+
collapsedNodeIds: parsed.collapsedNodeIds ?? [],
|
|
1195
|
+
viewport: parsed.viewport,
|
|
1196
|
+
origin: 'load',
|
|
1197
|
+
});
|
|
1198
|
+
return { ok: true, value: undefined };
|
|
1199
|
+
} catch (error) {
|
|
1200
|
+
return {
|
|
1201
|
+
ok: false,
|
|
1202
|
+
error:
|
|
1203
|
+
error instanceof FlowGraphValidationError
|
|
1204
|
+
? error
|
|
1205
|
+
: new FlowGraphValidationError([
|
|
1206
|
+
{ code: 'load_failed', path: '$', message: String(error) },
|
|
1207
|
+
]),
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
function resolvedLayoutAnimation(): LayoutAnimationControls {
|
|
1213
|
+
return { cancel: () => {}, done: Promise.resolve() };
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
function startLayoutAnimation(
|
|
1217
|
+
initialOffsets: Map<string, Point>,
|
|
1218
|
+
animation: LayoutAnimationOptions | undefined,
|
|
1219
|
+
): LayoutAnimationControls {
|
|
1220
|
+
const duration = animation?.duration ?? 0;
|
|
1221
|
+
if (
|
|
1222
|
+
!Number.isFinite(duration) ||
|
|
1223
|
+
duration <= 0 ||
|
|
1224
|
+
initialOffsets.size === 0
|
|
1225
|
+
) {
|
|
1226
|
+
store.trigger.clearLayoutAnimation();
|
|
1227
|
+
return resolvedLayoutAnimation();
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
const requestFrame = (callback: (time: number) => void): number => {
|
|
1231
|
+
if (typeof requestAnimationFrame === 'function') {
|
|
1232
|
+
return requestAnimationFrame(callback);
|
|
1233
|
+
}
|
|
1234
|
+
return setTimeout(() => callback(Date.now()), 16) as unknown as number;
|
|
1235
|
+
};
|
|
1236
|
+
const cancelFrame = (id: number) => {
|
|
1237
|
+
if (typeof cancelAnimationFrame === 'function') {
|
|
1238
|
+
cancelAnimationFrame(id);
|
|
1239
|
+
} else {
|
|
1240
|
+
clearTimeout(id);
|
|
1241
|
+
}
|
|
1242
|
+
};
|
|
1243
|
+
const easing = animation?.easing ?? ((t: number) =>
|
|
1244
|
+
t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
|
|
1245
|
+
let frame: number | null = null;
|
|
1246
|
+
let startTime: number | null = null;
|
|
1247
|
+
let stopped = false;
|
|
1248
|
+
let resolveDone = () => {};
|
|
1249
|
+
const done = new Promise<void>((resolve) => {
|
|
1250
|
+
resolveDone = resolve;
|
|
1251
|
+
});
|
|
1252
|
+
const controls: LayoutAnimationControls = {
|
|
1253
|
+
cancel: () => session.stop(true),
|
|
1254
|
+
done,
|
|
1255
|
+
};
|
|
1256
|
+
const session = {
|
|
1257
|
+
controls,
|
|
1258
|
+
stop: (clear: boolean) => {
|
|
1259
|
+
if (stopped) return;
|
|
1260
|
+
stopped = true;
|
|
1261
|
+
if (frame !== null) cancelFrame(frame);
|
|
1262
|
+
frame = null;
|
|
1263
|
+
if (clear) store.trigger.clearLayoutAnimation();
|
|
1264
|
+
if (activeLayoutAnimation === session) activeLayoutAnimation = null;
|
|
1265
|
+
resolveDone();
|
|
1266
|
+
},
|
|
1267
|
+
};
|
|
1268
|
+
const step = (time: number) => {
|
|
1269
|
+
if (stopped) return;
|
|
1270
|
+
if (startTime === null) startTime = time;
|
|
1271
|
+
const progress = Math.min(1, (time - startTime) / duration);
|
|
1272
|
+
if (progress >= 1) {
|
|
1273
|
+
session.stop(true);
|
|
1274
|
+
return;
|
|
1275
|
+
}
|
|
1276
|
+
const eased = easing(progress);
|
|
1277
|
+
const remaining = 1 - (Number.isFinite(eased) ? eased : progress);
|
|
1278
|
+
const offsets = new Map<string, Point>();
|
|
1279
|
+
for (const [id, offset] of initialOffsets) {
|
|
1280
|
+
const next = { x: offset.x * remaining, y: offset.y * remaining };
|
|
1281
|
+
if (Math.abs(next.x) > 1e-6 || Math.abs(next.y) > 1e-6) {
|
|
1282
|
+
offsets.set(id, next);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
store.trigger.setLayoutAnimationOffsets({ offsets });
|
|
1286
|
+
frame = requestFrame(step);
|
|
1287
|
+
};
|
|
1288
|
+
activeLayoutAnimation = session;
|
|
1289
|
+
frame = requestFrame(step);
|
|
1290
|
+
return controls;
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
function applyLayout(
|
|
1294
|
+
input: LayoutResult,
|
|
1295
|
+
applyOptions: LayoutApplyOptions = {},
|
|
1296
|
+
): LayoutAnimationControls {
|
|
1297
|
+
const result = normalizeLayoutResult(input);
|
|
1298
|
+
const graph = currentGraph();
|
|
1299
|
+
const nodeIds = new Set(graph.nodes.map((node) => node.id));
|
|
1300
|
+
const edgeIds = new Set(graph.edges.map((edge) => edge.id));
|
|
1301
|
+
const entityIds = new Set([...nodeIds, ...edgeIds]);
|
|
1302
|
+
const edgesWithLabels = new Set(
|
|
1303
|
+
graph.edges.filter((edge) => edge.label).map((edge) => edge.id),
|
|
1304
|
+
);
|
|
1305
|
+
const issues: Array<{ code: string; path: string; message: string }> = [];
|
|
1306
|
+
const finitePoint = (point: Point, path: string) => {
|
|
1307
|
+
if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {
|
|
1308
|
+
issues.push({
|
|
1309
|
+
code: 'invalid_layout_geometry',
|
|
1310
|
+
path,
|
|
1311
|
+
message: 'expected finite x/y',
|
|
1312
|
+
});
|
|
1313
|
+
}
|
|
1314
|
+
};
|
|
1315
|
+
const finiteSize = (size: Size, path: string) => {
|
|
1316
|
+
if (
|
|
1317
|
+
!Number.isFinite(size.width) ||
|
|
1318
|
+
!Number.isFinite(size.height) ||
|
|
1319
|
+
size.width < 0 ||
|
|
1320
|
+
size.height < 0
|
|
1321
|
+
) {
|
|
1322
|
+
issues.push({
|
|
1323
|
+
code: 'invalid_layout_geometry',
|
|
1324
|
+
path,
|
|
1325
|
+
message: 'expected non-negative finite width/height',
|
|
1326
|
+
});
|
|
1327
|
+
}
|
|
1328
|
+
};
|
|
1329
|
+
const validateMap = <TValue>(
|
|
1330
|
+
field: string,
|
|
1331
|
+
map: ReadonlyMap<string, TValue> | undefined,
|
|
1332
|
+
ids: ReadonlySet<string>,
|
|
1333
|
+
validate: (value: TValue, path: string) => void,
|
|
1334
|
+
) => {
|
|
1335
|
+
if (!map) return;
|
|
1336
|
+
for (const [id, value] of [...map].sort(([a], [b]) => a.localeCompare(b))) {
|
|
1337
|
+
const path = `$.layout.${field}.${id}`;
|
|
1338
|
+
if (!ids.has(id)) {
|
|
1339
|
+
issues.push({
|
|
1340
|
+
code: 'unknown_layout_entity',
|
|
1341
|
+
path,
|
|
1342
|
+
message: `unknown entity id "${id}"`,
|
|
1343
|
+
});
|
|
1344
|
+
continue;
|
|
1345
|
+
}
|
|
1346
|
+
validate(value, path);
|
|
1347
|
+
}
|
|
1348
|
+
};
|
|
1349
|
+
validateMap('positions', result.positions, nodeIds, finitePoint);
|
|
1350
|
+
validateMap('nodeSizes', result.nodeSizes, nodeIds, finiteSize);
|
|
1351
|
+
validateMap('nodeBounds', result.nodeBounds, nodeIds, (rect, path) => {
|
|
1352
|
+
finitePoint(rect, path);
|
|
1353
|
+
finiteSize(rect, path);
|
|
1354
|
+
});
|
|
1355
|
+
validateMap(
|
|
1356
|
+
'edgeLabelPositions',
|
|
1357
|
+
result.edgeLabelPositions,
|
|
1358
|
+
edgesWithLabels,
|
|
1359
|
+
finitePoint,
|
|
1360
|
+
);
|
|
1361
|
+
validateMap(
|
|
1362
|
+
'edgeLabelBounds',
|
|
1363
|
+
result.edgeLabelBounds,
|
|
1364
|
+
edgesWithLabels,
|
|
1365
|
+
(rect, path) => {
|
|
1366
|
+
finitePoint(rect, path);
|
|
1367
|
+
finiteSize(rect, path);
|
|
1368
|
+
},
|
|
1369
|
+
);
|
|
1370
|
+
validateMap('edgeRoutes', result.edgeRoutes, edgeIds, (route, path) => {
|
|
1371
|
+
const points = hasAuthoritativeLayoutPoints(route)
|
|
1372
|
+
? route.points
|
|
1373
|
+
: layoutWaypoints(route);
|
|
1374
|
+
points.forEach((point, index) =>
|
|
1375
|
+
finitePoint(point, `${path}.points[${index}]`),
|
|
1376
|
+
);
|
|
1377
|
+
});
|
|
1378
|
+
for (const [field, ids] of [
|
|
1379
|
+
['fixedEntityIds', applyOptions.fixedEntityIds],
|
|
1380
|
+
['pinnedEntityIds', applyOptions.pinnedEntityIds],
|
|
1381
|
+
[
|
|
1382
|
+
'overrideFixedEntityIds',
|
|
1383
|
+
applyOptions.overrideFixedEntityIds ?? result.overrideFixedEntityIds,
|
|
1384
|
+
],
|
|
1385
|
+
] as const) {
|
|
1386
|
+
for (const id of [...(ids ?? [])].sort()) {
|
|
1387
|
+
if (!entityIds.has(id)) {
|
|
1388
|
+
issues.push({
|
|
1389
|
+
code: 'unknown_layout_entity',
|
|
1390
|
+
path: `$.layout.${field}.${id}`,
|
|
1391
|
+
message: `unknown entity id "${id}"`,
|
|
1392
|
+
});
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
if (issues.length > 0) throw new FlowGraphValidationError(issues);
|
|
1397
|
+
|
|
1398
|
+
const fixedIds = new Set([
|
|
1399
|
+
...(applyOptions.fixedEntityIds ?? []),
|
|
1400
|
+
...(applyOptions.pinnedEntityIds ?? []),
|
|
1401
|
+
]);
|
|
1402
|
+
const overrideIds = new Set(
|
|
1403
|
+
applyOptions.overrideFixedEntityIds ??
|
|
1404
|
+
result.overrideFixedEntityIds ??
|
|
1405
|
+
[],
|
|
1406
|
+
);
|
|
1407
|
+
const animate = (applyOptions.animation?.duration ?? 0) > 0 && !activeTransaction;
|
|
1408
|
+
const beforeBounds = new Map<string, Rect>();
|
|
1409
|
+
if (animate) {
|
|
1410
|
+
for (const node of graph.nodes) {
|
|
1411
|
+
if (fixedIds.has(node.id) && !overrideIds.has(node.id)) continue;
|
|
1412
|
+
if (result.nodeBounds?.has(node.id) || result.positions.has(node.id)) {
|
|
1413
|
+
beforeBounds.set(node.id, engine.visualBounds(node.id));
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
const paths = engine.getAllEdgePaths();
|
|
1417
|
+
for (const edge of graph.edges) {
|
|
1418
|
+
if (fixedIds.has(edge.id) && !overrideIds.has(edge.id)) continue;
|
|
1419
|
+
if (
|
|
1420
|
+
edge.label &&
|
|
1421
|
+
(edge.labelAnchor ?? configuration.engine.labelAnchor ?? 'fixed') ===
|
|
1422
|
+
'fixed' &&
|
|
1423
|
+
(result.edgeLabelBounds?.has(edge.id) ||
|
|
1424
|
+
result.edgeLabelPositions?.has(edge.id))
|
|
1425
|
+
) {
|
|
1426
|
+
const bounds =
|
|
1427
|
+
paths.get(edge.id)?.labelBounds ?? engine.getBounds(edge.id);
|
|
1428
|
+
if (bounds) beforeBounds.set(edge.id, bounds);
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
const draft = validateAndCloneGraph(currentGraph(), options.dataSchemas);
|
|
1434
|
+
const changedNodeIds = new Set<string>();
|
|
1435
|
+
for (const node of draft.nodes) {
|
|
1436
|
+
if (fixedIds.has(node.id) && !overrideIds.has(node.id)) continue;
|
|
1437
|
+
const before = resolvedBounds(node);
|
|
1438
|
+
const bounds = result.nodeBounds?.get(node.id);
|
|
1439
|
+
const position = result.positions.get(node.id);
|
|
1440
|
+
const size = result.nodeSizes?.get(node.id);
|
|
1441
|
+
if (bounds) {
|
|
1442
|
+
node.x = roundLayoutPosition(bounds.x);
|
|
1443
|
+
node.y = roundLayoutPosition(bounds.y);
|
|
1444
|
+
node.width = bounds.width;
|
|
1445
|
+
node.height = bounds.height;
|
|
1446
|
+
}
|
|
1447
|
+
if (position) {
|
|
1448
|
+
node.x = roundLayoutPosition(position.x);
|
|
1449
|
+
node.y = roundLayoutPosition(position.y);
|
|
1450
|
+
}
|
|
1451
|
+
if (size) {
|
|
1452
|
+
node.width = size.width;
|
|
1453
|
+
node.height = size.height;
|
|
1454
|
+
}
|
|
1455
|
+
if (bounds || position) {
|
|
1456
|
+
delete node.dx;
|
|
1457
|
+
delete node.dy;
|
|
1458
|
+
}
|
|
1459
|
+
const after = resolvedBounds(node);
|
|
1460
|
+
if (
|
|
1461
|
+
before.x !== after.x ||
|
|
1462
|
+
before.y !== after.y ||
|
|
1463
|
+
before.width !== after.width ||
|
|
1464
|
+
before.height !== after.height
|
|
1465
|
+
) {
|
|
1466
|
+
changedNodeIds.add(node.id);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
const affectedNodeIds = withDerivedGroupAncestors(
|
|
1470
|
+
draft.nodes,
|
|
1471
|
+
changedNodeIds,
|
|
1472
|
+
);
|
|
1473
|
+
for (const edge of draft.edges) {
|
|
1474
|
+
if (fixedIds.has(edge.id) && !overrideIds.has(edge.id)) continue;
|
|
1475
|
+
delete edge.dx;
|
|
1476
|
+
delete edge.dy;
|
|
1477
|
+
const labelBounds = result.edgeLabelBounds?.get(edge.id);
|
|
1478
|
+
const labelPosition = result.edgeLabelPositions?.get(edge.id);
|
|
1479
|
+
const route = result.edgeRoutes?.get(edge.id);
|
|
1480
|
+
if (
|
|
1481
|
+
route ||
|
|
1482
|
+
affectedNodeIds.has(edge.sourceId) ||
|
|
1483
|
+
affectedNodeIds.has(edge.targetId)
|
|
1484
|
+
) {
|
|
1485
|
+
invalidateAuthoritativeEdgePath(edge);
|
|
1486
|
+
}
|
|
1487
|
+
if (edge.label && labelBounds) {
|
|
1488
|
+
edge.label.x = roundLayoutPosition(labelBounds.x);
|
|
1489
|
+
edge.label.y = roundLayoutPosition(labelBounds.y);
|
|
1490
|
+
edge.label.width = labelBounds.width;
|
|
1491
|
+
edge.label.height = labelBounds.height;
|
|
1492
|
+
edge.x = roundLayoutPosition(labelBounds.x);
|
|
1493
|
+
edge.y = roundLayoutPosition(labelBounds.y);
|
|
1494
|
+
edge.width = labelBounds.width;
|
|
1495
|
+
edge.height = labelBounds.height;
|
|
1496
|
+
}
|
|
1497
|
+
if (edge.label && labelPosition) {
|
|
1498
|
+
edge.label.x = roundLayoutPosition(labelPosition.x);
|
|
1499
|
+
edge.label.y = roundLayoutPosition(labelPosition.y);
|
|
1500
|
+
edge.x = roundLayoutPosition(labelPosition.x);
|
|
1501
|
+
edge.y = roundLayoutPosition(labelPosition.y);
|
|
1502
|
+
}
|
|
1503
|
+
if (edge.label && (labelBounds || labelPosition)) {
|
|
1504
|
+
delete edge.label.dx;
|
|
1505
|
+
delete edge.label.dy;
|
|
1506
|
+
}
|
|
1507
|
+
if (route) {
|
|
1508
|
+
if (hasAuthoritativeLayoutPoints(route)) {
|
|
1509
|
+
edge.points = route.points.map(roundLayoutPoint);
|
|
1510
|
+
edge.routing = route.routing ?? 'polyline';
|
|
1511
|
+
delete edge.waypoints;
|
|
1512
|
+
} else {
|
|
1513
|
+
const waypoints = layoutWaypoints(route);
|
|
1514
|
+
edge.waypoints = waypoints.map(roundLayoutPoint);
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
const initialOffsets = new Map<string, Point>();
|
|
1520
|
+
if (animate) {
|
|
1521
|
+
for (const [id, before] of beforeBounds) {
|
|
1522
|
+
const node = draft.nodes.find((candidate) => candidate.id === id);
|
|
1523
|
+
const edge = draft.edges.find((candidate) => candidate.id === id);
|
|
1524
|
+
const target = node
|
|
1525
|
+
? { x: node.x, y: node.y }
|
|
1526
|
+
: edge?.label
|
|
1527
|
+
? { x: edge.label.x, y: edge.label.y }
|
|
1528
|
+
: null;
|
|
1529
|
+
if (!target) continue;
|
|
1530
|
+
const offset = { x: before.x - target.x, y: before.y - target.y };
|
|
1531
|
+
if (Math.abs(offset.x) > 1e-6 || Math.abs(offset.y) > 1e-6) {
|
|
1532
|
+
initialOffsets.set(id, offset);
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
// A fixed label can keep the same authored coordinates while either
|
|
1537
|
+
// endpoint moves. Give it the midpoint endpoint offset so it follows
|
|
1538
|
+
// the animated edge instead of appearing detached until the final
|
|
1539
|
+
// frame. A label's own layout delta remains authoritative when present.
|
|
1540
|
+
for (const edge of draft.edges) {
|
|
1541
|
+
if (!beforeBounds.has(edge.id) || initialOffsets.has(edge.id)) continue;
|
|
1542
|
+
const sourceOffset = initialOffsets.get(edge.sourceId);
|
|
1543
|
+
const targetOffset = initialOffsets.get(edge.targetId);
|
|
1544
|
+
if (!sourceOffset && !targetOffset) continue;
|
|
1545
|
+
const offset = {
|
|
1546
|
+
x: ((sourceOffset?.x ?? 0) + (targetOffset?.x ?? 0)) / 2,
|
|
1547
|
+
y: ((sourceOffset?.y ?? 0) + (targetOffset?.y ?? 0)) / 2,
|
|
1548
|
+
};
|
|
1549
|
+
if (Math.abs(offset.x) > 1e-6 || Math.abs(offset.y) > 1e-6) {
|
|
1550
|
+
initialOffsets.set(edge.id, offset);
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
activeLayoutAnimation?.stop(false);
|
|
1556
|
+
commitGraph(
|
|
1557
|
+
draft,
|
|
1558
|
+
applyOptions,
|
|
1559
|
+
undefined,
|
|
1560
|
+
animate ? initialOffsets : undefined,
|
|
1561
|
+
);
|
|
1562
|
+
return startLayoutAnimation(initialOffsets, applyOptions.animation);
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
async function runLayout(
|
|
1566
|
+
layout = configuration.layout ?? undefined,
|
|
1567
|
+
runOptions: LayoutRunOptions = {},
|
|
1568
|
+
): Promise<LayoutRunResult> {
|
|
1569
|
+
if (!layout) {
|
|
1570
|
+
throw new Error(
|
|
1571
|
+
'flow.layout.run() was called without a layout algorithm. ' +
|
|
1572
|
+
'Pass one to createFlow({ layout }) or call flow.layout.run(myLayout) directly.',
|
|
1573
|
+
);
|
|
1574
|
+
}
|
|
1575
|
+
const runId = ++latestLayoutRun;
|
|
1576
|
+
activeLayoutAbort?.abort();
|
|
1577
|
+
const abortListeners = new Set<() => void>();
|
|
1578
|
+
let aborted = false;
|
|
1579
|
+
const controller = {
|
|
1580
|
+
signal: {
|
|
1581
|
+
get aborted() {
|
|
1582
|
+
return aborted;
|
|
1583
|
+
},
|
|
1584
|
+
addEventListener: (_type: 'abort', listener: () => void) => {
|
|
1585
|
+
abortListeners.add(listener);
|
|
1586
|
+
},
|
|
1587
|
+
removeEventListener: (_type: 'abort', listener: () => void) => {
|
|
1588
|
+
abortListeners.delete(listener);
|
|
1589
|
+
},
|
|
1590
|
+
} satisfies FlowAbortSignal,
|
|
1591
|
+
abort: () => {
|
|
1592
|
+
if (aborted) return;
|
|
1593
|
+
aborted = true;
|
|
1594
|
+
for (const listener of abortListeners) listener();
|
|
1595
|
+
abortListeners.clear();
|
|
1596
|
+
},
|
|
1597
|
+
};
|
|
1598
|
+
Object.freeze(controller.signal);
|
|
1599
|
+
const abort = () => controller.abort();
|
|
1600
|
+
const startedRevision = graphRevision;
|
|
1601
|
+
const startedGraph = store.getSnapshot().context.graph;
|
|
1602
|
+
const entityIds = new Set([
|
|
1603
|
+
...startedGraph.nodes.map((node) => node.id),
|
|
1604
|
+
...startedGraph.edges.map((edge) => edge.id),
|
|
1605
|
+
]);
|
|
1606
|
+
for (const [field, ids] of [
|
|
1607
|
+
['fixedEntityIds', runOptions.fixedEntityIds],
|
|
1608
|
+
['pinnedEntityIds', runOptions.pinnedEntityIds],
|
|
1609
|
+
] as const) {
|
|
1610
|
+
const unknown = [...(ids ?? [])]
|
|
1611
|
+
.filter((id) => !entityIds.has(id))
|
|
1612
|
+
.sort();
|
|
1613
|
+
if (unknown.length > 0) {
|
|
1614
|
+
throw new FlowGraphValidationError(
|
|
1615
|
+
unknown.map((id) => ({
|
|
1616
|
+
code: 'unknown_layout_entity',
|
|
1617
|
+
path: `$.layout.${field}.${id}`,
|
|
1618
|
+
message: `unknown entity id "${id}"`,
|
|
1619
|
+
})),
|
|
1620
|
+
);
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
const scope = runOptions.scope
|
|
1624
|
+
? validateViewScope(runOptions.scope)
|
|
1625
|
+
: undefined;
|
|
1626
|
+
const graphInput = immutableLayoutInput(
|
|
1627
|
+
validateAndCloneGraph(startedGraph, options.dataSchemas) as FlowGraph<
|
|
1628
|
+
TNodeData,
|
|
1629
|
+
TEdgeData,
|
|
1630
|
+
TLabelData
|
|
1631
|
+
>,
|
|
1632
|
+
);
|
|
1633
|
+
const algorithmOptions = Object.freeze({
|
|
1634
|
+
signal: controller.signal,
|
|
1635
|
+
...(runOptions.force !== undefined ? { force: runOptions.force } : {}),
|
|
1636
|
+
...(scope ? { scope } : {}),
|
|
1637
|
+
...(runOptions.previousResult !== undefined
|
|
1638
|
+
? {
|
|
1639
|
+
previousResult: immutablePreviousLayoutResult(
|
|
1640
|
+
runOptions.previousResult,
|
|
1641
|
+
),
|
|
1642
|
+
}
|
|
1643
|
+
: {}),
|
|
1644
|
+
...(runOptions.fixedEntityIds
|
|
1645
|
+
? { fixedEntityIds: immutableLayoutSet(runOptions.fixedEntityIds) }
|
|
1646
|
+
: {}),
|
|
1647
|
+
...(runOptions.pinnedEntityIds
|
|
1648
|
+
? { pinnedEntityIds: immutableLayoutSet(runOptions.pinnedEntityIds) }
|
|
1649
|
+
: {}),
|
|
1650
|
+
...(runOptions.source !== undefined ? { source: runOptions.source } : {}),
|
|
1651
|
+
...(runOptions.metadata
|
|
1652
|
+
? {
|
|
1653
|
+
metadata: immutableLayoutInput(
|
|
1654
|
+
cloneJsonSafe(runOptions.metadata, '$.layout.metadata'),
|
|
1655
|
+
),
|
|
1656
|
+
}
|
|
1657
|
+
: {}),
|
|
1658
|
+
...(runOptions.animation
|
|
1659
|
+
? { animation: Object.freeze({ ...runOptions.animation }) }
|
|
1660
|
+
: {}),
|
|
1661
|
+
}) satisfies Readonly<LayoutRunOptions> & { signal: FlowAbortSignal };
|
|
1662
|
+
activeLayoutAbort = controller;
|
|
1663
|
+
runOptions.signal?.addEventListener('abort', abort, { once: true });
|
|
1664
|
+
let result: LayoutResult | LayoutPositions;
|
|
1665
|
+
try {
|
|
1666
|
+
result = await layout(graphInput, algorithmOptions);
|
|
1667
|
+
} catch (error) {
|
|
1668
|
+
if (controller.signal.aborted) {
|
|
1669
|
+
const result: LayoutResult = {
|
|
1670
|
+
positions: new Map(),
|
|
1671
|
+
...(runOptions.source ? { source: runOptions.source } : {}),
|
|
1672
|
+
};
|
|
1673
|
+
return {
|
|
1674
|
+
applied: false,
|
|
1675
|
+
result,
|
|
1676
|
+
animation: resolvedLayoutAnimation(),
|
|
1677
|
+
...(result.source ? { source: result.source } : {}),
|
|
1678
|
+
};
|
|
1679
|
+
}
|
|
1680
|
+
throw error;
|
|
1681
|
+
} finally {
|
|
1682
|
+
runOptions.signal?.removeEventListener('abort', abort);
|
|
1683
|
+
if (activeLayoutAbort === controller) activeLayoutAbort = null;
|
|
1684
|
+
}
|
|
1685
|
+
let layoutResult = normalizeLayoutResult(result);
|
|
1686
|
+
if (!layoutResult.source && runOptions.source) {
|
|
1687
|
+
layoutResult = { ...layoutResult, source: runOptions.source };
|
|
1688
|
+
}
|
|
1689
|
+
const response = (
|
|
1690
|
+
applied: boolean,
|
|
1691
|
+
animation = resolvedLayoutAnimation(),
|
|
1692
|
+
): LayoutRunResult => ({
|
|
1693
|
+
applied,
|
|
1694
|
+
result: layoutResult,
|
|
1695
|
+
animation,
|
|
1696
|
+
...(layoutResult.source ? { source: layoutResult.source } : {}),
|
|
1697
|
+
...(layoutResult.diagnostics
|
|
1698
|
+
? { diagnostics: layoutResult.diagnostics }
|
|
1699
|
+
: {}),
|
|
1700
|
+
});
|
|
1701
|
+
if (
|
|
1702
|
+
controller.signal.aborted ||
|
|
1703
|
+
runId !== latestLayoutRun ||
|
|
1704
|
+
(!runOptions.force &&
|
|
1705
|
+
(graphRevision !== startedRevision ||
|
|
1706
|
+
store.getSnapshot().context.graph !== startedGraph))
|
|
1707
|
+
) {
|
|
1708
|
+
return response(false);
|
|
1709
|
+
}
|
|
1710
|
+
const animation = applyLayout(layoutResult, {
|
|
1711
|
+
origin: 'layout',
|
|
1712
|
+
fixedEntityIds: runOptions.fixedEntityIds,
|
|
1713
|
+
pinnedEntityIds: runOptions.pinnedEntityIds,
|
|
1714
|
+
overrideFixedEntityIds: layoutResult.overrideFixedEntityIds,
|
|
1715
|
+
animation: runOptions.animation,
|
|
1716
|
+
});
|
|
1717
|
+
return response(true, animation);
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
function writeViewport(viewport: Viewport): void {
|
|
1721
|
+
pendingInternalViewportWrites.push({ ...viewport });
|
|
1722
|
+
try {
|
|
1723
|
+
store.trigger.setViewport(viewport);
|
|
1724
|
+
} catch (error) {
|
|
1725
|
+
pendingInternalViewportWrites.pop();
|
|
1726
|
+
throw error;
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
function constrainedViewport(viewport: Viewport): Viewport {
|
|
1731
|
+
const context = store.getSnapshot().context;
|
|
1732
|
+
return context.translateExtent
|
|
1733
|
+
? constrainViewport(viewport, context.viewportSize, context.translateExtent)
|
|
1734
|
+
: viewport;
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
function cancelViewportAnimation(): void {
|
|
1738
|
+
activeViewportAnimation?.cancel();
|
|
1739
|
+
activeViewportAnimation = null;
|
|
1740
|
+
pendingInternalViewportWrites.length = 0;
|
|
1741
|
+
}
|
|
1742
|
+
|
|
1743
|
+
function resolvedViewportControls(reached = true): ViewportAnimationControls {
|
|
1744
|
+
return { cancel: () => {}, done: Promise.resolve(reached) };
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
function setViewportTarget(
|
|
1748
|
+
target: Viewport | null,
|
|
1749
|
+
animationOptions?: ViewportAnimationOptions,
|
|
1750
|
+
): ViewportAnimationControls {
|
|
1751
|
+
if (!target) {
|
|
1752
|
+
cancelViewportAnimation();
|
|
1753
|
+
return resolvedViewportControls(false);
|
|
1754
|
+
}
|
|
1755
|
+
cancelViewportAnimation();
|
|
1756
|
+
const resolvedAnimationOptions = {
|
|
1757
|
+
...(store.getSnapshot().context.viewportAnimation ?? {}),
|
|
1758
|
+
...animationOptions,
|
|
1759
|
+
...(animationOptions?.duration !== undefined
|
|
1760
|
+
? { lerp: undefined, spring: undefined }
|
|
1761
|
+
: animationOptions?.lerp !== undefined
|
|
1762
|
+
? { duration: undefined, easing: undefined, spring: undefined }
|
|
1763
|
+
: animationOptions?.spring !== undefined
|
|
1764
|
+
? { duration: undefined, easing: undefined, lerp: undefined }
|
|
1765
|
+
: {}),
|
|
1766
|
+
};
|
|
1767
|
+
if (
|
|
1768
|
+
(resolvedAnimationOptions.duration ?? 0) <= 0 &&
|
|
1769
|
+
!resolvedAnimationOptions.spring &&
|
|
1770
|
+
resolvedAnimationOptions.lerp === undefined
|
|
1771
|
+
) {
|
|
1772
|
+
store.trigger.setViewport(target);
|
|
1773
|
+
return resolvedViewportControls();
|
|
1774
|
+
}
|
|
1775
|
+
const animation = animateViewport(
|
|
1776
|
+
{
|
|
1777
|
+
...store,
|
|
1778
|
+
trigger: {
|
|
1779
|
+
...store.trigger,
|
|
1780
|
+
setViewport: writeViewport,
|
|
1781
|
+
},
|
|
1782
|
+
},
|
|
1783
|
+
target,
|
|
1784
|
+
resolvedAnimationOptions,
|
|
1785
|
+
);
|
|
1786
|
+
activeViewportAnimation = animation;
|
|
1787
|
+
void animation.done.then(() => {
|
|
1788
|
+
if (activeViewportAnimation === animation) {
|
|
1789
|
+
activeViewportAnimation = null;
|
|
1790
|
+
}
|
|
1791
|
+
});
|
|
1792
|
+
return animation;
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
function fitViewportTarget(
|
|
1796
|
+
fitOptions?: FitViewOptions & { includeHidden?: boolean },
|
|
1797
|
+
): Viewport | null {
|
|
1798
|
+
const context = store.getSnapshot().context;
|
|
1799
|
+
if (context.viewportSize.width === 0 || context.viewportSize.height === 0) {
|
|
1800
|
+
return null;
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
const ids = fitOptions?.nodes?.map((node) =>
|
|
1804
|
+
typeof node === 'string' ? node : node.id,
|
|
1805
|
+
);
|
|
1806
|
+
const idSet = ids && ids.length > 0 ? new Set(ids) : null;
|
|
1807
|
+
const visible = getViewEntities({
|
|
1808
|
+
includeHidden: fitOptions?.includeHidden,
|
|
1809
|
+
});
|
|
1810
|
+
const nodes = (visible.nodes as readonly FlowNode[]).filter(
|
|
1811
|
+
(node) => !idSet || idSet.has(node.id),
|
|
1812
|
+
);
|
|
1813
|
+
const edges = (visible.edges as readonly FlowEdge[]).filter(
|
|
1814
|
+
(edge) => !idSet || idSet.has(edge.id),
|
|
1815
|
+
);
|
|
1816
|
+
const bounds = getGraphBounds(
|
|
1817
|
+
nodes.map((node) => {
|
|
1818
|
+
const visual = engine.visualBounds(node.id);
|
|
1819
|
+
return visual
|
|
1820
|
+
? {
|
|
1821
|
+
...node,
|
|
1822
|
+
...visual,
|
|
1823
|
+
dx: 0,
|
|
1824
|
+
dy: 0,
|
|
1825
|
+
autoSize: false,
|
|
1826
|
+
style: undefined,
|
|
1827
|
+
}
|
|
1828
|
+
: node;
|
|
1829
|
+
}),
|
|
1830
|
+
edges.map((edge) => edge.label ? { ...edge, label: { ...edge.label, autoSize: engine.resolveAppearance(edge.label).autoSize } } : edge),
|
|
1831
|
+
context.measurements,
|
|
1832
|
+
);
|
|
1833
|
+
if (bounds.width === 0 && bounds.height === 0) return null;
|
|
1834
|
+
const { nodes: _nodes, includeHidden: _includeHidden, ...viewportOptions } = fitOptions ?? {};
|
|
1835
|
+
return viewportForBounds(bounds, context.viewportSize, {
|
|
1836
|
+
...viewportOptions,
|
|
1837
|
+
frame: getFitFrame(viewportOptions.frame),
|
|
1838
|
+
});
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
function getFitFrame(frame?: Rect): Readonly<Rect> {
|
|
1842
|
+
const context = store.getSnapshot().context;
|
|
1843
|
+
const base = frame
|
|
1844
|
+
? validateFitFrame(frame)
|
|
1845
|
+
: context.fitFrame
|
|
1846
|
+
? validateFitFrame(context.fitFrame)
|
|
1847
|
+
: {
|
|
1848
|
+
x: 0,
|
|
1849
|
+
y: 0,
|
|
1850
|
+
width: context.viewportSize.width,
|
|
1851
|
+
height: context.viewportSize.height,
|
|
1852
|
+
};
|
|
1853
|
+
// A controller can receive viewport commands before its DOM adapter has
|
|
1854
|
+
// reported a size. Preserve the pre-existing zero-sized frame behavior;
|
|
1855
|
+
// exclusions only become meaningful once there is a measurable frame.
|
|
1856
|
+
if (base.width <= 0 || base.height <= 0) {
|
|
1857
|
+
return Object.freeze(base);
|
|
1858
|
+
}
|
|
1859
|
+
const resolved = [...fitExclusions].flatMap((exclusion) => {
|
|
1860
|
+
const rect = exclusion.getRect();
|
|
1861
|
+
return rect
|
|
1862
|
+
? [{ rect, side: exclusion.side, gap: exclusion.gap }]
|
|
1863
|
+
: [];
|
|
1864
|
+
});
|
|
1865
|
+
return Object.freeze(fitFrameAroundExclusions(base, resolved));
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
function frameCenter(frame?: Rect): Point {
|
|
1869
|
+
const target = getFitFrame(frame);
|
|
1870
|
+
return {
|
|
1871
|
+
x: target.x + target.width / 2,
|
|
1872
|
+
y: target.y + target.height / 2,
|
|
1873
|
+
};
|
|
1874
|
+
}
|
|
1875
|
+
|
|
1876
|
+
type Graph = FlowGraph<TNodeData, TEdgeData, TLabelData>;
|
|
1877
|
+
const viewScopeCache = new WeakMap<FlowStoreContext, FlowViewScope>();
|
|
1878
|
+
const viewEntitiesCache = new WeakMap<
|
|
1879
|
+
FlowStoreContext,
|
|
1880
|
+
Map<string, FlowViewEntities<TNodeData, TEdgeData, TLabelData>>
|
|
1881
|
+
>();
|
|
1882
|
+
let activeTransaction: {
|
|
1883
|
+
graph: Graph;
|
|
1884
|
+
options?: FlowTransactionOptions;
|
|
1885
|
+
authoredEdgeRouteIds: Set<string>;
|
|
1886
|
+
removedEntityIds: Set<string>;
|
|
1887
|
+
} | null = null;
|
|
1888
|
+
|
|
1889
|
+
function scopedTransactionApi<TApi extends object>(
|
|
1890
|
+
api: TApi,
|
|
1891
|
+
assertOpen: () => void,
|
|
1892
|
+
): TApi {
|
|
1893
|
+
return new Proxy(api, {
|
|
1894
|
+
get(target, property, receiver) {
|
|
1895
|
+
const value = Reflect.get(target, property, receiver);
|
|
1896
|
+
if (typeof value !== 'function') return value;
|
|
1897
|
+
return (...args: unknown[]) => {
|
|
1898
|
+
assertOpen();
|
|
1899
|
+
return Reflect.apply(value, target, args);
|
|
1900
|
+
};
|
|
1901
|
+
},
|
|
1902
|
+
});
|
|
1903
|
+
}
|
|
1904
|
+
|
|
1905
|
+
function currentGraph(): Graph {
|
|
1906
|
+
return (activeTransaction?.graph ?? store.getSnapshot().context.graph) as Graph;
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
function currentViewScope(): FlowViewScope {
|
|
1910
|
+
const context = store.getSnapshot().context;
|
|
1911
|
+
const cached = viewScopeCache.get(context);
|
|
1912
|
+
if (cached) return cached;
|
|
1913
|
+
const scope = Object.freeze({
|
|
1914
|
+
parentId: context.parentNodeId,
|
|
1915
|
+
depth: context.depth,
|
|
1916
|
+
});
|
|
1917
|
+
viewScopeCache.set(context, scope);
|
|
1918
|
+
return scope;
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
function getViewEntities(
|
|
1922
|
+
viewOptions: { includeHidden?: boolean } = {},
|
|
1923
|
+
scope = currentViewScope(),
|
|
1924
|
+
): FlowViewEntities<TNodeData, TEdgeData, TLabelData> {
|
|
1925
|
+
const context = store.getSnapshot().context;
|
|
1926
|
+
const graph = currentGraph();
|
|
1927
|
+
const isCurrentScope =
|
|
1928
|
+
scope.parentId === context.parentNodeId && scope.depth === context.depth;
|
|
1929
|
+
const cacheKey = viewOptions.includeHidden ? 'hidden' : 'visible';
|
|
1930
|
+
if (!activeTransaction && isCurrentScope) {
|
|
1931
|
+
const cached = viewEntitiesCache.get(context)?.get(cacheKey);
|
|
1932
|
+
if (cached) return cached;
|
|
1933
|
+
}
|
|
1934
|
+
|
|
1935
|
+
const visible = viewOptions.includeHidden
|
|
1936
|
+
? { nodes: graph.nodes, edges: graph.edges }
|
|
1937
|
+
: engine.getVisibleEntities();
|
|
1938
|
+
const canonicalEdgeIds = new Set(graph.edges.map((edge) => edge.id));
|
|
1939
|
+
const result = deriveFlowView(graph, scope, {
|
|
1940
|
+
nodes: visible.nodes,
|
|
1941
|
+
edges: visible.edges,
|
|
1942
|
+
edgeOwner: (edge) =>
|
|
1943
|
+
!activeTransaction && canonicalEdgeIds.has(edge.id)
|
|
1944
|
+
? engine.getEdgeOwner(edge.id)
|
|
1945
|
+
: getDefaultEdgeOwner(edge, graph.nodes),
|
|
1946
|
+
});
|
|
1947
|
+
if (!activeTransaction && isCurrentScope) {
|
|
1948
|
+
let cache = viewEntitiesCache.get(context);
|
|
1949
|
+
if (!cache) {
|
|
1950
|
+
cache = new Map();
|
|
1951
|
+
viewEntitiesCache.set(context, cache);
|
|
1952
|
+
}
|
|
1953
|
+
cache.set(cacheKey, result);
|
|
1954
|
+
}
|
|
1955
|
+
return result;
|
|
1956
|
+
}
|
|
1957
|
+
|
|
1958
|
+
function validateViewScope(scope: FlowViewScope): FlowViewScope {
|
|
1959
|
+
if (!scope || typeof scope !== 'object') {
|
|
1960
|
+
throw new TypeError('flow.view.setScope(): scope must be an object.');
|
|
1961
|
+
}
|
|
1962
|
+
if (scope.parentId !== null && typeof scope.parentId !== 'string') {
|
|
1963
|
+
throw new TypeError(
|
|
1964
|
+
'flow.view.setScope(): parentId must be a node id or null.',
|
|
1965
|
+
);
|
|
1966
|
+
}
|
|
1967
|
+
if (scope.parentId !== null && !currentGraph().nodes.some(
|
|
1968
|
+
(node) => node.id === scope.parentId,
|
|
1969
|
+
)) {
|
|
1970
|
+
throw new RangeError(
|
|
1971
|
+
`flow.view.setScope(): parent node "${scope.parentId}" does not exist.`,
|
|
1972
|
+
);
|
|
1973
|
+
}
|
|
1974
|
+
if (
|
|
1975
|
+
scope.depth !== null &&
|
|
1976
|
+
(!Number.isInteger(scope.depth) || scope.depth < 0)
|
|
1977
|
+
) {
|
|
1978
|
+
throw new RangeError(
|
|
1979
|
+
'flow.view.setScope(): depth must be a non-negative integer or null.',
|
|
1980
|
+
);
|
|
1981
|
+
}
|
|
1982
|
+
return Object.freeze({ parentId: scope.parentId, depth: scope.depth });
|
|
1983
|
+
}
|
|
1984
|
+
|
|
1985
|
+
function validateDraftConnections(graph: Graph): void {
|
|
1986
|
+
const previousGraph = store.getSnapshot().context.graph;
|
|
1987
|
+
const previousEdges = new Map(
|
|
1988
|
+
previousGraph.edges.map((edge) => [edge.id, edge]),
|
|
1989
|
+
);
|
|
1990
|
+
const currentNodeIds = new Set(graph.nodes.map((node) => node.id));
|
|
1991
|
+
const context = { ...store.getSnapshot().context, graph };
|
|
1992
|
+
for (const edge of graph.edges) {
|
|
1993
|
+
const previous = previousEdges.get(edge.id);
|
|
1994
|
+
if (
|
|
1995
|
+
previous &&
|
|
1996
|
+
previous.sourceId === edge.sourceId &&
|
|
1997
|
+
previous.targetId === edge.targetId &&
|
|
1998
|
+
previous.sourcePort === edge.sourcePort &&
|
|
1999
|
+
previous.targetPort === edge.targetPort
|
|
2000
|
+
)
|
|
2001
|
+
continue;
|
|
2002
|
+
const retargetedAfterDeletion =
|
|
2003
|
+
configuration.store.onDeleteNodes === 'retarget' &&
|
|
2004
|
+
previous !== undefined &&
|
|
2005
|
+
((currentNodeIds.has(previous.sourceId) &&
|
|
2006
|
+
!currentNodeIds.has(previous.targetId) &&
|
|
2007
|
+
edge.sourceId === previous.sourceId &&
|
|
2008
|
+
edge.targetId === previous.sourceId &&
|
|
2009
|
+
edge.sourcePort === previous.sourcePort &&
|
|
2010
|
+
edge.targetPort === null) ||
|
|
2011
|
+
(!currentNodeIds.has(previous.sourceId) &&
|
|
2012
|
+
currentNodeIds.has(previous.targetId) &&
|
|
2013
|
+
edge.sourceId === previous.targetId &&
|
|
2014
|
+
edge.targetId === previous.targetId &&
|
|
2015
|
+
edge.sourcePort === null &&
|
|
2016
|
+
edge.targetPort === previous.targetPort));
|
|
2017
|
+
if (retargetedAfterDeletion) continue;
|
|
2018
|
+
if (
|
|
2019
|
+
context.mode === 'readonly' ||
|
|
2020
|
+
policyValue('canEdit') === false ||
|
|
2021
|
+
policyValue('canConnect') === false ||
|
|
2022
|
+
(previous && policyValue('canReconnect') === false)
|
|
2023
|
+
) {
|
|
2024
|
+
throw new Error(`Connection for edge "${edge.id}" is not allowed.`);
|
|
2025
|
+
}
|
|
2026
|
+
if (!engine.validateConnectionDetailed(edge, context).valid) {
|
|
2027
|
+
throw new Error(`Connection for edge "${edge.id}" is not allowed.`);
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
function commitGraph(
|
|
2033
|
+
graph: Graph,
|
|
2034
|
+
transactionOptions: FlowTransactionOptions = {},
|
|
2035
|
+
replacementOptions?: {
|
|
2036
|
+
retention: FlowGraphRetentionPolicy;
|
|
2037
|
+
history: FlowGraphHistoryPolicy;
|
|
2038
|
+
},
|
|
2039
|
+
layoutAnimationOffsets?: Map<string, Point>,
|
|
2040
|
+
resetMeasurementIds: readonly string[] = [],
|
|
2041
|
+
): FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null {
|
|
2042
|
+
assertTransactionOptions(transactionOptions);
|
|
2043
|
+
const validated = validateAndCloneGraph(graph, options.dataSchemas);
|
|
2044
|
+
if (activeTransaction) {
|
|
2045
|
+
activeTransaction.graph = validated;
|
|
2046
|
+
return null;
|
|
2047
|
+
}
|
|
2048
|
+
if (!replacementOptions) validateDraftConnections(validated);
|
|
2049
|
+
const before = currentGraph();
|
|
2050
|
+
const changeSet = createFlowChangeSet(before, validated, {
|
|
2051
|
+
revision: graphRevision + 1,
|
|
2052
|
+
...transactionOptions,
|
|
2053
|
+
});
|
|
2054
|
+
if (
|
|
2055
|
+
!changeSet &&
|
|
2056
|
+
!replacementOptions &&
|
|
2057
|
+
!layoutAnimationOffsets &&
|
|
2058
|
+
!resetMeasurementIds.length
|
|
2059
|
+
)
|
|
2060
|
+
return null;
|
|
2061
|
+
store.trigger.replaceGraph({
|
|
2062
|
+
graph: reuseUnchangedEntities(before, validated, changeSet),
|
|
2063
|
+
graphChanged: changeSet !== null,
|
|
2064
|
+
resetMeasurementIds,
|
|
2065
|
+
...transactionOptions,
|
|
2066
|
+
...replacementOptions,
|
|
2067
|
+
...(layoutAnimationOffsets ? { layoutAnimationOffsets } : {}),
|
|
2068
|
+
});
|
|
2069
|
+
return changeSet;
|
|
2070
|
+
}
|
|
2071
|
+
|
|
2072
|
+
function replaceGraph(
|
|
2073
|
+
graph: Graph,
|
|
2074
|
+
replaceOptions: FlowReplaceGraphOptions = {},
|
|
2075
|
+
): FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null {
|
|
2076
|
+
const retention = replaceOptions.retention ?? 'preserve';
|
|
2077
|
+
const history = replaceOptions.history ?? 'reset';
|
|
2078
|
+
if (retention !== 'preserve' && retention !== 'reset') {
|
|
2079
|
+
throw new TypeError(
|
|
2080
|
+
'flow.replaceGraph(): retention must be "preserve" or "reset".',
|
|
2081
|
+
);
|
|
2082
|
+
}
|
|
2083
|
+
if (history !== 'reset' && history !== 'ignore' && history !== 'record') {
|
|
2084
|
+
throw new TypeError(
|
|
2085
|
+
'flow.replaceGraph(): history must be "reset", "ignore", or "record".',
|
|
2086
|
+
);
|
|
2087
|
+
}
|
|
2088
|
+
if (activeTransaction) {
|
|
2089
|
+
throw new Error(
|
|
2090
|
+
'flow.replaceGraph() cannot run inside flow.transaction().',
|
|
2091
|
+
);
|
|
2092
|
+
}
|
|
2093
|
+
return commitGraph(
|
|
2094
|
+
graph,
|
|
2095
|
+
{
|
|
2096
|
+
origin: replaceOptions.origin ?? 'external',
|
|
2097
|
+
transactionId: replaceOptions.transactionId,
|
|
2098
|
+
},
|
|
2099
|
+
{ retention, history },
|
|
2100
|
+
);
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
function mutateGraph<TResult>(
|
|
2104
|
+
mutate: (graph: Graph) => TResult,
|
|
2105
|
+
transactionOptions?: FlowTransactionOptions,
|
|
2106
|
+
): TResult {
|
|
2107
|
+
assertTransactionOptions(transactionOptions);
|
|
2108
|
+
const previous = currentGraph();
|
|
2109
|
+
const draft = validateAndCloneGraph(previous, options.dataSchemas);
|
|
2110
|
+
const result = mutate(draft);
|
|
2111
|
+
const previousNodes = new Map(previous.nodes.map((node) => [node.id, node]));
|
|
2112
|
+
const previousEdges = new Map(previous.edges.map((edge) => [edge.id, edge]));
|
|
2113
|
+
const changedNodeIds = new Set<string>();
|
|
2114
|
+
for (const node of draft.nodes) {
|
|
2115
|
+
const before = previousNodes.get(node.id);
|
|
2116
|
+
if (!before) {
|
|
2117
|
+
changedNodeIds.add(node.id);
|
|
2118
|
+
} else if (
|
|
2119
|
+
nodeEndpointGeometryChanged(before, node) ||
|
|
2120
|
+
(before.parentId ?? null) !== (node.parentId ?? null)
|
|
2121
|
+
) {
|
|
2122
|
+
changedNodeIds.add(node.id);
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
const draftNodeIds = new Set(draft.nodes.map((node) => node.id));
|
|
2126
|
+
for (const node of previous.nodes) {
|
|
2127
|
+
if (!draftNodeIds.has(node.id)) changedNodeIds.add(node.id);
|
|
2128
|
+
}
|
|
2129
|
+
if (activeTransaction) {
|
|
2130
|
+
const draftEdgeIds = new Set(draft.edges.map((edge) => edge.id));
|
|
2131
|
+
for (const edgeId of activeTransaction.authoredEdgeRouteIds) {
|
|
2132
|
+
if (!draftEdgeIds.has(edgeId)) {
|
|
2133
|
+
activeTransaction.authoredEdgeRouteIds.delete(edgeId);
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
const affectedNodeIds = new Set([
|
|
2138
|
+
...withDerivedGroupAncestors(previous.nodes, changedNodeIds),
|
|
2139
|
+
...withDerivedGroupAncestors(draft.nodes, changedNodeIds),
|
|
2140
|
+
]);
|
|
2141
|
+
for (const edge of draft.edges) {
|
|
2142
|
+
const before = previousEdges.get(edge.id);
|
|
2143
|
+
const endpointChanged = before && (
|
|
2144
|
+
edge.sourceId !== before.sourceId ||
|
|
2145
|
+
edge.targetId !== before.targetId ||
|
|
2146
|
+
(edge.sourcePort ?? undefined) !== (before.sourcePort ?? undefined) ||
|
|
2147
|
+
(edge.targetPort ?? undefined) !== (before.targetPort ?? undefined)
|
|
2148
|
+
);
|
|
2149
|
+
const pointsUnchanged = before && pointsEqual(before.points, edge.points);
|
|
2150
|
+
if (activeTransaction && !pointsUnchanged) {
|
|
2151
|
+
if (edge.points && edge.points.length >= 2) {
|
|
2152
|
+
activeTransaction.authoredEdgeRouteIds.add(edge.id);
|
|
2153
|
+
} else {
|
|
2154
|
+
activeTransaction.authoredEdgeRouteIds.delete(edge.id);
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
const routeAuthoredInTransaction =
|
|
2158
|
+
activeTransaction?.authoredEdgeRouteIds.has(edge.id) ?? false;
|
|
2159
|
+
if (
|
|
2160
|
+
pointsUnchanged &&
|
|
2161
|
+
!routeAuthoredInTransaction &&
|
|
2162
|
+
(endpointChanged ||
|
|
2163
|
+
affectedNodeIds.has(edge.sourceId) ||
|
|
2164
|
+
affectedNodeIds.has(edge.targetId))
|
|
2165
|
+
) {
|
|
2166
|
+
invalidateAuthoritativeEdgePath(edge);
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
commitGraph(draft, transactionOptions);
|
|
2170
|
+
if (activeTransaction) {
|
|
2171
|
+
const surviving = new Set([...draft.nodes, ...draft.edges].map(entity => entity.id));
|
|
2172
|
+
for (const entity of [...previous.nodes, ...previous.edges]) {
|
|
2173
|
+
if (!surviving.has(entity.id)) activeTransaction.removedEntityIds.add(entity.id);
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
return result;
|
|
2177
|
+
}
|
|
2178
|
+
|
|
2179
|
+
function pointsEqual(
|
|
2180
|
+
previous: readonly Point[] | undefined,
|
|
2181
|
+
next: readonly Point[] | undefined,
|
|
2182
|
+
): boolean {
|
|
2183
|
+
if (!previous || !next) return previous === next;
|
|
2184
|
+
return (
|
|
2185
|
+
previous.length === next.length &&
|
|
2186
|
+
previous.every(
|
|
2187
|
+
(point, index) =>
|
|
2188
|
+
point.x === next[index]?.x && point.y === next[index]?.y,
|
|
2189
|
+
)
|
|
2190
|
+
);
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
function entityIds(graph = currentGraph()): Set<string> {
|
|
2194
|
+
return new Set([
|
|
2195
|
+
...graph.nodes.map((node) => node.id),
|
|
2196
|
+
...graph.edges.map((edge) => edge.id),
|
|
2197
|
+
]);
|
|
2198
|
+
}
|
|
2199
|
+
|
|
2200
|
+
function defaultCreateId(context: FlowCreateIdContext): string {
|
|
2201
|
+
const uuid = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto
|
|
2202
|
+
?.randomUUID?.() ??
|
|
2203
|
+
`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
|
|
2204
|
+
return `${context.kind}:${uuid}`;
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
function resolveId(
|
|
2208
|
+
explicitId: string | undefined,
|
|
2209
|
+
context: Omit<FlowCreateIdContext, 'attempt'>,
|
|
2210
|
+
): string {
|
|
2211
|
+
const existing = entityIds();
|
|
2212
|
+
if (explicitId !== undefined) {
|
|
2213
|
+
if (!explicitId) throw new TypeError('Entity id must be a non-empty string.');
|
|
2214
|
+
if (existing.has(explicitId)) {
|
|
2215
|
+
throw new Error(`Entity id "${explicitId}" already exists.`);
|
|
2216
|
+
}
|
|
2217
|
+
return explicitId;
|
|
2218
|
+
}
|
|
2219
|
+
const createId = options.createId ?? defaultCreateId;
|
|
2220
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
2221
|
+
const id = createId({ ...context, attempt });
|
|
2222
|
+
if (typeof id !== 'string' || id.length === 0) {
|
|
2223
|
+
throw new TypeError('createId() must return a non-empty string.');
|
|
2224
|
+
}
|
|
2225
|
+
if (!existing.has(id)) return id;
|
|
2226
|
+
}
|
|
2227
|
+
throw new Error('createId() did not produce a unique id after 100 attempts.');
|
|
2228
|
+
}
|
|
2229
|
+
|
|
2230
|
+
function deleteNodesFromGraph(graph: Graph, nodeIds: Set<string>): void {
|
|
2231
|
+
if (nodeIds.size === 0) return;
|
|
2232
|
+
const strategy = configuration.store.onDeleteNodes ?? 'cascade';
|
|
2233
|
+
if (typeof strategy === 'function') {
|
|
2234
|
+
const next = strategy(graph, nodeIds);
|
|
2235
|
+
graph.nodes = next.nodes as FlowNode<TNodeData>[];
|
|
2236
|
+
graph.edges = next.edges as FlowEdge<TEdgeData, TLabelData>[];
|
|
2237
|
+
return;
|
|
2238
|
+
}
|
|
2239
|
+
nodeIds = getNodeIdsWithDescendants(graph.nodes, nodeIds);
|
|
2240
|
+
graph.nodes = graph.nodes.filter((node) => !nodeIds.has(node.id));
|
|
2241
|
+
if (strategy === 'retarget') {
|
|
2242
|
+
graph.edges = graph.edges.flatMap((edge): FlowEdge<TEdgeData, TLabelData>[] => {
|
|
2243
|
+
const sourceDeleted = nodeIds.has(edge.sourceId);
|
|
2244
|
+
const targetDeleted = nodeIds.has(edge.targetId);
|
|
2245
|
+
if (sourceDeleted && targetDeleted) return [];
|
|
2246
|
+
if (sourceDeleted) {
|
|
2247
|
+
return [{ ...edge, sourceId: edge.targetId, sourcePort: null } as unknown as FlowEdge<TEdgeData, TLabelData>];
|
|
2248
|
+
}
|
|
2249
|
+
if (targetDeleted) {
|
|
2250
|
+
return [{ ...edge, targetId: edge.sourceId, targetPort: null } as unknown as FlowEdge<TEdgeData, TLabelData>];
|
|
2251
|
+
}
|
|
2252
|
+
return [edge];
|
|
2253
|
+
});
|
|
2254
|
+
} else {
|
|
2255
|
+
graph.edges = graph.edges.filter(
|
|
2256
|
+
(edge) => !nodeIds.has(edge.sourceId) && !nodeIds.has(edge.targetId),
|
|
2257
|
+
);
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
|
|
2261
|
+
function edgeInputWithDefaults(
|
|
2262
|
+
input: CreateEdgeInput<TEdgeData, TLabelData>,
|
|
2263
|
+
): CreateEdgeInput<TEdgeData, TLabelData> {
|
|
2264
|
+
return {
|
|
2265
|
+
...(defaultEdgeOptions as Partial<CreateEdgeInput<TEdgeData, TLabelData>> | undefined),
|
|
2266
|
+
...input,
|
|
2267
|
+
} as CreateEdgeInput<TEdgeData, TLabelData>;
|
|
2268
|
+
}
|
|
2269
|
+
|
|
2270
|
+
function validateGeometry(
|
|
2271
|
+
value: Point | Size | Rect,
|
|
2272
|
+
keys: readonly string[] = Object.keys(value),
|
|
2273
|
+
): void {
|
|
2274
|
+
for (const key of keys) {
|
|
2275
|
+
const number = Reflect.get(value, key);
|
|
2276
|
+
if (
|
|
2277
|
+
!Number.isFinite(number) ||
|
|
2278
|
+
((key === 'width' || key === 'height') && number < 0)
|
|
2279
|
+
) {
|
|
2280
|
+
throw new TypeError(
|
|
2281
|
+
'Geometry must contain finite coordinates and nonnegative sizes.',
|
|
2282
|
+
);
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
|
|
2287
|
+
function settled(value: number, geometryOptions?: FlowGeometryOptions): number {
|
|
2288
|
+
return normalizeGeometryPosition(value, geometryOptions?.positionPrecision);
|
|
2289
|
+
}
|
|
2290
|
+
|
|
2291
|
+
function sizeNode(node: FlowNode, size: Size): FlowNode {
|
|
2292
|
+
const { measured: _measured, ...authored } = node;
|
|
2293
|
+
return {
|
|
2294
|
+
...authored,
|
|
2295
|
+
width: size.width,
|
|
2296
|
+
height: size.height,
|
|
2297
|
+
style: {
|
|
2298
|
+
...node.style,
|
|
2299
|
+
customWidth: size.width,
|
|
2300
|
+
customHeight: size.height,
|
|
2301
|
+
},
|
|
2302
|
+
};
|
|
2303
|
+
}
|
|
2304
|
+
|
|
2305
|
+
function measurementId(id: string): string {
|
|
2306
|
+
const ref = engine.getEntityRef(id);
|
|
2307
|
+
return ref?.kind === 'port' ? `${ref.nodeId}:${ref.portName}` : id;
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
const measurements: FlowMeasurementsApi = {
|
|
2311
|
+
update(batch) {
|
|
2312
|
+
for (const { rect } of batch)
|
|
2313
|
+
validateGeometry(rect, ['x', 'y', 'width', 'height']);
|
|
2314
|
+
store.trigger.updateMeasurements({
|
|
2315
|
+
measurements: batch.map(({ id, rect }) => {
|
|
2316
|
+
const ref = engine.getEntityRef(id);
|
|
2317
|
+
const origin =
|
|
2318
|
+
ref?.kind === 'port' ? engine.visualBounds(ref.nodeId) : undefined;
|
|
2319
|
+
return {
|
|
2320
|
+
id: measurementId(id),
|
|
2321
|
+
rect: { ...rect },
|
|
2322
|
+
...(origin ? { origin: { x: origin.x, y: origin.y } } : {}),
|
|
2323
|
+
};
|
|
2324
|
+
}),
|
|
2325
|
+
derivedOnly: true,
|
|
2326
|
+
});
|
|
2327
|
+
},
|
|
2328
|
+
remove(ids) {
|
|
2329
|
+
store.trigger.removeMeasurements({
|
|
2330
|
+
ids: ids.map(measurementId),
|
|
2331
|
+
derivedOnly: true,
|
|
2332
|
+
});
|
|
2333
|
+
},
|
|
2334
|
+
get(id) {
|
|
2335
|
+
const rect = store
|
|
2336
|
+
.getSnapshot()
|
|
2337
|
+
.context.measurements.get(measurementId(id));
|
|
2338
|
+
return rect ? { ...rect } : undefined;
|
|
2339
|
+
},
|
|
2340
|
+
};
|
|
2341
|
+
|
|
2342
|
+
function createNodeApi(): FlowNodesApi<TNodeData> {
|
|
2343
|
+
return {
|
|
2344
|
+
move: (id, position, geometryOptions) => {
|
|
2345
|
+
validateGeometry(position, ['x', 'y']);
|
|
2346
|
+
assertCommandAllowed('move', { id });
|
|
2347
|
+
return mutateGraph((graph) => {
|
|
2348
|
+
const node = graph.nodes.find((candidate) => candidate.id === id);
|
|
2349
|
+
if (!node) throw new Error(`Node "${id}" does not exist.`);
|
|
2350
|
+
const context = store.getSnapshot().context;
|
|
2351
|
+
const grid = context.snapToGrid ? context.snapGrid : null;
|
|
2352
|
+
const x = settled(
|
|
2353
|
+
grid ? Math.round(position.x / grid[0]) * grid[0] : position.x,
|
|
2354
|
+
geometryOptions,
|
|
2355
|
+
);
|
|
2356
|
+
const y = settled(
|
|
2357
|
+
grid ? Math.round(position.y / grid[1]) * grid[1] : position.y,
|
|
2358
|
+
geometryOptions,
|
|
2359
|
+
);
|
|
2360
|
+
const plan = planNodeMovement(
|
|
2361
|
+
{ ...context, graph, selection: new Set([id]) },
|
|
2362
|
+
x - node.x - (node.dx ?? 0),
|
|
2363
|
+
y - node.y - (node.dy ?? 0),
|
|
2364
|
+
);
|
|
2365
|
+
if (plan) {
|
|
2366
|
+
for (const [index, delta] of plan.nodeDeltasByIndex) {
|
|
2367
|
+
const moved = graph.nodes[index];
|
|
2368
|
+
moved.x = settled(
|
|
2369
|
+
moved.x + (moved.dx ?? 0) + delta.x,
|
|
2370
|
+
geometryOptions,
|
|
2371
|
+
);
|
|
2372
|
+
moved.y = settled(
|
|
2373
|
+
moved.y + (moved.dy ?? 0) + delta.y,
|
|
2374
|
+
geometryOptions,
|
|
2375
|
+
);
|
|
2376
|
+
moved.dx = 0;
|
|
2377
|
+
moved.dy = 0;
|
|
2378
|
+
}
|
|
2379
|
+
for (const [index, delta] of plan.edgeDeltasByIndex) {
|
|
2380
|
+
const edge = graph.edges[index];
|
|
2381
|
+
edge.waypoints = edge.waypoints?.map((point) => ({
|
|
2382
|
+
x: point.x + delta.x,
|
|
2383
|
+
y: point.y + delta.y,
|
|
2384
|
+
}));
|
|
2385
|
+
}
|
|
2386
|
+
for (const [index, delta] of plan.labelDeltasByIndex) {
|
|
2387
|
+
const label = graph.edges[index].label;
|
|
2388
|
+
if (label) {
|
|
2389
|
+
label.x += delta.x;
|
|
2390
|
+
label.y += delta.y;
|
|
2391
|
+
}
|
|
2392
|
+
}
|
|
2393
|
+
}
|
|
2394
|
+
return node;
|
|
2395
|
+
}, geometryOptions);
|
|
2396
|
+
},
|
|
2397
|
+
resize: (id, bounds, geometryOptions) => {
|
|
2398
|
+
validateGeometry(bounds, ['x', 'y', 'width', 'height']);
|
|
2399
|
+
assertCommandAllowed('resize', { id });
|
|
2400
|
+
return createNodeApi().update(
|
|
2401
|
+
id,
|
|
2402
|
+
(node) => {
|
|
2403
|
+
const moving = clampResizeMovingPoint(
|
|
2404
|
+
node,
|
|
2405
|
+
'bottom-right',
|
|
2406
|
+
{ x: 0, y: 0 },
|
|
2407
|
+
{ x: bounds.width, y: bounds.height },
|
|
2408
|
+
);
|
|
2409
|
+
return {
|
|
2410
|
+
...sizeNode(node, { width: moving.x, height: moving.y }),
|
|
2411
|
+
x: settled(bounds.x, geometryOptions),
|
|
2412
|
+
y: settled(bounds.y, geometryOptions),
|
|
2413
|
+
dx: 0,
|
|
2414
|
+
dy: 0,
|
|
2415
|
+
};
|
|
2416
|
+
},
|
|
2417
|
+
geometryOptions,
|
|
2418
|
+
);
|
|
2419
|
+
},
|
|
2420
|
+
setContentSize: (id, size, geometryOptions) => {
|
|
2421
|
+
validateGeometry(size, ['width', 'height']);
|
|
2422
|
+
if (
|
|
2423
|
+
store.getSnapshot().context.mode === 'readonly' ||
|
|
2424
|
+
policyValue('canEdit') === false
|
|
2425
|
+
) {
|
|
2426
|
+
throw new Error('Flow content sizing is not allowed: readonly.');
|
|
2427
|
+
}
|
|
2428
|
+
const position = geometryOptions?.position;
|
|
2429
|
+
if (position) validateGeometry(position, ['x', 'y']);
|
|
2430
|
+
return createNodeApi().update(
|
|
2431
|
+
id,
|
|
2432
|
+
(node) => ({
|
|
2433
|
+
...sizeNode(node, size),
|
|
2434
|
+
...(position
|
|
2435
|
+
? {
|
|
2436
|
+
x: settled(position.x, geometryOptions),
|
|
2437
|
+
y: settled(position.y, geometryOptions),
|
|
2438
|
+
dx: 0,
|
|
2439
|
+
dy: 0,
|
|
2440
|
+
}
|
|
2441
|
+
: {}),
|
|
2442
|
+
}),
|
|
2443
|
+
geometryOptions,
|
|
2444
|
+
);
|
|
2445
|
+
},
|
|
2446
|
+
create: (input, transactionOptions) => {
|
|
2447
|
+
assertCommandAllowed('create');
|
|
2448
|
+
const id = resolveId(input.id, { kind: 'node', reason: 'create' });
|
|
2449
|
+
const node = createNode({ ...input, id } as Parameters<
|
|
2450
|
+
typeof createNode<TNodeData>
|
|
2451
|
+
>[0]);
|
|
2452
|
+
mutateGraph((graph) => graph.nodes.push(node), transactionOptions);
|
|
2453
|
+
return node;
|
|
2454
|
+
},
|
|
2455
|
+
delete: (id, transactionOptions) => {
|
|
2456
|
+
if (!currentGraph().nodes.some((node) => node.id === id)) return false;
|
|
2457
|
+
assertCommandAllowed('delete', { id });
|
|
2458
|
+
mutateGraph(
|
|
2459
|
+
(graph) => deleteNodesFromGraph(graph, new Set([id])),
|
|
2460
|
+
transactionOptions,
|
|
2461
|
+
);
|
|
2462
|
+
return true;
|
|
2463
|
+
},
|
|
2464
|
+
update: (id, patchOrUpdater, transactionOptions) => {
|
|
2465
|
+
let updated!: FlowNode<TNodeData>;
|
|
2466
|
+
mutateGraph((graph) => {
|
|
2467
|
+
const index = graph.nodes.findIndex((node) => node.id === id);
|
|
2468
|
+
if (index < 0) throw new Error(`Node "${id}" does not exist.`);
|
|
2469
|
+
const current = graph.nodes[index];
|
|
2470
|
+
updated = (
|
|
2471
|
+
typeof patchOrUpdater === 'function'
|
|
2472
|
+
? patchOrUpdater(current)
|
|
2473
|
+
: { ...current, ...patchOrUpdater }
|
|
2474
|
+
) as FlowNode<TNodeData>;
|
|
2475
|
+
if (updated.id !== id)
|
|
2476
|
+
throw new Error('Node update cannot change its id.');
|
|
2477
|
+
graph.nodes[index] = updated;
|
|
2478
|
+
}, transactionOptions);
|
|
2479
|
+
return updated;
|
|
2480
|
+
},
|
|
2481
|
+
setData: (id, data, transactionOptions) => {
|
|
2482
|
+
return createNodeApi().update(
|
|
2483
|
+
id,
|
|
2484
|
+
(node) => {
|
|
2485
|
+
const nextData =
|
|
2486
|
+
typeof data === 'function'
|
|
2487
|
+
? data(node.data, node as FlowNode<TNodeData>)
|
|
2488
|
+
: ({ ...(node.data as object), ...data } as TNodeData);
|
|
2489
|
+
return { ...node, data: nextData };
|
|
2490
|
+
},
|
|
2491
|
+
transactionOptions,
|
|
2492
|
+
);
|
|
2493
|
+
},
|
|
2494
|
+
reparent: (id, parentId, transactionOptions) => {
|
|
2495
|
+
assertCommandAllowed('reparent', { id });
|
|
2496
|
+
return createNodeApi().update(
|
|
2497
|
+
id,
|
|
2498
|
+
(node) => ({ ...node, parentId }),
|
|
2499
|
+
transactionOptions,
|
|
2500
|
+
);
|
|
2501
|
+
},
|
|
2502
|
+
collapse: (id, transactionOptions) => {
|
|
2503
|
+
store.trigger.collapseNode({ id, ...transactionOptions });
|
|
2504
|
+
},
|
|
2505
|
+
expand: (id, transactionOptions) => {
|
|
2506
|
+
store.trigger.expandNode({ id, ...transactionOptions });
|
|
2507
|
+
},
|
|
2508
|
+
};
|
|
2509
|
+
}
|
|
2510
|
+
|
|
2511
|
+
function createEdgeApi(): FlowEdgesApi<TEdgeData, TLabelData> {
|
|
2512
|
+
return {
|
|
2513
|
+
create: (input, transactionOptions) => {
|
|
2514
|
+
assertCommandAllowed('create');
|
|
2515
|
+
const withDefaults = edgeInputWithDefaults(input);
|
|
2516
|
+
const id = resolveId(withDefaults.id, { kind: 'edge', reason: 'create' });
|
|
2517
|
+
const edge = createEdge({
|
|
2518
|
+
...withDefaults,
|
|
2519
|
+
id,
|
|
2520
|
+
} as Parameters<typeof createEdge<TEdgeData, TLabelData>>[0]);
|
|
2521
|
+
mutateGraph((graph) => graph.edges.push(edge), transactionOptions);
|
|
2522
|
+
return edge;
|
|
2523
|
+
},
|
|
2524
|
+
delete: (id, transactionOptions) => {
|
|
2525
|
+
if (!currentGraph().edges.some((edge) => edge.id === id)) return false;
|
|
2526
|
+
assertCommandAllowed('delete', { id });
|
|
2527
|
+
mutateGraph((graph) => {
|
|
2528
|
+
graph.edges = graph.edges.filter((edge) => edge.id !== id);
|
|
2529
|
+
}, transactionOptions);
|
|
2530
|
+
return true;
|
|
2531
|
+
},
|
|
2532
|
+
update: (id, patchOrUpdater, transactionOptions) => {
|
|
2533
|
+
let updated!: FlowEdge<TEdgeData, TLabelData>;
|
|
2534
|
+
mutateGraph((graph) => {
|
|
2535
|
+
const index = graph.edges.findIndex((edge) => edge.id === id);
|
|
2536
|
+
if (index < 0) throw new Error(`Edge "${id}" does not exist.`);
|
|
2537
|
+
const current = graph.edges[index];
|
|
2538
|
+
updated = (
|
|
2539
|
+
typeof patchOrUpdater === 'function'
|
|
2540
|
+
? patchOrUpdater(current)
|
|
2541
|
+
: { ...current, ...patchOrUpdater }
|
|
2542
|
+
) as FlowEdge<TEdgeData, TLabelData>;
|
|
2543
|
+
if (updated.id !== id)
|
|
2544
|
+
throw new Error('Edge update cannot change its id.');
|
|
2545
|
+
graph.edges[index] = updated;
|
|
2546
|
+
}, transactionOptions);
|
|
2547
|
+
return updated;
|
|
2548
|
+
},
|
|
2549
|
+
setData: (id, data, transactionOptions) => {
|
|
2550
|
+
return createEdgeApi().update(
|
|
2551
|
+
id,
|
|
2552
|
+
(edge) => {
|
|
2553
|
+
const nextData =
|
|
2554
|
+
typeof data === 'function'
|
|
2555
|
+
? data(edge.data, edge as FlowEdge<TEdgeData, TLabelData>)
|
|
2556
|
+
: ({ ...(edge.data as object), ...data } as TEdgeData);
|
|
2557
|
+
return { ...edge, data: nextData };
|
|
2558
|
+
},
|
|
2559
|
+
transactionOptions,
|
|
2560
|
+
);
|
|
2561
|
+
},
|
|
2562
|
+
reconnect: (edgeId, patch, transactionOptions) => {
|
|
2563
|
+
assertCommandAllowed('reconnect', { id: edgeId });
|
|
2564
|
+
const edge = currentGraph().edges.find(
|
|
2565
|
+
(candidate) => candidate.id === edgeId,
|
|
2566
|
+
);
|
|
2567
|
+
if (!edge) throw new Error(`Edge "${edgeId}" does not exist.`);
|
|
2568
|
+
const proposed = {
|
|
2569
|
+
...edge,
|
|
2570
|
+
sourceId: patch.newSourceId ?? edge.sourceId,
|
|
2571
|
+
targetId: patch.newTargetId ?? edge.targetId,
|
|
2572
|
+
sourcePort:
|
|
2573
|
+
patch.newSourcePort === undefined
|
|
2574
|
+
? edge.sourcePort
|
|
2575
|
+
: patch.newSourcePort,
|
|
2576
|
+
targetPort:
|
|
2577
|
+
patch.newTargetPort === undefined
|
|
2578
|
+
? edge.targetPort
|
|
2579
|
+
: patch.newTargetPort,
|
|
2580
|
+
};
|
|
2581
|
+
return createEdgeApi().update(edgeId, proposed, transactionOptions);
|
|
2582
|
+
},
|
|
2583
|
+
};
|
|
2584
|
+
}
|
|
2585
|
+
|
|
2586
|
+
const nodes = createNodeApi();
|
|
2587
|
+
const edges = createEdgeApi();
|
|
2588
|
+
const view: FlowViewApi<TNodeData, TEdgeData, TLabelData> = {
|
|
2589
|
+
getScope: currentViewScope,
|
|
2590
|
+
setScope: (scope, viewOptions = {}) => {
|
|
2591
|
+
const validated = validateViewScope(scope);
|
|
2592
|
+
const selectionPolicy = viewOptions.selection ?? 'prune';
|
|
2593
|
+
if (selectionPolicy !== 'prune' && selectionPolicy !== 'clear') {
|
|
2594
|
+
throw new TypeError(
|
|
2595
|
+
'flow.view.setScope(): selection must be "prune" or "clear".',
|
|
2596
|
+
);
|
|
2597
|
+
}
|
|
2598
|
+
const entities = getViewEntities({}, validated);
|
|
2599
|
+
store.trigger.setViewScope({
|
|
2600
|
+
parentNodeId: validated.parentId,
|
|
2601
|
+
depth: validated.depth,
|
|
2602
|
+
selection: selectionPolicy,
|
|
2603
|
+
visibleEntityIds: [
|
|
2604
|
+
...entities.nodes.map((node) => node.id),
|
|
2605
|
+
...entities.edges.map((edge) => edge.id),
|
|
2606
|
+
],
|
|
2607
|
+
});
|
|
2608
|
+
},
|
|
2609
|
+
getEntities: getViewEntities,
|
|
2610
|
+
getBoundaryEndpoints: (edgeId) =>
|
|
2611
|
+
getViewEntities().boundaryEndpoints.find(
|
|
2612
|
+
(endpoints) => endpoints.edgeId === edgeId,
|
|
2613
|
+
),
|
|
2614
|
+
contains: (id, viewOptions) => {
|
|
2615
|
+
const entities = getViewEntities(viewOptions);
|
|
2616
|
+
return (
|
|
2617
|
+
entities.nodes.some((node) => node.id === id) ||
|
|
2618
|
+
entities.edges.some((edge) => edge.id === id)
|
|
2619
|
+
);
|
|
2620
|
+
},
|
|
2621
|
+
};
|
|
2622
|
+
|
|
2623
|
+
function selectedNodes(): FlowNode<TNodeData>[] {
|
|
2624
|
+
const selected = store.getSnapshot().context.selection;
|
|
2625
|
+
return currentGraph().nodes.filter((node) => selected.has(node.id));
|
|
2626
|
+
}
|
|
2627
|
+
|
|
2628
|
+
function duplicateSelection(
|
|
2629
|
+
duplicateOptions: { offset?: Point } = {},
|
|
2630
|
+
): FlowSelectionDuplicateResult | null {
|
|
2631
|
+
const selected = store.getSnapshot().context.selection;
|
|
2632
|
+
const selectedNodeList = selectedNodes();
|
|
2633
|
+
if (
|
|
2634
|
+
selectedNodeList.length === 0 ||
|
|
2635
|
+
!check('copy').allowed ||
|
|
2636
|
+
!check('create').allowed
|
|
2637
|
+
) {
|
|
2638
|
+
return null;
|
|
2639
|
+
}
|
|
2640
|
+
const offset = duplicateOptions.offset ?? { x: 24, y: 24 };
|
|
2641
|
+
if (!Number.isFinite(offset.x) || !Number.isFinite(offset.y)) {
|
|
2642
|
+
throw new RangeError('selection.duplicate(): offset must have finite x/y.');
|
|
2643
|
+
}
|
|
2644
|
+
const graph = currentGraph();
|
|
2645
|
+
const extracted = extractFlowContent(graph, selected, options.dataSchemas);
|
|
2646
|
+
if (!extracted || extracted.nodes.length === 0) return null;
|
|
2647
|
+
const inserted = insertFlowContent(graph, extracted, {
|
|
2648
|
+
preservePosition: true,
|
|
2649
|
+
schemas: options.dataSchemas,
|
|
2650
|
+
createId: (kind, sourceId, attempt) =>
|
|
2651
|
+
(options.createId ?? defaultCreateId)({
|
|
2652
|
+
kind,
|
|
2653
|
+
reason: 'content',
|
|
2654
|
+
sourceId,
|
|
2655
|
+
attempt,
|
|
2656
|
+
}),
|
|
2657
|
+
});
|
|
2658
|
+
const copiedNodeIds = new Set(extracted.nodes.map((node) => node.id));
|
|
2659
|
+
const originalNodes = new Map(graph.nodes.map((node) => [node.id, node]));
|
|
2660
|
+
const clonedNodeIds = new Set(inserted.nodeIds);
|
|
2661
|
+
for (const [sourceId, cloneId] of inserted.idMap) {
|
|
2662
|
+
if (!copiedNodeIds.has(sourceId)) continue;
|
|
2663
|
+
const clone = inserted.graph.nodes.find((node) => node.id === cloneId);
|
|
2664
|
+
const original = originalNodes.get(sourceId);
|
|
2665
|
+
if (!clone || !original) continue;
|
|
2666
|
+
if (original.parentId && !copiedNodeIds.has(original.parentId)) {
|
|
2667
|
+
clone.parentId = original.parentId;
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
for (const node of inserted.graph.nodes) {
|
|
2671
|
+
if (!clonedNodeIds.has(node.id)) continue;
|
|
2672
|
+
node.x += offset.x;
|
|
2673
|
+
node.y += offset.y;
|
|
2674
|
+
}
|
|
2675
|
+
const clonedEdgeIds = new Set(inserted.edgeIds);
|
|
2676
|
+
for (const edge of inserted.graph.edges) {
|
|
2677
|
+
if (!clonedEdgeIds.has(edge.id)) continue;
|
|
2678
|
+
edge.x += offset.x;
|
|
2679
|
+
edge.y += offset.y;
|
|
2680
|
+
if (edge.label) {
|
|
2681
|
+
edge.label.x += offset.x;
|
|
2682
|
+
edge.label.y += offset.y;
|
|
2683
|
+
}
|
|
2684
|
+
if (edge.waypoints) {
|
|
2685
|
+
edge.waypoints = edge.waypoints.map((point) => ({
|
|
2686
|
+
x: point.x + offset.x,
|
|
2687
|
+
y: point.y + offset.y,
|
|
2688
|
+
}));
|
|
2689
|
+
}
|
|
2690
|
+
if (offset.x !== 0 || offset.y !== 0) {
|
|
2691
|
+
invalidateAuthoritativeEdgePath(edge);
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
const changeSet = commitGraph(inserted.graph, {
|
|
2695
|
+
origin: 'selection.duplicate',
|
|
2696
|
+
});
|
|
2697
|
+
if (!changeSet) return null;
|
|
2698
|
+
selection.set([...inserted.nodeIds, ...inserted.edgeIds]);
|
|
2699
|
+
return {
|
|
2700
|
+
nodeIds: inserted.nodeIds,
|
|
2701
|
+
edgeIds: inserted.edgeIds,
|
|
2702
|
+
idMap: inserted.idMap,
|
|
2703
|
+
};
|
|
2704
|
+
}
|
|
2705
|
+
|
|
2706
|
+
function alignSelection(alignment: FlowSelectionAlignment): boolean {
|
|
2707
|
+
const eligible = selectedNodes();
|
|
2708
|
+
if (
|
|
2709
|
+
eligible.length < 2 ||
|
|
2710
|
+
eligible.some((node) => !check('move', { id: node.id }).allowed)
|
|
2711
|
+
) {
|
|
2712
|
+
return false;
|
|
2713
|
+
}
|
|
2714
|
+
const items = eligible.map((node) => ({
|
|
2715
|
+
node,
|
|
2716
|
+
bounds: engine.getBounds(node.id)!,
|
|
2717
|
+
}));
|
|
2718
|
+
const minX = Math.min(...items.map(({ bounds }) => bounds.x));
|
|
2719
|
+
const maxX = Math.max(...items.map(({ bounds }) => bounds.x + bounds.width));
|
|
2720
|
+
const minY = Math.min(...items.map(({ bounds }) => bounds.y));
|
|
2721
|
+
const maxY = Math.max(...items.map(({ bounds }) => bounds.y + bounds.height));
|
|
2722
|
+
const centerX = (minX + maxX) / 2;
|
|
2723
|
+
const centerY = (minY + maxY) / 2;
|
|
2724
|
+
const deltas = new Map<string, Point>();
|
|
2725
|
+
for (const { node, bounds } of items) {
|
|
2726
|
+
const next = { x: bounds.x, y: bounds.y };
|
|
2727
|
+
switch (alignment) {
|
|
2728
|
+
case 'left':
|
|
2729
|
+
next.x = minX;
|
|
2730
|
+
break;
|
|
2731
|
+
case 'right':
|
|
2732
|
+
next.x = maxX - bounds.width;
|
|
2733
|
+
break;
|
|
2734
|
+
case 'top':
|
|
2735
|
+
next.y = minY;
|
|
2736
|
+
break;
|
|
2737
|
+
case 'bottom':
|
|
2738
|
+
next.y = maxY - bounds.height;
|
|
2739
|
+
break;
|
|
2740
|
+
case 'center-x':
|
|
2741
|
+
next.x = centerX - bounds.width / 2;
|
|
2742
|
+
break;
|
|
2743
|
+
case 'center-y':
|
|
2744
|
+
next.y = centerY - bounds.height / 2;
|
|
2745
|
+
break;
|
|
2746
|
+
default:
|
|
2747
|
+
throw new TypeError(`Unknown selection alignment: ${String(alignment)}`);
|
|
2748
|
+
}
|
|
2749
|
+
deltas.set(node.id, { x: next.x - bounds.x, y: next.y - bounds.y });
|
|
2750
|
+
}
|
|
2751
|
+
if ([...deltas.values()].every(({ x, y }) => x === 0 && y === 0)) {
|
|
2752
|
+
return false;
|
|
2753
|
+
}
|
|
2754
|
+
mutateGraph((next) => {
|
|
2755
|
+
for (const node of next.nodes) {
|
|
2756
|
+
const delta = deltas.get(node.id);
|
|
2757
|
+
if (!delta) continue;
|
|
2758
|
+
node.x += delta.x;
|
|
2759
|
+
node.y += delta.y;
|
|
2760
|
+
}
|
|
2761
|
+
}, { origin: `selection.align.${alignment}` });
|
|
2762
|
+
return true;
|
|
2763
|
+
}
|
|
2764
|
+
|
|
2765
|
+
function distributeSelection(
|
|
2766
|
+
distribution: FlowSelectionDistribution,
|
|
2767
|
+
): boolean {
|
|
2768
|
+
const eligible = selectedNodes();
|
|
2769
|
+
if (
|
|
2770
|
+
eligible.length < 3 ||
|
|
2771
|
+
eligible.some((node) => !check('move', { id: node.id }).allowed)
|
|
2772
|
+
) {
|
|
2773
|
+
return false;
|
|
2774
|
+
}
|
|
2775
|
+
const horizontal = distribution === 'horizontal';
|
|
2776
|
+
if (!horizontal && distribution !== 'vertical') {
|
|
2777
|
+
throw new TypeError(
|
|
2778
|
+
`Unknown selection distribution: ${String(distribution)}`,
|
|
2779
|
+
);
|
|
2780
|
+
}
|
|
2781
|
+
const items = eligible
|
|
2782
|
+
.map((node) => ({ node, bounds: engine.getBounds(node.id)! }))
|
|
2783
|
+
.sort((a, b) => {
|
|
2784
|
+
const primary = horizontal
|
|
2785
|
+
? a.bounds.x - b.bounds.x
|
|
2786
|
+
: a.bounds.y - b.bounds.y;
|
|
2787
|
+
if (primary !== 0) return primary;
|
|
2788
|
+
const secondary = horizontal
|
|
2789
|
+
? a.bounds.y - b.bounds.y
|
|
2790
|
+
: a.bounds.x - b.bounds.x;
|
|
2791
|
+
return secondary !== 0
|
|
2792
|
+
? secondary
|
|
2793
|
+
: a.node.id.localeCompare(b.node.id);
|
|
2794
|
+
});
|
|
2795
|
+
const first = items[0]!;
|
|
2796
|
+
const last = items[items.length - 1]!;
|
|
2797
|
+
const totalSize = items.reduce(
|
|
2798
|
+
(sum, item) =>
|
|
2799
|
+
sum + (horizontal ? item.bounds.width : item.bounds.height),
|
|
2800
|
+
0,
|
|
2801
|
+
);
|
|
2802
|
+
const start = horizontal ? first.bounds.x : first.bounds.y;
|
|
2803
|
+
const end = horizontal
|
|
2804
|
+
? last.bounds.x + last.bounds.width
|
|
2805
|
+
: last.bounds.y + last.bounds.height;
|
|
2806
|
+
const gap = (end - start - totalSize) / (items.length - 1);
|
|
2807
|
+
const deltas = new Map<string, Point>();
|
|
2808
|
+
let cursor = start;
|
|
2809
|
+
for (const [index, { node, bounds }] of items.entries()) {
|
|
2810
|
+
const target =
|
|
2811
|
+
index === 0
|
|
2812
|
+
? start
|
|
2813
|
+
: index === items.length - 1
|
|
2814
|
+
? horizontal
|
|
2815
|
+
? bounds.x
|
|
2816
|
+
: bounds.y
|
|
2817
|
+
: cursor;
|
|
2818
|
+
deltas.set(node.id, {
|
|
2819
|
+
x: horizontal ? target - bounds.x : 0,
|
|
2820
|
+
y: horizontal ? 0 : target - bounds.y,
|
|
2821
|
+
});
|
|
2822
|
+
cursor += (horizontal ? bounds.width : bounds.height) + gap;
|
|
2823
|
+
}
|
|
2824
|
+
if ([...deltas.values()].every(({ x, y }) => x === 0 && y === 0)) {
|
|
2825
|
+
return false;
|
|
2826
|
+
}
|
|
2827
|
+
mutateGraph((next) => {
|
|
2828
|
+
for (const node of next.nodes) {
|
|
2829
|
+
const delta = deltas.get(node.id);
|
|
2830
|
+
if (!delta) continue;
|
|
2831
|
+
node.x += delta.x;
|
|
2832
|
+
node.y += delta.y;
|
|
2833
|
+
}
|
|
2834
|
+
}, { origin: `selection.distribute.${distribution}` });
|
|
2835
|
+
return true;
|
|
2836
|
+
}
|
|
2837
|
+
|
|
2838
|
+
const selection: FlowSelectionApi = {
|
|
2839
|
+
set: (ids, mode = 'single') => store.trigger.select({ ids, mode }),
|
|
2840
|
+
all: (selectOptions) => {
|
|
2841
|
+
const entities = getViewEntities(selectOptions);
|
|
2842
|
+
selection.set(
|
|
2843
|
+
[...entities.nodes.map((node) => node.id), ...entities.edges.map((edge) => edge.id)],
|
|
2844
|
+
);
|
|
2845
|
+
},
|
|
2846
|
+
clear: () => store.trigger.clearSelection(),
|
|
2847
|
+
delete: () => {
|
|
2848
|
+
const selected = store.getSnapshot().context.selection;
|
|
2849
|
+
const graph = currentGraph();
|
|
2850
|
+
const nodeIds = new Set(
|
|
2851
|
+
graph.nodes.filter((node) => selected.has(node.id)).map((node) => node.id),
|
|
2852
|
+
);
|
|
2853
|
+
const edgeIds = new Set(
|
|
2854
|
+
graph.edges.filter((edge) => selected.has(edge.id)).map((edge) => edge.id),
|
|
2855
|
+
);
|
|
2856
|
+
if (nodeIds.size === 0 && edgeIds.size === 0) return false;
|
|
2857
|
+
assertCommandAllowed('delete');
|
|
2858
|
+
mutateGraph((next) => {
|
|
2859
|
+
deleteNodesFromGraph(next, nodeIds);
|
|
2860
|
+
next.edges = next.edges.filter((edge) => !edgeIds.has(edge.id));
|
|
2861
|
+
}, { origin: 'selection.delete' });
|
|
2862
|
+
return true;
|
|
2863
|
+
},
|
|
2864
|
+
duplicate: duplicateSelection,
|
|
2865
|
+
align: alignSelection,
|
|
2866
|
+
distribute: distributeSelection,
|
|
2867
|
+
};
|
|
2868
|
+
const viewport: FlowViewportApi = {
|
|
2869
|
+
set: (next, animationOptions) =>
|
|
2870
|
+
setViewportTarget(next, animationOptions),
|
|
2871
|
+
panBy: (point, animationOptions) =>
|
|
2872
|
+
setViewportTarget(
|
|
2873
|
+
constrainedViewport(
|
|
2874
|
+
viewportPanBy(store.getSnapshot().context.viewport, point),
|
|
2875
|
+
),
|
|
2876
|
+
animationOptions,
|
|
2877
|
+
),
|
|
2878
|
+
zoomTo: (zoom, center, animationOptions) => {
|
|
2879
|
+
const context = store.getSnapshot().context;
|
|
2880
|
+
const clamped = Math.min(Math.max(zoom, context.minZoom), context.maxZoom);
|
|
2881
|
+
return setViewportTarget(
|
|
2882
|
+
constrainedViewport(
|
|
2883
|
+
viewportZoomTo(
|
|
2884
|
+
context.viewport,
|
|
2885
|
+
clamped,
|
|
2886
|
+
center ?? frameCenter(),
|
|
2887
|
+
),
|
|
2888
|
+
),
|
|
2889
|
+
animationOptions,
|
|
2890
|
+
);
|
|
2891
|
+
},
|
|
2892
|
+
zoomBy: (factor, center, animationOptions) => {
|
|
2893
|
+
const context = store.getSnapshot().context;
|
|
2894
|
+
const pivot = center ?? frameCenter();
|
|
2895
|
+
const clamped = Math.min(
|
|
2896
|
+
Math.max(context.viewport.zoom * factor, context.minZoom),
|
|
2897
|
+
context.maxZoom,
|
|
2898
|
+
);
|
|
2899
|
+
return setViewportTarget(
|
|
2900
|
+
constrainedViewport(viewportZoomTo(context.viewport, clamped, pivot)),
|
|
2901
|
+
animationOptions,
|
|
2902
|
+
);
|
|
2903
|
+
},
|
|
2904
|
+
fit: (fitOptions) => {
|
|
2905
|
+
return setViewportTarget(fitViewportTarget(fitOptions), fitOptions);
|
|
2906
|
+
},
|
|
2907
|
+
fitBounds: (bounds, fitOptions) => {
|
|
2908
|
+
const context = store.getSnapshot().context;
|
|
2909
|
+
if (context.viewportSize.width === 0 || context.viewportSize.height === 0) {
|
|
2910
|
+
cancelViewportAnimation();
|
|
2911
|
+
return resolvedViewportControls(false);
|
|
2912
|
+
}
|
|
2913
|
+
if (bounds.width === 0 && bounds.height === 0) {
|
|
2914
|
+
cancelViewportAnimation();
|
|
2915
|
+
return resolvedViewportControls(false);
|
|
2916
|
+
}
|
|
2917
|
+
const target = viewportForBounds(bounds, context.viewportSize, {
|
|
2918
|
+
...fitOptions,
|
|
2919
|
+
frame: getFitFrame(fitOptions?.frame),
|
|
2920
|
+
});
|
|
2921
|
+
return setViewportTarget(target, fitOptions);
|
|
2922
|
+
},
|
|
2923
|
+
centerOn: (point, centerOptions = {}) => {
|
|
2924
|
+
const context = store.getSnapshot().context;
|
|
2925
|
+
const {
|
|
2926
|
+
zoom = context.viewport.zoom,
|
|
2927
|
+
frame,
|
|
2928
|
+
...animationOptions
|
|
2929
|
+
} = centerOptions;
|
|
2930
|
+
const clamped = Math.min(Math.max(zoom, context.minZoom), context.maxZoom);
|
|
2931
|
+
return setViewportTarget(
|
|
2932
|
+
viewportCenteredOn(
|
|
2933
|
+
point,
|
|
2934
|
+
context.viewportSize,
|
|
2935
|
+
clamped,
|
|
2936
|
+
getFitFrame(frame),
|
|
2937
|
+
),
|
|
2938
|
+
animationOptions,
|
|
2939
|
+
);
|
|
2940
|
+
},
|
|
2941
|
+
getFitFrame,
|
|
2942
|
+
setFitFrame: (frame, options) => {
|
|
2943
|
+
store.trigger.setFitFrame({
|
|
2944
|
+
frame: frame ? validateFitFrame(frame) : null,
|
|
2945
|
+
preserveCenter: options?.preserveCenter,
|
|
2946
|
+
});
|
|
2947
|
+
},
|
|
2948
|
+
registerFitExclusion: (exclusion) => {
|
|
2949
|
+
if (!exclusion || typeof exclusion.getRect !== 'function') {
|
|
2950
|
+
throw new TypeError('Fit exclusion must provide getRect().');
|
|
2951
|
+
}
|
|
2952
|
+
fitExclusions.add(exclusion);
|
|
2953
|
+
return () => fitExclusions.delete(exclusion);
|
|
2954
|
+
},
|
|
2955
|
+
};
|
|
2956
|
+
const layout: FlowLayoutApi<TNodeData, TEdgeData, TLabelData> = {
|
|
2957
|
+
run: runLayout,
|
|
2958
|
+
apply: applyLayout,
|
|
2959
|
+
request: (algorithm) => store.trigger.requestLayout({ algorithm }),
|
|
2960
|
+
};
|
|
2961
|
+
const history: FlowHistoryApi = {
|
|
2962
|
+
undo: () => {
|
|
2963
|
+
assertCommandAllowed('undo');
|
|
2964
|
+
store.trigger.undo();
|
|
2965
|
+
},
|
|
2966
|
+
redo: () => {
|
|
2967
|
+
assertCommandAllowed('redo');
|
|
2968
|
+
store.trigger.redo();
|
|
2969
|
+
},
|
|
2970
|
+
canUndo: () => store.can.undo(),
|
|
2971
|
+
canRedo: () => store.can.redo(),
|
|
2972
|
+
};
|
|
2973
|
+
const highlights: FlowHighlightsApi = {
|
|
2974
|
+
set: (kind, entries) => store.trigger.setHighlights({ kind, entries }),
|
|
2975
|
+
add: (kind, entries) => store.trigger.addHighlights({ kind, entries }),
|
|
2976
|
+
remove: (kind, ids) => store.trigger.removeHighlights({ kind, ids }),
|
|
2977
|
+
clear: (kind) => store.trigger.clearHighlights(kind ? { kind } : undefined),
|
|
2978
|
+
};
|
|
2979
|
+
const projectionApi: FlowProjectionsApi = {
|
|
2980
|
+
get: getProjections,
|
|
2981
|
+
set: setProjections,
|
|
2982
|
+
add: (projection) => {
|
|
2983
|
+
setProjections([...projections, projection]);
|
|
2984
|
+
},
|
|
2985
|
+
remove: (id) => {
|
|
2986
|
+
setProjections(
|
|
2987
|
+
projections.filter((entry) => entry.projection.id !== id),
|
|
2988
|
+
);
|
|
2989
|
+
},
|
|
2990
|
+
clear: () => {
|
|
2991
|
+
setProjections([]);
|
|
2992
|
+
},
|
|
2993
|
+
subscribe: (listener) => {
|
|
2994
|
+
projectionListeners.add(listener);
|
|
2995
|
+
return () => {
|
|
2996
|
+
projectionListeners.delete(listener);
|
|
2997
|
+
};
|
|
2998
|
+
},
|
|
2999
|
+
getAttrs: () =>
|
|
3000
|
+
composeGraphProjectionAttrs({
|
|
3001
|
+
graph: store.getSnapshot().context.graph,
|
|
3002
|
+
projections,
|
|
3003
|
+
}),
|
|
3004
|
+
};
|
|
3005
|
+
|
|
3006
|
+
const connections: FlowConnectionsApi = {
|
|
3007
|
+
get: ({ nodeId, port, direction = 'both' }) => {
|
|
3008
|
+
const edges = currentGraph().edges;
|
|
3009
|
+
const adjacency = indexEdgeAdjacency(edges);
|
|
3010
|
+
const candidates = direction === 'in'
|
|
3011
|
+
? adjacency.byTarget.get(nodeId)
|
|
3012
|
+
: direction === 'out'
|
|
3013
|
+
? adjacency.bySource.get(nodeId)
|
|
3014
|
+
: adjacency.byNode.get(nodeId);
|
|
3015
|
+
return (candidates ?? []).flatMap((edge) => {
|
|
3016
|
+
const sourceMatches =
|
|
3017
|
+
direction !== 'in' &&
|
|
3018
|
+
edge.sourceId === nodeId &&
|
|
3019
|
+
(port === undefined || (edge.sourcePort ?? null) === port);
|
|
3020
|
+
const targetMatches =
|
|
3021
|
+
direction !== 'out' &&
|
|
3022
|
+
edge.targetId === nodeId &&
|
|
3023
|
+
(port === undefined || (edge.targetPort ?? null) === port);
|
|
3024
|
+
if (!sourceMatches && !targetMatches) return [];
|
|
3025
|
+
return [{
|
|
3026
|
+
edge,
|
|
3027
|
+
source: { nodeId: edge.sourceId, port: edge.sourcePort ?? null },
|
|
3028
|
+
target: { nodeId: edge.targetId, port: edge.targetPort ?? null },
|
|
3029
|
+
}];
|
|
3030
|
+
});
|
|
3031
|
+
},
|
|
3032
|
+
};
|
|
3033
|
+
|
|
3034
|
+
function policyValue(name: keyof FlowPolicies): boolean | undefined {
|
|
3035
|
+
const profile = configuration.store.profile;
|
|
3036
|
+
if (!profile) return undefined;
|
|
3037
|
+
const value = {
|
|
3038
|
+
...profile.policies,
|
|
3039
|
+
...profile.modes[store.getSnapshot().context.mode]?.policies,
|
|
3040
|
+
}[name];
|
|
3041
|
+
return typeof value === 'boolean' ? value : undefined;
|
|
3042
|
+
}
|
|
3043
|
+
|
|
3044
|
+
function check(command: FlowCapabilityCommand, input?: { id?: string }): FlowCapabilityResult {
|
|
3045
|
+
const editCommands: readonly FlowCapabilityCommand[] = [
|
|
3046
|
+
'edit', 'create', 'move', 'resize', 'connect', 'reconnect', 'reparent',
|
|
3047
|
+
'delete', 'cut', 'paste', 'undo', 'redo',
|
|
3048
|
+
];
|
|
3049
|
+
if (
|
|
3050
|
+
editCommands.includes(command) &&
|
|
3051
|
+
(store.getSnapshot().context.mode === 'readonly' || policyValue('canEdit') === false)
|
|
3052
|
+
) {
|
|
3053
|
+
return { allowed: false, reason: { code: 'readonly', command } };
|
|
3054
|
+
}
|
|
3055
|
+
const policyNames: Partial<Record<FlowCapabilityCommand, readonly (keyof FlowPolicies)[]>> = {
|
|
3056
|
+
create: ['canCreate'],
|
|
3057
|
+
move: ['canMove'],
|
|
3058
|
+
resize: ['canResize'],
|
|
3059
|
+
connect: ['canConnect'],
|
|
3060
|
+
reconnect: ['canConnect', 'canReconnect'],
|
|
3061
|
+
reparent: ['canReparent'],
|
|
3062
|
+
delete: ['canDelete'],
|
|
3063
|
+
cut: ['canCopy', 'canDelete'],
|
|
3064
|
+
paste: ['canPaste'],
|
|
3065
|
+
undo: ['canUndo'],
|
|
3066
|
+
redo: ['canRedo'],
|
|
3067
|
+
copy: ['canCopy'],
|
|
3068
|
+
export: ['canExport'],
|
|
3069
|
+
select: ['canSelect'],
|
|
3070
|
+
pan: ['canPan'],
|
|
3071
|
+
zoom: ['canZoom'],
|
|
3072
|
+
};
|
|
3073
|
+
if (policyNames[command]?.some((name) => policyValue(name) === false)) {
|
|
3074
|
+
return { allowed: false, reason: { code: 'policy', command } };
|
|
3075
|
+
}
|
|
3076
|
+
if (command === 'undo' && !history.canUndo()) {
|
|
3077
|
+
return { allowed: false, reason: { code: 'history', command } };
|
|
3078
|
+
}
|
|
3079
|
+
if (command === 'redo' && !history.canRedo()) {
|
|
3080
|
+
return { allowed: false, reason: { code: 'history', command } };
|
|
3081
|
+
}
|
|
3082
|
+
const ids = input?.id
|
|
3083
|
+
? [input.id]
|
|
3084
|
+
: [...store.getSnapshot().context.selection];
|
|
3085
|
+
if (['delete', 'cut', 'copy'].includes(command) && ids.length === 0) {
|
|
3086
|
+
return { allowed: false, reason: { code: 'empty', command } };
|
|
3087
|
+
}
|
|
3088
|
+
const flag =
|
|
3089
|
+
command === 'delete' || command === 'cut'
|
|
3090
|
+
? 'deletable'
|
|
3091
|
+
: command === 'move'
|
|
3092
|
+
? 'draggable'
|
|
3093
|
+
: command === 'resize'
|
|
3094
|
+
? 'resizable'
|
|
3095
|
+
: command === 'connect' || command === 'reconnect'
|
|
3096
|
+
? 'connectable'
|
|
3097
|
+
: command === 'select'
|
|
3098
|
+
? 'selectable'
|
|
3099
|
+
: null;
|
|
3100
|
+
if (
|
|
3101
|
+
flag &&
|
|
3102
|
+
ids.some((id) => {
|
|
3103
|
+
const entity = currentGraph().nodes.find((node) => node.id === id) ?? engine.getEntity(id);
|
|
3104
|
+
return entity && !engine.resolveEntityConfig(entity)[flag];
|
|
3105
|
+
})
|
|
3106
|
+
) {
|
|
3107
|
+
return { allowed: false, reason: { code: 'entity', command } };
|
|
3108
|
+
}
|
|
3109
|
+
return { allowed: true };
|
|
3110
|
+
}
|
|
3111
|
+
|
|
3112
|
+
function assertCommandAllowed(
|
|
3113
|
+
command: FlowCapabilityCommand,
|
|
3114
|
+
input?: { id?: string },
|
|
3115
|
+
): void {
|
|
3116
|
+
const result = check(command, input);
|
|
3117
|
+
if (!result.allowed) {
|
|
3118
|
+
throw new Error(`Flow command "${command}" is not allowed: ${result.reason.code}.`);
|
|
3119
|
+
}
|
|
3120
|
+
}
|
|
3121
|
+
|
|
3122
|
+
const content: FlowContentApi<TNodeData, TEdgeData, TLabelData> = {
|
|
3123
|
+
extract: (targets = store.getSnapshot().context.selection) =>
|
|
3124
|
+
extractFlowContent(currentGraph(), targets, options.dataSchemas),
|
|
3125
|
+
insert: (value, insertOptions = {}) => {
|
|
3126
|
+
if (!check('paste').allowed) {
|
|
3127
|
+
return {
|
|
3128
|
+
ok: false,
|
|
3129
|
+
error: new FlowGraphValidationError([
|
|
3130
|
+
{ code: 'capability_denied', path: '$', message: 'Paste is not allowed.' },
|
|
3131
|
+
]),
|
|
3132
|
+
};
|
|
3133
|
+
}
|
|
3134
|
+
try {
|
|
3135
|
+
const inserted = insertFlowContent(currentGraph(), value, {
|
|
3136
|
+
...insertOptions,
|
|
3137
|
+
schemas: options.dataSchemas,
|
|
3138
|
+
createId: (kind, sourceId, attempt) =>
|
|
3139
|
+
(options.createId ?? defaultCreateId)({
|
|
3140
|
+
kind,
|
|
3141
|
+
reason: 'content',
|
|
3142
|
+
sourceId,
|
|
3143
|
+
attempt,
|
|
3144
|
+
}),
|
|
3145
|
+
});
|
|
3146
|
+
if (inserted.nodeIds.length === 0 && inserted.edgeIds.length === 0) {
|
|
3147
|
+
throw new FlowGraphValidationError([
|
|
3148
|
+
{ code: 'empty_content', path: '$', message: 'Flow content is empty.' },
|
|
3149
|
+
]);
|
|
3150
|
+
}
|
|
3151
|
+
const changeSet = commitGraph(inserted.graph, { origin: 'content.insert' });
|
|
3152
|
+
if (!changeSet) throw new Error('Content insertion produced no graph change.');
|
|
3153
|
+
selection.set([...inserted.nodeIds, ...inserted.edgeIds], 'multi');
|
|
3154
|
+
return {
|
|
3155
|
+
ok: true,
|
|
3156
|
+
value: {
|
|
3157
|
+
nodeIds: inserted.nodeIds,
|
|
3158
|
+
edgeIds: inserted.edgeIds,
|
|
3159
|
+
idMap: inserted.idMap,
|
|
3160
|
+
changeSet,
|
|
3161
|
+
},
|
|
3162
|
+
};
|
|
3163
|
+
} catch (error) {
|
|
3164
|
+
return {
|
|
3165
|
+
ok: false,
|
|
3166
|
+
error:
|
|
3167
|
+
error instanceof FlowGraphValidationError
|
|
3168
|
+
? error
|
|
3169
|
+
: new FlowGraphValidationError([
|
|
3170
|
+
{ code: 'content_insert_failed', path: '$', message: String(error) },
|
|
3171
|
+
]),
|
|
3172
|
+
};
|
|
3173
|
+
}
|
|
3174
|
+
},
|
|
3175
|
+
};
|
|
3176
|
+
|
|
3177
|
+
function assertTransactionOptions(next?: FlowTransactionOptions) {
|
|
3178
|
+
if (next?.history !== undefined && next.history !== 'record' && next.history !== 'ignore') {
|
|
3179
|
+
throw new TypeError('Transaction history must be "record" or "ignore".');
|
|
3180
|
+
}
|
|
3181
|
+
if (!activeTransaction || !next) return;
|
|
3182
|
+
const outer = activeTransaction.options;
|
|
3183
|
+
for (const key of ['history', 'origin', 'transactionId'] as const) {
|
|
3184
|
+
const inherited = key === 'history' ? outer?.history ?? 'record' : outer?.[key];
|
|
3185
|
+
if (next[key] !== undefined && next[key] !== inherited) {
|
|
3186
|
+
throw new Error(`Nested transaction cannot override ${key}.`);
|
|
3187
|
+
}
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
|
|
3191
|
+
function transaction<TValue>(
|
|
3192
|
+
callback: (
|
|
3193
|
+
draft: FlowTransactionDraft<TNodeData, TEdgeData, TLabelData>,
|
|
3194
|
+
) => TValue,
|
|
3195
|
+
transactionOptions?: FlowTransactionOptions,
|
|
3196
|
+
): {
|
|
3197
|
+
value: TValue;
|
|
3198
|
+
changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null;
|
|
3199
|
+
} {
|
|
3200
|
+
assertTransactionOptions(transactionOptions);
|
|
3201
|
+
const nested = activeTransaction !== null;
|
|
3202
|
+
const previousGraph = nested
|
|
3203
|
+
? validateAndCloneGraph(activeTransaction!.graph, options.dataSchemas)
|
|
3204
|
+
: null;
|
|
3205
|
+
const previousAuthoredEdgeRouteIds = nested
|
|
3206
|
+
? new Set(activeTransaction!.authoredEdgeRouteIds)
|
|
3207
|
+
: null;
|
|
3208
|
+
const previousRemovedEntityIds = nested ? new Set(activeTransaction!.removedEntityIds) : null;
|
|
3209
|
+
if (!nested) {
|
|
3210
|
+
activeTransaction = {
|
|
3211
|
+
graph: validateAndCloneGraph(currentGraph(), options.dataSchemas),
|
|
3212
|
+
options: transactionOptions,
|
|
3213
|
+
authoredEdgeRouteIds: new Set(),
|
|
3214
|
+
removedEntityIds: new Set(),
|
|
3215
|
+
};
|
|
3216
|
+
}
|
|
3217
|
+
const transactionState = activeTransaction!;
|
|
3218
|
+
let draftOpen = true;
|
|
3219
|
+
const assertDraftOpen = () => {
|
|
3220
|
+
if (!draftOpen || activeTransaction !== transactionState) {
|
|
3221
|
+
throw new Error('Flow transaction draft is closed.');
|
|
3222
|
+
}
|
|
3223
|
+
};
|
|
3224
|
+
const { collapse: _collapse, expand: _expand, ...draftNodes } = nodes;
|
|
3225
|
+
const draft: FlowTransactionDraft<TNodeData, TEdgeData, TLabelData> = {
|
|
3226
|
+
getNode: (id) => {
|
|
3227
|
+
assertDraftOpen();
|
|
3228
|
+
const node = currentGraph().nodes.find((candidate) => candidate.id === id);
|
|
3229
|
+
return node ? cloneJsonSafe(node) : undefined;
|
|
3230
|
+
},
|
|
3231
|
+
getEdge: (id) => {
|
|
3232
|
+
assertDraftOpen();
|
|
3233
|
+
const edge = currentGraph().edges.find((candidate) => candidate.id === id);
|
|
3234
|
+
return edge ? cloneJsonSafe(edge) : undefined;
|
|
3235
|
+
},
|
|
3236
|
+
getNodeBounds: (id) => {
|
|
3237
|
+
assertDraftOpen();
|
|
3238
|
+
const node = currentGraph().nodes.find((candidate) => candidate.id === id);
|
|
3239
|
+
return node ? resolvedBounds(node) : undefined;
|
|
3240
|
+
},
|
|
3241
|
+
nodes: scopedTransactionApi(draftNodes, assertDraftOpen),
|
|
3242
|
+
edges: scopedTransactionApi(edges, assertDraftOpen),
|
|
3243
|
+
};
|
|
3244
|
+
try {
|
|
3245
|
+
const value = callback(draft);
|
|
3246
|
+
draftOpen = false;
|
|
3247
|
+
if (value && typeof (value as { then?: unknown }).then === 'function') {
|
|
3248
|
+
throw new TypeError('flow.transaction() callback must be synchronous.');
|
|
3249
|
+
}
|
|
3250
|
+
if (nested) return { value, changeSet: null };
|
|
3251
|
+
const next = activeTransaction!.graph;
|
|
3252
|
+
const surviving = new Set([...next.nodes, ...next.edges].map(entity => entity.id));
|
|
3253
|
+
const resetMeasurementIds = [...activeTransaction!.removedEntityIds].filter(id => surviving.has(id));
|
|
3254
|
+
activeTransaction = null;
|
|
3255
|
+
return { value, changeSet: commitGraph(next, transactionOptions, undefined, undefined, resetMeasurementIds) };
|
|
3256
|
+
} catch (error) {
|
|
3257
|
+
draftOpen = false;
|
|
3258
|
+
if (nested) {
|
|
3259
|
+
activeTransaction!.graph = previousGraph!;
|
|
3260
|
+
activeTransaction!.authoredEdgeRouteIds = previousAuthoredEdgeRouteIds!;
|
|
3261
|
+
activeTransaction!.removedEntityIds = previousRemovedEntityIds!;
|
|
3262
|
+
} else {
|
|
3263
|
+
activeTransaction = null;
|
|
3264
|
+
}
|
|
3265
|
+
throw error;
|
|
3266
|
+
}
|
|
3267
|
+
}
|
|
3268
|
+
|
|
3269
|
+
function applyChangeSet(
|
|
3270
|
+
changeSet: FlowChangeSet<TNodeData, TEdgeData, TLabelData>,
|
|
3271
|
+
applyOptions: FlowTransactionOptions & { strict?: boolean } = {},
|
|
3272
|
+
): FlowResult<FlowChangeSet<TNodeData, TEdgeData, TLabelData> | null> {
|
|
3273
|
+
const result = applyFlowPatches(currentGraph(), changeSet.forward, {
|
|
3274
|
+
strict: applyOptions.strict ?? true,
|
|
3275
|
+
schemas: options.dataSchemas,
|
|
3276
|
+
});
|
|
3277
|
+
if (!result.ok) return result;
|
|
3278
|
+
try {
|
|
3279
|
+
return {
|
|
3280
|
+
ok: true,
|
|
3281
|
+
value: commitGraph(result.value, {
|
|
3282
|
+
origin: applyOptions.origin ?? 'applyChangeSet',
|
|
3283
|
+
transactionId: applyOptions.transactionId,
|
|
3284
|
+
history: applyOptions.history,
|
|
3285
|
+
}),
|
|
3286
|
+
};
|
|
3287
|
+
} catch (error) {
|
|
3288
|
+
return {
|
|
3289
|
+
ok: false,
|
|
3290
|
+
error:
|
|
3291
|
+
error instanceof FlowGraphValidationError
|
|
3292
|
+
? error
|
|
3293
|
+
: new FlowGraphValidationError([
|
|
3294
|
+
{ code: 'change_set_error', path: '$', message: String(error) },
|
|
3295
|
+
]),
|
|
3296
|
+
};
|
|
3297
|
+
}
|
|
3298
|
+
}
|
|
3299
|
+
|
|
3300
|
+
const on = ((type: string, listener: (event: unknown) => void) => {
|
|
3301
|
+
if (type === 'destroy') {
|
|
3302
|
+
const destroyListener = listener as (event: { type: 'destroy' }) => void;
|
|
3303
|
+
if (!destroyed) destroyListeners.add(destroyListener);
|
|
3304
|
+
return { unsubscribe: () => { destroyListeners.delete(destroyListener); } };
|
|
3305
|
+
}
|
|
3306
|
+
if (type === 'commit') {
|
|
3307
|
+
commitListeners.add(listener as (event: FlowCommitEvent<TNodeData, TEdgeData, TLabelData>) => void);
|
|
3308
|
+
return {
|
|
3309
|
+
unsubscribe: () => {
|
|
3310
|
+
commitListeners.delete(
|
|
3311
|
+
listener as (event: FlowCommitEvent<TNodeData, TEdgeData, TLabelData>) => void,
|
|
3312
|
+
);
|
|
3313
|
+
},
|
|
3314
|
+
};
|
|
3315
|
+
}
|
|
3316
|
+
return store.on(type as Parameters<FlowStore['on']>[0], listener as never);
|
|
3317
|
+
}) as FlowController<TNodeData, TEdgeData, TLabelData>['on'];
|
|
3318
|
+
|
|
3319
|
+
const subscribe = ((
|
|
3320
|
+
selectorOrListener: ((context: FlowStoreContext) => unknown),
|
|
3321
|
+
maybeListener?: (selected: unknown, previous: unknown) => void,
|
|
3322
|
+
subscribeOptions?: {
|
|
3323
|
+
equals?: (a: unknown, b: unknown) => boolean;
|
|
3324
|
+
emitInitial?: boolean;
|
|
3325
|
+
keys?: readonly (keyof FlowStoreContext)[];
|
|
3326
|
+
},
|
|
3327
|
+
) => {
|
|
3328
|
+
if (!maybeListener) {
|
|
3329
|
+
const subscription = store.subscribe((snapshot) => {
|
|
3330
|
+
selectorOrListener(snapshot.context);
|
|
3331
|
+
});
|
|
3332
|
+
return () => subscription.unsubscribe();
|
|
3333
|
+
}
|
|
3334
|
+
const selector = selectorOrListener;
|
|
3335
|
+
const listener = maybeListener;
|
|
3336
|
+
const equals = subscribeOptions?.equals ?? Object.is;
|
|
3337
|
+
let previousContext = store.getSnapshot().context;
|
|
3338
|
+
let previous = selector(previousContext);
|
|
3339
|
+
if (subscribeOptions?.emitInitial) listener(previous, previous);
|
|
3340
|
+
const subscription = store.subscribe((snapshot) => {
|
|
3341
|
+
const context = snapshot.context;
|
|
3342
|
+
const unchanged = subscribeOptions?.keys?.every((key) =>
|
|
3343
|
+
Object.is(context[key], previousContext[key]),
|
|
3344
|
+
);
|
|
3345
|
+
previousContext = context;
|
|
3346
|
+
if (unchanged) return;
|
|
3347
|
+
const selected = selector(context);
|
|
3348
|
+
if (equals(selected, previous)) return;
|
|
3349
|
+
const old = previous;
|
|
3350
|
+
previous = selected;
|
|
3351
|
+
listener(selected, old);
|
|
3352
|
+
});
|
|
3353
|
+
return () => subscription.unsubscribe();
|
|
3354
|
+
}) as FlowController<TNodeData, TEdgeData, TLabelData>['subscribe'];
|
|
3355
|
+
|
|
3356
|
+
const controller: FlowController<TNodeData, TEdgeData, TLabelData> = {
|
|
3357
|
+
internals: { store, engine },
|
|
3358
|
+
beginExternalEdit: (editOptions) => {
|
|
3359
|
+
if (destroyed) throw new Error('Flow controller is destroyed.');
|
|
3360
|
+
return createFlowExternalEdit(controller, editOptions);
|
|
3361
|
+
},
|
|
3362
|
+
subscribeRender: (listener) => renderApi.subscribe(listener),
|
|
3363
|
+
on,
|
|
3364
|
+
destroy,
|
|
3365
|
+
|
|
3366
|
+
getContext: engine.getContext,
|
|
3367
|
+
getSnapshot: engine.getContext,
|
|
3368
|
+
subscribe,
|
|
3369
|
+
configure,
|
|
3370
|
+
invalidateRoutes: engine.invalidateRoutes,
|
|
3371
|
+
getConfiguration: () => immutableConfiguration(configuration),
|
|
3372
|
+
toJSON,
|
|
3373
|
+
load,
|
|
3374
|
+
replaceGraph,
|
|
3375
|
+
transaction,
|
|
3376
|
+
applyChangeSet,
|
|
3377
|
+
|
|
3378
|
+
getNode: engine.getNode as FlowController<
|
|
3379
|
+
TNodeData,
|
|
3380
|
+
TEdgeData,
|
|
3381
|
+
TLabelData
|
|
3382
|
+
>['getNode'],
|
|
3383
|
+
getEdge: engine.getEdge as FlowController<
|
|
3384
|
+
TNodeData,
|
|
3385
|
+
TEdgeData,
|
|
3386
|
+
TLabelData
|
|
3387
|
+
>['getEdge'],
|
|
3388
|
+
getEntity: engine.getEntity,
|
|
3389
|
+
getEntityRef: engine.getEntityRef,
|
|
3390
|
+
getAddressable: engine.getAddressable,
|
|
3391
|
+
getOwnerEntity: engine.getOwnerEntity as FlowController<
|
|
3392
|
+
TNodeData,
|
|
3393
|
+
TEdgeData,
|
|
3394
|
+
TLabelData
|
|
3395
|
+
>['getOwnerEntity'],
|
|
3396
|
+
getBounds: engine.getBounds,
|
|
3397
|
+
|
|
3398
|
+
screenToCanvas: engine.screenToCanvas,
|
|
3399
|
+
canvasToScreen: engine.canvasToScreen,
|
|
3400
|
+
getAllEdgePaths: engine.getAllEdgePaths,
|
|
3401
|
+
getConnectionCandidate: engine.getConnectionCandidate,
|
|
3402
|
+
getGraphBounds: engine.getGraphBounds,
|
|
3403
|
+
getIncomers: engine.getIncomers,
|
|
3404
|
+
getOutgoers: engine.getOutgoers,
|
|
3405
|
+
getConnectedEdges: engine.getConnectedEdges,
|
|
3406
|
+
getNeighbors: engine.getNeighbors,
|
|
3407
|
+
getSelectionBounds: engine.getSelectionBounds,
|
|
3408
|
+
getRenderableEntities: engine.getRenderableEntities,
|
|
3409
|
+
getEntityOrder: engine.getEntityOrder,
|
|
3410
|
+
check,
|
|
3411
|
+
can: (command, input) => check(command, input).allowed,
|
|
3412
|
+
mode: {
|
|
3413
|
+
get: () => store.getSnapshot().context.mode,
|
|
3414
|
+
set: (mode) => store.trigger.setMode({ mode }),
|
|
3415
|
+
},
|
|
3416
|
+
|
|
3417
|
+
nodes,
|
|
3418
|
+
measurements,
|
|
3419
|
+
edges,
|
|
3420
|
+
selection,
|
|
3421
|
+
view,
|
|
3422
|
+
viewport,
|
|
3423
|
+
layout,
|
|
3424
|
+
history,
|
|
3425
|
+
highlights,
|
|
3426
|
+
projections: projectionApi,
|
|
3427
|
+
connections,
|
|
3428
|
+
content,
|
|
3429
|
+
};
|
|
3430
|
+
const renderApi = createFlowRenderApi(controller);
|
|
3431
|
+
return controller;
|
|
3432
|
+
}
|
|
3433
|
+
|
|
3434
|
+
/**
|
|
3435
|
+
* Parse a persisted Flow document and create a controller from it.
|
|
3436
|
+
*
|
|
3437
|
+
* Restores graph, collapsed nodes, and viewport after applying configured data
|
|
3438
|
+
* migrations. Throws `FlowGraphValidationError` for invalid documents.
|
|
3439
|
+
*/
|
|
3440
|
+
export function fromJSON<
|
|
3441
|
+
TNodeData = any,
|
|
3442
|
+
TEdgeData = any,
|
|
3443
|
+
TLabelData = any,
|
|
3444
|
+
>(
|
|
3445
|
+
data: unknown,
|
|
3446
|
+
options: Omit<CreateFlowOptions<TNodeData, TEdgeData, TLabelData>, 'graph'> = {},
|
|
3447
|
+
): FlowController<TNodeData, TEdgeData, TLabelData> {
|
|
3448
|
+
const parsed = parseFlowSerialized<TNodeData, TEdgeData, TLabelData>(
|
|
3449
|
+
data,
|
|
3450
|
+
options.dataSchemas,
|
|
3451
|
+
);
|
|
3452
|
+
const flow = createFlow<TNodeData, TEdgeData, TLabelData>({
|
|
3453
|
+
...options,
|
|
3454
|
+
graph: parsed.graph,
|
|
3455
|
+
});
|
|
3456
|
+
flow.internals.store.trigger.setCollapsedNodes({
|
|
3457
|
+
ids: parsed.collapsedNodeIds ?? [],
|
|
3458
|
+
});
|
|
3459
|
+
// Hydration is synchronous even when public viewport commands inherit a
|
|
3460
|
+
// default animation. Callers must receive the restored viewport immediately.
|
|
3461
|
+
flow.internals.store.trigger.setViewport(parsed.viewport);
|
|
3462
|
+
return flow;
|
|
3463
|
+
}
|