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 builder to separate placement indicator computing (#1269)

Bogdan Chadkin24406491d108
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/use-sortable.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/use-sortable.tsx
index 516b641bda..346043602a 100644
--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/use-sortable.tsx
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/use-sortable.tsx
@@ -1,6 +1,8 @@
import { useState, useRef } from "react";
import {
+ type Placement,
PlacementIndicator,
+ computeIndicatorPlacement,
useDrag,
useDragCursor,
useDrop,
@@ -20,6 +22,9 @@ export const useSortable = <Item extends { id: string }>({
onSort,
}: UseSortable<Item>) => {
const [dropTarget, setDropTarget] = useState<DropTarget<true>>();
+ const [placementIndicator, setPlacementIndicator] = useState<
+ undefined | Placement
+ >();
const [dragItemId, setDragItemId] = useState<string>();
const rootRef = useRef<HTMLDivElement | null>(null);
@@ -39,6 +44,12 @@ export const useSortable = <Item extends { id: string }>({
},
onDropTargetChange(dropTarget) {
setDropTarget(dropTarget);
+ setPlacementIndicator(
+ computeIndicatorPlacement({
+ placement: dropTarget.placement,
+ element: dropTarget.element,
+ })
+ );
},
});
@@ -67,6 +78,7 @@ export const useSortable = <Item extends { id: string }>({
useDropHandlers.handleEnd({ isCanceled });
setDragItemId(undefined);
setDropTarget(undefined);
+ setPlacementIndicator(undefined);
if (isCanceled || dropTarget === undefined || dragItemId === undefined) {
return;
@@ -89,8 +101,8 @@ export const useSortable = <Item extends { id: string }>({
},
});
- const placementIndicator = dropTarget ? (
- <PlacementIndicator placement={dropTarget.placement} />
+ const placementIndicatorElement = placementIndicator ? (
+ <PlacementIndicator placement={placementIndicator} />
) : undefined;
const sortableRefCallback = (element: HTMLDivElement | null) => {
@@ -102,6 +114,6 @@ export const useSortable = <Item extends { id: string }>({
return {
sortableRefCallback,
dragItemId,
- placementIndicator,
+ placementIndicator: placementIndicatorElement,
};
};
diff --git a/apps/builder/app/builder/features/style-panel/style-source/use-sortable.tsx b/apps/builder/app/builder/features/style-panel/style-source/use-sortable.tsx
index 3b48912160..a77a7f4a7b 100644
--- a/apps/builder/app/builder/features/style-panel/style-source/use-sortable.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-source/use-sortable.tsx
@@ -1,10 +1,12 @@
import { useState, useRef } from "react";
import {
+ type Placement,
PlacementIndicator,
useDrag,
useDragCursor,
useDrop,
type DropTarget,
+ computeIndicatorPlacement,
} from "@webstudio-is/design-system";
type UseSortable<Item> = {
@@ -15,11 +17,23 @@ type UseSortable<Item> = {
const getItemId = (element: Element) =>
element instanceof HTMLElement ? element.dataset?.id : undefined;
+const sharedDropOptions = {
+ getValidChildren(parent: Element) {
+ return [...parent.children].filter(
+ (child) => getItemId(child) !== undefined
+ );
+ },
+ childrenOrientation: { type: "horizontal", reverse: false },
+} as const;
+
export const useSortable = <Item extends { id: string }>({
items,
onSort,
}: UseSortable<Item>) => {
const [dropTarget, setDropTarget] = useState<DropTarget<true>>();
+ const [placementIndicator, setPlacementIndicator] = useState<
+ undefined | Placement
+ >();
const [dragItemId, setDragItemId] = useState<string>();
const rootRef = useRef<HTMLDivElement | null>(null);
@@ -28,6 +42,7 @@ export const useSortable = <Item extends { id: string }>({
// drop target is always root
// we need useDrop only for dropTarget.placement & dropTarget.indexWithinChildren
const useDropHandlers = useDrop<true>({
+ ...sharedDropOptions,
elementToData() {
return true;
},
@@ -39,13 +54,14 @@ export const useSortable = <Item extends { id: string }>({
},
onDropTargetChange(dropTarget) {
setDropTarget(dropTarget);
- },
- getValidChildren(parent) {
- return [...parent.children].filter(
- (child) => getItemId(child) !== undefined
+ setPlacementIndicator(
+ computeIndicatorPlacement({
+ ...sharedDropOptions,
+ placement: dropTarget.placement,
+ element: dropTarget.element,
+ })
);
},
- childrenOrientation: { type: "horizontal", reverse: false },
});
const useDragHandlers = useDrag<string>({
@@ -98,8 +114,8 @@ export const useSortable = <Item extends { id: string }>({
},
});
- const placementIndicator = dropTarget ? (
- <PlacementIndicator placement={dropTarget.placement} />
+ const placementIndicatorElement = placementIndicator ? (
+ <PlacementIndicator placement={placementIndicator} />
) : undefined;
const sortableRefCallback = (element: HTMLDivElement | null) => {
@@ -111,6 +127,6 @@ export const useSortable = <Item extends { id: string }>({
return {
sortableRefCallback,
dragItemId,
- placementIndicator,
+ placementIndicator: placementIndicatorElement,
};
};
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx
index 7dd99d5179..093ed636b9 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx
@@ -52,7 +52,9 @@ export const CanvasTools = ({ publish }: CanvasToolsProps) => {
return (
<Box css={toolsStyle}>
<DropTargetOutline dropTarget={dragAndDropState.dropTarget} />
- <PlacementIndicator placement={dragAndDropState.dropTarget.placement} />
+ {dragAndDropState.placementIndicator !== undefined && (
+ <PlacementIndicator placement={dragAndDropState.placementIndicator} />
+ )}
</Box>
);
}
diff --git a/apps/builder/app/canvas/shared/use-drag-drop.ts b/apps/builder/app/canvas/shared/use-drag-drop.ts
index e62cfe8e96..b642dd7062 100644
--- a/apps/builder/app/canvas/shared/use-drag-drop.ts
+++ b/apps/builder/app/canvas/shared/use-drag-drop.ts
@@ -3,9 +3,11 @@ import { useStore } from "@nanostores/react";
import {
type DropTarget,
type Point,
+ type Placement,
useAutoScroll,
useDrag,
useDrop,
+ computeIndicatorPlacement,
} from "@webstudio-is/design-system";
import {
type Instance,
@@ -38,6 +40,7 @@ declare module "~/shared/pubsub" {
dragMove: DragMovePayload;
dragStart: DragStartPayload;
dropTargetChange: DropTargetChangePayload;
+ placementIndicatorChange: Placement;
}
}
@@ -68,6 +71,14 @@ const initialState: {
dragItem: undefined,
};
+const sharedDropOptions = {
+ getValidChildren: (parent: Element) => {
+ return Array.from(parent.children).filter(
+ (child) => getInstanceIdFromElement(child) !== undefined
+ );
+ },
+};
+
export const useDragAndDrop = () => {
const [rootInstance] = useRootInstance();
const instancesIndex = useStore(instancesIndexStore);
@@ -90,6 +101,8 @@ export const useDragAndDrop = () => {
};
const dropHandlers = useDrop<Instance>({
+ ...sharedDropOptions,
+
elementToData(element) {
const instanceId = getInstanceIdFromElement(element);
const instance =
@@ -161,12 +174,14 @@ export const useDragAndDrop = () => {
instance: toBaseInstance(dropTarget.data),
},
});
- },
-
- getValidChildren: (parent) => {
- return Array.from(parent.children).filter(
- (child) => getInstanceIdFromElement(child) !== undefined
- );
+ publish({
+ type: "placementIndicatorChange",
+ payload: computeIndicatorPlacement({
+ ...sharedDropOptions,
+ element: dropTarget.element,
+ placement: dropTarget.placement,
+ }),
+ });
},
});
diff --git a/apps/builder/app/shared/nano-states/nano-states.ts b/apps/builder/app/shared/nano-states/nano-states.ts
index 3699a41f93..a0a3eb10eb 100644
--- a/apps/builder/app/shared/nano-states/nano-states.ts
+++ b/apps/builder/app/shared/nano-states/nano-states.ts
@@ -4,6 +4,7 @@ import { useStore } from "@nanostores/react";
import { nanoid } from "nanoid";
import type { AuthPermit } from "@webstudio-is/trpc-interface";
import type { Asset } from "@webstudio-is/asset-uploader";
+import type { Placement } from "@webstudio-is/design-system";
import type {
Breakpoint,
Breakpoints,
@@ -435,6 +436,7 @@ export type DragAndDropState = {
origin?: "canvas" | "panel";
dropTarget?: DropTargetChangePayload;
dragItem?: DragStartPayload["dragItem"];
+ placementIndicator?: Placement;
};
const dragAndDropStateContainer = atom<DragAndDropState>({
isDragging: false,
diff --git a/apps/builder/app/shared/nano-states/use-subscribe-drag-drop-state.ts b/apps/builder/app/shared/nano-states/use-subscribe-drag-drop-state.ts
index d5cb3b57ea..752c9aa1d0 100644
--- a/apps/builder/app/shared/nano-states/use-subscribe-drag-drop-state.ts
+++ b/apps/builder/app/shared/nano-states/use-subscribe-drag-drop-state.ts
@@ -14,6 +14,10 @@ export const useSubscribeDragAndDropState = () => {
setState({ ...state, dropTarget });
});
+ useSubscribe("placementIndicatorChange", (placementIndicator) => {
+ setState({ ...state, placementIndicator });
+ });
+
useSubscribe("dragEnd", () => {
setState({ isDragging: false });
});
diff --git a/packages/design-system/src/components/primitives/dnd/placement-indicator.tsx b/packages/design-system/src/components/primitives/dnd/placement-indicator.tsx
index 0b13253f49..18d0e5a1cc 100644
--- a/packages/design-system/src/components/primitives/dnd/placement-indicator.tsx
+++ b/packages/design-system/src/components/primitives/dnd/placement-indicator.tsx
@@ -7,7 +7,7 @@ import {
getPlacementInside,
getPlacementNextTo,
} from "./geometry-utils";
-import type { DropTarget } from "./use-drop";
+import { defaultGetValidChildren, DropTarget } from "./use-drop";
const placementStyle = {
boxSizing: "content-box",
@@ -34,7 +34,13 @@ const getStyle = (placement: Placement) => {
};
export const PlacementIndicator = ({ placement }: { placement: Placement }) => {
- return <Box style={getStyle(placement)} css={placementStyle} />;
+ return (
+ <Box
+ data-placement-indicator
+ style={getStyle(placement)}
+ css={placementStyle}
+ />
+ );
};
type PlacementIndicatorOptions = {
@@ -59,7 +65,7 @@ export const computeIndicatorPlacement = (
const {
placement,
element,
- getValidChildren = (parent) => parent.children,
+ getValidChildren = defaultGetValidChildren,
} = options;
const parentRect = element.getBoundingClientRect();
const children = getValidChildren(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 9b0657a8d4..c4fdf60bd3 100644
--- a/packages/design-system/src/components/primitives/dnd/use-drag.ts
+++ b/packages/design-system/src/components/primitives/dnd/use-drag.ts
@@ -98,6 +98,8 @@ export const useDrag = <DragItemData>(
};
const handlePointerMove = (event: PointerEvent) => {
+ // prevent text selecting while dragging
+ event.preventDefault();
const {
startDistanceThreashold = 3,
onStart,
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 1e01abd253..55bb84963c 100644
--- a/packages/design-system/src/components/primitives/dnd/use-drop.ts
+++ b/packages/design-system/src/components/primitives/dnd/use-drop.ts
@@ -3,13 +3,9 @@ import {
isEqualRect,
getArea,
getClosestRectIndex,
- getPlacementBetween,
- getPlacementInside,
- getPlacementNextTo,
getIndexAdjustment,
type Rect,
type Point,
- type Placement,
type Area,
type ChildrenOrientation,
} from "./geometry-utils";
@@ -25,7 +21,7 @@ type PartialDropTarget<Data> = {
export type DropTarget<Data> = PartialDropTarget<Data> & {
rect: DOMRect;
indexWithinChildren: number;
- placement: Placement & {
+ placement: {
closestChildIndex: number;
indexAdjustment: number;
childrenOrientation: ChildrenOrientation;
@@ -72,9 +68,6 @@ type UseDropProps<Data> = {
// |___________|
emulatePointerAlwaysInRootBounds?: boolean;
- // Distance from an edge when placement is put next to an element edge
- placementPadding?: number;
-
// If not provided, will be guessed automatically based
// on the actual orientation of the children
childrenOrientation?: ChildrenOrientation;
@@ -105,6 +98,16 @@ const getInitialState = <Data>() => {
};
};
+/**
+ * accept by default only children without data-placement-indicator
+ * to avoid including placement indicator element which is often put
+ * along with other children and is always close to dragging point
+ */
+export const defaultGetValidChildren = (parent: Element) =>
+ Array.from(parent.children).filter(
+ (element) => element.hasAttribute("data-placement-indicator") === false
+ );
+
export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
// We want to use fresh props every time we use them,
// but we don't need to react to updates.
@@ -118,7 +121,7 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
// We want to return a stable object to avoid re-renders when it's a dependency
return useMemo(() => {
const getChildrenRectsMemoized = (parent: Element) => {
- const { getValidChildren = (parent) => parent.children } =
+ const { getValidChildren = defaultGetValidChildren } =
latestProps.current;
const fromCache = state.current.childrenRectsCache.get(parent);
if (fromCache !== undefined) {
@@ -176,59 +179,11 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {
current.indexWithinChildren !== indexWithinChildren ||
isEqualRect(current.rect, parentRect) === false
) {
- const toGlobalCoordinates = (placement: Placement | undefined) =>
- placement && {
- ...placement,
- x: placement.x + parentRect.left,
- y: placement.y + parentRect.top,
- };
-
- const neighbourRect = childrenRects[
- indexAdjustment === 0 ? closestChildIndex - 1 : closestChildIndex + 1
- ] as Rect | undefined;
-
- let placement = toGlobalCoordinates(
- getPlacementBetween(closestChildRect, neighbourRect)
- );
-
- // If childrenOrientation is set explicitly, we want to honor it:
- // discard placement generated by getPlacementBetween if it has wrong direction
- const propsChildrenOrientation =
- latestProps.current.childrenOrientation;
- if (
- propsChildrenOrientation !== undefined &&
- placement !== undefined &&
- placement.direction === propsChildrenOrientation.type
- ) {
- placement = undefined;
- }
-
- if (placement === undefined) {
- placement = toGlobalCoordinates(
- getPlacementNextTo(
- parentRect,
- closestChildRect,
- childrenOrientation,
- indexAdjustment > 0 ? "forward" : "backward",
- latestProps.current.placementPadding
- )
- );
- }
-
- if (placement === undefined) {
- placement = getPlacementInside(
- parentRect,
- childrenOrientation,
- latestProps.current.placementPadding
- );
- }
-
const dropTarget: DropTarget<Data> = {
...partialDropTarget,
rect: parentRect,
indexWithinChildren,
placement: {
- ...placement,
closestChildIndex,
indexAdjustment,
childrenOrientation,