Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
Access instance data by id in tree (#1265)
Bogdan Chadkin60a2380884f4
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/pages.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/pages.tsxindex 34f3e76de9..b349a010a1 100644--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/pages.tsx+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/pages.tsx@@ -59,18 +59,6 @@ const toTreeData = (pages: Pages): PagesTreeNode => {};};-const staticTreeProps = {- getItemChildren(node: PagesTreeNode) {- if (node.type === "folder") {- return node.children;- }- return [];- },- getIsExpanded(_node: PagesTreeNode) {- return true;- },-};-const MenuButton = styled(DeprecatedIconButton, {color: theme.colors.hint,"&:hover, &:focus-visible": { color: theme.colors.hiContrast },@@ -220,7 +208,13 @@ const PagesPanel = ({onSelect={onSelect}itemData={pagesTree}renderItem={renderItem}- {...staticTreeProps}+ getItemChildren={(nodeId) => {+ if (nodeId === pagesTree.id && pagesTree.type === "folder") {+ return pagesTree.children;+ }+ return [];+ }}+ getIsExpanded={() => true}/></Box>);diff --git a/apps/builder/app/builder/shared/tree/index.tsx b/apps/builder/app/builder/shared/tree/index.tsxindex 0a54012852..de132c42da 100644--- a/apps/builder/app/builder/shared/tree/index.tsx+++ b/apps/builder/app/builder/shared/tree/index.tsx@@ -1,4 +1,4 @@-import { useCallback } from "react";+import { useCallback, useMemo } from "react";import { useStore } from "@nanostores/react";import {Tree,@@ -15,35 +15,12 @@ import {type WsComponentMeta,} from "@webstudio-is/react-sdk";import { instancesIndexStore } from "~/shared/nano-states";-import { getInstanceAncestorsAndSelf } from "~/shared/tree-utils";+import {+ createInstancesIndex,+ getInstanceAncestorsAndSelf,+} from "~/shared/tree-utils";const instanceRelatedProps = {- canLeaveParent(item: Instance) {- const meta = getComponentMeta(item.component);- return meta?.type !== "rich-text-child";- },- canAcceptChild(item: Instance) {- const meta = getComponentMeta(item.component);- return meta?.type === "body" || meta?.type === "container";- },- getItemChildren(item: Instance) {- const meta = getComponentMeta(item.component);-- // We want to avoid calling .filter() unnecessarily, because this is a hot path for performance.- // We rely on the fact that only rich-text or rich-text-child components may have `string` children.- if (- meta?.type === "body" ||- meta?.type === "container" ||- meta?.type === "control" ||- meta?.type === "embed"- ) {- return item.children as Instance[];- }-- return item.children.filter(- (child): child is Instance => child.type === "instance"- );- },renderItem(props: TreeItemRenderProps<Instance>) {const meta = getComponentMeta(props.itemData.component);if (meta === undefined) {@@ -59,10 +36,37 @@ const instanceRelatedProps = {},} as const;+const getInstanceChildren = (instance: undefined | Instance) => {+ if (instance === undefined) {+ return [];+ }+ const meta = getComponentMeta(instance.component);++ // We want to avoid calling .filter() unnecessarily, because this is a hot path for performance.+ // We rely on the fact that only rich-text or rich-text-child components may have `string` children.+ if (+ meta?.type === "body" ||+ meta?.type === "container" ||+ meta?.type === "control" ||+ meta?.type === "embed"+ ) {+ return instance.children as Instance[];+ }++ return instance.children.filter(+ (child): child is Instance => child.type === "instance"+ );+};+export const InstanceTree = (props: Omit<TreeProps<Instance>,- keyof typeof instanceRelatedProps | "findItemById" | "getItemPath"+ | keyof typeof instanceRelatedProps+ | "findItemById"+ | "getItemPath"+ | "canLeaveParent"+ | "canAcceptChild"+ | "getItemChildren">) => {const instancesIndex = useStore(instancesIndexStore);@@ -82,25 +86,74 @@ export const InstanceTree = ([instancesIndex]);+ const canLeaveParent = useCallback(+ (instanceId: Instance["id"]) => {+ const instance = instancesIndex.instancesById.get(instanceId);+ if (instance === undefined) {+ return false;+ }+ const meta = getComponentMeta(instance.component);+ return meta?.type !== "rich-text-child";+ },+ [instancesIndex]+ );++ const canAcceptChild = useCallback(+ (instanceId: Instance["id"]) => {+ const instance = instancesIndex.instancesById.get(instanceId);+ if (instance === undefined) {+ return false;+ }+ const meta = getComponentMeta(instance.component);+ return meta?.type === "body" || meta?.type === "container";+ },+ [instancesIndex]+ );++ const getItemChildren = useCallback(+ (instanceId: Instance["id"]) => {+ const instance = instancesIndex.instancesById.get(instanceId);+ return getInstanceChildren(instance);+ },+ [instancesIndex]+ );+return (<Tree{...props}{...instanceRelatedProps}findItemById={findItemById}getItemPath={getItemPath}+ canLeaveParent={canLeaveParent}+ canAcceptChild={canAcceptChild}+ getItemChildren={getItemChildren}/>);};export const InstanceTreeNode = (props: Omit<TreeNodeProps<Instance>, "getItemChildren" | "renderItem">-) => (- <TreeNode- {...props}- getItemChildren={instanceRelatedProps.getItemChildren}- renderItem={instanceRelatedProps.renderItem}- />-);+) => {+ const instancesIndex = useMemo(+ () => createInstancesIndex(props.itemData),+ [props.itemData]+ );+ const getItemChildren = useCallback(+ (instanceId: Instance["id"]) => {+ const instance = instancesIndex.instancesById.get(instanceId);+ return getInstanceChildren(instance);+ },+ [instancesIndex]+ );++ return (+ <TreeNode+ {...props}+ getItemChildren={getItemChildren}+ renderItem={instanceRelatedProps.renderItem}+ />+ );+};export const getInstanceLabel = (instance: { label?: string },diff --git a/packages/design-system/src/components/tree/horizontal-shift.test.ts b/packages/design-system/src/components/tree/horizontal-shift.test.tsindex 085a8446b7..66d11763fa 100644--- a/packages/design-system/src/components/tree/horizontal-shift.test.ts+++ b/packages/design-system/src/components/tree/horizontal-shift.test.ts@@ -3,13 +3,7 @@ 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 {- canAcceptChild,- findItemById,- getItemChildren,- getItemPath,- Item,-} from "./test-tree-data";+import { findItemById, getItemPath, Item } from "./test-tree-data";const box1: Item = { canAcceptChildren: true, id: "box1", children: [] };const box2: Item = { canAcceptChildren: true, id: "box2", children: [] };@@ -115,8 +109,10 @@ const render = (root: tree,getIsExpanded: (itemSelector: ItemSelector) =>(findItemById(tree, itemSelector[0])?.children.length ?? 0) > 0,- canAcceptChild,- getItemChildren,+ canAcceptChild: (itemId: ItemId) =>+ findItemById(tree, itemId)?.canAcceptChildren ?? false,+ getItemChildren: (itemId: ItemId) =>+ findItemById(tree, itemId)?.children ?? [],getItemPath,},});diff --git a/packages/design-system/src/components/tree/horizontal-shift.ts b/packages/design-system/src/components/tree/horizontal-shift.tsindex 2178906bf3..43013d28a6 100644--- a/packages/design-system/src/components/tree/horizontal-shift.ts+++ b/packages/design-system/src/components/tree/horizontal-shift.ts@@ -1,6 +1,6 @@import { useMemo, useState } from "react";import type { Placement } from "../primitives/dnd";-import type { ItemDropTarget, ItemSelector } from "./item-utils";+import type { ItemDropTarget, ItemId, ItemSelector } from "./item-utils";import { getPlacementIndicatorAlignment } from "./tree-node";export type ShiftedDropTarget = {@@ -9,7 +9,7 @@ export type ShiftedDropTarget = {placement?: Placement;};-export const useHorizontalShift = <Data extends { id: string }>({+export const useHorizontalShift = <Data extends { id: ItemId }>({dragItemSelector,dropTarget,root,@@ -18,8 +18,8 @@ export const useHorizontalShift = <Data extends { id: string }>({canAcceptChild,getItemChildren,}: {- getItemChildren: (item: Data) => Data[];- canAcceptChild: (item: Data) => boolean;+ getItemChildren: (itemId: ItemId) => Data[];+ canAcceptChild: (itemId: ItemId) => boolean;getItemPath: (root: Data, id: string) => Data[];dragItemSelector: undefined | ItemSelector;dropTarget: ItemDropTarget<Data> | undefined;@@ -82,7 +82,7 @@ export const useHorizontalShift = <Data extends { id: string }>({let newPosition = indexWithinChildren;const isAtTheBottom = (parent: Data, index: number) => {- const children = getItemChildren(parent);+ const children = getItemChildren(parent.id);// 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.@@ -95,14 +95,14 @@ export const useHorizontalShift = <Data extends { id: string }>({const potentialNewParent = dropTargetPath[index];if (isAtTheBottom(newParent, newPosition) &&- canAcceptChild(potentialNewParent) &&+ canAcceptChild(potentialNewParent.id) &&shifted < currentDepth - desiredDepth) {shifted = index;newParent = potentialNewParent;newParentSelector = dropItemSelector.slice(index);const child = dropTargetPath[index - 1];- const childPosition = getItemChildren(newParent).findIndex(+ const childPosition = getItemChildren(newParent.id).findIndex((item) => item.id === child.id);newPosition = childPosition + 1;@@ -131,7 +131,7 @@ export const useHorizontalShift = <Data extends { id: string }>({parent: Data,position: number | "last"): undefined | Data => {- const children = getItemChildren(parent);+ const children = getItemChildren(parent.id);const index = position === "last" ? children.length - 1 : position;// There's a special case when the placement line is below the drag item.@@ -146,7 +146,7 @@ export const useHorizontalShift = <Data extends { id: string }>({while (potentialNewParent &&getIsExpanded([potentialNewParent.id, ...newParentSelector]) &&- canAcceptChild(potentialNewParent) &&+ canAcceptChild(potentialNewParent.id) &&shifted < desiredDepth - currentDepth) {newParent = potentialNewParent;diff --git a/packages/design-system/src/components/tree/tree-node.tsx b/packages/design-system/src/components/tree/tree-node.tsxindex 5a9a8c8377..6c10ae63b9 100644--- a/packages/design-system/src/components/tree/tree-node.tsx+++ b/packages/design-system/src/components/tree/tree-node.tsx@@ -7,6 +7,7 @@ import { Flex } from "../flex";import { DeprecatedText2 } from "../__DEPRECATED__/text2";import { keyframes, styled } from "../../stitches.config";import { theme } from "../../stitches.config";+import type { ItemId } from "./item-utils";export const INDENT = 16;const ITEM_HEIGHT = 32;@@ -383,9 +384,9 @@ export const TreeItemLabel = ({</>);-export type TreeNodeProps<Data extends { id: string }> = {+export type TreeNodeProps<Data extends { id: ItemId }> = {itemData: Data;- getItemChildren: (item: Data) => Data[];+ getItemChildren: (itemId: ItemId) => Data[];renderItem: (props: TreeItemRenderProps<Data>) => React.ReactNode;getIsExpanded: (item: Data) => boolean;@@ -428,7 +429,7 @@ export const TreeNode = <Data extends { id: string }>({const collapsibleContentRef = useRef<HTMLDivElement>(null);- const itemChildren = getItemChildren(itemData);+ const itemChildren = getItemChildren(itemData.id);const isAlwaysExpanded = level === 0;const isExpandable = itemChildren.length > 0;diff --git a/packages/design-system/src/components/tree/tree.stories.tsx b/packages/design-system/src/components/tree/tree.stories.tsxindex bc52edd343..abd09ed26b 100644--- a/packages/design-system/src/components/tree/tree.stories.tsx+++ b/packages/design-system/src/components/tree/tree.stories.tsx@@ -1,14 +1,7 @@import type { ComponentMeta } from "@storybook/react";import { useState } from "react";import { Tree } from "./tree";-import {- canAcceptChild,- findItemById,- getItemChildren,- getItemPath,- Item,- reparent,-} from "./test-tree-data";+import { findItemById, getItemPath, Item, reparent } from "./test-tree-data";import { Flex } from "../flex";import { TreeItemLabel, TreeItemBody } from "./tree-node";import type { ItemSelector } from "./item-utils";@@ -82,9 +75,11 @@ export const StressTest = ({ animate }: { animate: boolean }) => {<TreefindItemById={findItemById}getItemPath={getItemPath}- canAcceptChild={canAcceptChild}+ canAcceptChild={(itemId) =>+ findItemById(root, itemId)?.canAcceptChildren ?? false+ }canLeaveParent={() => true}- getItemChildren={getItemChildren}+ getItemChildren={(itemId) => findItemById(root, itemId)?.children ?? []}animate={animate}root={root}selectedItemSelector={selectedItemSelector}diff --git a/packages/design-system/src/components/tree/tree.tsx b/packages/design-system/src/components/tree/tree.tsxindex 75cdbd6936..47bee21c5e 100644--- a/packages/design-system/src/components/tree/tree.tsx+++ b/packages/design-system/src/components/tree/tree.tsx@@ -13,6 +13,7 @@ import {import { Box } from "../box";import { useHorizontalShift } from "./horizontal-shift";import {+ type ItemId,type ItemSelector,type ItemDropTarget,areItemSelectorsEqual,@@ -24,11 +25,11 @@ export type TreeProps<Data extends { id: string }> = {root: Data;selectedItemSelector: undefined | ItemSelector;- canLeaveParent: (item: Data) => boolean;- canAcceptChild: (item: Data) => boolean;+ canLeaveParent: (itemId: ItemId) => boolean;+ canAcceptChild: (itemId: ItemId) => boolean;findItemById: (root: Data, id: string) => Data | undefined;getItemPath: (root: Data, id: string) => Data[];- getItemChildren: (item: Data) => Data[];+ getItemChildren: (itemId: ItemId) => Data[];renderItem: (props: TreeItemRenderProps<Data>) => React.ReactNode;onSelect?: (itemId: string) => void;@@ -56,8 +57,6 @@ export const Tree = <Data extends { id: string }>({}: TreeProps<Data>) => {const { getIsExpanded, setIsExpanded } = useExpandState({selectedItemSelector,- root,- findItemById,getItemChildren,});@@ -96,8 +95,9 @@ export const Tree = <Data extends { id: string }>({isEqual: (a, b) => areItemSelectorsEqual(a.itemSelector, b.itemSelector),holdTimeThreshold: 600,onHold: (dropTarget) => {+ const [itemId] = dropTarget.itemSelector;if (- getItemChildren(dropTarget.data).length > 0 ||+ getItemChildren(itemId).length > 0 ||getIsExpanded(dropTarget.itemSelector) === false) {setIsExpanded(dropTarget.itemSelector, true);@@ -141,7 +141,7 @@ export const Tree = <Data extends { id: string }>({path.splice(0, dragItemIndex + 1);}- const data = path.find(canAcceptChild);+ const data = path.find((item) => canAcceptChild(item.id));if (data === undefined) {return getFallbackDropTarget();@@ -199,7 +199,7 @@ export const Tree = <Data extends { id: string }>({return false;}- if (canLeaveParent(instance) === false) {+ if (canLeaveParent(instance.id) === false) {return false;}@@ -336,22 +336,23 @@ const useKeyboardNavigation = <Data extends { id: string }>({}: {root: Data;selectedItemSelector: undefined | ItemSelector;- getItemChildren: (item: Data) => Data[];+ getItemChildren: (itemId: ItemId) => Data[];getIsExpanded: (itemSelector: ItemSelector) => boolean;setIsExpanded: (itemSelector: ItemSelector, isExpanded: boolean) => void;onEsc: () => void;}) => {const flatCurrentlyExpandedTree = useMemo(() => {const result: ItemSelector[] = [];- const traverse = (item: Data, itemSelector: ItemSelector) => {+ const traverse = (itemSelector: ItemSelector) => {+ const [itemId] = itemSelector;result.push(itemSelector);if (getIsExpanded(itemSelector)) {- for (const child of getItemChildren(item)) {- traverse(child, [child.id, ...itemSelector]);+ for (const child of getItemChildren(itemId)) {+ traverse([child.id, ...itemSelector]);}}};- traverse(root, [root.id]);+ traverse([root.id]);return result;}, [root, getIsExpanded, getItemChildren]);@@ -471,14 +472,10 @@ const useKeyboardNavigation = <Data extends { id: string }>({const useExpandState = <Data extends { id: string }>({selectedItemSelector,- root,- findItemById,getItemChildren,}: {selectedItemSelector: undefined | ItemSelector;- root: Data;- findItemById: (root: Data, id: string) => Data | undefined;- getItemChildren: (item: Data) => Data[];+ getItemChildren: (itemId: ItemId) => Data[];}) => {const [record, setRecord] = useState<Record<string, boolean>>({});@@ -520,16 +517,14 @@ const useExpandState = <Data extends { id: string }>({if (itemSelector.length === 1) {return true;}- const item = findItemById(root, itemSelector[0]);- if (item === undefined) {- return false;- }+ const [itemId] = itemSelector;return (- getItemChildren(item).length > 0 && record[itemSelector.join()] === true+ getItemChildren(itemId).length > 0 &&+ record[itemSelector.join()] === true);},- [record, root, findItemById, getItemChildren]+ [record, getItemChildren]);const setIsExpanded = useCallback(