Merge pull request #4548 from xyflow/handle-lookup

Improve search algorithm for close handles
This commit is contained in:
Moritz Klack
2024-08-14 16:39:50 +02:00
committed by GitHub
9 changed files with 272 additions and 107 deletions
+6
View File
@@ -0,0 +1,6 @@
---
'@xyflow/react': patch
'@xyflow/system': patch
---
Replaced algorithm used for searching close handles while connecting
+6
View File
@@ -53,6 +53,7 @@ import UseHandleConnections from '../examples/UseHandleConnections';
import AddNodeOnEdgeDrop from '../examples/AddNodeOnEdgeDrop'; import AddNodeOnEdgeDrop from '../examples/AddNodeOnEdgeDrop';
import DevTools from '../examples/DevTools'; import DevTools from '../examples/DevTools';
import Redux from '../examples/Redux'; import Redux from '../examples/Redux';
import MovingHandles from '../examples/MovingHandles';
export interface IRoute { export interface IRoute {
name: string; name: string;
@@ -206,6 +207,11 @@ const routes: IRoute[] = [
path: 'multi-setnodes', path: 'multi-setnodes',
component: MultiSetNodes, component: MultiSetNodes,
}, },
{
name: 'Moving Handles',
path: 'moving-handles',
component: MovingHandles,
},
{ {
name: 'Multi Flows', name: 'Multi Flows',
path: 'multiflows', path: 'multiflows',
@@ -2,9 +2,7 @@ import { Handle, NodeProps, Position, useConnection } from '@xyflow/react';
export default function CustomNode({ id }: NodeProps) { export default function CustomNode({ id }: NodeProps) {
const connection = useConnection(); const connection = useConnection();
const isTarget = connection.inProgress && connection.fromNode.id !== id; const isTarget = connection.inProgress && connection.fromNode.id !== id;
const label = isTarget ? 'Drop here' : 'Drag to connect'; const label = isTarget ? 'Drop here' : 'Drag to connect';
return ( return (
@@ -17,12 +15,12 @@ export default function CustomNode({ id }: NodeProps) {
}} }}
> >
{/* If handles are conditionally rendered and not present initially, you need to update the node internals https://reactflow.dev/docs/api/hooks/use-update-node-internals/ */} {/* If handles are conditionally rendered and not present initially, you need to update the node internals https://reactflow.dev/docs/api/hooks/use-update-node-internals/ */}
{/* In this case we don't need to use useUpdateNodeInternals, since !connection.inProgress is true at the beginning and all handles are rendered initially. */} {/* In this case we don't need to use useUpdateNodeInternals, since !isConnecting is true at the beginning and all handles are rendered initially. */}
{!connection.inProgress && <Handle className="customHandle" position={Position.Right} type="source" id="src" />} {!connection.inProgress && <Handle className="customHandle" position={Position.Right} type="source" />}
{/* We want to disable the target handle, if the connection was started from this node */} {/* We want to disable the target handle, if the connection was started from this node */}
{/* {(!connection.inProgress || isTarget) && ( */} {(!connection.inProgress || isTarget) && (
<Handle className="customHandle" position={Position.Left} type="target" isConnectableStart={false} id="trgt" /> <Handle className="customHandle" position={Position.Left} type="target" isConnectableStart={false} />
)}
{label} {label}
</div> </div>
</div> </div>
@@ -0,0 +1,57 @@
import React, { memo, CSSProperties } from 'react';
import { Handle, Position, NodeProps, useConnection } from '@xyflow/react';
import type { MovingHandleNode } from '.';
const sourceHandleStyle: CSSProperties = {
position: 'relative',
transform: 'translate(-50%, 0)',
top: 0,
transition: 'transform 0.5s',
};
function MovingHandleNode({}: NodeProps<MovingHandleNode>) {
const connection = useConnection();
return (
<>
<div
style={{
display: 'flex',
flexDirection: 'column',
position: 'absolute',
left: 0,
top: 0,
justifyContent: 'space-around',
height: '100%',
}}
>
<Handle
type="target"
id="a"
position={Position.Left}
style={{
...sourceHandleStyle,
transform: connection.inProgress ? 'translate(-20px, 0)' : 'translate(-50%, 0)',
}}
/>
<Handle
type="target"
id="b"
position={Position.Left}
style={{
...sourceHandleStyle,
transform: connection.inProgress ? 'translate(-20px, 0)' : 'translate(-50%, 0)',
}}
/>
</div>
<div style={{ background: '#f4f4f4', padding: 10 }}>
<div>moving handles</div>
<Handle type="source" position={Position.Right} />
<Handle type="source" position={Position.Right} />
</div>
</>
);
}
export default memo(MovingHandleNode);
@@ -0,0 +1,116 @@
import { useState, useCallback, useEffect } from 'react';
import {
ReactFlow,
Controls,
addEdge,
Node,
Position,
useEdgesState,
Background,
applyNodeChanges,
OnNodesChange,
OnConnect,
BuiltInNode,
BuiltInEdge,
NodeTypes,
ReactFlowProvider,
useConnection,
useReactFlow,
useUpdateNodeInternals,
} from '@xyflow/react';
import MovingHandleNode from './MovingHandleNode';
export type MovingHandleNode = Node<{}, 'movingHandle'>;
export type MyNode = BuiltInNode | MovingHandleNode;
export type MyEdge = BuiltInEdge;
const nodeTypes: NodeTypes = {
movingHandle: MovingHandleNode,
};
const initNodes: MyNode[] = [
{
id: 'input',
type: 'input',
data: { label: 'input' },
position: { x: -300, y: 0 },
sourcePosition: Position.Right,
},
];
for (let i = 0; i < 10; i++) {
initNodes.push({
id: `${i}`,
type: 'movingHandle',
position: { x: 0, y: i * 60 },
data: {},
});
}
const initEdges: MyEdge[] = [];
const CustomNodeFlow = () => {
const [nodes, setNodes] = useState<MyNode[]>(initNodes);
const onNodesChange: OnNodesChange<MyNode> = useCallback(
(changes) =>
setNodes((nds) => {
const nextNodes = applyNodeChanges(changes, nds);
return nextNodes;
}),
[setNodes]
);
const [edges, setEdges, onEdgesChange] = useEdgesState<MyEdge>(initEdges);
const onConnect: OnConnect = useCallback(
(connection) => setEdges((eds) => addEdge({ ...connection, animated: true }, eds)),
[setEdges]
);
return (
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
nodeTypes={nodeTypes}
minZoom={0.2}
fitView
>
<Controls />
<Background />
<NodeUpdater />
</ReactFlow>
);
};
function NodeUpdater() {
const connection = useConnection();
const { getNodes } = useReactFlow();
const updateNodeInternals = useUpdateNodeInternals();
useEffect(() => {
const startTime = Date.now();
const nodeIds = getNodes().map((n) => n.id);
function update() {
if (Date.now() - startTime < 500) {
updateNodeInternals(nodeIds);
requestAnimationFrame(update);
}
}
update();
}, [connection.inProgress]);
return null;
}
export default () => (
<ReactFlowProvider>
<CustomNodeFlow />
</ReactFlowProvider>
);
@@ -161,6 +161,7 @@ function HandleComponent(
isValidConnection: isValidConnectionStore, isValidConnection: isValidConnectionStore,
lib, lib,
rfId: flowId, rfId: flowId,
nodeLookup,
connection: connectionState, connection: connectionState,
} = store.getState(); } = store.getState();
@@ -190,6 +191,7 @@ function HandleComponent(
flowId, flowId,
doc, doc,
lib, lib,
nodeLookup,
}); });
if (isValid && connection) { if (isValid && connection) {
+12 -19
View File
@@ -15,7 +15,7 @@ import {
type Connection, type Connection,
} from '../types'; } from '../types';
import { getClosestHandle, isConnectionValid, getHandleLookup, getHandleType } from './utils'; import { getClosestHandle, isConnectionValid, getHandleType, getHandle } from './utils';
import { IsValidParams, OnPointerDownParams, Result, XYHandleInstance } from './types'; import { IsValidParams, OnPointerDownParams, Result, XYHandleInstance } from './types';
const alwaysValid = () => true; const alwaysValid = () => true;
@@ -61,19 +61,17 @@ function onPointerDown(
return; return;
} }
const fromHandleInternal = getHandle(nodeId, handleType, handleId, nodeLookup);
if (!fromHandleInternal) {
return;
}
let position = getEventPosition(event, containerBounds); let position = getEventPosition(event, containerBounds);
let autoPanStarted = false; let autoPanStarted = false;
let connection: Connection | null = null; let connection: Connection | null = null;
let isValid: boolean | null = false; let isValid: boolean | null = false;
let handleDomNode: Element | null = null; let handleDomNode: Element | null = null;
const [handleLookup, fromHandleInternal] = getHandleLookup({
nodeLookup,
nodeId,
handleId,
handleType,
});
// when the user is moving the mouse close to the edge of the canvas while connecting we move the canvas // when the user is moving the mouse close to the edge of the canvas while connecting we move the canvas
function autoPan(): void { function autoPan(): void {
if (!autoPanOnConnect || !containerBounds) { if (!autoPanOnConnect || !containerBounds) {
@@ -128,7 +126,8 @@ function onPointerDown(
closestHandle = getClosestHandle( closestHandle = getClosestHandle(
pointToRendererPoint(position, transform, false, [1, 1]), pointToRendererPoint(position, transform, false, [1, 1]),
connectionRadius, connectionRadius,
handleLookup nodeLookup,
fromHandle
); );
if (!autoPanStarted) { if (!autoPanStarted) {
@@ -146,7 +145,7 @@ function onPointerDown(
doc, doc,
lib, lib,
flowId, flowId,
handleLookup, nodeLookup,
}); });
handleDomNode = result.handleDomNode; handleDomNode = result.handleDomNode;
@@ -238,7 +237,7 @@ function isValidHandle(
lib, lib,
flowId, flowId,
isValidConnection = alwaysValid, isValidConnection = alwaysValid,
handleLookup, nodeLookup,
}: IsValidParams }: IsValidParams
) { ) {
const isTarget = fromType === 'target'; const isTarget = fromType === 'target';
@@ -266,7 +265,7 @@ function isValidHandle(
const connectable = handleToCheck.classList.contains('connectable'); const connectable = handleToCheck.classList.contains('connectable');
const connectableEnd = handleToCheck.classList.contains('connectableend'); const connectableEnd = handleToCheck.classList.contains('connectableend');
if (!handleNodeId) { if (!handleNodeId || !handleType) {
return result; return result;
} }
@@ -289,13 +288,7 @@ function isValidHandle(
result.isValid = isValid && isValidConnection(connection); result.isValid = isValid && isValidConnection(connection);
const toHandle = handleLookup?.get(`${handleNodeId}-${handleType}-${handleId}`); result.toHandle = getHandle(handleNodeId, handleType, handleId, nodeLookup, false);
if (toHandle) {
result.toHandle = {
...toHandle,
};
}
} }
return result; return result;
+1 -1
View File
@@ -48,7 +48,7 @@ export type IsValidParams = {
doc: Document | ShadowRoot; doc: Document | ShadowRoot;
lib: string; lib: string;
flowId: string | null; flowId: string | null;
handleLookup?: Map<string, Handle>; nodeLookup: NodeLookup;
}; };
export type XYHandleInstance = { export type XYHandleInstance = {
+67 -80
View File
@@ -1,109 +1,96 @@
import { getHandlePosition } from '../utils'; import { getHandlePosition, getOverlappingArea, nodeToRect } from '../utils';
import { import type { HandleType, XYPosition, Handle, InternalNodeBase, NodeLookup } from '../types';
type HandleType,
type NodeHandleBounds,
type XYPosition,
type Handle,
InternalNodeBase,
NodeLookup,
} from '../types';
// this functions collects all handles and adds an absolute position function getNodesWithinDistance(position: XYPosition, nodeLookup: NodeLookup, distance: number): InternalNodeBase[] {
// so that we can later find the closest handle to the mouse position const nodes: InternalNodeBase[] = [];
function getHandles( const rect = {
node: InternalNodeBase, x: position.x - distance,
handleBounds: NodeHandleBounds, y: position.y - distance,
type: HandleType, width: distance * 2,
currentHandle: { nodeId: string; handleId: string | null; handleType: HandleType } height: distance * 2,
): [Handle[], Handle | null] { };
let excludedHandle = null;
const handles = (handleBounds[type] || []).reduce<Handle[]>((res, handle) => { for (const node of nodeLookup.values()) {
if (node.id === currentHandle.nodeId && type === currentHandle.handleType && handle.id === currentHandle.handleId) { if (getOverlappingArea(rect, nodeToRect(node)) > 0) {
excludedHandle = handle; nodes.push(node);
} else {
const handleXY = getHandlePosition(node, handle, handle.position, true);
res.push({ ...handle, ...handleXY });
} }
return res; }
}, []);
return [handles, excludedHandle]; return nodes;
} }
// this distance is used for the area around the user pointer
// while doing a connection for finding the closest nodes
const ADDITIONAL_DISTANCE = 250;
export function getClosestHandle( export function getClosestHandle(
pos: XYPosition, position: XYPosition,
connectionRadius: number, connectionRadius: number,
handleLookup: Map<string, Handle> nodeLookup: NodeLookup,
fromHandle: { nodeId: string; type: HandleType; id?: string | null }
): Handle | null { ): Handle | null {
let closestHandles: Handle[] = []; let closestHandles: Handle[] = [];
let minDistance = Infinity; let minDistance = Infinity;
for (const handle of handleLookup.values()) { const closeNodes = getNodesWithinDistance(position, nodeLookup, connectionRadius + ADDITIONAL_DISTANCE);
const distance = Math.sqrt(Math.pow(handle.x - pos.x, 2) + Math.pow(handle.y - pos.y, 2));
if (distance <= connectionRadius) { for (const node of closeNodes) {
const allHandles = [...(node.internals.handleBounds?.source ?? []), ...(node.internals.handleBounds?.target ?? [])];
for (const handle of allHandles) {
// if the handle is the same as the fromHandle we skip it
if (fromHandle.nodeId === handle.nodeId && fromHandle.type === handle.type && fromHandle.id === handle.id) {
continue;
}
// determine absolute position of the handle
const { x, y } = getHandlePosition(node, handle, handle.position, true);
const distance = Math.sqrt(Math.pow(x - position.x, 2) + Math.pow(y - position.y, 2));
if (distance > connectionRadius) {
continue;
}
if (distance < minDistance) { if (distance < minDistance) {
closestHandles = [handle]; closestHandles = [{ ...handle, x, y }];
minDistance = distance;
} else if (distance === minDistance) { } else if (distance === minDistance) {
// when multiple handles are on the same distance we collect all of them // when multiple handles are on the same distance we collect all of them
closestHandles.push(handle); closestHandles.push({ ...handle, x, y });
} }
minDistance = distance;
} }
} }
if (!closestHandles.length) { if (!closestHandles.length) {
return null; return null;
} }
// when multiple handles overlay each other we prefer the opposite handle
if (closestHandles.length > 1) {
const oppositeHandleType = fromHandle.type === 'source' ? 'target' : 'source';
return closestHandles.find((handle) => handle.type === oppositeHandleType) ?? closestHandles[0];
}
return closestHandles.length === 1 return closestHandles[0];
? closestHandles[0]
: // if multiple handles are layouted on top of each other we take the one with type = target because it's more likely that the user wants to connect to this one
closestHandles.find((handle) => handle.type === 'target') || closestHandles[0];
} }
type GetHandleLookupParams = { export function getHandle(
nodeLookup: NodeLookup; nodeId: string,
nodeId: string; handleType: HandleType,
handleId: string | null; handleId: string | null,
handleType: HandleType; nodeLookup: NodeLookup,
}; withAbsolutePosition = false
): Handle | null {
export function getHandleLookup({ const node = nodeLookup.get(nodeId);
nodeLookup, if (!node) {
nodeId, return null;
handleId,
handleType,
}: GetHandleLookupParams): [Map<string, Handle>, Handle] {
const connectionHandles: Map<string, Handle> = new Map();
const currentHandle = { nodeId, handleId, handleType };
let matchingHandle: Handle | null = null;
for (const node of nodeLookup.values()) {
if (node.internals.handleBounds) {
const [sourceHandles, excludedSource] = getHandles(node, node.internals.handleBounds, 'source', currentHandle);
const [targetHandles, excludedTarget] = getHandles(node, node.internals.handleBounds, 'target', currentHandle);
matchingHandle = matchingHandle ? matchingHandle : excludedSource ?? excludedTarget;
[...sourceHandles, ...targetHandles].forEach((handle) =>
connectionHandles.set(`${handle.nodeId}-${handle.type}-${handle.id}`, handle)
);
}
} }
// if the user only works with handles that are type="source" + connectionMode="loose" const handles = node.internals.handleBounds?.[handleType];
// it happens that we can't find a matching handle. The reason for this is, that the const handle = (handleId ? handles?.find((h) => h.id === handleId) : handles?.[0]) ?? null;
// edge don't know about the handles and always assumes that there is source and a target.
// In this case we need to find the matching handle by switching the handleType
if (!matchingHandle) {
const node = nodeLookup.get(nodeId);
if (node?.internals.handleBounds) {
currentHandle.handleType = handleType === 'source' ? 'target' : 'source';
const [, excluded] = getHandles(node, node.internals.handleBounds, currentHandle.handleType, currentHandle);
matchingHandle = excluded;
}
}
return [connectionHandles, matchingHandle!]; return handle && withAbsolutePosition
? { ...handle, ...getHandlePosition(node, handle, handle.position, true) }
: handle;
} }
export function getHandleType( export function getHandleType(