refactor(useDragNode): simplify

This commit is contained in:
moklick
2022-05-17 15:14:57 +02:00
parent ed02c0ec9c
commit ac3f830ee8
+6 -18
View File
@@ -1,4 +1,4 @@
import { RefObject, useEffect, useRef, MouseEvent, useState, useMemo, useCallback } from 'react'; import { RefObject, useEffect, useRef, MouseEvent, useState, useCallback } from 'react';
import { D3DragEvent, drag, SubjectPosition } from 'd3-drag'; import { D3DragEvent, drag, SubjectPosition } from 'd3-drag';
import { select } from 'd3-selection'; import { select } from 'd3-selection';
@@ -47,23 +47,14 @@ function useDrag({
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 parentPos = useRef<XYPosition>({ x: 0, y: 0 }); const parentPos = useRef<XYPosition>({ x: 0, y: 0 });
// TODO: should we store the ref or the bounds in the store?
// So that it is easier / more reliable to access?
const countainerBounds = useMemo(() => {
if (typeof document !== 'undefined') {
return document.querySelector('.react-flow')?.getBoundingClientRect();
}
}, []);
// returns the mouse position projected to the RF coordinate system // returns the mouse position projected to the RF coordinate system
const getMousePosition = useCallback( const getMousePosition = useCallback((event: UseDragEvent) => {
(event: UseDragEvent) => {
const { transform, snapGrid, snapToGrid } = store.getState(); const { transform, snapGrid, snapToGrid } = store.getState();
const mousePos = pointToRendererPoint( const mousePos = pointToRendererPoint(
{ {
x: event.sourceEvent.clientX - (countainerBounds?.x || 0) - (window.scrollX || 0), x: event.sourceEvent.clientX,
y: event.sourceEvent.clientY - (countainerBounds?.y || 0) - (window.scrollY || 0), y: event.sourceEvent.clientY,
}, },
transform, transform,
snapToGrid, snapToGrid,
@@ -74,12 +65,10 @@ function useDrag({
mousePos.y -= parentPos.current.y; mousePos.y -= parentPos.current.y;
return mousePos; return mousePos;
}, }, []);
[countainerBounds?.x, countainerBounds?.y, store]
);
useEffect(() => { useEffect(() => {
if (nodeRef?.current && countainerBounds) { if (nodeRef?.current) {
const selection = select(nodeRef.current); const selection = select(nodeRef.current);
if (disabled) { if (disabled) {
@@ -182,7 +171,6 @@ function useDrag({
store, store,
nodeId, nodeId,
selectNodesOnDrag, selectNodesOnDrag,
countainerBounds,
getMousePosition, getMousePosition,
]); ]);