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
finish horizontal shift & other fixes
Roman Pominovf1242dd783bf
diff --git a/apps/designer/app/canvas/shared/instance.ts b/apps/designer/app/canvas/shared/instance.tsindex c1628538cd..1c99f92927 100644--- a/apps/designer/app/canvas/shared/instance.ts+++ b/apps/designer/app/canvas/shared/instance.ts@@ -114,7 +114,7 @@ export const useReparentInstance = () => {"reparentInstance",{instanceId: Instance["id"];- dropTarget: { instanceId: Instance["id"]; position: number };+ dropTarget: { instanceId: Instance["id"]; position: number | "end" };}>("reparentInstance", ({ instanceId, dropTarget }) => {store.createTransaction([rootInstanceContainer], (rootInstance) => {diff --git a/apps/designer/app/canvas/shared/use-drag-drop.ts b/apps/designer/app/canvas/shared/use-drag-drop.tsindex 201b5b908b..786d87d7da 100644--- a/apps/designer/app/canvas/shared/use-drag-drop.ts+++ b/apps/designer/app/canvas/shared/use-drag-drop.ts@@ -92,7 +92,7 @@ export const useDragAndDrop = () => {const path = getInstancePath(rootInstance, dropTarget.data.id);path.reverse();- if (dropTarget.area.isNearEdge === false) {+ if (dropTarget.area !== "center") {path.shift();}@@ -122,15 +122,7 @@ export const useDragAndDrop = () => {return getDefaultDropTarget();}- return {- data,- element,-- // The only reason we might need to swap again is if we're on the ende of the new target.- // But that shouldn't be possible unless we're also on the edge of the current target.- // @todo: test this- final: dropTarget.area.isNearEdge === false,- };+ return { data, element };},onDropTargetChange(dropTarget) {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.tsxindex 0f7e651ad2..78c16a388b 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@@ -34,7 +34,10 @@ export const Navigator = ({ publish, isClosable, onClose }: NavigatorProps) => {"reparentInstance",{instanceId: Instance["id"];- dropTarget: { instanceId: Instance["id"]; position: number };+ dropTarget: {+ instanceId: Instance["id"];+ position: number | "end";+ };}>({ type: "reparentInstance", payload });}}diff --git a/apps/designer/app/designer/features/tree-preview/tree-preview.tsx b/apps/designer/app/designer/features/tree-preview/tree-preview.tsxindex 936a067fbb..5e0e18281c 100644--- a/apps/designer/app/designer/features/tree-preview/tree-preview.tsx+++ b/apps/designer/app/designer/features/tree-preview/tree-preview.tsx@@ -66,7 +66,7 @@ export const TreePrevew = () => {return (treeProps && (<Flex gap="3" direction="column" css={{ padding: "$1" }}>- <Tree {...treeProps} animate={false} />+ {/* <Tree {...treeProps} animate={false} /> */}</Flex>));diff --git a/apps/designer/app/designer/shared/tree/base-tree.tsx b/apps/designer/app/designer/shared/tree/base-tree.tsxindex fbf2d95528..da519ffdfc 100644--- a/apps/designer/app/designer/shared/tree/base-tree.tsx+++ b/apps/designer/app/designer/shared/tree/base-tree.tsx@@ -3,13 +3,31 @@ import { type Instance } from "@webstudio-is/react-sdk";import { getInstancePath } from "~/shared/tree-utils";import { TreeNode, getIsExpandable } from "./tree-node";-export const useExpandState = () => {+export const useExpandState = ({+ selectedInstanceId,+ root,+}: {+ root: Instance;+ selectedInstanceId?: Instance["id"];+}) => {const [record, setRecord] = useState<Record<Instance["id"], boolean>>({});+ const selectedInstancePath = useMemo(+ () =>+ selectedInstanceId !== undefined+ ? getInstancePath(root, selectedInstanceId).map(+ (instance) => instance.id+ )+ : [],+ [root, selectedInstanceId]+ );+const getIsExpanded = useCallback((instance: Instance) =>- getIsExpandable(instance) && record[instance.id] === true,- [record]+ getIsExpandable(instance) &&+ (record[instance.id] === true ||+ selectedInstancePath.includes(instance.id)),+ [record, selectedInstancePath]);const setIsExpanded = useCallback(@@ -37,21 +55,12 @@ type BaseTreeProps = TreeProps & {export const BaseTree = forwardRef<HTMLDivElement, BaseTreeProps>(({ root, selectedInstanceId, ...rest }, ref) => {- const selectedInstancePath = useMemo(- () =>- selectedInstanceId !== undefined- ? getInstancePath(root, selectedInstanceId)- : [],- [root, selectedInstanceId]- );-return (<TreeNoderef={ref}instance={root}level={0}selectedInstanceId={selectedInstanceId}- selectedInstancePath={selectedInstancePath}{...rest}/>);@@ -60,6 +69,6 @@ export const BaseTree = forwardRef<HTMLDivElement, BaseTreeProps>(BaseTree.displayName = "BaseTree";export const Tree = (props: TreeProps) => {- const expandState = useExpandState();+ const expandState = useExpandState(props);return <BaseTree {...props} {...expandState} />;};diff --git a/apps/designer/app/designer/shared/tree/sortable-tree.tsx b/apps/designer/app/designer/shared/tree/sortable-tree.tsxindex f9bf429c36..4300d8a704 100644--- a/apps/designer/app/designer/shared/tree/sortable-tree.tsx+++ b/apps/designer/app/designer/shared/tree/sortable-tree.tsx@@ -2,11 +2,11 @@ import { useState, useMemo, useRef } from "react";import { type Instance, components } from "@webstudio-is/react-sdk";import {type DropTarget,+ type Rect,useDrag,useDrop,useHold,Box,- Rect,} from "@webstudio-is/design-system";import {findInstanceById,@@ -17,17 +17,19 @@ import { createPortal } from "react-dom";import { getIsExpandable } from "./tree-node";import { BaseTree, useExpandState, type TreeProps } from "./base-tree";+type Placement = DropTarget<unknown>["placement"];+export const SortableTree = (props: TreeProps & {onDragEnd: (event: {instanceId: Instance["id"];- dropTarget: { instanceId: Instance["id"]; position: number };+ dropTarget: { instanceId: Instance["id"]; position: number | "end" };}) => void;}) => {const { root, onDragEnd } = props;- const expandState = useExpandState();+ const { getIsExpanded, setIsExpanded } = useExpandState(props);const rootRef = useRef<HTMLElement | null>(null);@@ -43,56 +45,130 @@ export const SortableTree = (// Here we want to allow user to shift placement line horizontally// but only if that corresponds to a meaningful position in the tree- const finalDropTarget = useMemo((): DropTarget<Instance> | undefined => {- if (dragItemDepth === undefined || dropTarget === undefined) {- return dropTarget;+ const finalDropTarget = useMemo<+ | {+ instance: Instance;+ position: number | "end";+ placement:+ | { type: "rect"; rect: Rect }+ | { type: "line"; line: Placement };+ }+ | undefined+ >(() => {+ if (+ dropTarget === undefined ||+ dragItemDepth === undefined ||+ dragItem === undefined+ ) {+ return undefined;}- // This is the case where we render an outline instead of a line- if (dropTarget.placement.type === "inside-parent") {- return dropTarget;+ const { data, placement, rect, indexWithinChildren } = dropTarget;++ // Placement type “inside-parent” means that useDrop didn’t find any children,+ // and the “placement” corresponds to a line near an edge of the parent.+ // This means the drop target is empty or collapsed.+ // In this case, we want to show a rect instead of a line.+ // Also, we don’t want to apply shift, as there’s no line to shift.+ if (placement.type === "inside-parent") {+ return {+ instance: data,+ position: "end",+ placement: { type: "rect", rect: rect },+ };}- const dropTargetPath = getInstancePathWithPositions(- root,- dropTarget.data.id- );+ const dropTargetPath = getInstancePathWithPositions(root, data.id);dropTargetPath.reverse();const currentDepth = dropTargetPath.length;const desiredDepth = dragItemDepth + horizontalShift;- // @todo: shift deeper if <- if (currentDepth <= desiredDepth) {- return dropTarget;- }+ const shiftLine = (depth: number) => {+ // @todo: fix magic numbers+ const shift = depth * 15 + 15;+ return {+ ...placement,+ x: placement.x + shift,+ length: placement.length - shift,+ };+ };- // Unless we're currently at the bottom of drop target's children,- // decreasing depth will not correspond to a new meaningful position- if (dropTarget.indexWithinChildren !== dropTarget.data.children.length) {- return dropTarget;- }+ const withoutShift = {+ instance: data,+ position: indexWithinChildren,+ placement: { type: "line", line: shiftLine(currentDepth) },+ } as const;++ if (desiredDepth < currentDepth) {+ // Unless we're currently at the bottom of drop target's children,+ // decreasing depth will not correspond to a new meaningful position+ if (indexWithinChildren !== data.children.length) {+ // But there's a special case when the index is `last - 1` and the last child is the drag item.+ // When drag item is removed from its current position, `last - 1` will become `last`.++ if (indexWithinChildren !== data.children.length - 1) {+ return withoutShift;+ }++ const lastChild = data.children[data.children.length - 1];+ const lastChildIsDragItem =+ lastChild !== undefined &&+ typeof lastChild !== "string" &&+ lastChild.id === dragItem.id;++ if (lastChildIsDragItem === false) {+ return withoutShift;+ }+ }- const difference = Math.min(- dropTargetPath.length - 1,- currentDepth - desiredDepth- );+ const difference = Math.min(+ dropTargetPath.length - 1,+ currentDepth - desiredDepth+ );- // Ideally we should check canAcceptChildren on the new target- // but we assume that because it already has a child it can accept more+ // Ideally we should check canAcceptChildren on the new target+ // but we assume that because it already has a child, it can accept more.++ return {+ instance: dropTargetPath[difference].instance,+ position: dropTargetPath[difference - 1].position + 1,+ placement: {+ type: "line",+ line: shiftLine(currentDepth - difference),+ },+ };+ }- // @todo: if this works, move logic of placement modification here as well+ if (desiredDepth > currentDepth) {+ // When increasing depth we're moving inside the instance above the placement line.+ const instanceAbove = data.children[indexWithinChildren - 1];+ if (+ instanceAbove === undefined ||+ typeof instanceAbove === "string" ||+ getIsExpanded(instanceAbove) === false ||+ components[instanceAbove.component].canAcceptChild() === false+ ) {+ return withoutShift;+ }- return {- data: dropTargetPath[difference].instance,- placement: dropTarget.placement,- indexWithinChildren: dropTargetPath[difference - 1].position + 1,+ // @todo: allow shifting by more than one level+ return {+ instance: instanceAbove,+ position: "end",+ placement: { type: "line", line: shiftLine(currentDepth + 1) },+ };+ }- // @todo: these are wrong now, but not used- element: dropTarget.element,- rect: dropTarget.rect,- };- }, [dragItemDepth, dropTarget, root, horizontalShift]);+ return withoutShift;+ }, [+ dragItem,+ dragItemDepth,+ dropTarget,+ root,+ horizontalShift,+ getIsExpanded,+ ]);// @todo: not sure what this should return,// need to understand better when it's used@@ -110,7 +186,6 @@ export const SortableTree = (isEqual: (a, b) => a.data.id === b.data.id,holdTimeThreshold: 1000,onHold: (dropTarget) => {- const { getIsExpanded, setIsExpanded } = expandState;if (getIsExpandable(dropTarget.data) &&getIsExpanded(dropTarget.data) === false@@ -131,9 +206,6 @@ export const SortableTree = (return instance || false;},- // We don't use area so setting this to 0 to get less frequent updates- edgeDistanceThreshold: 0,-swapDropTarget: (dropTarget) => {if (dragItem === undefined || dropTarget === undefined) {return getFallbackDropTarget();@@ -146,6 +218,10 @@ export const SortableTree = (const path = getInstancePath(root, dropTarget.data.id);path.reverse();+ if (dropTarget.area === "top" || dropTarget.area === "bottom") {+ path.shift();+ }+// Don't allow to drop inside drag item or any of its childrenconst dragItemIndex = path.findIndex((instance) => instance.id === dragItem.id@@ -216,8 +292,8 @@ export const SortableTree = (onDragEnd({instanceId: dragItem.id,dropTarget: {- instanceId: finalDropTarget.data.id,- position: finalDropTarget.indexWithinChildren,+ instanceId: finalDropTarget.instance.id,+ position: finalDropTarget.position,},});}@@ -234,7 +310,8 @@ export const SortableTree = (<><BaseTree{...props}- {...expandState}+ getIsExpanded={getIsExpanded}+ setIsExpanded={setIsExpanded}onExpandTransitionEnd={dropHandlers.handleDomMutation}ref={(element) => {rootRef.current = element;@@ -244,13 +321,10 @@ export const SortableTree = (/>{finalDropTarget &&createPortal(- // Placement type "inside-parent" means that useDrop didn't find any children,- // and the placement coorespond to a line near an edge of the parent.- // In tree this doesn't make sense, so we're rendering an outline around the parent instead of a line.- finalDropTarget.placement.type === "inside-parent" ? (- <PlacementIndicatorOutline rect={finalDropTarget.rect} />+ finalDropTarget.placement.type === "rect" ? (+ <PlacementIndicatorOutline rect={finalDropTarget.placement.rect} />) : (- <PlacementIndicatorLine dropTarget={finalDropTarget} root={root} />+ <PlacementIndicatorLine line={finalDropTarget.placement.line} />),document.body@@ -259,29 +333,14 @@ export const SortableTree = ();};-const PlacementIndicatorLine = ({- dropTarget,- root,-}: {- root: Instance;- dropTarget: DropTarget<Instance>;-}) => {- const depth = useMemo(- () => getInstancePath(root, dropTarget.data.id).length,- [dropTarget.data.id, root]- );-- const { placement } = dropTarget;-- // @todo: fix magic numbers- const shift = depth * 15 + 15 + 4;-+const PlacementIndicatorLine = ({ line }: { line: Placement }) => {return (<Boxstyle={{- top: placement.y - 1,- left: placement.x + shift,- width: placement.length - shift,+ // @todo: fix magic numbers+ top: line.y - 1,+ left: line.x + 4,+ width: line.length - 4,height: 2,}}css={{diff --git a/apps/designer/app/designer/shared/tree/tree-node.tsx b/apps/designer/app/designer/shared/tree/tree-node.tsxindex a48cad9f34..34ab3dad12 100644--- a/apps/designer/app/designer/shared/tree/tree-node.tsx+++ b/apps/designer/app/designer/shared/tree/tree-node.tsx@@ -45,7 +45,6 @@ const CollapsibleContentUnanimated = styled(Collapsible.Content, {type TreeNodeProps = {instance: Instance;selectedInstanceId: Instance["id"] | undefined;- selectedInstancePath: Array<Instance>;level: number;onSelect?: (instance: Instance) => void;animate?: boolean;@@ -62,16 +61,13 @@ export const TreeNode = forwardRef<HTMLDivElement, TreeNodeProps>(setIsExpanded,selectedInstanceId,onSelect = noop,- selectedInstancePath,onExpandTransitionEnd = noop,} = commonProps;const collapsibleContentRef = useRef<HTMLDivElement>(null);const isExpandable = getIsExpandable(instance);- const isExpanded =- getIsExpanded(instance) ||- selectedInstancePath.some((item) => item.id === instance.id);+ const isExpanded = getIsExpanded(instance);const isSelected = instance.id === selectedInstanceId;const { Icon, label } = components[instance.component];diff --git a/apps/designer/app/shared/tree-utils/reparent-instance.ts b/apps/designer/app/shared/tree-utils/reparent-instance.tsindex 0785f81be5..44345f8aba 100644--- a/apps/designer/app/shared/tree-utils/reparent-instance.ts+++ b/apps/designer/app/shared/tree-utils/reparent-instance.ts@@ -8,13 +8,22 @@ export const reparentInstanceMutable = (rootInstance: Instance,instanceId: Instance["id"],newParentId: Instance["id"],- newPosition: number+ newPosition: number | "end") => {const instance = findInstanceById(rootInstance, instanceId);if (instance === undefined) {return;}+ if (newPosition === "end") {+ deleteInstanceMutable(rootInstance, instance.id);+ insertInstanceMutable(rootInstance, instance, {+ parentId: newParentId,+ position: "end",+ });+ return;+ }+let newPositionAdjusted = newPosition;// If parent is the same, we need to adjust the position to account for the removal of the instance.diff --git a/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx b/packages/design-system/src/components/primitives/dnd/canvas.stories.tsxindex 6977e746e3..1a6267dae1 100644--- a/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx+++ b/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx@@ -219,7 +219,7 @@ export const Canvas = () => {const path = findItemPath(data, id) ?? [];- if (area.isNearEdge === false) {+ if (area !== "center") {path.shift();}diff --git a/packages/design-system/src/components/primitives/dnd/geometry-utils.ts b/packages/design-system/src/components/primitives/dnd/geometry-utils.tsindex 50fd8bb4c2..6d8cfdab67 100644--- a/packages/design-system/src/components/primitives/dnd/geometry-utils.ts+++ b/packages/design-system/src/components/primitives/dnd/geometry-utils.ts@@ -19,13 +19,7 @@ export type Placement = {direction: "horizontal" | "vertical";};-export type Area = {- isNearTop: boolean;- isNearLeft: boolean;- isNearRight: boolean;- isNearBottom: boolean;- isNearEdge: boolean;-};+export type Area = "top" | "bottom" | "left" | "right" | "center";// https://stackoverflow.com/a/18157551/478603const getDistanceToRect = (rect: Rect, { x, y }: Point) => {@@ -59,12 +53,19 @@ export const getArea = (edgeDistanceThreshold: number,rect: Rect): Area => {- const isNearTop = y - rect.top <= edgeDistanceThreshold;- const isNearLeft = x - rect.left <= edgeDistanceThreshold;- const isNearRight = rect.left + rect.width - x <= edgeDistanceThreshold;- const isNearBottom = rect.top + rect.height - y <= edgeDistanceThreshold;- const isNearEdge = isNearTop || isNearLeft || isNearRight || isNearBottom;- return { isNearTop, isNearLeft, isNearRight, isNearBottom, isNearEdge };+ if (y - rect.top <= edgeDistanceThreshold) {+ return "top";+ }+ if (rect.top + rect.height - y <= edgeDistanceThreshold) {+ return "bottom";+ }+ if (x - rect.left <= edgeDistanceThreshold) {+ return "left";+ }+ if (rect.left + rect.width - x <= edgeDistanceThreshold) {+ return "right";+ }+ return "center";};export const getPlacementBetween = (diff --git a/packages/design-system/src/components/primitives/dnd/use-drop.ts b/packages/design-system/src/components/primitives/dnd/use-drop.tsindex 057cd68545..cac3a4c819 100644--- a/packages/design-system/src/components/primitives/dnd/use-drop.ts+++ b/packages/design-system/src/components/primitives/dnd/use-drop.ts@@ -42,16 +42,10 @@ export type UseDropProps<Data> = {// you can swap to another targetswapDropTarget: (// undefined is passed when no suitable element is found under the pointer- dropTarget:- | (PartialDropTarget<Data> & {- // @todo: revert to isNearEdge- area: Area;- })- | undefined+ dropTarget: (PartialDropTarget<Data> & { area: Area }) | undefined) => PartialDropTarget<Data> & {- // Set "final" to true if you don't want to swap- // any further for the current pointer position.- // (Normally swapDropTarget is called repeatedly until it returns the same value twice)+ // Set "final" to true if you don't want to swap any further.+ // (Normally swapDropTarget is called repeatedly until the output is the same as the input)final?: boolean;};@@ -259,8 +253,7 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {candidate.element.getBoundingClientRect()): undefined;- const isNewArea =- isSameArea(candidateArea, state.current.lastCandidateArea) === false;+ const isNewArea = candidateArea !== state.current.lastCandidateArea;state.current.lastCandidateArea = candidateArea;if (isNewCandidate === false &&@@ -364,18 +357,3 @@ const findClosestDropTarget = <Data>({currentElement = currentElement.parentElement;}};--const isSameArea = (a: Area | undefined, b: Area | undefined) => {- if (a === undefined && b === undefined) {- return true;- }- if (a === undefined || b === undefined) {- return false;- }- return (- a.isNearBottom === b.isNearBottom &&- a.isNearLeft === b.isNearLeft &&- a.isNearRight === b.isNearRight &&- a.isNearTop === b.isNearTop- );-};