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
Compute indicator placement separately from drop target (#1268)
Bogdan Chadkindc5553b4968f
diff --git a/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx b/packages/design-system/src/components/primitives/dnd/canvas.stories.tsxindex 0a2d4a8825..2bbd79a532 100644--- a/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx+++ b/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx@@ -3,9 +3,13 @@ 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-indicator";+import {+ computeIndicatorPlacement,+ PlacementIndicator,+} from "./placement-indicator";import { useAutoScroll } from "./use-auto-scroll";import { theme } from "../../../stitches.config";+import type { Placement } from "./geometry-utils";const ROOT_ID = "root";@@ -188,6 +192,9 @@ export const Canvas = () => {const [currentDropTarget, setCurrentDropTarget] = useState<DropTarget<string> | undefined>();+ const [placementIndicator, setPlacementIndicator] = useState<+ undefined | Placement+ >();const [dragItemId, setDragItemId] = useState<string>();const rootRef = useRef<HTMLElement | null>(null);@@ -247,6 +254,12 @@ export const Canvas = () => {onDropTargetChange(dropTarget) {setCurrentDropTarget(dropTarget);+ setPlacementIndicator(+ computeIndicatorPlacement({+ placement: dropTarget.placement,+ element: dropTarget.element,+ })+ );},});@@ -313,6 +326,7 @@ export const Canvas = () => {autoScrollHandlers.setEnabled(false);setDragItemId(undefined);setCurrentDropTarget(undefined);+ setPlacementIndicator(undefined);},});@@ -345,8 +359,8 @@ export const Canvas = () => {<Items data={data} dragItemId={dragItemId} /></Box></Box>- {currentDropTarget && (- <PlacementIndicator placement={currentDropTarget.placement} />+ {placementIndicator && (+ <PlacementIndicator placement={placementIndicator} />)}</>);diff --git a/packages/design-system/src/components/primitives/dnd/index.ts b/packages/design-system/src/components/primitives/dnd/index.tsindex b9f03e2785..f922a6e1a1 100644--- a/packages/design-system/src/components/primitives/dnd/index.ts+++ b/packages/design-system/src/components/primitives/dnd/index.ts@@ -1,7 +1,10 @@export { useDrag } from "./use-drag";export { useDrop, type DropTarget } from "./use-drop";export { useAutoScroll } from "./use-auto-scroll";-export { PlacementIndicator } from "./placement-indicator";+export {+ PlacementIndicator,+ computeIndicatorPlacement,+} from "./placement-indicator";export { useHold } from "./use-hold";export { useDragCursor } from "./use-drag-cursor";export { type Rect, type Point, type Placement } from "./geometry-utils";diff --git a/packages/design-system/src/components/primitives/dnd/placement-indicator.tsx b/packages/design-system/src/components/primitives/dnd/placement-indicator.tsxindex 73de07a010..0b13253f49 100644--- a/packages/design-system/src/components/primitives/dnd/placement-indicator.tsx+++ b/packages/design-system/src/components/primitives/dnd/placement-indicator.tsx@@ -1,6 +1,13 @@import { Box } from "../../box";-import type { Placement } from "./geometry-utils";import { theme } from "../../../stitches.config";+import {+ type ChildrenOrientation,+ type Placement,+ getPlacementBetween,+ getPlacementInside,+ getPlacementNextTo,+} from "./geometry-utils";+import type { DropTarget } from "./use-drop";const placementStyle = {boxSizing: "content-box",@@ -29,3 +36,75 @@ const getStyle = (placement: Placement) => {export const PlacementIndicator = ({ placement }: { placement: Placement }) => {return <Box style={getStyle(placement)} css={placementStyle} />;};++type PlacementIndicatorOptions = {+ placement: DropTarget<unknown>["placement"];+ element: Element;++ // Allows you to customize children+ // that will be used to determine placement and indexWithinChildren+ getValidChildren?: (parent: Element) => Element[] | HTMLCollection;++ // 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;+};++export const computeIndicatorPlacement = (+ options: PlacementIndicatorOptions+) => {+ const {+ placement,+ element,+ getValidChildren = (parent) => parent.children,+ } = options;+ const parentRect = element.getBoundingClientRect();+ const children = getValidChildren(element);+ const { closestChildIndex, indexAdjustment, childrenOrientation } = placement;++ const closestChildRect: undefined | DOMRect =+ children[closestChildIndex]?.getBoundingClientRect();++ const neighbourChildIndex =+ indexAdjustment === 0 ? closestChildIndex - 1 : closestChildIndex + 1;+ const neighbourChildRect: undefined | DOMRect =+ children[neighbourChildIndex]?.getBoundingClientRect();++ let placementIndicator = getPlacementBetween(+ closestChildRect,+ neighbourChildRect+ );++ // If childrenOrientation is set explicitly, we want to honor it:+ // discard placement generated by getPlacementBetween if it has wrong direction+ if (+ options.childrenOrientation !== undefined &&+ placementIndicator !== undefined &&+ placementIndicator.direction === options.childrenOrientation.type+ ) {+ placementIndicator = undefined;+ }++ if (placementIndicator === undefined) {+ placementIndicator = getPlacementNextTo(+ parentRect,+ closestChildRect,+ childrenOrientation,+ indexAdjustment > 0 ? "forward" : "backward",+ options.placementPadding+ );+ }++ if (placementIndicator === undefined) {+ placementIndicator = getPlacementInside(+ parentRect,+ childrenOrientation,+ options.placementPadding+ );+ }++ return placementIndicator;+};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.tsxindex 50bad24405..ef6410b2cc 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@@ -4,9 +4,13 @@ import { Box } from "../../box";import { styled } from "../../../stitches.config";import { useDrop, type DropTarget } from "./use-drop";import { useDrag } from "./use-drag";-import { PlacementIndicator } from "./placement-indicator";+import {+ computeIndicatorPlacement,+ PlacementIndicator,+} from "./placement-indicator";import { useAutoScroll } from "./use-auto-scroll";import { theme } from "../../../stitches.config";+import type { Placement } from "./geometry-utils";type ItemData = { id: string; text: string };@@ -67,6 +71,9 @@ export const SortableList = ({] as ItemData[]);const [dropTarget, setDropTarget] = useState<DropTarget<true>>();+ const [placementIndicator, setPlacementIndicator] = useState<+ undefined | Placement+ >();const [dragItemId, setDragItemId] = useState<string>();const rootRef = useRef<HTMLUListElement | null>(null);@@ -87,6 +94,12 @@ export const SortableList = ({},onDropTargetChange(dropTarget) {setDropTarget(dropTarget);+ setPlacementIndicator(+ computeIndicatorPlacement({+ placement: dropTarget.placement,+ element: dropTarget.element,+ })+ );},});@@ -131,6 +144,7 @@ export const SortableList = ({autoScrollHandlers.setEnabled(false);setDragItemId(undefined);setDropTarget(undefined);+ setPlacementIndicator(undefined);},});@@ -183,7 +197,9 @@ export const SortableList = ({))}</List></Box>- {dropTarget && <PlacementIndicator placement={dropTarget.placement} />}+ {placementIndicator && (+ <PlacementIndicator placement={placementIndicator} />+ )}</>);};diff --git a/packages/design-system/src/components/primitives/dnd/use-drop.ts b/packages/design-system/src/components/primitives/dnd/use-drop.tsindex 3151e36977..1e01abd253 100644--- a/packages/design-system/src/components/primitives/dnd/use-drop.ts+++ b/packages/design-system/src/components/primitives/dnd/use-drop.ts@@ -25,7 +25,11 @@ type PartialDropTarget<Data> = {export type DropTarget<Data> = PartialDropTarget<Data> & {rect: DOMRect;indexWithinChildren: number;- placement: Placement;+ placement: Placement & {+ closestChildIndex: number;+ indexAdjustment: number;+ childrenOrientation: ChildrenOrientation;+ };};// We pass around data, to avoid extra data lookups.@@ -223,7 +227,12 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {...partialDropTarget,rect: parentRect,indexWithinChildren,- placement,+ placement: {+ ...placement,+ closestChildIndex,+ indexAdjustment,+ childrenOrientation,+ },};state.current.dropTarget = dropTarget;diff --git a/packages/design-system/src/components/tree/horizontal-shift.test.ts b/packages/design-system/src/components/tree/horizontal-shift.test.tsindex 16f61ff9b1..1f309326ce 100644--- a/packages/design-system/src/components/tree/horizontal-shift.test.ts+++ b/packages/design-system/src/components/tree/horizontal-shift.test.ts@@ -58,7 +58,7 @@ const tree: Item = {children: [box1, box2, box3, box4, heading, box5],};-const makePlacement = (+const makePlacementIndicator = (type: Placement["type"] = "next-to-child"): Placement => ({type,@@ -71,17 +71,18 @@ const makePlacement = (const makeDrop = ({into,after,- placement = makePlacement(),}: {into: Item;after?: Item;- placement?: Placement;}): ItemDropTarget => ({itemSelector: getItemSelector(into.id),indexWithinChildren:after === undefined ? 0 : into.children.indexOf(after) + 1,- placement,- rect: null as unknown as DOMRect,+ placement: {+ closestChildIndex: 0,+ indexAdjustment: 0,+ childrenOrientation: { type: "mixed" },+ },});const getItemSelector = (itemId: ItemId) => {@@ -94,9 +95,11 @@ const render = ({dragItem,dropTarget,+ placementIndicator = makePlacementIndicator(),}: {dragItem: Item | undefined;dropTarget: ItemDropTarget | undefined;+ placementIndicator?: Placement;},shift = -1) => {@@ -105,6 +108,7 @@ const render = (dragItemSelector:dragItem === undefined ? undefined : getItemSelector(dragItem.id),dropTarget,+ placementIndicator,getIsExpanded: (itemSelector: ItemSelector) =>(findItemById(tree, itemSelector[0])?.children.length ?? 0) > 0,canAcceptChild: (itemId: ItemId) =>@@ -134,9 +138,12 @@ test("if there's no dragItem or dropTarget returns undefined", () => {test("drop target is empty or collapsed", () => {const dropTarget = makeDrop({into: box2,- placement: makePlacement("inside-parent"),});- const result = render({ dragItem: box1, dropTarget });+ const result = render({+ dragItem: box1,+ dropTarget,+ placementIndicator: makePlacementIndicator("inside-parent"),+ });// parent doesn't changeexpect(result?.itemSelector).toEqual(["box2", "root"]);@@ -147,7 +154,10 @@ test("drop target is empty or collapsed", () => {test("placement line coordinates are always adjusted", () => {const result = render(- { dragItem: box31, dropTarget: makeDrop({ into: box3, after: box32 }) },+ {+ dragItem: box31,+ dropTarget: makeDrop({ into: box3, after: box32 }),+ },0);@@ -157,7 +167,7 @@ test("placement line coordinates are always adjusted", () => {// placement line is adjusted to account for depth,// even though depth didn't changeexpect(result?.placement).toEqual({- ...makePlacement(),+ ...makePlacementIndicator(),length: 260,x: 40,});@@ -203,7 +213,7 @@ describe("shifting to the left", () => {expect(result?.itemSelector).toEqual(["root"]);expect(result?.position).toBe(tree.children.indexOf(box3) + 1);expect(result?.placement).toEqual({- ...makePlacement(),+ ...makePlacementIndicator(),x: 24,length: 276,});@@ -219,7 +229,7 @@ describe("shifting to the left", () => {expect(result1?.itemSelector).toEqual(["root"]);expect(result1?.position).toBe(tree.children.indexOf(box3) + 1);expect(result1?.placement).toEqual({- ...makePlacement(),+ ...makePlacementIndicator(),x: 24,length: 276,});@@ -228,7 +238,7 @@ describe("shifting to the left", () => {expect(result2?.itemSelector).toEqual(["box3", "root"]);expect(result2?.position).toBe(box3.children.indexOf(box32) + 1);expect(result2?.placement).toEqual({- ...makePlacement(),+ ...makePlacementIndicator(),x: 40,length: 260,});diff --git a/packages/design-system/src/components/tree/horizontal-shift.ts b/packages/design-system/src/components/tree/horizontal-shift.tsindex 8b5c9de175..38055ae037 100644--- a/packages/design-system/src/components/tree/horizontal-shift.ts+++ b/packages/design-system/src/components/tree/horizontal-shift.ts@@ -12,6 +12,7 @@ export type ShiftedDropTarget = {export const useHorizontalShift = <Data extends { id: ItemId }>({dragItemSelector,dropTarget,+ placementIndicator,getIsExpanded,canAcceptChild,getItemChildren,@@ -20,6 +21,7 @@ export const useHorizontalShift = <Data extends { id: ItemId }>({canAcceptChild: (itemId: ItemId) => boolean;dragItemSelector: undefined | ItemSelector;dropTarget: ItemDropTarget | undefined;+ placementIndicator: undefined | Placement;getIsExpanded: (itemSelector: ItemSelector) => boolean;}) => {const [horizontalShift, setHorizontalShift] = useState(0);@@ -27,31 +29,31 @@ export const useHorizontalShift = <Data extends { id: ItemId }>({// Here we want to allow user to shift placement line horizontally// but only if that corresponds to a meaningful position in the treeconst shiftedDropTarget = useMemo((): ShiftedDropTarget | undefined => {- if (dropTarget === undefined || dragItemSelector === undefined) {+ if (+ dropTarget === undefined ||+ placementIndicator === undefined ||+ dragItemSelector === undefined+ ) {return undefined;}const dragItemDepth = dragItemSelector.length - 1;- const {- itemSelector: dropItemSelector,- placement,- indexWithinChildren,- } = dropTarget;+ const { itemSelector: dropItemSelector, indexWithinChildren } = dropTarget;const shiftPlacement = (depth: number) => {const shift = getPlacementIndicatorAlignment(depth);return {- ...placement,- x: placement.x + shift,- length: placement.length - shift,+ ...placementIndicator,+ x: placementIndicator.x + shift,+ length: placementIndicator.length - shift,};};// Placement type “inside-parent” means that useDrop() didn’t find any children.// In this case the placement line coordinates are meaningless in the context of the tree.// We're dropping the placement and not performing any shifting.- if (placement.type === "inside-parent") {+ if (placementIndicator.type === "inside-parent") {return { itemSelector: dropItemSelector, position: "end" };}@@ -160,6 +162,7 @@ export const useHorizontalShift = <Data extends { id: ItemId }>({return withoutShift;}, [dropTarget,+ placementIndicator,dragItemSelector,horizontalShift,canAcceptChild,diff --git a/packages/design-system/src/components/tree/item-utils.ts b/packages/design-system/src/components/tree/item-utils.tsindex b63c057f0e..7c76516c35 100644--- a/packages/design-system/src/components/tree/item-utils.ts+++ b/packages/design-system/src/components/tree/item-utils.ts@@ -1,4 +1,4 @@-import type { Placement } from "../primitives/dnd";+import type { ChildrenOrientation } from "../primitives/dnd/geometry-utils";export type ItemId = string;@@ -6,9 +6,12 @@ export type ItemSelector = string[];export type ItemDropTarget = {itemSelector: ItemSelector;- rect: DOMRect;indexWithinChildren: number;- placement: Placement;+ placement: {+ closestChildIndex: number;+ indexAdjustment: number;+ childrenOrientation: ChildrenOrientation;+ };};export const getElementByItemSelector = (diff --git a/packages/design-system/src/components/tree/tree.tsx b/packages/design-system/src/components/tree/tree.tsxindex cdb3c76703..cdeddaab86 100644--- a/packages/design-system/src/components/tree/tree.tsx+++ b/packages/design-system/src/components/tree/tree.tsx@@ -4,11 +4,13 @@ import { createPortal } from "react-dom";import { ListPositionIndicator } from "../list-position-indicator";import { TreeNode, INDENT, TreeItemRenderProps } from "./tree-node";import {+ type Placement,useHold,useDrop,useDrag,useAutoScroll,useDragCursor,+ computeIndicatorPlacement,} from "../primitives/dnd";import { Box } from "../box";import { useHorizontalShift } from "./horizontal-shift";@@ -39,6 +41,19 @@ export type TreeProps<Data extends { id: string }> = {}) => void;};+const sharedDropOptions = {+ placementPadding: 0,+ getValidChildren: (element: Element) => {+ // NOTE:+ // redefining children like this will screw up automatic childrenOrientation detection+ // luckily we know the orientation and can define it manually below+ return Array.from(+ element.querySelectorAll(":scope > div > [data-drop-target-id]")+ );+ },+ childrenOrientation: { type: "vertical", reverse: false },+} as const;+export const Tree = <Data extends { id: string }>({root,selectedItemSelector,@@ -61,7 +76,10 @@ export const Tree = <Data extends { id: string }>({const [dragItemSelector, setDragItemSelector] = useState<undefined | ItemSelector>();- const [dropTarget, setDropTarget] = useState<ItemDropTarget>();+ const [dropTarget, setDropTarget] = useState<undefined | ItemDropTarget>();+ const [placementIndicator, setPlacementIndicator] = useState<+ undefined | Placement+ >();const getDropTargetElement = useCallback((id: string): HTMLElement | null | undefined =>@@ -72,6 +90,7 @@ export const Tree = <Data extends { id: string }>({const [shiftedDropTarget, setHorizontalShift] = useHorizontalShift({dragItemSelector,dropTarget,+ placementIndicator,getIsExpanded,getItemChildren,canAcceptChild,@@ -100,9 +119,9 @@ export const Tree = <Data extends { id: string }>({});const dropHandlers = useDrop<ItemSelector>({- emulatePointerAlwaysInRootBounds: true,+ ...sharedDropOptions,- placementPadding: 0,+ emulatePointerAlwaysInRootBounds: true,elementToData: (element) => {return getItemSelectorFromElement(element);@@ -155,24 +174,18 @@ export const Tree = <Data extends { id: string }>({onDropTargetChange: (dropTarget) => {const itemDropTarget = {itemSelector: dropTarget.data,- rect: dropTarget.rect,indexWithinChildren: dropTarget.indexWithinChildren,placement: dropTarget.placement,};useHoldHandler.setData(itemDropTarget);setDropTarget(itemDropTarget);+ const placementIndicator = computeIndicatorPlacement({+ placement: dropTarget.placement,+ element: dropTarget.element,+ ...sharedDropOptions,+ });+ setPlacementIndicator(placementIndicator);},-- getValidChildren: (element) => {- // NOTE:- // redefining children like this will screw up automatic childrenOrientation detection- // luckily we know the orientation and can define it manually below- return Array.from(- element.querySelectorAll(":scope > div > [data-drop-target-id]")- );- },-- childrenOrientation: { type: "vertical", reverse: false },});const dragHandlers = useDrag<ItemSelector>({