Merge branch 'main' into drag-edge

This commit is contained in:
Moritz Klack
2020-11-03 19:59:18 +01:00
committed by GitHub
161 changed files with 30109 additions and 48700 deletions
+4 -4
View File
@@ -15,6 +15,7 @@ import {
interface ConnectionLineProps {
connectionNodeId: ElementId;
connectionHandleId: ElementId | null;
connectionHandleType: HandleType;
connectionPositionX: number;
connectionPositionY: number;
@@ -28,6 +29,7 @@ interface ConnectionLineProps {
export default ({
connectionNodeId,
connectionHandleId,
connectionHandleType,
connectionLineStyle,
connectionPositionX,
@@ -39,10 +41,8 @@ export default ({
CustomConnectionLineComponent,
}: ConnectionLineProps) => {
const [sourceNode, setSourceNode] = useState<Node | null>(null);
const hasHandleId = connectionNodeId.includes('__');
const sourceIdSplitted = connectionNodeId.split('__');
const nodeId = sourceIdSplitted[0];
const handleId = hasHandleId ? sourceIdSplitted[1] : null;
const nodeId = connectionNodeId;
const handleId = connectionHandleId;
useEffect(() => {
const nextSourceNode = nodes.find((n) => n.id === nodeId) || null;
+34 -23
View File
@@ -28,7 +28,7 @@ interface BaseHandleProps {
setConnectionNodeId: SetSourceIdFunc;
setPosition: (pos: XYPosition) => void;
isValidConnection: ValidConnectionFunc;
id?: ElementId | boolean;
id?: ElementId | null;
className?: string;
style?: CSSProperties;
}
@@ -42,6 +42,7 @@ type Result = {
export function onMouseDown(
event: ReactMouseEvent,
handleId: ElementId | null,
nodeId: ElementId,
setConnectionNodeId: SetSourceIdFunc,
setPosition: (pos: XYPosition) => void,
@@ -66,8 +67,9 @@ export function onMouseDown(
x: event.clientX - containerBounds.left,
y: event.clientY - containerBounds.top,
});
setConnectionNodeId({ connectionNodeId: nodeId, connectionHandleType: handleType });
setConnectionNodeId({ connectionNodeId: nodeId, connectionHandleId: handleId, connectionHandleType: handleType });
if (onConnectStart) {
onConnectStart(event, { nodeId, handleType });
}
@@ -88,26 +90,33 @@ export function onMouseDown(
const result: Result = {
elementBelow,
isValid: false,
connection: { source: null, target: null },
connection: { source: null, target: null, sourceHandle: null, targetHandle: null },
isHoveringHandle: false,
};
if (elementBelow && (elementBelow.classList.contains('target') || elementBelow.classList.contains('source'))) {
let connection: Connection = { source: null, target: null };
if (isTarget) {
const sourceId = elementBelow.getAttribute('data-nodeid');
connection = { source: sourceId, target: nodeId };
} else {
const targetId = elementBelow.getAttribute('data-nodeid');
connection = { source: nodeId, target: targetId };
}
const isValid = isValidConnection(connection);
result.connection = connection;
result.isValid = isValid;
result.isHoveringHandle = true;
if (
(isTarget && elementBelow.classList.contains('source')) ||
(!isTarget && elementBelow.classList.contains('target'))
) {
let connection: Connection = { source: null, target: null, sourceHandle: null, targetHandle: null };
if (isTarget) {
const sourceId = elementBelow.getAttribute('data-nodeid');
const sourcehandleId = elementBelow.getAttribute('data-handleid');
connection = { source: sourceId, sourceHandle: sourcehandleId, target: nodeId, targetHandle: handleId };
} else {
const targetId = elementBelow.getAttribute('data-nodeid');
const targetHandleId = elementBelow.getAttribute('data-handleid');
connection = { source: nodeId, sourceHandle: handleId, target: targetId, targetHandle: targetHandleId };
}
const isValid = isValidConnection(connection);
result.connection = connection;
result.isValid = isValid;
}
}
return result;
@@ -150,7 +159,7 @@ export function onMouseDown(
}
resetRecentHandle();
setConnectionNodeId({ connectionNodeId: null, connectionHandleType: null });
setConnectionNodeId({ connectionNodeId: null, connectionHandleId: null, connectionHandleType: null });
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
@@ -171,7 +180,7 @@ const BaseHandle = ({
setConnectionNodeId,
setPosition,
className,
id = false,
id = null,
isValidConnection,
...rest
}: BaseHandleProps) => {
@@ -187,17 +196,19 @@ const BaseHandle = ({
},
]);
const nodeIdWithHandleId = id ? `${nodeId}__${id}` : nodeId;
const handleId = id || null;
return (
<div
data-nodeid={nodeIdWithHandleId}
data-handleid={handleId}
data-nodeid={nodeId}
data-handlepos={position}
className={handleClasses}
onMouseDown={(event) =>
onMouseDown(
event,
nodeIdWithHandleId,
handleId,
nodeId,
setConnectionNodeId,
setPosition,
onConnect,
+3 -10
View File
@@ -19,21 +19,14 @@ export const getHandleBounds = (
(handle): HandleElement => {
const bounds = handle.getBoundingClientRect();
const dimensions = getDimensions(handle);
const nodeIdAttr = handle.getAttribute('data-nodeid');
const handleId = handle.getAttribute('data-handleid');
const handlePosition = (handle.getAttribute('data-handlepos') as unknown) as Position;
const nodeIdSplitted = nodeIdAttr ? nodeIdAttr.split('__') : null;
let handleId = null;
if (nodeIdSplitted) {
handleId = (nodeIdSplitted.length ? nodeIdSplitted[1] : nodeIdSplitted) as string;
}
return {
id: handleId,
position: handlePosition,
x: (bounds.left - parentBounds.left) * (1 / k),
y: (bounds.top - parentBounds.top) * (1 / k),
x: (bounds.left - parentBounds.left) / k,
y: (bounds.top - parentBounds.top) / k,
...dimensions,
};
}
+1
View File
@@ -218,6 +218,7 @@ export default (NodeComponent: ComponentType<NodeComponentProps>) => {
isConnectable={isConnectable}
sourcePosition={sourcePosition}
targetPosition={targetPosition}
isDragging={isDragging}
/>
</Provider>
</div>
+24 -4
View File
@@ -102,6 +102,10 @@ function getHandle(bounds: HandleElement[], handleId: ElementId | null): HandleE
handle = bounds.find((d) => d.id === handleId);
}
if (typeof handle === 'undefined') {
return null;
}
return handle;
}
@@ -138,18 +142,22 @@ function renderEdge(
setConnectionNodeId: SetSourceIdFunc,
setPosition: (pos: XYPosition) => void,
) {
const [sourceId, sourceHandleId] = edge.source.split('__');
const [targetId, targetHandleId] = edge.target.split('__');
const sourceId = edge.source;
const sourceHandleId = edge.sourceHandle || null;
const targetId = edge.target;
const targetHandleId = edge.targetHandle || null;
const sourceNode = nodes.find((n) => n.id === sourceId);
const targetNode = nodes.find((n) => n.id === targetId);
if (!sourceNode) {
throw new Error(`couldn't create edge for source id: ${sourceId}`);
console.warn(`couldn't create edge for source id: ${sourceId}`);
return null;
}
if (!targetNode) {
throw new Error(`couldn't create edge for target id: ${targetId}`);
console.warn(`couldn't create edge for target id: ${targetId}`);
return null;
}
if (!sourceNode.__rf.width || !sourceNode.__rf.height) {
@@ -163,6 +171,16 @@ function renderEdge(
const sourcePosition = sourceHandle ? sourceHandle.position : Position.Bottom;
const targetPosition = targetHandle ? targetHandle.position : Position.Top;
if (!sourceHandle) {
console.warn(`couldn't create edge for source handle id: ${sourceHandleId}`);
return null;
}
if (!targetHandle) {
console.warn(`couldn't create edge for source handle id: ${targetHandleId}`);
return null;
}
const { sourceX, sourceY, targetX, targetY } = getEdgePositions(
sourceNode,
sourceHandle,
@@ -239,6 +257,7 @@ const EdgeRenderer = (props: EdgeRendererProps) => {
const edges = useStoreState((state) => state.edges);
const nodes = useStoreState((state) => state.nodes);
const connectionNodeId = useStoreState((state) => state.connectionNodeId);
const connectionHandleId = useStoreState((state) => state.connectionHandleId);
const connectionHandleType = useStoreState((state) => state.connectionHandleType);
const connectionPosition = useStoreState((state) => state.connectionPosition);
const selectedElements = useStoreState((state) => state.selectedElements);
@@ -276,6 +295,7 @@ const EdgeRenderer = (props: EdgeRendererProps) => {
<ConnectionLine
nodes={nodes}
connectionNodeId={connectionNodeId!}
connectionHandleId={connectionHandleId}
connectionHandleType={connectionHandleType!}
connectionPositionX={connectionPosition.x}
connectionPositionY={connectionPosition.y}
+22 -29
View File
@@ -1,12 +1,11 @@
import React, { useCallback, useRef, memo, ReactNode, WheelEvent, MouseEvent } from 'react';
import React, { useCallback, memo, ReactNode, WheelEvent, MouseEvent } from 'react';
import { useStoreActions, useStoreState } from '../../store/hooks';
import useResizeHandler from '../../hooks/useResizeHandler';
import useGlobalKeyHandler from '../../hooks/useGlobalKeyHandler';
import useD3Zoom from '../../hooks/useD3Zoom';
import useKeyPress from '../../hooks/useKeyPress';
import { GraphViewProps } from '../GraphView';
import ZoomPane from '../ZoomPane';
import UserSelection from '../../components/UserSelection';
import NodesSelection from '../../components/NodesSelection';
@@ -36,7 +35,10 @@ const FlowRenderer = ({
onMoveStart,
onMoveEnd,
selectionKeyCode,
elementsSelectable,
zoomOnScroll,
panOnScroll,
panOnScrollSpeed,
zoomOnDoubleClick,
paneMoveable,
defaultPosition,
@@ -47,29 +49,12 @@ const FlowRenderer = ({
onSelectionDragStop,
onSelectionContextMenu,
}: FlowRendererProps) => {
const zoomPane = useRef<HTMLDivElement>(null);
const rendererNode = useRef<HTMLDivElement>(null);
const unsetNodesSelection = useStoreActions((actions) => actions.unsetNodesSelection);
const nodesSelectionActive = useStoreState((state) => state.nodesSelectionActive);
const selectionKeyPressed = useKeyPress(selectionKeyCode);
useResizeHandler(rendererNode);
useGlobalKeyHandler({ onElementsRemove, deleteKeyCode });
useD3Zoom({
zoomPane,
onMove,
onMoveStart,
onMoveEnd,
selectionKeyPressed,
zoomOnScroll,
zoomOnDoubleClick,
paneMoveable,
defaultPosition,
defaultZoom,
translateExtent,
});
const onClick = useCallback(
(event: MouseEvent) => {
onPaneClick?.(event);
@@ -93,7 +78,21 @@ const FlowRenderer = ({
);
return (
<div className="react-flow__renderer" ref={rendererNode}>
<ZoomPane
onMove={onMove}
onMoveStart={onMoveStart}
onMoveEnd={onMoveEnd}
selectionKeyPressed={selectionKeyPressed}
elementsSelectable={elementsSelectable}
zoomOnScroll={zoomOnScroll}
panOnScroll={panOnScroll}
panOnScrollSpeed={panOnScrollSpeed}
zoomOnDoubleClick={zoomOnDoubleClick}
paneMoveable={paneMoveable}
defaultPosition={defaultPosition}
defaultZoom={defaultZoom}
translateExtent={translateExtent}
>
{children}
<UserSelection selectionKeyPressed={selectionKeyPressed} />
{nodesSelectionActive && (
@@ -104,14 +103,8 @@ const FlowRenderer = ({
onSelectionContextMenu={onSelectionContextMenu}
/>
)}
<div
className="react-flow__pane"
onClick={onClick}
onContextMenu={onContextMenu}
onWheel={onWheel}
ref={zoomPane}
/>
</div>
<div className="react-flow__pane" onClick={onClick} onContextMenu={onContextMenu} onWheel={onWheel} />
</ZoomPane>
);
};
+7
View File
@@ -71,6 +71,8 @@ export interface GraphViewProps {
arrowHeadColor: string;
markerEndId?: string;
zoomOnScroll?: boolean;
panOnScroll?: boolean;
panOnScrollSpeed?: number;
zoomOnDoubleClick?: boolean;
paneMoveable?: boolean;
onEdgeUpdate?: OnEdgeUpdateFunc;
@@ -120,6 +122,8 @@ const GraphView = ({
arrowHeadColor,
markerEndId,
zoomOnScroll,
panOnScroll,
panOnScrollSpeed,
zoomOnDoubleClick,
paneMoveable,
onPaneClick,
@@ -248,11 +252,14 @@ const GraphView = ({
onElementsRemove={onElementsRemove}
deleteKeyCode={deleteKeyCode}
selectionKeyCode={selectionKeyCode}
elementsSelectable={elementsSelectable}
onMove={onMove}
onMoveStart={onMoveStart}
onMoveEnd={onMoveEnd}
zoomOnScroll={zoomOnScroll}
zoomOnDoubleClick={zoomOnDoubleClick}
panOnScroll={panOnScroll}
panOnScrollSpeed={panOnScrollSpeed}
paneMoveable={paneMoveable}
defaultPosition={defaultPosition}
defaultZoom={defaultZoom}
+7 -1
View File
@@ -1,7 +1,7 @@
import React, { useMemo, CSSProperties, HTMLAttributes, MouseEvent, WheelEvent } from 'react';
import cc from 'classcat';
const nodeEnv: string = process.env.NODE_ENV as string;
const nodeEnv: string = (typeof __ENV__ !== 'undefined' && __ENV__) as string;
if (nodeEnv !== 'production') {
const whyDidYouRender = require('@welldone-software/why-did-you-render');
@@ -99,6 +99,8 @@ export interface ReactFlowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'on
arrowHeadColor?: string;
markerEndId?: string;
zoomOnScroll?: boolean;
panOnScroll?: boolean;
panOnScrollSpeed?: number;
zoomOnDoubleClick?: boolean;
onEdgeUpdate?: OnEdgeUpdateFunc;
}
@@ -149,6 +151,8 @@ const ReactFlow = ({
arrowHeadColor = '#b1b1b7',
markerEndId,
zoomOnScroll = true,
panOnScroll = false,
panOnScrollSpeed = 0.5,
zoomOnDoubleClick = true,
paneMoveable = true,
onPaneClick,
@@ -206,6 +210,8 @@ const ReactFlow = ({
markerEndId={markerEndId}
zoomOnScroll={zoomOnScroll}
zoomOnDoubleClick={zoomOnDoubleClick}
panOnScroll={panOnScroll}
panOnScrollSpeed={panOnScrollSpeed}
paneMoveable={paneMoveable}
onPaneClick={onPaneClick}
onPaneScroll={onPaneScroll}
@@ -1,12 +1,15 @@
import { useEffect, useRef, MutableRefObject } from 'react';
import React, { useEffect, useRef, ReactNode } from 'react';
import { useStoreState, useStoreActions } from '../store/hooks';
import { FlowTransform, TranslateExtent } from '../types';
import useResizeHandler from '../../hooks/useResizeHandler';
import { useStoreState, useStoreActions } from '../../store/hooks';
import { FlowTransform, TranslateExtent } from '../../types';
interface UseD3ZoomParams {
zoomPane: MutableRefObject<Element | null>;
interface ZoomPaneProps {
selectionKeyPressed: boolean;
elementsSelectable?: boolean;
zoomOnScroll?: boolean;
panOnScroll?: boolean;
panOnScrollSpeed?: number;
zoomOnDoubleClick?: boolean;
paneMoveable?: boolean;
defaultPosition?: [number, number];
@@ -15,6 +18,7 @@ interface UseD3ZoomParams {
onMove?: (flowTransform?: FlowTransform) => void;
onMoveStart?: (flowTransform?: FlowTransform) => void;
onMoveEnd?: (flowTransform?: FlowTransform) => void;
children: ReactNode;
}
const viewChanged = (prevTransform: FlowTransform, eventTransform: any): boolean =>
@@ -28,31 +32,63 @@ const eventToFlowTransform = (eventTransform: any): FlowTransform => ({
zoom: eventTransform.k,
});
export default ({
zoomPane,
const ZoomPane = ({
onMove,
onMoveStart,
onMoveEnd,
zoomOnScroll = true,
panOnScroll = false,
panOnScrollSpeed = 0.5,
zoomOnDoubleClick = true,
selectionKeyPressed,
elementsSelectable,
paneMoveable = true,
defaultPosition = [0, 0],
defaultZoom = 1,
translateExtent,
}: UseD3ZoomParams): void => {
children,
}: ZoomPaneProps) => {
const zoomPane = useRef<HTMLDivElement>(null);
const prevTransform = useRef<FlowTransform>({ x: 0, y: 0, zoom: 0 });
const d3Zoom = useStoreState((s) => s.d3Zoom);
const d3Selection = useStoreState((s) => s.d3Selection);
const d3ZoomHandler = useStoreState((s) => s.d3ZoomHandler);
const initD3 = useStoreActions((actions) => actions.initD3);
const updateTransform = useStoreActions((actions) => actions.updateTransform);
useResizeHandler(zoomPane);
useEffect(() => {
if (zoomPane.current) {
initD3({ zoomPane: zoomPane.current, defaultPosition, defaultZoom, translateExtent });
}
}, []);
useEffect(() => {
if (d3Selection && d3Zoom) {
if (panOnScroll) {
d3Selection
.on('wheel', (event: any) => {
event.preventDefault();
event.stopImmediatePropagation();
const currentZoom = d3Selection.property('__zoom').k || 1;
d3Zoom.translateBy(
d3Selection,
(event.wheelDeltaX / currentZoom) * panOnScrollSpeed,
(event.wheelDeltaY / currentZoom) * panOnScrollSpeed
);
})
.on('wheel.zoom', null);
} else if (typeof d3ZoomHandler !== 'undefined') {
d3Selection.on('wheel', null).on('wheel.zoom', d3ZoomHandler);
}
}
}, [panOnScroll, d3Selection, d3Zoom, d3ZoomHandler]);
useEffect(() => {
if (d3Zoom) {
if (selectionKeyPressed) {
@@ -107,34 +143,52 @@ export default ({
useEffect(() => {
if (d3Zoom) {
d3Zoom.filter((event: any) => {
// if all interactions are disabled, we prevent all zoom events
if (!paneMoveable && !zoomOnScroll && !panOnScroll && !zoomOnDoubleClick) {
return false;
}
// during a selection we prevent all other interactions
if (selectionKeyPressed) {
return false;
}
// only allow zoom on nodes
if (event.target.closest('.react-flow__node') && event.type !== 'wheel') {
return false;
}
// only allow zoom on user selection
if (event.target.closest('.react-flow__nodesselection') && event.type !== 'wheel') {
return false;
}
if (!paneMoveable) {
return false;
}
if (!zoomOnScroll && event.type === 'wheel') {
return false;
}
// if zoom on double click is disabled, we prevent the double click event
if (!zoomOnDoubleClick && event.type === 'dblclick') {
return false;
}
// when the target element is a node, we still allow zooming
if (event.target.closest('.react-flow__node') && event.type !== 'wheel') {
return false;
}
// when the target element is a node selection, we still allow zooming
if (event.target.closest('.react-flow__nodesselection') && event.type !== 'wheel') {
return false;
}
// when there is no scroll handling enabled, we prevent all wheel events
if (!zoomOnScroll && !panOnScroll && event.type === 'wheel') {
return false;
}
// if the pane is not movable, we prevent dragging it with the mouse
if (!paneMoveable && event.type === 'mousedown') {
return false;
}
// default filter for d3-zoom, prevents zooming on buttons and when ctrl is pressed
return !event.ctrlKey && !event.button;
});
}
}, [d3Zoom, zoomOnScroll, zoomOnDoubleClick, paneMoveable, selectionKeyPressed]);
}, [d3Zoom, zoomOnScroll, panOnScroll, zoomOnDoubleClick, paneMoveable, selectionKeyPressed, elementsSelectable]);
return (
<div className="react-flow__renderer react-flow__zoompane" ref={zoomPane}>
{children}
</div>
);
};
export default ZoomPane;
+2 -1
View File
@@ -3,7 +3,7 @@ declare module '*.css' {
export default content;
}
interface SvgrComponent extends React.StatelessComponent<React.SVGAttributes<SVGElement>> {}
interface SvgrComponent extends React.FunctionComponent<React.SVGAttributes<SVGElement>> {}
declare module '*.svg' {
const svgUrl: string;
@@ -13,3 +13,4 @@ declare module '*.svg' {
}
declare var __REACT_FLOW_VERSION__: string;
declare var __ENV__: string;
+13 -5
View File
@@ -1,6 +1,6 @@
import { createStore, Action, action, Thunk, thunk, computed, Computed } from 'easy-peasy';
import isEqual from 'fast-deep-equal';
import { Selection as D3Selection, ZoomBehavior } from 'd3';
import { Selection as D3Selection, ZoomBehavior, ValueFn } from 'd3';
import { zoom, zoomIdentity } from 'd3-zoom';
import { select } from 'd3-selection';
@@ -61,6 +61,7 @@ export interface StoreModel {
d3Zoom: ZoomBehavior<Element, unknown> | null;
d3Selection: D3Selection<Element, unknown, null, undefined> | null;
d3ZoomHandler: ValueFn<Element, unknown, void> | undefined;
d3Initialised: boolean;
minZoom: number;
maxZoom: number;
@@ -72,6 +73,7 @@ export interface StoreModel {
userSelectionRect: SelectionRect;
connectionNodeId: ElementId | null;
connectionHandleId: ElementId | null;
connectionHandleType: HandleType | null;
connectionPosition: XYPosition;
@@ -157,6 +159,7 @@ export const storeModel: StoreModel = {
d3Zoom: null,
d3Selection: null,
d3Initialised: false,
d3ZoomHandler: () => {},
minZoom: 0.5,
maxZoom: 2,
translateExtent: [
@@ -177,6 +180,7 @@ export const storeModel: StoreModel = {
draw: false,
},
connectionNodeId: null,
connectionHandleId: null,
connectionHandleType: 'source',
connectionPosition: { x: 0, y: 0 },
@@ -288,8 +292,8 @@ export const storeModel: StoreModel = {
...state.userSelectionRect,
x: negativeX ? mousePos.x : state.userSelectionRect.x,
y: negativeY ? mousePos.y : state.userSelectionRect.y,
width: negativeX ? startX - mousePos.x : mousePos.x - startX,
height: negativeY ? startY - mousePos.y : mousePos.y - startY,
width: Math.abs(mousePos.x - startX),
height: Math.abs(mousePos.y - startY),
};
const selectedNodes = getNodesInside(state.nodes, nextRect, state.transform);
@@ -380,11 +384,14 @@ export const storeModel: StoreModel = {
const updatedTransform = zoomIdentity.translate(clampedX, clampedY).scale(clampedZoom);
selection.property('__zoom', updatedTransform);
const defaultHandler = selection.on('wheel.zoom');
state.transform[0] = clampedX;
state.transform[1] = clampedY;
state.transform[2] = clampedZoom;
state.d3Zoom = d3ZoomInstance;
state.d3Selection = selection;
state.d3ZoomHandler = defaultHandler;
state.d3Initialised = true;
}),
@@ -416,8 +423,9 @@ export const storeModel: StoreModel = {
state.connectionPosition = position;
}),
setConnectionNodeId: action((state, { connectionNodeId, connectionHandleType }) => {
setConnectionNodeId: action((state, { connectionNodeId, connectionHandleId, connectionHandleType }) => {
state.connectionNodeId = connectionNodeId;
state.connectionHandleId = connectionHandleId;
state.connectionHandleType = connectionHandleType;
}),
@@ -511,7 +519,7 @@ export const storeModel: StoreModel = {
}),
};
const nodeEnv: string = process.env.NODE_ENV as string;
const nodeEnv: string = (typeof __ENV__ !== 'undefined' && __ENV__) as string;
const store = createStore(storeModel, { devTools: nodeEnv === 'development' });
export default store;
+8 -1
View File
@@ -60,6 +60,8 @@ export interface Edge {
type?: string;
source: ElementId;
target: ElementId;
sourceHandle?: ElementId | null;
targetHandle?: ElementId | null;
label?: string;
labelStyle?: CSSProperties;
labelShowBg?: boolean;
@@ -168,6 +170,7 @@ export interface NodeProps {
isConnectable: boolean;
targetPosition?: Position;
sourcePosition?: Position;
isDragging?: boolean;
}
export interface NodeComponentProps {
@@ -189,6 +192,7 @@ export interface NodeComponentProps {
onNodeDragStart?: (node: Node) => void;
onNodeDragStop?: (node: Node) => void;
style?: CSSProperties;
isDragging?: boolean;
}
export interface WrapNodeProps {
@@ -242,6 +246,8 @@ export type OnLoadFunc = (params: OnLoadParams) => void;
export interface Connection {
source: ElementId | null;
target: ElementId | null;
sourceHandle: ElementId | null;
targetHandle: ElementId | null;
}
export enum ConnectionLineType {
@@ -275,6 +281,7 @@ export type OnConnectEndFunc = (event: MouseEvent) => void;
export type SetConnectionId = {
connectionNodeId: ElementId | null;
connectionHandleId: ElementId | null;
connectionHandleType: HandleType | null;
};
@@ -289,7 +296,7 @@ export interface HandleProps {
isConnectable?: boolean;
onConnect?: OnConnectFunc;
isValidConnection?: (connection: Connection) => boolean;
id?: string;
id?: ElementId;
style?: CSSProperties;
className?: string;
}
+28 -16
View File
@@ -40,29 +40,39 @@ export const removeElements = (elementsToRemove: Elements, elements: Elements):
});
};
const getEdgeId = ({ source, target }: Connection): ElementId => `reactflow__edge-${source}-${target}`;
const getEdgeId = ({ source, sourceHandle, target, targetHandle }: Connection): ElementId =>
`reactflow__edge-${source}${sourceHandle}-${target}${targetHandle}`;
const connectionExists = (edge: Edge, elements: Elements) => {
return elements.some(
(el) =>
isEdge(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, elements: Elements): Elements => {
if (!edgeParams.source || !edgeParams.target) {
throw new Error("Can't create edge. An edge needs a source and a target.");
console.warn("Can't create edge. An edge needs a source and a target.");
return elements;
}
// make sure that there is node with the target and one with the source id
[edgeParams.source, edgeParams.target].forEach((id) => {
const nodeId = id.includes('__') ? id.split('__')[0] : id;
if (!elements.find((e) => isNode(e) && e.id === nodeId)) {
throw new Error(`Can't create edge. Node with id=${nodeId} does not exist.`);
}
});
let edge: Edge;
if (isEdge(edgeParams)) {
return elements.concat({ ...edgeParams });
edge = { ...edgeParams };
} else {
edge = {
...edgeParams,
id: getEdgeId(edgeParams),
} as Edge;
}
const edge = {
...edgeParams,
id: getEdgeId(edgeParams),
} as Edge;
if (connectionExists(edge, elements)) {
return elements;
}
return elements.concat(edge);
};
@@ -143,6 +153,8 @@ export const parseElement = (element: Node | Edge): Node | Edge => {
...element,
source: element.source.toString(),
target: element.target.toString(),
sourceHandle: element.sourceHandle ? element.sourceHandle.toString() : null,
targetHandle: element.targetHandle ? element.targetHandle.toString() : null,
id: element.id.toString(),
type: element.type || 'default',
};
@@ -218,7 +230,7 @@ export const getNodesInside = (
const nBox = rectToBox({ ...position, width, height });
const xOverlap = Math.max(0, Math.min(rBox.x2, nBox.x2) - Math.max(rBox.x, nBox.x));
const yOverlap = Math.max(0, Math.min(rBox.y2, nBox.y2) - Math.max(rBox.y, nBox.y));
const overlappingArea = xOverlap * yOverlap;
const overlappingArea = Math.ceil(xOverlap * yOverlap);
if (width === null || height === null || isDragging) {
// at the beginnning all nodes have width & height === 0