feat(utils): add vanilla drag and panzoom (#3108)
* refactor(panzoom): create vanilla helper * feat(svelte): add interaction example * refactor(panzoom): cleanup * Update function-runner.ts * refactor(panzoom): cleanup * refactor(panzoom): rename functions * feat(utils): add vanilla drag helper (#3107) * feat(utils): add vanilla drag helper * refactor(drag): cleanup * refactor(drag): cleanup * chore(packages): cleanup * refactor(panzoom): cleanup and simplify
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
import { useEffect, useRef, useState, type RefObject } from 'react';
|
||||
import { XYDrag, type XYDragInstance } from '@reactflow/utils';
|
||||
|
||||
import { handleNodeClick } from '../components/Nodes/utils';
|
||||
import { useStoreApi } from './useStore';
|
||||
|
||||
type UseDragParams = {
|
||||
nodeRef: RefObject<Element>;
|
||||
disabled?: boolean;
|
||||
noDragClassName?: string;
|
||||
handleSelector?: string;
|
||||
nodeId?: string;
|
||||
isSelectable?: boolean;
|
||||
};
|
||||
|
||||
function useDrag({ nodeRef, disabled = false, noDragClassName, handleSelector, nodeId, isSelectable }: UseDragParams) {
|
||||
const store = useStoreApi();
|
||||
const [dragging, setDragging] = useState<boolean>(false);
|
||||
const xyDrag = useRef<XYDragInstance>();
|
||||
|
||||
useEffect(() => {
|
||||
if (nodeRef?.current) {
|
||||
xyDrag.current = XYDrag({
|
||||
domNode: nodeRef.current,
|
||||
getStoreItems: () => {
|
||||
const currentStore = store.getState();
|
||||
|
||||
return {
|
||||
nodes: currentStore.getNodes(),
|
||||
...store.getState(),
|
||||
};
|
||||
},
|
||||
onNodeClick: () => {
|
||||
if (nodeId) {
|
||||
handleNodeClick({
|
||||
id: nodeId,
|
||||
store,
|
||||
nodeRef: nodeRef as RefObject<HTMLDivElement>,
|
||||
});
|
||||
}
|
||||
},
|
||||
onDragStart: () => {
|
||||
setDragging(true);
|
||||
},
|
||||
onDragStop: () => {
|
||||
setDragging(false);
|
||||
},
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (disabled) {
|
||||
xyDrag.current?.destroy();
|
||||
} else {
|
||||
xyDrag.current?.update({
|
||||
noDragClassName,
|
||||
handleSelector,
|
||||
domNode: nodeRef.current as Element,
|
||||
isSelectable,
|
||||
nodeId,
|
||||
});
|
||||
return () => {
|
||||
xyDrag.current?.destroy();
|
||||
};
|
||||
}
|
||||
}, [noDragClassName, handleSelector, disabled, isSelectable, nodeRef, nodeId]);
|
||||
|
||||
return dragging;
|
||||
}
|
||||
|
||||
export default useDrag;
|
||||
@@ -1,250 +0,0 @@
|
||||
import { useEffect, useRef, useState, type RefObject, type MouseEvent } from 'react';
|
||||
import { drag } from 'd3-drag';
|
||||
import { select } from 'd3-selection';
|
||||
import { calcAutoPan, getEventPosition } from '@reactflow/utils';
|
||||
import type { NodeDragItem, UseDragEvent, XYPosition } from '@reactflow/system';
|
||||
|
||||
import { useStoreApi } from '../../hooks/useStore';
|
||||
import { getDragItems, getEventHandlerParams, hasSelector, calcNextPosition } from './utils';
|
||||
import { handleNodeClick } from '../../components/Nodes/utils';
|
||||
import useGetPointerPosition from '../useGetPointerPosition';
|
||||
import type { Node, SelectionDragHandler } from '../../types';
|
||||
|
||||
export type UseDragData = { dx: number; dy: number };
|
||||
|
||||
type UseDragParams = {
|
||||
nodeRef: RefObject<Element>;
|
||||
disabled?: boolean;
|
||||
noDragClassName?: string;
|
||||
handleSelector?: string;
|
||||
nodeId?: string;
|
||||
isSelectable?: boolean;
|
||||
selectNodesOnDrag?: boolean;
|
||||
};
|
||||
|
||||
function wrapSelectionDragFunc(selectionFunc?: SelectionDragHandler) {
|
||||
return (event: MouseEvent, _: Node, nodes: Node[]) => selectionFunc?.(event, nodes);
|
||||
}
|
||||
|
||||
function useDrag({
|
||||
nodeRef,
|
||||
disabled = false,
|
||||
noDragClassName,
|
||||
handleSelector,
|
||||
nodeId,
|
||||
isSelectable,
|
||||
selectNodesOnDrag,
|
||||
}: UseDragParams) {
|
||||
const store = useStoreApi();
|
||||
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();
|
||||
|
||||
useEffect(() => {
|
||||
if (nodeRef?.current) {
|
||||
const selection = select(nodeRef.current);
|
||||
|
||||
const updateNodes = ({ x, y }: XYPosition) => {
|
||||
const {
|
||||
nodeInternals,
|
||||
onNodeDrag,
|
||||
onSelectionDrag,
|
||||
updateNodePositions,
|
||||
nodeExtent,
|
||||
snapGrid,
|
||||
snapToGrid,
|
||||
nodeOrigin,
|
||||
onError,
|
||||
} = 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, onError);
|
||||
|
||||
// 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];
|
||||
|
||||
if (panBy({ x: xMovement, y: yMovement })) {
|
||||
updateNodes(lastPos.current as XYPosition);
|
||||
}
|
||||
}
|
||||
autoPanId.current = requestAnimationFrame(autoPan);
|
||||
};
|
||||
|
||||
if (disabled) {
|
||||
selection.on('.drag', null);
|
||||
} else {
|
||||
const dragHandler = drag()
|
||||
.on('start', (event: UseDragEvent) => {
|
||||
const {
|
||||
nodeInternals,
|
||||
multiSelectionActive,
|
||||
domNode,
|
||||
nodesDraggable,
|
||||
unselectNodesAndEdges,
|
||||
onNodeDragStart,
|
||||
onSelectionDragStart,
|
||||
} = store.getState();
|
||||
|
||||
const onStart = nodeId ? onNodeDragStart : wrapSelectionDragFunc(onSelectionDragStart);
|
||||
|
||||
if (!selectNodesOnDrag && !multiSelectionActive && nodeId) {
|
||||
if (!nodeInternals.get(nodeId)?.selected) {
|
||||
// we need to reset selected nodes when selectNodesOnDrag=false
|
||||
unselectNodesAndEdges();
|
||||
}
|
||||
}
|
||||
|
||||
if (nodeId && isSelectable && selectNodesOnDrag) {
|
||||
handleNodeClick({
|
||||
id: nodeId,
|
||||
store,
|
||||
nodeRef: nodeRef as RefObject<HTMLDivElement>,
|
||||
});
|
||||
}
|
||||
|
||||
const pointerPos = getPointerPosition(event);
|
||||
lastPos.current = pointerPos;
|
||||
dragItems.current = getDragItems(nodeInternals, nodesDraggable, pointerPos, nodeId);
|
||||
|
||||
if (onStart && dragItems.current) {
|
||||
const [currentNode, nodes] = getEventHandlerParams({
|
||||
nodeId,
|
||||
dragItems: dragItems.current,
|
||||
nodeInternals,
|
||||
});
|
||||
onStart(event.sourceEvent as MouseEvent, currentNode, nodes);
|
||||
}
|
||||
|
||||
containerBounds.current = domNode?.getBoundingClientRect() || null;
|
||||
mousePosition.current = getEventPosition(event.sourceEvent, containerBounds.current!);
|
||||
})
|
||||
.on('drag', (event: UseDragEvent) => {
|
||||
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
|
||||
) {
|
||||
dragEvent.current = event.sourceEvent as MouseEvent;
|
||||
mousePosition.current = getEventPosition(event.sourceEvent, containerBounds.current!);
|
||||
|
||||
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);
|
||||
|
||||
updateNodePositions(dragItems.current, false, false);
|
||||
|
||||
if (onStop) {
|
||||
const [currentNode, nodes] = getEventHandlerParams({
|
||||
nodeId,
|
||||
dragItems: dragItems.current,
|
||||
nodeInternals,
|
||||
});
|
||||
onStop(event.sourceEvent as MouseEvent, currentNode, nodes);
|
||||
}
|
||||
}
|
||||
})
|
||||
.filter((event: MouseEvent) => {
|
||||
const target = event.target as HTMLDivElement;
|
||||
const isDraggable =
|
||||
!event.button &&
|
||||
(!noDragClassName || !hasSelector(target, `.${noDragClassName}`, nodeRef)) &&
|
||||
(!handleSelector || hasSelector(target, handleSelector, nodeRef));
|
||||
|
||||
return isDraggable;
|
||||
});
|
||||
|
||||
selection.call(dragHandler);
|
||||
|
||||
return () => {
|
||||
selection.on('.drag', null);
|
||||
};
|
||||
}
|
||||
}
|
||||
}, [
|
||||
nodeRef,
|
||||
disabled,
|
||||
noDragClassName,
|
||||
handleSelector,
|
||||
isSelectable,
|
||||
store,
|
||||
nodeId,
|
||||
selectNodesOnDrag,
|
||||
getPointerPosition,
|
||||
]);
|
||||
|
||||
return dragging;
|
||||
}
|
||||
|
||||
export default useDrag;
|
||||
@@ -1,162 +0,0 @@
|
||||
import type { RefObject } from 'react';
|
||||
import {
|
||||
errorMessages,
|
||||
type CoordinateExtent,
|
||||
type NodeDragItem,
|
||||
type NodeOrigin,
|
||||
type OnError,
|
||||
type XYPosition,
|
||||
} from '@reactflow/system';
|
||||
import { clampPosition, isNumeric, getNodePositionWithOrigin } from '@reactflow/utils';
|
||||
|
||||
import type { Node, NodeInternals } from '../../types';
|
||||
|
||||
export function isParentSelected(node: Node, nodeInternals: NodeInternals): boolean {
|
||||
if (!node.parentNode) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const parentNode = nodeInternals.get(node.parentNode);
|
||||
|
||||
if (!parentNode) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (parentNode.selected) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return isParentSelected(parentNode, nodeInternals);
|
||||
}
|
||||
|
||||
export function hasSelector(target: Element, selector: string, nodeRef: RefObject<Element>): boolean {
|
||||
let current = target;
|
||||
|
||||
do {
|
||||
if (current?.matches(selector)) return true;
|
||||
if (current === nodeRef.current) return false;
|
||||
current = current.parentElement as Element;
|
||||
} while (current);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// looks for all selected nodes and created a NodeDragItem for each of them
|
||||
export function getDragItems(
|
||||
nodeInternals: NodeInternals,
|
||||
nodesDraggable: boolean,
|
||||
mousePos: XYPosition,
|
||||
nodeId?: string
|
||||
): NodeDragItem[] {
|
||||
return Array.from(nodeInternals.values())
|
||||
.filter(
|
||||
(n) =>
|
||||
(n.selected || n.id === nodeId) &&
|
||||
(!n.parentNode || !isParentSelected(n, nodeInternals)) &&
|
||||
(n.draggable || (nodesDraggable && typeof n.draggable === 'undefined'))
|
||||
)
|
||||
.map((n) => ({
|
||||
id: n.id,
|
||||
position: n.position || { x: 0, y: 0 },
|
||||
positionAbsolute: n.positionAbsolute || { x: 0, y: 0 },
|
||||
distance: {
|
||||
x: mousePos.x - (n.positionAbsolute?.x ?? 0),
|
||||
y: mousePos.y - (n.positionAbsolute?.y ?? 0),
|
||||
},
|
||||
delta: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
},
|
||||
extent: n.extent,
|
||||
parentNode: n.parentNode,
|
||||
width: n.width,
|
||||
height: n.height,
|
||||
origin: n.origin,
|
||||
}));
|
||||
}
|
||||
|
||||
export function calcNextPosition(
|
||||
node: NodeDragItem | Node,
|
||||
nextPosition: XYPosition,
|
||||
nodeInternals: NodeInternals,
|
||||
nodeExtent?: CoordinateExtent,
|
||||
nodeOrigin: NodeOrigin = [0, 0],
|
||||
onError?: OnError
|
||||
): { position: XYPosition; positionAbsolute: XYPosition } {
|
||||
let currentExtent = node.extent || nodeExtent;
|
||||
|
||||
if (node.extent === 'parent') {
|
||||
if (node.parentNode && node.width && node.height) {
|
||||
const parent = nodeInternals.get(node.parentNode);
|
||||
const parentOrigin = parent?.origin || nodeOrigin;
|
||||
const currNodeOrigin = node.origin || nodeOrigin;
|
||||
|
||||
const { x: parentX, y: parentY } = getNodePositionWithOrigin(parent, parentOrigin).positionAbsolute;
|
||||
currentExtent =
|
||||
parent && isNumeric(parentX) && isNumeric(parentY) && isNumeric(parent.width) && isNumeric(parent.height)
|
||||
? [
|
||||
[parentX + node.width * currNodeOrigin[0], parentY + node.height * currNodeOrigin[1]],
|
||||
[
|
||||
parentX + parent.width - node.width + node.width * currNodeOrigin[0],
|
||||
parentY + parent.height - node.height + node.height * currNodeOrigin[1],
|
||||
],
|
||||
]
|
||||
: currentExtent;
|
||||
} else {
|
||||
onError?.('005', errorMessages['error005']());
|
||||
|
||||
currentExtent = nodeExtent;
|
||||
}
|
||||
} else if (node.extent && node.parentNode) {
|
||||
const parent = nodeInternals.get(node.parentNode);
|
||||
const { x: parentX, y: parentY } = getNodePositionWithOrigin(parent, parent?.origin || nodeOrigin).positionAbsolute;
|
||||
currentExtent = [
|
||||
[node.extent[0][0] + parentX, node.extent[0][1] + parentY],
|
||||
[node.extent[1][0] + parentX, node.extent[1][1] + parentY],
|
||||
];
|
||||
}
|
||||
|
||||
let parentPosition = { x: 0, y: 0 };
|
||||
|
||||
if (node.parentNode) {
|
||||
const parentNode = nodeInternals.get(node.parentNode);
|
||||
parentPosition = getNodePositionWithOrigin(parentNode, parentNode?.origin || nodeOrigin).positionAbsolute;
|
||||
}
|
||||
|
||||
const positionAbsolute = currentExtent
|
||||
? clampPosition(nextPosition, currentExtent as CoordinateExtent)
|
||||
: nextPosition;
|
||||
|
||||
return {
|
||||
position: {
|
||||
x: positionAbsolute.x - parentPosition.x,
|
||||
y: positionAbsolute.y - parentPosition.y,
|
||||
},
|
||||
positionAbsolute,
|
||||
};
|
||||
}
|
||||
|
||||
// returns two params:
|
||||
// 1. the dragged node (or the first of the list, if we are dragging a node selection)
|
||||
// 2. array of selected nodes (for multi selections)
|
||||
export function getEventHandlerParams({
|
||||
nodeId,
|
||||
dragItems,
|
||||
nodeInternals,
|
||||
}: {
|
||||
nodeId?: string;
|
||||
dragItems: NodeDragItem[];
|
||||
nodeInternals: NodeInternals;
|
||||
}): [Node, Node[]] {
|
||||
const extentedDragItems: Node[] = dragItems.map((n) => {
|
||||
const node = nodeInternals.get(n.id)!;
|
||||
|
||||
return {
|
||||
...node,
|
||||
position: n.position,
|
||||
positionAbsolute: n.positionAbsolute,
|
||||
};
|
||||
});
|
||||
|
||||
return [nodeId ? extentedDragItems.find((n) => n.id === nodeId)! : extentedDragItems[0], extentedDragItems];
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import { useCallback } from 'react';
|
||||
import type { UseDragEvent } from '@reactflow/system';
|
||||
|
||||
import { useStoreApi } from './useStore';
|
||||
|
||||
function useGetPointerPosition() {
|
||||
const store = useStoreApi();
|
||||
|
||||
// returns the pointer position projected to the RF coordinate system
|
||||
const getPointerPosition = useCallback(({ sourceEvent }: UseDragEvent) => {
|
||||
const { transform, snapGrid, snapToGrid } = store.getState();
|
||||
const x = sourceEvent.touches ? sourceEvent.touches[0].clientX : sourceEvent.clientX;
|
||||
const y = sourceEvent.touches ? sourceEvent.touches[0].clientY : sourceEvent.clientY;
|
||||
|
||||
const pointerPos = {
|
||||
x: (x - transform[0]) / transform[2],
|
||||
y: (y - transform[1]) / transform[2],
|
||||
};
|
||||
|
||||
// we need the snapped position in order to be able to skip unnecessary drag events
|
||||
return {
|
||||
xSnapped: snapToGrid ? snapGrid[0] * Math.round(pointerPos.x / snapGrid[0]) : pointerPos.x,
|
||||
ySnapped: snapToGrid ? snapGrid[1] * Math.round(pointerPos.y / snapGrid[1]) : pointerPos.y,
|
||||
...pointerPos,
|
||||
};
|
||||
}, []);
|
||||
|
||||
return getPointerPosition;
|
||||
}
|
||||
|
||||
export default useGetPointerPosition;
|
||||
@@ -1,15 +1,16 @@
|
||||
import { useCallback } from 'react';
|
||||
import { calcNextPosition } from '@reactflow/utils';
|
||||
|
||||
import { useStoreApi } from '../hooks/useStore';
|
||||
import { calcNextPosition } from './useDrag/utils';
|
||||
|
||||
function useUpdateNodePositions() {
|
||||
const store = useStoreApi();
|
||||
|
||||
const updatePositions = useCallback((params: { x: number; y: number; isShiftPressed: boolean }) => {
|
||||
const { nodeInternals, nodeExtent, updateNodePositions, getNodes, snapToGrid, snapGrid, onError, nodesDraggable } =
|
||||
const { nodeExtent, updateNodePositions, getNodes, snapToGrid, snapGrid, onError, nodesDraggable } =
|
||||
store.getState();
|
||||
const selectedNodes = getNodes().filter(
|
||||
const nodes = getNodes();
|
||||
const selectedNodes = nodes.filter(
|
||||
(n) => n.selected && (n.draggable || (nodesDraggable && typeof n.draggable === 'undefined'))
|
||||
);
|
||||
// by default a node moves 5px on each key press, or 20px if shift is pressed
|
||||
@@ -30,14 +31,7 @@ function useUpdateNodePositions() {
|
||||
nextPosition.y = snapGrid[1] * Math.round(nextPosition.y / snapGrid[1]);
|
||||
}
|
||||
|
||||
const { positionAbsolute, position } = calcNextPosition(
|
||||
n,
|
||||
nextPosition,
|
||||
nodeInternals,
|
||||
nodeExtent,
|
||||
undefined,
|
||||
onError
|
||||
);
|
||||
const { positionAbsolute, position } = calcNextPosition(n, nextPosition, nodes, nodeExtent, undefined, onError);
|
||||
|
||||
n.position = position;
|
||||
n.positionAbsolute = positionAbsolute;
|
||||
|
||||
@@ -1,104 +1,94 @@
|
||||
import { useMemo } from 'react';
|
||||
import { zoomIdentity } from 'd3-zoom';
|
||||
import { shallow } from 'zustand/shallow';
|
||||
import { pointToRendererPoint, getTransformForBounds, getD3Transition, fitView } from '@reactflow/utils';
|
||||
import { pointToRendererPoint, getTransformForBounds, fitView } from '@reactflow/utils';
|
||||
import type { XYPosition } from '@reactflow/system';
|
||||
|
||||
import { useStoreApi, useStore } from '../hooks/useStore';
|
||||
import type { ViewportHelperFunctions, ReactFlowState } from '../types';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-function
|
||||
const noop = () => {};
|
||||
|
||||
const initialViewportHelper: ViewportHelperFunctions = {
|
||||
zoomIn: noop,
|
||||
zoomOut: noop,
|
||||
zoomTo: noop,
|
||||
getZoom: () => 1,
|
||||
setViewport: noop,
|
||||
getViewport: () => ({ x: 0, y: 0, zoom: 1 }),
|
||||
fitView: () => false,
|
||||
setCenter: noop,
|
||||
fitBounds: noop,
|
||||
project: (position: XYPosition) => position,
|
||||
viewportInitialized: false,
|
||||
};
|
||||
|
||||
const selector = (s: ReactFlowState) => ({
|
||||
d3Zoom: s.d3Zoom,
|
||||
d3Selection: s.d3Selection,
|
||||
});
|
||||
const selector = (s: ReactFlowState) => !!s.panZoom;
|
||||
|
||||
const useViewportHelper = (): ViewportHelperFunctions => {
|
||||
const store = useStoreApi();
|
||||
const { d3Zoom, d3Selection } = useStore(selector, shallow);
|
||||
const panZoomInitialized = useStore(selector);
|
||||
|
||||
const viewportHelperFunctions = useMemo<ViewportHelperFunctions>(() => {
|
||||
if (d3Selection && d3Zoom) {
|
||||
return {
|
||||
zoomIn: (options) => d3Zoom.scaleBy(getD3Transition(d3Selection, options?.duration), 1.2),
|
||||
zoomOut: (options) => d3Zoom.scaleBy(getD3Transition(d3Selection, options?.duration), 1 / 1.2),
|
||||
zoomTo: (zoomLevel, options) => d3Zoom.scaleTo(getD3Transition(d3Selection, options?.duration), zoomLevel),
|
||||
getZoom: () => store.getState().transform[2],
|
||||
setViewport: (transform, options) => {
|
||||
const [x, y, zoom] = store.getState().transform;
|
||||
const nextTransform = zoomIdentity
|
||||
.translate(transform.x ?? x, transform.y ?? y)
|
||||
.scale(transform.zoom ?? zoom);
|
||||
d3Zoom.transform(getD3Transition(d3Selection, options?.duration), nextTransform);
|
||||
},
|
||||
getViewport: () => {
|
||||
const [x, y, zoom] = store.getState().transform;
|
||||
return { x, y, zoom };
|
||||
},
|
||||
fitView: (options) => {
|
||||
const { getNodes, width, height, nodeOrigin, minZoom, maxZoom, d3Selection, d3Zoom } = store.getState();
|
||||
const d3Initialized = d3Selection && d3Zoom;
|
||||
return {
|
||||
zoomIn: (options) => store.getState().panZoom?.scaleBy(1.2, { duration: options?.duration }),
|
||||
zoomOut: (options) => store.getState().panZoom?.scaleBy(1 / 1.2, { duration: options?.duration }),
|
||||
zoomTo: (zoomLevel, options) => store.getState().panZoom?.scaleTo(zoomLevel, { duration: options?.duration }),
|
||||
getZoom: () => store.getState().transform[2],
|
||||
setViewport: (viewport, options) => {
|
||||
const {
|
||||
transform: [tX, tY, tZoom],
|
||||
panZoom,
|
||||
} = store.getState();
|
||||
|
||||
if (!d3Initialized) {
|
||||
return false;
|
||||
}
|
||||
panZoom?.setViewport(
|
||||
{
|
||||
x: viewport.x ?? tX,
|
||||
y: viewport.y ?? tY,
|
||||
zoom: viewport.zoom ?? tZoom,
|
||||
},
|
||||
{ duration: options?.duration }
|
||||
);
|
||||
},
|
||||
getViewport: () => {
|
||||
const [x, y, zoom] = store.getState().transform;
|
||||
return { x, y, zoom };
|
||||
},
|
||||
fitView: (options) => {
|
||||
const { getNodes, width, height, nodeOrigin, minZoom, maxZoom, panZoom } = store.getState();
|
||||
|
||||
return fitView(
|
||||
{
|
||||
nodes: getNodes(),
|
||||
width,
|
||||
height,
|
||||
nodeOrigin,
|
||||
minZoom,
|
||||
maxZoom,
|
||||
d3Selection,
|
||||
d3Zoom,
|
||||
},
|
||||
options
|
||||
);
|
||||
},
|
||||
setCenter: (x, y, options) => {
|
||||
const { width, height, maxZoom } = store.getState();
|
||||
const nextZoom = typeof options?.zoom !== 'undefined' ? options.zoom : maxZoom;
|
||||
const centerX = width / 2 - x * nextZoom;
|
||||
const centerY = height / 2 - y * nextZoom;
|
||||
const transform = zoomIdentity.translate(centerX, centerY).scale(nextZoom);
|
||||
return panZoom
|
||||
? fitView(
|
||||
{
|
||||
nodes: getNodes(),
|
||||
width,
|
||||
height,
|
||||
nodeOrigin,
|
||||
minZoom,
|
||||
maxZoom,
|
||||
panZoom,
|
||||
},
|
||||
options
|
||||
)
|
||||
: false;
|
||||
},
|
||||
setCenter: (x, y, options) => {
|
||||
const { width, height, maxZoom, panZoom } = store.getState();
|
||||
const nextZoom = typeof options?.zoom !== 'undefined' ? options.zoom : maxZoom;
|
||||
const centerX = width / 2 - x * nextZoom;
|
||||
const centerY = height / 2 - y * nextZoom;
|
||||
|
||||
d3Zoom.transform(getD3Transition(d3Selection, options?.duration), transform);
|
||||
},
|
||||
fitBounds: (bounds, options) => {
|
||||
const { width, height, minZoom, maxZoom } = store.getState();
|
||||
const [x, y, zoom] = getTransformForBounds(bounds, width, height, minZoom, maxZoom, options?.padding ?? 0.1);
|
||||
const transform = zoomIdentity.translate(x, y).scale(zoom);
|
||||
panZoom?.setViewport(
|
||||
{
|
||||
x: centerX,
|
||||
y: centerY,
|
||||
zoom: nextZoom,
|
||||
},
|
||||
{ duration: options?.duration }
|
||||
);
|
||||
},
|
||||
fitBounds: (bounds, options) => {
|
||||
const { width, height, minZoom, maxZoom, panZoom } = store.getState();
|
||||
const [x, y, zoom] = getTransformForBounds(bounds, width, height, minZoom, maxZoom, options?.padding ?? 0.1);
|
||||
|
||||
d3Zoom.transform(getD3Transition(d3Selection, options?.duration), transform);
|
||||
},
|
||||
project: (position: XYPosition) => {
|
||||
const { transform, snapToGrid, snapGrid } = store.getState();
|
||||
return pointToRendererPoint(position, transform, snapToGrid, snapGrid);
|
||||
},
|
||||
viewportInitialized: true,
|
||||
};
|
||||
}
|
||||
|
||||
return initialViewportHelper;
|
||||
}, [d3Zoom, d3Selection]);
|
||||
panZoom?.setViewport(
|
||||
{
|
||||
x,
|
||||
y,
|
||||
zoom,
|
||||
},
|
||||
{ duration: options?.duration }
|
||||
);
|
||||
},
|
||||
project: (position: XYPosition) => {
|
||||
const { transform, snapToGrid, snapGrid } = store.getState();
|
||||
return pointToRendererPoint(position, transform, snapToGrid, snapGrid);
|
||||
},
|
||||
viewportInitialized: panZoomInitialized,
|
||||
};
|
||||
}, [panZoomInitialized]);
|
||||
|
||||
return viewportHelperFunctions;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user