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.

index detection & sortable list demo (wip)

Roman Pominov5a0d69c08105
diff --git a/apps/designer/app/shared/design-system/components/primitives/dnd/placement.tsx b/apps/designer/app/shared/design-system/components/primitives/dnd/placement.tsx
index 9fbf12fdb6..de26e9be01 100644
--- a/apps/designer/app/shared/design-system/components/primitives/dnd/placement.tsx
+++ b/apps/designer/app/shared/design-system/components/primitives/dnd/placement.tsx
@@ -1,11 +1,8 @@
+import { useRef } from "react";
import { Box } from "../../box";
export type Rect = Pick<DOMRect, "top" | "left" | "width" | "height">;
-
-export type Parameters = {
- target: HTMLElement;
- index?: number;
-};
+type Coordinates = { x: number; y: number };
const probe = document.createElement("div");
@@ -13,7 +10,13 @@ const probe = document.createElement("div");
* 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.
*/
-export const getPlacement = ({ target, index = 0 }: Parameters) => {
+export const getPlacement = ({
+ target,
+ index = 0,
+}: {
+ target: HTMLElement;
+ index?: number;
+}) => {
const { children } = target;
if (index > children.length - 1) {
target.appendChild(probe);
@@ -25,6 +28,163 @@ export const getPlacement = ({ target, index = 0 }: Parameters) => {
return rect;
};
+// https://stackoverflow.com/a/18157551/478603
+const getDistance = (rect: Rect, { x, y }: Coordinates) => {
+ 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: Coordinates) => {
+ 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;
+};
+
+type Parameters = {
+ onPalcementChange: (event: { index: number; placementRect: Rect }) => void;
+};
+
+type Handlers = {
+ handleEnd: () => void;
+ handleMove: (pointerCoordinate: Coordinates) => void;
+ handleScroll: () => void;
+ handleTargetChange: (target: HTMLElement) => void;
+};
+
+export const usePlacement = ({ onPalcementChange }: Parameters): Handlers => {
+ const state = useRef({
+ childrenRectsCache: new WeakMap<HTMLElement, Rect[]>(),
+ target: undefined as HTMLElement | undefined,
+ targetRect: undefined as DOMRect | undefined,
+ pointerCoordinate: undefined as Coordinates | undefined,
+ index: undefined as number | 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,
+ });
+ }
+ }
+
+ state.current.childrenRectsCache.set(parent, result);
+ return result;
+ };
+
+ const getIndex = (
+ parent: HTMLElement,
+ parentRect: DOMRect,
+ pointerCoordinate: Coordinates
+ ) => {
+ if (parent.children.length === 0) {
+ return 0;
+ }
+
+ const childrenRects = getChildrenRects(parent, parentRect);
+
+ const pointerAdjusted = {
+ x: pointerCoordinate.x - parentRect.left,
+ y: pointerCoordinate.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 detectChange = (reason: "move" | "scroll" | "target-change") => {
+ const { target, pointerCoordinate } = state.current;
+
+ if (target === undefined || pointerCoordinate === undefined) {
+ return;
+ }
+
+ const nextTargetRect = target.getBoundingClientRect();
+ const targetRectChanged =
+ state.current.targetRect === undefined ||
+ nextTargetRect.top !== state.current.targetRect.top ||
+ nextTargetRect.left !== state.current.targetRect.left ||
+ nextTargetRect.width !== state.current.targetRect.width ||
+ nextTargetRect.height !== state.current.targetRect.height;
+ state.current.targetRect = nextTargetRect;
+
+ const nextIndex = getIndex(target, nextTargetRect, pointerCoordinate);
+ const indexChanged = nextIndex !== state.current.index;
+ state.current.index = nextIndex;
+
+ if (indexChanged || reason === "target-change" || targetRectChanged) {
+ onPalcementChange({
+ index: nextIndex,
+ placementRect: getPlacement({ target, index: nextIndex }),
+ });
+ }
+ };
+
+ return {
+ handleEnd() {
+ state.current = {
+ childrenRectsCache: new WeakMap(),
+ target: undefined,
+ targetRect: undefined,
+ pointerCoordinate: undefined,
+ index: undefined,
+ };
+ },
+ handleMove(pointerCoordinate) {
+ state.current.pointerCoordinate = pointerCoordinate;
+ detectChange("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 = {
diff --git a/apps/designer/app/shared/design-system/components/primitives/dnd/sortable-list.stories.tsx b/apps/designer/app/shared/design-system/components/primitives/dnd/sortable-list.stories.tsx
new file mode 100644
index 0000000000..f347084aaf
--- /dev/null
+++ b/apps/designer/app/shared/design-system/components/primitives/dnd/sortable-list.stories.tsx
@@ -0,0 +1,123 @@
+import { ComponentMeta } from "@storybook/react";
+import { useState } from "react";
+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 { useAutoScroll } from "./use-auto-scroll";
+
+type ItemData = { id: string; text: string };
+
+const ListItem = styled("li", {
+ display: "block",
+ margin: 10,
+ background: "$mint12",
+ padding: 10,
+ userSelect: "none",
+ cursor: "grab",
+});
+
+const List = styled("ul", {
+ display: "block",
+ margin: 0,
+ padding: 10,
+});
+
+const Item = ({ data }: { data: ItemData }) => {
+ return <ListItem>{data.text}</ListItem>;
+};
+
+export const SortableList = () => {
+ const [data, _setData] = useState([
+ { id: "0", text: "First" },
+ { id: "1", text: "Second" },
+ { id: "2", text: "Third" },
+ { id: "3", text: "Fourth" },
+ { id: "4", text: "Fifth" },
+ { id: "5", text: "Sixth" },
+ { id: "6", text: "Seventh" },
+ { id: "7", text: "Eighth" },
+ { id: "8", text: "Ninth" },
+ { id: "9", text: "Tenth" },
+ { id: "10", text: "Eleventh" },
+ { id: "11", text: "Twelfth" },
+ { id: "12", text: "Thirteenth" },
+ { id: "13", text: "Fourteenth" },
+ { id: "14", text: "Fifteenth" },
+ { id: "15", text: "Sixteenth" },
+ { id: "16", text: "Seventeenth" },
+ { id: "17", text: "Eighteenth" },
+ ] as ItemData[]);
+
+ const [placement, setPalcement] = useState<{
+ index: number;
+ placementRect: Rect;
+ }>();
+
+ const dropTargetHandlers = useDropTarget({
+ isDropTarget(element: HTMLElement) {
+ return element instanceof HTMLUListElement;
+ },
+ onDropTargetChange(event) {
+ placementHandlers.handleTargetChange(event.target);
+ },
+ });
+
+ const autoScrollHandlers = useAutoScroll();
+
+ const dragProps = useDrag({
+ onStart(event) {
+ if (!(event.target instanceof HTMLLIElement)) {
+ event.cancel();
+ return;
+ }
+ autoScrollHandlers.setEnabled(true);
+ },
+ onMove: (poiterCoordinate) => {
+ dropTargetHandlers.handleMove(poiterCoordinate);
+ autoScrollHandlers.handleMove(poiterCoordinate);
+ placementHandlers.handleMove(poiterCoordinate);
+ },
+ onEnd() {
+ dropTargetHandlers.handleEnd();
+ autoScrollHandlers.setEnabled(false);
+ placementHandlers.handleEnd();
+ setPalcement(undefined);
+ },
+ });
+
+ const placementHandlers = usePlacement({
+ onPalcementChange: (event) => {
+ setPalcement(event);
+ },
+ });
+
+ return (
+ <>
+ <Box
+ css={{
+ height: 500,
+ overflow: "auto",
+ background: "white",
+ color: "black",
+ }}
+ ref={autoScrollHandlers.targetRef}
+ onScroll={() => {
+ dropTargetHandlers.handleScroll();
+ placementHandlers.handleScroll();
+ }}
+ {...dragProps}
+ >
+ <List ref={dropTargetHandlers.rootRef}>
+ {data.map((item) => (
+ <Item key={item.id} data={item} />
+ ))}
+ </List>
+ </Box>
+ {placement && <PlacementIndicator rect={placement.placementRect} />}
+ </>
+ );
+};
+
+export default {} as ComponentMeta<typeof SortableList>;
diff --git a/apps/designer/app/shared/design-system/components/primitives/dnd/use-drag.ts b/apps/designer/app/shared/design-system/components/primitives/dnd/use-drag.ts
index c1fa71c12e..e168b71eca 100644
--- a/apps/designer/app/shared/design-system/components/primitives/dnd/use-drag.ts
+++ b/apps/designer/app/shared/design-system/components/primitives/dnd/use-drag.ts
@@ -23,7 +23,7 @@ export type Parameters = {
shiftDistanceThreshold?: number;
onStart: (event: { target: HTMLElement; cancel: () => void }) => void;
onMove: (event: { x: number; y: number }) => void;
- onShiftChange: (event: { shifts: number }) => void;
+ onShiftChange?: (event: { shifts: number }) => void;
onEnd: () => void;
};
@@ -32,7 +32,8 @@ export const useDrag = ({
shiftDistanceThreshold = 20,
onStart,
onMove,
- onShiftChange,
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
+ onShiftChange = () => {},
onEnd,
}: Parameters): React.HTMLAttributes<HTMLElement> => {
const state = useRef<State>(initialState);
diff --git a/apps/designer/app/shared/design-system/components/primitives/dnd/use-drop-target.ts b/apps/designer/app/shared/design-system/components/primitives/dnd/use-drop-target.ts
index 2893d7b2d6..d979b0fcfb 100644
--- a/apps/designer/app/shared/design-system/components/primitives/dnd/use-drop-target.ts
+++ b/apps/designer/app/shared/design-system/components/primitives/dnd/use-drop-target.ts
@@ -11,7 +11,7 @@ export type Parameters = {
area: Area;
target: HTMLElement;
}) => void;
- onHold: (event: { target: HTMLElement }) => void;
+ onHold?: (event: { target: HTMLElement }) => void;
};
export type Handlers = {
@@ -26,7 +26,8 @@ export const useDropTarget = ({
edgeDistanceThreshold = 3,
holdTimeThreshold = 500,
onDropTargetChange,
- onHold,
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
+ onHold = () => {},
}: Parameters): Handlers => {
const state = useRef({
root: null as HTMLElement | null,
@@ -35,6 +36,7 @@ export const useDropTarget = ({
rect: undefined as DOMRect | undefined,
holdTimeout: undefined as NodeJS.Timeout | undefined,
pointerCoordinate: undefined as Coordinate | undefined,
+ dropIndex: undefined as number | undefined,
});
const clearHoldTimeout = () => {
@@ -95,6 +97,7 @@ export const useDropTarget = ({
if (hasTargetChanged || hasAreaChanged || hasRectChanged) {
onDropTargetChange({
rect: nextRect,
+ // NOTE: might make more sense to pass the area to isDropTarget instead of here
area: nextArea,
target: nextTarget,
});