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.

base case works

Roman Pominov5780c3cf504f
diff --git a/apps/designer/app/designer/features/sidebar-left/lib/navigator/navigator.tsx b/apps/designer/app/designer/features/sidebar-left/lib/navigator/navigator.tsx
index 96ef4bb775..cf09350e51 100644
--- a/apps/designer/app/designer/features/sidebar-left/lib/navigator/navigator.tsx
+++ b/apps/designer/app/designer/features/sidebar-left/lib/navigator/navigator.tsx
@@ -29,6 +29,15 @@ export const Navigator = ({ publish, isClosable, onClose }: NavigatorProps) => {
payload: instance.id,
});
}}
+ onDragEnd={(payload) => {
+ publish<
+ "reparentInstance",
+ {
+ instanceId: Instance["id"];
+ dropTarget: { instanceId: Instance["id"]; position: number };
+ }
+ >({ type: "reparentInstance", payload });
+ }}
/>
</Box>
</>
diff --git a/apps/designer/app/designer/shared/tree/tree.tsx b/apps/designer/app/designer/shared/tree/tree.tsx
index 47fec15d17..f057db0330 100644
--- a/apps/designer/app/designer/shared/tree/tree.tsx
+++ b/apps/designer/app/designer/shared/tree/tree.tsx
@@ -19,6 +19,7 @@ import {
styled,
type DropTarget,
type Point,
+ PlacementIndicator,
useAutoScroll,
useDrag,
useDrop,
@@ -26,6 +27,7 @@ import {
} from "@webstudio-is/design-system";
import { TriangleRightIcon, TriangleDownIcon } from "@webstudio-is/icons";
import { findInstanceById, getInstancePath } from "~/shared/tree-utils";
+import { createPortal } from "react-dom";
const openKeyframes = keyframes({
from: { height: 0 },
@@ -168,6 +170,12 @@ type TreeProps = {
selectedInstanceId?: Instance["id"];
onSelect?: (instance: Instance) => void;
animate?: boolean;
+
+ // @todo: export a Tree component without drag and drop, to use in tree preview etc.
+ onDragEnd?: (event: {
+ instanceId: Instance["id"];
+ dropTarget: { instanceId: Instance["id"]; position: number };
+ }) => void;
};
export const Tree = ({
@@ -175,6 +183,7 @@ export const Tree = ({
selectedInstanceId,
onSelect = () => null,
animate = true,
+ onDragEnd = () => null,
}: TreeProps) => {
const selectedInstancePath = useMemo(
() =>
@@ -186,40 +195,93 @@ export const Tree = ({
const rootRef = useRef<HTMLElement | null>(null);
+ const [dragItem, setDragItem] = useState<Instance>();
+ const [dropTarget, setDropTarget] = useState<DropTarget<Instance>>();
+
+ // @todo: not sure what this should return,
+ // need to understand better when it's used
+ //
+ // maybe we should return previous dropTarget, or current dragItem's parent?
+ const getFallbackDropTarget = () => {
+ console.warn("getFallbackDropTarget");
+ return {
+ data: root,
+ element: rootRef.current as HTMLElement,
+ };
+ };
+
const dropHandlers = useDrop<Instance>({
+ // We don't want drop target to fall back to root
+ // when user moves pointer outside of the tree.
+ emulatePointerAlwaysInRootBounds: true,
+
+ placementPadding: 0,
+
elementToData: (element) => {
const id = (element as HTMLElement).dataset.dropTargetId;
const instance = id && findInstanceById(root, id);
return instance || false;
},
- // @todo: we need an ability to tell useDrop to keep previous drop target
- // because once user moves the cursor out of navigator
- // we loose the ability to meaningfully track the drop target
- //
- // OR: modify coordinates when passing to dropHandlers.handleMove()
swapDropTarget: (dropTarget) => {
console.log("swapDropTarget", dropTarget);
- if (dropTarget) {
+ if (dragItem === undefined || dropTarget === undefined) {
+ return getFallbackDropTarget();
+ }
+
+ if (dropTarget.data.id === root.id) {
return dropTarget;
}
- return { element: document.body as Element, data: root };
+ const path = getInstancePath(root, dropTarget.data.id);
+ path.reverse();
+
+ if (dropTarget.nearEdge) {
+ path.shift();
+ }
+
+ // Don't allow to drop inside drag item or any of its children
+ const dragItemIndex = path.findIndex(
+ (instance) => instance.id === dragItem.id
+ );
+ if (dragItemIndex !== -1) {
+ path.splice(0, dragItemIndex + 1);
+ }
+
+ const data = path.find((instance) =>
+ components[instance.component].canAcceptChild()
+ );
+
+ if (!data) {
+ return getFallbackDropTarget();
+ }
+
+ const element =
+ data &&
+ rootRef.current?.querySelector(`[data-drop-target-id="${data.id}"]`);
+
+ if (element == null) {
+ return getFallbackDropTarget();
+ }
+
+ return { data, element };
},
onDropTargetChange: (dropTarget) => {
console.log("onDropTargetChange", dropTarget);
+ setDropTarget(dropTarget);
},
getValidChildren: (element) => {
return Array.from(
+ // @todo: if this works as expected, we need a selector that assumes less about the DOM structure
element.querySelectorAll(":scope > div > [data-drop-target-id]")
);
},
});
- const dragHandlers = useDrag<Instance["id"]>({
+ const dragHandlers = useDrag<Instance>({
elementToData: (element) => {
const dragItemElement = element.closest("[data-drag-item-id]");
if (!(dragItemElement instanceof HTMLElement)) {
@@ -229,28 +291,33 @@ export const Tree = ({
if (id === undefined || id === root.id) {
return false;
}
- return id;
+ return findInstanceById(root, id) || false;
},
onStart: ({ data }) => {
- console.log("drag start", data);
+ setDragItem(data);
},
onMove: (point) => {
dropHandlers.handleMove(point);
},
onEnd: ({ isCanceled }) => {
- console.log("drag end", isCanceled);
+ if (dropTarget && dragItem && isCanceled === false) {
+ onDragEnd({
+ instanceId: dragItem.id,
+ dropTarget: {
+ instanceId: dropTarget.data.id,
+ position: dropTarget.indexWithinChildren,
+ },
+ });
+ }
+
+ setDragItem(undefined);
+ setDropTarget(undefined);
dropHandlers.handleEnd();
},
});
return (
- <Box
- ref={(element) => {
- rootRef.current = element;
- dragHandlers.rootRef(element);
- dropHandlers.rootRef(element);
- }}
- >
+ <>
<Node
instance={root}
selectedInstanceId={selectedInstanceId}
@@ -258,7 +325,24 @@ export const Tree = ({
onSelect={onSelect}
animate={animate}
level={0}
+ ref={(element) => {
+ rootRef.current = element;
+ dragHandlers.rootRef(element);
+ dropHandlers.rootRef(element);
+ }}
/>
- </Box>
+
+ {/* @todo: need to render an outline instead of the line when there're no children */}
+ {/* @todo: need to adjust line length according to the depth of the drop target inside the tree */}
+ {dropTarget && (
+ <PlacementIndicatorLayer placement={dropTarget.placement} />
+ )}
+ </>
);
};
+
+const PlacementIndicatorLayer = (
+ props: React.ComponentProps<typeof PlacementIndicator>
+) => {
+ return createPortal(<PlacementIndicator {...props} />, document.body);
+};
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 24c9b9178a..8f3a1e555c 100644
--- a/packages/design-system/src/components/primitives/dnd/geometry-utils.ts
+++ b/packages/design-system/src/components/primitives/dnd/geometry-utils.ts
@@ -106,7 +106,8 @@ export const getPlacementNextTo = (
parentRect: Rect,
rect: Rect | undefined,
childrenOrientation: ChildrenOrientation,
- direction: "forward" | "backward"
+ direction: "forward" | "backward",
+ padding = 5
): Placement | undefined => {
if (rect === undefined) {
return undefined;
@@ -126,7 +127,7 @@ export const getPlacementNextTo = (
: "top";
const getMargin = (distnaceToParentEdge: number) =>
- Math.min(10, Math.max(0, distnaceToParentEdge)) / 2;
+ Math.min(padding * 2, Math.max(0, distnaceToParentEdge)) / 2;
if (side === "top") {
return {
@@ -171,10 +172,9 @@ export const getPlacementNextTo = (
export const getPlacementInside = (
parentRect: Rect,
- childrenOrientation: ChildrenOrientation
+ childrenOrientation: ChildrenOrientation,
+ padding = 5
): Placement => {
- const padding = 5;
-
if (childrenOrientation.type === "horizontal") {
const safePadding = Math.min(parentRect.width / 2, padding);
return {
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 d3fd63a736..a85e91dc09 100644
--- a/packages/design-system/src/components/primitives/dnd/use-drop.ts
+++ b/packages/design-system/src/components/primitives/dnd/use-drop.ts
@@ -49,6 +49,23 @@ export type UseDropProps<Data> = {
// Allows you to customize children
// that will be used to determine placement and indexWithinChildren
getValidChildren?: (parent: Element) => Element[] | HTMLCollection;
+
+ // If set to true, the target selection will work as if
+ // the pointer is always inside the root element's bounds.
+ //
+ // For example:
+ // ___________
+ // | |
+ // | *| * - real pointer
+ // | ^------- emulated pointer
+ // | |
+ // |___________|
+ //
+ // The pointer will be always at least 2px away from any edge of the root.
+ emulatePointerAlwaysInRootBounds?: boolean;
+
+ // Distance from an edge when placement is put next to an element edge
+ placementPadding?: number;
};
export type UseDropHandlers = {
@@ -107,6 +124,8 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
const childrenRects = getChildrenRectsMemoized(partialDropTarget.element);
+ console.log({ parentRect, pointerRelativeToParent, childrenRects });
+
const closestChildIndex =
childrenRects.length === 0
? 0
@@ -156,10 +175,15 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
parentRect,
closestChildRect,
childrenOrientation,
- indexAdjustment > 0 ? "forward" : "backward"
+ indexAdjustment > 0 ? "forward" : "backward",
+ latestProps.current.placementPadding
)
) ||
- getPlacementInside(parentRect, childrenOrientation);
+ getPlacementInside(
+ parentRect,
+ childrenOrientation,
+ latestProps.current.placementPadding
+ );
const dropTarget: DropTarget<Data> = {
...partialDropTarget,
@@ -218,6 +242,8 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
isNewIsNearEdge === false &&
state.current.dropTarget
) {
+ console.log("skipping swap", 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
@@ -248,7 +274,17 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
return {
handleMove(pointerCoordinates) {
- state.current.pointerCoordinates = pointerCoordinates;
+ if (latestProps.current.emulatePointerAlwaysInRootBounds === true) {
+ const rect = (rootRef.current as Element).getBoundingClientRect();
+ const padding = 2;
+ const { x, y } = pointerCoordinates;
+ state.current.pointerCoordinates = {
+ x: Math.max(rect.left + padding, Math.min(rect.right - padding, x)),
+ y: Math.max(rect.top + padding, Math.min(rect.bottom - padding, y)),
+ };
+ } else {
+ state.current.pointerCoordinates = pointerCoordinates;
+ }
detectTarget();
},