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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
useDrop hook (wip)
Roman Pominov98902564cad1
diff --git a/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx b/packages/design-system/src/components/primitives/dnd/canvas.stories.tsxindex e442ca5da0..6f058904a0 100644--- a/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx+++ b/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx@@ -1,10 +1,9 @@import { ComponentMeta } from "@storybook/react";import React, { useState, useRef } from "react";import { Box } from "../../box";-import { useDrop } from "./use-drop";+import { useDrop, type DropTarget } from "./use-drop";import { useDrag } from "./use-drag";-import { type Rect } from "./rect";-import { usePlacement, PlacementIndicator } from "./placement";+import { PlacementIndicator } from "./placement";import { useAutoScroll } from "./use-auto-scroll";const ROOT_ID = "root";@@ -155,17 +154,14 @@ export const Canvas = () => {{ id: "6", style: {}, children: [], acceptsChildren: false },]);- const [placement, setPalcement] = useState<{- index: number;- placementRect: Rect;- }>();-+ const [currentDropTarget, setCurrentDropTarget] = useState<+ DropTarget<string> | undefined+ >();const [dragItemId, setDragItemId] = useState<string>();- const dropTargetId = useRef<string>();const rootRef = useRef<HTMLElement | null>(null);- const dropTargetHandlers = useDrop<string>({+ const dropHandlers = useDrop<string>({edgeDistanceThreshold: 10,isDropTarget(element) {@@ -218,9 +214,8 @@ export const Canvas = () => {return { data: newItem.id, element };},- onDropTargetChange({ data, element }) {- dropTargetId.current = data;- placementHandlers.handleTargetChange(element as any);+ onDropTargetChange(dropTarget) {+ setCurrentDropTarget(dropTarget);},});@@ -239,17 +234,11 @@ export const Canvas = () => {autoScrollHandlers.setEnabled(true);},onMove: (poiterCoordinate) => {- dropTargetHandlers.handleMove(poiterCoordinate);+ dropHandlers.handleMove(poiterCoordinate);autoScrollHandlers.handleMove(poiterCoordinate);- placementHandlers.handleMove(poiterCoordinate);},onEnd() {- const currentDropTargetId = dropTargetId.current;- if (- placement !== undefined &&- dragItemId !== undefined &&- currentDropTargetId !== undefined- ) {+ if (dragItemId !== undefined && currentDropTarget !== undefined) {setData((current) => {const dragItem = findItem(current, dragItemId);@@ -270,13 +259,14 @@ export const Canvas = () => {children.splice(oldIndex, 1);}- if (item.id === currentDropTargetId) {+ if (item.id === currentDropTarget.data) {// 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.const newIndex =- oldIndex !== -1 && oldIndex < placement.index- ? placement.index - 1- : placement.index;+ oldIndex !== -1 &&+ oldIndex < currentDropTarget.indexWithinChildren+ ? currentDropTarget.indexWithinChildren - 1+ : currentDropTarget.indexWithinChildren;children = children.slice();children.splice(newIndex, 0, dragItem);@@ -287,18 +277,10 @@ export const Canvas = () => {});}- dropTargetHandlers.handleEnd();+ dropHandlers.handleEnd();autoScrollHandlers.setEnabled(false);- placementHandlers.handleEnd();setDragItemId(undefined);- setPalcement(undefined);- dropTargetId.current = undefined;- },- });-- const placementHandlers = usePlacement({- onPlacementChange: (event) => {- setPalcement(event);+ setCurrentDropTarget(undefined);},});@@ -318,22 +300,32 @@ export const Canvas = () => {},}}ref={(element) => {- dropTargetHandlers.rootRef(element);+ dropHandlers.rootRef(element);autoScrollHandlers.targetRef(element);useDragHandlers.rootRef(element);rootRef.current = element;}}- onScroll={() => {- dropTargetHandlers.handleScroll();- placementHandlers.handleScroll();- }}+ onScroll={dropHandlers.handleScroll}data-id={ROOT_ID}><Items data={data} dragItemId={dragItemId} /></Box>- {placement && <PlacementIndicator rect={placement.placementRect} />}+ {currentDropTarget && (+ <PlacementIndicator+ rect={tmpToLegacyPlacementRect(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/use-drop.test.ts b/packages/design-system/src/components/primitives/dnd/use-drop.test.tsindex 7ee27dcef5..47212115e9 100644--- a/packages/design-system/src/components/primitives/dnd/use-drop.test.ts+++ b/packages/design-system/src/components/primitives/dnd/use-drop.test.ts@@ -3,163 +3,57 @@ import { getPlacementBetween } from "./use-drop";const size = { width: 100, height: 100 };describe("getPlacementBetween", () => {- // [a] | [b]- test("horizontal rects", () => {- const placement = getPlacementBetween(- { top: 0, left: 0, ...size },- { top: 0, left: 200, ...size }- );- expect(placement).toEqual({- direction: "vertical",- x: 150,- y: 0,- length: 100,- });- });-- // [b] | [a]- test("horizontal rects (reversed)", () => {- const placement = getPlacementBetween(- { top: 0, left: 200, ...size },- { top: 0, left: 0, ...size }- );- expect(placement).toEqual({- direction: "vertical",- x: 150,- y: 0,- length: 100,- });- });-- // [a]- // ---- // [b]- test("vertical rects", () => {- const placement = getPlacementBetween(- { top: 0, left: 0, ...size },- { top: 200, left: 0, ...size }- );- expect(placement).toEqual({- direction: "horizontal",- x: 0,- y: 150,- length: 100,- });- });-- // [a]- // ---- // [b]- test("vertical rects (reversed)", () => {- const placement = getPlacementBetween(- { top: 200, left: 0, ...size },- { top: 0, left: 0, ...size }- );- expect(placement).toEqual({- direction: "horizontal",- x: 0,- y: 150,- length: 100,- });- });-- // [a]- // ------------ // [b]- test("diagonal, closer by Y", () => {- const placement = getPlacementBetween(- { top: 0, left: 600, ...size },- { top: 200, left: 0, ...size }- );- expect(placement).toEqual({- direction: "horizontal",- x: 0,- y: 150,- length: 700,- });- });-- // [b]- // ------------ // [a]- test("diagonal, closer by Y (reversed)", () => {- const placement = getPlacementBetween(- { top: 200, left: 0, ...size },- { top: 0, left: 600, ...size }- );- expect(placement).toEqual({- direction: "horizontal",- x: 0,- y: 150,- length: 700,- });- });-- // [a] |- // |- // |- // | [b]- test("diagonal, closer by X", () => {- const placement = getPlacementBetween(- { top: 0, left: 0, ...size },- { top: 600, left: 200, ...size }- );- expect(placement).toEqual({- direction: "vertical",- x: 150,- y: 0,- length: 700,- });- });-- // [b] |- // |- // |- // | [a]- test("diagonal, closer by X (reversed)", () => {- const placement = getPlacementBetween(- { top: 600, left: 200, ...size },- { top: 0, left: 0, ...size }- );- expect(placement).toEqual({- direction: "vertical",- x: 150,- y: 0,- length: 700,- });- });-test.each([[+ // [a] | [b]{ top: 0, left: 0 },- { top: 0, left: 0 },- ],- [- { top: 0, left: 0 },- { top: 50, left: 50 },+ { top: 0, left: 200 },+ { direction: "vertical", x: 150, y: 0, length: 100 },],+[- { top: 50, left: 50 },+ // [a]+ // ---+ // [b]{ top: 0, left: 0 },+ { top: 200, left: 0 },+ { direction: "horizontal", x: 0, y: 150, length: 100 },],+[- { top: 0, left: 50 },- { top: 50, left: 0 },+ // [a]+ // -----------+ // [b]+ { top: 0, left: 600 },+ { top: 200, left: 0 },+ { direction: "horizontal", x: 0, y: 150, length: 700 },],+[- { top: 50, left: 0 },- { top: 0, left: 50 },+ // [a] |+ // |+ // |+ // | [b]+ { top: 0, left: 0 },+ { top: 600, left: 200 },+ { direction: "vertical", x: 150, y: 0, length: 700 },],++ // overlaps ...+ [{ top: 0, left: 0 }, { top: 0, left: 0 }, undefined],+ [{ top: 0, left: 0 }, { top: 50, left: 50 }, undefined],+ [{ top: 0, left: 50 }, { top: 50, left: 0 }, undefined],[{ top: 0, left: 0, width: 200, height: 200 },{ top: 50, left: 50 },+ undefined,],- [- { top: 50, left: 50 },- { top: 0, left: 0, width: 200, height: 200 },- ],- ])("overlap %o %o", (a, b) => {- const placement = getPlacementBetween({ ...size, ...a }, { ...size, ...b });- expect(placement).toBeUndefined();+ ])("%o + %o", (a, b, placement) => {+ expect(getPlacementBetween({ ...size, ...a }, { ...size, ...b })).toEqual(+ placement+ );+ expect(getPlacementBetween({ ...size, ...b }, { ...size, ...a })).toEqual(+ placement+ );});});diff --git a/packages/design-system/src/components/primitives/dnd/use-drop.ts b/packages/design-system/src/components/primitives/dnd/use-drop.tsindex 9f26a556ad..3d19ee86f9 100644--- a/packages/design-system/src/components/primitives/dnd/use-drop.ts+++ b/packages/design-system/src/components/primitives/dnd/use-drop.ts@@ -147,6 +147,79 @@ export const getPlacementBetween = (};};+export const getPlacementNextTo = (+ parentRect: Rect,+ rect: Rect,+ side: "top" | "bottom" | "left" | "right"+): Placement => {+ const margin = 5;++ if (side === "top") {+ return {+ x: rect.left,+ y: Math.min(rect.top, Math.max(parentRect.top, rect.top - margin)),+ length: rect.width,+ direction: "horizontal",+ };+ }++ if (side === "bottom") {+ return {+ x: rect.left,+ y: Math.max(+ rect.top + rect.height,+ Math.min(parentRect.top + parentRect.height, rect.top + margin)+ ),+ length: rect.width,+ direction: "horizontal",+ };+ }++ if (side === "left") {+ return {+ x: Math.min(rect.left, Math.max(parentRect.left, rect.left - margin)),+ y: rect.top,+ length: rect.height,+ direction: "vertical",+ };+ }++ return {+ x: Math.max(+ rect.left + rect.width,+ Math.min(parentRect.left + parentRect.width, rect.left + margin)+ ),+ y: rect.top,+ length: rect.height,+ direction: "vertical",+ };+};++export const getPlacementInside = (+ parentRect: Rect,+ childrenOrientation: ChildrenOrientation+): Placement => {+ const padding = 5;++ if (childrenOrientation === "horizontal") {+ const safePadding = Math.min(parentRect.width / 2, padding);+ return {+ y: parentRect.top + safePadding,+ x: parentRect.left + safePadding,+ length: parentRect.height - safePadding * 2,+ direction: "vertical",+ };+ }++ const safePadding = Math.min(parentRect.height / 2, padding);+ return {+ y: parentRect.top + safePadding,+ x: parentRect.left + safePadding,+ length: parentRect.width - safePadding * 2,+ direction: "horizontal",+ };+};+export type DropTarget<Data> = PartialDropTarget<Data> & {rect: DOMRect;indexWithinChildren: number;@@ -220,12 +293,15 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {parent: UsableElement,parentRect: Rect,pointer: { x: number; y: number }- ) => {++ // @todo: don't return array here like that+ ): [number, ChildrenOrientation, number, number] => {const pointerRelativeToParent = pointRelativeToRect(parentRect, pointer);const childrenRects = getChildrenRects(parent, parentRect);if (childrenRects.length === 0) {- return 0;+ // @todo: still call getLocalChildrenOrientation+ return [0, "vertical", -1, 0];}const closestChildIndex = getClosestRectIndex(@@ -245,7 +321,12 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {orientation);- return closestChildIndex + adjustment;+ return [+ closestChildIndex + adjustment,+ orientation,+ closestChildIndex,+ adjustment === 0 ? closestChildIndex - 1 : closestChildIndex + 1,+ ];};const handleDropTargetChange = (@@ -258,11 +339,8 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {const rect = partialDropTarget.element.getBoundingClientRect();- const indexWithinChildren = getIndex(- partialDropTarget.element,- rect,- pointerCoordinates- );+ const [indexWithinChildren, childrenOrientation, aIndex, bIndex] =+ getIndex(partialDropTarget.element, rect, pointerCoordinates);const current = state.current.dropTarget;if (@@ -271,16 +349,35 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {current.indexWithinChildren !== indexWithinChildren ||!isEqualRect(current.rect, rect)) {+ const childrenRects = getChildrenRects(partialDropTarget.element, rect);+ const aRect = childrenRects[aIndex] as Rect | undefined;+ const bRect = childrenRects[bIndex] as Rect | undefined;++ let placement: Placement | undefined;++ if (aRect !== undefined && bRect !== undefined) {+ placement = getPlacementBetween(aRect, bRect);+ }++ if (placement === undefined && aRect !== undefined) {+ placement = getPlacementNextTo(+ rect,+ aRect,+ childrenOrientation === "horizontal"+ ? bIndex > aIndex+ ? "right"+ : "left"+ : bIndex > aIndex+ ? "bottom"+ : "top"+ );+ }+const dropTarget: DropTarget<Data> = {...partialDropTarget,rect,indexWithinChildren: indexWithinChildren,- placement: {- x: 0,- y: 0,- length: 0,- direction: "horizontal",- },+ placement: placement || getPlacementInside(rect, childrenOrientation),};state.current.dropTarget = dropTarget;latestProps.current.onDropTargetChange(dropTarget);