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.

switch to the new hook & bugfixes

Roman Pominov36f8daab0273
diff --git a/apps/designer/app/canvas/shared/use-drag-drop.ts b/apps/designer/app/canvas/shared/use-drag-drop.ts
index 54cbf9ea09..176f0cb034 100644
--- a/apps/designer/app/canvas/shared/use-drag-drop.ts
+++ b/apps/designer/app/canvas/shared/use-drag-drop.ts
@@ -7,9 +7,8 @@ import { findInstanceById, getInstancePath } from "~/shared/tree-utils";
import {
type DropTarget,
useAutoScroll,
- usePlacement,
useDrag,
- useDropTarget,
+ useDrop,
} from "@webstudio-is/design-system";
import {
publish,
@@ -18,11 +17,9 @@ import {
components as primitives,
} from "@webstudio-is/react-sdk";
-type Rect = Pick<DOMRect, "top" | "left" | "width" | "height">;
-
export type DropTargetChangePayload = {
- rect: Rect;
- placementRect: Rect;
+ rect: DropTarget<null>["rect"];
+ placement: DropTarget<null>["placement"];
position: number;
instanceId: Instance["id"];
instanceComponent: Instance["component"];
@@ -39,7 +36,6 @@ export type DragMovePayload = { canvasCoordinates: { x: number; y: number } };
const initialState = {
dropTarget: undefined as DropTarget<Instance> | undefined,
- placement: undefined as { index: number; placementRect: Rect } | undefined,
dragItem: undefined as Instance | undefined,
};
@@ -49,33 +45,20 @@ export const useDragAndDrop = () => {
const state = useRef({ ...initialState });
- const publishDropTargetChange = () => {
- const { dropTarget, placement } = state.current;
- if (dropTarget === undefined || placement === undefined) {
- return;
- }
- publish<"dropTargetChange", DropTargetChangePayload>({
- type: "dropTargetChange",
- payload: {
- rect: dropTarget.rect,
- placementRect: placement.placementRect,
- position: placement.index,
- instanceId: dropTarget.data.id,
- instanceComponent: dropTarget.data.component,
- },
- });
- };
-
const autoScrollHandlers = useAutoScroll({ fullScreen: true });
- const placementHandlers = usePlacement({
- onPlacementChange: (placement) => {
- state.current.placement = placement;
- publishDropTargetChange();
- },
- });
+ const getDefaultDropTarget = () => {
+ const element = rootInstance && document.getElementById(rootInstance.id);
+
+ // Should never happen
+ if (!element || !rootInstance) {
+ throw new Error("Could not find root instance element");
+ }
+
+ return { element, data: rootInstance };
+ };
- const dropTargetHandlers = useDropTarget<Instance>({
+ const dropHandlers = useDrop<Instance>({
isDropTarget(element) {
return (
(rootInstance !== undefined &&
@@ -85,25 +68,22 @@ export const useDragAndDrop = () => {
);
},
- isSameData(a, b) {
- return a.id === b.id;
- },
-
// This must be fast, it can be called multiple times per pointer move
swapDropTarget(dropTarget) {
const { dragItem } = state.current;
- if (
- dragItem === undefined ||
- rootInstance === undefined ||
- dropTarget.data.id === rootInstance.id
- ) {
+
+ if (!dropTarget || dragItem === undefined || rootInstance === undefined) {
+ return getDefaultDropTarget();
+ }
+
+ if (dropTarget.data.id === rootInstance.id) {
return dropTarget;
}
const path = getInstancePath(rootInstance, dropTarget.data.id);
path.reverse();
- if (dropTarget.area !== "center") {
+ if (dropTarget.nearEdge) {
path.shift();
}
@@ -113,28 +93,39 @@ export const useDragAndDrop = () => {
path.splice(0, dragItemIndex + 1);
}
- const data =
- path.find((instance) =>
- primitives[instance.component].canAcceptChild()
- ) || rootInstance;
+ const data = path.find((instance) =>
+ primitives[instance.component].canAcceptChild()
+ );
- const element = document.getElementById(data.id);
+ if (!data) {
+ return getDefaultDropTarget();
+ }
- if (element == null) {
+ if (data.id === dropTarget.data.id) {
return dropTarget;
}
+ const element = data && document.getElementById(data.id);
+
+ if (!element) {
+ return getDefaultDropTarget();
+ }
+
return { data, element };
},
onDropTargetChange(dropTarget) {
state.current.dropTarget = dropTarget;
- placementHandlers.handleTargetChange(dropTarget.element);
-
- // @todo: The line above may or may not fire publishDropTargetChange as well.
- // So we're firing duplicate events.
- // One more reason to merge useDropTarget and usePlacement.
- publishDropTargetChange();
+ publish<"dropTargetChange", DropTargetChangePayload>({
+ type: "dropTargetChange",
+ payload: {
+ rect: dropTarget.rect,
+ placement: dropTarget.placement,
+ position: dropTarget.indexWithinChildren,
+ instanceId: dropTarget.data.id,
+ instanceComponent: dropTarget.data.component,
+ },
+ });
},
});
@@ -176,23 +167,21 @@ export const useDragAndDrop = () => {
});
},
onMove: (poiterCoordinate) => {
- dropTargetHandlers.handleMove(poiterCoordinate);
+ dropHandlers.handleMove(poiterCoordinate);
autoScrollHandlers.handleMove(poiterCoordinate);
- placementHandlers.handleMove(poiterCoordinate);
},
onEnd() {
- dropTargetHandlers.handleEnd();
+ dropHandlers.handleEnd();
autoScrollHandlers.setEnabled(false);
- placementHandlers.handleEnd();
publish<"dragEnd", DragEndPayload>({
type: "dragEnd",
payload: { origin: "canvas" },
});
- const { dropTarget, placement, dragItem } = state.current;
+ const { dropTarget, dragItem } = state.current;
- if (dropTarget && placement && dragItem) {
+ if (dropTarget && dragItem) {
publish<
"reparentInstance",
{
@@ -205,7 +194,7 @@ export const useDragAndDrop = () => {
instanceId: dragItem.id,
dropTarget: {
instanceId: dropTarget.data.id,
- position: placement.index,
+ position: dropTarget.indexWithinChildren,
},
},
});
@@ -220,26 +209,16 @@ export const useDragAndDrop = () => {
// We prefer useLayoutEffect over useEffect
// because it's closer in the life cycle to when React noramlly calls the "ref" callbacks.
useLayoutEffect(() => {
- const handleScroll = () => {
- dropTargetHandlers.handleScroll();
- placementHandlers.handleScroll();
- };
-
- dropTargetHandlers.rootRef(document.body);
+ dropHandlers.rootRef(document.body);
useDragHandlers.rootRef(document.body);
- window.addEventListener("scroll", handleScroll);
+ window.addEventListener("scroll", dropHandlers.handleScroll);
return () => {
- dropTargetHandlers.rootRef(null);
+ dropHandlers.rootRef(null);
useDragHandlers.rootRef(null);
- window.removeEventListener("scroll", handleScroll);
+ window.removeEventListener("scroll", dropHandlers.handleScroll);
};
- }, [
- useDragHandlers,
- dropTargetHandlers,
- placementHandlers,
- autoScrollHandlers,
- ]);
+ }, [useDragHandlers, dropHandlers, autoScrollHandlers]);
// Handle drag from the panel
// ================================================================
@@ -257,24 +236,19 @@ export const useDragAndDrop = () => {
useSubscribe<"dragMove", DragMovePayload>(
"dragMove",
({ canvasCoordinates }) => {
- // @todo: This will only produce and update a drop target if the mouse is over the canvas.
- // We should figure out a way to default to the root instance as a drop target when we're not over the canvas.
- dropTargetHandlers.handleMove(canvasCoordinates);
-
+ dropHandlers.handleMove(canvasCoordinates);
autoScrollHandlers.handleMove(canvasCoordinates);
- placementHandlers.handleMove(canvasCoordinates);
}
);
useSubscribe<"dragEnd", DragEndPayload>("dragEnd", ({ origin }) => {
if (origin === "panel") {
- dropTargetHandlers.handleEnd();
+ dropHandlers.handleEnd();
autoScrollHandlers.setEnabled(false);
- placementHandlers.handleEnd();
- const { dropTarget, placement, dragItem } = state.current;
+ const { dropTarget, dragItem } = state.current;
- if (dropTarget && placement && dragItem) {
+ if (dropTarget && dragItem) {
publish<
"insertInstance",
{
@@ -287,7 +261,7 @@ export const useDragAndDrop = () => {
instance: dragItem,
dropTarget: {
instanceId: dropTarget.data.id,
- position: placement.index,
+ position: dropTarget.indexWithinChildren,
},
},
});
diff --git a/apps/designer/app/designer/features/workspace/canvas-tools/canvas-tools.tsx b/apps/designer/app/designer/features/workspace/canvas-tools/canvas-tools.tsx
index 23671a27da..bf34ceaebf 100644
--- a/apps/designer/app/designer/features/workspace/canvas-tools/canvas-tools.tsx
+++ b/apps/designer/app/designer/features/workspace/canvas-tools/canvas-tools.tsx
@@ -50,7 +50,7 @@ export const CanvasTools = ({ publish }: CanvasToolsProps) => {
return (
<Box css={toolsStyle}>
<DropTargetOutline dropTarget={dragAndDropState.dropTarget} />
- <PlacementIndicator rect={dragAndDropState.dropTarget.placementRect} />
+ <PlacementIndicator placement={dragAndDropState.dropTarget.placement} />
</Box>
);
}
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 28ea0e4ed7..1f010225eb 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,7 @@ import React, { useState, useRef } from "react";
import { Box } from "../../box";
import { useDrop, type DropTarget } from "./use-drop";
import { useDrag } from "./use-drag";
-import { PlacementIndicator } from "./placement";
+import { PlacementIndicator } from "./placement-indicator";
import { useAutoScroll } from "./use-auto-scroll";
const ROOT_ID = "root";
@@ -344,21 +344,10 @@ export const Canvas = () => {
</Box>
</Box>
{currentDropTarget && (
- <PlacementIndicator
- rect={tmpToLegacyPlacementRect(currentDropTarget.placement)}
- />
+ <PlacementIndicator placement={currentDropTarget.placement} />
)}
</>
);
};
-const tmpToLegacyPlacementRect = (placement: DropTarget<null>["placement"]) => {
- return {
- top: placement.y,
- left: placement.x,
- width: placement.direction === "horizontal" ? placement.length : 0,
- height: placement.direction === "vertical" ? placement.length : 0,
- };
-};
-
export default {} as ComponentMeta<typeof Canvas>;
diff --git a/packages/design-system/src/components/primitives/dnd/geometry-utils.ts b/packages/design-system/src/components/primitives/dnd/geometry-utils.ts
index 0d947858d2..b1445a2d3d 100644
--- a/packages/design-system/src/components/primitives/dnd/geometry-utils.ts
+++ b/packages/design-system/src/components/primitives/dnd/geometry-utils.ts
@@ -115,7 +115,7 @@ export const getPlacementNextTo = (
x: rect.left,
y: Math.max(
rect.top + rect.height,
- Math.min(parentRect.height, rect.top + margin)
+ Math.min(parentRect.height, rect.top + rect.height + margin)
),
length: rect.width,
direction: "horizontal",
@@ -134,7 +134,7 @@ export const getPlacementNextTo = (
return {
x: Math.max(
rect.left + rect.width,
- Math.min(parentRect.width, rect.left + margin)
+ Math.min(parentRect.width, rect.left + rect.width + margin)
),
y: rect.top,
length: rect.height,
diff --git a/packages/design-system/src/components/primitives/dnd/index.ts b/packages/design-system/src/components/primitives/dnd/index.ts
index 357d77b756..e567a425b6 100644
--- a/packages/design-system/src/components/primitives/dnd/index.ts
+++ b/packages/design-system/src/components/primitives/dnd/index.ts
@@ -1,4 +1,4 @@
-export * from "./placement";
export * from "./use-drag";
-export * from "./use-drop-target";
+export * from "./use-drop";
export * from "./use-auto-scroll";
+export * from "./placement-indicator";
diff --git a/packages/design-system/src/components/primitives/dnd/placement-indicator.tsx b/packages/design-system/src/components/primitives/dnd/placement-indicator.tsx
new file mode 100644
index 0000000000..edcaf8db4c
--- /dev/null
+++ b/packages/design-system/src/components/primitives/dnd/placement-indicator.tsx
@@ -0,0 +1,20 @@
+import { Box } from "../../box";
+import { type Placement } from "./geometry-utils";
+
+const placementStyle = {
+ boxSizing: "content-box",
+ position: "absolute",
+ background: "$blue9",
+ pointerEvents: "none",
+};
+
+export const PlacementIndicator = ({ placement }: { placement: Placement }) => {
+ const style = {
+ top: placement.y - (placement.direction === "horizontal" ? 1 : 0),
+ left: placement.x - (placement.direction === "vertical" ? 1 : 0),
+ width: placement.direction === "horizontal" ? placement.length : 2,
+ height: placement.direction === "vertical" ? placement.length : 2,
+ };
+
+ return <Box style={style} css={placementStyle} />;
+};
diff --git a/packages/design-system/src/components/primitives/dnd/placement.tsx b/packages/design-system/src/components/primitives/dnd/placement.tsx
deleted file mode 100644
index bdbd568e96..0000000000
--- a/packages/design-system/src/components/primitives/dnd/placement.tsx
+++ /dev/null
@@ -1,218 +0,0 @@
-import { useRef, useMemo } from "react";
-import { Box } from "../../box";
-import { type Rect, getClosestRectIndex, isEqualRect } from "./geometry-utils";
-
-let probeCache: undefined | HTMLElement;
-const getProbe = () => {
- if (probeCache === undefined) {
- probeCache = document.createElement("div");
- }
- return probeCache;
-};
-
-/**
- * We place a div at the position where future drop will happen.
- * We learn if the indicator will render vertically or horizontally as well as its width/heigh.
- */
-const getPlacement = ({
- target,
- index = 0,
-}: {
- target: HTMLElement;
- index?: number;
-}) => {
- const probe = getProbe();
- const { children } = target;
- if (index > children.length - 1) {
- target.appendChild(probe);
- } else {
- target.insertBefore(probe, children[index]);
- }
- const rect = probe.getBoundingClientRect();
- target.removeChild(probe);
- return rect;
-};
-
-type UsePlacementProps = {
- onPlacementChange: (event: { index: number; placementRect: Rect }) => void;
-};
-
-type Handlers = {
- handleEnd: () => void;
- handleMove: (pointerPoint: { x: number; y: number }) => void;
- handleScroll: () => void;
- handleTargetChange: (target: HTMLElement) => void;
-};
-
-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 { x: number; y: number } | undefined,
- index: undefined as number | undefined,
- placementRext: undefined as Rect | undefined,
- });
-
- // We want to return 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;
- }
-
- const result: Rect[] = [];
-
- for (const child of parent.children) {
- 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: { x: number; y: number }
- ) => {
- if (parent.children.length === 0) {
- return 0;
- }
-
- const childrenRects = getChildrenRects(parent, parentRect);
-
- const pointerAdjusted = {
- x: pointerPoint.x - parentRect.left,
- y: pointerPoint.y - parentRect.top,
- };
-
- const closestRectIndex = getClosestRectIndex(
- childrenRects,
- pointerAdjusted
- );
- const closestRect = childrenRects[closestRectIndex];
-
- const isOrientationVertical =
- childrenRects.length < 2 ||
- childrenRects[0].left === childrenRects[1].left;
-
- if (isOrientationVertical) {
- const middleY = closestRect.top + closestRect.height / 2;
- return pointerAdjusted.y < middleY
- ? closestRectIndex
- : closestRectIndex + 1;
- } else {
- const middleX = closestRect.left + closestRect.width / 2;
- return pointerAdjusted.x < middleX
- ? closestRectIndex
- : closestRectIndex + 1;
- }
- };
-
- 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) {
- 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 }) => {
- if (rect === undefined) {
- return null;
- }
-
- const style = {
- top: rect.top - 1,
- left: rect.left - 1,
- width: rect.width,
- height: rect.height,
- };
-
- return (
- <Box
- style={style}
- css={{
- boxSizing: "content-box",
- position: "absolute",
-
- // @todo: this makes the line 2px longer that it should be.
- // need to render it differently somehow.
- border: "1px solid $blue9",
- pointerEvents: "none",
- }}
- />
- );
-};
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 2a7a180815..333bbc4ccd 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
@@ -1,11 +1,10 @@
import { ComponentMeta } from "@storybook/react";
-import { useState } from "react";
+import { useState, useRef } from "react";
import { Box } from "../../box";
import { styled } from "../../../stitches.config";
-import { useDropTarget } from "./use-drop-target";
+import { useDrop, type DropTarget } from "./use-drop";
import { useDrag } from "./use-drag";
-import { type Rect } from "./geometry-utils";
-import { usePlacement, PlacementIndicator } from "./placement";
+import { PlacementIndicator } from "./placement-indicator";
import { useAutoScroll } from "./use-auto-scroll";
type ItemData = { id: string; text: string };
@@ -64,19 +63,25 @@ export const SortableList = ({
{ id: "17", text: "Eighteenth" },
] as ItemData[]);
- const [placement, setPalcement] = useState<{
- index: number;
- placementRect: Rect;
- }>();
-
+ const [dropTarget, setDropTarget] = useState<DropTarget<true>>();
const [dragItemId, setDragItemId] = useState<string>();
+ const rootRef = useRef<HTMLUListElement | null>(null);
- const dropTargetHandlers = useDropTarget<true>({
- isDropTarget(element: HTMLElement) {
+ const useDropHandlers = useDrop<true>({
+ isDropTarget(element) {
return element instanceof HTMLUListElement;
},
- onDropTargetChange(event) {
- placementHandlers.handleTargetChange(event.element);
+ swapDropTarget(dropTarget) {
+ if (!dropTarget) {
+ if (rootRef.current === null) {
+ throw new Error("should not happen");
+ }
+ return { data: true, element: rootRef.current };
+ }
+ return dropTarget;
+ },
+ onDropTargetChange(dropTarget) {
+ setDropTarget(dropTarget);
},
});
@@ -91,15 +96,14 @@ export const SortableList = ({
autoScrollHandlers.setEnabled(true);
},
onMove: (poiterCoordinate) => {
- dropTargetHandlers.handleMove(poiterCoordinate);
+ useDropHandlers.handleMove(poiterCoordinate);
autoScrollHandlers.handleMove(poiterCoordinate);
- placementHandlers.handleMove(poiterCoordinate);
},
onEnd() {
- if (placement !== undefined && dragItemId !== undefined) {
+ if (dropTarget !== undefined && dragItemId !== undefined) {
const oldIndex = data.findIndex((item) => item.id === dragItemId);
if (oldIndex !== -1) {
- let newIndex = placement.index;
+ let newIndex = dropTarget.indexWithinChildren;
// placement.index does not take into account the fact that the drag item will be removed.
// we need to do this to account for it.
@@ -116,17 +120,10 @@ export const SortableList = ({
}
}
- dropTargetHandlers.handleEnd();
+ useDropHandlers.handleEnd();
autoScrollHandlers.setEnabled(false);
- placementHandlers.handleEnd();
setDragItemId(undefined);
- setPalcement(undefined);
- },
- });
-
- const placementHandlers = usePlacement({
- onPlacementChange: (event) => {
- setPalcement(event);
+ setDropTarget(undefined);
},
});
@@ -144,15 +141,13 @@ export const SortableList = ({
touchAction: "none",
}}
ref={autoScrollHandlers.targetRef}
- onScroll={() => {
- dropTargetHandlers.handleScroll();
- placementHandlers.handleScroll();
- }}
+ onScroll={useDropHandlers.handleScroll}
>
<List
ref={(element) => {
- dropTargetHandlers.rootRef(element);
+ useDropHandlers.rootRef(element);
useDragHandlers.rootRef(element);
+ rootRef.current = element;
}}
css={{
li: { cursor: dragItemId === undefined ? "grab" : "default" },
@@ -170,7 +165,7 @@ export const SortableList = ({
))}
</List>
</Box>
- {placement && <PlacementIndicator rect={placement.placementRect} />}
+ {dropTarget && <PlacementIndicator placement={dropTarget.placement} />}
</>
);
};
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
deleted file mode 100644
index a4d4511a1e..0000000000
--- a/packages/design-system/src/components/primitives/dnd/use-drop-target.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-import { useRef, useMemo } from "react";
-import { isEqualRect } from "./geometry-utils";
-
-export type Area = "top" | "right" | "bottom" | "left" | "center";
-
-export type DropTarget<Data> = {
- data: Data;
- element: HTMLElement;
- rect: DOMRect;
-};
-
-// 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.
-export type UseDropTargetProps<Data> = {
- // To check that the element can qualify as a target
- isDropTarget: (element: HTMLElement) => Data | false;
-
- // Given the potential target that has passed isDropTarget check,
- // and the position of the pointer on the target,
- // you can swap to another target
- swapDropTarget?: (args: { element: HTMLElement; data: Data; area: Area }) => {
- element: HTMLElement;
- data: Data;
- };
-
- onDropTargetChange: (dropTarget: DropTarget<Data>) => void;
- edgeDistanceThreshold?: number;
-
- // @todo: not sure we should do any data comparisons here.
- // On the contrary, we may want to rely on the assumption
- // that the data for the same element is always the same (for caching)
- isSameData?: (data1: Data, data2: Data) => boolean;
-};
-
-export type UseDropTargetHandlers = {
- handleMove: (pointerCoordinate: Coordinate) => void;
- handleScroll: () => void;
- handleEnd: () => void;
- rootRef: (element: HTMLElement | null) => void;
-};
-
-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,
- });
-
- // We want to return 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 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.
-
- 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) ||
- !isEqualRect(state.current.dropTarget.rect, dropTarget.rect)
- ) {
- state.current.dropTarget = dropTarget;
- onDropTargetChange(dropTarget);
- }
- };
-
- return {
- handleMove(pointerCoordinate: Coordinate) {
- state.current.pointerCoordinate = pointerCoordinate;
- detectTarget();
- },
-
- handleScroll() {
- detectTarget();
- },
-
- handleEnd() {
- state.current.pointerCoordinate = undefined;
- state.current.dropTarget = undefined;
- },
-
- rootRef(rootElement: HTMLElement | null) {
- state.current.root = rootElement;
- },
- };
- }, []);
-};
-
-type Coordinate = { x: number; y: number };
-
-const elementFromPoint = (coordinate: Coordinate): HTMLElement | undefined => {
- const element = document.elementFromPoint(coordinate.x, coordinate.y);
- if (element instanceof HTMLElement) return element;
-};
-
-// @todo: it seems we only care about whether the area is center or on an edge.
-// Knowing which edge doesn't help much.
-const getArea = (
- pointerCoordinate: Coordinate,
- edgeDistanceThreshold: number,
- targetRect?: DOMRect
-) => {
- let area: Area = "center";
- if (targetRect === undefined) return area;
- // We are at the edge and this means user wants to insert after that element into its parent
- if (pointerCoordinate.y - targetRect.top <= edgeDistanceThreshold)
- area = "top";
- if (targetRect.bottom - pointerCoordinate.y <= edgeDistanceThreshold)
- area = "bottom";
- if (pointerCoordinate.x - targetRect.left <= edgeDistanceThreshold)
- area = "left";
- if (targetRect.right - pointerCoordinate.x <= edgeDistanceThreshold)
- area = "right";
- return area;
-};
-
-// @todo: maybe rather than climbing the DOM tree,
-// we should use document.elementsFromPoint() array?
-// Might work better with absolute positioned elements.
-const findClosestDropTarget = <Data>({
- root,
- target,
- isDropTarget,
-}: {
- root: HTMLElement;
- target: HTMLElement;
- isDropTarget: (target: HTMLElement) => Data | false;
-}) => {
- let currentTarget: HTMLElement | null = target;
- while (currentTarget !== null) {
- const data = isDropTarget(currentTarget);
- if (data !== false) {
- return { data: data, element: currentTarget };
- }
-
- // @todo: what makes us think that document.elementFromPoint() is inside the root in the first place?
- if (currentTarget === root) {
- break;
- }
-
- currentTarget = currentTarget.parentElement;
- }
-};
diff --git a/packages/design-system/src/components/primitives/dnd/use-drop.ts b/packages/design-system/src/components/primitives/dnd/use-drop.ts
index 509a12fbf6..25a2931d7f 100644
--- a/packages/design-system/src/components/primitives/dnd/use-drop.ts
+++ b/packages/design-system/src/components/primitives/dnd/use-drop.ts
@@ -96,7 +96,6 @@ export type UseDropHandlers = {
const getInitialState = <Data>() => {
return {
- root: undefined as UsableElement | undefined,
pointerCoordinates: undefined as { x: number; y: number } | undefined,
dropTarget: undefined as DropTarget<Data> | undefined,
childrenRectsCache: new WeakMap<UsableElement, Rect[]>(),
@@ -112,6 +111,7 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
const latestProps = useRef<UseDropProps<Data>>(props);
latestProps.current = props;
+ const rootRef = useRef<UsableElement>();
const state = useRef(getInitialState<Data>());
// We want to return a stable object to avoid re-renders when it's a dependency
@@ -234,7 +234,8 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
swapDropTarget,
} = latestProps.current;
- const { pointerCoordinates, root } = state.current;
+ const { pointerCoordinates } = state.current;
+ const root = rootRef.current;
// @todo: Cache this?
// Not expensive by itself, but it may call isDropTarget multiple times.
@@ -253,6 +254,7 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
isDropTarget,
});
+ // To avoid calling swapDropTarget unnecessarily on every pointermove
const isNewCandidate =
candidate?.element !== state.current.lastCandidateElement;
state.current.lastCandidateElement = candidate?.element;
@@ -267,9 +269,11 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
const isNewIsNearEdge =
candidateIsNearEdge !== state.current.lastCandidateIsNearEdge;
state.current.lastCandidateIsNearEdge = candidateIsNearEdge;
-
- // to avoid calling swapDropTarget unnecessarily on every pointermove
- if (!isNewCandidate && !isNewIsNearEdge) {
+ if (!isNewCandidate && !isNewIsNearEdge && state.current.dropTarget) {
+ // Still need to call setDropTarget to update rect and/or placement.
+ // Because indexWithinChildren might have changed,
+ // or parent coordinates might have moved in case of a scroll
+ setDropTarget(state.current.dropTarget);
return;
}
@@ -298,6 +302,7 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
return {
handleMove(pointerCoordinates) {
+ // console.log("handleMove", pointerCoordinates);
state.current.pointerCoordinates = pointerCoordinates;
detectTarget();
},
@@ -311,7 +316,7 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
},
rootRef(rootElement) {
- state.current.root = toUseableElement(rootElement);
+ rootRef.current = toUseableElement(rootElement);
},
};
}, []);