refactor(handle-handling): cleanup

This commit is contained in:
moklick
2020-10-29 12:36:10 +01:00
parent 15d0900ba9
commit ddd3baa5f7
10 changed files with 78 additions and 63 deletions
+2 -2
View File
@@ -15,8 +15,8 @@ export default memo(({ data }) => {
Custom Color Picker Node: <strong>{data.color}</strong> Custom Color Picker Node: <strong>{data.color}</strong>
</div> </div>
<input className="nodrag" type="color" onChange={data.onChange} defaultValue={data.color} /> <input className="nodrag" type="color" onChange={data.onChange} defaultValue={data.color} />
<Handle type="source" position="right" id="0" style={{ top: 10, background: '#555' }} /> <Handle type="source" position="right" id="a" style={{ top: 10, background: '#555' }} />
<Handle type="source" position="right" id="1" style={{ bottom: 10, top: 'auto', background: '#555' }} /> <Handle type="source" position="right" id="b" style={{ bottom: 10, top: 'auto', background: '#555' }} />
</> </>
); );
}); });
+2 -2
View File
@@ -56,8 +56,8 @@ const CustomNodeFlow = () => {
{ id: '4', type: 'output', data: { label: 'Output B' }, position: { x: 550, y: 100 }, targetPosition: 'left' }, { id: '4', type: 'output', data: { label: 'Output B' }, position: { x: 550, y: 100 }, targetPosition: 'left' },
{ id: 'e1-2', source: '1', target: '2', animated: true, style: { stroke: '#fff' } }, { id: 'e1-2', source: '1', target: '2', animated: true, style: { stroke: '#fff' } },
{ id: 'e2a-3', source: '2', sourceHandle: '0', target: '3', animated: true, style: { stroke: '#fff' } }, { id: 'e2a-3', source: '2', sourceHandle: 'a', target: '3', animated: true, style: { stroke: '#fff' } },
{ id: 'e2b-4', source: '2', sourceHandle: '1', target: '4', animated: true, style: { stroke: '#fff' } }, { id: 'e2b-4', source: '2', sourceHandle: 'b', target: '4', animated: true, style: { stroke: '#fff' } },
]); ]);
}, []); }, []);
+1 -1
View File
@@ -20,7 +20,7 @@ const onConnectEnd = (event) => console.log('on connect end', event);
const CustomInput = () => ( const CustomInput = () => (
<> <>
<div>Only connectable with B</div> <div>Only connectable with B</div>
<Handle type="source" position="right" id="a" isValidConnection={isValidConnection} /> <Handle type="source" position="right" isValidConnection={isValidConnection} />
</> </>
); );
+4 -4
View File
@@ -15,6 +15,7 @@ import {
interface ConnectionLineProps { interface ConnectionLineProps {
connectionNodeId: ElementId; connectionNodeId: ElementId;
connectionHandleId: ElementId | null;
connectionHandleType: HandleType; connectionHandleType: HandleType;
connectionPositionX: number; connectionPositionX: number;
connectionPositionY: number; connectionPositionY: number;
@@ -28,6 +29,7 @@ interface ConnectionLineProps {
export default ({ export default ({
connectionNodeId, connectionNodeId,
connectionHandleId,
connectionHandleType, connectionHandleType,
connectionLineStyle, connectionLineStyle,
connectionPositionX, connectionPositionX,
@@ -39,10 +41,8 @@ export default ({
CustomConnectionLineComponent, CustomConnectionLineComponent,
}: ConnectionLineProps) => { }: ConnectionLineProps) => {
const [sourceNode, setSourceNode] = useState<Node | null>(null); const [sourceNode, setSourceNode] = useState<Node | null>(null);
const hasHandleId = connectionNodeId.includes('__'); const nodeId = connectionNodeId;
const sourceIdSplitted = connectionNodeId.split('__'); const handleId = connectionHandleId;
const nodeId = sourceIdSplitted[0];
const handleId = hasHandleId ? sourceIdSplitted[1] : null;
useEffect(() => { useEffect(() => {
const nextSourceNode = nodes.find((n) => n.id === nodeId) || null; const nextSourceNode = nodes.find((n) => n.id === nodeId) || null;
+12 -8
View File
@@ -28,7 +28,7 @@ interface BaseHandleProps {
setConnectionNodeId: SetSourceIdFunc; setConnectionNodeId: SetSourceIdFunc;
setPosition: (pos: XYPosition) => void; setPosition: (pos: XYPosition) => void;
isValidConnection: ValidConnectionFunc; isValidConnection: ValidConnectionFunc;
id?: ElementId | boolean; id?: ElementId | null;
className?: string; className?: string;
style?: CSSProperties; style?: CSSProperties;
} }
@@ -42,7 +42,7 @@ type Result = {
function onMouseDown( function onMouseDown(
event: ReactMouseEvent, event: ReactMouseEvent,
handleId: ElementId, handleId: ElementId | null,
nodeId: ElementId, nodeId: ElementId,
setConnectionNodeId: SetSourceIdFunc, setConnectionNodeId: SetSourceIdFunc,
setPosition: (pos: XYPosition) => void, setPosition: (pos: XYPosition) => void,
@@ -67,7 +67,7 @@ function onMouseDown(
x: event.clientX - containerBounds.left, x: event.clientX - containerBounds.left,
y: event.clientY - containerBounds.top, y: event.clientY - containerBounds.top,
}); });
setConnectionNodeId({ connectionNodeId: nodeId, connectionHandleType: handleType }); setConnectionNodeId({ connectionNodeId: nodeId, connectionHandleId: handleId, connectionHandleType: handleType });
if (onConnectStart) { if (onConnectStart) {
onConnectStart(event, { nodeId, handleType }); onConnectStart(event, { nodeId, handleType });
@@ -95,7 +95,10 @@ function onMouseDown(
if (elementBelow && (elementBelow.classList.contains('target') || elementBelow.classList.contains('source'))) { if (elementBelow && (elementBelow.classList.contains('target') || elementBelow.classList.contains('source'))) {
result.isHoveringHandle = true; result.isHoveringHandle = true;
if ((isTarget && elementBelow.classList.contains('source')) || (!isTarget && elementBelow.classList.contains('target'))) { if (
(isTarget && elementBelow.classList.contains('source')) ||
(!isTarget && elementBelow.classList.contains('target'))
) {
let connection: Connection = { source: null, target: null, sourceHandle: null, targetHandle: null }; let connection: Connection = { source: null, target: null, sourceHandle: null, targetHandle: null };
if (isTarget) { if (isTarget) {
@@ -105,7 +108,7 @@ function onMouseDown(
} else { } else {
const targetId = elementBelow.getAttribute('data-nodeid'); const targetId = elementBelow.getAttribute('data-nodeid');
const targetHandleId = elementBelow.getAttribute('data-handleid'); const targetHandleId = elementBelow.getAttribute('data-handleid');
connection = { source: nodeId, sourceHandle: handleId, target: targetId , targetHandle: targetHandleId}; connection = { source: nodeId, sourceHandle: handleId, target: targetId, targetHandle: targetHandleId };
} }
const isValid = isValidConnection(connection); const isValid = isValidConnection(connection);
@@ -155,7 +158,7 @@ function onMouseDown(
} }
resetRecentHandle(); resetRecentHandle();
setConnectionNodeId({ connectionNodeId: null, connectionHandleType: null }); setConnectionNodeId({ connectionNodeId: null, connectionHandleId: null, connectionHandleType: null });
document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp); document.removeEventListener('mouseup', onMouseUp);
@@ -176,7 +179,7 @@ const BaseHandle = ({
setConnectionNodeId, setConnectionNodeId,
setPosition, setPosition,
className, className,
id = false, id = null,
isValidConnection, isValidConnection,
...rest ...rest
}: BaseHandleProps) => { }: BaseHandleProps) => {
@@ -192,7 +195,8 @@ const BaseHandle = ({
}, },
]); ]);
const handleId = id ? `${id}`: '' const handleId = id || null;
return ( return (
<div <div
data-handleid={handleId} data-handleid={handleId}
+2 -2
View File
@@ -25,8 +25,8 @@ export const getHandleBounds = (
return { return {
id: handleId, id: handleId,
position: handlePosition, position: handlePosition,
x: (bounds.left - parentBounds.left) * (1 / k), x: (bounds.left - parentBounds.left) / k,
y: (bounds.top - parentBounds.top) * (1 / k), y: (bounds.top - parentBounds.top) / k,
...dimensions, ...dimensions,
}; };
} }
+24 -6
View File
@@ -98,6 +98,10 @@ function getHandle(bounds: HandleElement[], handleId: ElementId | null): HandleE
handle = bounds.find((d) => d.id === handleId); handle = bounds.find((d) => d.id === handleId);
} }
if (typeof handle === 'undefined') {
return null;
}
return handle; return handle;
} }
@@ -132,20 +136,22 @@ function renderEdge(
selectedElements: Elements | null, selectedElements: Elements | null,
elementsSelectable: boolean elementsSelectable: boolean
) { ) {
const sourceId = edge.source const sourceId = edge.source;
const sourceHandleId = edge.sourceHandle! const sourceHandleId = edge.sourceHandle || null;
const targetId = edge.target const targetId = edge.target;
const targetHandleId = edge.targetHandle! const targetHandleId = edge.targetHandle || null;
const sourceNode = nodes.find((n) => n.id === sourceId); const sourceNode = nodes.find((n) => n.id === sourceId);
const targetNode = nodes.find((n) => n.id === targetId); const targetNode = nodes.find((n) => n.id === targetId);
if (!sourceNode) { 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) { 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) { if (!sourceNode.__rf.width || !sourceNode.__rf.height) {
@@ -159,6 +165,16 @@ function renderEdge(
const sourcePosition = sourceHandle ? sourceHandle.position : Position.Bottom; const sourcePosition = sourceHandle ? sourceHandle.position : Position.Bottom;
const targetPosition = targetHandle ? targetHandle.position : Position.Top; 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( const { sourceX, sourceY, targetX, targetY } = getEdgePositions(
sourceNode, sourceNode,
sourceHandle, sourceHandle,
@@ -210,6 +226,7 @@ const EdgeRenderer = (props: EdgeRendererProps) => {
const edges = useStoreState((state) => state.edges); const edges = useStoreState((state) => state.edges);
const nodes = useStoreState((state) => state.nodes); const nodes = useStoreState((state) => state.nodes);
const connectionNodeId = useStoreState((state) => state.connectionNodeId); const connectionNodeId = useStoreState((state) => state.connectionNodeId);
const connectionHandleId = useStoreState((state) => state.connectionHandleId);
const connectionHandleType = useStoreState((state) => state.connectionHandleType); const connectionHandleType = useStoreState((state) => state.connectionHandleType);
const connectionPosition = useStoreState((state) => state.connectionPosition); const connectionPosition = useStoreState((state) => state.connectionPosition);
const selectedElements = useStoreState((state) => state.selectedElements); const selectedElements = useStoreState((state) => state.selectedElements);
@@ -236,6 +253,7 @@ const EdgeRenderer = (props: EdgeRendererProps) => {
<ConnectionLine <ConnectionLine
nodes={nodes} nodes={nodes}
connectionNodeId={connectionNodeId!} connectionNodeId={connectionNodeId!}
connectionHandleId={connectionHandleId}
connectionHandleType={connectionHandleType!} connectionHandleType={connectionHandleType!}
connectionPositionX={connectionPosition.x} connectionPositionX={connectionPosition.x}
connectionPositionY={connectionPosition.y} connectionPositionY={connectionPosition.y}
+4 -1
View File
@@ -72,6 +72,7 @@ export interface StoreModel {
userSelectionRect: SelectionRect; userSelectionRect: SelectionRect;
connectionNodeId: ElementId | null; connectionNodeId: ElementId | null;
connectionHandleId: ElementId | null;
connectionHandleType: HandleType | null; connectionHandleType: HandleType | null;
connectionPosition: XYPosition; connectionPosition: XYPosition;
@@ -177,6 +178,7 @@ export const storeModel: StoreModel = {
draw: false, draw: false,
}, },
connectionNodeId: null, connectionNodeId: null,
connectionHandleId: null,
connectionHandleType: 'source', connectionHandleType: 'source',
connectionPosition: { x: 0, y: 0 }, connectionPosition: { x: 0, y: 0 },
@@ -416,8 +418,9 @@ export const storeModel: StoreModel = {
state.connectionPosition = position; state.connectionPosition = position;
}), }),
setConnectionNodeId: action((state, { connectionNodeId, connectionHandleType }) => { setConnectionNodeId: action((state, { connectionNodeId, connectionHandleId, connectionHandleType }) => {
state.connectionNodeId = connectionNodeId; state.connectionNodeId = connectionNodeId;
state.connectionHandleId = connectionHandleId;
state.connectionHandleType = connectionHandleType; state.connectionHandleType = connectionHandleType;
}), }),
+4 -3
View File
@@ -60,8 +60,8 @@ export interface Edge {
type?: string; type?: string;
source: ElementId; source: ElementId;
target: ElementId; target: ElementId;
sourceHandle?: ElementId; sourceHandle?: ElementId | null;
targetHandle?: ElementId; targetHandle?: ElementId | null;
label?: string; label?: string;
labelStyle?: CSSProperties; labelStyle?: CSSProperties;
labelShowBg?: boolean; labelShowBg?: boolean;
@@ -280,6 +280,7 @@ export type OnConnectEndFunc = (event: MouseEvent) => void;
export type SetConnectionId = { export type SetConnectionId = {
connectionNodeId: ElementId | null; connectionNodeId: ElementId | null;
connectionHandleId: ElementId | null;
connectionHandleType: HandleType | null; connectionHandleType: HandleType | null;
}; };
@@ -294,7 +295,7 @@ export interface HandleProps {
isConnectable?: boolean; isConnectable?: boolean;
onConnect?: OnConnectFunc; onConnect?: OnConnectFunc;
isValidConnection?: (connection: Connection) => boolean; isValidConnection?: (connection: Connection) => boolean;
id?: string; id?: ElementId;
style?: CSSProperties; style?: CSSProperties;
className?: string; className?: string;
} }
+23 -34
View File
@@ -40,43 +40,29 @@ export const removeElements = (elementsToRemove: Elements, elements: Elements):
}); });
}; };
const getEdgeId = ({ source, sourceHandle, target, targetHandle }: Connection): ElementId => `reactflow__edge-${source}${sourceHandle}-${target}${targetHandle}`; const getEdgeId = ({ source, sourceHandle, target, targetHandle }: Connection): ElementId =>
`reactflow__edge-${source}${sourceHandle}-${target}${targetHandle}`;
const existingConnection = (edge: Edge, elements: Elements) => {
for (const element of elements) {
if (isEdge(element)) {
if (element.source === edge.source && element.sourceHandle === edge.sourceHandle && element.target === edge.target && element.targetHandle === edge.targetHandle) {
return true
}
}
}
return false
}
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 => { export const addEdge = (edgeParams: Edge | Connection, elements: Elements): Elements => {
if (!edgeParams.source || !edgeParams.target) { 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 let edge: Edge;
[edgeParams.source, edgeParams.target].forEach((id) => {
if (!elements.find((e) => isNode(e) && e.id === id)) {
throw new Error(`Can't create edge. Node with id=${id} does not exist.`);
}
});
// make sure that the handles exists in each node
const handleElements = Array.from(document.getElementsByClassName("react-flow__handle")) as HTMLDivElement[]
[[edgeParams.source, edgeParams.sourceHandle], [edgeParams.target, edgeParams.targetHandle]].forEach(([nodeId, handleId]) => {
if (!handleElements.find((he) => he.getAttribute('data-nodeid') === nodeId && he.getAttribute('data-handleid') === handleId)) {
throw new Error(`Can't create edge. Handle with id=${handleId} does not exist within Node with id=${nodeId}.`);
}
})
let edge: Edge
if (isEdge(edgeParams)) { if (isEdge(edgeParams)) {
edge = {...edgeParams} edge = { ...edgeParams };
} else { } else {
edge = { edge = {
...edgeParams, ...edgeParams,
@@ -84,8 +70,11 @@ export const addEdge = (edgeParams: Edge | Connection, elements: Elements): Elem
} as Edge; } as Edge;
} }
if (existingConnection(edge, elements)) {return elements} if (connectionExists(edge, elements)) {
return elements.concat(edge) return elements;
}
return elements.concat(edge);
}; };
export const pointToRendererPoint = ( export const pointToRendererPoint = (
@@ -133,8 +122,8 @@ export const parseElement = (element: Node | Edge): Node | Edge => {
...element, ...element,
source: element.source.toString(), source: element.source.toString(),
target: element.target.toString(), target: element.target.toString(),
sourceHandle: element.sourceHandle ? element.sourceHandle.toString() : '', sourceHandle: element.sourceHandle ? element.sourceHandle.toString() : null,
targetHandle: element.targetHandle ? element.targetHandle.toString() : '', targetHandle: element.targetHandle ? element.targetHandle.toString() : null,
id: element.id.toString(), id: element.id.toString(),
type: element.type || 'default', type: element.type || 'default',
}; };