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.

refactor: remove deprecated tree (#4180)

Bogdan Chadkind74b3e6b6512
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/navigator/navigator-tree.tsx b/apps/builder/app/builder/features/sidebar-left/panels/navigator/navigator-tree.tsx
index 600193835a..8d70ed2abf 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/navigator/navigator-tree.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/navigator/navigator-tree.tsx
@@ -16,7 +16,6 @@ import {
TreeNodeLabel,
TreeRoot,
TreeSortableItem,
- type ItemDropTarget,
type TreeDropTarget,
} from "@webstudio-is/design-system";
import {
@@ -39,6 +38,7 @@ import {
$selectedInstanceSelector,
$selectedPage,
getIndexedInstanceId,
+ type ItemDropTarget,
} from "~/shared/nano-states";
import type { InstanceSelector } from "~/shared/tree-utils";
import { serverSyncStore } from "~/shared/sync";
diff --git a/apps/builder/app/canvas/shared/use-drag-drop.ts b/apps/builder/app/canvas/shared/use-drag-drop.ts
index a142908d44..ef89f277bf 100644
--- a/apps/builder/app/canvas/shared/use-drag-drop.ts
+++ b/apps/builder/app/canvas/shared/use-drag-drop.ts
@@ -2,7 +2,6 @@ import { useLayoutEffect, useRef } from "react";
import type { Instance } from "@webstudio-is/sdk";
import {
type Point,
- type ItemDropTarget,
useAutoScroll,
useDrag,
useDrop,
@@ -12,6 +11,7 @@ import {
$dragAndDropState,
$instances,
$registeredComponentMetas,
+ type ItemDropTarget,
} from "~/shared/nano-states";
import { publish, useSubscribe } from "~/shared/pubsub";
import {
diff --git a/apps/builder/app/shared/nano-states/misc.ts b/apps/builder/app/shared/nano-states/misc.ts
index 98b3e45a25..cce7d53685 100644
--- a/apps/builder/app/shared/nano-states/misc.ts
+++ b/apps/builder/app/shared/nano-states/misc.ts
@@ -1,7 +1,7 @@
import { atom, computed, onSet } from "nanostores";
import { nanoid } from "nanoid";
import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";
-import type { ItemDropTarget, Placement } from "@webstudio-is/design-system";
+import type { Placement } from "@webstudio-is/design-system";
import type {
Assets,
DataSources,
@@ -27,6 +27,7 @@ import { $selectedInstanceSelector } from "./instances";
import type { UnitSizes } from "~/builder/features/style-panel/shared/css-value-input/convert-units";
import type { Simplify } from "type-fest";
import type { AssetType } from "@webstudio-is/asset-uploader";
+import type { ChildrenOrientation } from "node_modules/@webstudio-is/design-system/src/components/primitives/dnd/geometry-utils";
export const $project = atom<Project | undefined>();
@@ -314,6 +315,16 @@ export const $authToken = atom<string | undefined>(undefined);
export const $toastErrors = atom<string[]>([]);
+export type ItemDropTarget = {
+ itemSelector: InstanceSelector;
+ indexWithinChildren: number;
+ placement: {
+ closestChildIndex: number;
+ indexAdjustment: number;
+ childrenOrientation: ChildrenOrientation;
+ };
+};
+
export type DragAndDropState = {
isDragging: boolean;
dropTarget?: ItemDropTarget;
diff --git a/packages/design-system/package.json b/packages/design-system/package.json
index ae5339ebd1..6d4b007c49 100644
--- a/packages/design-system/package.json
+++ b/packages/design-system/package.json
@@ -12,7 +12,6 @@
},
"devDependencies": {
"@jest/globals": "^29.7.0",
- "@testing-library/react-hooks": "^8.0.1",
"@types/react": "^18.2.70",
"@types/react-dom": "^18.2.25",
"@webstudio-is/image": "workspace:*",
@@ -65,7 +64,6 @@
"@webstudio-is/icons": "workspace:*",
"change-case": "^5.4.4",
"downshift": "^6.1.7",
- "immer": "^10.0.3",
"match-sorter": "^6.3.4",
"react-field-sizing-content": "^1.0.0",
"react-hot-toast": "^2.4.1",
diff --git a/packages/design-system/src/components/__DEPRECATED__/tree/horizontal-shift.test.ts b/packages/design-system/src/components/__DEPRECATED__/tree/horizontal-shift.test.ts
deleted file mode 100644
index f44c41ada3..0000000000
--- a/packages/design-system/src/components/__DEPRECATED__/tree/horizontal-shift.test.ts
+++ /dev/null
@@ -1,321 +0,0 @@
-import { describe, test, expect } from "@jest/globals";
-import { renderHook, act } from "@testing-library/react-hooks";
-import type { Placement } from "../../primitives/dnd";
-import { useHorizontalShift } from "./horizontal-shift";
-import type { ItemDropTarget, ItemId, ItemSelector } from "./item-utils";
-import { type Item, findItemById, getItemPath } from "./test-tree-data";
-
-const box1: Item = { canAcceptChildren: true, id: "box1", children: [] };
-const box2: Item = { canAcceptChildren: true, id: "box2", children: [] };
-const box321: Item = { canAcceptChildren: true, id: "box321", children: [] };
-const box32: Item = {
- canAcceptChildren: true,
- children: [box321],
- id: "box32",
-};
-const box31: Item = { canAcceptChildren: true, id: "box31", children: [] };
-const box3: Item = {
- canAcceptChildren: true,
- children: [box31, box32],
- id: "box3",
-};
-const box4: Item = { canAcceptChildren: true, id: "box4", children: [] };
-const heading: Item = {
- canAcceptChildren: false,
- children: [{ canAcceptChildren: false, id: "bold", children: [] }],
- id: "heading",
-};
-const box511: Item = { canAcceptChildren: true, id: "box511", children: [] };
-const box51: Item = {
- canAcceptChildren: true,
- id: "box51",
- children: [box511],
-};
-const box52: Item = { canAcceptChildren: true, id: "box52", children: [] };
-const box5: Item = {
- canAcceptChildren: true,
- id: "box5",
- children: [box51, box52],
-};
-
-// root
-// | box1
-// | box2
-// | box3
-// | | box31
-// | | box32
-// | | | box321
-// | box4
-// | heading
-// | | bold
-// | box5
-// | | box51
-// | | | box511
-// | | box52
-const tree: Item = {
- id: "root",
- canAcceptChildren: true,
- children: [box1, box2, box3, box4, heading, box5],
-};
-
-const makePlacementIndicator = (
- type: Placement["type"] = "next-to-child"
-): Placement => ({
- parentRect: { width: 0, height: 0, left: 0, top: 0 },
- type,
- direction: "horizontal",
- x: 0,
- y: 100,
- length: 300,
-});
-
-const makeDrop = ({
- into,
- after,
-}: {
- into: Item;
- after?: Item;
-}): ItemDropTarget => ({
- itemSelector: getItemSelector(into.id),
- indexWithinChildren:
- after === undefined ? 0 : into.children.indexOf(after) + 1,
- placement: {
- closestChildIndex: 0,
- indexAdjustment: 0,
- childrenOrientation: { type: "mixed" },
- },
-});
-
-const getItemSelector = (itemId: ItemId) => {
- return getItemPath(tree, itemId)
- .reverse()
- .map((item) => item.id);
-};
-
-const render = (
- {
- dragItem,
- dropTarget,
- placementIndicator = makePlacementIndicator(),
- }: {
- dragItem: Item | undefined;
- dropTarget: ItemDropTarget | undefined;
- placementIndicator?: Placement;
- },
- shift = -1
-) => {
- const { result } = renderHook((props) => useHorizontalShift<Item>(props), {
- initialProps: {
- dragItemSelector:
- dragItem === undefined ? undefined : getItemSelector(dragItem.id),
- dropTarget,
- placementIndicator,
- getIsExpanded: (itemSelector: ItemSelector) =>
- (findItemById(tree, itemSelector[0])?.children.length ?? 0) > 0,
- canAcceptChild: (itemSelector: ItemSelector) =>
- findItemById(tree, itemSelector[0])?.canAcceptChildren ?? false,
- getItemChildren: (itemSelector: ItemSelector) =>
- findItemById(tree, itemSelector[0])?.children ?? [],
- isItemHidden: ([_itemId]: ItemSelector) => false,
- },
- });
-
- 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,
- });
- const result = render({
- dragItem: box1,
- dropTarget,
- placementIndicator: makePlacementIndicator("inside-parent"),
- });
-
- // parent doesn't change
- expect(result?.itemSelector).toEqual(["box2", "root"]);
-
- // 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?.itemSelector).toEqual(["box3", "root"]);
-
- // placement line is adjusted to account for depth,
- // even though depth didn't change
- expect(result?.placement).toEqual({
- ...makePlacementIndicator(),
- 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?.itemSelector).toEqual(["root"]);
-
- // 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?.itemSelector).toEqual(["box3", "root"]);
- expect(result2?.position).toBe(2);
-});
-
-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?.itemSelector).toEqual(["root"]);
- });
-
- 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?.itemSelector).toEqual(["box3", "root"]);
- });
-
- 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?.itemSelector).toEqual(["root"]);
- expect(result?.position).toBe(tree.children.indexOf(box3) + 1);
- expect(result?.placement).toEqual({
- ...makePlacementIndicator(),
- 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?.itemSelector).toEqual(["root"]);
- expect(result1?.position).toBe(tree.children.indexOf(box3) + 1);
- expect(result1?.placement).toEqual({
- ...makePlacementIndicator(),
- x: 24,
- length: 276,
- });
-
- const result2 = render(args, 1);
- expect(result2?.itemSelector).toEqual(["box3", "root"]);
- expect(result2?.position).toBe(box3.children.indexOf(box32) + 1);
- expect(result2?.placement).toEqual({
- ...makePlacementIndicator(),
- 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?.itemSelector).toEqual(["box5", "root"]);
- 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?.itemSelector).toEqual(["root"]);
- });
-
- 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?.itemSelector).toEqual(["box3", "root"]);
-
- const result2 = render(args, 2);
- expect(result2?.itemSelector).toEqual(["box32", "box3", "root"]);
- });
-
- 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?.itemSelector).toEqual(["root"]);
-
- // 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?.itemSelector).toEqual(["box3", "root"]);
- expect(result2?.position).toBe(2);
- });
-
- 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?.itemSelector).toEqual(["box3", "root"]);
- expect(result?.position).toBe(2);
- });
-
- 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?.itemSelector).toEqual(["root"]);
- });
-});
diff --git a/packages/design-system/src/components/__DEPRECATED__/tree/horizontal-shift.ts b/packages/design-system/src/components/__DEPRECATED__/tree/horizontal-shift.ts
deleted file mode 100644
index d622eec94c..0000000000
--- a/packages/design-system/src/components/__DEPRECATED__/tree/horizontal-shift.ts
+++ /dev/null
@@ -1,235 +0,0 @@
-import { useMemo, useState } from "react";
-import type { Placement } from "../../primitives/dnd";
-import type { ItemDropTarget, ItemId, ItemSelector } from "./item-utils";
-import { getPlacementIndicatorAlignment } from "./tree-node";
-
-export type ShiftedDropTarget = {
- itemSelector: ItemSelector;
- position: number | "end";
- placement?: Placement;
-};
-
-export const useHorizontalShift = <Data extends { id: ItemId }>({
- dragItemSelector,
- dropTarget,
- placementIndicator,
- getIsExpanded,
- canAcceptChild,
- isItemHidden,
- getItemChildren,
-}: {
- getItemChildren: (itemSelector: ItemSelector) => Data[];
- canAcceptChild: (itemSelector: ItemSelector) => boolean;
- isItemHidden: (itemSelector: ItemSelector) => boolean;
- dragItemSelector: undefined | ItemSelector;
- dropTarget: ItemDropTarget | undefined;
- placementIndicator: undefined | Placement;
- getIsExpanded: (itemSelector: ItemSelector) => boolean;
-}) => {
- const [horizontalShift, setHorizontalShift] = useState(0);
-
- // 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 => {
- if (
- dropTarget === undefined ||
- placementIndicator === undefined ||
- dragItemSelector === undefined
- ) {
- return undefined;
- }
-
- const { itemSelector: dropItemSelector, indexWithinChildren } = dropTarget;
-
- const shiftPlacement = (depth: number) => {
- const shift = getPlacementIndicatorAlignment(depth);
- return {
- ...placementIndicator,
- x: placementIndicator.x + shift,
- length: placementIndicator.length - shift,
- };
- };
-
- // Placement type “inside-parent” means that useDrop() didn’t find any children.
- // In this case the placement line coordinates are meaningless in the context of the tree.
- // We're dropping the placement and not performing any shifting.
- if (placementIndicator.type === "inside-parent") {
- return { itemSelector: dropItemSelector, position: "end" };
- }
-
- let dropHiddenCount = 0;
- dropItemSelector.forEach((_itemId, index) => {
- if (isItemHidden(dropItemSelector.slice(index))) {
- dropHiddenCount += 1;
- }
- });
-
- const dragItemDepth = dragItemSelector.length - 1;
- const currentDepth = dropItemSelector.length;
- const desiredDepth = dragItemDepth + horizontalShift;
-
- const withoutShift = {
- itemSelector: dropItemSelector,
- position: indexWithinChildren,
- placement: shiftPlacement(currentDepth - dropHiddenCount),
- } as const;
-
- if (desiredDepth === currentDepth) {
- return withoutShift;
- }
-
- const [dragItemId] = dragItemSelector;
- const isDragItem = (item: Data | undefined) => item?.id === dragItemId;
-
- const isAtTheBottom = (parentSelector: ItemSelector, index: number) => {
- const children = getItemChildren(parentSelector);
- // 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.
- const indexCorrected = isDragItem(children[index]) ? index + 1 : index;
- return indexCorrected === children.length;
- };
-
- // @todo generalize the logic of both directions
-
- // find the last matching while shifting to the left
- // until cursor is reached
- // since the direction of search from the deepest to the root is same
- // break on last match
- if (desiredDepth < currentDepth) {
- let newParentSelector = dropItemSelector;
- let newPosition = indexWithinChildren;
-
- // skip drop item
- for (let index = 1; index < dropItemSelector.length; index += 1) {
- if (
- index > currentDepth - desiredDepth ||
- isAtTheBottom(dropItemSelector.slice(index - 1), newPosition) ===
- false
- ) {
- break;
- }
- const currentItemSelector = dropItemSelector.slice(index);
- if (canAcceptChild(currentItemSelector)) {
- newParentSelector = currentItemSelector;
- const children = getItemChildren(dropItemSelector.slice(index));
- const childId = dropItemSelector[index - 1] ?? children.at(-1)?.id;
- const childPosition = children.findIndex(
- (item) => item.id === childId
- );
- newPosition = childPosition + 1;
- }
- }
-
- const shifted = newParentSelector.length - dropItemSelector.length;
-
- if (shifted === 0) {
- return withoutShift;
- }
-
- return {
- itemSelector: newParentSelector,
- position: newPosition,
- placement: shiftPlacement(currentDepth - dropHiddenCount + shifted),
- };
- }
-
- // find deepest item at the bottom
- const getLastChild = (
- children: Data[],
- position: number
- ): undefined | ItemId => {
- // 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.
- return isDragItem(children[position])
- ? children[position - 1]?.id
- : children[position]?.id;
- };
- let deepestAtTheBottomItemSelector = dropItemSelector;
- let deepestAtTheBottomParentId: undefined | string =
- deepestAtTheBottomItemSelector[0];
- let deepestAtTheBottomChildren = getItemChildren(
- deepestAtTheBottomItemSelector
- );
- let deepestAtTheBottomPosition = indexWithinChildren - 1;
- while (true) {
- deepestAtTheBottomParentId = getLastChild(
- deepestAtTheBottomChildren,
- deepestAtTheBottomPosition
- );
- if (deepestAtTheBottomParentId === undefined) {
- break;
- }
- const newItemSelector = [
- deepestAtTheBottomParentId,
- ...deepestAtTheBottomItemSelector,
- ];
- if (getIsExpanded(newItemSelector) === false) {
- break;
- }
- deepestAtTheBottomItemSelector = newItemSelector;
- deepestAtTheBottomChildren = getItemChildren(
- deepestAtTheBottomItemSelector
- );
- deepestAtTheBottomPosition = deepestAtTheBottomChildren.length - 1;
- }
-
- // find the last matching while shifting to the right
- // until cursor is reached
- // since the direction of search from the deepest to the root is reversed
- // break on first match
- if (desiredDepth > currentDepth) {
- let newParentSelector = deepestAtTheBottomItemSelector;
- let newPosition = deepestAtTheBottomPosition;
-
- for (
- let index = Math.max(
- 0,
- deepestAtTheBottomItemSelector.length - desiredDepth
- );
- index < deepestAtTheBottomItemSelector.length;
- index += 1
- ) {
- const currentItemSelector = deepestAtTheBottomItemSelector.slice(index);
- if (canAcceptChild(currentItemSelector)) {
- newParentSelector = currentItemSelector;
- const children = getItemChildren(
- deepestAtTheBottomItemSelector.slice(index)
- );
- const childId =
- deepestAtTheBottomItemSelector[index - 1] ?? children.at(-1)?.id;
- const childPosition = children.findIndex(
- (item) => item.id === childId
- );
- newPosition = childPosition + 1;
- break;
- }
- continue;
- }
-
- const shifted = newParentSelector.length - dropItemSelector.length;
-
- if (shifted === 0) {
- return withoutShift;
- }
-
- return {
- itemSelector: newParentSelector,
- position: newPosition,
- placement: shiftPlacement(currentDepth - dropHiddenCount + shifted),
- };
- }
-
- return withoutShift;
- }, [
- dropTarget,
- placementIndicator,
- dragItemSelector,
- horizontalShift,
- canAcceptChild,
- isItemHidden,
- getItemChildren,
- getIsExpanded,
- ]);
-
- return [shiftedDropTarget, setHorizontalShift] as const;
-};
diff --git a/packages/design-system/src/components/__DEPRECATED__/tree/index.ts b/packages/design-system/src/components/__DEPRECATED__/tree/index.ts
deleted file mode 100644
index 019b7cd278..0000000000
--- a/packages/design-system/src/components/__DEPRECATED__/tree/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-export type { ItemSelector, ItemDropTarget } from "./item-utils";
-export * from "./tree";
-export {
- TreeItemBody,
- TreeItemLabel,
- getNodeVars,
- getPlacementIndicatorAlignment,
- type TreeItemRenderProps,
-} from "./tree-node";
diff --git a/packages/design-system/src/components/__DEPRECATED__/tree/item-utils.ts b/packages/design-system/src/components/__DEPRECATED__/tree/item-utils.ts
deleted file mode 100644
index 4dc1e354e0..0000000000
--- a/packages/design-system/src/components/__DEPRECATED__/tree/item-utils.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import type { ChildrenOrientation } from "../../primitives/dnd/geometry-utils";
-
-export type ItemId = string;
-
-export type ItemSelector = string[];
-
-export type ItemDropTarget = {
- itemSelector: ItemSelector;
- indexWithinChildren: number;
- placement: {
- closestChildIndex: number;
- indexAdjustment: number;
- childrenOrientation: ChildrenOrientation;
- };
-};
-
-export const getElementByItemSelector = (
- root: undefined | Element,
- itemSelector: ItemSelector
-) => {
- // query item from root to target
- const domSelector = itemSelector
- .map((id) => `[data-drop-target-id="${id}"]`)
- .reverse()
- .join(" ");
- return root?.querySelector(domSelector) ?? undefined;
-};
-
-export const getItemSelectorFromElement = (element: Element) => {
- const itemSelector: ItemSelector = [];
- let matched: undefined | Element =
- element.closest(`[data-drop-target-id]`) ?? undefined;
- while (matched) {
- const itemId = matched.getAttribute("data-drop-target-id") ?? undefined;
- if (itemId !== undefined) {
- itemSelector.push(itemId);
- }
- matched =
- matched.parentElement?.closest(`[data-drop-target-id]`) ?? undefined;
- }
- return itemSelector;
-};
-
-export const areItemSelectorsEqual = (
- left: undefined | ItemSelector,
- right: undefined | ItemSelector
-) => {
- if (left === undefined || right === undefined) {
- return false;
- }
- return left.join(",") === right.join(",");
-};
diff --git a/packages/design-system/src/components/__DEPRECATED__/tree/test-tree-data.ts b/packages/design-system/src/components/__DEPRECATED__/tree/test-tree-data.ts
deleted file mode 100644
index 1ea3ea78a4..0000000000
--- a/packages/design-system/src/components/__DEPRECATED__/tree/test-tree-data.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { produce } from "immer";
-import type { ItemSelector } from "./item-utils";
-
-export type Item = {
- id: string;
- canAcceptChildren: boolean;
- isHidden?: boolean;
- children: Item[];
-};
-
-export const getItemPath = (tree: Item, itemId: string) => {
- const path = [];
-
- const find = (item: Item) => {
- if (item.id === itemId) {
- return true;
- }
- const children = item.children;
- for (let i = 0; i < children.length; i++) {
- const child = children[i];
- if (typeof child === "string") {
- continue;
- }
- const found = find(child);
- if (found) {
- path.push(child);
- return true;
- }
- }
- };
-
- if (find(tree)) {
- path.push(tree);
- }
-
- return path.reverse();
-};
-
-export const canAcceptChild = (item: Item) => item.canAcceptChildren;
-
-export const getItemChildren = (item: Item) => item.children;
-
-export const findItemById = (root: Item, id: string) => {
- const path = getItemPath(root, id);
- return path.length > 0 ? path[path.length - 1] : undefined;
-};
-
-export const reparent = (
- root: Item,
- {
- itemSelector,
- dropTarget,
- }: {
- itemSelector: ItemSelector;
- dropTarget: {
- itemSelector: ItemSelector;
- position: number | "end";
- };
- }
-) =>
- produce(root, (draft) => {
- const [itemId] = itemSelector;
- const path = getItemPath(draft, itemId);
- const item = path[path.length - 1];
- const currentParent = path[path.length - 2];
- const newParent = findItemById(draft, dropTarget.itemSelector[0]);
-
- if (
- item === undefined ||
- currentParent === undefined ||
- newParent === undefined
- ) {
- return;
- }
-
- const currentIndex = currentParent.children.findIndex(
- (child) => child.id === itemId
- );
-
- currentParent.children.splice(currentIndex, 1);
-
- if (dropTarget.position === "end") {
- newParent.children.push(item);
- } else {
- let newIndex = dropTarget.position;
-
- // dropTarget.position does not take into account the fact that the drag item will be removed
- if (currentParent.id === newParent.id && currentIndex < newIndex) {
- newIndex--;
- }
-
- newParent.children.splice(newIndex, 0, item);
- }
- });
diff --git a/packages/design-system/src/components/__DEPRECATED__/tree/tree-node.tsx b/packages/design-system/src/components/__DEPRECATED__/tree/tree-node.tsx
deleted file mode 100644
index 8eab1eb988..0000000000
--- a/packages/design-system/src/components/__DEPRECATED__/tree/tree-node.tsx
+++ /dev/null
@@ -1,581 +0,0 @@
-import {
- useRef,
- useEffect,
- useMemo,
- useState,
- forwardRef,
- type ForwardRefRenderFunction,
- type MouseEvent,
- type ComponentProps,
-} from "react";
-import {
- ChevronFilledDownIcon,
- ChevronFilledRightIcon,
-} from "@webstudio-is/icons";
-import { Box } from "../../box";
-import { Flex } from "../../flex";
-import { Text } from "../../text";
-import { styled, type CSS } from "../../../stitches.config";
-import { theme } from "../../../stitches.config";
-import {
- type ItemId,
- type ItemSelector,
- areItemSelectorsEqual,
-} from "./item-utils";
-
-export const INDENT = 16;
-const ITEM_HEIGHT = 32;
-const ICONS_SIZE = 16;
-const ITEM_PADDING_LEFT = 8;
-// extra padding on the right to make sure scrollbar doesn't obscure anything
-const ITEM_PADDING_RIGHT = 14;
-
-export const getPlacementIndicatorAlignment = (depth: number) => {
- return depth * INDENT + ITEM_PADDING_LEFT;
-};
-
-const suffixWidthVar = `--ws-tree-node-suffix-width`;
-
-const itemButtonVars = {
- paddingRight: `--ws-tree-node-item-button-padding-right`,
-};
-const getItemButtonCssVars = ({
- suffixVisible,
-}: {
- suffixVisible: boolean;
-}) => {
- if (suffixVisible) {
- const suffixWidth = `var(${suffixWidthVar}, 0px)`;
- return {
- // We have to use a padding to make space for the suffix
- // because we can't put it inside ItemButton (see comment in TreeItemBody)
- [itemButtonVars.paddingRight]: `calc(${ITEM_PADDING_RIGHT}px + ${suffixWidth})`,
- };
- }
- return {
- [itemButtonVars.paddingRight]: ITEM_PADDING_RIGHT,
- };
-};
-const ItemButton = styled("button", {
- all: "unset",
- display: "flex",
- alignItems: "center",
- boxSizing: "border-box",
- userSelect: "none",
- height: ITEM_HEIGHT,
- minWidth: 0,
- margin: 0,
- pt: 0,
- pb: 0,
- pl: ITEM_PADDING_LEFT,
- pr: `var(${itemButtonVars.paddingRight})`,
- flexBasis: 0,
- flexGrow: 1,
- position: "relative",
-});
-
-const nestingLinesVisibilityVar = "--ws-tree-node-nesting-lines-visibility";
-
-export const showNestingLineVars = () => ({
- [nestingLinesVisibilityVar]: "visible",
-});
-
-const NestingLine = styled(Box, {
- visibility: `var(${nestingLinesVisibilityVar}, hidden)`,
- width: Math.ceil(INDENT / 2),
- marginRight: Math.floor(INDENT / 2),
- height: ITEM_HEIGHT,
- borderRight: "solid",
- borderRightWidth: 1,
- borderColor: theme.colors.borderItemChildLine,
- variants: {
- isSelected: {
- true: { borderColor: theme.colors.borderItemChildLineCurrent },
- },
- },
-});
-
-const NestingLines = ({
- isSelected,
- level,
-}: {
- isSelected: boolean;
- level: number;
-}) =>
- level > 1 ? (
- <>
- {Array.from({ length: level - 1 }, (_, index) => (
- <NestingLine key={index} isSelected={isSelected} />
- ))}
- </>
- ) : undefined;
-
-const CollapsibleTrigger = styled("button", {
- all: "unset",
- display: "flex",
- pr: INDENT - ICONS_SIZE,
- height: ITEM_HEIGHT,
- alignItems: "center",
- position: "absolute",
-
- // We want the button to take extra space so it's easier to hit
- ml: `-${theme.spacing[3]}`,
- pl: theme.spacing[3],
-});
-
-const TriggerPlaceholder = styled(Box, { width: INDENT });
-
-const suffixContainerVars = {
- opacity: "--ws-tree-node-suffix-opacity",
- pointerEvents: "--ws-tree-node-suffix-pointer-events",
-};
-const getSuffixContainerCssVars = ({
- suffixVisible,
-}: {
- suffixVisible: boolean;
-}) => {
- if (suffixVisible) {
- return {
- [suffixContainerVars.opacity]: "1",
- [suffixContainerVars.pointerEvents]: "all",
- };
- }
- return {
- [suffixContainerVars.opacity]: "0",
- [suffixContainerVars.pointerEvents]: "none",
- };
-};
-const SuffixContainer = styled(Flex, {
- position: "absolute",
- alignItems: "center",
- right: ITEM_PADDING_RIGHT,
- top: 0,
- bottom: 0,
- defaultVariants: { align: "center" },
-
- // We use opacity to hide the suffix buttons
- // becuase when `visibility` is used it's impossible to focus the button.
- opacity: `var(${suffixContainerVars.opacity})`,
- pointerEvents: `var(${suffixContainerVars.pointerEvents})`,
-});
-
-const hoverStyle: CSS = {
- content: "''",
- position: "absolute",
- left: 2,
- right: 2,
- height: ITEM_HEIGHT,
- borderStyle: "solid",
- borderColor: theme.colors.borderFocus,
- borderWidth: 2,
- borderRadius: theme.borderRadius[6],
- pointerEvents: "none",
- boxSizing: "border-box",
-};
-
-const itemContainerColor: string = "--ws-tree-node-item-container-color";
-const itemContainerOpacity: string = "--ws-tree-node-item-container-opacity";
-
-export const getNodeVars = ({
- color,
- opacity,
-}: {
- color?: string;
- opacity?: number;
-}) => {
- return {
- ...(color ? { [itemContainerColor]: color } : undefined),
- ...(opacity !== undefined
- ? { [itemContainerOpacity]: opacity }
- : undefined),
- };
-};
-
-const ItemContainer = styled(Flex, {
- color: `var(${itemContainerColor}, ${theme.colors.foregroundMain})`,
- opacity: `var(${itemContainerOpacity}, 1)`,
- alignItems: "center",
- position: "relative",
- ...getItemButtonCssVars({ suffixVisible: false }),
- ...getSuffixContainerCssVars({ suffixVisible: false }),
-
- variants: {
- isSelected: {
- true: {
- bc: theme.colors.backgroundItemCurrent,
- },
- },
- isHighlighted: {
- true: { "&:after": hoverStyle },
- },
- parentIsSelected: {
- true: {
- bc: theme.colors.backgroundItemCurrentChild,
- },
- },
- suffixVisible: {
- true: {
- ...getItemButtonCssVars({ suffixVisible: true }),
- ...getSuffixContainerCssVars({ suffixVisible: true }),
- },
- },
- enableHoverState: {
- true: {
- "&:hover:after": hoverStyle,
-
- // Suffix is also visible on hover, which we don't track using JavaScript
- "&:hover": {
- ...getItemButtonCssVars({ suffixVisible: true }),
- ...getSuffixContainerCssVars({ suffixVisible: true }),
- },
- },
- },
- forceHoverState: {
- true: { "&:after": hoverStyle },
- },
- },
-});
-
-const useScrollIntoView = (
- elementRef: { current: HTMLElement | null },
- {
- isDragging,
- isDropTarget,
- isSelected,
- }: { isDragging: boolean; isDropTarget: boolean; isSelected: boolean }
-) => {
- const isDraggingRef = useRef(isDragging);
- isDraggingRef.current = isDragging;
- const isDropTargetRef = useRef(isDropTarget);
- isDropTargetRef.current = isDropTarget;
-
- // Scroll the selected button into view when selected from canvas.
- useEffect(() => {
- if (
- isSelected &&
- isDraggingRef.current === false &&
- isDropTargetRef.current === false
- ) {
- elementRef.current?.scrollIntoView({
- behavior: "smooth",
- block: "nearest",
- });
- }
- }, [
- isSelected,
- //only for the linter
- elementRef,
- ]);
-};
-
-export type TreeItemRenderProps<Data extends { id: string }> = {
- onHover?: (itemSelector?: ItemSelector) => void;
- itemData: Data;
- itemSelector: ItemSelector;
- dropTargetItemSelector?: ItemSelector;
- parentIsSelected?: boolean;
- isSelected?: boolean;
- isHighlighted?: boolean;
- onSelect?: (itemSelector: ItemSelector, all?: boolean) => void;
- level: number;
- isAlwaysExpanded: boolean;
- shouldRenderExpandButton: boolean;
- isExpanded: boolean;
- onToggle: (all: boolean) => void;
-};
-
-export const TreeItemBody = <Data extends { id: string }>({
- isAlwaysExpanded,
- onSelect,
- parentIsSelected = false,
- isSelected = false,
- isHighlighted = false,
- dropTargetItemSelector,
- onHover,
- itemData,
- itemSelector,
- level,
- shouldRenderExpandButton,
- isExpanded,
- children,
- suffix,
- suffixWidth = suffix ? theme.spacing[9] : "0px",
- alwaysShowSuffix = false,
- forceFocus = false,
- selectionEvent = "click",
- onToggle,
-}: TreeItemRenderProps<Data> & {
- children: React.ReactNode;
- suffix?: React.ReactNode;
- suffixWidth?: string;
- alwaysShowSuffix?: boolean;
- forceFocus?: boolean;
- selectionEvent?: "click" | "focus";
-}) => {
- const [focusTarget, setFocusTarget] = useState<
- "item-button" | "suffix" | undefined
- >();
- const itemButtonRef = useRef<HTMLButtonElement>(null);
- const suffixContainerRef = useRef<HTMLDivElement>(null);
-
- const updateFocusTarget = () => {
- if (document.activeElement === itemButtonRef.current) {
- setFocusTarget("item-button");
- return;
- }
- if (
- suffixContainerRef.current !== null &&
- suffixContainerRef.current.contains(document.activeElement)
- ) {
- setFocusTarget("suffix");
- return;
- }
- setFocusTarget(undefined);
- };
-
- const { handleFocus, handleClick } = useMemo(() => {
- if (onSelect === undefined) {
- return {};
- }
- return selectionEvent === "click"
- ? {
- handleClick: (event: MouseEvent) =>
- onSelect(itemSelector, event.altKey),
- }
- : {
- handleFocus: () => onSelect(itemSelector),
- handleClick: () => {
- // The intent is to reset the selection on focused item click to ensure the same behavior as on focus change.
- // This resolves an edge case with copy/paste when text is selected (e.g., inside CSS Preview) and a Tree Node is selected.
- // Visually, it's unclear what will be selected on the 'copy' event.
- const selection = window.getSelection();
- if (selection === null) {
- return;
- }
-
- const selectionNode = selection.focusNode;
-
- if (selectionNode === null) {
- return;
- }
-
- if (itemButtonRef.current === null) {
- return;
- }
-
- if (false === itemButtonRef.current.contains(selectionNode)) {
- selection.removeAllRanges();
- }
- },
- };
- }, [selectionEvent, onSelect, itemSelector]);
-
- const isDragging = dropTargetItemSelector !== undefined;
- const isDropTarget = areItemSelectorsEqual(
- dropTargetItemSelector,
- itemSelector
- );
-
- useScrollIntoView(itemButtonRef, {
- isSelected,
- isDragging,
- isDropTarget,
- });
-
- return (
- <ItemContainer
- onMouseEnter={onHover && (() => onHover(itemSelector))}
- onMouseLeave={onHover && (() => onHover())}
- isSelected={isSelected}
- isHighlighted={isHighlighted}
- parentIsSelected={parentIsSelected}
- enableHoverState={isDragging === false}
- forceHoverState={
- isDropTarget || focusTarget === "item-button" || forceFocus
- }
- suffixVisible={alwaysShowSuffix || focusTarget !== undefined}
- onFocus={updateFocusTarget}
- onBlur={updateFocusTarget}
- css={{ [suffixWidthVar]: suffixWidth }}
- >
- <ItemButton
- type="button"
- data-drag-item-id={itemData.id}
- data-item-button-id={itemData.id}
- onFocus={handleFocus}
- onClick={handleClick}
- ref={itemButtonRef}
- >
- <NestingLines isSelected={isSelected} level={level} />
- {isAlwaysExpanded === false && <TriggerPlaceholder />}
- {children}
- </ItemButton>
-
- {/* We can't nest the collapsible trigger and suffix inside the ItemButton because
- <button> can't be nested inside <button>,
- click events will be mixed up,
- may hurt accessibility, etc. */}
-
- {shouldRenderExpandButton && (
- <CollapsibleTrigger
- style={{ left: (level - 1) * INDENT + ITEM_PADDING_LEFT }}
- // We don't want this trigger to be focusable
- tabIndex={-1}
- onClick={(event) => {
- // If we don't stop propagation, the currently focused item will loose focus and then regain it
- // which will result in blinking outline.
- // We prefer to focus the collapsible trigger instead since it is also a button and it was actually clicked.
- event.stopPropagation();
- onToggle(event.altKey);
- }}
- >
- {isExpanded ? <ChevronFilledDownIcon /> : <ChevronFilledRightIcon />}
- </CollapsibleTrigger>
- )}
-
- {suffix && (
- <SuffixContainer ref={suffixContainerRef}>{suffix}</SuffixContainer>
- )}
- </ItemContainer>
- );
-};
-
-export const TreeItemLabelBase: ForwardRefRenderFunction<
- HTMLDivElement,
- {
- children: React.ReactNode;
- prefix?: React.ReactNode;
- }
-> = ({ children, prefix, ...restProps }, ref) => {
- return (
- <>
- {prefix}
- <Text
- ref={ref}
- variant="labelsSentenceCase"
- truncate
- css={{
- ml: prefix ? theme.spacing[3] : 0,
- flexBasis: 0,
- flexGrow: 1,
- }}
- {...restProps}
- >
- {children}
- </Text>
- </>
- );
-};
-
-export const TreeItemLabel = forwardRef(TreeItemLabelBase);
-
-export type TreeNodeProps<Data extends { id: ItemId }> = {
- itemData: Data;
- getItemChildren: (itemSelector: ItemSelector) => Data[];
- getItemProps?: (options: {
- itemData: Data;
- itemSelector: ItemSelector;
- }) => ComponentProps<"div"> | undefined;
- isItemHidden: (itemSelector: ItemSelector) => boolean;
- renderItem: (props: TreeItemRenderProps<Data>) => React.ReactNode;
-
- getIsExpanded: (itemSelector: ItemSelector) => boolean;
- setIsExpanded?: (
- itemSelector: ItemSelector,
- value: boolean,
- all?: boolean
- ) => void;
-
- selectedItemSelector?: ItemSelector;
- highlightedItemSelector?: ItemSelector;
- dropTargetItemSelector?: ItemSelector;
- parentSelector?: ItemSelector;
-
- parentIsSelected?: boolean;
- onSelect?: (itemSelector: ItemSelector) => void;
- onHover?: (itemSelector?: ItemSelector) => void;
-
- level?: number;
-};
-
-export const TreeNode = <Data extends { id: string }>({
- itemData,
- parentSelector,
- parentIsSelected,
- level = 0,
- ...commonProps
-}: TreeNodeProps<Data>) => {
- const {
- getIsExpanded,
- setIsExpanded,
- selectedItemSelector,
- highlightedItemSelector,
- onSelect,
- onHover,
- dropTargetItemSelector,
- renderItem,
- getItemChildren,
- getItemProps,
- isItemHidden,
- } = commonProps;
-
- const itemSelector = [itemData.id, ...(parentSelector ?? [])];
-
- const itemChildren = getItemChildren(itemSelector);
-
- const itemIsHidden = isItemHidden(itemSelector);
- // hidden items and root are always expanded
- const isAlwaysExpanded = itemIsHidden || level === 0;
-
- const isExpandable = itemChildren.length > 0;
- const isExpanded = getIsExpanded(itemSelector) || isAlwaysExpanded;
- const isSelected = areItemSelectorsEqual(itemSelector, selectedItemSelector);
- const isHighlighted = areItemSelectorsEqual(
- itemSelector,
- highlightedItemSelector
- );
- const shouldRenderExpandButton = isExpandable && isAlwaysExpanded === false;
-
- return (
- <div
- data-drop-target-id={itemData.id}
- {...getItemProps?.({ itemData, itemSelector })}
- >
- {/* optionally prevent rendering root item */}
- {itemIsHidden === false &&
- renderItem({
- dropTargetItemSelector,
- onHover,
- itemData,
- itemSelector,
- parentIsSelected,
- isSelected,
- isHighlighted,
- onSelect,
- level,
- isAlwaysExpanded,
- shouldRenderExpandButton,
- isExpanded,
- onToggle: (all) => {
- setIsExpanded?.(
- itemSelector,
- getIsExpanded(itemSelector) === false,
- all
- );
- },
- })}
- {isExpandable &&
- isExpanded &&
- itemChildren.map((child) => (
- <TreeNode
- key={child.id}
- itemData={child}
- parentSelector={itemSelector}
- parentIsSelected={isSelected || parentIsSelected}
- level={itemIsHidden ? level : level + 1}
- {...commonProps}
- />
- ))}
- </div>
- );
-};
diff --git a/packages/design-system/src/components/__DEPRECATED__/tree/tree.stories.tsx b/packages/design-system/src/components/__DEPRECATED__/tree/tree.stories.tsx
deleted file mode 100644
index 70fc322d16..0000000000
--- a/packages/design-system/src/components/__DEPRECATED__/tree/tree.stories.tsx
+++ /dev/null
@@ -1,132 +0,0 @@
-import type { Meta } from "@storybook/react";
-import { useState } from "react";
-import { Tree } from "./tree";
-import { type Item, findItemById, reparent } from "./test-tree-data";
-import { Flex } from "../../flex";
-import { TreeItemLabel, TreeItemBody } from "./tree-node";
-import type { ItemDropTarget, ItemSelector } from "./item-utils";
-
-export const StressTest = () => {
- const [root, setRoot] = useState<Item>((): Item => {
- return {
- id: "root",
- canAcceptChildren: true,
- children: Array.from(
- { length: 100 },
- (_, index): Item => ({
- id: `box-${index}`,
- canAcceptChildren: true,
- children: [
- {
- id: `heading-${index}.0`,
- canAcceptChildren: false,
- children: [],
- },
- {
- id: `paragraph-${index}.0`,
- canAcceptChildren: false,
- children: [],
- },
- {
- id: `box-${index}.0`,
- canAcceptChildren: true,
- children: [
- {
- id: `hidden-${index}.0.0`,
- canAcceptChildren: true,
- isHidden: true,
- children: [
- {
- id: `box-${index}.0.0.0`,
- canAcceptChildren: true,
- children: [
- {
- id: `box-${index}.0.0.0.0`,
- canAcceptChildren: true,
- children: [
- {
- id: `heading-${index}.1`,
- canAcceptChildren: false,
- children: [],
- },
- {
- id: `paragraph-${index}.1`,
- canAcceptChildren: false,
- children: [],
- },
- ],
- },
- ],
- },
- ],
- },
- {
- id: `box-${index}.0.1`,
- canAcceptChildren: true,
- children: [],
- },
- ],
- },
- ],
- })
- ),
- };
- });
-
- const [selectedItemSelector, setSelectedItemSelector] = useState<
- undefined | ItemSelector
- >();
- const [dropTarget, setDropTarget] = useState<undefined | ItemDropTarget>();
- const [dragItemSelector, setDragItemSelector] = useState<
- undefined | ItemSelector
- >();
-
- return (
- <Flex css={{ width: 300, height: 500, flexDirection: "column" }}>
- <Tree
- editingItemId={undefined}
- findClosestDroppableIndex={(itemSelector) => {
- return itemSelector.findIndex((itemId) => {
- const item = findItemById(root, itemId);
- return (
- (item?.canAcceptChildren ?? false) &&
- (item?.isHidden ?? false) === false
- );
- });
- }}
- canLeaveParent={() => true}
- getItemChildren={(itemSelector) =>
- findItemById(root, itemSelector[0])?.children ?? []
- }
- isItemHidden={(itemSelector) =>
- findItemById(root, itemSelector[0])?.isHidden ?? false
- }
- root={root}
- selectedItemSelector={selectedItemSelector}
- dragItemSelector={dragItemSelector}
- dropTarget={dropTarget}
- onSelect={setSelectedItemSelector}
- onDropTargetChange={setDropTarget}
- onDragItemChange={setDragItemSelector}
- renderItem={(props) => (
- <TreeItemBody {...props}>
- <TreeItemLabel>{props.itemData.id}</TreeItemLabel>
- </TreeItemBody>
- )}
- onDragEnd={(payload) => {
- setRoot((root) => reparent(root, payload));
- setDragItemSelector(undefined);
- setDropTarget(undefined);
- }}
- onCancel={() => {
- setDragItemSelector(undefined);
- setDropTarget(undefined);
- }}
- />
- </Flex>
- );
-};
-
-export default {
- component: Tree,
-} satisfies Meta<typeof Tree>;
diff --git a/packages/design-system/src/components/__DEPRECATED__/tree/tree.tsx b/packages/design-system/src/components/__DEPRECATED__/tree/tree.tsx
deleted file mode 100644
index a659302f4a..0000000000
--- a/packages/design-system/src/components/__DEPRECATED__/tree/tree.tsx
+++ /dev/null
@@ -1,463 +0,0 @@
-import type { ReactNode } from "react";
-import { useState, useMemo, useRef, useCallback, useEffect } from "react";
-import { createPortal } from "react-dom";
-import { FocusScope, useFocusManager } from "@react-aria/focus";
-import { TreePositionIndicator } from "../../list-position-indicator";
-import {
- TreeNode,
- INDENT,
- type TreeItemRenderProps,
- showNestingLineVars,
- type TreeNodeProps,
-} from "./tree-node";
-import {
- useHold,
- useDrop,
- useDrag,
- useAutoScroll,
- useDragCursor,
- computeIndicatorPlacement,
-} from "../../primitives/dnd";
-import { Box } from "../../box";
-import { useHorizontalShift } from "./horizontal-shift";
-import {
- type ItemId,
- type ItemSelector,
- type ItemDropTarget,
- areItemSelectorsEqual,
- getElementByItemSelector,
- getItemSelectorFromElement,
-} from "./item-utils";
-import { ScrollArea } from "../../scroll-area";
-import { theme } from "../../..";
-
-const KeyboardNavigation = ({
- editingItemId,
- onExpandedChange,
- children,
-}: {
- editingItemId: ItemId | undefined;
- onExpandedChange: (expanded?: boolean) => void;
- children: ReactNode;
-}) => {
- const focusManager = useFocusManager();
- return (
- <div
- onKeyDown={(event) => {
- if (event.defaultPrevented) {
- return;
- }
- // prevent navigating while editing nodes
- if (editingItemId) {
- return;
- }
- if (event.key === "ArrowUp") {
- focusManager?.focusPrevious({
- accept: (node) => node.hasAttribute("data-item-button-id"),
- });
- // prevent scrolling
- event.preventDefault();
- }
- if (event.key === "ArrowDown") {
- focusManager?.focusNext({
- accept: (node) => node.hasAttribute("data-item-button-id"),
- });
- // prevent scrolling
- event.preventDefault();
- }
- if (event.key === "ArrowLeft") {
- onExpandedChange(false);
- //
- }
- if (event.key === "ArrowRight") {
- onExpandedChange(true);
- }
- if (event.key === " ") {
- onExpandedChange();
- // prevent scrolling
- event.preventDefault();
- }
- }}
- >
- {children}
- </div>
- );
-};
-
-export type TreeProps<Data extends { id: string }> = {
- root: Data;
- selectedItemSelector: undefined | ItemSelector;
- highlightedItemSelector?: ItemSelector;
- dragItemSelector: undefined | ItemSelector;
- dropTarget: undefined | ItemDropTarget;
-
- canLeaveParent: (itemSelector: ItemSelector) => boolean;
- findClosestDroppableIndex: (itemSelector: ItemSelector) => number;
- getItemChildren: (itemSelector: ItemSelector) => Data[];
- getItemProps?: TreeNodeProps<Data>["getItemProps"];
- isItemHidden: (itemSelector: ItemSelector) => boolean;
- renderItem: (props: TreeItemRenderProps<Data>) => React.ReactNode;
-
- onSelect?: (itemSelector: ItemSelector) => void;
- onHover?: (itemSelector: undefined | ItemSelector) => void;
- onDropTargetChange: (dropTarget: undefined | ItemDropTarget) => void;
- onDragItemChange: (itemSelector: ItemSelector) => void;
- onDragEnd: (event: {
- itemSelector: ItemSelector;
- dropTarget: { itemSelector: ItemSelector; position: number | "end" };
- }) => void;
- onCancel: () => void;
- editingItemId: ItemId | undefined;
-};
-
-const sharedDropOptions = {
- placementPadding: 0,
- getValidChildren: (element: Element) => {
- // NOTE:
- // redefining children like this will screw up automatic childrenOrientation detection
- // luckily we know the orientation and can define it manually below
- return Array.from(
- element.querySelectorAll(":scope > [data-drop-target-id]")
- );
- },
- childrenOrientation: { type: "vertical", reverse: false },
-} as const;
-
-export const Tree = <Data extends { id: string }>({
- root,
- selectedItemSelector,
- highlightedItemSelector,
- dragItemSelector,
- dropTarget,
- canLeaveParent,
- findClosestDroppableIndex,
- getItemChildren,
- getItemProps,
- isItemHidden,
- renderItem,
- onSelect,
- onHover,
- onDropTargetChange,
- onDragItemChange,
- onDragEnd,
- onCancel,
- editingItemId,
-}: TreeProps<Data>) => {
- const { getIsExpanded, setIsExpanded } = useExpandState({
- selectedItemSelector,
- getItemChildren,
- });
-
- const rootRef = useRef<HTMLElement | null>(null);
-
- const placementIndicator = useMemo(() => {
- if (dropTarget === undefined) {
- return;
- }
- const element = getElementByItemSelector(
- rootRef.current ?? undefined,
- dropTarget.itemSelector
- );
- if (element === undefined) {
- return;
- }
- return computeIndicatorPlacement({
- placement: dropTarget.placement,
- element,
- ...sharedDropOptions,
- });
- }, [dropTarget]);
-
- const canAcceptChild = useCallback(
- (itemSelector: ItemSelector) => {
- const ancestorIndex = findClosestDroppableIndex(itemSelector);
- return ancestorIndex === 0;
- },
- [findClosestDroppableIndex]
- );
-
- const [shiftedDropTarget, setHorizontalShift] = useHorizontalShift({
- dragItemSelector,
- dropTarget,
- placementIndicator,
- getIsExpanded,
- getItemChildren,
- isItemHidden,
- canAcceptChild,
- });
-
- const useHoldHandler = useHold({
- data: dropTarget,
- isEqual: (a, b) => areItemSelectorsEqual(a?.itemSelector, b?.itemSelector),
- holdTimeThreshold: 600,
- onHold: (dropTarget) => {
- if (dropTarget === undefined) {
- return;
- }
- if (getIsExpanded(dropTarget.itemSelector) === false) {
- setIsExpanded(dropTarget.itemSelector, true);
- }
- },
- });
-
- const dropHandlers = useDrop<ItemSelector>({
- ...sharedDropOptions,
-
- elementToData: (element) => {
- // We want to make sure edge detection is calculated relative
- // to the element with the data-drop-target-id attribute.
- // So, unless it has the attribute,
- // we return `false` to make useDrop go up the tree.
- if (element.getAttribute("data-drop-target-id") === null) {
- return false;
- }
- return getItemSelectorFromElement(element);
- },
-
- swapDropTarget: (dropTarget) => {
- if (dragItemSelector === undefined || dropTarget === undefined) {
- return;
- }
-
- let newDropItemSelector = dropTarget.data.slice();
-
- if (dropTarget.area === "top" || dropTarget.area === "bottom") {
- newDropItemSelector.shift();
- }
-
- // Don't allow to drop inside drag item or any of its children
- const [dragItemId] = dragItemSelector;
- const dragItemIndex = newDropItemSelector.indexOf(dragItemId);
- if (dragItemIndex !== -1) {
- newDropItemSelector.splice(0, dragItemIndex + 1);
- }
-
- // select closest droppable
- const ancestorIndex = findClosestDroppableIndex(newDropItemSelector);
- if (ancestorIndex === -1) {
- return;
- }
- newDropItemSelector = newDropItemSelector.slice(ancestorIndex);
-
- const element = getElementByItemSelector(
- rootRef.current ?? undefined,
- newDropItemSelector
- );
-
- if (element === undefined) {
- return;
- }
-
- return { data: newDropItemSelector, element, final: true };
- },
-
- onDropTargetChange: (dropTarget) => {
- if (dropTarget === undefined) {
- onDropTargetChange(undefined);
- } else {
- const itemDropTarget = {
- itemSelector: dropTarget.data,
- indexWithinChildren: dropTarget.indexWithinChildren,
- placement: dropTarget.placement,
- };
- onDropTargetChange(itemDropTarget);
- }
- },
- });
-
- const dragHandlers = useDrag<ItemSelector>({
- shiftDistanceThreshold: INDENT,
-
- elementToData: (element) => {
- if (element.hasAttribute("contenteditable")) {
- return false;
- }
- const dragItemSelector = getItemSelectorFromElement(element);
- // tree root is not draggable
- if (dragItemSelector.length === 1) {
- return false;
- }
-
- if (canLeaveParent(dragItemSelector) === false) {
- return false;
- }
-
- return dragItemSelector;
- },
- onStart: ({ data: itemSelector }) => {
- onSelect?.(itemSelector);
- onDragItemChange(itemSelector);
- dropHandlers.handleStart();
- autoScrollHandlers.setEnabled(true);
- },
- onMove: (point) => {
- dropHandlers.handleMove(point);
- autoScrollHandlers.handleMove(point);
- },
- onShiftChange: ({ shifts }) => {
- setHorizontalShift(shifts);
- },
- onEnd: ({ isCanceled }) => {
- if (shiftedDropTarget && dragItemSelector && isCanceled === false) {
- onDragEnd({
- itemSelector: dragItemSelector,
- dropTarget: {
- itemSelector: shiftedDropTarget.itemSelector,
- position: shiftedDropTarget.position,
- },
- });
- } else {
- onCancel();
- }
-
- autoScrollHandlers.setEnabled(false);
- setHorizontalShift(0);
- dropHandlers.handleEnd({ isCanceled });
- useHoldHandler.reset();
- },
- });
-
- const autoScrollHandlers = useAutoScroll();
-
- useDragCursor(dragItemSelector !== undefined);
-
- return (
- <ScrollArea
- // TODO allow resizing of the panel instead.
- direction="both"
- css={{
- width: "100%",
- overflow: "hidden",
- flexBasis: 0,
- flexGrow: 1,
- "&:hover": showNestingLineVars(),
- }}
- ref={(element) => {
- rootRef.current = element;
- autoScrollHandlers.targetRef(element);
- dragHandlers.rootRef(element);
- dropHandlers.rootRef(element);
- }}
- onScroll={dropHandlers.handleScroll}
- >
- <FocusScope>
- <KeyboardNavigation
- editingItemId={editingItemId}
- onExpandedChange={(expanded) => {
- if (selectedItemSelector) {
- expanded ??= getIsExpanded(selectedItemSelector) === false;
- setIsExpanded(selectedItemSelector, expanded);
- }
- }}
- >
- <TreeNode
- renderItem={renderItem}
- getItemChildren={getItemChildren}
- getItemProps={getItemProps}
- isItemHidden={isItemHidden}
- onSelect={onSelect}
- onHover={onHover}
- selectedItemSelector={selectedItemSelector}
- highlightedItemSelector={highlightedItemSelector}
- itemData={root}
- getIsExpanded={getIsExpanded}
- setIsExpanded={(itemSelector, value, all) => {
- setIsExpanded(itemSelector, value, all);
- dropHandlers.handleDomMutation();
- }}
- dropTargetItemSelector={shiftedDropTarget?.itemSelector}
- />
- </KeyboardNavigation>
- </FocusScope>
- {/* To not intersect last element with the scroll */}
- <Box css={{ height: theme.spacing[7] }}></Box>
- {shiftedDropTarget?.placement &&
- createPortal(
- <TreePositionIndicator
- x={shiftedDropTarget.placement.x}
- y={shiftedDropTarget.placement.y}
- length={shiftedDropTarget.placement.length}
- />,
- document.body
- )}
- </ScrollArea>
- );
-};
-
-const useExpandState = <Data extends { id: string }>({
- selectedItemSelector,
- getItemChildren,
-}: {
- selectedItemSelector: undefined | ItemSelector;
- getItemChildren: (itemSelector: ItemSelector) => Data[];
-}) => {
- const [expandMap, setExpandMap] = useState<Map<string, boolean>>(new Map());
-
- // whenever selected instance is changed
- // all its parents should be automatically expanded
- const prevSelectedItemSelector = useRef<ItemSelector>();
- useEffect(() => {
- if (
- areItemSelectorsEqual(
- selectedItemSelector,
- prevSelectedItemSelector.current
- )
- ) {
- return;
- }
- prevSelectedItemSelector.current = selectedItemSelector;
- if (selectedItemSelector === undefined) {
- return;
- }
- setExpandMap((expandMap) => {
- const newExpandMap = new Map(expandMap);
- let expanded = 0;
- // do not expand the selected instance itself, start with parent
- for (let index = 1; index < selectedItemSelector.length; index += 1) {
- const key = selectedItemSelector.slice(index).join();
- if (newExpandMap.get(key) !== true) {
- newExpandMap.set(key, true);
- expanded += 1;
- }
- }
- // prevent rerender if nothing new is expanded
- return expanded === 0 ? expandMap : newExpandMap;
- });
- }, [selectedItemSelector]);
-
- const getIsExpanded = useCallback(
- (itemSelector: ItemSelector) => {
- // root is always expanded
- if (itemSelector.length === 1) {
- return true;
- }
- return expandMap.get(itemSelector.join()) === true;
- },
- [expandMap]
- );
-
- const setIsExpanded = useCallback(
- (itemSelector: ItemSelector, value: boolean, all?: boolean) => {
- setExpandMap((expandMap) => {
- const newExpandMap = new Map(expandMap);
- if (all) {
- const addChildren = (parentSelector: string[]) => {
- for (const child of getItemChildren(parentSelector)) {
- const itemSelector = [child.id, ...parentSelector];
- newExpandMap.set(itemSelector.join(), value);
- addChildren(itemSelector);
- }
- };
- newExpandMap.set(itemSelector.join(), value);
- addChildren(itemSelector);
- return newExpandMap;
- }
- newExpandMap.set(itemSelector.join(), value);
- return newExpandMap;
- });
- },
- [getItemChildren]
- );
-
- return { getIsExpanded, setIsExpanded };
-};
diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.ts
index 4131e1929e..561c10b5c9 100644
--- a/packages/design-system/src/index.ts
+++ b/packages/design-system/src/index.ts
@@ -86,4 +86,3 @@ export * from "./components/kbd";
// Deprecated
export * from "./components/__DEPRECATED__/list";
-export * from "./components/__DEPRECATED__/tree";
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4d41323a72..12e06acc6f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1405,9 +1405,6 @@ importers:
downshift:
specifier: ^6.1.7
version: 6.1.7([email protected])
- immer:
- specifier: ^10.0.3
- version: 10.0.3
match-sorter:
specifier: ^6.3.4
version: 6.3.4
@@ -1430,9 +1427,6 @@ importers:
'@jest/globals':
specifier: ^29.7.0
version: 29.7.0
- '@testing-library/react-hooks':
- specifier: ^8.0.1
'@types/react':
specifier: ^18.2.70
version: 18.2.79