feat(packages): add @reactflow/system and @reactflow/utils
This commit is contained in:
@@ -0,0 +1,287 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import type { Selection as D3Selection } from 'd3';
|
||||
|
||||
import { boxToRect, clamp, devWarn, getBoundsOfBoxes, getOverlappingArea, rectToBox } from './utils';
|
||||
import {
|
||||
errorMessages,
|
||||
type Node,
|
||||
type Edge,
|
||||
type Connection,
|
||||
type EdgeMarkerType,
|
||||
type Transform,
|
||||
type XYPosition,
|
||||
type Rect,
|
||||
type NodeInternals,
|
||||
type NodeOrigin,
|
||||
} from '@reactflow/system';
|
||||
|
||||
export const isEdge = (element: Node | Connection | Edge): element is Edge =>
|
||||
'id' in element && 'source' in element && 'target' in element;
|
||||
|
||||
export const isNode = (element: Node | Connection | Edge): element is Node =>
|
||||
'id' in element && !('source' in element) && !('target' in element);
|
||||
|
||||
export const getOutgoers = <T = any, U extends T = T>(node: Node<U>, nodes: Node<T>[], edges: Edge[]): Node<T>[] => {
|
||||
if (!isNode(node)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const outgoerIds = edges.filter((e) => e.source === node.id).map((e) => e.target);
|
||||
return nodes.filter((n) => outgoerIds.includes(n.id));
|
||||
};
|
||||
|
||||
export const getIncomers = <T = any, U extends T = T>(node: Node<U>, nodes: Node<T>[], edges: Edge[]): Node<T>[] => {
|
||||
if (!isNode(node)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const incomersIds = edges.filter((e) => e.target === node.id).map((e) => e.source);
|
||||
return nodes.filter((n) => incomersIds.includes(n.id));
|
||||
};
|
||||
|
||||
const getEdgeId = ({ source, sourceHandle, target, targetHandle }: Connection): string =>
|
||||
`reactflow__edge-${source}${sourceHandle || ''}-${target}${targetHandle || ''}`;
|
||||
|
||||
export const getMarkerId = (marker: EdgeMarkerType | undefined, rfId?: string): string => {
|
||||
if (typeof marker === 'undefined') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (typeof marker === 'string') {
|
||||
return marker;
|
||||
}
|
||||
|
||||
const idPrefix = rfId ? `${rfId}__` : '';
|
||||
|
||||
return `${idPrefix}${Object.keys(marker)
|
||||
.sort()
|
||||
.map((key: string) => `${key}=${(marker as any)[key]}`)
|
||||
.join('&')}`;
|
||||
};
|
||||
|
||||
const connectionExists = (edge: Edge, edges: Edge[]) => {
|
||||
return edges.some(
|
||||
(el) =>
|
||||
el.source === edge.source &&
|
||||
el.target === edge.target &&
|
||||
(el.sourceHandle === edge.sourceHandle || (!el.sourceHandle && !edge.sourceHandle)) &&
|
||||
(el.targetHandle === edge.targetHandle || (!el.targetHandle && !edge.targetHandle))
|
||||
);
|
||||
};
|
||||
|
||||
export const addEdge = (edgeParams: Edge | Connection, edges: Edge[]): Edge[] => {
|
||||
if (!edgeParams.source || !edgeParams.target) {
|
||||
devWarn('006', errorMessages['006']());
|
||||
|
||||
return edges;
|
||||
}
|
||||
|
||||
let edge: Edge;
|
||||
if (isEdge(edgeParams)) {
|
||||
edge = { ...edgeParams };
|
||||
} else {
|
||||
edge = {
|
||||
...edgeParams,
|
||||
id: getEdgeId(edgeParams),
|
||||
} as Edge;
|
||||
}
|
||||
|
||||
if (connectionExists(edge, edges)) {
|
||||
return edges;
|
||||
}
|
||||
|
||||
return edges.concat(edge);
|
||||
};
|
||||
|
||||
export const updateEdge = (oldEdge: Edge, newConnection: Connection, edges: Edge[]): Edge[] => {
|
||||
if (!newConnection.source || !newConnection.target) {
|
||||
devWarn('006', errorMessages['006']());
|
||||
|
||||
return edges;
|
||||
}
|
||||
|
||||
const foundEdge = edges.find((e) => e.id === oldEdge.id) as Edge;
|
||||
|
||||
if (!foundEdge) {
|
||||
devWarn('007', errorMessages['007'](oldEdge.id));
|
||||
|
||||
return edges;
|
||||
}
|
||||
|
||||
// Remove old edge and create the new edge with parameters of old edge.
|
||||
const edge = {
|
||||
...oldEdge,
|
||||
id: getEdgeId(newConnection),
|
||||
source: newConnection.source,
|
||||
target: newConnection.target,
|
||||
sourceHandle: newConnection.sourceHandle,
|
||||
targetHandle: newConnection.targetHandle,
|
||||
} as Edge;
|
||||
|
||||
return edges.filter((e) => e.id !== oldEdge.id).concat(edge);
|
||||
};
|
||||
|
||||
export const pointToRendererPoint = (
|
||||
{ x, y }: XYPosition,
|
||||
[tx, ty, tScale]: Transform,
|
||||
snapToGrid: boolean,
|
||||
[snapX, snapY]: [number, number]
|
||||
): XYPosition => {
|
||||
const position: XYPosition = {
|
||||
x: (x - tx) / tScale,
|
||||
y: (y - ty) / tScale,
|
||||
};
|
||||
|
||||
if (snapToGrid) {
|
||||
return {
|
||||
x: snapX * Math.round(position.x / snapX),
|
||||
y: snapY * Math.round(position.y / snapY),
|
||||
};
|
||||
}
|
||||
|
||||
return position;
|
||||
};
|
||||
|
||||
export const rendererPointToPoint = ({ x, y }: XYPosition, [tx, ty, tScale]: Transform): XYPosition => {
|
||||
return {
|
||||
x: x * tScale + tx,
|
||||
y: y * tScale + ty,
|
||||
};
|
||||
};
|
||||
|
||||
export const getNodePositionWithOrigin = (
|
||||
node: Node | undefined,
|
||||
nodeOrigin: NodeOrigin = [0, 0]
|
||||
): XYPosition & { positionAbsolute: XYPosition } => {
|
||||
if (!node) {
|
||||
return {
|
||||
x: 0,
|
||||
y: 0,
|
||||
positionAbsolute: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const offsetX = (node.width ?? 0) * nodeOrigin[0];
|
||||
const offsetY = (node.height ?? 0) * nodeOrigin[1];
|
||||
|
||||
const position: XYPosition = {
|
||||
x: node.position.x - offsetX,
|
||||
y: node.position.y - offsetY,
|
||||
};
|
||||
|
||||
return {
|
||||
...position,
|
||||
positionAbsolute: node.positionAbsolute
|
||||
? {
|
||||
x: node.positionAbsolute.x - offsetX,
|
||||
y: node.positionAbsolute.y - offsetY,
|
||||
}
|
||||
: position,
|
||||
};
|
||||
};
|
||||
|
||||
export const getRectOfNodes = (nodes: Node[], nodeOrigin: NodeOrigin = [0, 0]): Rect => {
|
||||
if (nodes.length === 0) {
|
||||
return { x: 0, y: 0, width: 0, height: 0 };
|
||||
}
|
||||
|
||||
const box = nodes.reduce(
|
||||
(currBox, node) => {
|
||||
const { x, y } = getNodePositionWithOrigin(node, nodeOrigin).positionAbsolute;
|
||||
return getBoundsOfBoxes(
|
||||
currBox,
|
||||
rectToBox({
|
||||
x,
|
||||
y,
|
||||
width: node.width || 0,
|
||||
height: node.height || 0,
|
||||
})
|
||||
);
|
||||
},
|
||||
{ x: Infinity, y: Infinity, x2: -Infinity, y2: -Infinity }
|
||||
);
|
||||
|
||||
return boxToRect(box);
|
||||
};
|
||||
|
||||
export const getNodesInside = (
|
||||
nodeInternals: NodeInternals,
|
||||
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,
|
||||
nodeOrigin: NodeOrigin = [0, 0]
|
||||
): Node[] => {
|
||||
const paneRect = {
|
||||
x: (rect.x - tx) / tScale,
|
||||
y: (rect.y - ty) / tScale,
|
||||
width: rect.width / tScale,
|
||||
height: rect.height / tScale,
|
||||
};
|
||||
|
||||
const visibleNodes: Node[] = [];
|
||||
|
||||
nodeInternals.forEach((node) => {
|
||||
const { width, height, selectable = true, hidden = false } = node;
|
||||
|
||||
if ((excludeNonSelectableNodes && !selectable) || hidden) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const { positionAbsolute } = getNodePositionWithOrigin(node, nodeOrigin);
|
||||
|
||||
const nodeRect = {
|
||||
x: positionAbsolute.x,
|
||||
y: positionAbsolute.y,
|
||||
width: width || 0,
|
||||
height: height || 0,
|
||||
};
|
||||
const overlappingArea = getOverlappingArea(paneRect, nodeRect);
|
||||
const notInitialized =
|
||||
typeof width === 'undefined' || typeof height === 'undefined' || width === null || height === null;
|
||||
|
||||
const partiallyVisible = partially && overlappingArea > 0;
|
||||
const area = (width || 0) * (height || 0);
|
||||
const isVisible = notInitialized || partiallyVisible || overlappingArea >= area;
|
||||
|
||||
if (isVisible || node.dragging) {
|
||||
visibleNodes.push(node);
|
||||
}
|
||||
});
|
||||
|
||||
return visibleNodes;
|
||||
};
|
||||
|
||||
export const getConnectedEdges = (nodes: Node[], edges: Edge[]): Edge[] => {
|
||||
const nodeIds = nodes.map((node) => node.id);
|
||||
|
||||
return edges.filter((edge) => nodeIds.includes(edge.source) || nodeIds.includes(edge.target));
|
||||
};
|
||||
|
||||
export const getTransformForBounds = (
|
||||
bounds: Rect,
|
||||
width: number,
|
||||
height: number,
|
||||
minZoom: number,
|
||||
maxZoom: number,
|
||||
padding = 0.1
|
||||
): Transform => {
|
||||
const xZoom = width / (bounds.width * (1 + padding));
|
||||
const yZoom = height / (bounds.height * (1 + padding));
|
||||
const zoom = Math.min(xZoom, yZoom);
|
||||
const clampedZoom = clamp(zoom, minZoom, maxZoom);
|
||||
const boundsCenterX = bounds.x + bounds.width / 2;
|
||||
const boundsCenterY = bounds.y + bounds.height / 2;
|
||||
const x = width / 2 - boundsCenterX * clampedZoom;
|
||||
const y = height / 2 - boundsCenterY * clampedZoom;
|
||||
|
||||
return [x, y, clampedZoom];
|
||||
};
|
||||
|
||||
export const getD3Transition = (selection: D3Selection<Element, unknown, null, undefined>, duration = 0) => {
|
||||
return selection.transition().duration(duration);
|
||||
};
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './graph';
|
||||
export * from './utils';
|
||||
@@ -0,0 +1,127 @@
|
||||
import type {
|
||||
KeyboardEvent as ReactKeyboardEvent,
|
||||
MouseEvent as ReactMouseEvent,
|
||||
TouchEvent as ReactTouchEvent,
|
||||
} from 'react';
|
||||
import type { Dimensions, Node, XYPosition, CoordinateExtent, Box, Rect } from '@reactflow/system';
|
||||
|
||||
export const getDimensions = (node: HTMLDivElement): Dimensions => ({
|
||||
width: node.offsetWidth,
|
||||
height: node.offsetHeight,
|
||||
});
|
||||
|
||||
export const clamp = (val: number, min = 0, max = 1): number => Math.min(Math.max(val, min), max);
|
||||
|
||||
export const clampPosition = (position: XYPosition = { x: 0, y: 0 }, extent: CoordinateExtent) => ({
|
||||
x: clamp(position.x, extent[0][0], extent[1][0]),
|
||||
y: clamp(position.y, extent[0][1], extent[1][1]),
|
||||
});
|
||||
|
||||
// returns a number between 0 and 1 that represents the velocity of the movement
|
||||
// when the mouse is close to the edge of the canvas
|
||||
const calcAutoPanVelocity = (value: number, min: number, max: number): number => {
|
||||
if (value < min) {
|
||||
return clamp(Math.abs(value - min), 1, 50) / 50;
|
||||
} else if (value > max) {
|
||||
return -clamp(Math.abs(value - max), 1, 50) / 50;
|
||||
}
|
||||
|
||||
return 0;
|
||||
};
|
||||
|
||||
export const calcAutoPan = (pos: XYPosition, bounds: Dimensions): number[] => {
|
||||
const xMovement = calcAutoPanVelocity(pos.x, 35, bounds.width - 35) * 20;
|
||||
const yMovement = calcAutoPanVelocity(pos.y, 35, bounds.height - 35) * 20;
|
||||
|
||||
return [xMovement, yMovement];
|
||||
};
|
||||
|
||||
export const getHostForElement = (element: HTMLElement): Document | ShadowRoot =>
|
||||
(element.getRootNode?.() as Document | ShadowRoot) || window?.document;
|
||||
|
||||
export const getBoundsOfBoxes = (box1: Box, box2: Box): Box => ({
|
||||
x: Math.min(box1.x, box2.x),
|
||||
y: Math.min(box1.y, box2.y),
|
||||
x2: Math.max(box1.x2, box2.x2),
|
||||
y2: Math.max(box1.y2, box2.y2),
|
||||
});
|
||||
|
||||
export const rectToBox = ({ x, y, width, height }: Rect): Box => ({
|
||||
x,
|
||||
y,
|
||||
x2: x + width,
|
||||
y2: y + height,
|
||||
});
|
||||
|
||||
export const boxToRect = ({ x, y, x2, y2 }: Box): Rect => ({
|
||||
x,
|
||||
y,
|
||||
width: x2 - x,
|
||||
height: y2 - y,
|
||||
});
|
||||
|
||||
export const nodeToRect = (node: Node): Rect => ({
|
||||
...(node.positionAbsolute || { x: 0, y: 0 }),
|
||||
width: node.width || 0,
|
||||
height: node.height || 0,
|
||||
});
|
||||
|
||||
export const getBoundsOfRects = (rect1: Rect, rect2: Rect): Rect =>
|
||||
boxToRect(getBoundsOfBoxes(rectToBox(rect1), rectToBox(rect2)));
|
||||
|
||||
export const getOverlappingArea = (rectA: Rect, rectB: Rect): number => {
|
||||
const xOverlap = Math.max(0, Math.min(rectA.x + rectA.width, rectB.x + rectB.width) - Math.max(rectA.x, rectB.x));
|
||||
const yOverlap = Math.max(0, Math.min(rectA.y + rectA.height, rectB.y + rectB.height) - Math.max(rectA.y, rectB.y));
|
||||
|
||||
return Math.ceil(xOverlap * yOverlap);
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export const isRectObject = (obj: any): obj is Rect =>
|
||||
isNumeric(obj.width) && isNumeric(obj.height) && isNumeric(obj.x) && isNumeric(obj.y);
|
||||
|
||||
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
|
||||
export const isNumeric = (n: any): n is number => !isNaN(n) && isFinite(n);
|
||||
|
||||
// used for a11y key board controls for nodes and edges
|
||||
export const elementSelectionKeys = ['Enter', ' ', 'Escape'];
|
||||
|
||||
export const devWarn = (id: string, message: string) => {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.warn(`[React Flow]: ${message} Help: https://reactflow.dev/error#${id}`);
|
||||
}
|
||||
};
|
||||
|
||||
const isReactKeyboardEvent = (event: KeyboardEvent | ReactKeyboardEvent): event is ReactKeyboardEvent =>
|
||||
'nativeEvent' in event;
|
||||
|
||||
export function isInputDOMNode(event: KeyboardEvent | ReactKeyboardEvent): boolean {
|
||||
const kbEvent = isReactKeyboardEvent(event) ? event.nativeEvent : event;
|
||||
// using composed path for handling shadow dom
|
||||
const target = (kbEvent.composedPath?.()?.[0] || event.target) as HTMLElement;
|
||||
|
||||
const isInput = ['INPUT', 'SELECT', 'TEXTAREA'].includes(target?.nodeName) || target?.hasAttribute('contenteditable');
|
||||
// we want to be able to do a multi selection event if we are in an input field
|
||||
const isModifierKey = event.ctrlKey || event.metaKey || event.shiftKey;
|
||||
|
||||
// when an input field is focused we don't want to trigger deletion or movement of nodes
|
||||
return (isInput && !isModifierKey) || !!target?.closest('.nokey');
|
||||
}
|
||||
|
||||
export const isMouseEvent = (
|
||||
event: MouseEvent | ReactMouseEvent | TouchEvent | ReactTouchEvent
|
||||
): event is MouseEvent | ReactMouseEvent => 'clientX' in event;
|
||||
|
||||
export const getEventPosition = (
|
||||
event: MouseEvent | ReactMouseEvent | TouchEvent | ReactTouchEvent,
|
||||
bounds?: DOMRect
|
||||
) => {
|
||||
const isMouseTriggered = isMouseEvent(event);
|
||||
const evtX = isMouseTriggered ? event.clientX : event.touches?.[0].clientX;
|
||||
const evtY = isMouseTriggered ? event.clientY : event.touches?.[0].clientY;
|
||||
|
||||
return {
|
||||
x: evtX - (bounds?.left ?? 0),
|
||||
y: evtY - (bounds?.top ?? 0),
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user