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.

move tree to design-system (wip)

Roman Pominov8d31832499a7
diff --git a/apps/designer/app/canvas/shared/instance.ts b/apps/designer/app/canvas/shared/instance.ts
index d3f6d40608..ad6249ee29 100644
--- a/apps/designer/app/canvas/shared/instance.ts
+++ b/apps/designer/app/canvas/shared/instance.ts
@@ -62,8 +62,8 @@ export const findInsertLocation = (
const path = getInstancePathWithPositions(rootInstance, selectedInstanceId);
path.reverse();
- const parentIndex = path.findIndex(({ instance }) =>
- components[instance.component].canAcceptChild()
+ const parentIndex = path.findIndex(({ item }) =>
+ components[item.component].canAcceptChild()
);
// Just in case selected Instance is not in the tree for some reason.
@@ -72,7 +72,7 @@ export const findInsertLocation = (
}
return {
- parentId: path[parentIndex].instance.id,
+ parentId: path[parentIndex].item.id,
position: parentIndex === 0 ? "end" : path[parentIndex - 1].position + 1,
};
};
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.tsx
index 4bcb55e9b3..2084674370 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
@@ -1,11 +1,45 @@
-import { Flex } from "@webstudio-is/design-system";
-import type { Instance, Publish } from "@webstudio-is/react-sdk";
+import { Flex, Tree, TreeNodeLabel } from "@webstudio-is/design-system";
+import {
+ type Instance,
+ type Publish,
+ components,
+} from "@webstudio-is/react-sdk";
import { useCallback } from "react";
import { useSelectedInstanceData } from "~/designer/shared/nano-states";
-import { Tree } from "~/designer/shared/tree";
import { useRootInstance } from "~/shared/nano-states";
+import {
+ findInstanceById,
+ getInstancePath,
+ getInstancePathWithPositions,
+} from "~/shared/tree-utils";
import { Header } from "../header";
+const tmp = {
+ findItemById: findInstanceById,
+ getItemPath: getInstancePath,
+ getItemPathWithPositions: getInstancePathWithPositions,
+ canBeReparented(item: Instance) {
+ return components[item.component].isInlineOnly !== true;
+ },
+ canAcceptChild(item: Instance) {
+ return components[item.component].canAcceptChild();
+ },
+ getItemChildren(item: Instance) {
+ return item.children.filter(
+ (child) => typeof child !== "string"
+ ) as Instance[];
+ },
+ renderItem(props: { data: Instance; isSelected: boolean }) {
+ const { Icon, label } = components[props.data.component];
+ return (
+ <>
+ <Icon />
+ <TreeNodeLabel isSelected={props.isSelected} text={label} withIcon />
+ </>
+ );
+ },
+};
+
type NavigatorProps = {
publish: Publish;
isClosable?: boolean;
@@ -31,10 +65,19 @@ export const Navigator = ({ publish, isClosable, onClose }: NavigatorProps) => {
dropTarget: { instanceId: Instance["id"]; position: number | "end" };
};
const handleDragEnd = useCallback(
- (payload: ReparentInstancePayload) => {
+ (payload: {
+ itemId: string;
+ dropTarget: { itemId: string; position: number | "end" };
+ }) => {
publish<"reparentInstance", ReparentInstancePayload>({
type: "reparentInstance",
- payload,
+ payload: {
+ instanceId: payload.itemId,
+ dropTarget: {
+ instanceId: payload.dropTarget.itemId,
+ position: payload.dropTarget.position,
+ },
+ },
});
},
[publish]
@@ -56,8 +99,9 @@ export const Navigator = ({ publish, isClosable, onClose }: NavigatorProps) => {
<Header title="Navigator" onClose={onClose} isClosable={isClosable} />
<Flex css={{ flexGrow: 1, flexDirection: "column" }}>
<Tree
+ {...tmp}
root={rootInstance}
- selectedInstanceId={selectedInstanceData?.id}
+ selectedItemId={selectedInstanceData?.id}
onSelect={handleSelect}
onDragEnd={handleDragEnd}
onDelete={handleDelete}
diff --git a/apps/designer/app/designer/features/tree-preview/tree-preview.tsx b/apps/designer/app/designer/features/tree-preview/tree-preview.tsx
index 0cb4f169e2..83f63fcaf3 100644
--- a/apps/designer/app/designer/features/tree-preview/tree-preview.tsx
+++ b/apps/designer/app/designer/features/tree-preview/tree-preview.tsx
@@ -1,8 +1,7 @@
import produce from "immer";
-import { type Instance } from "@webstudio-is/react-sdk";
+import { components, type Instance } from "@webstudio-is/react-sdk";
import { useMemo } from "react";
-import { TreeNode } from "~/designer/shared/tree";
-import { Flex } from "@webstudio-is/design-system";
+import { Flex, TreeNode, TreeNodeLabel } from "@webstudio-is/design-system";
import { useRootInstance, useDragAndDropState } from "~/shared/nano-states";
import {
reparentInstanceMutable,
@@ -12,6 +11,23 @@ import {
getInstancePath,
} from "~/shared/tree-utils";
+const tmp = {
+ getItemChildren(item: Instance) {
+ return item.children.filter(
+ (child) => typeof child !== "string"
+ ) as Instance[];
+ },
+ renderItem(props: { data: Instance; isSelected: boolean }) {
+ const { Icon, label } = components[props.data.component];
+ return (
+ <>
+ <Icon />
+ <TreeNodeLabel isSelected={props.isSelected} text={label} withIcon />
+ </>
+ );
+ },
+};
+
export const TreePrevew = () => {
const [rootInstance] = useRootInstance();
const [dragAndDropState] = useDragAndDropState();
@@ -59,8 +75,8 @@ export const TreePrevew = () => {
).map((item) => item.id);
return {
- instance,
- selectedInstanceId: dragItemInstance.id,
+ itemData: instance,
+ selectedItemId: dragItemInstance.id,
getIsExpanded: (instance: Instance) =>
dropTargetPath.includes(instance.id),
animate: false,
@@ -75,7 +91,7 @@ export const TreePrevew = () => {
return (
treeProps && (
<Flex direction="column" css={{ pt: "$1", pb: "$1", width: "100%" }}>
- <TreeNode {...treeProps} />
+ <TreeNode {...tmp} {...treeProps} />
</Flex>
)
);
diff --git a/apps/designer/app/designer/shared/tree/tree.stories.tsx b/apps/designer/app/designer/shared/tree/tree.stories.tsx
deleted file mode 100644
index 099423f130..0000000000
--- a/apps/designer/app/designer/shared/tree/tree.stories.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import { ComponentMeta } from "@storybook/react";
-import { Instance } from "@webstudio-is/react-sdk";
-import { useState } from "react";
-import produce from "immer";
-import { createInstance, reparentInstanceMutable } from "~/shared/tree-utils";
-import { Tree } from "./tree";
-import { Flex } from "@webstudio-is/design-system";
-
-export const StressTest = ({ animate }: { animate: boolean }) => {
- const [root, setRoot] = useState<Instance>(() => {
- return createInstance({
- component: "Body",
- children: Array.from({ length: 100 }, () =>
- createInstance({
- component: "Box",
- children: [
- createInstance({ component: "Heading" }),
- createInstance({ component: "Paragraph" }),
- createInstance({
- component: "Box",
- children: [
- createInstance({
- component: "Box",
- children: [
- createInstance({
- component: "Box",
- children: [
- createInstance({ component: "Heading" }),
- createInstance({ component: "Paragraph" }),
- ],
- }),
- ],
- }),
- createInstance({ component: "Box" }),
- ],
- }),
- ],
- })
- ),
- });
- });
-
- const [selectedInstanceId, setSelectedInstanceId] = useState<
- string | undefined
- >();
-
- return (
- <Flex css={{ width: 300, height: 500, flexDirection: "column" }}>
- <Tree
- animate={animate}
- root={root}
- selectedInstanceId={selectedInstanceId}
- onSelect={(instanceId) => setSelectedInstanceId(instanceId)}
- onDragEnd={(payload) =>
- setRoot(
- produce((draft) =>
- reparentInstanceMutable(
- draft,
- payload.instanceId,
- payload.dropTarget.instanceId,
- payload.dropTarget.position
- )
- )
- )
- }
- onDelete={() => null}
- />
- </Flex>
- );
-};
-
-export default {
- args: { animate: true },
-} as ComponentMeta<typeof Tree>;
diff --git a/apps/designer/app/designer/shared/tree/tree.test.ts b/apps/designer/app/designer/shared/tree/tree.test.ts
deleted file mode 100644
index 3ae2708276..0000000000
--- a/apps/designer/app/designer/shared/tree/tree.test.ts
+++ /dev/null
@@ -1,302 +0,0 @@
-import { renderHook, act } from "@testing-library/react-hooks";
-import { DropTarget, Placement } from "@webstudio-is/design-system";
-import { Instance } from "@webstudio-is/react-sdk";
-import { createInstance } from "~/shared/tree-utils";
-import { useHorizontalShift } from "./tree";
-
-describe("useHorizontalShift", () => {
- const box1 = createInstance({ component: "Box", id: "box1" });
- const box2 = createInstance({ component: "Box", id: "box2" });
- const box321 = createInstance({ component: "Box", id: "box321" });
- const box32 = createInstance({
- component: "Box",
- children: [box321],
- id: "box32",
- });
- const box31 = createInstance({ component: "Box", id: "box31" });
- const box3 = createInstance({
- component: "Box",
- children: [box31, box32],
- id: "box3",
- });
- const box4 = createInstance({ component: "Box", id: "box4" });
- const heading = createInstance({
- component: "Heading",
- children: [createInstance({ component: "Bold" })],
- id: "heading",
- });
- const box511 = createInstance({ component: "Box", id: "box511" });
- const box51 = createInstance({
- component: "Box",
- id: "box51",
- children: [box511],
- });
- const box52 = createInstance({ component: "Box", id: "box52" });
- const box5 = createInstance({
- component: "Box",
- id: "box5",
- children: [box51, box52],
- });
-
- // Body
- // | Box (box1)
- // | Box (box2)
- // | Box (box3)
- // | | Box (box31)
- // | | Box (box32)
- // | | | Box (box321)
- // | Box (box4)
- // | Heading (heading)
- // | | Bold
- // | Box (box5)
- // | | Box (box51)
- // | | | Box (box511)
- // | | Box (box52)
- const tree = createInstance({
- id: "root",
- component: "Body",
- children: [box1, box2, box3, box4, heading, box5],
- });
-
- const makePlacement = (
- type: Placement["type"] = "next-to-child"
- ): Placement => ({
- type,
- direction: "horizontal",
- x: 0,
- y: 100,
- length: 300,
- });
-
- const makeDrop = ({
- into,
- after,
- placement = makePlacement(),
- }: {
- into: Instance;
- after?: Instance;
- placement?: Placement;
- }): DropTarget<Instance> => ({
- data: into,
- indexWithinChildren:
- after === undefined ? 0 : into.children.indexOf(after) + 1,
- placement,
-
- // not used
- element: null as unknown as HTMLElement,
- rect: null as unknown as DOMRect,
- });
-
- const render = (
- {
- dragItem,
- dropTarget,
- }: {
- dragItem: Instance | undefined;
- dropTarget: DropTarget<Instance> | undefined;
- },
- shift = -1
- ) => {
- const { result } = renderHook(useHorizontalShift, {
- initialProps: {
- dragItem,
- dropTarget,
- root: tree,
- getIsExpanded: (instance) => instance.children.length > 0,
- },
- });
-
- act(() => {
- const [, setHorizontalShift] = result.current;
- setHorizontalShift(shift);
- });
-
- const [shiftedDroptTarget] = result.current;
- return shiftedDroptTarget;
- };
-
- test("if there's no dragItem or dropTarget returns undefined", () => {
- const result = render({
- dragItem: undefined,
- dropTarget: undefined,
- });
- expect(result).toBeUndefined();
- });
-
- test("drop target is empty or collapsed", () => {
- const dropTarget = makeDrop({
- into: box2,
- placement: makePlacement("inside-parent"),
- });
- const result = render({ dragItem: box1, dropTarget });
-
- // parent doesn't change
- expect(result?.instance.id).toBe(box2.id);
-
- // placement line geometry isn't provided
- expect(result?.placement).toBeUndefined();
- });
-
- test("placement line coordinates are always adjusted", () => {
- const result = render(
- { dragItem: box31, dropTarget: makeDrop({ into: box3, after: box32 }) },
- 0
- );
-
- // parent doesn't change
- expect(result?.instance.id).toBe(box3.id);
-
- // placement line is adjusted to account for depth,
- // even though depth didn't change
- expect(result?.placement).toEqual({
- ...makePlacement(),
- length: 260,
- x: 40,
- });
- });
-
- test("shifting is relative to the drag item's depth", () => {
- // same shift and drop target
- const shift = 0;
- const dropTarget = makeDrop({ into: tree, after: box3 });
-
- // box2's depth is 1, so it's inserted without shifting
- const result1 = render({ dragItem: box2, dropTarget }, shift);
- expect(result1?.instance.id).toBe(tree.id);
-
- // box31's depth is 2, so it's inserted with shifting, to maintain the same depth
- const result2 = render({ dragItem: box31, dropTarget }, shift);
- expect(result2?.instance.id).toBe(box3.id);
- expect(result2?.position).toBe("end");
- });
-
- describe("shifting to the left", () => {
- test("if we're already at the root, no shift occurs", () => {
- const result = render(
- { dragItem: box1, dropTarget: makeDrop({ into: tree, after: box2 }) },
- -1
- );
- expect(result?.instance.id).toBe(tree.id);
- });
-
- test("a shifting is possible only when we're at the bottom of the initial drop target", () => {
- const result1 = render(
- { dragItem: box1, dropTarget: makeDrop({ into: box3, after: box31 }) },
- -1
- );
- expect(result1?.instance.id).toBe(box3.id);
- });
-
- test("when above the drag item, which is at the bottom, the shift is allowed", () => {
- const result = render(
- { dragItem: box32, dropTarget: makeDrop({ into: box3, after: box31 }) },
- -1
- );
- expect(result?.instance.id).toBe(tree.id);
- expect(result?.position).toBe(tree.children.indexOf(box3) + 1);
- expect(result?.placement).toEqual({
- ...makePlacement(),
- x: 24,
- length: 276,
- });
- });
-
- test("shifting by different ammounts works correctly", () => {
- const args = {
- dragItem: box1,
- dropTarget: makeDrop({ into: box32, after: box321 }),
- };
-
- const result1 = render(args, 0);
- expect(result1?.instance.id).toBe(tree.id);
- expect(result1?.position).toBe(tree.children.indexOf(box3) + 1);
- expect(result1?.placement).toEqual({
- ...makePlacement(),
- x: 24,
- length: 276,
- });
-
- const result2 = render(args, 1);
- expect(result2?.instance.id).toBe(box3.id);
- expect(result2?.position).toBe(box3.children.indexOf(box32) + 1);
- expect(result2?.placement).toEqual({
- ...makePlacement(),
- x: 40,
- length: 260,
- });
- });
-
- test('the "at the bottom" check is perforamed at every step, dissalowing futher shifting when we\'re no longer at the bottom', () => {
- const result = render(
- {
- dragItem: box1,
- dropTarget: makeDrop({ into: box51, after: box511 }),
- },
- -10
- );
- expect(result?.instance.id).toBe(box5.id);
- expect(result?.position).toBe(box5.children.indexOf(box51) + 1);
- });
- });
-
- describe("shifting to the right ", () => {
- test("if there's no expanded item above, no shift occurs", () => {
- const result = render(
- { dragItem: box1, dropTarget: makeDrop({ into: tree, after: box2 }) },
- 1
- );
- expect(result?.instance.id).toBe(tree.id);
- });
-
- test("if there's an expanded item above, we shift inside it", () => {
- const args = {
- dragItem: box1,
- dropTarget: makeDrop({ into: tree, after: box3 }),
- };
-
- const result1 = render(args, 1);
- expect(result1?.instance.id).toBe(box3.id);
-
- const result2 = render(args, 2);
- expect(result2?.instance.id).toBe(box32.id);
- });
-
- test("you cannot move inside drag item by shifting", () => {
- // drag item is right above, no shifting
- const result1 = render(
- { dragItem: box3, dropTarget: makeDrop({ into: tree, after: box3 }) },
- 3
- );
- expect(result1?.instance.id).toBe(tree.id);
-
- // drag item is inside the item above
- // we shift into the item above, but not inside the drag item
- const result2 = render(
- { dragItem: box32, dropTarget: makeDrop({ into: tree, after: box3 }) },
- 3
- );
- expect(result2?.instance.id).toBe(box3.id);
- expect(result2?.position).toBe("end");
- });
-
- test("when the item above is the drag item itself, we consider the item above it as a potential target", () => {
- const result = render(
- { dragItem: box4, dropTarget: makeDrop({ into: tree, after: box4 }) },
- 1
- );
- expect(result?.instance.id).toBe(box3.id);
- expect(result?.position).toBe("end");
- });
-
- test("if there's an expanded item above, but it cannot accept shildren, no shift occurs", () => {
- const result = render(
- {
- dragItem: box1,
- dropTarget: makeDrop({ into: tree, after: heading }),
- },
- 1
- );
- expect(result?.instance.id).toBe(tree.id);
- });
- });
-});
diff --git a/apps/designer/app/shared/tree-utils/get-instance-path.test.ts b/apps/designer/app/shared/tree-utils/get-instance-path.test.ts
index 93c1086919..c69fef0010 100644
--- a/apps/designer/app/shared/tree-utils/get-instance-path.test.ts
+++ b/apps/designer/app/shared/tree-utils/get-instance-path.test.ts
@@ -74,8 +74,8 @@ describe("Get instance path", () => {
});
const getIdAndPosition = (
- array: Array<{ instance: { id: string }; position: number }>
-) => array.map((item) => [item.instance.id, item.position]);
+ array: Array<{ item: { id: string }; position: number }>
+) => array.map((item) => [item.item.id, item.position]);
describe("Get instance path with positions", () => {
test("single possible path", () => {
diff --git a/apps/designer/app/shared/tree-utils/get-instance-path.ts b/apps/designer/app/shared/tree-utils/get-instance-path.ts
index 44f0c4e58b..546d571a27 100644
--- a/apps/designer/app/shared/tree-utils/get-instance-path.ts
+++ b/apps/designer/app/shared/tree-utils/get-instance-path.ts
@@ -38,14 +38,14 @@ export const getInstancePathWithPositions = (
if (typeof child === "string") continue;
const found = find(child);
if (found) {
- path.push({ instance: child, position: i });
+ path.push({ item: child, position: i });
return true;
}
}
};
if (find(instance)) {
- path.push({ instance, position: 0 });
+ path.push({ item: instance, position: 0 });
}
return path.reverse();
diff --git a/apps/designer/app/designer/shared/tree/index.ts b/packages/design-system/src/components/tree/index.ts
similarity index 100%
rename from apps/designer/app/designer/shared/tree/index.ts
rename to packages/design-system/src/components/tree/index.ts
diff --git a/apps/designer/app/designer/shared/tree/placement-indicator.tsx b/packages/design-system/src/components/tree/placement-indicator.tsx
similarity index 92%
rename from apps/designer/app/designer/shared/tree/placement-indicator.tsx
rename to packages/design-system/src/components/tree/placement-indicator.tsx
index b2ea7e8c70..0031e7bcb9 100644
--- a/apps/designer/app/designer/shared/tree/placement-indicator.tsx
+++ b/packages/design-system/src/components/tree/placement-indicator.tsx
@@ -1,4 +1,6 @@
-import { Box, Placement, styled } from "@webstudio-is/design-system";
+import { styled } from "~/stitches.config";
+import { Box } from "../box";
+import { Placement } from "../primitives/dnd";
const CIRCLE_SIZE = 8;
const LINE_THICKNESS = 2;
diff --git a/apps/designer/app/designer/shared/tree/tree-node.tsx b/packages/design-system/src/components/tree/tree-node.tsx
similarity index 74%
rename from apps/designer/app/designer/shared/tree/tree-node.tsx
rename to packages/design-system/src/components/tree/tree-node.tsx
index 884889cb89..61de919499 100644
--- a/apps/designer/app/designer/shared/tree/tree-node.tsx
+++ b/packages/design-system/src/components/tree/tree-node.tsx
@@ -1,14 +1,10 @@
import { useCallback, useRef, useEffect } from "react";
-import { type Instance, components } from "@webstudio-is/react-sdk";
-import {
- Flex,
- Text,
- Collapsible,
- keyframes,
- styled,
- Box,
-} from "@webstudio-is/design-system";
import { TriangleRightIcon, TriangleDownIcon } from "@webstudio-is/icons";
+import { keyframes, styled } from "~/stitches.config";
+import { Box } from "../box";
+import * as Collapsible from "@radix-ui/react-collapsible";
+import { Flex } from "../flex";
+import { Text } from "../text";
export const INDENT = 16;
const ITEM_HEIGHT = 32;
@@ -19,13 +15,6 @@ export const getPlacementIndicatorAlignment = (depth: number) => {
return depth * INDENT + ITEM_PADDING;
};
-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 ItemButton = styled("button", {
all: "unset",
display: "flex",
@@ -142,66 +131,59 @@ const ItemWrapper = styled(Flex, {
},
});
-const Label = styled(Text, {
- whiteSpace: "nowrap",
- overflow: "hidden",
- textOverflow: "ellipsis",
- lineHeight: 1.4,
- flexBasis: 0,
- flexGrow: 1,
- ml: "$1",
+type TreeNodeProps<Data extends { id: string }> = {
+ itemData: Data;
+ getItemChildren: (item: Data) => Data[];
+ renderItem: (props: { data: Data; isSelected: boolean }) => React.ReactNode;
- // For some reason flexBasis:0 is not enough
- // to stop it growing past the container
- width: 0,
-});
+ getIsExpanded: (item: Data) => boolean;
+ setIsExpanded?: (item: Data, expanded: boolean) => void;
+ onExpandTransitionEnd?: () => void;
-type TreeNodeProps = {
- instance: Instance;
- selectedInstanceId?: Instance["id"];
+ selectedItemId?: string;
parentIsSelected?: boolean;
+ onSelect?: (itemId: string) => void;
+
level?: number;
- onSelect?: (instanceId: Instance["id"]) => void;
animate?: boolean;
- getIsExpanded: (instance: Instance) => boolean;
- setIsExpanded?: (instance: Instance, expanded: boolean) => void;
- onExpandTransitionEnd?: () => void;
- forceHoverStateAtItem?: Instance["id"];
+ forceHoverStateAtItem?: string;
};
-export const TreeNode = ({
- instance,
+export const TreeNode = <Data extends { id: string }>({
+ itemData,
level = 0,
parentIsSelected,
...commonProps
-}: TreeNodeProps) => {
+}: TreeNodeProps<Data>) => {
const {
getIsExpanded,
animate = true,
setIsExpanded,
- selectedInstanceId,
+ selectedItemId,
onSelect,
onExpandTransitionEnd,
forceHoverStateAtItem,
+ renderItem,
+ getItemChildren,
} = commonProps;
const collapsibleContentRef = useRef<HTMLDivElement>(null);
+ const itemChildren = getItemChildren(itemData);
+
const isAlwaysExpanded = level === 0;
- const isExpandable = getIsExpandable(instance);
- const isExpanded = getIsExpanded(instance) || isAlwaysExpanded;
- const isSelected = instance.id === selectedInstanceId;
+ const isExpandable = itemChildren.length > 0;
+ const isExpanded = getIsExpanded(itemData) || isAlwaysExpanded;
+ const isSelected = itemData.id === selectedItemId;
const makeSelected = () => {
if (isSelected === false) {
- onSelect?.(instance.id);
+ onSelect?.(itemData.id);
}
};
const shouldRenderExpandButton = isExpandable && isAlwaysExpanded === false;
- const { Icon, label } = components[instance.component];
-
const CollapsibleContent = animate
? CollapsibleContentAnimated
: CollapsibleContentUnanimated;
@@ -227,14 +209,14 @@ export const TreeNode = ({
return (
<Collapsible.Root
open={isExpanded}
- onOpenChange={(isOpen) => setIsExpanded?.(instance, isOpen)}
- data-drop-target-id={instance.id}
+ onOpenChange={(isOpen) => setIsExpanded?.(itemData, isOpen)}
+ data-drop-target-id={itemData.id}
>
<ItemWrapper
isSelected={isSelected}
parentIsSelected={parentIsSelected}
enableHoverState={forceHoverStateAtItem === undefined}
- forceHoverState={forceHoverStateAtItem === instance.id}
+ forceHoverState={forceHoverStateAtItem === itemData.id}
>
{/* We want the main ItemButton to take the entire space,
* and then position the collapsible trigger on top of it using absolute positionning.
@@ -243,16 +225,13 @@ export const TreeNode = ({
<ItemButton
type="button"
- data-drag-item-id={instance.id}
- data-item-button-id={instance.id}
+ data-drag-item-id={itemData.id}
+ data-item-button-id={itemData.id}
onFocus={makeSelected}
>
<NestingLines isSelected={isSelected} level={level} />
{isAlwaysExpanded === false && <TriggerPlaceholder />}
- <Icon />
- <Label size="1" variant={isSelected ? "loContrast" : "contrast"}>
- {label}
- </Label>
+ {renderItem({ data: itemData, isSelected })}
</ItemButton>
{shouldRenderExpandButton && (
@@ -275,22 +254,53 @@ export const TreeNode = ({
{
// CollapsibleContent doesn't render children when collapsed.
// No need to worry about optimizing this.
- instance.children.flatMap((child) =>
- typeof child === "string"
- ? []
- : [
- <TreeNode
- key={child.id}
- instance={child}
- level={level + 1}
- parentIsSelected={isSelected || parentIsSelected}
- {...commonProps}
- />,
- ]
- )
+ itemChildren.map((child) => (
+ <TreeNode
+ key={child.id}
+ itemData={child}
+ level={level + 1}
+ parentIsSelected={isSelected || parentIsSelected}
+ {...commonProps}
+ />
+ ))
}
</CollapsibleContent>
)}
</Collapsible.Root>
);
};
+
+const Label = styled(Text, {
+ whiteSpace: "nowrap",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
+ lineHeight: 1.4,
+ flexBasis: 0,
+ flexGrow: 1,
+
+ // For some reason flexBasis:0 is not enough
+ // to stop it from growing past the container
+ width: 0,
+
+ variants: {
+ withIcon: { true: { ml: "$1" } },
+ },
+});
+
+export const TreeNodeLabel = ({
+ text,
+ isSelected,
+ withIcon = false,
+}: {
+ text: string;
+ isSelected: boolean;
+ withIcon?: boolean;
+}) => (
+ <Label
+ size="1"
+ variant={isSelected ? "loContrast" : "contrast"}
+ withIcon={withIcon}
+ >
+ {text}
+ </Label>
+);
diff --git a/packages/design-system/src/components/tree/tree.stories.tsx b/packages/design-system/src/components/tree/tree.stories.tsx
new file mode 100644
index 0000000000..da26f63624
--- /dev/null
+++ b/packages/design-system/src/components/tree/tree.stories.tsx
@@ -0,0 +1,76 @@
+// import { ComponentMeta } from "@storybook/react";
+// import { Instance } from "@webstudio-is/react-sdk";
+// import { useState } from "react";
+// import produce from "immer";
+// import { createInstance, reparentInstanceMutable } from "~/shared/tree-utils";
+// import { Tree } from "./tree";
+// import { Flex } from "@webstudio-is/design-system";
+
+// export const StressTest = ({ animate }: { animate: boolean }) => {
+// const [root, setRoot] = useState<Instance>(() => {
+// return createInstance({
+// component: "Body",
+// children: Array.from({ length: 100 }, () =>
+// createInstance({
+// component: "Box",
+// children: [
+// createInstance({ component: "Heading" }),
+// createInstance({ component: "Paragraph" }),
+// createInstance({
+// component: "Box",
+// children: [
+// createInstance({
+// component: "Box",
+// children: [
+// createInstance({
+// component: "Box",
+// children: [
+// createInstance({ component: "Heading" }),
+// createInstance({ component: "Paragraph" }),
+// ],
+// }),
+// ],
+// }),
+// createInstance({ component: "Box" }),
+// ],
+// }),
+// ],
+// })
+// ),
+// });
+// });
+
+// const [selectedInstanceId, setSelectedInstanceId] = useState<
+// string | undefined
+// >();
+
+// return (
+// <Flex css={{ width: 300, height: 500, flexDirection: "column" }}>
+// <Tree
+// animate={animate}
+// root={root}
+// selectedInstanceId={selectedInstanceId}
+// onSelect={(instanceId) => setSelectedInstanceId(instanceId)}
+// onDragEnd={(payload) =>
+// setRoot(
+// produce((draft) =>
+// reparentInstanceMutable(
+// draft,
+// payload.instanceId,
+// payload.dropTarget.instanceId,
+// payload.dropTarget.position
+// )
+// )
+// )
+// }
+// onDelete={() => null}
+// />
+// </Flex>
+// );
+// };
+
+// export default {
+// args: { animate: true },
+// } as ComponentMeta<typeof Tree>;
+
+export const tmp = 1;
diff --git a/packages/design-system/src/components/tree/tree.test.ts b/packages/design-system/src/components/tree/tree.test.ts
new file mode 100644
index 0000000000..31db0cbed9
--- /dev/null
+++ b/packages/design-system/src/components/tree/tree.test.ts
@@ -0,0 +1,304 @@
+// import { renderHook, act } from "@testing-library/react-hooks";
+// import { DropTarget, Placement } from "@webstudio-is/design-system";
+// import { Instance } from "@webstudio-is/react-sdk";
+// import { createInstance } from "~/shared/tree-utils";
+// import { useHorizontalShift } from "./tree";
+
+// describe("useHorizontalShift", () => {
+// const box1 = createInstance({ component: "Box", id: "box1" });
+// const box2 = createInstance({ component: "Box", id: "box2" });
+// const box321 = createInstance({ component: "Box", id: "box321" });
+// const box32 = createInstance({
+// component: "Box",
+// children: [box321],
+// id: "box32",
+// });
+// const box31 = createInstance({ component: "Box", id: "box31" });
+// const box3 = createInstance({
+// component: "Box",
+// children: [box31, box32],
+// id: "box3",
+// });
+// const box4 = createInstance({ component: "Box", id: "box4" });
+// const heading = createInstance({
+// component: "Heading",
+// children: [createInstance({ component: "Bold" })],
+// id: "heading",
+// });
+// const box511 = createInstance({ component: "Box", id: "box511" });
+// const box51 = createInstance({
+// component: "Box",
+// id: "box51",
+// children: [box511],
+// });
+// const box52 = createInstance({ component: "Box", id: "box52" });
+// const box5 = createInstance({
+// component: "Box",
+// id: "box5",
+// children: [box51, box52],
+// });
+
+// // Body
+// // | Box (box1)
+// // | Box (box2)
+// // | Box (box3)
+// // | | Box (box31)
+// // | | Box (box32)
+// // | | | Box (box321)
+// // | Box (box4)
+// // | Heading (heading)
+// // | | Bold
+// // | Box (box5)
+// // | | Box (box51)
+// // | | | Box (box511)
+// // | | Box (box52)
+// const tree = createInstance({
+// id: "root",
+// component: "Body",
+// children: [box1, box2, box3, box4, heading, box5],
+// });
+
+// const makePlacement = (
+// type: Placement["type"] = "next-to-child"
+// ): Placement => ({
+// type,
+// direction: "horizontal",
+// x: 0,
+// y: 100,
+// length: 300,
+// });
+
+// const makeDrop = ({
+// into,
+// after,
+// placement = makePlacement(),
+// }: {
+// into: Instance;
+// after?: Instance;
+// placement?: Placement;
+// }): DropTarget<Instance> => ({
+// data: into,
+// indexWithinChildren:
+// after === undefined ? 0 : into.children.indexOf(after) + 1,
+// placement,
+
+// // not used
+// element: null as unknown as HTMLElement,
+// rect: null as unknown as DOMRect,
+// });
+
+// const render = (
+// {
+// dragItem,
+// dropTarget,
+// }: {
+// dragItem: Instance | undefined;
+// dropTarget: DropTarget<Instance> | undefined;
+// },
+// shift = -1
+// ) => {
+// const { result } = renderHook(useHorizontalShift, {
+// initialProps: {
+// dragItem,
+// dropTarget,
+// root: tree,
+// getIsExpanded: (instance) => instance.children.length > 0,
+// },
+// });
+
+// act(() => {
+// const [, setHorizontalShift] = result.current;
+// setHorizontalShift(shift);
+// });
+
+// const [shiftedDroptTarget] = result.current;
+// return shiftedDroptTarget;
+// };
+
+// test("if there's no dragItem or dropTarget returns undefined", () => {
+// const result = render({
+// dragItem: undefined,
+// dropTarget: undefined,
+// });
+// expect(result).toBeUndefined();
+// });
+
+// test("drop target is empty or collapsed", () => {
+// const dropTarget = makeDrop({
+// into: box2,
+// placement: makePlacement("inside-parent"),
+// });
+// const result = render({ dragItem: box1, dropTarget });
+
+// // parent doesn't change
+// expect(result?.instance.id).toBe(box2.id);
+
+// // placement line geometry isn't provided
+// expect(result?.placement).toBeUndefined();
+// });
+
+// test("placement line coordinates are always adjusted", () => {
+// const result = render(
+// { dragItem: box31, dropTarget: makeDrop({ into: box3, after: box32 }) },
+// 0
+// );
+
+// // parent doesn't change
+// expect(result?.instance.id).toBe(box3.id);
+
+// // placement line is adjusted to account for depth,
+// // even though depth didn't change
+// expect(result?.placement).toEqual({
+// ...makePlacement(),
+// length: 260,
+// x: 40,
+// });
+// });
+
+// test("shifting is relative to the drag item's depth", () => {
+// // same shift and drop target
+// const shift = 0;
+// const dropTarget = makeDrop({ into: tree, after: box3 });
+
+// // box2's depth is 1, so it's inserted without shifting
+// const result1 = render({ dragItem: box2, dropTarget }, shift);
+// expect(result1?.instance.id).toBe(tree.id);
+
+// // box31's depth is 2, so it's inserted with shifting, to maintain the same depth
+// const result2 = render({ dragItem: box31, dropTarget }, shift);
+// expect(result2?.instance.id).toBe(box3.id);
+// expect(result2?.position).toBe("end");
+// });
+
+// describe("shifting to the left", () => {
+// test("if we're already at the root, no shift occurs", () => {
+// const result = render(
+// { dragItem: box1, dropTarget: makeDrop({ into: tree, after: box2 }) },
+// -1
+// );
+// expect(result?.instance.id).toBe(tree.id);
+// });
+
+// test("a shifting is possible only when we're at the bottom of the initial drop target", () => {
+// const result1 = render(
+// { dragItem: box1, dropTarget: makeDrop({ into: box3, after: box31 }) },
+// -1
+// );
+// expect(result1?.instance.id).toBe(box3.id);
+// });
+
+// test("when above the drag item, which is at the bottom, the shift is allowed", () => {
+// const result = render(
+// { dragItem: box32, dropTarget: makeDrop({ into: box3, after: box31 }) },
+// -1
+// );
+// expect(result?.instance.id).toBe(tree.id);
+// expect(result?.position).toBe(tree.children.indexOf(box3) + 1);
+// expect(result?.placement).toEqual({
+// ...makePlacement(),
+// x: 24,
+// length: 276,
+// });
+// });
+
+// test("shifting by different ammounts works correctly", () => {
+// const args = {
+// dragItem: box1,
+// dropTarget: makeDrop({ into: box32, after: box321 }),
+// };
+
+// const result1 = render(args, 0);
+// expect(result1?.instance.id).toBe(tree.id);
+// expect(result1?.position).toBe(tree.children.indexOf(box3) + 1);
+// expect(result1?.placement).toEqual({
+// ...makePlacement(),
+// x: 24,
+// length: 276,
+// });
+
+// const result2 = render(args, 1);
+// expect(result2?.instance.id).toBe(box3.id);
+// expect(result2?.position).toBe(box3.children.indexOf(box32) + 1);
+// expect(result2?.placement).toEqual({
+// ...makePlacement(),
+// x: 40,
+// length: 260,
+// });
+// });
+
+// test('the "at the bottom" check is perforamed at every step, dissalowing futher shifting when we\'re no longer at the bottom', () => {
+// const result = render(
+// {
+// dragItem: box1,
+// dropTarget: makeDrop({ into: box51, after: box511 }),
+// },
+// -10
+// );
+// expect(result?.instance.id).toBe(box5.id);
+// expect(result?.position).toBe(box5.children.indexOf(box51) + 1);
+// });
+// });
+
+// describe("shifting to the right ", () => {
+// test("if there's no expanded item above, no shift occurs", () => {
+// const result = render(
+// { dragItem: box1, dropTarget: makeDrop({ into: tree, after: box2 }) },
+// 1
+// );
+// expect(result?.instance.id).toBe(tree.id);
+// });
+
+// test("if there's an expanded item above, we shift inside it", () => {
+// const args = {
+// dragItem: box1,
+// dropTarget: makeDrop({ into: tree, after: box3 }),
+// };
+
+// const result1 = render(args, 1);
+// expect(result1?.instance.id).toBe(box3.id);
+
+// const result2 = render(args, 2);
+// expect(result2?.instance.id).toBe(box32.id);
+// });
+
+// test("you cannot move inside drag item by shifting", () => {
+// // drag item is right above, no shifting
+// const result1 = render(
+// { dragItem: box3, dropTarget: makeDrop({ into: tree, after: box3 }) },
+// 3
+// );
+// expect(result1?.instance.id).toBe(tree.id);
+
+// // drag item is inside the item above
+// // we shift into the item above, but not inside the drag item
+// const result2 = render(
+// { dragItem: box32, dropTarget: makeDrop({ into: tree, after: box3 }) },
+// 3
+// );
+// expect(result2?.instance.id).toBe(box3.id);
+// expect(result2?.position).toBe("end");
+// });
+
+// test("when the item above is the drag item itself, we consider the item above it as a potential target", () => {
+// const result = render(
+// { dragItem: box4, dropTarget: makeDrop({ into: tree, after: box4 }) },
+// 1
+// );
+// expect(result?.instance.id).toBe(box3.id);
+// expect(result?.position).toBe("end");
+// });
+
+// test("if there's an expanded item above, but it cannot accept shildren, no shift occurs", () => {
+// const result = render(
+// {
+// dragItem: box1,
+// dropTarget: makeDrop({ into: tree, after: heading }),
+// },
+// 1
+// );
+// expect(result?.instance.id).toBe(tree.id);
+// });
+// });
+// });
+
+export const tmp = 1;
diff --git a/apps/designer/app/designer/shared/tree/tree.tsx b/packages/design-system/src/components/tree/tree.tsx
similarity index 64%
rename from apps/designer/app/designer/shared/tree/tree.tsx
rename to packages/design-system/src/components/tree/tree.tsx
index 694206c865..9edcf1025c 100644
--- a/apps/designer/app/designer/shared/tree/tree.tsx
+++ b/packages/design-system/src/components/tree/tree.tsx
@@ -1,66 +1,72 @@
import { useState, useMemo, useRef, useCallback, useEffect } from "react";
-import {
- type Instance,
- components,
- useSubscribe,
-} from "@webstudio-is/react-sdk";
+import { createPortal } from "react-dom";
+import { useHotkeys } from "react-hotkeys-hook";
+import { TreeNode, getPlacementIndicatorAlignment, INDENT } from "./tree-node";
+import { PlacementIndicator } from "./placement-indicator";
import {
type DropTarget,
type Placement,
- useDrag,
- useDrop,
useHold,
+ useDrop,
+ useDrag,
useAutoScroll,
useDragCursor,
- Box,
-} from "@webstudio-is/design-system";
-import {
- findInstanceById,
- getInstancePath,
- getInstancePathWithPositions,
-} from "~/shared/tree-utils";
-import { createPortal } from "react-dom";
-import {
- TreeNode,
- getIsExpandable,
- getPlacementIndicatorAlignment,
- INDENT,
-} from "./tree-node";
-import { PlacementIndicator } from "./placement-indicator";
-import { useHotkeys } from "react-hotkeys-hook";
-
-type TreeProps = {
- root: Instance;
- selectedInstanceId?: Instance["id"];
- onSelect?: (instanceId: Instance["id"]) => void;
+} from "../primitives/dnd";
+import { Box } from "../box";
+
+type TreeProps<Data extends { id: string }> = {
+ root: Data;
+
+ canBeReparented: (item: Data) => boolean;
+ canAcceptChild: (item: Data) => boolean;
+ findItemById: (root: Data, id: string) => Data | undefined;
+ getItemPath: (root: Data, id: string) => Data[];
+ getItemPathWithPositions: (
+ root: Data,
+ id: string
+ ) => Array<{ item: Data; position: number }>;
+ getItemChildren: (item: Data) => Data[];
+ renderItem: (props: { data: Data; isSelected: boolean }) => React.ReactNode;
+
+ selectedItemId?: string;
+ onSelect?: (itemId: string) => void;
animate?: boolean;
onDragEnd: (event: {
- instanceId: Instance["id"];
- dropTarget: { instanceId: Instance["id"]; position: number | "end" };
+ itemId: string;
+ dropTarget: { itemId: string; position: number | "end" };
}) => void;
- onDelete: (instanceId: Instance["id"]) => void;
+ onDelete: (itemId: string) => void;
};
-export const Tree = ({
+export const Tree = <Data extends { id: string }>({
root,
- selectedInstanceId,
+ getItemPathWithPositions,
+ canBeReparented,
+ canAcceptChild,
+ findItemById,
+ getItemPath,
+ getItemChildren,
+ renderItem,
+ selectedItemId,
onSelect,
animate,
onDragEnd,
onDelete,
-}: TreeProps) => {
+}: TreeProps<Data>) => {
const { getIsExpanded, setIsExpanded } = useExpandState({
root,
- selectedInstanceId,
+ selectedItemId,
+ getItemPath,
+ getItemChildren,
});
const rootRef = useRef<HTMLElement | null>(null);
- const [dragItem, setDragItem] = useState<Instance>();
- const [dropTarget, setDropTarget] = useState<DropTarget<Instance>>();
+ const [dragItem, setDragItem] = useState<Data>();
+ const [dropTarget, setDropTarget] = useState<DropTarget<Data>>();
const getDropTargetElement = useCallback(
- (id: Instance["id"]): HTMLElement | null | undefined =>
+ (id: string): HTMLElement | null | undefined =>
rootRef.current?.querySelector(`[data-drop-target-id="${id}"]`),
[]
);
@@ -70,6 +76,10 @@ export const Tree = ({
dropTarget,
root,
getIsExpanded,
+ getItemPath,
+ getItemPathWithPositions,
+ getItemChildren,
+ canAcceptChild,
});
const getFallbackDropTarget = () => {
@@ -80,12 +90,12 @@ export const Tree = ({
};
};
- const useHoldHandler = useHold<DropTarget<Instance>>({
+ const useHoldHandler = useHold<DropTarget<Data>>({
isEqual: (a, b) => a.data.id === b.data.id,
holdTimeThreshold: 600,
onHold: (dropTarget) => {
if (
- getIsExpandable(dropTarget.data) &&
+ getItemChildren(dropTarget.data).length > 0 ||
getIsExpanded(dropTarget.data) === false
) {
setIsExpanded(dropTarget.data, true);
@@ -93,14 +103,14 @@ export const Tree = ({
},
});
- const dropHandlers = useDrop<Instance>({
+ const dropHandlers = useDrop<Data>({
emulatePointerAlwaysInRootBounds: true,
placementPadding: 0,
elementToData: (element) => {
const id = (element as HTMLElement).dataset.dropTargetId;
- const instance = id && findInstanceById(root, id);
+ const instance = id && findItemById(root, id);
return instance || false;
},
@@ -113,7 +123,7 @@ export const Tree = ({
return dropTarget;
}
- const path = getInstancePath(root, dropTarget.data.id);
+ const path = getItemPath(root, dropTarget.data.id);
path.reverse();
if (dropTarget.area === "top" || dropTarget.area === "bottom") {
@@ -128,9 +138,7 @@ export const Tree = ({
path.splice(0, dragItemIndex + 1);
}
- const data = path.find((instance) =>
- components[instance.component].canAcceptChild()
- );
+ const data = path.find(canAcceptChild);
if (data === undefined) {
return getFallbackDropTarget();
@@ -157,7 +165,7 @@ export const Tree = ({
},
});
- const dragHandlers = useDrag<Instance>({
+ const dragHandlers = useDrag<Data>({
shiftDistanceThreshold: INDENT,
elementToData: (element) => {
@@ -170,13 +178,13 @@ export const Tree = ({
return false;
}
- const instance = findInstanceById(root, id);
+ const instance = findItemById(root, id);
if (instance === undefined) {
return false;
}
- if (components[instance.component].isInlineOnly) {
+ if (canBeReparented(instance) === false) {
return false;
}
@@ -198,9 +206,9 @@ export const Tree = ({
onEnd: ({ isCanceled }) => {
if (shiftedDropTarget && dragItem && isCanceled === false) {
onDragEnd({
- instanceId: dragItem.id,
+ itemId: dragItem.id,
dropTarget: {
- instanceId: shiftedDropTarget.instance.id,
+ itemId: shiftedDropTarget.instance.id,
position: shiftedDropTarget.position,
},
});
@@ -215,20 +223,19 @@ export const Tree = ({
},
});
- useSubscribe("cancelCurrentDrag", () => {
- dragHandlers.cancelCurrentDrag();
- });
-
const autoScrollHandlers = useAutoScroll();
useDragCursor(dragItem !== undefined);
const keyboardNavigation = useKeyboardNavigation({
root,
- selectedInstanceId,
+ getItemChildren,
+ findItemById,
+ selectedItemId,
getIsExpanded,
setIsExpanded,
onDelete,
+ onEsc: dragHandlers.cancelCurrentDrag,
});
return (
@@ -256,10 +263,12 @@ export const Tree = ({
onBlur={keyboardNavigation.handleBlur}
>
<TreeNode
+ renderItem={renderItem}
+ getItemChildren={getItemChildren}
animate={animate}
onSelect={onSelect}
- selectedInstanceId={selectedInstanceId}
- instance={root}
+ selectedItemId={selectedItemId}
+ itemData={root}
level={0}
getIsExpanded={getIsExpanded}
setIsExpanded={setIsExpanded}
@@ -277,76 +286,82 @@ export const Tree = ({
);
};
-const useKeyboardNavigation = ({
+const useKeyboardNavigation = <Data extends { id: string }>({
root,
- selectedInstanceId,
+ getItemChildren,
+ findItemById,
+ selectedItemId,
getIsExpanded,
setIsExpanded,
onDelete,
+ onEsc,
}: {
- root: Instance;
- selectedInstanceId: Instance["id"] | undefined;
- getIsExpanded: (instance: Instance) => boolean;
- setIsExpanded: (instance: Instance, isExpanded: boolean) => void;
- onDelete: (instanceId: Instance["id"]) => void;
+ root: Data;
+ getItemChildren: (item: Data) => Data[];
+ findItemById: (root: Data, id: string) => Data | undefined;
+ selectedItemId: string | undefined;
+ getIsExpanded: (instance: Data) => boolean;
+ setIsExpanded: (instance: Data, isExpanded: boolean) => void;
+ onDelete: (itemId: string) => void;
+ onEsc: () => void;
}) => {
- const selectedInstance = useMemo(() => {
- if (selectedInstanceId === undefined) {
+ const selectedItem = useMemo(() => {
+ if (selectedItemId === undefined) {
return undefined;
}
- return findInstanceById(root, selectedInstanceId);
- }, [root, selectedInstanceId]);
+ return findItemById(root, selectedItemId);
+ }, [root, selectedItemId, findItemById]);
const flatCurrentlyExpandedTree = useMemo(() => {
- const result = [] as Instance["id"][];
- const traverse = (instance: Instance | string) => {
- if (typeof instance === "string") {
- return;
- }
+ const result = [] as string[];
+ const traverse = (instance: Data) => {
result.push(instance.id);
if (getIsExpanded(instance)) {
- instance.children.forEach(traverse);
+ getItemChildren(instance).forEach(traverse);
}
};
traverse(root);
return result;
- }, [root, getIsExpanded]);
+ }, [root, getIsExpanded, getItemChildren]);
const rootRef = useHotkeys(
- "up,down,right,left,space,backspace,delete",
+ "up,down,right,left,space,backspace,delete,esc",
(event, { shortcut }) => {
- if (selectedInstance === undefined) {
+ if (selectedItem === undefined) {
return;
}
- if (shortcut === "right" && getIsExpanded(selectedInstance) === false) {
- setIsExpanded(selectedInstance, true);
+ if (shortcut === "right" && getIsExpanded(selectedItem) === false) {
+ setIsExpanded(selectedItem, true);
}
- if (shortcut === "left" && getIsExpanded(selectedInstance)) {
- setIsExpanded(selectedInstance, false);
+ if (shortcut === "left" && getIsExpanded(selectedItem)) {
+ setIsExpanded(selectedItem, false);
}
if (shortcut === "space") {
- setIsExpanded(selectedInstance, !getIsExpanded(selectedInstance));
+ setIsExpanded(selectedItem, !getIsExpanded(selectedItem));
}
if (shortcut === "up") {
- const index = flatCurrentlyExpandedTree.indexOf(selectedInstance.id);
+ const index = flatCurrentlyExpandedTree.indexOf(selectedItem.id);
if (index > 0) {
setFocus(flatCurrentlyExpandedTree[index - 1], "changing");
event.preventDefault(); // prevent scrolling
}
}
if (shortcut === "down") {
- const index = flatCurrentlyExpandedTree.indexOf(selectedInstance.id);
+ const index = flatCurrentlyExpandedTree.indexOf(selectedItem.id);
if (index < flatCurrentlyExpandedTree.length - 1) {
setFocus(flatCurrentlyExpandedTree[index + 1], "changing");
event.preventDefault(); // prevent scrolling
}
}
if (shortcut === "backspace" || shortcut === "delete") {
- onDelete(selectedInstance.id);
+ onDelete(selectedItem.id);
+ }
+ if (shortcut === "esc") {
+ onEsc();
}
},
[
- selectedInstance,
+ selectedItem,
flatCurrentlyExpandedTree,
getIsExpanded,
setIsExpanded,
@@ -355,9 +370,9 @@ const useKeyboardNavigation = ({
);
const setFocus = useCallback(
- (instanceId: Instance["id"], reason: "restoring" | "changing") => {
+ (itemId: string, reason: "restoring" | "changing") => {
const itemButton = rootRef.current?.querySelector(
- `[data-item-button-id="${instanceId}"]`
+ `[data-item-button-id="${itemId}"]`
);
if (itemButton instanceof HTMLElement) {
itemButton.focus({ preventScroll: reason === "restoring" });
@@ -381,11 +396,11 @@ const useKeyboardNavigation = ({
isRootChanged &&
haveFocus === false &&
hadFocus.current === true &&
- selectedInstanceId !== undefined
+ selectedItemId !== undefined
) {
- setFocus(selectedInstanceId, "restoring");
+ setFocus(selectedItemId, "restoring");
}
- }, [root, rootRef, selectedInstanceId, setFocus]);
+ }, [root, rootRef, selectedItemId, setFocus]);
// onBlur doesn't fire when the activeElement is removed from the DOM
useEffect(() => {
@@ -411,8 +426,8 @@ const useKeyboardNavigation = ({
// When clicking anywhere else in the tree,
// make sure the selected item doesn't loose focus.
- if (selectedInstanceId !== undefined) {
- setFocus(selectedInstanceId, "restoring");
+ if (selectedItemId !== undefined) {
+ setFocus(selectedItemId, "restoring");
}
},
handleBlur() {
@@ -421,31 +436,35 @@ const useKeyboardNavigation = ({
};
};
-const useExpandState = ({
- selectedInstanceId,
+const useExpandState = <Data extends { id: string }>({
+ selectedItemId,
root,
+ getItemPath,
+ getItemChildren,
}: {
- root: Instance;
- selectedInstanceId?: Instance["id"];
+ root: Data;
+ getItemPath: (root: Data, id: string) => Data[];
+ getItemChildren: (item: Data) => Data[];
+ selectedItemId?: string;
}) => {
- const [record, setRecord] = useState<Record<Instance["id"], boolean>>({});
+ const [record, setRecord] = useState<Record<string, boolean>>({});
// We want to automatically expand all parents of the selected instance whenever it changes
- const prevSelectedInstanceId = useRef(selectedInstanceId);
+ const prevSelectedItemId = useRef(selectedItemId);
const prevRoot = useRef(root);
useEffect(() => {
if (
- selectedInstanceId === prevSelectedInstanceId.current &&
+ selectedItemId === prevSelectedItemId.current &&
prevRoot.current === root
) {
return;
}
- prevSelectedInstanceId.current = selectedInstanceId;
+ prevSelectedItemId.current = selectedItemId;
prevRoot.current = root;
- if (selectedInstanceId === undefined) {
+ if (selectedItemId === undefined) {
return;
}
- const path = getInstancePath(root, selectedInstanceId).map(
+ const path = getItemPath(root, selectedItemId).map(
(instance) => instance.id
);
// Don't want to expand the selected instance itself
@@ -461,54 +480,67 @@ const useExpandState = ({
}
return newRecord;
});
- }, [record, root, selectedInstanceId]);
+ }, [record, root, selectedItemId, getItemPath]);
const getIsExpanded = useCallback(
- (instance: Instance) => {
+ (instance: Data) => {
// root is always expanded
if (instance.id === root.id) {
return true;
}
- return getIsExpandable(instance) && record[instance.id] === true;
+ return (
+ getItemChildren(instance).length > 0 && record[instance.id] === true
+ );
},
- [record, root]
+ [record, root, getItemChildren]
);
- const setIsExpanded = useCallback((instance: Instance, expanded: boolean) => {
+ const setIsExpanded = useCallback((instance: Data, expanded: boolean) => {
setRecord((record) => ({ ...record, [instance.id]: expanded }));
}, []);
return { getIsExpanded, setIsExpanded };
};
-export type ShiftedDropTarget = {
- instance: Instance;
+export type ShiftedDropTarget<Data> = {
+ instance: Data;
position: number | "end";
placement?: Placement;
};
-export const useHorizontalShift = ({
+export const useHorizontalShift = <Data extends { id: string }>({
dragItem,
dropTarget,
root,
getIsExpanded,
+ getItemPath,
+ getItemPathWithPositions,
+ canAcceptChild,
+ getItemChildren,
}: {
- dragItem: Instance | undefined;
- dropTarget: DropTarget<Instance> | undefined;
- root: Instance;
- getIsExpanded: (instance: Instance) => boolean;
+ getItemChildren: (item: Data) => Data[];
+ canAcceptChild: (item: Data) => boolean;
+ getItemPath: (root: Data, id: string) => Data[];
+ getItemPathWithPositions: (
+ root: Data,
+ id: string
+ ) => Array<{ item: Data; position: number }>;
+ dragItem: Data | undefined;
+ dropTarget: DropTarget<Data> | undefined;
+ root: Data;
+ getIsExpanded: (instance: Data) => boolean;
}) => {
const [horizontalShift, setHorizontalShift] = useState(0);
const dragItemDepth = useMemo(
- () => dragItem && getInstancePath(root, dragItem.id).length - 1,
- [dragItem, root]
+ () => dragItem && getItemPath(root, dragItem.id).length - 1,
+ [dragItem, root, getItemPath]
);
// Here we want to allow user to shift placement line horizontally
// but only if that corresponds to a meaningful position in the tree
- const shiftedDropTarget = useMemo<ShiftedDropTarget | undefined>(() => {
+ const shiftedDropTarget = useMemo<ShiftedDropTarget<Data> | undefined>(() => {
if (
dropTarget === undefined ||
dragItemDepth === undefined ||
@@ -535,7 +567,7 @@ export const useHorizontalShift = ({
return { instance: data, position: "end" };
}
- const dropTargetPath = getInstancePathWithPositions(root, data.id);
+ const dropTargetPath = getItemPathWithPositions(root, data.id);
dropTargetPath.reverse();
const currentDepth = dropTargetPath.length;
@@ -547,7 +579,7 @@ export const useHorizontalShift = ({
placement: shiftPlacement(currentDepth),
} as const;
- const isDragItem = (instance: Instance | undefined | string) =>
+ const isDragItem = (instance: Data | undefined) =>
typeof instance === "object" && instance.id === dragItem.id;
if (desiredDepth < currentDepth) {
@@ -555,13 +587,13 @@ export const useHorizontalShift = ({
let newParent = data;
let newPosition = indexWithinChildren;
- const isAtTheBottom = (parent: Instance, index: number) => {
+ const isAtTheBottom = (parent: Data, index: number) => {
+ const children = getItemChildren(parent);
+
// There's a special case when the placement line is above the drag item.
// For reparenting above and below the drag item means the same thing.
- const indexCorrected = isDragItem(parent.children[index])
- ? index + 1
- : index;
- return indexCorrected === parent.children.length;
+ const indexCorrected = isDragItem(children[index]) ? index + 1 : index;
+ return indexCorrected === children.length;
};
let potentialNewParent = dropTargetPath[shifted + 1];
@@ -569,12 +601,12 @@ export const useHorizontalShift = ({
while (
isAtTheBottom(newParent, newPosition) &&
typeof potentialNewParent === "object" &&
- components[potentialNewParent.instance.component].canAcceptChild() &&
+ canAcceptChild(potentialNewParent.item) &&
shifted < currentDepth - desiredDepth
) {
shifted++;
newPosition = dropTargetPath[shifted - 1].position + 1;
- newParent = potentialNewParent.instance;
+ newParent = potentialNewParent.item;
potentialNewParent = dropTargetPath[shifted + 1];
}
@@ -593,29 +625,30 @@ export const useHorizontalShift = ({
let shifted = 0;
let newParent = data;
- // There's a special case when the placement line is below the drag item.
- // For reparenting above and below the drag item means the same thing.
- const getChildAbove = (
- parent: Instance,
- index: number
- ): string | undefined | Instance =>
- isDragItem(parent.children[index - 1])
- ? parent.children[index - 2]
- : parent.children[index - 1];
+ const findNextParent = (
+ parent: Data,
+ position: number | "last"
+ ): undefined | Data => {
+ const children = getItemChildren(parent);
+ const index = position === "last" ? children.length - 1 : position;
+
+ // There's a special case when the placement line is below the drag item.
+ // For reparenting, above and below the drag item means the same thing.
+ return isDragItem(children[index])
+ ? children[index - 1]
+ : children[index];
+ };
- let potentialNewParent = getChildAbove(data, indexWithinChildren);
+ let potentialNewParent = findNextParent(data, indexWithinChildren - 1);
while (
typeof potentialNewParent === "object" &&
getIsExpanded(potentialNewParent) &&
- components[potentialNewParent.component].canAcceptChild() &&
+ canAcceptChild(potentialNewParent) &&
shifted < desiredDepth - currentDepth
) {
newParent = potentialNewParent;
- potentialNewParent = getChildAbove(
- newParent,
- newParent.children.length
- );
+ potentialNewParent = findNextParent(newParent, "last");
shifted++;
}
@@ -632,11 +665,14 @@ export const useHorizontalShift = ({
return withoutShift;
}, [
- dragItem,
- dragItemDepth,
dropTarget,
+ dragItemDepth,
+ dragItem,
+ getItemPathWithPositions,
root,
horizontalShift,
+ canAcceptChild,
+ getItemChildren,
getIsExpanded,
]);
diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.ts
index 80cce17b23..a48465559e 100644
--- a/packages/design-system/src/index.ts
+++ b/packages/design-system/src/index.ts
@@ -63,3 +63,4 @@ export * from "./components/checkbox";
export * from "./components/avatar";
export * from "./components/primitives/dnd";
export * from "./components/separator";
+export * from "./components/tree";