@@ -6,10 +6,10 @@ const onNodeDragStop = (event, node) => console.log('drag stop', node);
|
||||
const onElementClick = (event, element) => console.log('click', element);
|
||||
|
||||
const initialElements = [
|
||||
{ id: '1', type: 'input', data: { label: 'Node 1' }, position: { x: 250, y: 5 } },
|
||||
{ id: '2', data: { label: 'Node 2' }, position: { x: 100, y: 100 } },
|
||||
{ id: '3', data: { label: 'Node 3' }, position: { x: 400, y: 100 } },
|
||||
{ id: '4', data: { label: 'Node 4' }, position: { x: 400, y: 200 } },
|
||||
{ id: '1', type: 'input', data: { label: 'Node 1' }, position: { x: 250, y: 5 }, className: 'light' },
|
||||
{ id: '2', data: { label: 'Node 2' }, position: { x: 100, y: 100 }, className: 'light' },
|
||||
{ id: '3', data: { label: 'Node 3' }, position: { x: 400, y: 100 }, className: 'light' },
|
||||
{ id: '4', data: { label: 'Node 4' }, position: { x: 400, y: 200 }, className: 'light' },
|
||||
{ id: 'e1-2', source: '1', target: '2', animated: true },
|
||||
{ id: 'e1-3', source: '1', target: '3' },
|
||||
];
|
||||
@@ -40,9 +40,23 @@ const BasicFlow = () => {
|
||||
};
|
||||
|
||||
const logToObject = () => console.log(rfInstance.toObject());
|
||||
|
||||
const resetTransform = () => rfInstance.setTransform({ x: 0, y: 0, zoom: 1 });
|
||||
|
||||
const toggleClassnames = () => {
|
||||
setElements((elms) => {
|
||||
return elms.map((el) => {
|
||||
if (isNode(el)) {
|
||||
return {
|
||||
...el,
|
||||
className: el.className === 'light' ? 'dark' : 'light',
|
||||
};
|
||||
}
|
||||
|
||||
return el;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<ReactFlow
|
||||
elements={elements}
|
||||
@@ -65,6 +79,9 @@ const BasicFlow = () => {
|
||||
<button onClick={updatePos} style={{ marginRight: 5 }}>
|
||||
change pos
|
||||
</button>
|
||||
<button onClick={toggleClassnames} style={{ marginRight: 5 }}>
|
||||
toggle classnames
|
||||
</button>
|
||||
<button onClick={logToObject}>toObject</button>
|
||||
</div>
|
||||
</ReactFlow>
|
||||
|
||||
@@ -33,6 +33,7 @@ const ProviderFlow = () => {
|
||||
onConnect={onConnect}
|
||||
onElementsRemove={onElementsRemove}
|
||||
onLoad={onLoad}
|
||||
connectionMode="loose"
|
||||
>
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
|
||||
57
example/src/UpdatableEdge/index.js
Normal file
57
example/src/UpdatableEdge/index.js
Normal file
@@ -0,0 +1,57 @@
|
||||
import React, { useState } from 'react';
|
||||
import ReactFlow, { Controls, updateEdge, addEdge } from 'react-flow-renderer';
|
||||
|
||||
const initialElements = [
|
||||
{
|
||||
id: '1',
|
||||
type: 'input',
|
||||
data: {
|
||||
label: (
|
||||
<>
|
||||
Node <strong>A</strong>
|
||||
</>
|
||||
),
|
||||
},
|
||||
position: { x: 250, y: 0 },
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
data: {
|
||||
label: (
|
||||
<>
|
||||
Node <strong>B</strong>
|
||||
</>
|
||||
),
|
||||
},
|
||||
position: { x: 100, y: 100 },
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
data: {
|
||||
label: (
|
||||
<>
|
||||
Node <strong>C</strong>
|
||||
</>
|
||||
),
|
||||
},
|
||||
position: { x: 400, y: 100 },
|
||||
style: { background: '#D6D5E6', color: '#333', border: '1px solid #222138', width: 180 },
|
||||
},
|
||||
{ id: 'e1-2', source: '1', target: '2', label: 'This is a draggable edge' },
|
||||
];
|
||||
|
||||
const onLoad = (reactFlowInstance) => reactFlowInstance.fitView();
|
||||
|
||||
const UpdatableEdge = () => {
|
||||
const [elements, setElements] = useState(initialElements);
|
||||
const onEdgeUpdate = (oldEdge, newConnection) => setElements((els) => updateEdge(oldEdge, newConnection, els));
|
||||
const onConnect = (params) => setElements((els) => addEdge(params, els));
|
||||
|
||||
return (
|
||||
<ReactFlow elements={elements} onLoad={onLoad} snapToGrid={true} onEdgeUpdate={onEdgeUpdate} onConnect={onConnect}>
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
);
|
||||
};
|
||||
|
||||
export default UpdatableEdge;
|
||||
@@ -140,6 +140,11 @@ nav a.active:before {
|
||||
color: #f8f8f8;
|
||||
}
|
||||
|
||||
.react-flow__node.dark {
|
||||
background: #557;
|
||||
color: #f8f8f8;
|
||||
}
|
||||
|
||||
.react-flow__node-selectorNode {
|
||||
font-size: 12px;
|
||||
background: #f0f2f3;
|
||||
|
||||
@@ -15,6 +15,7 @@ import Hidden from './Hidden';
|
||||
import EdgeTypes from './EdgeTypes';
|
||||
import CustomConnectionLine from './CustomConnectionLine';
|
||||
import NodeTypeChange from './NodeTypeChange';
|
||||
import UpdatableEdge from './UpdatableEdge';
|
||||
|
||||
import './index.css';
|
||||
|
||||
@@ -78,6 +79,11 @@ const routes = [
|
||||
path: '/nodetype-change',
|
||||
component: NodeTypeChange,
|
||||
},
|
||||
{
|
||||
path: '/updatable-edge',
|
||||
component: UpdatableEdge,
|
||||
label: 'Updatable Edge',
|
||||
},
|
||||
];
|
||||
|
||||
const navLinks = routes.filter((route) => route.label);
|
||||
|
||||
8794
package-lock.json
generated
8794
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-flow-renderer",
|
||||
"version": "8.0.0",
|
||||
"version": "8.0.0-next.11",
|
||||
"main": "dist/ReactFlow.js",
|
||||
"module": "dist/ReactFlow.esm.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
||||
@@ -55,6 +55,18 @@ export function getSmoothStepPath({
|
||||
let firstCornerPath = null;
|
||||
let secondCornerPath = null;
|
||||
|
||||
if (sourceX <= targetX) {
|
||||
firstCornerPath =
|
||||
sourceY <= targetY ? bottomLeftCorner(sourceX, cY, cornerSize) : topLeftCorner(sourceX, cY, cornerSize);
|
||||
secondCornerPath =
|
||||
sourceY <= targetY ? rightTopCorner(targetX, cY, cornerSize) : rightBottomCorner(targetX, cY, cornerSize);
|
||||
} else {
|
||||
firstCornerPath =
|
||||
sourceY < targetY ? bottomRightCorner(sourceX, cY, cornerSize) : topRightCorner(sourceX, cY, cornerSize);
|
||||
secondCornerPath =
|
||||
sourceY < targetY ? leftTopCorner(targetX, cY, cornerSize) : leftBottomCorner(targetX, cY, cornerSize);
|
||||
}
|
||||
|
||||
if (leftAndRight.includes(sourcePosition) && leftAndRight.includes(targetPosition)) {
|
||||
if (sourceX <= targetX) {
|
||||
firstCornerPath =
|
||||
@@ -88,18 +100,6 @@ export function getSmoothStepPath({
|
||||
: topRightCorner(sourceX, targetY, cornerSize);
|
||||
}
|
||||
secondCornerPath = '';
|
||||
} else {
|
||||
if (sourceX <= targetX) {
|
||||
firstCornerPath =
|
||||
sourceY <= targetY ? bottomLeftCorner(sourceX, cY, cornerSize) : topLeftCorner(sourceX, cY, cornerSize);
|
||||
secondCornerPath =
|
||||
sourceY <= targetY ? rightTopCorner(targetX, cY, cornerSize) : rightBottomCorner(targetX, cY, cornerSize);
|
||||
} else {
|
||||
firstCornerPath =
|
||||
sourceY < targetY ? bottomRightCorner(sourceX, cY, cornerSize) : topRightCorner(sourceX, cY, cornerSize);
|
||||
secondCornerPath =
|
||||
sourceY < targetY ? leftTopCorner(targetX, cY, cornerSize) : leftBottomCorner(targetX, cY, cornerSize);
|
||||
}
|
||||
}
|
||||
|
||||
return `M ${sourceX},${sourceY}${firstCornerPath}${secondCornerPath}L ${targetX},${targetY}`;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import React, { memo, ComponentType, useCallback } from 'react';
|
||||
import React, { memo, ComponentType, useCallback, useState } from 'react';
|
||||
import cc from 'classcat';
|
||||
|
||||
import { useStoreActions } from '../../store/hooks';
|
||||
import { useStoreActions, useStoreState } from '../../store/hooks';
|
||||
import { Edge, EdgeProps, WrapEdgeProps } from '../../types';
|
||||
import { onMouseDown } from '../../components/Handle/handler';
|
||||
|
||||
export default (EdgeComponent: ComponentType<EdgeProps>) => {
|
||||
const EdgeWrapper = ({
|
||||
@@ -32,42 +33,117 @@ export default (EdgeComponent: ComponentType<EdgeProps>) => {
|
||||
elementsSelectable,
|
||||
markerEndId,
|
||||
isHidden,
|
||||
sourceHandleId,
|
||||
targetHandleId,
|
||||
handleEdgeUpdate,
|
||||
onConnectEdge,
|
||||
}: WrapEdgeProps) => {
|
||||
const addSelectedElements = useStoreActions((actions) => actions.addSelectedElements);
|
||||
const setConnectionNodeId = useStoreActions((actions) => actions.setConnectionNodeId);
|
||||
const setPosition = useStoreActions((actions) => actions.setConnectionPosition);
|
||||
const connectionMode = useStoreState((state) => state.connectionMode);
|
||||
|
||||
const [updating, setUpdating] = useState<boolean>(false);
|
||||
|
||||
const inactive = !elementsSelectable && !onClick;
|
||||
const edgeClasses = cc([
|
||||
'react-flow__edge',
|
||||
`react-flow__edge-${type}`,
|
||||
className,
|
||||
{ selected, animated, inactive },
|
||||
{ selected, animated, inactive, updating },
|
||||
]);
|
||||
|
||||
const onEdgeClick = useCallback(
|
||||
(event: React.MouseEvent<SVGGElement, MouseEvent>): void => {
|
||||
const edgeElement: Edge = {
|
||||
id,
|
||||
source,
|
||||
target,
|
||||
type,
|
||||
};
|
||||
|
||||
if (sourceHandleId) {
|
||||
edgeElement.sourceHandle = sourceHandleId;
|
||||
}
|
||||
|
||||
if (targetHandleId) {
|
||||
edgeElement.targetHandle = targetHandleId;
|
||||
}
|
||||
|
||||
if (typeof data !== 'undefined') {
|
||||
edgeElement.data = data;
|
||||
}
|
||||
|
||||
if (elementsSelectable) {
|
||||
addSelectedElements({ id, source, target });
|
||||
addSelectedElements(edgeElement);
|
||||
}
|
||||
|
||||
if (onClick) {
|
||||
const edgeElement: Edge = { id, source, target, type };
|
||||
|
||||
if (typeof data !== 'undefined') {
|
||||
edgeElement.data = data;
|
||||
}
|
||||
|
||||
onClick(event, edgeElement);
|
||||
}
|
||||
onClick?.(event, edgeElement);
|
||||
},
|
||||
[elementsSelectable, id, source, target, type, data, onClick]
|
||||
[elementsSelectable, id, source, target, type, data, sourceHandleId, targetHandleId, onClick]
|
||||
);
|
||||
|
||||
const handleEdgeUpdater = useCallback(
|
||||
(event: React.MouseEvent<SVGGElement, MouseEvent>, isSourceHandle: boolean) => {
|
||||
const nodeId = isSourceHandle ? target : source;
|
||||
const handleId = isSourceHandle ? targetHandleId : sourceHandleId;
|
||||
const isValidConnection = () => true;
|
||||
const isTarget = isSourceHandle;
|
||||
|
||||
onMouseDown(
|
||||
event,
|
||||
handleId,
|
||||
nodeId,
|
||||
setConnectionNodeId,
|
||||
setPosition,
|
||||
onConnectEdge,
|
||||
isTarget,
|
||||
isValidConnection,
|
||||
connectionMode
|
||||
);
|
||||
},
|
||||
[id, source, target, type, sourceHandleId, targetHandleId, setConnectionNodeId, setPosition]
|
||||
);
|
||||
|
||||
const onEdgeUpdaterSourceMouseDown = useCallback(
|
||||
(event: React.MouseEvent<SVGGElement, MouseEvent>): void => {
|
||||
handleEdgeUpdater(event, true);
|
||||
},
|
||||
[id, source, sourceHandleId, handleEdgeUpdater]
|
||||
);
|
||||
|
||||
const onEdgeUpdaterTargetMouseDown = useCallback(
|
||||
(event: React.MouseEvent<SVGGElement, MouseEvent>): void => {
|
||||
handleEdgeUpdater(event, false);
|
||||
},
|
||||
[id, target, targetHandleId, handleEdgeUpdater]
|
||||
);
|
||||
|
||||
const onEdgeUpdaterMouseEnter = useCallback(() => setUpdating(true), [setUpdating]);
|
||||
const onEdgeUpdaterMouseOut = useCallback(() => setUpdating(false), [setUpdating]);
|
||||
|
||||
if (isHidden) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<g className={edgeClasses} onClick={onEdgeClick}>
|
||||
{handleEdgeUpdate && (
|
||||
<g
|
||||
onMouseDown={onEdgeUpdaterSourceMouseDown}
|
||||
onMouseEnter={onEdgeUpdaterMouseEnter}
|
||||
onMouseOut={onEdgeUpdaterMouseOut}
|
||||
>
|
||||
<circle
|
||||
className="react-flow__edgeupdater"
|
||||
cx={sourceX}
|
||||
cy={sourceY}
|
||||
r={10}
|
||||
stroke="transparent"
|
||||
fill="transparent"
|
||||
/>
|
||||
</g>
|
||||
)}
|
||||
<EdgeComponent
|
||||
id={id}
|
||||
source={source}
|
||||
@@ -91,6 +167,22 @@ export default (EdgeComponent: ComponentType<EdgeProps>) => {
|
||||
targetPosition={targetPosition}
|
||||
markerEndId={markerEndId}
|
||||
/>
|
||||
{handleEdgeUpdate && (
|
||||
<g
|
||||
onMouseDown={onEdgeUpdaterTargetMouseDown}
|
||||
onMouseEnter={onEdgeUpdaterMouseEnter}
|
||||
onMouseOut={onEdgeUpdaterMouseOut}
|
||||
>
|
||||
<circle
|
||||
className="react-flow__edgeupdater"
|
||||
cx={targetX}
|
||||
cy={targetY}
|
||||
r={10}
|
||||
stroke="transparent"
|
||||
fill="transparent"
|
||||
/>
|
||||
</g>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,147 +1,18 @@
|
||||
import { useEffect } from 'react';
|
||||
import isEqual from 'fast-deep-equal';
|
||||
|
||||
import { useStoreState, useStoreActions } from '../../store/hooks';
|
||||
import { parseElement, isNode, isEdge } from '../../utils/graph';
|
||||
import { Elements, Node, Edge, FlowElement } from '../../types';
|
||||
import { useStoreActions } from '../../store/hooks';
|
||||
import { Elements } from '../../types';
|
||||
|
||||
interface ElementUpdaterProps {
|
||||
elements: Elements;
|
||||
}
|
||||
|
||||
const ElementUpdater = ({ elements }: ElementUpdaterProps) => {
|
||||
const stateElements = useStoreState((state) => state.elements);
|
||||
const setElements = useStoreActions((actions) => actions.setElements);
|
||||
|
||||
useEffect(() => {
|
||||
const nextElements: Elements = elements.map((propElement) => {
|
||||
const existingElement = stateElements.find((el) => el.id === propElement.id?.toString());
|
||||
|
||||
if (existingElement) {
|
||||
const data = !isEqual(existingElement.data, propElement.data)
|
||||
? { ...existingElement.data, ...propElement.data }
|
||||
: existingElement.data;
|
||||
|
||||
const style = !isEqual(existingElement.style, propElement.style)
|
||||
? { ...existingElement.style, ...propElement.style }
|
||||
: existingElement.style;
|
||||
|
||||
const elementProps = {
|
||||
...existingElement,
|
||||
};
|
||||
|
||||
if (typeof data !== 'undefined') {
|
||||
elementProps.data = data;
|
||||
}
|
||||
|
||||
if (typeof style !== 'undefined') {
|
||||
elementProps.style = style;
|
||||
}
|
||||
|
||||
if (typeof propElement.className !== 'undefined') {
|
||||
elementProps.className = propElement.className;
|
||||
}
|
||||
|
||||
if (typeof propElement.isHidden !== 'undefined') {
|
||||
elementProps.isHidden = propElement.isHidden;
|
||||
}
|
||||
|
||||
if (typeof propElement.type !== 'undefined') {
|
||||
elementProps.type = propElement.type;
|
||||
|
||||
// we reset the elements dimensions here in order to force a re-calculation of the bounds.
|
||||
// When the type of a node changes it is possible that the number or positions of handles changes too.
|
||||
if (isNode(existingElement) && propElement.type !== existingElement.type) {
|
||||
existingElement.__rf.width = null;
|
||||
existingElement.__rf.height = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (isNode(existingElement)) {
|
||||
const propNode = propElement as Node;
|
||||
const nodeProps = elementProps as Node;
|
||||
|
||||
const positionChanged =
|
||||
existingElement.position.x !== propNode.position.x || existingElement.position.y !== propNode.position.y;
|
||||
|
||||
if (positionChanged) {
|
||||
nodeProps.__rf = {
|
||||
...existingElement.__rf,
|
||||
position: propNode.position,
|
||||
};
|
||||
nodeProps.position = propNode.position;
|
||||
}
|
||||
|
||||
if (typeof propNode.draggable !== 'undefined') {
|
||||
nodeProps.draggable = propNode.draggable;
|
||||
}
|
||||
|
||||
if (typeof propNode.selectable !== 'undefined') {
|
||||
nodeProps.selectable = propNode.selectable;
|
||||
}
|
||||
|
||||
if (typeof propNode.connectable !== 'undefined') {
|
||||
nodeProps.connectable = propNode.connectable;
|
||||
}
|
||||
|
||||
return nodeProps;
|
||||
} else if (isEdge(existingElement)) {
|
||||
const propEdge = propElement as Edge;
|
||||
const edgeProps = elementProps as Edge;
|
||||
|
||||
const labelStyle = !isEqual(existingElement.labelStyle, propEdge.labelStyle)
|
||||
? { ...existingElement.labelStyle, ...propEdge.labelStyle }
|
||||
: existingElement.labelStyle;
|
||||
|
||||
const labelBgStyle = !isEqual(existingElement.labelBgStyle, propEdge.labelBgStyle)
|
||||
? { ...existingElement.labelBgStyle, ...propEdge.labelBgStyle }
|
||||
: existingElement.labelBgStyle;
|
||||
|
||||
if (typeof propEdge.label !== 'undefined') {
|
||||
edgeProps.label = propEdge.label;
|
||||
}
|
||||
|
||||
if (typeof labelStyle !== 'undefined') {
|
||||
edgeProps.labelStyle = labelStyle;
|
||||
}
|
||||
|
||||
if (typeof propEdge.labelShowBg !== 'undefined') {
|
||||
edgeProps.labelShowBg = propEdge.labelShowBg;
|
||||
}
|
||||
|
||||
if (typeof propEdge.labelBgPadding !== 'undefined') {
|
||||
edgeProps.labelBgPadding = propEdge.labelBgPadding;
|
||||
}
|
||||
|
||||
if (typeof propEdge.labelBgBorderRadius !== 'undefined') {
|
||||
edgeProps.labelBgBorderRadius = propEdge.labelBgBorderRadius;
|
||||
}
|
||||
|
||||
if (typeof labelBgStyle !== 'undefined') {
|
||||
edgeProps.labelBgStyle = labelBgStyle;
|
||||
}
|
||||
|
||||
if (typeof propEdge.animated !== 'undefined') {
|
||||
edgeProps.animated = propEdge.animated;
|
||||
}
|
||||
|
||||
if (typeof propEdge.arrowHeadType !== 'undefined') {
|
||||
edgeProps.arrowHeadType = propEdge.arrowHeadType;
|
||||
}
|
||||
|
||||
return edgeProps;
|
||||
}
|
||||
}
|
||||
|
||||
return parseElement(propElement) as FlowElement;
|
||||
});
|
||||
|
||||
const elementsChanged: boolean = !isEqual(stateElements, nextElements);
|
||||
|
||||
if (elementsChanged) {
|
||||
setElements(nextElements);
|
||||
}
|
||||
}, [elements, stateElements]);
|
||||
setElements(elements);
|
||||
}, [elements]);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
@@ -1,228 +0,0 @@
|
||||
import React, { memo, MouseEvent as ReactMouseEvent, CSSProperties } from 'react';
|
||||
import cc from 'classcat';
|
||||
|
||||
import {
|
||||
HandleType,
|
||||
ElementId,
|
||||
Position,
|
||||
XYPosition,
|
||||
OnConnectFunc,
|
||||
OnConnectStartFunc,
|
||||
OnConnectStopFunc,
|
||||
OnConnectEndFunc,
|
||||
Connection,
|
||||
SetConnectionId,
|
||||
} from '../../types';
|
||||
|
||||
type ValidConnectionFunc = (connection: Connection) => boolean;
|
||||
type SetSourceIdFunc = (params: SetConnectionId) => void;
|
||||
|
||||
interface BaseHandleProps {
|
||||
type: HandleType;
|
||||
nodeId: ElementId;
|
||||
onConnect: OnConnectFunc;
|
||||
onConnectStart?: OnConnectStartFunc;
|
||||
onConnectStop?: OnConnectStopFunc;
|
||||
onConnectEnd?: OnConnectEndFunc;
|
||||
position: Position;
|
||||
setConnectionNodeId: SetSourceIdFunc;
|
||||
setPosition: (pos: XYPosition) => void;
|
||||
isValidConnection: ValidConnectionFunc;
|
||||
id?: ElementId | null;
|
||||
className?: string;
|
||||
style?: CSSProperties;
|
||||
}
|
||||
|
||||
type Result = {
|
||||
elementBelow: Element | null;
|
||||
isValid: boolean;
|
||||
connection: Connection;
|
||||
isHoveringHandle: boolean;
|
||||
};
|
||||
|
||||
function onMouseDown(
|
||||
event: ReactMouseEvent,
|
||||
handleId: ElementId | null,
|
||||
nodeId: ElementId,
|
||||
setConnectionNodeId: SetSourceIdFunc,
|
||||
setPosition: (pos: XYPosition) => void,
|
||||
onConnect: OnConnectFunc,
|
||||
isTarget: boolean,
|
||||
isValidConnection: ValidConnectionFunc,
|
||||
onConnectStart?: OnConnectStartFunc,
|
||||
onConnectStop?: OnConnectStopFunc,
|
||||
onConnectEnd?: OnConnectEndFunc
|
||||
): void {
|
||||
const reactFlowNode = (event.target as Element).closest('.react-flow');
|
||||
|
||||
if (!reactFlowNode) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleType = isTarget ? 'target' : 'source';
|
||||
const containerBounds = reactFlowNode.getBoundingClientRect();
|
||||
let recentHoveredHandle: Element;
|
||||
|
||||
setPosition({
|
||||
x: event.clientX - containerBounds.left,
|
||||
y: event.clientY - containerBounds.top,
|
||||
});
|
||||
setConnectionNodeId({ connectionNodeId: nodeId, connectionHandleId: handleId, connectionHandleType: handleType });
|
||||
|
||||
if (onConnectStart) {
|
||||
onConnectStart(event, { nodeId, handleType });
|
||||
}
|
||||
|
||||
function resetRecentHandle(): void {
|
||||
if (!recentHoveredHandle) {
|
||||
return;
|
||||
}
|
||||
|
||||
recentHoveredHandle.classList.remove('react-flow__handle-valid');
|
||||
recentHoveredHandle.classList.remove('react-flow__handle-connecting');
|
||||
}
|
||||
|
||||
// checks if element below mouse is a handle and returns connection in form of an object { source: 123, target: 312 }
|
||||
function checkElementBelowIsValid(event: MouseEvent) {
|
||||
const elementBelow = document.elementFromPoint(event.clientX, event.clientY);
|
||||
|
||||
const result: Result = {
|
||||
elementBelow,
|
||||
isValid: false,
|
||||
connection: { source: null, target: null, sourceHandle: null, targetHandle: null },
|
||||
isHoveringHandle: false,
|
||||
};
|
||||
|
||||
if (elementBelow && (elementBelow.classList.contains('target') || elementBelow.classList.contains('source'))) {
|
||||
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;
|
||||
}
|
||||
|
||||
function onMouseMove(event: MouseEvent) {
|
||||
setPosition({
|
||||
x: event.clientX - containerBounds.left,
|
||||
y: event.clientY - containerBounds.top,
|
||||
});
|
||||
|
||||
const { connection, elementBelow, isValid, isHoveringHandle } = checkElementBelowIsValid(event);
|
||||
|
||||
if (!isHoveringHandle) {
|
||||
return resetRecentHandle();
|
||||
}
|
||||
|
||||
const isOwnHandle = connection.source === connection.target;
|
||||
|
||||
if (!isOwnHandle && elementBelow) {
|
||||
recentHoveredHandle = elementBelow;
|
||||
elementBelow.classList.add('react-flow__handle-connecting');
|
||||
elementBelow.classList.toggle('react-flow__handle-valid', isValid);
|
||||
}
|
||||
}
|
||||
|
||||
function onMouseUp(event: MouseEvent) {
|
||||
const { connection, isValid } = checkElementBelowIsValid(event);
|
||||
|
||||
if (onConnectStop) {
|
||||
onConnectStop(event);
|
||||
}
|
||||
|
||||
if (isValid && onConnect) {
|
||||
onConnect(connection);
|
||||
}
|
||||
|
||||
if (onConnectEnd) {
|
||||
onConnectEnd(event);
|
||||
}
|
||||
|
||||
resetRecentHandle();
|
||||
setConnectionNodeId({ connectionNodeId: null, connectionHandleId: null, connectionHandleType: null });
|
||||
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
}
|
||||
|
||||
document.addEventListener('mousemove', onMouseMove);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
}
|
||||
|
||||
const BaseHandle = ({
|
||||
type,
|
||||
nodeId,
|
||||
onConnect,
|
||||
onConnectStart,
|
||||
onConnectStop,
|
||||
onConnectEnd,
|
||||
position,
|
||||
setConnectionNodeId,
|
||||
setPosition,
|
||||
className,
|
||||
id = null,
|
||||
isValidConnection,
|
||||
...rest
|
||||
}: BaseHandleProps) => {
|
||||
const isTarget = type === 'target';
|
||||
const handleClasses = cc([
|
||||
'react-flow__handle',
|
||||
`react-flow__handle-${position}`,
|
||||
'nodrag',
|
||||
className,
|
||||
{
|
||||
source: !isTarget,
|
||||
target: isTarget,
|
||||
},
|
||||
]);
|
||||
|
||||
const handleId = id || null;
|
||||
|
||||
return (
|
||||
<div
|
||||
data-handleid={handleId}
|
||||
data-nodeid={nodeId}
|
||||
data-handlepos={position}
|
||||
className={handleClasses}
|
||||
onMouseDown={(event) =>
|
||||
onMouseDown(
|
||||
event,
|
||||
handleId,
|
||||
nodeId,
|
||||
setConnectionNodeId,
|
||||
setPosition,
|
||||
onConnect,
|
||||
isTarget,
|
||||
isValidConnection,
|
||||
onConnectStart,
|
||||
onConnectStop,
|
||||
onConnectEnd
|
||||
)
|
||||
}
|
||||
{...rest}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
BaseHandle.displayName = 'BaseHandle';
|
||||
|
||||
export default memo(BaseHandle);
|
||||
171
src/components/Handle/handler.ts
Normal file
171
src/components/Handle/handler.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
import { MouseEvent as ReactMouseEvent } from 'react';
|
||||
|
||||
import {
|
||||
ElementId,
|
||||
XYPosition,
|
||||
OnConnectFunc,
|
||||
OnConnectStartFunc,
|
||||
OnConnectStopFunc,
|
||||
OnConnectEndFunc,
|
||||
ConnectionMode,
|
||||
SetConnectionId,
|
||||
Connection,
|
||||
} from '../../types';
|
||||
|
||||
type ValidConnectionFunc = (connection: Connection) => boolean;
|
||||
export type SetSourceIdFunc = (params: SetConnectionId) => void;
|
||||
|
||||
type Result = {
|
||||
elementBelow: Element | null;
|
||||
isValid: boolean;
|
||||
connection: Connection;
|
||||
isHoveringHandle: boolean;
|
||||
};
|
||||
|
||||
// checks if element below mouse is a handle and returns connection in form of an object { source: 123, target: 312 }
|
||||
function checkElementBelowIsValid(
|
||||
event: MouseEvent,
|
||||
connectionMode: ConnectionMode,
|
||||
isTarget: boolean,
|
||||
nodeId: ElementId,
|
||||
handleId: ElementId | null,
|
||||
isValidConnection: ValidConnectionFunc
|
||||
) {
|
||||
const elementBelow = document.elementFromPoint(event.clientX, event.clientY);
|
||||
const elementBelowIsTarget = elementBelow?.classList.contains('target') || false;
|
||||
const elementBelowIsSource = elementBelow?.classList.contains('source') || false;
|
||||
|
||||
const result: Result = {
|
||||
elementBelow,
|
||||
isValid: false,
|
||||
connection: { source: null, target: null, sourceHandle: null, targetHandle: null },
|
||||
isHoveringHandle: false,
|
||||
};
|
||||
|
||||
if (elementBelow && (elementBelowIsTarget || elementBelowIsSource)) {
|
||||
result.isHoveringHandle = true;
|
||||
|
||||
// in strict mode we don't allow target to target or source to source connections
|
||||
const isValid =
|
||||
connectionMode === ConnectionMode.Strict
|
||||
? (isTarget && elementBelowIsSource) || (!isTarget && elementBelowIsTarget)
|
||||
: true;
|
||||
|
||||
if (isValid) {
|
||||
const elementBelowNodeId = elementBelow.getAttribute('data-nodeid');
|
||||
const elementBelowHandleId = elementBelow.getAttribute('data-handleid');
|
||||
const connection: Connection = isTarget
|
||||
? {
|
||||
source: elementBelowNodeId,
|
||||
sourceHandle: elementBelowHandleId,
|
||||
target: nodeId,
|
||||
targetHandle: handleId,
|
||||
}
|
||||
: {
|
||||
source: nodeId,
|
||||
sourceHandle: handleId,
|
||||
target: elementBelowNodeId,
|
||||
targetHandle: elementBelowHandleId,
|
||||
};
|
||||
|
||||
result.connection = connection;
|
||||
result.isValid = isValidConnection(connection);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function resetRecentHandle(hoveredHandle: Element): void {
|
||||
hoveredHandle?.classList.remove('react-flow__handle-valid');
|
||||
hoveredHandle?.classList.remove('react-flow__handle-connecting');
|
||||
}
|
||||
|
||||
export function onMouseDown(
|
||||
event: ReactMouseEvent,
|
||||
handleId: ElementId | null,
|
||||
nodeId: ElementId,
|
||||
setConnectionNodeId: SetSourceIdFunc,
|
||||
setPosition: (pos: XYPosition) => void,
|
||||
onConnect: OnConnectFunc,
|
||||
isTarget: boolean,
|
||||
isValidConnection: ValidConnectionFunc,
|
||||
connectionMode: ConnectionMode,
|
||||
onConnectStart?: OnConnectStartFunc,
|
||||
onConnectStop?: OnConnectStopFunc,
|
||||
onConnectEnd?: OnConnectEndFunc
|
||||
): void {
|
||||
const reactFlowNode = (event.target as Element).closest('.react-flow');
|
||||
|
||||
if (!reactFlowNode) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleType = isTarget ? 'target' : 'source';
|
||||
const containerBounds = reactFlowNode.getBoundingClientRect();
|
||||
let recentHoveredHandle: Element;
|
||||
|
||||
setPosition({
|
||||
x: event.clientX - containerBounds.left,
|
||||
y: event.clientY - containerBounds.top,
|
||||
});
|
||||
|
||||
setConnectionNodeId({ connectionNodeId: nodeId, connectionHandleId: handleId, connectionHandleType: handleType });
|
||||
onConnectStart?.(event, { nodeId, handleId, handleType });
|
||||
|
||||
function onMouseMove(event: MouseEvent) {
|
||||
setPosition({
|
||||
x: event.clientX - containerBounds.left,
|
||||
y: event.clientY - containerBounds.top,
|
||||
});
|
||||
|
||||
const { connection, elementBelow, isValid, isHoveringHandle } = checkElementBelowIsValid(
|
||||
event,
|
||||
connectionMode,
|
||||
isTarget,
|
||||
nodeId,
|
||||
handleId,
|
||||
isValidConnection
|
||||
);
|
||||
|
||||
if (!isHoveringHandle) {
|
||||
return resetRecentHandle(recentHoveredHandle);
|
||||
}
|
||||
|
||||
const isOwnHandle = connection.source === connection.target;
|
||||
|
||||
if (!isOwnHandle && elementBelow) {
|
||||
recentHoveredHandle = elementBelow;
|
||||
elementBelow.classList.add('react-flow__handle-connecting');
|
||||
elementBelow.classList.toggle('react-flow__handle-valid', isValid);
|
||||
}
|
||||
}
|
||||
|
||||
function onMouseUp(event: MouseEvent) {
|
||||
const { connection, isValid } = checkElementBelowIsValid(
|
||||
event,
|
||||
connectionMode,
|
||||
isTarget,
|
||||
nodeId,
|
||||
handleId,
|
||||
isValidConnection
|
||||
);
|
||||
|
||||
onConnectStop?.(event);
|
||||
|
||||
if (isValid) {
|
||||
onConnect?.(connection);
|
||||
}
|
||||
|
||||
onConnectEnd?.(event);
|
||||
|
||||
resetRecentHandle(recentHoveredHandle);
|
||||
setConnectionNodeId({ connectionNodeId: null, connectionHandleId: null, connectionHandleType: null });
|
||||
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
}
|
||||
|
||||
document.addEventListener('mousemove', onMouseMove);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
}
|
||||
@@ -1,16 +1,18 @@
|
||||
import React, { memo, useContext } from 'react';
|
||||
import React, { memo, useContext, useCallback } from 'react';
|
||||
import cc from 'classcat';
|
||||
|
||||
import { useStoreActions, useStoreState } from '../../store/hooks';
|
||||
import BaseHandle from './BaseHandle';
|
||||
import NodeIdContext from '../../contexts/NodeIdContext';
|
||||
import { HandleProps, Connection, ElementId, Position } from '../../types';
|
||||
|
||||
import { HandleProps, ElementId, Position, Connection } from '../../types';
|
||||
import { onMouseDown } from './handler';
|
||||
|
||||
const alwaysValid = () => true;
|
||||
|
||||
const Handle = ({
|
||||
type = 'source',
|
||||
position = Position.Top,
|
||||
isValidConnection = () => true,
|
||||
isValidConnection = alwaysValid,
|
||||
isConnectable = true,
|
||||
style,
|
||||
className,
|
||||
@@ -24,32 +26,69 @@ const Handle = ({
|
||||
const onConnectStart = useStoreState((state) => state.onConnectStart);
|
||||
const onConnectStop = useStoreState((state) => state.onConnectStop);
|
||||
const onConnectEnd = useStoreState((state) => state.onConnectEnd);
|
||||
const connectionMode = useStoreState((state) => state.connectionMode);
|
||||
const handleId = id || null;
|
||||
const isTarget = type === 'target';
|
||||
|
||||
const onConnectExtended = (params: Connection) => {
|
||||
if (onConnectAction) {
|
||||
onConnectAction(params);
|
||||
}
|
||||
const onConnectExtended = useCallback(
|
||||
(params: Connection) => {
|
||||
onConnectAction?.(params);
|
||||
onConnect?.(params);
|
||||
},
|
||||
[onConnectAction, onConnect]
|
||||
);
|
||||
|
||||
if (onConnect) {
|
||||
onConnect(params);
|
||||
}
|
||||
};
|
||||
const handleClasses = cc([className, { connectable: isConnectable }]);
|
||||
const onMouseDownHandler = useCallback(
|
||||
(event: React.MouseEvent) => {
|
||||
onMouseDown(
|
||||
event,
|
||||
handleId,
|
||||
nodeId,
|
||||
setConnectionNodeId,
|
||||
setPosition,
|
||||
onConnectExtended,
|
||||
isTarget,
|
||||
isValidConnection,
|
||||
connectionMode,
|
||||
onConnectStart,
|
||||
onConnectStop,
|
||||
onConnectEnd
|
||||
);
|
||||
},
|
||||
[
|
||||
handleId,
|
||||
nodeId,
|
||||
setConnectionNodeId,
|
||||
setPosition,
|
||||
onConnectExtended,
|
||||
isTarget,
|
||||
isValidConnection,
|
||||
connectionMode,
|
||||
onConnectStart,
|
||||
onConnectStop,
|
||||
onConnectEnd,
|
||||
]
|
||||
);
|
||||
|
||||
const handleClasses = cc([
|
||||
'react-flow__handle',
|
||||
`react-flow__handle-${position}`,
|
||||
'nodrag',
|
||||
className,
|
||||
{
|
||||
source: !isTarget,
|
||||
target: isTarget,
|
||||
connectable: isConnectable,
|
||||
},
|
||||
]);
|
||||
|
||||
return (
|
||||
<BaseHandle
|
||||
<div
|
||||
data-handleid={handleId}
|
||||
data-nodeid={nodeId}
|
||||
data-handlepos={position}
|
||||
className={handleClasses}
|
||||
id={id}
|
||||
nodeId={nodeId}
|
||||
setPosition={setPosition}
|
||||
setConnectionNodeId={setConnectionNodeId}
|
||||
onConnect={onConnectExtended}
|
||||
onConnectStart={onConnectStart}
|
||||
onConnectStop={onConnectStop}
|
||||
onConnectEnd={onConnectEnd}
|
||||
type={type}
|
||||
position={position}
|
||||
isValidConnection={isValidConnection}
|
||||
onMouseDown={onMouseDownHandler}
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { HandleElement, Position } from '../../types';
|
||||
import { getDimensions } from '../../utils';
|
||||
|
||||
export const getHandleBounds = (
|
||||
export const getHandleBounds = (nodeElement: HTMLDivElement, scale: number) => {
|
||||
const bounds = nodeElement.getBoundingClientRect();
|
||||
|
||||
return {
|
||||
source: getHandleBoundsByHandleType('.source', nodeElement, bounds, scale),
|
||||
target: getHandleBoundsByHandleType('.target', nodeElement, bounds, scale),
|
||||
};
|
||||
};
|
||||
|
||||
export const getHandleBoundsByHandleType = (
|
||||
selector: string,
|
||||
nodeElement: HTMLDivElement,
|
||||
parentBounds: ClientRect | DOMRect,
|
||||
|
||||
@@ -35,6 +35,7 @@ export default (NodeComponent: ComponentType<NodeComponentProps>) => {
|
||||
snapToGrid,
|
||||
snapGrid,
|
||||
isDragging,
|
||||
resizeObserver,
|
||||
}: WrapNodeProps) => {
|
||||
const updateNodeDimensions = useStoreActions((actions) => actions.updateNodeDimensions);
|
||||
const addSelectedElements = useStoreActions((actions) => actions.addSelectedElements);
|
||||
@@ -160,24 +161,19 @@ export default (NodeComponent: ComponentType<NodeComponentProps>) => {
|
||||
useEffect(() => {
|
||||
if (nodeElement.current && !isHidden) {
|
||||
updateNodeDimensions({ id, nodeElement: nodeElement.current });
|
||||
}
|
||||
}, [id, isHidden]);
|
||||
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
if (nodeElement.current) {
|
||||
updateNodeDimensions({ id, nodeElement: nodeElement.current });
|
||||
}
|
||||
});
|
||||
useEffect(() => {
|
||||
if (nodeElement.current) {
|
||||
const currNode = nodeElement.current;
|
||||
resizeObserver.observe(currNode);
|
||||
|
||||
resizeObserver.observe(nodeElement.current);
|
||||
|
||||
return () => {
|
||||
if (resizeObserver && nodeElement.current) {
|
||||
resizeObserver.unobserve(nodeElement.current);
|
||||
}
|
||||
};
|
||||
return () => resizeObserver.unobserve(currNode);
|
||||
}
|
||||
|
||||
return;
|
||||
}, [id, isHidden]);
|
||||
}, []);
|
||||
|
||||
if (isHidden) {
|
||||
return null;
|
||||
@@ -213,6 +209,7 @@ export default (NodeComponent: ComponentType<NodeComponentProps>) => {
|
||||
onMouseLeave={onMouseLeaveHandler}
|
||||
onContextMenu={onContextMenuHandler}
|
||||
onClick={onSelectNodeHandler}
|
||||
data-id={id}
|
||||
>
|
||||
<Provider value={id}>
|
||||
<NodeComponent
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
import React, { memo, CSSProperties } from 'react';
|
||||
import React, { memo, CSSProperties, useCallback } from 'react';
|
||||
|
||||
import { useStoreState } from '../../store/hooks';
|
||||
import ConnectionLine from '../../components/ConnectionLine/index';
|
||||
import { isEdge } from '../../utils/graph';
|
||||
import MarkerDefinitions from './MarkerDefinitions';
|
||||
import { getEdgePositions, getHandle, isEdgeVisible, getSourceTargetNodes } from './utils';
|
||||
import { Position, Edge, Node, Elements, ConnectionLineType, ConnectionLineComponent, Transform } from '../../types';
|
||||
import {
|
||||
Position,
|
||||
Edge,
|
||||
Node,
|
||||
Elements,
|
||||
ConnectionLineType,
|
||||
ConnectionLineComponent,
|
||||
Transform,
|
||||
OnEdgeUpdateFunc,
|
||||
Connection,
|
||||
} from '../../types';
|
||||
|
||||
interface EdgeRendererProps {
|
||||
edgeTypes: any;
|
||||
@@ -16,23 +26,43 @@ interface EdgeRendererProps {
|
||||
markerEndId?: string;
|
||||
connectionLineComponent?: ConnectionLineComponent;
|
||||
onlyRenderVisibleElements: boolean;
|
||||
onEdgeUpdate?: OnEdgeUpdateFunc;
|
||||
}
|
||||
|
||||
function renderEdge(
|
||||
edge: Edge,
|
||||
props: EdgeRendererProps,
|
||||
nodes: Node[],
|
||||
selectedElements: Elements | null,
|
||||
elementsSelectable: boolean,
|
||||
transform: Transform,
|
||||
width: number,
|
||||
height: number,
|
||||
onlyRenderVisibleElements: boolean
|
||||
) {
|
||||
interface EdgeWrapperProps {
|
||||
edge: Edge;
|
||||
props: EdgeRendererProps;
|
||||
nodes: Node[];
|
||||
selectedElements: Elements | null;
|
||||
elementsSelectable: boolean;
|
||||
transform: Transform;
|
||||
width: number;
|
||||
height: number;
|
||||
onlyRenderVisibleElements: boolean;
|
||||
}
|
||||
|
||||
const Edge = ({
|
||||
edge,
|
||||
props,
|
||||
nodes,
|
||||
selectedElements,
|
||||
elementsSelectable,
|
||||
transform,
|
||||
width,
|
||||
height,
|
||||
onlyRenderVisibleElements,
|
||||
}: EdgeWrapperProps) => {
|
||||
const sourceHandleId = edge.sourceHandle || null;
|
||||
const targetHandleId = edge.targetHandle || null;
|
||||
const { sourceNode, targetNode } = getSourceTargetNodes(edge, nodes);
|
||||
|
||||
const onConnectEdge = useCallback(
|
||||
(connection: Connection) => {
|
||||
props.onEdgeUpdate?.(edge, connection);
|
||||
},
|
||||
[edge]
|
||||
);
|
||||
|
||||
if (!sourceNode) {
|
||||
console.warn(`couldn't create edge for source id: ${edge.source}; edge id: ${edge.id}`);
|
||||
return null;
|
||||
@@ -120,9 +150,11 @@ function renderEdge(
|
||||
elementsSelectable={elementsSelectable}
|
||||
markerEndId={props.markerEndId}
|
||||
isHidden={edge.isHidden}
|
||||
onConnectEdge={onConnectEdge}
|
||||
handleEdgeUpdate={typeof props.onEdgeUpdate !== 'undefined'}
|
||||
/>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const EdgeRenderer = (props: EdgeRendererProps) => {
|
||||
const transform = useStoreState((state) => state.transform);
|
||||
@@ -156,19 +188,20 @@ const EdgeRenderer = (props: EdgeRendererProps) => {
|
||||
<svg width={width} height={height} className="react-flow__edges">
|
||||
<MarkerDefinitions color={arrowHeadColor} />
|
||||
<g transform={transformStyle}>
|
||||
{edges.map((edge: Edge) =>
|
||||
renderEdge(
|
||||
edge,
|
||||
props,
|
||||
nodes,
|
||||
selectedElements,
|
||||
elementsSelectable,
|
||||
transform,
|
||||
width,
|
||||
height,
|
||||
onlyRenderVisibleElements
|
||||
)
|
||||
)}
|
||||
{edges.map((edge: Edge) => (
|
||||
<Edge
|
||||
key={edge.id}
|
||||
edge={edge}
|
||||
props={props}
|
||||
nodes={nodes}
|
||||
selectedElements={selectedElements}
|
||||
elementsSelectable={elementsSelectable}
|
||||
transform={transform}
|
||||
width={width}
|
||||
height={height}
|
||||
onlyRenderVisibleElements={onlyRenderVisibleElements}
|
||||
/>
|
||||
))}
|
||||
{renderConnectionLine && (
|
||||
<ConnectionLine
|
||||
nodes={nodes}
|
||||
|
||||
@@ -45,6 +45,7 @@ const GraphView = ({
|
||||
onSelectionDrag,
|
||||
onSelectionDragStop,
|
||||
onSelectionContextMenu,
|
||||
connectionMode,
|
||||
connectionLineType,
|
||||
connectionLineStyle,
|
||||
connectionLineComponent,
|
||||
@@ -79,6 +80,7 @@ const GraphView = ({
|
||||
onPaneClick,
|
||||
onPaneScroll,
|
||||
onPaneContextMenu,
|
||||
onEdgeUpdate,
|
||||
}: GraphViewProps) => {
|
||||
const isInitialised = useRef<boolean>(false);
|
||||
const setOnConnect = useStoreActions((actions) => actions.setOnConnect);
|
||||
@@ -93,6 +95,7 @@ const GraphView = ({
|
||||
const setMinZoom = useStoreActions((actions) => actions.setMinZoom);
|
||||
const setMaxZoom = useStoreActions((actions) => actions.setMaxZoom);
|
||||
const setTranslateExtent = useStoreActions((actions) => actions.setTranslateExtent);
|
||||
const setConnectionMode = useStoreActions((actions) => actions.setConnectionMode);
|
||||
const currentStore = useStore();
|
||||
const { zoomIn, zoomOut, zoomTo, transform, fitView, initialized } = useZoomPanHelper();
|
||||
|
||||
@@ -187,6 +190,12 @@ const GraphView = ({
|
||||
}
|
||||
}, [translateExtent]);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof connectionMode !== 'undefined') {
|
||||
setConnectionMode(connectionMode);
|
||||
}
|
||||
}, [connectionMode]);
|
||||
|
||||
return (
|
||||
<FlowRenderer
|
||||
onPaneClick={onPaneClick}
|
||||
@@ -236,6 +245,7 @@ const GraphView = ({
|
||||
arrowHeadColor={arrowHeadColor}
|
||||
markerEndId={markerEndId}
|
||||
connectionLineComponent={connectionLineComponent}
|
||||
onEdgeUpdate={onEdgeUpdate}
|
||||
onlyRenderVisibleElements={onlyRenderVisibleElements}
|
||||
/>
|
||||
</FlowRenderer>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { memo, useMemo, ComponentType, MouseEvent } from 'react';
|
||||
|
||||
import { getNodesInside } from '../../utils/graph';
|
||||
import { useStoreState } from '../../store/hooks';
|
||||
import { useStoreState, useStoreActions } from '../../store/hooks';
|
||||
import { Node, NodeTypesType, WrapNodeProps, Edge } from '../../types';
|
||||
|
||||
interface NodeRendererProps {
|
||||
@@ -27,6 +27,7 @@ const NodeRenderer = (props: NodeRendererProps) => {
|
||||
const elementsSelectable = useStoreState((state) => state.elementsSelectable);
|
||||
const viewportBox = useStoreState((state) => state.viewportBox);
|
||||
const nodes = useStoreState((state) => state.nodes);
|
||||
const batchUpdateNodeDimensions = useStoreActions((actions) => actions.batchUpdateNodeDimensions);
|
||||
|
||||
const visibleNodes = props.onlyRenderVisibleElements ? getNodesInside(nodes, viewportBox, transform, true) : nodes;
|
||||
|
||||
@@ -37,6 +38,19 @@ const NodeRenderer = (props: NodeRendererProps) => {
|
||||
[transform[0], transform[1], transform[2]]
|
||||
);
|
||||
|
||||
const resizeObserver = useMemo(
|
||||
() =>
|
||||
new ResizeObserver((entries) => {
|
||||
const updates = entries.map((entry) => ({
|
||||
id: entry.target.getAttribute('data-id') as string,
|
||||
nodeElement: entry.target as HTMLDivElement,
|
||||
}));
|
||||
|
||||
batchUpdateNodeDimensions({ updates });
|
||||
}),
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="react-flow__nodes" style={transformStyle}>
|
||||
{visibleNodes.map((node) => {
|
||||
@@ -81,6 +95,7 @@ const NodeRenderer = (props: NodeRendererProps) => {
|
||||
isDraggable={isDraggable}
|
||||
isSelectable={isSelectable}
|
||||
isConnectable={isConnectable}
|
||||
resizeObserver={resizeObserver}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
Node,
|
||||
Edge,
|
||||
Connection,
|
||||
ConnectionMode,
|
||||
ConnectionLineType,
|
||||
ConnectionLineComponent,
|
||||
FlowTransform,
|
||||
@@ -28,6 +29,7 @@ import {
|
||||
TranslateExtent,
|
||||
KeyCode,
|
||||
PanOnScrollMode,
|
||||
OnEdgeUpdateFunc,
|
||||
} from '../../types';
|
||||
|
||||
import '../../style.css';
|
||||
@@ -73,6 +75,7 @@ export interface ReactFlowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'on
|
||||
onPaneContextMenu?: (event: MouseEvent) => void;
|
||||
nodeTypes?: NodeTypesType;
|
||||
edgeTypes?: EdgeTypesType;
|
||||
connectionMode?: ConnectionMode;
|
||||
connectionLineType?: ConnectionLineType;
|
||||
connectionLineStyle?: CSSProperties;
|
||||
connectionLineComponent?: ConnectionLineComponent;
|
||||
@@ -99,6 +102,7 @@ export interface ReactFlowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'on
|
||||
panOnScrollSpeed?: number;
|
||||
panOnScrollMode?: PanOnScrollMode;
|
||||
zoomOnDoubleClick?: boolean;
|
||||
onEdgeUpdate?: OnEdgeUpdateFunc;
|
||||
}
|
||||
|
||||
const ReactFlow = ({
|
||||
@@ -127,6 +131,7 @@ const ReactFlow = ({
|
||||
onSelectionDrag,
|
||||
onSelectionDragStop,
|
||||
onSelectionContextMenu,
|
||||
connectionMode,
|
||||
connectionLineType = ConnectionLineType.Bezier,
|
||||
connectionLineStyle,
|
||||
connectionLineComponent,
|
||||
@@ -157,6 +162,7 @@ const ReactFlow = ({
|
||||
onPaneScroll,
|
||||
onPaneContextMenu,
|
||||
children,
|
||||
onEdgeUpdate,
|
||||
...rest
|
||||
}: ReactFlowProps) => {
|
||||
const nodeTypesParsed = useMemo(() => createNodeTypes(nodeTypes), []);
|
||||
@@ -180,6 +186,7 @@ const ReactFlow = ({
|
||||
onNodeDragStop={onNodeDragStop}
|
||||
nodeTypes={nodeTypesParsed}
|
||||
edgeTypes={edgeTypesParsed}
|
||||
connectionMode={connectionMode}
|
||||
connectionLineType={connectionLineType}
|
||||
connectionLineStyle={connectionLineStyle}
|
||||
connectionLineComponent={connectionLineComponent}
|
||||
@@ -218,6 +225,7 @@ const ReactFlow = ({
|
||||
onSelectionDrag={onSelectionDrag}
|
||||
onSelectionDragStop={onSelectionDragStop}
|
||||
onSelectionContextMenu={onSelectionContextMenu}
|
||||
onEdgeUpdate={onEdgeUpdate}
|
||||
/>
|
||||
<ElementUpdater elements={elements} />
|
||||
{onSelectionChange && <SelectionListener onSelectionChange={onSelectionChange} />}
|
||||
|
||||
@@ -189,7 +189,10 @@ const ZoomPane = ({
|
||||
}
|
||||
|
||||
// when the target element is a node, we still allow zooming
|
||||
if (event.target.closest('.react-flow__node') && event.type !== 'wheel') {
|
||||
if (
|
||||
(event.target.closest('.react-flow__node') || event.target.closest('.react-flow__edgeupdater')) &&
|
||||
event.type !== 'wheel'
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
11
src/index.ts
11
src/index.ts
@@ -8,7 +8,16 @@ export { getBezierPath } from './components/Edges/BezierEdge';
|
||||
export { getSmoothStepPath } from './components/Edges/SmoothStepEdge';
|
||||
export { getMarkerEnd, getCenter as getEdgeCenter } from './components/Edges/utils';
|
||||
|
||||
export { isNode, isEdge, removeElements, addEdge, getOutgoers, getIncomers, getConnectedEdges } from './utils/graph';
|
||||
export {
|
||||
isNode,
|
||||
isEdge,
|
||||
removeElements,
|
||||
addEdge,
|
||||
getOutgoers,
|
||||
getIncomers,
|
||||
getConnectedEdges,
|
||||
updateEdge,
|
||||
} from './utils/graph';
|
||||
export { default as useZoomPanHelper } from './hooks/useZoomPanHelper';
|
||||
|
||||
export * from './additional-components';
|
||||
|
||||
@@ -3,7 +3,7 @@ import isEqual from 'fast-deep-equal';
|
||||
import { Selection as D3Selection, ZoomBehavior } from 'd3';
|
||||
|
||||
import { getDimensions } from '../utils';
|
||||
import { getNodesInside, getConnectedEdges, getRectOfNodes, isNode, isEdge } from '../utils/graph';
|
||||
import { getNodesInside, getConnectedEdges, getRectOfNodes, isNode, isEdge, parseElement } from '../utils/graph';
|
||||
import { getHandleBounds } from '../components/Nodes/utils';
|
||||
|
||||
import {
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
NodeDiffUpdate,
|
||||
TranslateExtent,
|
||||
SnapGrid,
|
||||
ConnectionMode,
|
||||
} from '../types';
|
||||
|
||||
type NodeDimensionUpdate = {
|
||||
@@ -33,6 +34,10 @@ type NodeDimensionUpdate = {
|
||||
nodeElement: HTMLDivElement;
|
||||
};
|
||||
|
||||
type NodeDimensionUpdates = {
|
||||
updates: NodeDimensionUpdate[];
|
||||
};
|
||||
|
||||
type InitD3Zoom = {
|
||||
d3Zoom: ZoomBehavior<Element, unknown>;
|
||||
d3Selection: D3Selection<Element, unknown, null, undefined>;
|
||||
@@ -66,6 +71,7 @@ export interface StoreModel {
|
||||
connectionHandleId: ElementId | null;
|
||||
connectionHandleType: HandleType | null;
|
||||
connectionPosition: XYPosition;
|
||||
connectionMode: ConnectionMode;
|
||||
|
||||
snapToGrid: boolean;
|
||||
snapGrid: SnapGrid;
|
||||
@@ -90,6 +96,7 @@ export interface StoreModel {
|
||||
|
||||
setElements: Action<StoreModel, Elements>;
|
||||
|
||||
batchUpdateNodeDimensions: Action<StoreModel, NodeDimensionUpdates>;
|
||||
updateNodeDimensions: Action<StoreModel, NodeDimensionUpdate>;
|
||||
|
||||
updateNodePos: Action<StoreModel, NodePosUpdate>;
|
||||
@@ -131,6 +138,8 @@ export interface StoreModel {
|
||||
unsetUserSelection: Action<StoreModel>;
|
||||
|
||||
setMultiSelectionActive: Action<StoreModel, boolean>;
|
||||
|
||||
setConnectionMode: Action<StoreModel, ConnectionMode>;
|
||||
}
|
||||
|
||||
export const storeModel: StoreModel = {
|
||||
@@ -139,10 +148,10 @@ export const storeModel: StoreModel = {
|
||||
transform: [0, 0, 1],
|
||||
elements: [],
|
||||
nodes: computed((state) => state.elements.filter(isNode)),
|
||||
viewportBox: computed((state) => ({ x: 0, y: 0, width: state.width, height: state.height })),
|
||||
edges: computed((state) => state.elements.filter(isEdge)),
|
||||
selectedElements: null,
|
||||
selectedNodesBbox: { x: 0, y: 0, width: 0, height: 0 },
|
||||
viewportBox: computed((state) => ({ x: 0, y: 0, width: state.width, height: state.height })),
|
||||
|
||||
d3Zoom: null,
|
||||
d3Selection: null,
|
||||
@@ -170,6 +179,7 @@ export const storeModel: StoreModel = {
|
||||
connectionHandleId: null,
|
||||
connectionHandleType: 'source',
|
||||
connectionPosition: { x: 0, y: 0 },
|
||||
connectionMode: ConnectionMode.Strict,
|
||||
|
||||
snapGrid: [15, 15],
|
||||
snapToGrid: false,
|
||||
@@ -195,35 +205,90 @@ export const storeModel: StoreModel = {
|
||||
state.onConnectEnd = onConnectEnd;
|
||||
}),
|
||||
|
||||
setElements: action((state, elements) => {
|
||||
state.elements = elements;
|
||||
setElements: action((state, propElements) => {
|
||||
// remove deleted elements
|
||||
for (let i = 0; i < state.elements.length; i++) {
|
||||
const se = state.elements[i];
|
||||
const elementExistsInProps = propElements.find((pe) => pe.id === se.id);
|
||||
|
||||
if (!elementExistsInProps) {
|
||||
state.elements.splice(i, 1);
|
||||
i--;
|
||||
}
|
||||
}
|
||||
|
||||
propElements.forEach((el) => {
|
||||
const storeElementIndex = state.elements.findIndex((se) => se.id === el.id);
|
||||
|
||||
// update existing element
|
||||
if (storeElementIndex !== -1) {
|
||||
const storeElement = state.elements[storeElementIndex];
|
||||
|
||||
if (isNode(storeElement)) {
|
||||
const propNode = el as Node;
|
||||
const positionChanged =
|
||||
storeElement.position.x !== propNode.position.x || storeElement.position.y !== propNode.position.y;
|
||||
const typeChanged = typeof propNode.type !== 'undefined' && propNode.type !== storeElement.type;
|
||||
|
||||
state.elements[storeElementIndex] = {
|
||||
...storeElement,
|
||||
...propNode,
|
||||
};
|
||||
|
||||
if (positionChanged) {
|
||||
(state.elements[storeElementIndex] as Node).__rf.position = propNode.position;
|
||||
}
|
||||
|
||||
if (typeChanged) {
|
||||
// we reset the elements dimensions here in order to force a re-calculation of the bounds.
|
||||
// When the type of a node changes it is possible that the number or positions of handles changes too.
|
||||
(state.elements[storeElementIndex] as Node).__rf.width = null;
|
||||
}
|
||||
} else {
|
||||
state.elements[storeElementIndex] = {
|
||||
...storeElement,
|
||||
...el,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// add new element
|
||||
state.elements.push(parseElement(el));
|
||||
}
|
||||
});
|
||||
}),
|
||||
|
||||
batchUpdateNodeDimensions: action((state, { updates }) => {
|
||||
updates.forEach((update) => {
|
||||
const dimensions = getDimensions(update.nodeElement);
|
||||
const matchingIndex = state.elements.findIndex((n) => n.id === update.id);
|
||||
const matchingNode = state.elements[matchingIndex] as Node;
|
||||
|
||||
if (
|
||||
matchingIndex !== -1 &&
|
||||
dimensions.width &&
|
||||
dimensions.height &&
|
||||
(matchingNode.__rf.width !== dimensions.width || matchingNode.__rf.height !== dimensions.height)
|
||||
) {
|
||||
const handleBounds = getHandleBounds(update.nodeElement, state.transform[2]);
|
||||
|
||||
(state.elements[matchingIndex] as Node).__rf.width = dimensions.width;
|
||||
(state.elements[matchingIndex] as Node).__rf.height = dimensions.height;
|
||||
(state.elements[matchingIndex] as Node).__rf.handleBounds = handleBounds;
|
||||
}
|
||||
});
|
||||
}),
|
||||
|
||||
updateNodeDimensions: action((state, { id, nodeElement }) => {
|
||||
const dimensions = getDimensions(nodeElement);
|
||||
const matchingNode = state.nodes.find((n) => n.id === id);
|
||||
const matchingIndex = state.elements.findIndex((n) => n.id === id);
|
||||
|
||||
// only update when size change
|
||||
if (
|
||||
!matchingNode ||
|
||||
(matchingNode.__rf.width === dimensions.width && matchingNode.__rf.height === dimensions.height)
|
||||
) {
|
||||
return;
|
||||
if (matchingIndex !== -1 && dimensions.width && dimensions.height) {
|
||||
const handleBounds = getHandleBounds(nodeElement, state.transform[2]);
|
||||
|
||||
(state.elements[matchingIndex] as Node).__rf.width = dimensions.width;
|
||||
(state.elements[matchingIndex] as Node).__rf.height = dimensions.height;
|
||||
(state.elements[matchingIndex] as Node).__rf.handleBounds = handleBounds;
|
||||
}
|
||||
|
||||
const bounds = nodeElement.getBoundingClientRect();
|
||||
const handleBounds = {
|
||||
source: getHandleBounds('.source', nodeElement, bounds, state.transform[2]),
|
||||
target: getHandleBounds('.target', nodeElement, bounds, state.transform[2]),
|
||||
};
|
||||
|
||||
state.elements.forEach((n) => {
|
||||
if (n.id === id && isNode(n)) {
|
||||
n.__rf.width = dimensions.width;
|
||||
n.__rf.height = dimensions.height;
|
||||
n.__rf.handleBounds = handleBounds;
|
||||
}
|
||||
});
|
||||
}),
|
||||
|
||||
updateNodePos: action((state, { id, pos }) => {
|
||||
@@ -440,6 +505,10 @@ export const storeModel: StoreModel = {
|
||||
setMultiSelectionActive: action((state, isActive) => {
|
||||
state.multiSelectionActive = isActive;
|
||||
}),
|
||||
|
||||
setConnectionMode: action((state, connectionMode) => {
|
||||
state.connectionMode = connectionMode;
|
||||
}),
|
||||
};
|
||||
|
||||
const nodeEnv: string = (typeof __ENV__ !== 'undefined' && __ENV__) as string;
|
||||
|
||||
@@ -60,6 +60,12 @@
|
||||
stroke-dasharray: 5;
|
||||
animation: dashdraw 0.5s linear infinite;
|
||||
}
|
||||
|
||||
&.updating {
|
||||
.react-flow__edge-path {
|
||||
stroke: #777;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes dashdraw {
|
||||
@@ -236,3 +242,7 @@
|
||||
top: 50%;
|
||||
transform: translate(0, -50%);
|
||||
}
|
||||
|
||||
.react-flow__edgeupdater {
|
||||
cursor: move;
|
||||
}
|
||||
|
||||
@@ -111,7 +111,8 @@ export interface WrapEdgeProps {
|
||||
arrowHeadType?: ArrowHeadType;
|
||||
source: ElementId;
|
||||
target: ElementId;
|
||||
sourceHandleId?: string;
|
||||
sourceHandleId: ElementId | null;
|
||||
targetHandleId: ElementId | null;
|
||||
sourceX: number;
|
||||
sourceY: number;
|
||||
targetX: number;
|
||||
@@ -121,6 +122,8 @@ export interface WrapEdgeProps {
|
||||
elementsSelectable?: boolean;
|
||||
markerEndId?: string;
|
||||
isHidden?: boolean;
|
||||
handleEdgeUpdate: boolean;
|
||||
onConnectEdge: OnConnectFunc;
|
||||
}
|
||||
|
||||
export interface EdgeProps {
|
||||
@@ -224,6 +227,7 @@ export interface WrapNodeProps {
|
||||
snapToGrid?: boolean;
|
||||
snapGrid?: SnapGrid;
|
||||
isDragging?: boolean;
|
||||
resizeObserver: ResizeObserver;
|
||||
}
|
||||
|
||||
export type FitViewParams = {
|
||||
@@ -260,6 +264,11 @@ export interface Connection {
|
||||
targetHandle: ElementId | null;
|
||||
}
|
||||
|
||||
export enum ConnectionMode {
|
||||
Strict = 'strict',
|
||||
Loose = 'loose',
|
||||
}
|
||||
|
||||
export enum ConnectionLineType {
|
||||
Bezier = 'default',
|
||||
Straight = 'straight',
|
||||
@@ -283,6 +292,7 @@ export type ConnectionLineComponent = React.ComponentType<ConnectionLineComponen
|
||||
export type OnConnectFunc = (connection: Connection) => void;
|
||||
export type OnConnectStartParams = {
|
||||
nodeId: ElementId | null;
|
||||
handleId: ElementId | null;
|
||||
handleType: HandleType | null;
|
||||
};
|
||||
export type OnConnectStartFunc = (event: ReactMouseEvent, params: OnConnectStartParams) => void;
|
||||
@@ -346,3 +356,5 @@ export interface ZoomPanHelperFunctions {
|
||||
fitView: (params?: FitViewParams) => void;
|
||||
initialized: boolean;
|
||||
}
|
||||
|
||||
export type OnEdgeUpdateFunc = (oldEdge: Edge, newConnection: Connection) => void;
|
||||
|
||||
@@ -87,6 +87,32 @@ export const addEdge = (edgeParams: Edge | Connection, elements: Elements): Elem
|
||||
return elements.concat(edge);
|
||||
};
|
||||
|
||||
export const updateEdge = (oldEdge: Edge, newConnection: Connection, elements: Elements): Elements => {
|
||||
if (!newConnection.source || !newConnection.target) {
|
||||
console.warn("Can't create new edge. An edge needs a source and a target.");
|
||||
return elements;
|
||||
}
|
||||
|
||||
const foundEdge = elements.find((e) => isEdge(e) && e.id === oldEdge.id) as Edge;
|
||||
|
||||
if (!foundEdge) {
|
||||
console.warn(`The old edge with id=${oldEdge.id} does not exist.`);
|
||||
return elements;
|
||||
}
|
||||
|
||||
// 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 elements.filter((e) => e.id !== oldEdge.id).concat(edge);
|
||||
};
|
||||
|
||||
export const pointToRendererPoint = (
|
||||
{ x, y }: XYPosition,
|
||||
[tx, ty, tScale]: Transform,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { DraggableEvent } from 'react-draggable';
|
||||
import { MouseEvent as ReactMouseEvent } from 'react';
|
||||
|
||||
import { Dimensions } from '../types';
|
||||
|
||||
export const isInputDOMNode = (e: ReactMouseEvent | DraggableEvent | KeyboardEvent) => {
|
||||
const target = e?.target as HTMLElement;
|
||||
|
||||
@@ -9,7 +11,7 @@ export const isInputDOMNode = (e: ReactMouseEvent | DraggableEvent | KeyboardEve
|
||||
);
|
||||
};
|
||||
|
||||
export const getDimensions = (node: HTMLDivElement) => ({
|
||||
export const getDimensions = (node: HTMLDivElement): Dimensions => ({
|
||||
width: node.offsetWidth,
|
||||
height: node.offsetHeight,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user