Repository navigation
Expand file tree
/
Copy pathgraph.ts
More file actions
545 lines (483 loc) · 16.4 KB
/
Copy pathgraph.ts
File metadata and controls
545 lines (483 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
import {
boxToRect,
clampPosition,
getBoundsOfBoxes,
getRectsOverlappingArea,
getViewportForBounds,
isCoordinateExtent,
getNodeDimensions,
nodeToBox,
} from './general';
import {
type Transform,
type XYPosition,
type Rect,
type NodeOrigin,
type NodeBase,
type EdgeBase,
type FitViewParamsBase,
type FitViewOptionsBase,
CoordinateExtent,
OnError,
OnBeforeDeleteBase,
NodeLookup,
InternalNodeBase,
NodeDragItem,
} from '../types';
import { errorMessages } from '../constants';
/**
* Test whether an object is usable as an Edge
* @public
* @remarks In TypeScript this is a type guard that will narrow the type of whatever you pass in to Edge if it returns true
* @param element - The element to test
* @returns A boolean indicating whether the element is an Edge
*/
export const isEdgeBase = <EdgeType extends EdgeBase = EdgeBase>(element: unknown): element is EdgeType =>
!!element && typeof element === 'object' && 'id' in element && 'source' in element && 'target' in element;
/**
* Test whether an object is usable as a Node
* @public
* @remarks In TypeScript this is a type guard that will narrow the type of whatever you pass in to Node if it returns true
* @param element - The element to test
* @returns A boolean indicating whether the element is an Node
*/
export const isNodeBase = <NodeType extends NodeBase = NodeBase>(element: unknown): element is NodeType =>
!!element && typeof element === 'object' && 'id' in element && 'position' in element && !('source' in element) && !('target' in element);
export const isInternalNodeBase = <NodeType extends InternalNodeBase = InternalNodeBase>(
element: unknown
): element is NodeType => !!element && typeof element === 'object' && 'id' in element && 'internals' in element && !('source' in element) && !('target' in element);
/**
* This util is used to tell you what nodes, if any, are connected to the given node
* as the _target_ of an edge.
* @public
* @param node - The node to get the connected nodes from.
* @param nodes - The array of all nodes.
* @param edges - The array of all edges.
* @returns An array of nodes that are connected over edges where the source is the given node.
*
* @example
* ```ts
*import { getOutgoers } from '@xyflow/react';
*
*const nodes = [];
*const edges = [];
*
*const outgoers = getOutgoers(
* { id: '1', position: { x: 0, y: 0 }, data: { label: 'node' } },
* nodes,
* edges,
*);
*```
*/
export const getOutgoers = <NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase>(
node: NodeType | { id: string },
nodes: NodeType[],
edges: EdgeType[]
): NodeType[] => {
if (!node.id) {
return [];
}
const outgoerIds = new Set();
edges.forEach((edge) => {
if (edge.source === node.id) {
outgoerIds.add(edge.target);
}
});
return nodes.filter((n) => outgoerIds.has(n.id));
};
/**
* This util is used to tell you what nodes, if any, are connected to the given node
* as the _source_ of an edge.
* @public
* @param node - The node to get the connected nodes from.
* @param nodes - The array of all nodes.
* @param edges - The array of all edges.
* @returns An array of nodes that are connected over edges where the target is the given node.
*
* @example
* ```ts
*import { getIncomers } from '@xyflow/react';
*
*const nodes = [];
*const edges = [];
*
*const incomers = getIncomers(
* { id: '1', position: { x: 0, y: 0 }, data: { label: 'node' } },
* nodes,
* edges,
*);
*```
*/
export const getIncomers = <NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase>(
node: NodeType | { id: string },
nodes: NodeType[],
edges: EdgeType[]
): NodeType[] => {
if (!node.id) {
return [];
}
const incomersIds = new Set();
edges.forEach((edge) => {
if (edge.target === node.id) {
incomersIds.add(edge.source);
}
});
return nodes.filter((n) => incomersIds.has(n.id));
};
export const getNodePositionWithOrigin = (node: NodeBase, nodeOrigin: NodeOrigin = [0, 0]): XYPosition => {
const { width, height } = getNodeDimensions(node);
const origin = node.origin ?? nodeOrigin;
const offsetX = width * origin[0];
const offsetY = height * origin[1];
return {
x: node.position.x - offsetX,
y: node.position.y - offsetY,
};
};
export type GetNodesBoundsParams<NodeType extends NodeBase = NodeBase> = {
/**
* Origin of the nodes: `[0, 0]` for top-left, `[0.5, 0.5]` for center.
* @default [0, 0]
*/
nodeOrigin?: NodeOrigin;
nodeLookup?: NodeLookup<InternalNodeBase<NodeType>>;
};
/**
* Returns the bounding box that contains all the given nodes in an array. This can
* be useful when combined with [`getViewportForBounds`](/api-reference/utils/get-viewport-for-bounds)
* to calculate the correct transform to fit the given nodes in a viewport.
* @public
* @remarks Useful when combined with {@link getViewportForBounds} to calculate the correct transform to fit the given nodes in a viewport.
* @param nodes - Nodes to calculate the bounds for.
* @returns Bounding box enclosing all nodes.
*
* @remarks This function was previously called `getRectOfNodes`
*
* @example
* ```js
*import { getNodesBounds } from '@xyflow/react';
*
*const nodes = [
* {
* id: 'a',
* position: { x: 0, y: 0 },
* data: { label: 'a' },
* width: 50,
* height: 25,
* },
* {
* id: 'b',
* position: { x: 100, y: 100 },
* data: { label: 'b' },
* width: 50,
* height: 25,
* },
*];
*
*const bounds = getNodesBounds(nodes);
*```
*/
export const getNodesBounds = <NodeType extends NodeBase = NodeBase>(
nodes: (NodeType | InternalNodeBase<NodeType> | string)[],
params: GetNodesBoundsParams<NodeType> = { nodeOrigin: [0, 0] }
): Rect => {
if (process.env.NODE_ENV === 'development' && !params.nodeLookup) {
console.warn(
'Please use `getNodesBounds` from `useReactFlow`/`useSvelteFlow` hook to ensure correct values for sub flows. If not possible, you have to provide a nodeLookup to support sub flows.'
);
}
if (nodes.length === 0) {
return { x: 0, y: 0, width: 0, height: 0 };
}
let hasNode = false;
const box = nodes.reduce(
(currBox, nodeOrId) => {
const isId = typeof nodeOrId === 'string';
let currentNode = !params.nodeLookup && !isId ? nodeOrId : undefined;
if (params.nodeLookup) {
currentNode = isId
? params.nodeLookup.get(nodeOrId)
: !isInternalNodeBase(nodeOrId)
? params.nodeLookup.get(nodeOrId.id)
: nodeOrId;
}
/*
* Skip ids/nodes that can't be resolved (e.g. a stale or already-removed id).
* Merging a phantom box at the origin would stretch the bounds to include
* (0, 0). This mirrors getInternalNodesBounds, which skips unmatched nodes.
*/
if (!currentNode) {
return currBox;
}
hasNode = true;
return getBoundsOfBoxes(currBox, nodeToBox(currentNode, params.nodeOrigin));
},
{ x: Infinity, y: Infinity, x2: -Infinity, y2: -Infinity }
);
return hasNode ? boxToRect(box) : { x: 0, y: 0, width: 0, height: 0 };
};
export type GetInternalNodesBoundsParams<NodeType> = {
useRelativePosition?: boolean;
filter?: (node: NodeType) => boolean;
};
/**
* Determines a bounding box that contains all given nodes in an array
* @internal
*/
export const getInternalNodesBounds = <NodeType extends InternalNodeBase | NodeDragItem>(
nodeLookup: Map<string, NodeType>,
params: GetInternalNodesBoundsParams<NodeType> = {}
): Rect => {
let box = { x: Infinity, y: Infinity, x2: -Infinity, y2: -Infinity };
let hasVisibleNodes = false;
nodeLookup.forEach((node) => {
if (params.filter === undefined || params.filter(node)) {
box = getBoundsOfBoxes(box, nodeToBox(node as InternalNodeBase));
hasVisibleNodes = true;
}
});
return hasVisibleNodes ? boxToRect(box) : { x: 0, y: 0, width: 0, height: 0 };
};
export const getNodesInside = <NodeType extends NodeBase = NodeBase>(
nodes: Map<string, InternalNodeBase<NodeType>>,
rect: Rect,
[tx, ty, tScale]: Transform = [0, 0, 1],
partially = false,
// set excludeNonSelectableNodes if you want to pay attention to the nodes "selectable" attribute
excludeNonSelectableNodes = false
): InternalNodeBase<NodeType>[] => {
// viewport in flow coordinates, as scalars to avoid a Rect allocation per node
const paneX = (rect.x - tx) / tScale;
const paneY = (rect.y - ty) / tScale;
const paneWidth = rect.width / tScale;
const paneHeight = rect.height / tScale;
const visibleNodes: InternalNodeBase<NodeType>[] = [];
for (const node of nodes.values()) {
const { measured, selectable = true, hidden = false } = node;
if ((excludeNonSelectableNodes && !selectable) || hidden) {
continue;
}
const width = measured.width ?? node.width ?? node.initialWidth ?? 0;
const height = measured.height ?? node.height ?? node.initialHeight ?? 0;
const { x, y } = node.internals.positionAbsolute;
const overlappingArea = getRectsOverlappingArea(paneX, paneY, paneWidth, paneHeight, x, y, width, height);
const area = width * height;
const partiallyVisible = partially && overlappingArea > 0;
const forceInitialRender = !node.internals.handleBounds;
const isVisible = forceInitialRender || partiallyVisible || overlappingArea >= area;
if (isVisible || node.dragging) {
visibleNodes.push(node);
}
}
return visibleNodes;
};
/**
* This utility filters an array of edges, keeping only those where either the source or target
* node is present in the given array of nodes.
* @public
* @param nodes - Nodes you want to get the connected edges for.
* @param edges - All edges.
* @returns Array of edges that connect any of the given nodes with each other.
*
* @example
* ```js
*import { getConnectedEdges } from '@xyflow/react';
*
*const nodes = [
* { id: 'a', position: { x: 0, y: 0 } },
* { id: 'b', position: { x: 100, y: 0 } },
*];
*
*const edges = [
* { id: 'a->c', source: 'a', target: 'c' },
* { id: 'c->d', source: 'c', target: 'd' },
*];
*
*const connectedEdges = getConnectedEdges(nodes, edges);
* // => [{ id: 'a->c', source: 'a', target: 'c' }]
*```
*/
export const getConnectedEdges = <NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase>(
nodes: NodeType[],
edges: EdgeType[]
): EdgeType[] => {
const nodeIds = new Set();
nodes.forEach((node) => {
nodeIds.add(node.id);
});
return edges.filter((edge) => nodeIds.has(edge.source) || nodeIds.has(edge.target));
};
function getFitViewNodes<
Params extends NodeLookup<InternalNodeBase<NodeBase>>,
Options extends FitViewOptionsBase<NodeBase>
>(nodeLookup: Params, options?: Options) {
const fitViewNodes: NodeLookup = new Map();
const optionNodeIds = options?.nodes ? new Set(options.nodes.map((node) => node.id)) : null;
nodeLookup.forEach((n) => {
let isVisible: boolean;
if (options?.includeHiddenNodes) {
/*
* when hidden nodes are included they were never rendered, so they have no
* measured size. Fall back to the declared dimensions (same fallback as
* nodeToBox) so a hidden node with an intrinsic size still contributes to
* the fit bounds instead of being dropped by a measured-only check. (#5841)
*/
const { width, height } = getNodeDimensions(n);
isVisible = width > 0 && height > 0;
} else {
isVisible = Boolean(n.measured.width && n.measured.height && !n.hidden);
}
if (isVisible && (!optionNodeIds || optionNodeIds.has(n.id))) {
fitViewNodes.set(n.id, n);
}
});
return fitViewNodes;
}
export async function fitViewport<
Params extends FitViewParamsBase<NodeBase>,
Options extends FitViewOptionsBase<NodeBase>
>(
{ nodes, width, height, panZoom, minZoom, maxZoom }: Params,
options?: Omit<Options, 'nodes' | 'includeHiddenNodes'>
): Promise<boolean> {
if (nodes.size === 0) {
return true;
}
const nodesToFit = getFitViewNodes(nodes, options);
const bounds = getInternalNodesBounds(nodesToFit);
const viewport = getViewportForBounds(
bounds,
width,
height,
options?.minZoom ?? minZoom,
options?.maxZoom ?? maxZoom,
options?.padding ?? 0.1
);
await panZoom.setViewport(viewport, {
duration: options?.duration,
ease: options?.ease,
interpolate: options?.interpolate,
});
return true;
}
/**
* This function calculates the next position of a node, taking into account the node's extent, parent node, and origin.
*
* @internal
* @returns position, positionAbsolute
*/
export function calculateNodePosition<NodeType extends NodeBase>({
nodeId,
nextPosition,
nodeLookup,
nodeOrigin = [0, 0],
nodeExtent,
onError,
}: {
nodeId: string;
nextPosition: XYPosition;
nodeLookup: NodeLookup<InternalNodeBase<NodeType>>;
nodeOrigin?: NodeOrigin;
nodeExtent?: CoordinateExtent;
onError?: OnError;
}): { position: XYPosition; positionAbsolute: XYPosition } {
const node = nodeLookup.get(nodeId)!;
const parentNode = node.parentId ? nodeLookup.get(node.parentId) : undefined;
const { x: parentX, y: parentY } = parentNode ? parentNode.internals.positionAbsolute : { x: 0, y: 0 };
const origin = node.origin ?? nodeOrigin;
let extent = node.extent || nodeExtent;
if (node.extent === 'parent' && !node.expandParent) {
if (!parentNode) {
onError?.('005', errorMessages['error005']());
} else {
const { width: parentWidth, height: parentHeight } = getNodeDimensions(parentNode);
if (parentWidth && parentHeight) {
extent = [
[parentX, parentY],
[parentX + parentWidth, parentY + parentHeight],
];
}
}
} else if (parentNode && isCoordinateExtent(node.extent)) {
extent = [
[node.extent[0][0] + parentX, node.extent[0][1] + parentY],
[node.extent[1][0] + parentX, node.extent[1][1] + parentY],
];
}
const positionAbsolute = isCoordinateExtent(extent)
? clampPosition(nextPosition, extent, node.measured)
: nextPosition;
if (node.measured.width === undefined || node.measured.height === undefined) {
onError?.('015', errorMessages['error015']());
}
return {
position: {
x: positionAbsolute.x - parentX + (node.measured.width ?? 0) * origin[0],
y: positionAbsolute.y - parentY + (node.measured.height ?? 0) * origin[1],
},
positionAbsolute,
};
}
/**
* Pass in nodes & edges to delete, get arrays of nodes and edges that actually can be deleted
* @internal
* @param param.nodesToRemove - The nodes to remove
* @param param.edgesToRemove - The edges to remove
* @param param.nodes - All nodes
* @param param.edges - All edges
* @param param.onBeforeDelete - Callback to check which nodes and edges can be deleted
* @returns nodes: nodes that can be deleted, edges: edges that can be deleted
*/
export async function getElementsToRemove<NodeType extends NodeBase = NodeBase, EdgeType extends EdgeBase = EdgeBase>({
nodesToRemove = [],
edgesToRemove = [],
nodes,
edges,
onBeforeDelete,
}: {
nodesToRemove: Partial<NodeType>[];
edgesToRemove: Partial<EdgeType>[];
nodes: NodeType[];
edges: EdgeType[];
onBeforeDelete?: OnBeforeDeleteBase<NodeType, EdgeType>;
}): Promise<{
nodes: NodeType[];
edges: EdgeType[];
}> {
const nodeIds = new Set(nodesToRemove.map((node) => node.id));
const matchingNodes: NodeType[] = [];
for (const node of nodes) {
if (node.deletable === false) {
continue;
}
const isIncluded = nodeIds.has(node.id);
const parentHit = !isIncluded && node.parentId && matchingNodes.find((n) => n.id === node.parentId);
if (isIncluded || parentHit) {
matchingNodes.push(node);
}
}
const edgeIds = new Set(edgesToRemove.map((edge) => edge.id));
const deletableEdges = edges.filter((edge) => edge.deletable !== false);
const connectedEdges = getConnectedEdges(matchingNodes, deletableEdges);
const matchingEdges: EdgeType[] = connectedEdges;
for (const edge of deletableEdges) {
const isIncluded = edgeIds.has(edge.id);
if (isIncluded && !matchingEdges.find((e) => e.id === edge.id)) {
matchingEdges.push(edge);
}
}
if (!onBeforeDelete) {
return {
edges: matchingEdges,
nodes: matchingNodes,
};
}
const onBeforeDeleteResult = await onBeforeDelete({
nodes: matchingNodes,
edges: matchingEdges,
});
if (typeof onBeforeDeleteResult === 'boolean') {
return onBeforeDeleteResult ? { edges: matchingEdges, nodes: matchingNodes } : { edges: [], nodes: [] };
}
return onBeforeDeleteResult;
}