Merge pull request #2754 from wbkd/refactor/connecting-nodes
Auto pan for nodes, selection and connection line and connectionRadius
This commit is contained in:
@@ -0,0 +1,5 @@
|
|||||||
|
---
|
||||||
|
'@reactflow/core': minor
|
||||||
|
---
|
||||||
|
|
||||||
|
Add autoPan for connecting and node dragging
|
||||||
@@ -12,6 +12,7 @@ import ReactFlow, {
|
|||||||
MiniMap,
|
MiniMap,
|
||||||
Background,
|
Background,
|
||||||
Panel,
|
Panel,
|
||||||
|
NodeOrigin,
|
||||||
} from 'reactflow';
|
} from 'reactflow';
|
||||||
|
|
||||||
import DebugNode from './DebugNode';
|
import DebugNode from './DebugNode';
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { MouseEvent, useCallback } from 'react';
|
import { MouseEvent, useCallback } from 'react';
|
||||||
import ReactFlow, { addEdge, Node, Connection, Edge, useNodesState, useEdgesState } from 'reactflow';
|
import ReactFlow, { addEdge, Node, Connection, Edge, useNodesState, useEdgesState, NodeOrigin } from 'reactflow';
|
||||||
|
|
||||||
const onNodeDragStop = (_: MouseEvent, node: Node) => console.log('drag stop', node);
|
const onNodeDragStop = (_: MouseEvent, node: Node) => console.log('drag stop', node);
|
||||||
const onNodeClick = (_: MouseEvent, node: Node) => console.log('click', node);
|
const onNodeClick = (_: MouseEvent, node: Node) => console.log('click', node);
|
||||||
@@ -35,7 +35,7 @@ const nodesA: Node[] = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
const edgesA: Edge[] = [
|
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' },
|
{ id: 'e1-3', source: '1a', target: '3a' },
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -83,6 +83,8 @@ const edgesB: Edge[] = [
|
|||||||
{ id: 'e4b', source: 'inputb', target: '4b' },
|
{ id: 'e4b', source: 'inputb', target: '4b' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const onNodeDrag = (_: MouseEvent, node: Node) => console.log('drag', node.position);
|
||||||
|
|
||||||
const BasicFlow = () => {
|
const BasicFlow = () => {
|
||||||
const [nodes, setNodes, onNodesChange] = useNodesState(nodesA);
|
const [nodes, setNodes, onNodesChange] = useNodesState(nodesA);
|
||||||
const [edges, setEdges, onEdgesChange] = useEdgesState(edgesA);
|
const [edges, setEdges, onEdgesChange] = useEdgesState(edgesA);
|
||||||
@@ -99,6 +101,7 @@ const BasicFlow = () => {
|
|||||||
onConnect={onConnect}
|
onConnect={onConnect}
|
||||||
onNodeDragStop={onNodeDragStop}
|
onNodeDragStop={onNodeDragStop}
|
||||||
disableKeyboardA11y
|
disableKeyboardA11y
|
||||||
|
onNodeDrag={onNodeDrag}
|
||||||
>
|
>
|
||||||
<div style={{ position: 'absolute', right: 10, top: 10, zIndex: 4 }}>
|
<div style={{ position: 'absolute', right: 10, top: 10, zIndex: 4 }}>
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -1,78 +1,21 @@
|
|||||||
import type { MouseEvent as ReactMouseEvent } from 'react';
|
import type { MouseEvent as ReactMouseEvent } from 'react';
|
||||||
import { StoreApi } from 'zustand';
|
import { StoreApi } from 'zustand';
|
||||||
|
|
||||||
import { getHostForElement } from '../../utils';
|
import { getHostForElement, calcAutoPan } from '../../utils';
|
||||||
import { ConnectionMode } from '../../types';
|
import type { OnConnect, HandleType, ReactFlowState } from '../../types';
|
||||||
import type { OnConnect, Connection, HandleType, ReactFlowState } from '../../types';
|
import { pointToRendererPoint, rendererPointToPoint } from '../../utils/graph';
|
||||||
|
import {
|
||||||
|
ConnectionHandle,
|
||||||
|
getClosestHandle,
|
||||||
|
getConnectionPosition,
|
||||||
|
getHandleLookup,
|
||||||
|
isValidHandle,
|
||||||
|
ValidConnectionFunc,
|
||||||
|
} from './utils';
|
||||||
|
|
||||||
type ValidConnectionFunc = (connection: Connection) => boolean;
|
function resetRecentHandle(handleDomNode: Element): void {
|
||||||
|
handleDomNode?.classList.remove('react-flow__handle-valid');
|
||||||
type Result = {
|
handleDomNode?.classList.remove('react-flow__handle-connecting');
|
||||||
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');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function handleMouseDown({
|
export function handleMouseDown({
|
||||||
@@ -98,32 +41,47 @@ export function handleMouseDown({
|
|||||||
elementEdgeUpdaterType?: HandleType;
|
elementEdgeUpdaterType?: HandleType;
|
||||||
onEdgeUpdateEnd?: (evt: MouseEvent) => void;
|
onEdgeUpdateEnd?: (evt: MouseEvent) => void;
|
||||||
}): 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
|
// 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 { 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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const elementBelow = doc.elementFromPoint(event.clientX, event.clientY);
|
const handleType = elementEdgeUpdaterType ? elementEdgeUpdaterType : elementIsTarget ? 'target' : 'source';
|
||||||
const elementBelowIsTarget = elementBelow?.classList.contains('target');
|
const containerBounds = domNode.getBoundingClientRect();
|
||||||
const elementBelowIsSource = elementBelow?.classList.contains('source');
|
let prevActiveHandle: Element;
|
||||||
|
let connectionPosition = getConnectionPosition(event, containerBounds);
|
||||||
|
let autoPanStarted = false;
|
||||||
|
|
||||||
if (!reactFlowNode || (!elementBelowIsTarget && !elementBelowIsSource && !elementEdgeUpdaterType)) {
|
const handleLookup = getHandleLookup({
|
||||||
return;
|
nodes: getNodes(),
|
||||||
}
|
nodeId,
|
||||||
|
handleId,
|
||||||
|
handleType,
|
||||||
|
});
|
||||||
|
|
||||||
const { onConnectStart, connectionMode } = getState();
|
// when the user is moving the mouse close to the edge of the canvas while connecting we move the canvas
|
||||||
const handleType = elementEdgeUpdaterType ? elementEdgeUpdaterType : elementBelowIsTarget ? 'target' : 'source';
|
const autoPan = (): void => {
|
||||||
const containerBounds = reactFlowNode.getBoundingClientRect();
|
if (!autoPanOnConnect) {
|
||||||
let recentHoveredHandle: Element;
|
return;
|
||||||
|
}
|
||||||
|
const [xMovement, yMovement] = calcAutoPan(connectionPosition, containerBounds);
|
||||||
|
|
||||||
|
panBy({ x: xMovement, y: yMovement });
|
||||||
|
autoPanId = requestAnimationFrame(autoPan);
|
||||||
|
};
|
||||||
|
|
||||||
setState({
|
setState({
|
||||||
connectionPosition: {
|
connectionPosition,
|
||||||
x: event.clientX - containerBounds.left,
|
|
||||||
y: event.clientY - containerBounds.top,
|
|
||||||
},
|
|
||||||
connectionNodeId: nodeId,
|
connectionNodeId: nodeId,
|
||||||
connectionHandleId: handleId,
|
connectionHandleId: handleId,
|
||||||
connectionHandleType: handleType,
|
connectionHandleType: handleType,
|
||||||
@@ -132,57 +90,82 @@ export function handleMouseDown({
|
|||||||
onConnectStart?.(event, { nodeId, handleId, handleType });
|
onConnectStart?.(event, { nodeId, handleId, handleType });
|
||||||
|
|
||||||
function onMouseMove(event: MouseEvent) {
|
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({
|
setState({
|
||||||
connectionPosition: {
|
connectionPosition: prevClosestHandle
|
||||||
x: event.clientX - containerBounds.left,
|
? rendererPointToPoint(
|
||||||
y: event.clientY - containerBounds.top,
|
{
|
||||||
},
|
x: prevClosestHandle.x,
|
||||||
|
y: prevClosestHandle.y,
|
||||||
|
},
|
||||||
|
transform
|
||||||
|
)
|
||||||
|
: connectionPosition,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { connection, elementBelow, isValid, isHoveringHandle } = checkElementBelowIsValid(
|
if (!prevClosestHandle) {
|
||||||
event,
|
return resetRecentHandle(prevActiveHandle);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { connection, handleDomNode, isValid } = isValidHandle(
|
||||||
|
prevClosestHandle,
|
||||||
connectionMode,
|
connectionMode,
|
||||||
isTarget,
|
|
||||||
nodeId,
|
nodeId,
|
||||||
handleId,
|
handleId,
|
||||||
|
isTarget ? 'target' : 'source',
|
||||||
isValidConnection,
|
isValidConnection,
|
||||||
doc
|
doc
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!isHoveringHandle) {
|
if (connection.source !== connection.target && handleDomNode) {
|
||||||
return resetRecentHandle(recentHoveredHandle);
|
resetRecentHandle(prevActiveHandle);
|
||||||
}
|
prevActiveHandle = handleDomNode;
|
||||||
|
handleDomNode.classList.add('react-flow__handle-connecting');
|
||||||
if (connection.source !== connection.target && elementBelow) {
|
handleDomNode.classList.toggle('react-flow__handle-valid', isValid);
|
||||||
resetRecentHandle(recentHoveredHandle);
|
|
||||||
recentHoveredHandle = elementBelow;
|
|
||||||
elementBelow.classList.add('react-flow__handle-connecting');
|
|
||||||
elementBelow.classList.toggle('react-flow__handle-valid', isValid);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function onMouseUp(event: MouseEvent) {
|
function onMouseUp(event: MouseEvent) {
|
||||||
const { connection, isValid } = checkElementBelowIsValid(
|
cancelAnimationFrame(autoPanId);
|
||||||
event,
|
autoPanStarted = false;
|
||||||
connectionMode,
|
|
||||||
isTarget,
|
|
||||||
nodeId,
|
|
||||||
handleId,
|
|
||||||
isValidConnection,
|
|
||||||
doc
|
|
||||||
);
|
|
||||||
|
|
||||||
if (isValid) {
|
if (prevClosestHandle) {
|
||||||
onConnect?.(connection);
|
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) {
|
if (elementEdgeUpdaterType) {
|
||||||
onEdgeUpdateEnd(event);
|
onEdgeUpdateEnd?.(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
resetRecentHandle(recentHoveredHandle);
|
resetRecentHandle(prevActiveHandle);
|
||||||
|
|
||||||
setState({
|
setState({
|
||||||
connectionNodeId: null,
|
connectionNodeId: null,
|
||||||
connectionHandleId: null,
|
connectionHandleId: null,
|
||||||
|
|||||||
@@ -4,11 +4,12 @@ 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 } from './handler';
|
||||||
import { getHostForElement } from '../../utils';
|
import { devWarn, getHostForElement } from '../../utils';
|
||||||
import { addEdge } from '../../utils/graph';
|
import { addEdge } from '../../utils/graph';
|
||||||
import { Position } from '../../types';
|
import { Position } from '../../types';
|
||||||
import type { HandleProps, Connection, ReactFlowState } from '../../types';
|
import type { HandleProps, Connection, ReactFlowState } from '../../types';
|
||||||
|
import { isValidHandle } from './utils';
|
||||||
|
|
||||||
const alwaysValid = () => true;
|
const alwaysValid = () => true;
|
||||||
|
|
||||||
@@ -37,9 +38,13 @@ const Handle = forwardRef<HTMLDivElement, HandleComponentProps>(
|
|||||||
ref
|
ref
|
||||||
) => {
|
) => {
|
||||||
const store = useStoreApi();
|
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 { connectionStartHandle, connectOnClick, noPanClassName } = useStore(selector, shallow);
|
||||||
|
|
||||||
const handleId = id || null;
|
const handleId = id || null;
|
||||||
@@ -86,12 +91,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 } = isValidHandle(
|
||||||
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 +119,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}`,
|
||||||
|
|||||||
@@ -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'
|
| 'noPanClassName'
|
||||||
| 'nodeOrigin'
|
| 'nodeOrigin'
|
||||||
| 'elevateNodesOnSelect'
|
| 'elevateNodesOnSelect'
|
||||||
|
| 'autoPanOnConnect'
|
||||||
|
| 'autoPanOnNodeDrag'
|
||||||
> & { rfId: string };
|
> & { rfId: string };
|
||||||
|
|
||||||
const selector = (s: ReactFlowState) => ({
|
const selector = (s: ReactFlowState) => ({
|
||||||
@@ -119,6 +121,8 @@ const StoreUpdater = ({
|
|||||||
noPanClassName,
|
noPanClassName,
|
||||||
nodeOrigin,
|
nodeOrigin,
|
||||||
rfId,
|
rfId,
|
||||||
|
autoPanOnConnect,
|
||||||
|
autoPanOnNodeDrag,
|
||||||
}: StoreUpdaterProps) => {
|
}: StoreUpdaterProps) => {
|
||||||
const {
|
const {
|
||||||
setNodes,
|
setNodes,
|
||||||
@@ -172,6 +176,8 @@ const StoreUpdater = ({
|
|||||||
useDirectStoreUpdater('noPanClassName', noPanClassName, store.setState);
|
useDirectStoreUpdater('noPanClassName', noPanClassName, store.setState);
|
||||||
useDirectStoreUpdater('nodeOrigin', nodeOrigin, store.setState);
|
useDirectStoreUpdater('nodeOrigin', nodeOrigin, store.setState);
|
||||||
useDirectStoreUpdater('rfId', rfId, store.setState);
|
useDirectStoreUpdater('rfId', rfId, store.setState);
|
||||||
|
useDirectStoreUpdater('autoPanOnConnect', autoPanOnConnect, store.setState);
|
||||||
|
useDirectStoreUpdater('autoPanOnNodeDrag', autoPanOnNodeDrag, store.setState);
|
||||||
|
|
||||||
useStoreUpdater<Node[]>(nodes, setNodes);
|
useStoreUpdater<Node[]>(nodes, setNodes);
|
||||||
useStoreUpdater<Edge[]>(edges, setEdges);
|
useStoreUpdater<Edge[]>(edges, setEdges);
|
||||||
|
|||||||
@@ -160,6 +160,9 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
|
|||||||
elevateNodesOnSelect = true,
|
elevateNodesOnSelect = true,
|
||||||
elevateEdgesOnSelect = false,
|
elevateEdgesOnSelect = false,
|
||||||
disableKeyboardA11y = false,
|
disableKeyboardA11y = false,
|
||||||
|
autoPanOnConnect = true,
|
||||||
|
autoPanOnNodeDrag = true,
|
||||||
|
connectionRadius = 20,
|
||||||
style,
|
style,
|
||||||
id,
|
id,
|
||||||
...rest
|
...rest
|
||||||
@@ -287,6 +290,8 @@ const ReactFlow = forwardRef<ReactFlowRefType, ReactFlowProps>(
|
|||||||
noPanClassName={noPanClassName}
|
noPanClassName={noPanClassName}
|
||||||
nodeOrigin={nodeOrigin}
|
nodeOrigin={nodeOrigin}
|
||||||
rfId={rfId}
|
rfId={rfId}
|
||||||
|
autoPanOnConnect={autoPanOnConnect}
|
||||||
|
autoPanOnNodeDrag={autoPanOnNodeDrag}
|
||||||
/>
|
/>
|
||||||
<SelectionListener onSelectionChange={onSelectionChange} />
|
<SelectionListener onSelectionChange={onSelectionChange} />
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ import { useStoreApi } from '../../hooks/useStore';
|
|||||||
import { getDragItems, getEventHandlerParams, hasSelector, calcNextPosition } from './utils';
|
import { getDragItems, getEventHandlerParams, hasSelector, calcNextPosition } from './utils';
|
||||||
import { handleNodeClick } from '../../components/Nodes/utils';
|
import { handleNodeClick } from '../../components/Nodes/utils';
|
||||||
import useGetPointerPosition from '../useGetPointerPosition';
|
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 };
|
export type UseDragData = { dx: number; dy: number };
|
||||||
|
|
||||||
@@ -34,10 +35,15 @@ function useDrag({
|
|||||||
isSelectable,
|
isSelectable,
|
||||||
selectNodesOnDrag,
|
selectNodesOnDrag,
|
||||||
}: UseDragParams) {
|
}: UseDragParams) {
|
||||||
const [dragging, setDragging] = useState<boolean>(false);
|
|
||||||
const store = useStoreApi();
|
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 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();
|
const getPointerPosition = useGetPointerPosition();
|
||||||
|
|
||||||
@@ -45,6 +51,79 @@ function useDrag({
|
|||||||
if (nodeRef?.current) {
|
if (nodeRef?.current) {
|
||||||
const selection = select(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) {
|
if (disabled) {
|
||||||
selection.on('.drag', null);
|
selection.on('.drag', null);
|
||||||
} else {
|
} else {
|
||||||
@@ -56,6 +135,7 @@ function useDrag({
|
|||||||
unselectNodesAndEdges,
|
unselectNodesAndEdges,
|
||||||
onNodeDragStart,
|
onNodeDragStart,
|
||||||
onSelectionDragStart,
|
onSelectionDragStart,
|
||||||
|
domNode,
|
||||||
} = store.getState();
|
} = store.getState();
|
||||||
|
|
||||||
const onStart = nodeId ? onNodeDragStart : wrapSelectionDragFunc(onSelectionDragStart);
|
const onStart = nodeId ? onNodeDragStart : wrapSelectionDragFunc(onSelectionDragStart);
|
||||||
@@ -86,72 +166,41 @@ function useDrag({
|
|||||||
});
|
});
|
||||||
onStart(event.sourceEvent as MouseEvent, currentNode, nodes);
|
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) => {
|
.on('drag', (event: UseDragEvent) => {
|
||||||
const {
|
|
||||||
updateNodePositions,
|
|
||||||
nodeInternals,
|
|
||||||
nodeExtent,
|
|
||||||
onNodeDrag,
|
|
||||||
onSelectionDrag,
|
|
||||||
snapGrid,
|
|
||||||
snapToGrid,
|
|
||||||
nodeOrigin,
|
|
||||||
} = store.getState();
|
|
||||||
const pointerPos = getPointerPosition(event);
|
const pointerPos = getPointerPosition(event);
|
||||||
|
const { autoPanOnNodeDrag } = store.getState();
|
||||||
|
|
||||||
|
if (!autoPanStarted.current && autoPanOnNodeDrag) {
|
||||||
|
autoPanStarted.current = true;
|
||||||
|
autoPan();
|
||||||
|
}
|
||||||
|
|
||||||
// skip events without movement
|
// skip events without movement
|
||||||
if (
|
if (
|
||||||
(lastPos.current.x !== pointerPos.xSnapped || lastPos.current.y !== pointerPos.ySnapped) &&
|
(lastPos.current.x !== pointerPos.xSnapped || lastPos.current.y !== pointerPos.ySnapped) &&
|
||||||
dragItems.current
|
dragItems.current
|
||||||
) {
|
) {
|
||||||
lastPos.current = {
|
dragEvent.current = event.sourceEvent as MouseEvent;
|
||||||
x: pointerPos.xSnapped,
|
mousePosition.current = {
|
||||||
y: pointerPos.ySnapped,
|
x: event.sourceEvent.clientX - (containerBounds.current?.left ?? 0),
|
||||||
|
y: event.sourceEvent.clientY - (containerBounds.current?.top ?? 0),
|
||||||
};
|
};
|
||||||
|
|
||||||
let hasChange = false;
|
updateNodes(pointerPos);
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.on('end', (event: UseDragEvent) => {
|
.on('end', (event: UseDragEvent) => {
|
||||||
setDragging(false);
|
setDragging(false);
|
||||||
|
autoPanStarted.current = false;
|
||||||
|
cancelAnimationFrame(autoPanId.current);
|
||||||
|
|
||||||
if (dragItems.current) {
|
if (dragItems.current) {
|
||||||
const { updateNodePositions, nodeInternals, onNodeDragStop, onSelectionDragStop } = store.getState();
|
const { updateNodePositions, nodeInternals, onNodeDragStop, onSelectionDragStop } = store.getState();
|
||||||
const onStop = nodeId ? onNodeDragStop : wrapSelectionDragFunc(onSelectionDragStop);
|
const onStop = nodeId ? onNodeDragStop : wrapSelectionDragFunc(onSelectionDragStop);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { createStore } from 'zustand';
|
import { createStore } from 'zustand';
|
||||||
|
import { zoomIdentity } from 'd3-zoom';
|
||||||
|
|
||||||
import { clampPosition, getDimensions, internalsSymbol } from '../utils';
|
import { clampPosition, getDimensions, internalsSymbol } from '../utils';
|
||||||
import { applyNodeChanges, createSelectionChange, getSelectionChanges } from '../utils/changes';
|
import { applyNodeChanges, createSelectionChange, getSelectionChanges } from '../utils/changes';
|
||||||
@@ -19,6 +20,7 @@ import type {
|
|||||||
UnselectNodesAndEdgesParams,
|
UnselectNodesAndEdgesParams,
|
||||||
NodeChange,
|
NodeChange,
|
||||||
} from '../types';
|
} from '../types';
|
||||||
|
import { XYPosition } from 'react-flow-renderer';
|
||||||
|
|
||||||
const createRFStore = () =>
|
const createRFStore = () =>
|
||||||
createStore<ReactFlowState>((set, get) => ({
|
createStore<ReactFlowState>((set, get) => ({
|
||||||
@@ -250,6 +252,23 @@ const createRFStore = () =>
|
|||||||
nodeInternals: new Map(nodeInternals),
|
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: () =>
|
cancelConnection: () =>
|
||||||
set({
|
set({
|
||||||
connectionNodeId: initialState.connectionNodeId,
|
connectionNodeId: initialState.connectionNodeId,
|
||||||
|
|||||||
@@ -56,6 +56,9 @@ const initialState: ReactFlowStore = {
|
|||||||
connectOnClick: true,
|
connectOnClick: true,
|
||||||
|
|
||||||
ariaLiveMessage: '',
|
ariaLiveMessage: '',
|
||||||
|
autoPanOnConnect: true,
|
||||||
|
autoPanOnNodeDrag: true,
|
||||||
|
connectionRadius: 20,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default initialState;
|
export default initialState;
|
||||||
|
|||||||
@@ -139,6 +139,9 @@ export type ReactFlowProps = HTMLAttributes<HTMLDivElement> & {
|
|||||||
elevateNodesOnSelect?: boolean;
|
elevateNodesOnSelect?: boolean;
|
||||||
elevateEdgesOnSelect?: boolean;
|
elevateEdgesOnSelect?: boolean;
|
||||||
disableKeyboardA11y?: boolean;
|
disableKeyboardA11y?: boolean;
|
||||||
|
autoPanOnNodeDrag?: boolean;
|
||||||
|
autoPanOnConnect?: boolean;
|
||||||
|
connectionRadius?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ReactFlowRefType = HTMLDivElement;
|
export type ReactFlowRefType = HTMLDivElement;
|
||||||
|
|||||||
@@ -210,6 +210,9 @@ export type ReactFlowStore = {
|
|||||||
onSelectionChange?: OnSelectionChangeFunc;
|
onSelectionChange?: OnSelectionChangeFunc;
|
||||||
|
|
||||||
ariaLiveMessage: string;
|
ariaLiveMessage: string;
|
||||||
|
autoPanOnConnect: boolean;
|
||||||
|
autoPanOnNodeDrag: boolean;
|
||||||
|
connectionRadius: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ReactFlowActions = {
|
export type ReactFlowActions = {
|
||||||
@@ -230,6 +233,7 @@ export type ReactFlowActions = {
|
|||||||
cancelConnection: () => void;
|
cancelConnection: () => void;
|
||||||
reset: () => void;
|
reset: () => void;
|
||||||
triggerNodeChanges: (changes: NodeChange[]) => void;
|
triggerNodeChanges: (changes: NodeChange[]) => void;
|
||||||
|
panBy: (delta: XYPosition) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ReactFlowState = ReactFlowStore & ReactFlowActions;
|
export type ReactFlowState = ReactFlowStore & 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]
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { KeyboardEvent as ReactKeyboardEvent } from 'react';
|
import type { KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||||
|
|
||||||
import type { Dimensions, Node, XYPosition, CoordinateExtent, Box, Rect } from '../types';
|
import type { Dimensions, Node, XYPosition, CoordinateExtent, Box, Rect } from '../types';
|
||||||
|
|
||||||
export const getDimensions = (node: HTMLDivElement): Dimensions => ({
|
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]),
|
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 =>
|
export const getHostForElement = (element: HTMLElement): Document | ShadowRoot =>
|
||||||
(element.getRootNode?.() as Document | ShadowRoot) || window?.document;
|
(element.getRootNode?.() as Document | ShadowRoot) || window?.document;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user