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
expand on hold & refactoring
Roman Pominov17b4027bb9f5
diff --git a/apps/designer/app/canvas/shared/use-drag-drop.ts b/apps/designer/app/canvas/shared/use-drag-drop.tsindex f7ab5c16b3..a4fd2b83b2 100644--- a/apps/designer/app/canvas/shared/use-drag-drop.ts+++ b/apps/designer/app/canvas/shared/use-drag-drop.ts@@ -173,6 +173,7 @@ export const useDragAndDrop = () => {state.current.dragItem = instance;autoScrollHandlers.setEnabled(true);+ dropHandlers.handleStart();publish<"dragStart", DragStartPayload>({type: "dragStart",@@ -249,6 +250,7 @@ export const useDragAndDrop = () => {if (origin === "panel") {state.current.dragItem = dragItem;autoScrollHandlers.setEnabled(true);+ dropHandlers.handleStart();}});diff --git a/apps/designer/app/designer/shared/tree/base-tree.tsx b/apps/designer/app/designer/shared/tree/base-tree.tsxnew file mode 100644index 0000000000..4ac8937c42--- /dev/null+++ b/apps/designer/app/designer/shared/tree/base-tree.tsx@@ -0,0 +1,70 @@+import { useState, useMemo, forwardRef, useCallback } from "react";+import { type Instance } from "@webstudio-is/react-sdk";+import { getInstancePath } from "~/shared/tree-utils";+import { TreeNode, getIsExpandable } from "./tree-node";++type ExpandState = {+ getIsExpanded: (instance: Instance) => boolean;+ setIsExpanded: (instanceId: Instance["id"], expanded: boolean) => void;+};++export const useExpandState = (): ExpandState => {+ const [record, setRecord] = useState<Record<Instance["id"], boolean>>({});++ const getIsExpanded = useCallback(+ (instance: Instance) =>+ getIsExpandable(instance) && record[instance.id] === true,+ [record]+ );++ const setIsExpanded = useCallback(+ (instanceId: Instance["id"], expanded: boolean) => {+ setRecord((record) => ({ ...record, [instanceId]: expanded }));+ },+ []+ );++ return { getIsExpanded, setIsExpanded };+};++export type TreeProps = {+ root: Instance;+ selectedInstanceId?: Instance["id"];+ onSelect?: (instance: Instance) => void;+ animate?: boolean;+};++type BaseTreeProps = TreeProps & {+ getIsExpanded: (instance: Instance) => boolean;+ setIsExpanded: (instanceId: Instance["id"], expanded: boolean) => void;+ onAnimationEnd?: () => void;+};++export const BaseTree = forwardRef<HTMLDivElement, BaseTreeProps>(+ ({ root, selectedInstanceId, ...rest }, ref) => {+ const selectedInstancePath = useMemo(+ () =>+ selectedInstanceId !== undefined+ ? getInstancePath(root, selectedInstanceId)+ : [],+ [root, selectedInstanceId]+ );++ return (+ <TreeNode+ ref={ref}+ instance={root}+ level={0}+ selectedInstanceId={selectedInstanceId}+ selectedInstancePath={selectedInstancePath}+ {...rest}+ />+ );+ }+);+BaseTree.displayName = "BaseTree";++export const Tree = (props: TreeProps) => {+ const expandState = useExpandState();+ return <BaseTree {...props} {...expandState} />;+};diff --git a/apps/designer/app/designer/shared/tree/index.ts b/apps/designer/app/designer/shared/tree/index.tsindex 8f2111195c..8c4cc7182a 100644--- a/apps/designer/app/designer/shared/tree/index.ts+++ b/apps/designer/app/designer/shared/tree/index.ts@@ -1 +1,2 @@+export * from "./sortable-tree";export * from "./tree";diff --git a/apps/designer/app/designer/shared/tree/sortable-tree.tsx b/apps/designer/app/designer/shared/tree/sortable-tree.tsxnew file mode 100644index 0000000000..eec3473dca--- /dev/null+++ b/apps/designer/app/designer/shared/tree/sortable-tree.tsx@@ -0,0 +1,250 @@+import { useState, useMemo, useRef } from "react";+import { type Instance, components } from "@webstudio-is/react-sdk";+import {+ type DropTarget,+ useDrag,+ useDrop,+ useHold,+ Box,+} from "@webstudio-is/design-system";+import { findInstanceById, getInstancePath } from "~/shared/tree-utils";+import { createPortal } from "react-dom";+import { getIsExpandable } from "./tree-node";+import { BaseTree, useExpandState, type TreeProps } from "./base-tree";++export const SortableTree = (+ props: TreeProps & {+ onDragEnd: (event: {+ instanceId: Instance["id"];+ dropTarget: { instanceId: Instance["id"]; position: number };+ }) => void;+ }+) => {+ const { root, onDragEnd } = props;++ const expandState = useExpandState();++ 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 = () => {+ return {+ data: root,+ element: rootRef.current as HTMLElement,+ };+ };++ const useHoldHandler = useHold<DropTarget<Instance>>({+ 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+ ) {+ setIsExpanded(dropTarget.data.id, true);+ }+ },+ });++ const dropHandlers = useDrop<Instance>({+ emulatePointerAlwaysInRootBounds: true,++ placementPadding: 0,++ elementToData: (element) => {+ const id = (element as HTMLElement).dataset.dropTargetId;+ const instance = id && findInstanceById(root, id);+ return instance || false;+ },++ swapDropTarget: (dropTarget) => {+ if (dragItem === undefined || dropTarget === undefined) {+ return getFallbackDropTarget();+ }++ if (dropTarget.data.id === root.id) {+ return dropTarget;+ }++ 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 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) => {+ useHoldHandler.setData(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>({+ elementToData: (element) => {+ const dragItemElement = element.closest("[data-drag-item-id]");+ if (!(dragItemElement instanceof HTMLElement)) {+ return false;+ }+ const id = dragItemElement.dataset.dragItemId;+ if (id === undefined || id === root.id) {+ return false;+ }+ return findInstanceById(root, id) || false;+ },+ onStart: ({ data }) => {+ setDragItem(data);+ dropHandlers.handleStart();+ },+ onMove: (point) => {+ dropHandlers.handleMove(point);+ },+ onEnd: ({ isCanceled }) => {+ if (dropTarget && dragItem && isCanceled === false) {+ onDragEnd({+ instanceId: dragItem.id,+ dropTarget: {+ instanceId: dropTarget.data.id,+ position: dropTarget.indexWithinChildren,+ },+ });+ }++ setDragItem(undefined);+ setDropTarget(undefined);+ dropHandlers.handleEnd();+ useHoldHandler.reset();+ },+ });++ return (+ <>+ <BaseTree+ {...props}+ {...expandState}+ onAnimationEnd={dropHandlers.handleDomMutation}+ ref={(element) => {+ rootRef.current = element;+ dragHandlers.rootRef(element);+ dropHandlers.rootRef(element);+ }}+ />+ {dropTarget && <PlacementIndicator root={root} dropTarget={dropTarget} />}+ </>+ );+};++const PlacementIndicator = ({+ root,+ dropTarget,+}: {+ root: Instance;+ dropTarget: DropTarget<Instance>;+}) => {+ const depth = useMemo(() => {+ // We only need depth if we're rendering a line+ if (dropTarget.placement.type !== "inside-parent") {+ return getInstancePath(root, dropTarget.data.id).length;+ }+ return undefined;+ }, [dropTarget.data.id, dropTarget.placement.type, root]);++ if (depth !== undefined) {+ const { placement } = dropTarget;++ // @todo: fix magic numbers+ const shift = depth * 15 + 15 + 4;++ return createPortal(+ <Box+ style={{+ top: placement.y - 1,+ left: placement.x + shift,+ width: placement.length - shift,+ height: 2,+ }}+ css={{+ boxSizing: "content-box",+ position: "absolute",+ background: "#f531b3",+ pointerEvents: "none",+ }}+ >+ <Box+ css={{+ // @todo: fix magic numbers+ width: 8,+ height: 8,+ top: -3,+ left: -7,+ position: "absolute",+ border: "solid 2px #f531b3",+ borderRadius: "50%",+ }}+ />+ </Box>,+ document.body+ );+ }++ const { rect } = dropTarget;++ return createPortal(+ <Box+ style={{+ top: rect.top,+ left: rect.left,+ width: rect.width,+ height: rect.height,+ }}+ css={{+ position: "absolute",+ pointerEvents: "none",+ outline: "2px solid #f531b3",+ borderRadius: 6,+ }}+ />,+ document.body+ );+};diff --git a/apps/designer/app/designer/shared/tree/tree-node.tsx b/apps/designer/app/designer/shared/tree/tree-node.tsxnew file mode 100644index 0000000000..1067329cf8--- /dev/null+++ b/apps/designer/app/designer/shared/tree/tree-node.tsx@@ -0,0 +1,153 @@+import { forwardRef, useCallback, useRef, useEffect } from "react";+import { type Instance, components } from "@webstudio-is/react-sdk";+import {+ Flex,+ Text,+ Collapsible,+ Button,+ keyframes,+ styled,+} from "@webstudio-is/design-system";+import { TriangleRightIcon, TriangleDownIcon } from "@webstudio-is/icons";+import noop from "lodash.noop";++export const getIsExpandable = (instance: Instance) => {+ return (+ // Text nodes have only one child which is a string.+ instance.children.length > 1 || typeof instance.children[0] === "object"+ );+};++const openKeyframes = keyframes({+ from: { height: 0 },+ to: { height: "var(--radix-collapsible-content-height)" },+});++const closeKeyframes = keyframes({+ from: { height: "var(--radix-collapsible-content-height)" },+ to: { height: 0 },+});++const CollapsibleContentAnimated = styled(Collapsible.Content, {+ overflow: "hidden",+ '&[data-state="open"]': {+ animation: `${openKeyframes} 150ms ease-in-out`,+ },+ '&[data-state="closed"]': {+ animation: `${closeKeyframes} 150ms ease-in-out`,+ },+});++const CollapsibleContentUnanimated = styled(Collapsible.Content, {+ overflow: "hidden",+});++type TreeNodeProps = {+ instance: Instance;+ selectedInstanceId: Instance["id"] | undefined;+ selectedInstancePath: Array<Instance>;+ level: number;+ onSelect?: (instance: Instance) => void;+ animate?: boolean;+ getIsExpanded: (instance: Instance) => boolean;+ setIsExpanded: (instanceId: Instance["id"], expanded: boolean) => void;+ onAnimationEnd?: () => void;+};++export const TreeNode = forwardRef<HTMLDivElement, TreeNodeProps>(+ ({ instance, level, ...commonProps }, ref) => {+ const {+ getIsExpanded,+ animate = true,+ setIsExpanded,+ selectedInstanceId,+ onSelect = noop,+ selectedInstancePath,+ onAnimationEnd = noop,+ } = commonProps;++ const collapsibleContentRef = useRef<HTMLDivElement>(null);++ const isExpandable = getIsExpandable(instance);+ const isExpanded =+ getIsExpanded(instance) ||+ selectedInstancePath.some((item) => item.id === instance.id);+ const isSelected = instance.id === selectedInstanceId;++ const { Icon, label } = components[instance.component];++ const CollapsibleContent = animate+ ? CollapsibleContentAnimated+ : CollapsibleContentUnanimated;++ const handleAnimationEnd = useCallback(+ (event: React.AnimationEvent<HTMLDivElement>) => {+ if (event.target === collapsibleContentRef.current) {+ onAnimationEnd();+ }+ },+ [onAnimationEnd]+ );++ const prevIsExpanded = useRef(isExpanded);+ useEffect(() => {+ if (animate === false && isExpanded !== prevIsExpanded.current) {+ onAnimationEnd();+ }+ prevIsExpanded.current = isExpanded;+ }, [animate, onAnimationEnd, isExpanded]);++ return (+ <Collapsible.Root+ ref={ref}+ open={isExpanded}+ onOpenChange={(isOpen: boolean) => setIsExpanded(instance.id, isOpen)}+ data-drop-target-id={instance.id}+ >+ <Flex+ css={{+ // @todo don't hardcode the padding+ paddingLeft: level * 15 + (isExpandable ? 0 : 15),+ color: "$hiContrast",+ alignItems: "center",+ }}+ >+ {isExpandable && (+ <Collapsible.Trigger asChild>+ {isExpanded ? <TriangleDownIcon /> : <TriangleRightIcon />}+ </Collapsible.Trigger>+ )}+ <Button+ {...(isSelected ? { state: "active" } : { ghost: true })}+ css={{ display: "flex", gap: "$1", padding: "$1" }}+ data-drag-item-id={instance.id}+ onFocus={() => onSelect(instance)}+ >+ <Icon />+ <Text size="1">{label}</Text>+ </Button>+ </Flex>+ {isExpandable && (isExpanded || animate) && (+ <CollapsibleContent+ onAnimationEnd={handleAnimationEnd}+ ref={collapsibleContentRef}+ >+ {instance.children.flatMap((child) =>+ typeof child === "string"+ ? []+ : [+ <TreeNode+ key={child.id}+ instance={child}+ level={level + 1}+ {...commonProps}+ />,+ ]+ )}+ </CollapsibleContent>+ )}+ </Collapsible.Root>+ );+ }+);+TreeNode.displayName = "TreeNode";diff --git a/apps/designer/app/designer/shared/tree/tree.tsx b/apps/designer/app/designer/shared/tree/tree.tsxindex f37a559e65..6db8031945 100644--- a/apps/designer/app/designer/shared/tree/tree.tsx+++ b/apps/designer/app/designer/shared/tree/tree.tsx@@ -1,434 +1,6 @@-import { useState, useMemo, forwardRef, useRef, useCallback } from "react";-import { type Instance, components } from "@webstudio-is/react-sdk";-import {- Flex,- Text,- Collapsible,- Button,- keyframes,- styled,- type DropTarget,- useDrag,- useDrop,- Box,-} 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 },- to: { height: "var(--radix-collapsible-content-height)" },-});--const closeKeyframes = keyframes({- from: { height: "var(--radix-collapsible-content-height)" },- to: { height: 0 },-});--const CollapsibleContentAnimated = styled(Collapsible.Content, {- overflow: "hidden",- '&[data-state="open"]': {- animation: `${openKeyframes} 150ms ease-in-out`,- },- '&[data-state="closed"]': {- animation: `${closeKeyframes} 150ms ease-in-out`,- },-});--const CollapsibleContentUnanimated = styled(Collapsible.Content, {- overflow: "hidden",-});--type NodeProps = {- instance: Instance;- selectedInstanceId: Instance["id"] | undefined;- selectedInstancePath: Array<Instance>;- level: number;- onSelect: (instance: Instance) => void;- animate: boolean;-} & ExpandState;--// eslint-disable-next-line react/display-name-const Node = forwardRef<HTMLDivElement, NodeProps>(- ({ instance, level, ...commonProps }, ref) => {- const {- getIsExpanded,- animate,- setIsExpanded,- selectedInstanceId,- onSelect,- selectedInstancePath,- } = commonProps;-- const isExpandable = getIsExpandable(instance);- const isExpanded =- getIsExpanded(instance) ||- selectedInstancePath.some((item) => item.id === instance.id);- const isSelected = instance.id === selectedInstanceId;-- const { Icon, label } = components[instance.component];-- const CollapsibleContent = animate- ? CollapsibleContentAnimated- : CollapsibleContentUnanimated;-- return (- <Collapsible.Root- ref={ref}- open={isExpanded}- onOpenChange={(isOpen: boolean) => setIsExpanded(instance.id, isOpen)}- data-drop-target-id={instance.id}- >- <Flex- css={{- // @todo don't hardcode the padding- paddingLeft: level * 15 + (isExpandable ? 0 : 15),- color: "$hiContrast",- alignItems: "center",- }}- >- {isExpandable && (- <Collapsible.Trigger asChild>- {isExpanded ? <TriangleDownIcon /> : <TriangleRightIcon />}- </Collapsible.Trigger>- )}- <Button- {...(isSelected ? { state: "active" } : { ghost: true })}- css={{ display: "flex", gap: "$1", padding: "$1" }}- data-drag-item-id={instance.id}- onFocus={() => onSelect(instance)}- >- <Icon />- <Text size="1">{label}</Text>- </Button>- </Flex>- {isExpandable && (isExpanded || animate) && (- <CollapsibleContent>- {instance.children.flatMap((child) =>- typeof child === "string"- ? []- : [- <Node- key={child.id}- instance={child}- level={level + 1}- {...commonProps}- />,- ]- )}- </CollapsibleContent>- )}- </Collapsible.Root>- );- }-);--type TreeProps = {- root: Instance;- selectedInstanceId?: Instance["id"];- onSelect?: (instance: Instance) => void;- animate?: boolean;-};--// eslint-disable-next-line react/display-name-const BaseTree = forwardRef<HTMLDivElement, TreeProps & ExpandState>(- (- {- root,- selectedInstanceId,- onSelect = () => null,- animate = true,- getIsExpanded,- setIsExpanded,- },- ref- ) => {- const selectedInstancePath = useMemo(- () =>- selectedInstanceId !== undefined- ? getInstancePath(root, selectedInstanceId)- : [],- [root, selectedInstanceId]- );- return (- <Node- instance={root}- selectedInstanceId={selectedInstanceId}- selectedInstancePath={selectedInstancePath}- onSelect={onSelect}- animate={animate}- level={0}- getIsExpanded={getIsExpanded}- setIsExpanded={setIsExpanded}- ref={ref}- />- );- }-);+import { BaseTree, TreeProps, useExpandState } from "./base-tree";export const Tree = (props: TreeProps) => {const expandState = useExpandState();return <BaseTree {...props} {...expandState} />;};--export const SortableTree = (- props: TreeProps & {- onDragEnd: (event: {- instanceId: Instance["id"];- dropTarget: { instanceId: Instance["id"]; position: number };- }) => void;- }-) => {- const { root, onDragEnd } = props;-- const expandState = useExpandState();-- 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 = () => {- 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;- },-- swapDropTarget: (dropTarget) => {- if (dragItem === undefined || dropTarget === undefined) {- return getFallbackDropTarget();- }-- if (dropTarget.data.id === root.id) {- return dropTarget;- }-- 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 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) => {- 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>({- elementToData: (element) => {- const dragItemElement = element.closest("[data-drag-item-id]");- if (!(dragItemElement instanceof HTMLElement)) {- return false;- }- const id = dragItemElement.dataset.dragItemId;- if (id === undefined || id === root.id) {- return false;- }- return findInstanceById(root, id) || false;- },- onStart: ({ data }) => {- setDragItem(data);- },- onMove: (point) => {- dropHandlers.handleMove(point);- },- onEnd: ({ 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 (- <>- <BaseTree- {...props}- {...expandState}- animate={props.animate && dropTarget === undefined}- ref={(element) => {- rootRef.current = element;- dragHandlers.rootRef(element);- dropHandlers.rootRef(element);- }}- />- {dropTarget && (- <PlacementIndicator- root={root}- getIsExpanded={expandState.getIsExpanded}- dropTarget={dropTarget}- />- )}- </>- );-};--const PlacementIndicator = ({- root,- dropTarget,- getIsExpanded,-}: {- root: Instance;- getIsExpanded: (instanceId: Instance) => boolean;- dropTarget: DropTarget<Instance>;-}) => {- const depth = useMemo(() => {- // We only need depth if we're rendering a line- if (getIsExpanded(dropTarget.data)) {- return getInstancePath(root, dropTarget.data.id).length;- }- return undefined;- }, [dropTarget.data, getIsExpanded, root]);-- if (depth !== undefined) {- const { placement } = dropTarget;-- // @todo: fix magic numbers- const shift = depth * 15 + 15 + 4;-- return createPortal(- <Box- style={{- top: placement.y - 1,- left: placement.x + shift,- width: placement.length - shift,- height: 2,- }}- css={{- boxSizing: "content-box",- position: "absolute",- background: "#f531b3",- pointerEvents: "none",- }}- >- <Box- css={{- // @todo: fix magic numbers- width: 8,- height: 8,- top: -3,- left: -7,- position: "absolute",- border: "solid 2px #f531b3",- borderRadius: "50%",- }}- />- </Box>,- document.body- );- }-- const { rect } = dropTarget;-- return createPortal(- <Box- style={{- top: rect.top,- left: rect.left,- width: rect.width,- height: rect.height,- }}- css={{- position: "absolute",- pointerEvents: "none",- outline: "2px solid #f531b3",- borderRadius: 6,- }}- />,- document.body- );-};--const getIsExpandable = (instance: Instance) => {- return (- // Text nodes have only one child which is a string.- instance.children.length > 1 || typeof instance.children[0] === "object"- );-};--type ExpandState = {- getIsExpanded: (instance: Instance) => boolean;- setIsExpanded: (instanceId: Instance["id"], expanded: boolean) => void;-};--const useExpandState = (): ExpandState => {- const [record, setRecord] = useState<Record<Instance["id"], boolean>>({});-- const getIsExpanded = useCallback(- (instance: Instance) =>- getIsExpandable(instance) && record[instance.id] === true,- [record]- );-- const setIsExpanded = useCallback(- (instanceId: Instance["id"], expanded: boolean) => {- setRecord((record) => ({ ...record, [instanceId]: expanded }));- },- []- );-- return { getIsExpanded, setIsExpanded };-};diff --git a/apps/designer/app/designer/shared/tree/tree2.tsx b/apps/designer/app/designer/shared/tree/tree2.tsxdeleted file mode 100644index 0d29e6ba50..0000000000--- a/apps/designer/app/designer/shared/tree/tree2.tsx+++ /dev/null@@ -1,221 +0,0 @@-/* eslint-disable */--// @todo: enable eslint-// @todo: delete file if not used--import { useState, useMemo, useCallback, useRef } from "react";-import { type Instance, components } from "@webstudio-is/react-sdk";-import {- Flex,- Text,- Button,- type DropTarget,- type Point,- useAutoScroll,- useDrag,- useDrop,-} from "@webstudio-is/design-system";-import { TriangleRightIcon, TriangleDownIcon } from "@webstudio-is/icons";-import { getInstancePath } from "~/shared/tree-utils";--type FlatNode = {- instance: Instance;- depth: number;- isOpen: boolean;- areParentsOpen: boolean;-- // @todo: remove if not needed- indexWithinVisible: number;-};--const flattenTree = (- root: Instance,- isOpenRecord: Record<Instance["id"], boolean | undefined>,- selectedInstancePath: Instance[]-) => {- let indexWithinVisible = 0;- const result: Array<FlatNode> = [];-- const traverse = (- instance: Instance,- depth: number,- areParentsOpen: boolean- ) => {- const isOpen =- (isOpenRecord[instance.id] ?? false) ||- selectedInstancePath.some((item) => item.id === instance.id);-- result.push({- instance,- depth,- indexWithinVisible,- isOpen,- areParentsOpen,- });-- if (areParentsOpen) {- indexWithinVisible++;- }-- for (const child of instance.children) {- if (typeof child === "string") {- continue;- }- traverse(child, depth + 1, isOpen && areParentsOpen);- }- };-- traverse(root, 0, true);- return result;-};--const Node = ({- instance,- depth,- isOpen,- isSelected,- onSelect,- setOpen,- areParentsOpen,-}: FlatNode & {- isSelected: boolean;- onSelect: (instance: Instance) => void;- setOpen: (id: Instance["id"], open: boolean) => void;-}) => {- if (!areParentsOpen) {- return null;- }-- const hasChildren =- instance.children.length > 1 || typeof instance.children[0] === "object";-- const { Icon, label } = components[instance.component];-- return (- <Flex- css={{- // @todo don't hardcode the padding- paddingLeft: depth * 15 + (hasChildren ? 0 : 15),- color: "$hiContrast",- alignItems: "center",- }}- >- {hasChildren && (- <Button- css={{ padding: 0 }}- ghost- onClick={() => setOpen(instance.id, !isOpen)}- >- {isOpen ? <TriangleDownIcon /> : <TriangleRightIcon />}- </Button>- )}- <Button- {...(isSelected ? { state: "active" } : { ghost: true })}- css={{ display: "flex", gap: "$1", padding: "$1" }}- onFocus={() => onSelect(instance)}- data-drag-item-id={instance.id}- >- <Icon />- <Text>{label}</Text>- </Button>- </Flex>- );-};--type TreeProps = {- root: Instance;- selectedInstanceId?: Instance["id"];- onSelect?: (instance: Instance) => void;-- // @todo: add animation support- animate?: boolean;-};--export const Tree = ({- root,- selectedInstanceId,- onSelect = () => null,-}: TreeProps) => {- const [isOpen, setOpen] = useRecordState<boolean>({});-- const flatTree = useMemo(() => {- return flattenTree(- root,- isOpen,- selectedInstanceId !== undefined- ? getInstancePath(root, selectedInstanceId)- : []- );- }, [root, isOpen, selectedInstanceId]);-- const rootRef = useRef<HTMLDivElement | null>(null);-- // All we use from useDrop is just the index?- const dropHandlers = useDrop<true>({- elementToData: (element) => {- return element === rootRef.current;- },- swapDropTarget: (dropTarget) => {- if (dropTarget) {- return dropTarget;- }- return { element: rootRef.current as Element, data: true };- },- onDropTargetChange: (dropTarget) => {- console.log("onDropTargetChange", dropTarget);- },- });-- const dragHandlers = useDrag<Instance["id"]>({- elementToData: (element) => {- const dragItemElement = element.closest("[data-drag-item-id]");- if (!(dragItemElement instanceof HTMLElement)) {- return false;- }- const id = dragItemElement.dataset.dragItemId;- if (id === undefined || id === root.id) {- return false;- }- return id;- },- onStart: ({ data }) => {- console.log("drag start", data);- },- onMove: (point) => {- dropHandlers.handleMove(point);- },- onEnd: ({ isCanceled }) => {- dropHandlers.handleEnd();- },- });-- return (- <Flex- direction="column"- ref={(element) => {- rootRef.current = element;- dropHandlers.rootRef(element);- dragHandlers.rootRef(element);- }}- >- {flatTree.map((node) => (- <Node- {...node}- isSelected={selectedInstanceId === node.instance.id}- onSelect={onSelect}- setOpen={setOpen}- key={node.instance.id}- />- ))}- </Flex>- );-};--const useRecordState = <T,>(initialState: Record<string, T>) => {- const [state, setState] =- useState<Record<string, T | undefined>>(initialState);- const setItem = useCallback((key: string, value: T) => {- setState((state) => ({ ...state, [key]: value }));- }, []);- return [state, setItem] as const;-};diff --git a/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx b/packages/design-system/src/components/primitives/dnd/canvas.stories.tsxindex 0e835d4746..1a6267dae1 100644--- a/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx+++ b/packages/design-system/src/components/primitives/dnd/canvas.stories.tsx@@ -262,6 +262,7 @@ export const Canvas = () => {onStart({ data: id }) {setDragItemId(id);autoScrollHandlers.setEnabled(true);+ dropHandlers.handleStart();},onMove: (point) => {dropHandlers.handleMove(point);diff --git a/packages/design-system/src/components/primitives/dnd/geometry-utils.test.ts b/packages/design-system/src/components/primitives/dnd/geometry-utils.test.tsindex 5a963473a1..11ceff2cae 100644--- a/packages/design-system/src/components/primitives/dnd/geometry-utils.test.ts+++ b/packages/design-system/src/components/primitives/dnd/geometry-utils.test.ts@@ -8,7 +8,13 @@ describe("getPlacementBetween", () => {// [a] | [b]{ top: 0, left: 0 },{ top: 0, left: 200 },- { direction: "vertical", x: 150, y: 0, length: 100 },+ {+ type: "between-children",+ direction: "vertical",+ x: 150,+ y: 0,+ length: 100,+ },],[@@ -17,7 +23,13 @@ describe("getPlacementBetween", () => {// [b]{ top: 0, left: 0 },{ top: 200, left: 0 },- { direction: "horizontal", x: 0, y: 150, length: 100 },+ {+ type: "between-children",+ direction: "horizontal",+ x: 0,+ y: 150,+ length: 100,+ },],[diff --git a/packages/design-system/src/components/primitives/dnd/geometry-utils.ts b/packages/design-system/src/components/primitives/dnd/geometry-utils.tsindex f1a24f0f02..9b585a34ad 100644--- a/packages/design-system/src/components/primitives/dnd/geometry-utils.ts+++ b/packages/design-system/src/components/primitives/dnd/geometry-utils.ts@@ -12,6 +12,7 @@ export type ChildrenOrientation =| { type: "mixed"; reverse?: boolean };export type Placement = {+ type: "between-children" | "next-to-child" | "inside-parent";x: number;y: number;length: number;@@ -95,6 +96,7 @@ export const getPlacementBetween = (const minX = Math.min(a.left, b.left);const maxX = Math.max(a.left + a.width, b.left + b.width);return {+ type: "between-children",y: firstY.top + firstY.height + distanceY / 2,x: minX,length: maxX - minX,@@ -105,6 +107,7 @@ export const getPlacementBetween = (const minY = Math.min(a.top, b.top);const maxY = Math.max(a.top + a.height, b.top + b.height);return {+ type: "between-children",y: minY,x: firstX.left + firstX.width + distanceX / 2,length: maxY - minY,@@ -141,6 +144,7 @@ export const getPlacementNextTo = (if (side === "top") {return {+ type: "next-to-child",x: rect.left,y: rect.top - getMargin(rect.top),length: rect.width,@@ -150,6 +154,7 @@ export const getPlacementNextTo = (if (side === "bottom") {return {+ type: "next-to-child",x: rect.left,y:rect.top +@@ -162,6 +167,7 @@ export const getPlacementNextTo = (if (side === "left") {return {+ type: "next-to-child",x: rect.left - getMargin(rect.left),y: rect.top,length: rect.height,@@ -170,6 +176,7 @@ export const getPlacementNextTo = (}return {+ type: "next-to-child",x:rect.left +rect.width +@@ -188,6 +195,7 @@ export const getPlacementInside = (if (childrenOrientation.type === "horizontal") {const safePadding = Math.min(parentRect.width / 2, padding);return {+ type: "inside-parent",y: parentRect.top + safePadding,x: parentRect.left + safePadding,length: parentRect.height - safePadding * 2,@@ -197,6 +205,7 @@ export const getPlacementInside = (const safePadding = Math.min(parentRect.height / 2, padding);return {+ type: "inside-parent",y: parentRect.top + safePadding,x: parentRect.left + safePadding,length: parentRect.width - safePadding * 2,diff --git a/packages/design-system/src/components/primitives/dnd/index.ts b/packages/design-system/src/components/primitives/dnd/index.tsindex c519d8370e..e4e1a5075e 100644--- a/packages/design-system/src/components/primitives/dnd/index.ts+++ b/packages/design-system/src/components/primitives/dnd/index.ts@@ -2,4 +2,5 @@ export * from "./use-drag";export * from "./use-drop";export * from "./use-auto-scroll";export * from "./placement-indicator";+export * from "./use-hold";export { type Rect, type Point } from "./geometry-utils";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 b81e6555bf..b62e1a1636 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@@ -98,6 +98,7 @@ export const SortableList = ({onStart(event) {setDragItemId(event.target.dataset.id);autoScrollHandlers.setEnabled(true);+ useDropHandlers.handleStart();},onMove: (point) => {useDropHandlers.handleMove(point);diff --git a/packages/design-system/src/components/primitives/dnd/use-drop.ts b/packages/design-system/src/components/primitives/dnd/use-drop.tsindex e716d3ec51..e1ac984e40 100644--- a/packages/design-system/src/components/primitives/dnd/use-drop.ts+++ b/packages/design-system/src/components/primitives/dnd/use-drop.ts@@ -72,12 +72,15 @@ export type UseDropProps<Data> = {export type UseDropHandlers = {handleMove: (pointerCoordinates: Point) => void;handleScroll: () => void;+ handleStart: () => void;handleEnd: () => void;rootRef: (target: Element | null) => void;+ handleDomMutation: () => void;};const getInitialState = <Data>() => {return {+ started: false,pointerCoordinates: undefined as Point | undefined,dropTarget: undefined as DropTarget<Data> | undefined,childrenRectsCache: new WeakMap<Element, Rect[]>(),@@ -203,6 +206,10 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {swapDropTarget,} = latestProps.current;+ if (state.current.started === false) {+ return;+ }+const { pointerCoordinates } = state.current;const root = rootRef.current;@@ -288,6 +295,10 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {detectTarget();},+ handleStart() {+ state.current.started = true;+ },+handleEnd() {state.current = getInitialState();},@@ -295,6 +306,12 @@ export const useDrop = <Data>(props: UseDropProps<Data>): UseDropHandlers => {rootRef(rootElement) {rootRef.current = rootElement;},++ handleDomMutation() {+ state.current.childrenRectsCache = new WeakMap();+ state.current.lastCandidateElement = undefined;+ detectTarget();+ },};}, []);};diff --git a/packages/design-system/src/components/primitives/dnd/use-hold.ts b/packages/design-system/src/components/primitives/dnd/use-hold.tsnew file mode 100644index 0000000000..e1e3acb530--- /dev/null+++ b/packages/design-system/src/components/primitives/dnd/use-hold.ts@@ -0,0 +1,47 @@+import { useMemo, useRef } from "react";++export type UseHoldProps<Data> = {+ isEqual: (a: Data, b: Data) => boolean;+ holdTimeThreshold: number;+ onHold: (data: Data) => void;+};++// Detects when a piece of data stays the same for a given amount of time+export const useHold = <Data>(props: UseHoldProps<Data>) => {+ const state = useRef({+ currentData: undefined as Data | undefined,+ timeoutId: undefined as NodeJS.Timeout | undefined,+ });++ // We want to use fresh props every time we use them,+ // but we don't need to react to updates.+ // So we can put them in a ref and make useMemo below very efficient.+ const latestProps = useRef<UseHoldProps<Data>>(props);++ // We want to return a stable object to avoid re-renders when it's a dependency+ return useMemo(+ () => ({+ setData(data: Data) {+ const { currentData } = state.current;+ const { isEqual, holdTimeThreshold } = latestProps.current;++ if (currentData !== undefined && isEqual(currentData, data)) {+ return;+ }++ clearTimeout(state.current.timeoutId);++ state.current.timeoutId = setTimeout(() => {+ state.current.timeoutId = undefined;+ latestProps.current.onHold(data);+ }, holdTimeThreshold);+ },++ reset() {+ clearTimeout(state.current.timeoutId);+ state.current = { currentData: undefined, timeoutId: undefined };+ },+ }),+ []+ );+};