Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

make hooks' handlers stable & some cleanup

Roman Pominove09a7e9efd77
diff --git a/apps/designer/app/canvas/shared/use-drag-drop.ts b/apps/designer/app/canvas/shared/use-drag-drop.ts
index ddc80c0fd3..d746193b20 100644
--- a/apps/designer/app/canvas/shared/use-drag-drop.ts
+++ b/apps/designer/app/canvas/shared/use-drag-drop.ts
@@ -2,7 +2,6 @@ import { useLayoutEffect, useRef } from "react";
import { useRootInstance } from "~/shared/nano-states";
import { findInstanceById, getInstancePath } from "~/shared/tree-utils";
import {
- type Rect,
type DropTarget,
useAutoScroll,
usePlacement,
@@ -16,6 +15,8 @@ import {
components as primitives,
} from "@webstudio-is/react-sdk";
+export type Rect = Pick<DOMRect, "top" | "left" | "width" | "height">;
+
// data shared between iframe and main window
export type DropTargetSharedData = {
rect: Rect;
@@ -207,14 +208,11 @@ export const useDragAndDrop = () => {
useDragHandlers.rootRef(document.body);
window.addEventListener("scroll", handleScroll);
- () => {
+ return () => {
dropTargetHandlers.rootRef(null);
useDragHandlers.rootRef(null);
window.removeEventListener("scroll", handleScroll);
};
-
- // @todo: need to make the dependencies more stable,
- // because as is this will fire on every render
}, [
useDragHandlers,
dropTargetHandlers,
diff --git a/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx b/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx
index 0ab86182dd..a694bf15c6 100644
--- a/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx
+++ b/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx
@@ -3,7 +3,8 @@ import React, { useState, useRef } from "react";
import { Box } from "../../box";
import { useDropTarget } from "./use-drop-target";
import { useDrag } from "./use-drag";
-import { usePlacement, PlacementIndicator, type Rect } from "./placement";
+import { type Rect } from "./rect";
+import { usePlacement, PlacementIndicator } from "./placement";
import { useAutoScroll } from "./use-auto-scroll";
const ROOT_ID = "root";
diff --git a/packages/design-system/src/components/primitives/dnd/placement.tsx b/packages/design-system/src/components/primitives/dnd/placement.tsx
index d71cb6ea63..2784ffacf7 100644
--- a/packages/design-system/src/components/primitives/dnd/placement.tsx
+++ b/packages/design-system/src/components/primitives/dnd/placement.tsx
@@ -1,8 +1,6 @@
-import { useRef } from "react";
+import { useRef, useMemo } from "react";
import { Box } from "../../box";
-
-export type Rect = Pick<DOMRect, "top" | "left" | "width" | "height">;
-type Point = { x: number; y: number };
+import { type Rect, getClosestRectIndex, isEqualRect } from "./rect";
let probeCache: undefined | HTMLElement;
const getProbe = () => {
@@ -35,184 +33,162 @@ const getPlacement = ({
return rect;
};
-// https://stackoverflow.com/a/18157551/478603
-const getDistance = (rect: Rect, { x, y }: Point) => {
- const dx = Math.max(rect.left - x, 0, x - (rect.left + rect.width));
- const dy = Math.max(rect.top - y, 0, y - (rect.top + rect.height));
- return Math.sqrt(dx * dx + dy * dy);
-};
-
-const getClosestRectIndex = (rects: Rect[], point: Point) => {
- if (rects.length === 0) {
- return -1;
- }
-
- const sorted = rects
- .map((rect, index) => ({
- index,
- distance: getDistance(rect, point),
- }))
- .sort((a, b) => a.distance - b.distance);
-
- return sorted[0].index;
-};
-
-const isEqualRect = (a: Rect | undefined, b: Rect) => {
- return (
- a !== undefined &&
- a.top === b.top &&
- a.left === b.left &&
- a.width === b.width &&
- a.height === b.height
- );
-};
-
type UsePlacementProps = {
onPlacementChange: (event: { index: number; placementRect: Rect }) => void;
};
type Handlers = {
handleEnd: () => void;
- handleMove: (pointerPoint: Point) => void;
+ handleMove: (pointerPoint: { x: number; y: number }) => void;
handleScroll: () => void;
handleTargetChange: (target: HTMLElement) => void;
};
-export const usePlacement = ({
- onPlacementChange,
-}: UsePlacementProps): Handlers => {
+export const usePlacement = (props: UsePlacementProps): Handlers => {
+ // We want to use fresh props every time we use them,
+ // but we don't need to react to updates.
+ // So we can put them in a ref and make useMemo below very efficient.
+ const latestProps = useRef<UsePlacementProps>(props);
+ latestProps.current = props;
+
const state = useRef({
childrenRectsCache: new WeakMap<HTMLElement, Rect[]>(),
target: undefined as HTMLElement | undefined,
targetRect: undefined as DOMRect | undefined,
- pointerPoint: undefined as Point | undefined,
+ pointerPoint: undefined as { x: number; y: number } | undefined,
index: undefined as number | undefined,
placementRext: undefined as Rect | undefined,
});
- const getChildrenRects = (parent: HTMLElement, parentRect: DOMRect) => {
- const fromCache = state.current.childrenRectsCache.get(parent);
- if (fromCache !== undefined) {
- return fromCache;
- }
-
- const result: Rect[] = [];
-
- for (const child of parent.children) {
- if (child instanceof HTMLElement) {
- const rect = child.getBoundingClientRect();
- result.push({
- top: rect.top - parentRect.top,
- left: rect.left - parentRect.left,
- width: rect.width,
- height: rect.height,
- });
+ // We want to retrun a stable object to avoid re-renders when it's a dependency
+ return useMemo(() => {
+ const getChildrenRects = (parent: HTMLElement, parentRect: DOMRect) => {
+ const fromCache = state.current.childrenRectsCache.get(parent);
+ if (fromCache !== undefined) {
+ return fromCache;
}
- }
- state.current.childrenRectsCache.set(parent, result);
- return result;
- };
+ const result: Rect[] = [];
+
+ for (const child of parent.children) {
+ if (child instanceof HTMLElement) {
+ const rect = child.getBoundingClientRect();
+ result.push({
+ top: rect.top - parentRect.top,
+ left: rect.left - parentRect.left,
+ width: rect.width,
+ height: rect.height,
+ });
+ }
+ }
+
+ state.current.childrenRectsCache.set(parent, result);
+ return result;
+ };
- const getIndex = (
- parent: HTMLElement,
- parentRect: DOMRect,
- pointerPoint: Point
- ) => {
- if (parent.children.length === 0) {
- return 0;
- }
+ const getIndex = (
+ parent: HTMLElement,
+ parentRect: DOMRect,
+ pointerPoint: { x: number; y: number }
+ ) => {
+ if (parent.children.length === 0) {
+ return 0;
+ }
- const childrenRects = getChildrenRects(parent, parentRect);
+ const childrenRects = getChildrenRects(parent, parentRect);
- const pointerAdjusted = {
- x: pointerPoint.x - parentRect.left,
- y: pointerPoint.y - parentRect.top,
+ const pointerAdjusted = {
+ x: pointerPoint.x - parentRect.left,
+ y: pointerPoint.y - parentRect.top,
+ };
+
+ const closestRectIndex = getClosestRectIndex(
+ childrenRects,
+ pointerAdjusted
+ );
+ const closesRect = childrenRects[closestRectIndex];
+
+ const isOrientationVertical =
+ childrenRects.length < 2 ||
+ childrenRects[0].left === childrenRects[1].left;
+
+ if (isOrientationVertical) {
+ const middleY = closesRect.top + closesRect.height / 2;
+ return pointerAdjusted.y < middleY
+ ? closestRectIndex
+ : closestRectIndex + 1;
+ } else {
+ const middleX = closesRect.left + closesRect.width / 2;
+ return pointerAdjusted.x < middleX
+ ? closestRectIndex
+ : closestRectIndex + 1;
+ }
};
- const closestRectIndex = getClosestRectIndex(
- childrenRects,
- pointerAdjusted
- );
- const closesRect = childrenRects[closestRectIndex];
-
- const isOrientationVertical =
- childrenRects.length < 2 ||
- childrenRects[0].left === childrenRects[1].left;
-
- if (isOrientationVertical) {
- const middleY = closesRect.top + closesRect.height / 2;
- return pointerAdjusted.y < middleY
- ? closestRectIndex
- : closestRectIndex + 1;
- } else {
- const middleX = closesRect.left + closesRect.width / 2;
- return pointerAdjusted.x < middleX
- ? closestRectIndex
- : closestRectIndex + 1;
- }
- };
+ const detectChange = (
+ reason: "pointer-move" | "scroll" | "target-change"
+ ) => {
+ const { target, pointerPoint } = state.current;
- const detectChange = (
- reason: "pointer-move" | "scroll" | "target-change"
- ) => {
- const { target, pointerPoint } = state.current;
-
- if (target === undefined || pointerPoint === undefined) {
- return;
- }
-
- const nextTargetRect = target.getBoundingClientRect();
- const targetRectChanged = !isEqualRect(
- state.current.targetRect,
- nextTargetRect
- );
-
- state.current.targetRect = nextTargetRect;
-
- const nextIndex = getIndex(target, nextTargetRect, pointerPoint);
- const indexChanged = nextIndex !== state.current.index;
- state.current.index = nextIndex;
-
- if (reason !== "target-change" && !indexChanged && !targetRectChanged) {
- return;
- }
-
- const nextPlacementRect = getPlacement({ target, index: nextIndex });
- const placementRectChanged = !isEqualRect(
- state.current.placementRext,
- nextPlacementRect
- );
- state.current.placementRext = nextPlacementRect;
-
- if (placementRectChanged || indexChanged) {
- onPlacementChange({ index: nextIndex, placementRect: nextPlacementRect });
- }
- };
+ if (target === undefined || pointerPoint === undefined) {
+ return;
+ }
- return {
- handleEnd() {
- state.current = {
- childrenRectsCache: new WeakMap(),
- target: undefined,
- targetRect: undefined,
- pointerPoint: undefined,
- index: undefined,
- placementRext: undefined,
- };
- },
- handleMove(pointerPoint) {
- state.current.pointerPoint = pointerPoint;
- detectChange("pointer-move");
- },
- handleScroll() {
- detectChange("scroll");
- },
- handleTargetChange: (target) => {
- state.current.target = target;
- detectChange("target-change");
- },
- };
+ const nextTargetRect = target.getBoundingClientRect();
+ const targetRectChanged = !isEqualRect(
+ state.current.targetRect,
+ nextTargetRect
+ );
+
+ state.current.targetRect = nextTargetRect;
+
+ const nextIndex = getIndex(target, nextTargetRect, pointerPoint);
+ const indexChanged = nextIndex !== state.current.index;
+ state.current.index = nextIndex;
+
+ if (reason !== "target-change" && !indexChanged && !targetRectChanged) {
+ return;
+ }
+
+ const nextPlacementRect = getPlacement({ target, index: nextIndex });
+ const placementRectChanged = !isEqualRect(
+ state.current.placementRext,
+ nextPlacementRect
+ );
+ state.current.placementRext = nextPlacementRect;
+
+ if (placementRectChanged || indexChanged) {
+ latestProps.current.onPlacementChange({
+ index: nextIndex,
+ placementRect: nextPlacementRect,
+ });
+ }
+ };
+
+ return {
+ handleEnd() {
+ state.current = {
+ childrenRectsCache: new WeakMap(),
+ target: undefined,
+ targetRect: undefined,
+ pointerPoint: undefined,
+ index: undefined,
+ placementRext: undefined,
+ };
+ },
+ handleMove(pointerPoint) {
+ state.current.pointerPoint = pointerPoint;
+ detectChange("pointer-move");
+ },
+ handleScroll() {
+ detectChange("scroll");
+ },
+ handleTargetChange: (target) => {
+ state.current.target = target;
+ detectChange("target-change");
+ },
+ };
+ }, []);
};
export const PlacementIndicator = ({ rect }: { rect?: Rect }) => {
diff --git a/packages/design-system/src/components/primitives/dnd/rect.ts b/packages/design-system/src/components/primitives/dnd/rect.ts
new file mode 100644
index 0000000000..b6dd8e17ee
--- /dev/null
+++ b/packages/design-system/src/components/primitives/dnd/rect.ts
@@ -0,0 +1,36 @@
+export type Rect = Pick<DOMRect, "top" | "left" | "width" | "height">;
+
+// https://stackoverflow.com/a/18157551/478603
+const getDistanceToRect = (rect: Rect, { x, y }: { x: number; y: number }) => {
+ const dx = Math.max(rect.left - x, 0, x - (rect.left + rect.width));
+ const dy = Math.max(rect.top - y, 0, y - (rect.top + rect.height));
+ return Math.sqrt(dx * dx + dy * dy);
+};
+
+export const getClosestRectIndex = (
+ rects: Rect[],
+ point: { x: number; y: number }
+) => {
+ if (rects.length === 0) {
+ return -1;
+ }
+
+ const sorted = rects
+ .map((rect, index) => ({
+ index,
+ distance: getDistanceToRect(rect, point),
+ }))
+ .sort((a, b) => a.distance - b.distance);
+
+ return sorted[0].index;
+};
+
+export const isEqualRect = (a: Rect | undefined, b: Rect) => {
+ return (
+ a !== undefined &&
+ a.top === b.top &&
+ a.left === b.left &&
+ a.width === b.width &&
+ a.height === b.height
+ );
+};
diff --git a/packages/design-system/src/components/primitives/dnd/sortable-list.stories.tsx b/packages/design-system/src/components/primitives/dnd/sortable-list.stories.tsx
index 6a0446fc60..37edace62c 100644
--- a/packages/design-system/src/components/primitives/dnd/sortable-list.stories.tsx
+++ b/packages/design-system/src/components/primitives/dnd/sortable-list.stories.tsx
@@ -4,7 +4,8 @@ import { Box } from "../../box";
import { styled } from "../../../stitches.config";
import { useDropTarget } from "./use-drop-target";
import { useDrag } from "./use-drag";
-import { usePlacement, PlacementIndicator, type Rect } from "./placement";
+import { type Rect } from "./rect";
+import { usePlacement, PlacementIndicator } from "./placement";
import { useAutoScroll } from "./use-auto-scroll";
type ItemData = { id: string; text: string };
@@ -75,7 +76,6 @@ export const SortableList = ({
return element instanceof HTMLUListElement;
},
onDropTargetChange(event) {
- console.log(event);
placementHandlers.handleTargetChange(event.element);
},
});
diff --git a/packages/design-system/src/components/primitives/dnd/use-auto-scroll.ts b/packages/design-system/src/components/primitives/dnd/use-auto-scroll.ts
index 999e9f09a6..e05d76df70 100644
--- a/packages/design-system/src/components/primitives/dnd/use-auto-scroll.ts
+++ b/packages/design-system/src/components/primitives/dnd/use-auto-scroll.ts
@@ -1,4 +1,4 @@
-import { useRef } from "react";
+import { useRef, useMemo } from "react";
// Time between frames of scroll animation in milliseconds
const FRAME_PERIOD = 30;
@@ -56,12 +56,15 @@ export type UseAutoScrollHandlers = {
targetRef: (element: HTMLElement | null) => void;
};
-export const useAutoScroll = ({
- edgeDistanceThreshold = 100,
- minSpeed = 1,
- maxSpeed = 500,
- fullScreen = false,
-}: UseAutoScrollProps = {}): UseAutoScrollHandlers => {
+export const useAutoScroll = (
+ props: UseAutoScrollProps = {}
+): UseAutoScrollHandlers => {
+ // We want to use fresh props every time we use them,
+ // but we don't need to react to updates.
+ // So we can put them in a ref and make useMemo below very efficient.
+ const latestProps = useRef<UseAutoScrollProps>(props);
+ latestProps.current = props;
+
const state = useRef({
target: null as HTMLElement | null,
enabled: false,
@@ -71,114 +74,122 @@ export const useAutoScroll = ({
stepScheduled: false,
});
- const getViewportRect = () => {
- if (fullScreen) {
- return {
- top: 0,
- left: 0,
- bottom: window.innerHeight,
- right: window.innerWidth,
- };
- }
-
- if (state.current.target === null) {
- return;
- }
-
- return state.current.target.getBoundingClientRect();
- };
-
- const scrollBy = (x: number, y: number) => {
- if (fullScreen) {
- window.scrollBy(x, y);
- }
-
- if (state.current.target === null) {
- return;
- }
-
- state.current.target.scrollBy(x, y);
- };
-
- const step = (timestamp: number) => {
- state.current.stepScheduled = false;
+ return useMemo(() => {
+ const getViewportRect = () => {
+ if (latestProps.current.fullScreen) {
+ return {
+ top: 0,
+ left: 0,
+ bottom: window.innerHeight,
+ right: window.innerWidth,
+ };
+ }
- if (
- !state.current.enabled ||
- (Math.round((state.current.speedX / 1000) * FRAME_PERIOD) === 0 &&
- Math.round((state.current.speedY / 1000) * FRAME_PERIOD) === 0)
- ) {
- return;
- }
+ if (state.current.target === null) {
+ return;
+ }
- const elapsed = timestamp - state.current.prevTimestamp;
+ return state.current.target.getBoundingClientRect();
+ };
- // to avoid a big jump when auto-scroll becomes enabled
- if (elapsed > FRAME_PERIOD * 100) {
- state.current.prevTimestamp = timestamp;
- scheduleStep();
- return;
- }
+ const scrollBy = (x: number, y: number) => {
+ if (latestProps.current.fullScreen) {
+ window.scrollBy(x, y);
+ }
- if (elapsed < FRAME_PERIOD) {
- scheduleStep();
- return;
- }
+ if (state.current.target === null) {
+ return;
+ }
- state.current.prevTimestamp = timestamp;
+ state.current.target.scrollBy(x, y);
+ };
- scrollBy(
- (state.current.speedX / 1000) * elapsed,
- (state.current.speedY / 1000) * elapsed
- );
+ const step = (timestamp: number) => {
+ state.current.stepScheduled = false;
- scheduleStep();
- };
+ if (
+ !state.current.enabled ||
+ (Math.round((state.current.speedX / 1000) * FRAME_PERIOD) === 0 &&
+ Math.round((state.current.speedY / 1000) * FRAME_PERIOD) === 0)
+ ) {
+ return;
+ }
- const scheduleStep = () => {
- if (!state.current.stepScheduled) {
- state.current.stepScheduled = true;
- window.requestAnimationFrame(step);
- }
- };
+ const elapsed = timestamp - state.current.prevTimestamp;
- return {
- handleMove({ x, y }) {
- if (!state.current.enabled) {
+ // to avoid a big jump when auto-scroll becomes enabled
+ if (elapsed > FRAME_PERIOD * 100) {
+ state.current.prevTimestamp = timestamp;
+ scheduleStep();
return;
}
- const rect = getViewportRect();
- if (rect === undefined) {
+ if (elapsed < FRAME_PERIOD) {
+ scheduleStep();
return;
}
- state.current.speedY = getSpeed(
- y,
- rect.top,
- rect.bottom,
- edgeDistanceThreshold,
- minSpeed,
- maxSpeed
- );
+ state.current.prevTimestamp = timestamp;
- state.current.speedX = getSpeed(
- x,
- rect.left,
- rect.right,
- edgeDistanceThreshold,
- minSpeed,
- maxSpeed
+ scrollBy(
+ (state.current.speedX / 1000) * elapsed,
+ (state.current.speedY / 1000) * elapsed
);
scheduleStep();
- },
- setEnabled(newEnabled) {
- state.current.enabled = newEnabled;
- scheduleStep();
- },
- targetRef: (element) => {
- state.current.target = element;
- },
- };
+ };
+
+ const scheduleStep = () => {
+ if (!state.current.stepScheduled) {
+ state.current.stepScheduled = true;
+ window.requestAnimationFrame(step);
+ }
+ };
+
+ const {
+ edgeDistanceThreshold = 100,
+ minSpeed = 1,
+ maxSpeed = 500,
+ } = latestProps.current;
+
+ return {
+ handleMove({ x, y }) {
+ if (!state.current.enabled) {
+ return;
+ }
+
+ const rect = getViewportRect();
+ if (rect === undefined) {
+ return;
+ }
+
+ state.current.speedY = getSpeed(
+ y,
+ rect.top,
+ rect.bottom,
+ edgeDistanceThreshold,
+ minSpeed,
+ maxSpeed
+ );
+
+ state.current.speedX = getSpeed(
+ x,
+ rect.left,
+ rect.right,
+ edgeDistanceThreshold,
+ minSpeed,
+ maxSpeed
+ );
+
+ scheduleStep();
+ },
+ setEnabled(newEnabled) {
+ state.current.enabled = newEnabled;
+ scheduleStep();
+ },
+ targetRef: (element) => {
+ state.current.target = element;
+ },
+ };
+ }, []);
};
diff --git a/packages/design-system/src/components/primitives/dnd/use-drag.ts b/packages/design-system/src/components/primitives/dnd/use-drag.ts
index ed3866e23d..e097a7af6e 100644
--- a/packages/design-system/src/components/primitives/dnd/use-drag.ts
+++ b/packages/design-system/src/components/primitives/dnd/use-drag.ts
@@ -1,5 +1,5 @@
import { useMove } from "./use-move";
-import { useRef, useEffect } from "react";
+import { useRef, useEffect, useMemo } from "react";
type State =
| {
@@ -136,9 +136,12 @@ export const useDrag = ({
}
}, [onPointerDown]);
- return {
- rootRef(element) {
- rootRef.current = element;
- },
- };
+ // We want to retrun a stable object to avoid re-renders when it's a dependency
+ return useMemo(() => {
+ return {
+ rootRef(element) {
+ rootRef.current = element;
+ },
+ };
+ }, []);
};
diff --git a/packages/design-system/src/components/primitives/dnd/use-drop-target.ts b/packages/design-system/src/components/primitives/dnd/use-drop-target.ts
index c8e859c209..441fb2b279 100644
--- a/packages/design-system/src/components/primitives/dnd/use-drop-target.ts
+++ b/packages/design-system/src/components/primitives/dnd/use-drop-target.ts
@@ -1,4 +1,5 @@
-import { useRef } from "react";
+import { useRef, useMemo } from "react";
+import { isEqualRect } from "./rect";
export type Area = "top" | "right" | "bottom" | "left" | "center";
@@ -8,12 +9,6 @@ export type DropTarget<Data> = {
rect: DOMRect;
};
-const isSameRect = (a: DOMRect, b: DOMRect) =>
- a.top === b.top &&
- a.left === b.left &&
- a.bottom === b.bottom &&
- a.right === b.right;
-
// We pass around data, to avoid extra data lookups.
// For example, data found in isDropTarget
// doesn't have to be looked up again in swapDropTarget.
@@ -45,99 +40,112 @@ export type UseDropTargetHandlers = {
rootRef: (element: HTMLElement | null) => void;
};
-export const useDropTarget = <Data>({
- edgeDistanceThreshold = 3,
- isSameData = (data1: Data, data2: Data) => data1 === data2,
- isDropTarget,
- swapDropTarget = (args) => args,
- onDropTargetChange,
-}: UseDropTargetProps<Data>): UseDropTargetHandlers => {
+export const useDropTarget = <Data>(
+ props: UseDropTargetProps<Data>
+): UseDropTargetHandlers => {
+ // We want to use fresh props every time we use them,
+ // but we don't need to react to updates.
+ // So we can put them in a ref and make useMemo below very efficient.
+ const latestProps = useRef<UseDropTargetProps<Data>>(props);
+ latestProps.current = props;
+
const state = useRef({
root: null as HTMLElement | null,
pointerCoordinate: undefined as Coordinate | undefined,
dropTarget: undefined as DropTarget<Data> | undefined,
});
- const detectTarget = () => {
- const { pointerCoordinate, root } = state.current;
- if (pointerCoordinate === undefined || root === null) {
- return;
- }
-
- const target = elementFromPoint(pointerCoordinate);
- if (target === undefined) {
- return;
- }
-
- // @todo: cache this? Not expensive by itself, but it may call isDropTarget a lot
- const potentialTarget = findClosestDropTarget({
- root,
- target,
- isDropTarget,
- });
- if (potentialTarget === undefined) {
- return;
- }
-
- // @todo: if neither potentialTarget nor area has changed since the last time,
- // don't call swapDropTarget.
+ // We want to retrun a stable object to avoid re-renders when it's a dependency
+ return useMemo(() => {
+ const detectTarget = () => {
+ const {
+ edgeDistanceThreshold = 3,
+ isSameData = (data1: Data, data2: Data) => data1 === data2,
+ isDropTarget,
+ swapDropTarget = (args) => args,
+ onDropTargetChange,
+ } = latestProps.current;
+
+ const { pointerCoordinate, root } = state.current;
+ if (pointerCoordinate === undefined || root === null) {
+ return;
+ }
- const dropTarget = {
- ...potentialTarget,
- rect: potentialTarget.element.getBoundingClientRect(),
- };
+ const target = elementFromPoint(pointerCoordinate);
+ if (target === undefined) {
+ return;
+ }
- // eslint-disable-next-line no-constant-condition
- while (true) {
- const swappedTarget = swapDropTarget({
- element: dropTarget.element,
- data: dropTarget.data,
- area: getArea(
- pointerCoordinate,
- edgeDistanceThreshold,
- dropTarget.rect
- ),
+ // @todo: cache this? Not expensive by itself, but it may call isDropTarget a lot
+ const potentialTarget = findClosestDropTarget({
+ root,
+ target,
+ isDropTarget,
});
-
- if (swappedTarget.element === dropTarget.element) {
- break;
+ if (potentialTarget === undefined) {
+ return;
}
- dropTarget.element = swappedTarget.element;
- dropTarget.data = swappedTarget.data;
- dropTarget.rect = swappedTarget.element.getBoundingClientRect();
- }
+ // @todo: if neither potentialTarget nor area has changed since the last time,
+ // don't call swapDropTarget.
+
+ const dropTarget = {
+ ...potentialTarget,
+ rect: potentialTarget.element.getBoundingClientRect(),
+ };
+
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ const swappedTarget = swapDropTarget({
+ element: dropTarget.element,
+ data: dropTarget.data,
+ area: getArea(
+ pointerCoordinate,
+ edgeDistanceThreshold,
+ dropTarget.rect
+ ),
+ });
+
+ if (swappedTarget.element === dropTarget.element) {
+ break;
+ }
+
+ dropTarget.element = swappedTarget.element;
+ dropTarget.data = swappedTarget.data;
+ dropTarget.rect = swappedTarget.element.getBoundingClientRect();
+ }
- if (
- state.current.dropTarget === undefined ||
- state.current.dropTarget.element !== dropTarget.element ||
- !isSameData(state.current.dropTarget.data, dropTarget.data) ||
- !isSameRect(state.current.dropTarget.rect, dropTarget.rect)
- ) {
- state.current.dropTarget = dropTarget;
- onDropTargetChange(dropTarget);
- }
- };
+ if (
+ state.current.dropTarget === undefined ||
+ state.current.dropTarget.element !== dropTarget.element ||
+ !isSameData(state.current.dropTarget.data, dropTarget.data) ||
+ !isEqualRect(state.current.dropTarget.rect, dropTarget.rect)
+ ) {
+ state.current.dropTarget = dropTarget;
+ onDropTargetChange(dropTarget);
+ }
+ };
- return {
- handleMove(pointerCoordinate: Coordinate) {
- state.current.pointerCoordinate = pointerCoordinate;
- detectTarget();
- },
+ return {
+ handleMove(pointerCoordinate: Coordinate) {
+ state.current.pointerCoordinate = pointerCoordinate;
+ detectTarget();
+ },
- handleScroll() {
- detectTarget();
- },
+ handleScroll() {
+ detectTarget();
+ },
- handleEnd() {
- state.current.pointerCoordinate = undefined;
- state.current.dropTarget = undefined;
- },
+ handleEnd() {
+ state.current.pointerCoordinate = undefined;
+ state.current.dropTarget = undefined;
+ },
- rootRef(rootElement: HTMLElement | null) {
- state.current.root = rootElement;
- },
- };
+ rootRef(rootElement: HTMLElement | null) {
+ state.current.root = rootElement;
+ },
+ };
+ }, []);
};
type Coordinate = { x: number; y: number };