feat(connection-radius): use closest handle / snappy edges #2759
This commit is contained in:
@@ -1,9 +1,10 @@
|
|||||||
import type { MouseEvent as ReactMouseEvent } from 'react';
|
import type { MouseEvent as ReactMouseEvent } from 'react';
|
||||||
import { StoreApi } from 'zustand';
|
import { StoreApi } from 'zustand';
|
||||||
|
|
||||||
import { getHostForElement, calcAutoPanVelocity } from '../../utils';
|
import { getHostForElement, calcAutoPanVelocity, internalsSymbol } from '../../utils';
|
||||||
import { ConnectionMode } from '../../types';
|
import { ConnectionMode, Node, NodeHandleBounds } from '../../types';
|
||||||
import type { OnConnect, Connection, HandleType, ReactFlowState, XYPosition } from '../../types';
|
import type { OnConnect, Connection, HandleType, ReactFlowState, XYPosition } from '../../types';
|
||||||
|
import { pointToRendererPoint, rendererPointToPoint } from '../../utils/graph';
|
||||||
|
|
||||||
type ValidConnectionFunc = (connection: Connection) => boolean;
|
type ValidConnectionFunc = (connection: Connection) => boolean;
|
||||||
|
|
||||||
@@ -15,55 +16,60 @@ type Result = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// checks if element below mouse is a handle and returns connection in form of an object { source: 123, target: 312 }
|
// checks if element below mouse is a handle and returns connection in form of an object { source: 123, target: 312 }
|
||||||
export function checkElementBelowIsValid(
|
export function isHandleValid(
|
||||||
event: MouseEvent,
|
handle: Pick<ConnectionHandle, 'nodeId' | 'id' | 'type'> | undefined,
|
||||||
connectionMode: ConnectionMode,
|
connectionMode: ConnectionMode,
|
||||||
isTarget: boolean,
|
fromNodeId: string,
|
||||||
nodeId: string,
|
fromHandleId: string | null,
|
||||||
handleId: string | null,
|
fromType: string,
|
||||||
isValidConnection: ValidConnectionFunc,
|
isValidConnection: ValidConnectionFunc,
|
||||||
doc: Document | ShadowRoot
|
doc: Document | ShadowRoot
|
||||||
) {
|
) {
|
||||||
const elementBelow = doc.elementFromPoint(event.clientX, event.clientY);
|
|
||||||
const elementBelowIsTarget = elementBelow?.classList.contains('target') || false;
|
|
||||||
const elementBelowIsSource = elementBelow?.classList.contains('source') || false;
|
|
||||||
|
|
||||||
const result: Result = {
|
const result: Result = {
|
||||||
elementBelow,
|
elementBelow: null,
|
||||||
isValid: false,
|
isValid: false,
|
||||||
connection: { source: null, target: null, sourceHandle: null, targetHandle: null },
|
connection: { source: null, target: null, sourceHandle: null, targetHandle: null },
|
||||||
isHoveringHandle: false,
|
isHoveringHandle: false,
|
||||||
};
|
};
|
||||||
|
const isTarget = fromType === 'target';
|
||||||
|
|
||||||
if (elementBelow && (elementBelowIsTarget || elementBelowIsSource)) {
|
if (handle) {
|
||||||
result.isHoveringHandle = true;
|
const elementBelow = doc.querySelector(
|
||||||
|
`.react-flow__handle[data-id="${handle?.nodeId}-${handle?.id}-${handle?.type}"]`
|
||||||
|
);
|
||||||
|
|
||||||
const elementBelowNodeId = elementBelow.getAttribute('data-nodeid');
|
if (elementBelow) {
|
||||||
const elementBelowHandleId = elementBelow.getAttribute('data-handleid');
|
const elementBelowIsTarget = handle.type === 'target';
|
||||||
const connection: Connection = isTarget
|
const elementBelowIsSource = handle.type === 'source';
|
||||||
? {
|
result.isHoveringHandle = true;
|
||||||
source: elementBelowNodeId,
|
|
||||||
sourceHandle: elementBelowHandleId,
|
|
||||||
target: nodeId,
|
|
||||||
targetHandle: handleId,
|
|
||||||
}
|
|
||||||
: {
|
|
||||||
source: nodeId,
|
|
||||||
sourceHandle: handleId,
|
|
||||||
target: elementBelowNodeId,
|
|
||||||
targetHandle: elementBelowHandleId,
|
|
||||||
};
|
|
||||||
|
|
||||||
result.connection = connection;
|
const elementBelowNodeId = elementBelow.getAttribute('data-nodeid');
|
||||||
|
const elementBelowHandleId = elementBelow.getAttribute('data-handleid');
|
||||||
|
const connection: Connection = isTarget
|
||||||
|
? {
|
||||||
|
source: handle.nodeId,
|
||||||
|
sourceHandle: handle.id,
|
||||||
|
target: fromNodeId,
|
||||||
|
targetHandle: fromHandleId,
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
source: fromNodeId,
|
||||||
|
sourceHandle: fromHandleId,
|
||||||
|
target: handle.nodeId,
|
||||||
|
targetHandle: handle.id,
|
||||||
|
};
|
||||||
|
|
||||||
// in strict mode we don't allow target to target or source to source connections
|
result.connection = connection;
|
||||||
const isValid =
|
|
||||||
connectionMode === ConnectionMode.Strict
|
|
||||||
? (isTarget && elementBelowIsSource) || (!isTarget && elementBelowIsTarget)
|
|
||||||
: elementBelowNodeId !== nodeId || elementBelowHandleId !== handleId;
|
|
||||||
|
|
||||||
if (isValid) {
|
// in strict mode we don't allow target to target or source to source connections
|
||||||
result.isValid = isValidConnection(connection);
|
const isValid =
|
||||||
|
connectionMode === ConnectionMode.Strict
|
||||||
|
? (isTarget && elementBelowIsSource) || (!isTarget && elementBelowIsTarget)
|
||||||
|
: elementBelowNodeId !== handle.nodeId || elementBelowHandleId !== handle.id;
|
||||||
|
|
||||||
|
if (isValid) {
|
||||||
|
result.isValid = isValidConnection(connection);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,6 +81,53 @@ function resetRecentHandle(hoveredHandle: Element): void {
|
|||||||
hoveredHandle?.classList.remove('react-flow__handle-connecting');
|
hoveredHandle?.classList.remove('react-flow__handle-connecting');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ConnectionHandle = {
|
||||||
|
id: string | null;
|
||||||
|
type: HandleType;
|
||||||
|
nodeId: string;
|
||||||
|
absX: number;
|
||||||
|
absY: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function getHandles(
|
||||||
|
node: Node,
|
||||||
|
handleBounds: NodeHandleBounds,
|
||||||
|
type: HandleType,
|
||||||
|
currentHandle: string
|
||||||
|
): ConnectionHandle[] {
|
||||||
|
return (handleBounds[type] || []).reduce<ConnectionHandle[]>((res, h) => {
|
||||||
|
if (`${node.id}-${h.id}-${type}` !== currentHandle) {
|
||||||
|
res.push({
|
||||||
|
id: h.id || null,
|
||||||
|
type,
|
||||||
|
nodeId: node.id,
|
||||||
|
absX: (node.positionAbsolute?.x ?? 0) + h.x,
|
||||||
|
absY: (node.positionAbsolute?.y ?? 0) + h.y,
|
||||||
|
width: h.width,
|
||||||
|
height: h.height,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}, []);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getClosestHandle(pos: XYPosition, connectionRadius: number, handles: ConnectionHandle[]) {
|
||||||
|
let closestHandle: ConnectionHandle | undefined;
|
||||||
|
let minDistance = Infinity;
|
||||||
|
|
||||||
|
handles.forEach((handle) => {
|
||||||
|
const distance = Math.sqrt(Math.pow(handle.absX - pos.x, 2) + Math.pow(handle.absY - pos.y, 2));
|
||||||
|
if (distance <= connectionRadius && distance < minDistance) {
|
||||||
|
minDistance = distance;
|
||||||
|
closestHandle = handle;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return closestHandle;
|
||||||
|
}
|
||||||
|
|
||||||
export function handleMouseDown({
|
export function handleMouseDown({
|
||||||
event,
|
event,
|
||||||
handleId,
|
handleId,
|
||||||
@@ -100,9 +153,10 @@ export function handleMouseDown({
|
|||||||
}): void {
|
}): void {
|
||||||
// when react-flow is used inside a shadow root we can't use document
|
// when react-flow is used inside a shadow root we can't use document
|
||||||
const doc = getHostForElement(event.target as HTMLElement);
|
const doc = getHostForElement(event.target as HTMLElement);
|
||||||
const { onConnectStart, movePane, connectionMode, domNode, autoPanOnConnect } = getState();
|
const { onConnectStart, movePane, connectionMode, domNode, autoPanOnConnect, connectionRadius } = getState();
|
||||||
let connectionPosition: XYPosition = { x: 0, y: 0 };
|
let connectionPosition: XYPosition = { x: 0, y: 0 };
|
||||||
let autoPanId = 0;
|
let autoPanId = 0;
|
||||||
|
let prevClosestHandle: ConnectionHandle | undefined;
|
||||||
|
|
||||||
// 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
|
||||||
const autoPan = (): void => {
|
const autoPan = (): void => {
|
||||||
@@ -148,22 +202,55 @@ export function handleMouseDown({
|
|||||||
});
|
});
|
||||||
onConnectStart?.(event, { nodeId, handleId, handleType });
|
onConnectStart?.(event, { nodeId, handleId, handleType });
|
||||||
|
|
||||||
|
const handles = getState()
|
||||||
|
.getNodes()
|
||||||
|
.reduce<ConnectionHandle[]>((res, node) => {
|
||||||
|
if (node[internalsSymbol]) {
|
||||||
|
const { handleBounds } = node[internalsSymbol];
|
||||||
|
let sourceHandles: ConnectionHandle[] = [];
|
||||||
|
let targetHandles: ConnectionHandle[] = [];
|
||||||
|
|
||||||
|
if (handleBounds) {
|
||||||
|
sourceHandles = getHandles(node, handleBounds, 'source', `${nodeId}-${handleId}-${handleType}`);
|
||||||
|
targetHandles = getHandles(node, handleBounds, 'target', `${nodeId}-${handleId}-${handleType}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
res.push(...sourceHandles, ...targetHandles);
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}, []);
|
||||||
|
|
||||||
function onMouseMove(event: MouseEvent) {
|
function onMouseMove(event: MouseEvent) {
|
||||||
|
const { transform } = getState();
|
||||||
connectionPosition = {
|
connectionPosition = {
|
||||||
x: event.clientX - containerBounds.left,
|
x: event.clientX - containerBounds.left,
|
||||||
y: event.clientY - containerBounds.top,
|
y: event.clientY - containerBounds.top,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
prevClosestHandle = getClosestHandle(
|
||||||
|
pointToRendererPoint(connectionPosition, transform, false, [1, 1]),
|
||||||
|
connectionRadius,
|
||||||
|
handles
|
||||||
|
);
|
||||||
|
|
||||||
setState({
|
setState({
|
||||||
connectionPosition,
|
connectionPosition: prevClosestHandle
|
||||||
|
? rendererPointToPoint(
|
||||||
|
{
|
||||||
|
x: prevClosestHandle.absX + prevClosestHandle.width / 2,
|
||||||
|
y: prevClosestHandle.absY + prevClosestHandle.height / 2,
|
||||||
|
},
|
||||||
|
transform
|
||||||
|
)
|
||||||
|
: connectionPosition,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { connection, elementBelow, isValid, isHoveringHandle } = checkElementBelowIsValid(
|
const { connection, elementBelow, isValid, isHoveringHandle } = isHandleValid(
|
||||||
event,
|
prevClosestHandle,
|
||||||
connectionMode,
|
connectionMode,
|
||||||
isTarget,
|
|
||||||
nodeId,
|
nodeId,
|
||||||
handleId,
|
handleId,
|
||||||
|
isTarget ? 'target' : 'source',
|
||||||
isValidConnection,
|
isValidConnection,
|
||||||
doc
|
doc
|
||||||
);
|
);
|
||||||
@@ -183,12 +270,12 @@ export function handleMouseDown({
|
|||||||
function onMouseUp(event: MouseEvent) {
|
function onMouseUp(event: MouseEvent) {
|
||||||
cancelAnimationFrame(autoPanId);
|
cancelAnimationFrame(autoPanId);
|
||||||
|
|
||||||
const { connection, isValid } = checkElementBelowIsValid(
|
const { connection, isValid } = isHandleValid(
|
||||||
event,
|
prevClosestHandle,
|
||||||
connectionMode,
|
connectionMode,
|
||||||
isTarget,
|
|
||||||
nodeId,
|
nodeId,
|
||||||
handleId,
|
handleId,
|
||||||
|
isTarget ? 'target' : 'source',
|
||||||
isValidConnection,
|
isValidConnection,
|
||||||
doc
|
doc
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { shallow } from 'zustand/shallow';
|
|||||||
|
|
||||||
import { useStore, useStoreApi } from '../../hooks/useStore';
|
import { useStore, useStoreApi } from '../../hooks/useStore';
|
||||||
import { useNodeId } from '../../contexts/NodeIdContext';
|
import { useNodeId } from '../../contexts/NodeIdContext';
|
||||||
import { checkElementBelowIsValid, handleMouseDown } from './handler';
|
import { handleMouseDown, isHandleValid } from './handler';
|
||||||
import { getHostForElement } from '../../utils';
|
import { getHostForElement } from '../../utils';
|
||||||
import { addEdge } from '../../utils/graph';
|
import { addEdge } from '../../utils/graph';
|
||||||
import { Position } from '../../types';
|
import { Position } from '../../types';
|
||||||
@@ -86,12 +86,16 @@ const Handle = forwardRef<HTMLDivElement, HandleComponentProps>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const doc = getHostForElement(event.target as HTMLElement);
|
const doc = getHostForElement(event.target as HTMLElement);
|
||||||
const { connection, isValid } = checkElementBelowIsValid(
|
const { connection, isValid } = isHandleValid(
|
||||||
event as unknown as MouseEvent,
|
{
|
||||||
|
nodeId,
|
||||||
|
id: handleId,
|
||||||
|
type,
|
||||||
|
},
|
||||||
connectionMode,
|
connectionMode,
|
||||||
connectionStartHandle.type === 'target',
|
|
||||||
connectionStartHandle.nodeId,
|
connectionStartHandle.nodeId,
|
||||||
connectionStartHandle.handleId || null,
|
connectionStartHandle.handleId || null,
|
||||||
|
connectionStartHandle.type,
|
||||||
isValidConnection,
|
isValidConnection,
|
||||||
doc
|
doc
|
||||||
);
|
);
|
||||||
@@ -110,6 +114,7 @@ const Handle = forwardRef<HTMLDivElement, HandleComponentProps>(
|
|||||||
data-handleid={handleId}
|
data-handleid={handleId}
|
||||||
data-nodeid={nodeId}
|
data-nodeid={nodeId}
|
||||||
data-handlepos={position}
|
data-handlepos={position}
|
||||||
|
data-id={`${nodeId}-${handleId}-${type}`}
|
||||||
className={cc([
|
className={cc([
|
||||||
'react-flow__handle',
|
'react-flow__handle',
|
||||||
`react-flow__handle-${position}`,
|
`react-flow__handle-${position}`,
|
||||||
|
|||||||
@@ -162,6 +162,7 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
|
|||||||
disableKeyboardA11y = false,
|
disableKeyboardA11y = false,
|
||||||
autoPanOnConnect = true,
|
autoPanOnConnect = true,
|
||||||
autoPanOnNodeDrag = true,
|
autoPanOnNodeDrag = true,
|
||||||
|
connectionRadius = 20,
|
||||||
style,
|
style,
|
||||||
id,
|
id,
|
||||||
...rest
|
...rest
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ const initialState: ReactFlowStore = {
|
|||||||
ariaLiveMessage: '',
|
ariaLiveMessage: '',
|
||||||
autoPanOnConnect: true,
|
autoPanOnConnect: true,
|
||||||
autoPanOnNodeDrag: true,
|
autoPanOnNodeDrag: true,
|
||||||
|
connectionRadius: 20,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default initialState;
|
export default initialState;
|
||||||
|
|||||||
@@ -141,6 +141,7 @@ export type ReactFlowProps = HTMLAttributes<HTMLDivElement> & {
|
|||||||
disableKeyboardA11y?: boolean;
|
disableKeyboardA11y?: boolean;
|
||||||
autoPanOnNodeDrag?: boolean;
|
autoPanOnNodeDrag?: boolean;
|
||||||
autoPanOnConnect?: boolean;
|
autoPanOnConnect?: boolean;
|
||||||
|
connectionRadius?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ReactFlowRefType = HTMLDivElement;
|
export type ReactFlowRefType = HTMLDivElement;
|
||||||
|
|||||||
@@ -212,6 +212,7 @@ export type ReactFlowStore = {
|
|||||||
ariaLiveMessage: string;
|
ariaLiveMessage: string;
|
||||||
autoPanOnConnect: boolean;
|
autoPanOnConnect: boolean;
|
||||||
autoPanOnNodeDrag: boolean;
|
autoPanOnNodeDrag: boolean;
|
||||||
|
connectionRadius: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ReactFlowActions = {
|
export type ReactFlowActions = {
|
||||||
|
|||||||
@@ -141,6 +141,13 @@ export const pointToRendererPoint = (
|
|||||||
return position;
|
return position;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const rendererPointToPoint = ({ x, y }: XYPosition, [tx, ty, tScale]: Transform): XYPosition => {
|
||||||
|
return {
|
||||||
|
x: x * tScale + tx,
|
||||||
|
y: y * tScale + ty,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
export const getNodePositionWithOrigin = (
|
export const getNodePositionWithOrigin = (
|
||||||
node: Node | undefined,
|
node: Node | undefined,
|
||||||
nodeOrigin: NodeOrigin = [0, 0]
|
nodeOrigin: NodeOrigin = [0, 0]
|
||||||
|
|||||||
Reference in New Issue
Block a user