Merge pull request #2754 from wbkd/refactor/connecting-nodes

Auto pan for nodes, selection and connection line and connectionRadius
This commit is contained in:
Moritz Klack
2023-01-23 17:59:38 +01:00
committed by GitHub
15 changed files with 444 additions and 183 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@reactflow/core': minor
---
Add autoPan for connecting and node dragging
@@ -12,6 +12,7 @@ import ReactFlow, {
MiniMap,
Background,
Panel,
NodeOrigin,
} from 'reactflow';
import DebugNode from './DebugNode';
@@ -1,5 +1,5 @@
import React, { MouseEvent, useCallback } from 'react';
import ReactFlow, { addEdge, Node, Connection, Edge, useNodesState, useEdgesState } from 'reactflow';
import { MouseEvent, useCallback } from 'react';
import ReactFlow, { addEdge, Node, Connection, Edge, useNodesState, useEdgesState, NodeOrigin } from 'reactflow';
const onNodeDragStop = (_: MouseEvent, node: Node) => console.log('drag stop', node);
const onNodeClick = (_: MouseEvent, node: Node) => console.log('click', node);
@@ -35,7 +35,7 @@ const nodesA: Node[] = [
];
const edgesA: Edge[] = [
{ id: 'e1-2', source: '1a', target: '2a', ariaLabel: null },
{ id: 'e1-2', source: '1a', target: '2a', ariaLabel: undefined },
{ id: 'e1-3', source: '1a', target: '3a' },
];
@@ -83,6 +83,8 @@ const edgesB: Edge[] = [
{ id: 'e4b', source: 'inputb', target: '4b' },
];
const onNodeDrag = (_: MouseEvent, node: Node) => console.log('drag', node.position);
const BasicFlow = () => {
const [nodes, setNodes, onNodesChange] = useNodesState(nodesA);
const [edges, setEdges, onEdgesChange] = useEdgesState(edgesA);
@@ -99,6 +101,7 @@ const BasicFlow = () => {
onConnect={onConnect}
onNodeDragStop={onNodeDragStop}
disableKeyboardA11y
onNodeDrag={onNodeDrag}
>
<div style={{ position: 'absolute', right: 10, top: 10, zIndex: 4 }}>
<button
+101 -118
View File
@@ -1,78 +1,21 @@
import type { MouseEvent as ReactMouseEvent } from 'react';
import { StoreApi } from 'zustand';
import { getHostForElement } from '../../utils';
import { ConnectionMode } from '../../types';
import type { OnConnect, Connection, HandleType, ReactFlowState } from '../../types';
import { getHostForElement, calcAutoPan } from '../../utils';
import type { OnConnect, HandleType, ReactFlowState } from '../../types';
import { pointToRendererPoint, rendererPointToPoint } from '../../utils/graph';
import {
ConnectionHandle,
getClosestHandle,
getConnectionPosition,
getHandleLookup,
isValidHandle,
ValidConnectionFunc,
} from './utils';
type ValidConnectionFunc = (connection: Connection) => boolean;
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 }
export function checkElementBelowIsValid(
event: MouseEvent,
connectionMode: ConnectionMode,
isTarget: boolean,
nodeId: string,
handleId: string | null,
isValidConnection: ValidConnectionFunc,
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 = {
elementBelow,
isValid: false,
connection: { source: null, target: null, sourceHandle: null, targetHandle: null },
isHoveringHandle: false,
};
if (elementBelow && (elementBelowIsTarget || elementBelowIsSource)) {
result.isHoveringHandle = true;
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;
// in strict mode we don't allow target to target or source to source connections
const isValid =
connectionMode === ConnectionMode.Strict
? (isTarget && elementBelowIsSource) || (!isTarget && elementBelowIsTarget)
: elementBelowNodeId !== nodeId || elementBelowHandleId !== handleId;
if (isValid) {
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');
function resetRecentHandle(handleDomNode: Element): void {
handleDomNode?.classList.remove('react-flow__handle-valid');
handleDomNode?.classList.remove('react-flow__handle-connecting');
}
export function handleMouseDown({
@@ -98,32 +41,47 @@ export function handleMouseDown({
elementEdgeUpdaterType?: HandleType;
onEdgeUpdateEnd?: (evt: MouseEvent) => void;
}): void {
const reactFlowNode = (event.target as Element).closest('.react-flow');
// when react-flow is used inside a shadow root we can't use document
const doc = getHostForElement(event.target as HTMLElement);
const { connectionMode, domNode, autoPanOnConnect, connectionRadius, onConnectStart, onConnectEnd, panBy, getNodes } =
getState();
let autoPanId = 0;
let prevClosestHandle: ConnectionHandle | null;
if (!doc) {
const clickedElement = doc?.elementFromPoint(event.clientX, event.clientY);
const elementIsTarget = clickedElement?.classList.contains('target');
const elementIsSource = clickedElement?.classList.contains('source');
if (!domNode || (!elementIsTarget && !elementIsSource && !elementEdgeUpdaterType)) {
return;
}
const elementBelow = doc.elementFromPoint(event.clientX, event.clientY);
const elementBelowIsTarget = elementBelow?.classList.contains('target');
const elementBelowIsSource = elementBelow?.classList.contains('source');
const handleType = elementEdgeUpdaterType ? elementEdgeUpdaterType : elementIsTarget ? 'target' : 'source';
const containerBounds = domNode.getBoundingClientRect();
let prevActiveHandle: Element;
let connectionPosition = getConnectionPosition(event, containerBounds);
let autoPanStarted = false;
if (!reactFlowNode || (!elementBelowIsTarget && !elementBelowIsSource && !elementEdgeUpdaterType)) {
return;
}
const handleLookup = getHandleLookup({
nodes: getNodes(),
nodeId,
handleId,
handleType,
});
const { onConnectStart, connectionMode } = getState();
const handleType = elementEdgeUpdaterType ? elementEdgeUpdaterType : elementBelowIsTarget ? 'target' : 'source';
const containerBounds = reactFlowNode.getBoundingClientRect();
let recentHoveredHandle: Element;
// when the user is moving the mouse close to the edge of the canvas while connecting we move the canvas
const autoPan = (): void => {
if (!autoPanOnConnect) {
return;
}
const [xMovement, yMovement] = calcAutoPan(connectionPosition, containerBounds);
panBy({ x: xMovement, y: yMovement });
autoPanId = requestAnimationFrame(autoPan);
};
setState({
connectionPosition: {
x: event.clientX - containerBounds.left,
y: event.clientY - containerBounds.top,
},
connectionPosition,
connectionNodeId: nodeId,
connectionHandleId: handleId,
connectionHandleType: handleType,
@@ -132,57 +90,82 @@ export function handleMouseDown({
onConnectStart?.(event, { nodeId, handleId, handleType });
function onMouseMove(event: MouseEvent) {
const { transform } = getState();
connectionPosition = getConnectionPosition(event, containerBounds);
prevClosestHandle = getClosestHandle(
pointToRendererPoint(connectionPosition, transform, false, [1, 1]),
connectionRadius,
handleLookup
);
if (!autoPanStarted) {
autoPan();
autoPanStarted = true;
}
setState({
connectionPosition: {
x: event.clientX - containerBounds.left,
y: event.clientY - containerBounds.top,
},
connectionPosition: prevClosestHandle
? rendererPointToPoint(
{
x: prevClosestHandle.x,
y: prevClosestHandle.y,
},
transform
)
: connectionPosition,
});
const { connection, elementBelow, isValid, isHoveringHandle } = checkElementBelowIsValid(
event,
if (!prevClosestHandle) {
return resetRecentHandle(prevActiveHandle);
}
const { connection, handleDomNode, isValid } = isValidHandle(
prevClosestHandle,
connectionMode,
isTarget,
nodeId,
handleId,
isTarget ? 'target' : 'source',
isValidConnection,
doc
);
if (!isHoveringHandle) {
return resetRecentHandle(recentHoveredHandle);
}
if (connection.source !== connection.target && elementBelow) {
resetRecentHandle(recentHoveredHandle);
recentHoveredHandle = elementBelow;
elementBelow.classList.add('react-flow__handle-connecting');
elementBelow.classList.toggle('react-flow__handle-valid', isValid);
if (connection.source !== connection.target && handleDomNode) {
resetRecentHandle(prevActiveHandle);
prevActiveHandle = handleDomNode;
handleDomNode.classList.add('react-flow__handle-connecting');
handleDomNode.classList.toggle('react-flow__handle-valid', isValid);
}
}
function onMouseUp(event: MouseEvent) {
const { connection, isValid } = checkElementBelowIsValid(
event,
connectionMode,
isTarget,
nodeId,
handleId,
isValidConnection,
doc
);
cancelAnimationFrame(autoPanId);
autoPanStarted = false;
if (isValid) {
onConnect?.(connection);
if (prevClosestHandle) {
const { connection, isValid } = isValidHandle(
prevClosestHandle,
connectionMode,
nodeId,
handleId,
isTarget ? 'target' : 'source',
isValidConnection,
doc
);
if (isValid) {
onConnect?.(connection);
}
}
getState().onConnectEnd?.(event);
onConnectEnd?.(event);
if (elementEdgeUpdaterType && onEdgeUpdateEnd) {
onEdgeUpdateEnd(event);
if (elementEdgeUpdaterType) {
onEdgeUpdateEnd?.(event);
}
resetRecentHandle(recentHoveredHandle);
resetRecentHandle(prevActiveHandle);
setState({
connectionNodeId: null,
connectionHandleId: null,
+17 -7
View File
@@ -4,11 +4,12 @@ import { shallow } from 'zustand/shallow';
import { useStore, useStoreApi } from '../../hooks/useStore';
import { useNodeId } from '../../contexts/NodeIdContext';
import { checkElementBelowIsValid, handleMouseDown } from './handler';
import { getHostForElement } from '../../utils';
import { handleMouseDown } from './handler';
import { devWarn, getHostForElement } from '../../utils';
import { addEdge } from '../../utils/graph';
import { Position } from '../../types';
import type { HandleProps, Connection, ReactFlowState } from '../../types';
import { isValidHandle } from './utils';
const alwaysValid = () => true;
@@ -37,9 +38,13 @@ const Handle = forwardRef<HTMLDivElement, HandleComponentProps>(
ref
) => {
const store = useStoreApi();
const nodeId = useNodeId();
if (!nodeId) {
devWarn('Handle: No node id found. Make sure to only use a Handle inside a custom Node.');
return null;
}
// @fixme: remove type assertion and handle nodeId === null
const nodeId = useNodeId() as string;
const { connectionStartHandle, connectOnClick, noPanClassName } = useStore(selector, shallow);
const handleId = id || null;
@@ -86,12 +91,16 @@ const Handle = forwardRef<HTMLDivElement, HandleComponentProps>(
}
const doc = getHostForElement(event.target as HTMLElement);
const { connection, isValid } = checkElementBelowIsValid(
event as unknown as MouseEvent,
const { connection, isValid } = isValidHandle(
{
nodeId,
id: handleId,
type,
},
connectionMode,
connectionStartHandle.type === 'target',
connectionStartHandle.nodeId,
connectionStartHandle.handleId || null,
connectionStartHandle.type,
isValidConnection,
doc
);
@@ -110,6 +119,7 @@ const Handle = forwardRef<HTMLDivElement, HandleComponentProps>(
data-handleid={handleId}
data-nodeid={nodeId}
data-handlepos={position}
data-id={`${nodeId}-${handleId}-${type}`}
className={cc([
'react-flow__handle',
`react-flow__handle-${position}`,
@@ -0,0 +1,143 @@
import { MouseEvent as ReactMouseEvent } from 'react';
import { ConnectionMode } from '../../types';
import type { Connection, HandleType, XYPosition, Node, NodeHandleBounds } from '../../types';
import { internalsSymbol } from '../../utils';
export type ConnectionHandle = {
id: string | null;
type: HandleType;
nodeId: string;
x: number;
y: number;
};
export type ValidConnectionFunc = (connection: Connection) => boolean;
// this functions collects all handles and adds an absolute position
// so that we can later find the closest handle to the mouse position
export 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,
x: (node.positionAbsolute?.x ?? 0) + h.x + h.width / 2,
y: (node.positionAbsolute?.y ?? 0) + h.y + h.height / 2,
});
}
return res;
}, []);
}
export function getClosestHandle(
pos: XYPosition,
connectionRadius: number,
handles: ConnectionHandle[]
): ConnectionHandle | null {
let closestHandle: ConnectionHandle | null = null;
let minDistance = Infinity;
handles.forEach((handle) => {
const distance = Math.sqrt(Math.pow(handle.x - pos.x, 2) + Math.pow(handle.y - pos.y, 2));
if (distance <= connectionRadius && distance < minDistance) {
minDistance = distance;
closestHandle = handle;
}
});
return closestHandle;
}
type Result = {
handleDomNode: Element | null;
isValid: boolean;
connection: Connection;
};
// checks if and returns connection in fom of an object { source: 123, target: 312 }
export function isValidHandle(
handle: Pick<ConnectionHandle, 'nodeId' | 'id' | 'type'>,
connectionMode: ConnectionMode,
fromNodeId: string,
fromHandleId: string | null,
fromType: string,
isValidConnection: ValidConnectionFunc,
doc: Document | ShadowRoot
) {
const isTarget = fromType === 'target';
const handleDomNode = doc.querySelector(
`.react-flow__handle[data-id="${handle?.nodeId}-${handle?.id}-${handle?.type}"]`
);
const result: Result = {
handleDomNode,
isValid: false,
connection: { source: null, target: null, sourceHandle: null, targetHandle: null },
};
if (handleDomNode) {
const handleIsTarget = handle.type === 'target';
const handleIsSource = handle.type === 'source';
const handleNodeId = handleDomNode.getAttribute('data-nodeid');
const handleId = handleDomNode.getAttribute('data-handleid');
const connection: Connection = {
source: isTarget ? handle.nodeId : fromNodeId,
sourceHandle: isTarget ? handle.id : fromHandleId,
target: isTarget ? fromNodeId : handle.nodeId,
targetHandle: isTarget ? fromHandleId : handle.id,
};
result.connection = connection;
// in strict mode we don't allow target to target or source to source connections
const isValid =
connectionMode === ConnectionMode.Strict
? (isTarget && handleIsSource) || (!isTarget && handleIsTarget)
: handleNodeId !== handle.nodeId || handleId !== handle.id;
if (isValid) {
result.isValid = isValidConnection(connection);
}
}
return result;
}
type GetHandleLookupParams = {
nodes: Node[];
nodeId: string;
handleId: string | null;
handleType: string;
};
export function getHandleLookup({ nodes, nodeId, handleId, handleType }: GetHandleLookupParams) {
return nodes.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;
}, []);
}
export function getConnectionPosition(event: MouseEvent | ReactMouseEvent, bounds: DOMRect): XYPosition {
return {
x: event.clientX - bounds.left,
y: event.clientY - bounds.top,
};
}
@@ -45,6 +45,8 @@ type StoreUpdaterProps = Pick<
| 'noPanClassName'
| 'nodeOrigin'
| 'elevateNodesOnSelect'
| 'autoPanOnConnect'
| 'autoPanOnNodeDrag'
> & { rfId: string };
const selector = (s: ReactFlowState) => ({
@@ -119,6 +121,8 @@ const StoreUpdater = ({
noPanClassName,
nodeOrigin,
rfId,
autoPanOnConnect,
autoPanOnNodeDrag,
}: StoreUpdaterProps) => {
const {
setNodes,
@@ -172,6 +176,8 @@ const StoreUpdater = ({
useDirectStoreUpdater('noPanClassName', noPanClassName, store.setState);
useDirectStoreUpdater('nodeOrigin', nodeOrigin, store.setState);
useDirectStoreUpdater('rfId', rfId, store.setState);
useDirectStoreUpdater('autoPanOnConnect', autoPanOnConnect, store.setState);
useDirectStoreUpdater('autoPanOnNodeDrag', autoPanOnNodeDrag, store.setState);
useStoreUpdater<Node[]>(nodes, setNodes);
useStoreUpdater<Edge[]>(edges, setEdges);
@@ -160,6 +160,9 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
elevateNodesOnSelect = true,
elevateEdgesOnSelect = false,
disableKeyboardA11y = false,
autoPanOnConnect = true,
autoPanOnNodeDrag = true,
connectionRadius = 20,
style,
id,
...rest
@@ -287,6 +290,8 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
noPanClassName={noPanClassName}
nodeOrigin={nodeOrigin}
rfId={rfId}
autoPanOnConnect={autoPanOnConnect}
autoPanOnNodeDrag={autoPanOnNodeDrag}
/>
<SelectionListener onSelectionChange={onSelectionChange} />
{children}
+104 -55
View File
@@ -7,7 +7,8 @@ import { useStoreApi } from '../../hooks/useStore';
import { getDragItems, getEventHandlerParams, hasSelector, calcNextPosition } from './utils';
import { handleNodeClick } from '../../components/Nodes/utils';
import useGetPointerPosition from '../useGetPointerPosition';
import type { NodeDragItem, Node, SelectionDragHandler, UseDragEvent } from '../../types';
import { calcAutoPan } from '../../utils';
import type { NodeDragItem, Node, SelectionDragHandler, UseDragEvent, XYPosition } from '../../types';
export type UseDragData = { dx: number; dy: number };
@@ -34,10 +35,15 @@ function useDrag({
isSelectable,
selectNodesOnDrag,
}: UseDragParams) {
const [dragging, setDragging] = useState<boolean>(false);
const store = useStoreApi();
const dragItems = useRef<NodeDragItem[]>();
const [dragging, setDragging] = useState<boolean>(false);
const dragItems = useRef<NodeDragItem[]>([]);
const lastPos = useRef<{ x: number | null; y: number | null }>({ x: null, y: null });
const autoPanId = useRef(0);
const containerBounds = useRef<DOMRect | null>(null);
const mousePosition = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
const dragEvent = useRef<MouseEvent | null>(null);
const autoPanStarted = useRef(false);
const getPointerPosition = useGetPointerPosition();
@@ -45,6 +51,79 @@ function useDrag({
if (nodeRef?.current) {
const selection = select(nodeRef.current);
const updateNodes = ({ x, y }: XYPosition) => {
const {
nodeInternals,
onNodeDrag,
onSelectionDrag,
updateNodePositions,
nodeExtent,
snapGrid,
snapToGrid,
nodeOrigin,
} = store.getState();
lastPos.current = { x, y };
let hasChange = false;
dragItems.current = dragItems.current.map((n) => {
const nextPosition = { x: x - n.distance.x, y: y - n.distance.y };
if (snapToGrid) {
nextPosition.x = snapGrid[0] * Math.round(nextPosition.x / snapGrid[0]);
nextPosition.y = snapGrid[1] * Math.round(nextPosition.y / snapGrid[1]);
}
const updatedPos = calcNextPosition(n, nextPosition, nodeInternals, nodeExtent, nodeOrigin);
// we want to make sure that we only fire a change event when there is a changes
hasChange = hasChange || n.position.x !== updatedPos.position.x || n.position.y !== updatedPos.position.y;
n.position = updatedPos.position;
n.positionAbsolute = updatedPos.positionAbsolute;
return n;
});
if (!hasChange) {
return;
}
updateNodePositions(dragItems.current, true, true);
setDragging(true);
const onDrag = nodeId ? onNodeDrag : wrapSelectionDragFunc(onSelectionDrag);
if (onDrag && dragEvent.current) {
const [currentNode, nodes] = getEventHandlerParams({
nodeId,
dragItems: dragItems.current,
nodeInternals,
});
onDrag(dragEvent.current as MouseEvent, currentNode, nodes);
}
};
const autoPan = (): void => {
if (!containerBounds.current) {
return;
}
const [xMovement, yMovement] = calcAutoPan(mousePosition.current, containerBounds.current);
if (xMovement !== 0 || yMovement !== 0) {
const { transform, panBy } = store.getState();
lastPos.current.x = (lastPos.current.x ?? 0) - xMovement / transform[2];
lastPos.current.y = (lastPos.current.y ?? 0) - yMovement / transform[2];
updateNodes(lastPos.current as XYPosition);
panBy({ x: xMovement, y: yMovement });
}
autoPanId.current = requestAnimationFrame(autoPan);
};
if (disabled) {
selection.on('.drag', null);
} else {
@@ -56,6 +135,7 @@ function useDrag({
unselectNodesAndEdges,
onNodeDragStart,
onSelectionDragStart,
domNode,
} = store.getState();
const onStart = nodeId ? onNodeDragStart : wrapSelectionDragFunc(onSelectionDragStart);
@@ -86,72 +166,41 @@ function useDrag({
});
onStart(event.sourceEvent as MouseEvent, currentNode, nodes);
}
containerBounds.current = domNode?.getBoundingClientRect() || null;
mousePosition.current = {
x: event.sourceEvent.clientX - (containerBounds.current?.left ?? 0),
y: event.sourceEvent.clientY - (containerBounds.current?.top ?? 0),
};
})
.on('drag', (event: UseDragEvent) => {
const {
updateNodePositions,
nodeInternals,
nodeExtent,
onNodeDrag,
onSelectionDrag,
snapGrid,
snapToGrid,
nodeOrigin,
} = store.getState();
const pointerPos = getPointerPosition(event);
const { autoPanOnNodeDrag } = store.getState();
if (!autoPanStarted.current && autoPanOnNodeDrag) {
autoPanStarted.current = true;
autoPan();
}
// skip events without movement
if (
(lastPos.current.x !== pointerPos.xSnapped || lastPos.current.y !== pointerPos.ySnapped) &&
dragItems.current
) {
lastPos.current = {
x: pointerPos.xSnapped,
y: pointerPos.ySnapped,
dragEvent.current = event.sourceEvent as MouseEvent;
mousePosition.current = {
x: event.sourceEvent.clientX - (containerBounds.current?.left ?? 0),
y: event.sourceEvent.clientY - (containerBounds.current?.top ?? 0),
};
let hasChange = false;
dragItems.current = dragItems.current.map((n) => {
const nextPosition = { x: pointerPos.x - n.distance.x, y: pointerPos.y - n.distance.y };
if (snapToGrid) {
nextPosition.x = snapGrid[0] * Math.round(nextPosition.x / snapGrid[0]);
nextPosition.y = snapGrid[1] * Math.round(nextPosition.y / snapGrid[1]);
}
const updatedPos = calcNextPosition(n, nextPosition, nodeInternals, nodeExtent, nodeOrigin);
// we want to make sure that we only fire a change event when there is a changes
hasChange =
hasChange || n.position.x !== updatedPos.position.x || n.position.y !== updatedPos.position.y;
n.position = updatedPos.position;
n.positionAbsolute = updatedPos.positionAbsolute;
return n;
});
if (!hasChange) {
return;
}
const onDrag = nodeId ? onNodeDrag : wrapSelectionDragFunc(onSelectionDrag);
updateNodePositions(dragItems.current, true, true);
setDragging(true);
if (onDrag) {
const [currentNode, nodes] = getEventHandlerParams({
nodeId,
dragItems: dragItems.current,
nodeInternals,
});
onDrag(event.sourceEvent as MouseEvent, currentNode, nodes);
}
updateNodes(pointerPos);
}
})
.on('end', (event: UseDragEvent) => {
setDragging(false);
autoPanStarted.current = false;
cancelAnimationFrame(autoPanId.current);
if (dragItems.current) {
const { updateNodePositions, nodeInternals, onNodeDragStop, onSelectionDragStop } = store.getState();
const onStop = nodeId ? onNodeDragStop : wrapSelectionDragFunc(onSelectionDragStop);
+19
View File
@@ -1,4 +1,5 @@
import { createStore } from 'zustand';
import { zoomIdentity } from 'd3-zoom';
import { clampPosition, getDimensions, internalsSymbol } from '../utils';
import { applyNodeChanges, createSelectionChange, getSelectionChanges } from '../utils/changes';
@@ -19,6 +20,7 @@ import type {
UnselectNodesAndEdgesParams,
NodeChange,
} from '../types';
import { XYPosition } from 'react-flow-renderer';
const createRFStore = () =>
createStore<ReactFlowState>((set, get) => ({
@@ -250,6 +252,23 @@ const createRFStore = () =>
nodeInternals: new Map(nodeInternals),
});
},
panBy: (delta: XYPosition) => {
const { transform, width, height, d3Zoom, d3Selection, translateExtent } = get();
if (!d3Zoom || !d3Selection || (!delta.x && !delta.y)) {
return;
}
const nextTransform = zoomIdentity.translate(transform[0] + delta.x, transform[1] + delta.y).scale(transform[2]);
const extent: CoordinateExtent = [
[0, 0],
[width, height],
];
const constrainedTransform = d3Zoom?.constrain()(nextTransform, extent, translateExtent);
d3Zoom.transform(d3Selection, constrainedTransform);
},
cancelConnection: () =>
set({
connectionNodeId: initialState.connectionNodeId,
+3
View File
@@ -56,6 +56,9 @@ const initialState: ReactFlowStore = {
connectOnClick: true,
ariaLiveMessage: '',
autoPanOnConnect: true,
autoPanOnNodeDrag: true,
connectionRadius: 20,
};
export default initialState;
@@ -139,6 +139,9 @@ export type ReactFlowProps = HTMLAttributes<HTMLDivElement> & {
elevateNodesOnSelect?: boolean;
elevateEdgesOnSelect?: boolean;
disableKeyboardA11y?: boolean;
autoPanOnNodeDrag?: boolean;
autoPanOnConnect?: boolean;
connectionRadius?: number;
};
export type ReactFlowRefType = HTMLDivElement;
+4
View File
@@ -210,6 +210,9 @@ export type ReactFlowStore = {
onSelectionChange?: OnSelectionChangeFunc;
ariaLiveMessage: string;
autoPanOnConnect: boolean;
autoPanOnNodeDrag: boolean;
connectionRadius: number;
};
export type ReactFlowActions = {
@@ -230,6 +233,7 @@ export type ReactFlowActions = {
cancelConnection: () => void;
reset: () => void;
triggerNodeChanges: (changes: NodeChange[]) => void;
panBy: (delta: XYPosition) => void;
};
export type ReactFlowState = ReactFlowStore & ReactFlowActions;
+7
View File
@@ -141,6 +141,13 @@ export const pointToRendererPoint = (
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 = (
node: Node | undefined,
nodeOrigin: NodeOrigin = [0, 0]
+20
View File
@@ -1,4 +1,5 @@
import type { KeyboardEvent as ReactKeyboardEvent } from 'react';
import type { Dimensions, Node, XYPosition, CoordinateExtent, Box, Rect } from '../types';
export const getDimensions = (node: HTMLDivElement): Dimensions => ({
@@ -13,6 +14,25 @@ export const clampPosition = (position: XYPosition = { x: 0, y: 0 }, extent: Coo
y: clamp(position.y, extent[0][1], extent[1][1]),
});
// returns a number between 0 and 1 that represents the velocity of the movement
// when the mouse is close to the edge of the canvas
const calcAutoPanVelocity = (value: number, min: number, max: number): number => {
if (value < min) {
return clamp(Math.abs(value - min), 1, 50) / 50;
} else if (value > max) {
return -clamp(Math.abs(value - max), 1, 50) / 50;
}
return 0;
};
export const calcAutoPan = (pos: XYPosition, bounds: Dimensions): number[] => {
const xMovement = calcAutoPanVelocity(pos.x, 35, bounds.width - 35) * 20;
const yMovement = calcAutoPanVelocity(pos.y, 35, bounds.height - 35) * 20;
return [xMovement, yMovement];
};
export const getHostForElement = (element: HTMLElement): Document | ShadowRoot =>
(element.getRootNode?.() as Document | ShadowRoot) || window?.document;