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.

Address selected instance with tree path (#1228)

Bogdan Chadkin91fbdb2ee1eb
diff --git a/apps/builder/app/builder/features/footer/breadcrumbs.tsx b/apps/builder/app/builder/features/footer/breadcrumbs.tsx
index 9fc5ce1280..6378fa5f33 100644
--- a/apps/builder/app/builder/features/footer/breadcrumbs.tsx
+++ b/apps/builder/app/builder/features/footer/breadcrumbs.tsx
@@ -1,4 +1,3 @@
-import { useMemo } from "react";
import { useStore } from "@nanostores/react";
import { ChevronRightIcon } from "@webstudio-is/icons";
import {
@@ -8,10 +7,10 @@ import {
DeprecatedText2,
} from "@webstudio-is/design-system";
import {
- instancesIndexStore,
- selectedInstanceIdStore,
+ instancesStore,
+ selectedInstanceAddressStore,
} from "~/shared/nano-states";
-import { getInstanceAncestorsAndSelf } from "~/shared/tree-utils";
+import { getAncestorInstanceAddress } from "~/shared/tree-utils";
type BreadcrumbProps = {
children: JSX.Element | string;
@@ -39,33 +38,41 @@ const Breadcrumb = ({ children, onClick }: BreadcrumbProps) => {
};
export const Breadcrumbs = () => {
- const instancesIndex = useStore(instancesIndexStore);
- const selectedInstanceId = useStore(selectedInstanceIdStore);
-
- const selectedInstancePath = useMemo(() => {
- if (selectedInstanceId === undefined) {
- return [];
- }
- return getInstanceAncestorsAndSelf(instancesIndex, selectedInstanceId);
- }, [selectedInstanceId, instancesIndex]);
+ const instances = useStore(instancesStore);
+ const selectedInstanceAddress = useStore(selectedInstanceAddressStore);
return (
<Flex align="center" css={{ height: "100%" }}>
- {selectedInstancePath.length === 0 ? (
+ {selectedInstanceAddress === undefined ? (
<Breadcrumb>
<DeprecatedText2>No instance selected</DeprecatedText2>
</Breadcrumb>
) : (
- selectedInstancePath.map((instance) => (
- <Breadcrumb
- key={instance.id}
- onClick={() => {
- selectedInstanceIdStore.set(instance.id);
- }}
- >
- {instance.component}
- </Breadcrumb>
- ))
+ selectedInstanceAddress
+ // start breadcrumbs from the root
+ .slice()
+ .reverse()
+ .map((instanceId) => {
+ const instance = instances.get(instanceId);
+ if (instance === undefined) {
+ return;
+ }
+ return (
+ <Breadcrumb
+ key={instance.id}
+ onClick={() => {
+ selectedInstanceAddressStore.set(
+ getAncestorInstanceAddress(
+ selectedInstanceAddress,
+ instance.id
+ )
+ );
+ }}
+ >
+ {instance.component}
+ </Breadcrumb>
+ );
+ })
)}
</Flex>
);
diff --git a/apps/builder/app/builder/features/sidebar-left/navigator/navigator.tsx b/apps/builder/app/builder/features/sidebar-left/navigator/navigator.tsx
index 772612e0aa..acd1cd681a 100644
--- a/apps/builder/app/builder/features/sidebar-left/navigator/navigator.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/navigator/navigator.tsx
@@ -3,13 +3,15 @@ import { useStore } from "@nanostores/react";
import { Flex } from "@webstudio-is/design-system";
import type { Instance } from "@webstudio-is/project-build";
import {
- selectedInstanceIdStore,
+ selectedInstanceAddressStore,
hoveredInstanceIdStore,
useRootInstance,
+ instancesStore,
} from "~/shared/nano-states";
import { InstanceTree } from "~/builder/shared/tree";
import { reparentInstance } from "~/shared/instance-utils";
import { Header, CloseButton } from "../header";
+import { getInstanceAddress } from "~/shared/tree-utils";
type NavigatorProps = {
isClosable?: boolean;
@@ -17,11 +19,14 @@ type NavigatorProps = {
};
export const Navigator = ({ isClosable, onClose }: NavigatorProps) => {
- const selectedInstanceId = useStore(selectedInstanceIdStore);
+ const selectedInstanceAddress = useStore(selectedInstanceAddressStore);
+ const selectedInstanceId = selectedInstanceAddress?.[0];
const [rootInstance] = useRootInstance();
const handleSelect = useCallback((instanceId: Instance["id"]) => {
- selectedInstanceIdStore.set(instanceId);
+ const instances = instancesStore.get();
+ const instanceAddress = getInstanceAddress(instances, instanceId);
+ selectedInstanceAddressStore.set(instanceAddress);
}, []);
const handleDragEnd = useCallback(
@@ -53,6 +58,7 @@ export const Navigator = ({ isClosable, onClose }: NavigatorProps) => {
<Flex css={{ flexGrow: 1, flexDirection: "column" }}>
<InstanceTree
root={rootInstance}
+ // @todo accept and provide in callback instance address instead of just id
selectedItemId={selectedInstanceId}
onSelect={handleSelect}
onHover={handleHover}
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx b/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx
index db8802b88d..a6b8c81b24 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/components/components.tsx
@@ -13,7 +13,7 @@ import { utils } from "@webstudio-is/project";
import { findClosestDroppableTarget } from "~/shared/tree-utils";
import {
instancesIndexStore,
- selectedInstanceIdStore,
+ selectedInstanceAddressStore,
} from "~/shared/nano-states";
import { useSubscribe, type Publish } from "~/shared/pubsub";
import { useCanvasRect } from "~/builder/shared/nano-states";
@@ -175,7 +175,8 @@ export const TabContent = ({ publish, onSetActiveTab }: TabContentProps) => {
onSetActiveTab("none");
const dropTarget = findClosestDroppableTarget(
instancesIndexStore.get(),
- selectedInstanceIdStore.get()
+ // @todo accept instance address
+ selectedInstanceAddressStore.get()?.[0]
);
insertNewComponentInstance(component, dropTarget);
}}
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx
index 099efc3a61..a8c4b33a08 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/settings.tsx
@@ -401,7 +401,7 @@ export const PageSettings = ({
}
const page = pages.pages.find((item) => item.id === pageId);
if (page) {
- deleteInstance(page.rootInstanceId);
+ deleteInstance([page.rootInstanceId]);
}
pagesStore.set({
homePage: pages.homePage,
diff --git a/apps/builder/app/builder/features/style-panel/shared/style-info.ts b/apps/builder/app/builder/features/style-panel/shared/style-info.ts
index 16666114b1..3a3959977d 100644
--- a/apps/builder/app/builder/features/style-panel/shared/style-info.ts
+++ b/apps/builder/app/builder/features/style-panel/shared/style-info.ts
@@ -12,7 +12,7 @@ import type {
import {
instancesIndexStore,
selectedInstanceBrowserStyleStore,
- selectedInstanceIdStore,
+ selectedInstanceAddressStore,
selectedStyleSourceStore,
stylesIndexStore,
useBreakpoints,
@@ -232,7 +232,7 @@ export const useStyleInfo = () => {
const [breakpoints] = useBreakpoints();
const selectedBreakpoint = useStore(selectedBreakpointStore);
const selectedBreakpointId = selectedBreakpoint?.id;
- const selectedInstanceId = useStore(selectedInstanceIdStore);
+ const selectedInstanceAddress = useStore(selectedInstanceAddressStore);
const selectedStyleSource = useStore(selectedStyleSourceStore);
const selectedStyleSourceId = selectedStyleSource?.id;
const browserStyle = useStore(selectedInstanceBrowserStyleStore);
@@ -262,13 +262,15 @@ export const useStyleInfo = () => {
const inheritedInfo = useMemo(() => {
if (
selectedBreakpointId === undefined ||
- selectedInstanceId === undefined
+ selectedInstanceAddress === undefined
) {
return {};
}
+ const [selectedInstanceId] = selectedInstanceAddress;
return getInheritedInfo(
instancesIndex,
stylesByInstanceId,
+ // @todo accept instance address
selectedInstanceId,
cascadedBreakpointIds,
selectedBreakpointId
@@ -278,23 +280,26 @@ export const useStyleInfo = () => {
stylesByInstanceId,
cascadedBreakpointIds,
selectedBreakpointId,
- selectedInstanceId,
+ selectedInstanceAddress,
]);
const cascadedInfo = useMemo(() => {
- if (selectedInstanceId === undefined) {
+ if (selectedInstanceAddress === undefined) {
return {};
}
+ const [selectedInstanceId] = selectedInstanceAddress;
return getCascadedInfo(
stylesByInstanceId,
+ // @todo accept instance address
selectedInstanceId,
cascadedBreakpointIds
);
- }, [stylesByInstanceId, selectedInstanceId, cascadedBreakpointIds]);
+ }, [stylesByInstanceId, selectedInstanceAddress, cascadedBreakpointIds]);
const presetStyle = useMemo(() => {
- return getPresetStyle(instancesIndex, selectedInstanceId);
- }, [instancesIndex, selectedInstanceId]);
+ // @todo accept instance address
+ return getPresetStyle(instancesIndex, selectedInstanceAddress?.[0]);
+ }, [instancesIndex, selectedInstanceAddress]);
const styleInfoData = useMemo(() => {
const styleInfoData: StyleInfo = {};
diff --git a/apps/builder/app/builder/features/style-panel/style-settings.tsx b/apps/builder/app/builder/features/style-panel/style-settings.tsx
index f7e22d87d7..809743eac2 100644
--- a/apps/builder/app/builder/features/style-panel/style-settings.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-settings.tsx
@@ -15,10 +15,7 @@ import type { SetProperty, CreateBatchUpdate } from "./shared/use-style-data";
import type { StyleInfo } from "./shared/style-info";
import type { RenderPropertyProps } from "./style-sections";
import { useStore } from "@nanostores/react";
-import {
- instancesIndexStore,
- selectedInstanceIdStore,
-} from "~/shared/nano-states";
+import { selectedInstanceAddressStore } from "~/shared/nano-states";
import { useInstanceStyleData } from "./shared/style-info";
// Finds a property/value by using any available form: property, label, value
@@ -99,15 +96,9 @@ export type StyleSettingsProps = {
};
const useParentStyle = () => {
- const selectedInstanceId = useStore(selectedInstanceIdStore);
- const instanceIndex = useStore(instancesIndexStore);
-
- const parentInstance =
- selectedInstanceId === undefined
- ? undefined
- : instanceIndex.parentInstancesById.get(selectedInstanceId);
-
- const parentInstanceStyleData = useInstanceStyleData(parentInstance?.id);
+ const selectedInstanceAddress = useStore(selectedInstanceAddressStore);
+ const parentInstanceId = selectedInstanceAddress?.[1];
+ const parentInstanceStyleData = useInstanceStyleData(parentInstanceId);
return parentInstanceStyleData;
};
diff --git a/apps/builder/app/builder/features/style-panel/style-source-section.tsx b/apps/builder/app/builder/features/style-panel/style-source-section.tsx
index 56ceaf4c57..9af3c224eb 100644
--- a/apps/builder/app/builder/features/style-panel/style-source-section.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-source-section.tsx
@@ -16,7 +16,7 @@ import {
import { useStore } from "@nanostores/react";
import {
availableStyleSourcesStore,
- selectedInstanceIdStore,
+ selectedInstanceAddressStore,
selectedInstanceStyleSourcesStore,
selectedStyleSourceIdStore,
selectedStyleSourceStore,
@@ -43,10 +43,11 @@ const getOrCreateStyleSourceSelectionMutable = (
};
const createStyleSource = (name: string) => {
- const selectedInstanceId = selectedInstanceIdStore.get();
- if (selectedInstanceId === undefined) {
+ const selectedInstanceAddress = selectedInstanceAddressStore.get();
+ if (selectedInstanceAddress === undefined) {
return;
}
+ const [selectedInstanceId] = selectedInstanceAddress;
const newStyleSource: StyleSource = {
type: "token",
id: nanoid(),
@@ -67,10 +68,11 @@ const createStyleSource = (name: string) => {
};
const addStyleSourceToInstace = (newStyleSourceId: StyleSource["id"]) => {
- const selectedInstanceId = selectedInstanceIdStore.get();
- if (selectedInstanceId === undefined) {
+ const selectedInstanceAddress = selectedInstanceAddressStore.get();
+ if (selectedInstanceAddress === undefined) {
return;
}
+ const [selectedInstanceId] = selectedInstanceAddress;
store.createTransaction(
[styleSourceSelectionsStore],
(styleSourceSelections) => {
@@ -87,10 +89,11 @@ const addStyleSourceToInstace = (newStyleSourceId: StyleSource["id"]) => {
};
const removeStyleSourceFromInstance = (styleSourceId: StyleSource["id"]) => {
- const selectedInstanceId = selectedInstanceIdStore.get();
- if (selectedInstanceId === undefined) {
+ const selectedInstanceAddress = selectedInstanceAddressStore.get();
+ if (selectedInstanceAddress === undefined) {
return;
}
+ const [selectedInstanceId] = selectedInstanceAddress;
store.createTransaction(
[styleSourceSelectionsStore],
(styleSourceSelections) => {
@@ -108,10 +111,11 @@ const removeStyleSourceFromInstance = (styleSourceId: StyleSource["id"]) => {
};
const duplicateStyleSource = (styleSourceId: StyleSource["id"]) => {
- const selectedInstanceId = selectedInstanceIdStore.get();
- if (selectedInstanceId === undefined) {
+ const selectedInstanceAddress = selectedInstanceAddressStore.get();
+ if (selectedInstanceAddress === undefined) {
return;
}
+ const [selectedInstanceId] = selectedInstanceAddress;
const styleSources = styleSourcesStore.get();
// style source may not exist in store which means
// temporary generated local stye source was not applied yet
@@ -153,10 +157,11 @@ const duplicateStyleSource = (styleSourceId: StyleSource["id"]) => {
};
const convertLocalStyleSourceToToken = (styleSourceId: StyleSource["id"]) => {
- const selectedInstanceId = selectedInstanceIdStore.get();
- if (selectedInstanceId === undefined) {
+ const selectedInstanceAddress = selectedInstanceAddressStore.get();
+ if (selectedInstanceAddress === undefined) {
return;
}
+ const [selectedInstanceId] = selectedInstanceAddress;
const newStyleSource: StyleSource = {
type: "token",
id: styleSourceId,
@@ -180,10 +185,11 @@ const convertLocalStyleSourceToToken = (styleSourceId: StyleSource["id"]) => {
};
const reorderStyleSources = (styleSourceIds: StyleSource["id"][]) => {
- const selectedInstanceId = selectedInstanceIdStore.get();
- if (selectedInstanceId === undefined) {
+ const selectedInstanceAddress = selectedInstanceAddressStore.get();
+ if (selectedInstanceAddress === undefined) {
return;
}
+ const [selectedInstanceId] = selectedInstanceAddress;
store.createTransaction(
[styleSourcesStore, styleSourceSelectionsStore],
(styleSources, styleSourceSelections) => {
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/hovered-instance-outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/hovered-instance-outline.tsx
index bb500c333e..224a9e31d1 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/hovered-instance-outline.tsx
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/hovered-instance-outline.tsx
@@ -3,21 +3,23 @@ import {
hoveredInstanceIdStore,
hoveredInstanceOutlineStore,
instancesStore,
- selectedInstanceIdStore,
+ selectedInstanceAddressStore,
useTextEditingInstanceId,
} from "~/shared/nano-states";
import { Outline } from "./outline";
import { Label } from "./label";
export const HoveredInstanceOutline = () => {
- const selectedInstanceId = useStore(selectedInstanceIdStore);
+ const selectedInstanceAddress = useStore(selectedInstanceAddressStore);
const hoveredInstanceId = useStore(hoveredInstanceIdStore);
const instanceOutline = useStore(hoveredInstanceOutlineStore);
const [textEditingInstanceId] = useTextEditingInstanceId();
const instances = useStore(instancesStore);
const isEditingText = textEditingInstanceId !== undefined;
- const isHoveringSelectedInstance = selectedInstanceId === hoveredInstanceId;
+ // @todo compare instance addresses
+ const isHoveringSelectedInstance =
+ selectedInstanceAddress?.[0] === hoveredInstanceId;
const instance = hoveredInstanceId
? instances.get(hoveredInstanceId)
: undefined;
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar/text-toolbar.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar/text-toolbar.tsx
index 6de8aa2c7c..9e9f117307 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar/text-toolbar.tsx
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/text-toolbar/text-toolbar.tsx
@@ -18,7 +18,7 @@ import {
} from "@webstudio-is/icons";
import { useSubscribe } from "~/shared/pubsub";
import { theme } from "@webstudio-is/design-system";
-import { selectedInstanceIdStore } from "~/shared/nano-states";
+import { selectedInstanceAddressStore } from "~/shared/nano-states";
type Format =
| "bold"
@@ -191,9 +191,9 @@ type TextToolbarProps = {
export const TextToolbar = ({ publish }: TextToolbarProps) => {
const [textToolbar] = useTextToolbarState();
- const selectedInstanceId = useStore(selectedInstanceIdStore);
+ const selectedInstanceAddress = useStore(selectedInstanceAddressStore);
- if (textToolbar == null || selectedInstanceId === undefined) {
+ if (textToolbar == null || selectedInstanceAddress === undefined) {
return null;
}
diff --git a/apps/builder/app/builder/features/workspace/workspace.tsx b/apps/builder/app/builder/features/workspace/workspace.tsx
index 2153a0fe39..a02e7e036e 100644
--- a/apps/builder/app/builder/features/workspace/workspace.tsx
+++ b/apps/builder/app/builder/features/workspace/workspace.tsx
@@ -2,7 +2,7 @@ import { useStore } from "@nanostores/react";
import { theme, Box, Flex, Toaster } from "@webstudio-is/design-system";
import { useCanvasWidth } from "~/builder/shared/nano-states";
import type { Publish } from "~/shared/pubsub";
-import { selectedInstanceIdStore } from "~/shared/nano-states";
+import { selectedInstanceAddressStore } from "~/shared/nano-states";
import {
workspaceRectStore,
zoomStore,
@@ -60,7 +60,7 @@ export const Workspace = ({
const workspaceRef = useSetWorkspaceRect();
const handleWorkspaceClick = () => {
- selectedInstanceIdStore.set(undefined);
+ selectedInstanceAddressStore.set(undefined);
};
return (
diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
index ae85954707..93eea98f8a 100644
--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
@@ -16,13 +16,14 @@ import {
import type { GetComponent } from "@webstudio-is/react-sdk";
import {
instancesStore,
- selectedInstanceIdStore,
+ selectedInstanceAddressStore,
useInstanceProps,
useInstanceStyles,
useTextEditingInstanceId,
} from "~/shared/nano-states";
import { useCssRules } from "~/canvas/shared/styles";
import { SelectedInstanceConnector } from "./selected-instance-connector";
+import { getInstanceAddress } from "~/shared/tree-utils";
const TextEditor = lazy(() => import("../text-editor"));
@@ -68,7 +69,7 @@ export const WebstudioComponentDev = ({
const [editingInstanceId, setTextEditingInstanceId] =
useTextEditingInstanceId();
- const selectedInstanceId = useStore(selectedInstanceIdStore);
+ const selectedInstanceAddress = useStore(selectedInstanceAddressStore);
const instanceProps = useInstanceProps(instance.id);
const userProps = useMemo(() => {
@@ -84,7 +85,8 @@ export const WebstudioComponentDev = ({
return result;
}, [instanceProps]);
- const isSelected = selectedInstanceId === instanceId;
+ // @todo compare instance addresses
+ const isSelected = selectedInstanceAddress?.[0] === instanceId;
// Scroll the selected instance into view when selected from navigator.
useEffect(() => {
@@ -172,9 +174,12 @@ export const WebstudioComponentDev = ({
}
});
}}
+ // @todo provide instance address
onSelectInstance={(instanceId) => {
setTextEditingInstanceId(undefined);
- selectedInstanceIdStore.set(instanceId);
+ selectedInstanceAddressStore.set(
+ getInstanceAddress(instancesStore.get(), instanceId)
+ );
}}
/>
</Suspense>
diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts
index dc9a9d1e9f..ebd2414f1c 100644
--- a/apps/builder/app/canvas/shared/styles.ts
+++ b/apps/builder/app/canvas/shared/styles.ts
@@ -5,7 +5,7 @@ import { addGlobalRules } from "@webstudio-is/project";
import {
assetsStore,
isPreviewModeStore,
- selectedInstanceIdStore,
+ selectedInstanceAddressStore,
useBreakpoints,
} from "~/shared/nano-states";
import type { StyleDecl } from "@webstudio-is/project-build";
@@ -263,7 +263,8 @@ const setCssVar = (id: string, property: string, value?: StyleValue) => {
const useUpdateStyle = () => {
useSubscribe("updateStyle", ({ id, updates }) => {
- const selectedInstanceId = selectedInstanceIdStore.get();
+ const selectedInstanceAddress = selectedInstanceAddressStore.get();
+ const selectedInstanceId = selectedInstanceAddress?.[0];
// Only update styles if they match the selected instance
// It can potentially happen that we selected a difference instance right after we changed the style in style panel.
if (id !== selectedInstanceId) {
diff --git a/apps/builder/app/canvas/shared/use-shortcuts.ts b/apps/builder/app/canvas/shared/use-shortcuts.ts
index 94a09e9263..2a20706b65 100644
--- a/apps/builder/app/canvas/shared/use-shortcuts.ts
+++ b/apps/builder/app/canvas/shared/use-shortcuts.ts
@@ -3,7 +3,7 @@ import { getComponentMeta } from "@webstudio-is/react-sdk";
import { shortcuts, options } from "~/shared/shortcuts";
import { publish, useSubscribe } from "~/shared/pubsub";
import {
- selectedInstanceIdStore,
+ selectedInstanceAddressStore,
selectedInstanceStore,
useTextEditingInstanceId,
isPreviewModeStore,
@@ -40,8 +40,8 @@ export const useShortcuts = () => {
useHotkeys(
"esc",
() => {
- const selectedInstanceId = selectedInstanceIdStore.get();
- if (selectedInstanceId === undefined) {
+ const selectedInstanceAddress = selectedInstanceAddressStore.get();
+ if (selectedInstanceAddress === undefined) {
return;
}
// Since we are in text editing mode, we want to first exit that mode without unselecting the instance.
@@ -49,7 +49,7 @@ export const useShortcuts = () => {
setEditingInstanceId(undefined);
return;
}
- selectedInstanceIdStore.set(undefined);
+ selectedInstanceAddressStore.set(undefined);
},
{ ...options, enableOnContentEditable: true },
[editingInstanceId]
diff --git a/apps/builder/app/canvas/shared/use-track-selected-element.ts b/apps/builder/app/canvas/shared/use-track-selected-element.ts
index cb9c427043..cbe40e5aa1 100644
--- a/apps/builder/app/canvas/shared/use-track-selected-element.ts
+++ b/apps/builder/app/canvas/shared/use-track-selected-element.ts
@@ -2,12 +2,16 @@ import { useEffect, useRef } from "react";
import { useStore } from "@nanostores/react";
import {
instancesIndexStore,
- selectedInstanceIdStore,
+ instancesStore,
+ selectedInstanceAddressStore,
useRootInstance,
useTextEditingInstanceId,
} from "~/shared/nano-states";
import { publish } from "~/shared/pubsub";
-import { findClosestRichTextInstance } from "~/shared/tree-utils";
+import {
+ findClosestRichTextInstance,
+ getInstanceAddress,
+} from "~/shared/tree-utils";
import { componentAttribute } from "@webstudio-is/react-sdk";
declare module "~/shared/pubsub" {
@@ -23,7 +27,8 @@ const eventOptions = {
const isHighlighting = () => getSelection()?.type === "Range";
export const useTrackSelectedElement = () => {
- const selectedInstanceId = useStore(selectedInstanceIdStore);
+ const selectedInstanceAddress = useStore(selectedInstanceAddressStore);
+ const selectedInstanceId = selectedInstanceAddress?.[0];
const [editingInstanceId, setEditingInstanceId] = useTextEditingInstanceId();
const editingInstanceIdRef = useRef(editingInstanceId);
editingInstanceIdRef.current = editingInstanceId;
@@ -32,6 +37,7 @@ export const useTrackSelectedElement = () => {
useEffect(() => {
if (
editingInstanceIdRef.current !== undefined &&
+ // @todo compare instance addresses
selectedInstanceId !== editingInstanceIdRef.current
) {
setEditingInstanceId(undefined);
@@ -62,6 +68,7 @@ export const useTrackSelectedElement = () => {
element = instanceElement;
}
+ // @todo find rendered instance address
const { id } = element;
// Enable clicking inside of content editable without trying to select the element as an instance.
@@ -78,12 +85,16 @@ export const useTrackSelectedElement = () => {
id
);
if (richTextInstance) {
- selectedInstanceIdStore.set(richTextInstance.id);
+ selectedInstanceAddressStore.set(
+ getInstanceAddress(instancesStore.get(), richTextInstance.id)
+ );
setEditingInstanceId(richTextInstance.id);
}
return;
}
- selectedInstanceIdStore.set(id);
+ selectedInstanceAddressStore.set(
+ getInstanceAddress(instancesStore.get(), id)
+ );
};
window.addEventListener("click", handleClick, eventOptions);
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.ts
index 78e3b2e5db..23e4d48f02 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts
@@ -11,7 +11,7 @@ import {
import {
propsStore,
stylesStore,
- selectedInstanceIdStore,
+ selectedInstanceAddressStore,
styleSourceSelectionsStore,
styleSourcesStore,
instancesIndexStore,
@@ -126,12 +126,19 @@ export const mimeType = "application/json";
export const onPaste = (clipboardData: string) => {
const data = parse(clipboardData);
- if (data === undefined) {
+ const selectedPage = selectedPageStore.get();
+ if (data === undefined || selectedPage === undefined) {
return;
}
+ // paste to the root if nothing is selected
+ const instanceAddress = selectedInstanceAddressStore.get() ?? [
+ selectedPage.rootInstanceId,
+ ];
+ const [targetInstanceId] = instanceAddress;
const dropTarget = findClosestDroppableTarget(
instancesIndexStore.get(),
- selectedInstanceIdStore.get()
+ // @todo accept instance address
+ targetInstanceId
);
store.createTransaction(
[
@@ -162,16 +169,20 @@ export const onPaste = (clipboardData: string) => {
// first item is guaranteed root of copied tree
const copiedRootInstanceId = Array.from(copiedInstanceIds.values())[0];
- selectedInstanceIdStore.set(copiedRootInstanceId);
+ selectedInstanceAddressStore.set([
+ copiedRootInstanceId,
+ ...instanceAddress,
+ ]);
}
);
};
export const onCopy = () => {
- const selectedInstanceId = selectedInstanceIdStore.get();
- if (selectedInstanceId === undefined) {
+ const selectedInstanceAddress = selectedInstanceAddressStore.get();
+ if (selectedInstanceAddress === undefined) {
return;
}
+ const [selectedInstanceId] = selectedInstanceAddress;
const data = getTreeData(selectedInstanceId);
if (data === undefined) {
return;
@@ -180,20 +191,21 @@ export const onCopy = () => {
};
export const onCut = () => {
- const selectedInstanceId = selectedInstanceIdStore.get();
+ const selectedInstanceAddress = selectedInstanceAddressStore.get();
+ if (selectedInstanceAddress === undefined) {
+ return;
+ }
+ const [selectedInstanceId] = selectedInstanceAddress;
const rootInstanceId = selectedPageStore.get()?.rootInstanceId;
// @todo tell user they can't delete root
- if (
- selectedInstanceId === undefined ||
- selectedInstanceId === rootInstanceId
- ) {
+ if (selectedInstanceId === rootInstanceId) {
return;
}
const data = getTreeData(selectedInstanceId);
if (data === undefined) {
return;
}
- deleteInstance(selectedInstanceId);
+ deleteInstance(selectedInstanceAddress);
if (data === undefined) {
return;
}
diff --git a/apps/builder/app/shared/copy-paste/plugin-markdown.ts b/apps/builder/app/shared/copy-paste/plugin-markdown.ts
index bd4c079604..c99643fb2e 100644
--- a/apps/builder/app/shared/copy-paste/plugin-markdown.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-markdown.ts
@@ -16,7 +16,8 @@ import {
instancesIndexStore,
instancesStore,
propsStore,
- selectedInstanceIdStore,
+ selectedInstanceAddressStore,
+ selectedPageStore,
} from "../nano-states";
const micromarkOptions = { extensions: [gfm()] };
@@ -207,13 +208,19 @@ export const parse = (clipboardData: string, options?: Options) => {
export const onPaste = (clipboardData: string) => {
const data = parse(clipboardData);
- if (data === undefined) {
+ const selectedPage = selectedPageStore.get();
+ if (data === undefined || selectedPage === undefined) {
return;
}
-
+ // paste to the root if nothing is selected
+ const instanceAddress = selectedInstanceAddressStore.get() ?? [
+ selectedPage.rootInstanceId,
+ ];
+ const [targetInstanceId] = instanceAddress;
const dropTarget = findClosestDroppableTarget(
instancesIndexStore.get(),
- selectedInstanceIdStore.get()
+ // @todo accept instance address
+ targetInstanceId
);
store.createTransaction([instancesStore, propsStore], (instances, props) => {
insertInstancesMutable(instances, data.instances, data.rootIds, dropTarget);
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index 581d837266..bd21012c64 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -3,19 +3,21 @@ import { findTreeInstanceIds, Instance } from "@webstudio-is/project-build";
import {
propsStore,
stylesStore,
- selectedInstanceIdStore,
+ selectedInstanceAddressStore,
styleSourceSelectionsStore,
styleSourcesStore,
instancesStore,
selectedPageStore,
} from "./nano-states";
import {
+ type DroppableTarget,
+ type InstanceAddress,
createComponentInstance,
- DroppableTarget,
- findParentInstance,
findSubtreeLocalStyleSources,
+ getInstanceAddress,
insertInstancesMutable,
reparentInstanceMutable,
+ getAncestorInstanceAddress,
} from "./tree-utils";
import { removeByMutable } from "./array-utils";
@@ -27,7 +29,9 @@ export const insertNewComponentInstance = (
store.createTransaction([instancesStore], (instances) => {
insertInstancesMutable(instances, [instance], [instance.id], dropTarget);
});
- selectedInstanceIdStore.set(instance.id);
+ selectedInstanceAddressStore.set(
+ getInstanceAddress(instancesStore.get(), instance.id)
+ );
};
export const reparentInstance = (
@@ -35,12 +39,18 @@ export const reparentInstance = (
dropTarget: DroppableTarget
) => {
store.createTransaction([instancesStore], (instances) => {
- reparentInstanceMutable(instances, targetInstanceId, dropTarget);
+ reparentInstanceMutable(
+ instances,
+ getInstanceAddress(instances, targetInstanceId),
+ dropTarget
+ );
});
- selectedInstanceIdStore.set(targetInstanceId);
+ selectedInstanceAddressStore.set(
+ getInstanceAddress(instancesStore.get(), targetInstanceId)
+ );
};
-export const deleteInstance = (targetInstanceId: Instance["id"]) => {
+export const deleteInstance = (instanceAddress: InstanceAddress) => {
store.createTransaction(
[
instancesStore,
@@ -50,7 +60,11 @@ export const deleteInstance = (targetInstanceId: Instance["id"]) => {
stylesStore,
],
(instances, props, styleSourceSelections, styleSources, styles) => {
- const parentInstance = findParentInstance(instances, targetInstanceId);
+ const [targetInstanceId, parentInstanceId] = instanceAddress;
+ const parentInstance =
+ parentInstanceId === undefined
+ ? undefined
+ : instances.get(parentInstanceId);
const subtreeIds = findTreeInstanceIds(instances, targetInstanceId);
const subtreeLocalStyleSourceIds = findSubtreeLocalStyleSources(
subtreeIds,
@@ -88,21 +102,23 @@ export const deleteInstance = (targetInstanceId: Instance["id"]) => {
}
if (parentInstance) {
- selectedInstanceIdStore.set(parentInstance.id);
+ selectedInstanceAddressStore.set(
+ getAncestorInstanceAddress(instanceAddress, parentInstance.id)
+ );
}
}
);
};
export const deleteSelectedInstance = () => {
- const selectedInstanceId = selectedInstanceIdStore.get();
+ const selectedInstanceAddress = selectedInstanceAddressStore.get();
const rootInstanceId = selectedPageStore.get()?.rootInstanceId;
// @todo tell user they can't delete root
if (
- selectedInstanceId === undefined ||
- selectedInstanceId === rootInstanceId
+ selectedInstanceAddress === undefined ||
+ selectedInstanceAddress[0] === rootInstanceId
) {
return;
}
- deleteInstance(selectedInstanceId);
+ deleteInstance(selectedInstanceAddress);
};
diff --git a/apps/builder/app/shared/nano-states/nano-states.ts b/apps/builder/app/shared/nano-states/nano-states.ts
index 0d3193b767..c846d7ac5e 100644
--- a/apps/builder/app/shared/nano-states/nano-states.ts
+++ b/apps/builder/app/shared/nano-states/nano-states.ts
@@ -33,7 +33,7 @@ import type {
} from "~/builder/shared/assets";
import { useSyncInitializeOnce } from "../hook-utils";
import { shallowComputed } from "../store-utils";
-import { createInstancesIndex } from "../tree-utils";
+import { createInstancesIndex, type InstanceAddress } from "../tree-utils";
const useValue = <T>(atom: WritableAtom<T>) => {
const value = useStore(atom);
@@ -304,15 +304,17 @@ export const useSetAssets = (assets: Asset[]) => {
});
};
-export const selectedInstanceIdStore = atom<undefined | Instance["id"]>(
+export const selectedInstanceAddressStore = atom<undefined | InstanceAddress>(
undefined
);
+
export const selectedInstanceStore = computed(
- [instancesIndexStore, selectedInstanceIdStore],
- (instancesIndex, selectedInstanceId) => {
- if (selectedInstanceId === undefined) {
+ [instancesIndexStore, selectedInstanceAddressStore],
+ (instancesIndex, selectedInstanceAddress) => {
+ if (selectedInstanceAddress === undefined) {
return;
}
+ const [selectedInstanceId] = selectedInstanceAddress;
return instancesIndex.instancesById.get(selectedInstanceId);
}
);
@@ -320,12 +322,13 @@ export const selectedInstanceStore = computed(
export const selectedInstanceBrowserStyleStore = atom<undefined | Style>();
export const selectedInstanceStyleSourcesStore = computed(
- [styleSourceSelectionsStore, styleSourcesStore, selectedInstanceIdStore],
- (styleSourceSelections, styleSources, selectedInstanceId) => {
+ [styleSourceSelectionsStore, styleSourcesStore, selectedInstanceAddressStore],
+ (styleSourceSelections, styleSources, selectedInstanceAddress) => {
const selectedInstanceStyleSources: StyleSource[] = [];
- if (selectedInstanceId === undefined) {
+ if (selectedInstanceAddress === undefined) {
return selectedInstanceStyleSources;
}
+ const [selectedInstanceId] = selectedInstanceAddress;
const styleSourceIds =
styleSourceSelections.get(selectedInstanceId)?.values ?? [];
let hasLocal = false;
diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts
index 1cf8aeff13..3534979c16 100644
--- a/apps/builder/app/shared/sync/sync-stores.ts
+++ b/apps/builder/app/shared/sync/sync-stores.ts
@@ -13,7 +13,7 @@ import {
styleSourceSelectionsStore,
selectedPageIdStore,
assetContainersStore,
- selectedInstanceIdStore,
+ selectedInstanceAddressStore,
selectedInstanceBrowserStyleStore,
hoveredInstanceIdStore,
hoveredInstanceOutlineStore,
@@ -60,7 +60,7 @@ export const registerContainers = () => {
// synchronize whole states
clientStores.set("selectedPageId", selectedPageIdStore);
clientStores.set("assetContainers", assetContainersStore);
- clientStores.set("selectedInstanceId", selectedInstanceIdStore);
+ clientStores.set("selectedInstanceAddress", selectedInstanceAddressStore);
clientStores.set(
"selectedInstanceBrowserStyle",
selectedInstanceBrowserStyleStore
diff --git a/apps/builder/app/shared/tree-utils.test.ts b/apps/builder/app/shared/tree-utils.test.ts
index f941619d12..599e6a6805 100644
--- a/apps/builder/app/shared/tree-utils.test.ts
+++ b/apps/builder/app/shared/tree-utils.test.ts
@@ -14,8 +14,9 @@ import {
createInstancesIndex,
findClosestDroppableTarget,
findClosestRichTextInstance,
- findParentInstance,
findSubtreeLocalStyleSources,
+ getAncestorInstanceAddress,
+ getInstanceAddress,
getInstanceAncestorsAndSelf,
insertInstancesCopyMutable,
insertInstancesMutable,
@@ -23,6 +24,7 @@ import {
insertStylesCopyMutable,
insertStyleSourcesCopyMutable,
insertStyleSourceSelectionsCopyMutable,
+ InstanceAddress,
reparentInstanceMutable,
} from "./tree-utils";
@@ -114,6 +116,37 @@ const createStyleDecl = (
};
};
+test("get ancestor instance address", () => {
+ const instanceAddress: InstanceAddress = ["4", "3", "2", "1"];
+ expect(getAncestorInstanceAddress(instanceAddress, "2")).toEqual(["2", "1"]);
+ expect(getAncestorInstanceAddress(instanceAddress, "-1")).toEqual(undefined);
+ expect(getAncestorInstanceAddress(instanceAddress, "1")).toEqual(["1"]);
+});
+
+test("get instance address", () => {
+ const instances: Instances = new Map([
+ createInstancePair("root", "Box", [
+ { type: "id", value: "box1" },
+ { type: "id", value: "box2" },
+ { type: "id", value: "box4" },
+ ]),
+ createInstancePair("box1", "Box", []),
+ createInstancePair("box2", "Box", [{ type: "id", value: "box3" }]),
+ createInstancePair("box4", "Box", []),
+ createInstancePair("box3", "Box", [
+ { type: "id", value: "child1" },
+ { type: "id", value: "child2" },
+ ]),
+ createInstancePair("child1", "Box", []),
+ createInstancePair("child2", "Box", []),
+ ]);
+ expect(getInstanceAddress(instances, "box3")).toEqual([
+ "box3",
+ "box2",
+ "root",
+ ]);
+});
+
test("find closest droppable target", () => {
const rootInstance = createInstance("root", "Body", [
createInstance("box1", "Box", [
@@ -252,7 +285,7 @@ test("reparent instance into target", () => {
createInstancePair("box13", "Box", []),
]);
- reparentInstanceMutable(instances, "target", {
+ reparentInstanceMutable(instances, ["target", "root"], {
parentId: "box1",
position: 1,
});
@@ -276,7 +309,7 @@ test("reparent instance into target", () => {
])
);
- reparentInstanceMutable(instances, "target", {
+ reparentInstanceMutable(instances, ["target", "box1", "root"], {
parentId: "box1",
position: 3,
});
@@ -300,7 +333,7 @@ test("reparent instance into target", () => {
])
);
- reparentInstanceMutable(instances, "target", {
+ reparentInstanceMutable(instances, ["target", "box1", "root"], {
parentId: "root",
position: "end",
});
@@ -379,32 +412,6 @@ test("find closest rich text to instance", () => {
);
});
-test("find parent instance", () => {
- const instances: Instances = new Map([
- createInstancePair("1", "Body", [{ type: "id", value: "3" }]),
- // this is outside of subtree
- createInstancePair("2", "Box", []),
- // these should be matched
- createInstancePair("3", "Box", [
- { type: "id", value: "4" },
- { type: "id", value: "5" },
- ]),
- createInstancePair("4", "Box", []),
- createInstancePair("5", "Box", []),
- // this one is from other tree
- createInstancePair("6", "Box", []),
- ]);
- expect(findParentInstance(instances, "4")).toEqual({
- type: "instance",
- id: "3",
- component: "Box",
- children: [
- { type: "id", value: "4" },
- { type: "id", value: "5" },
- ],
- });
-});
-
test("insert tree of instances copy and provide map from ids map", () => {
const instances = new Map([
createInstancePair("1", "Body", [
diff --git a/apps/builder/app/shared/tree-utils.ts b/apps/builder/app/shared/tree-utils.ts
index d72074af37..6b7e86d0d8 100644
--- a/apps/builder/app/shared/tree-utils.ts
+++ b/apps/builder/app/shared/tree-utils.ts
@@ -15,6 +15,49 @@ import {
} from "@webstudio-is/project-build";
import { getComponentMeta } from "@webstudio-is/react-sdk";
+// slots can have multiple parents so instance should be addressed
+// with full rendered path to avoid double selections with slots
+// and support deletion of slot child from specific parent
+// address starts with target instance and ends with root
+export type InstanceAddress = Instance["id"][];
+
+// provide an address starting with ancestor id
+// useful to select parent instance or one of breadcrumbs instances
+export const getAncestorInstanceAddress = (
+ instanceAddress: InstanceAddress,
+ ancestorId: Instance["id"]
+): undefined | InstanceAddress => {
+ const ancestorIndex = instanceAddress.indexOf(ancestorId);
+ if (ancestorIndex === -1) {
+ return undefined;
+ }
+ return instanceAddress.slice(ancestorIndex);
+};
+
+// this utility is temporary solution to compute instance addresses
+// before all logic is migrated to get it from rendered context
+// @todo should be deleted before adding slots
+export const getInstanceAddress = (
+ instances: Instances,
+ instanceId: Instance["id"]
+) => {
+ const parentInstancesById = new Map<Instance["id"], Instance["id"]>();
+ for (const instance of instances.values()) {
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ parentInstancesById.set(child.value, instance.id);
+ }
+ }
+ }
+ const address: InstanceAddress = [];
+ let currentInstanceId: undefined | Instance["id"] = instanceId;
+ while (currentInstanceId) {
+ address.push(currentInstanceId);
+ currentInstanceId = parentInstancesById.get(currentInstanceId);
+ }
+ return address;
+};
+
export const createComponentInstance = (
component: Instance["component"]
): InstancesItem => {
@@ -181,10 +224,14 @@ export const reparentInstanceMutableDeprecated = (
export const reparentInstanceMutable = (
instances: Instances,
- instanceId: Instance["id"],
+ instanceAddress: InstanceAddress,
dropTarget: DroppableTarget
) => {
- const prevParent = findParentInstance(instances, instanceId);
+ const [instanceId, parentInstanceId] = instanceAddress;
+ const prevParent =
+ parentInstanceId === undefined
+ ? undefined
+ : instances.get(parentInstanceId);
const nextParent = instances.get(dropTarget.parentId);
const instance = instances.get(instanceId);
if (
@@ -246,19 +293,6 @@ export const findClosestRichTextInstance = (
);
};
-export const findParentInstance = (
- instances: Instances,
- instanceId: Instance["id"]
-) => {
- for (const instance of instances.values()) {
- for (const child of instance.children) {
- if (child.type === "id" && child.value === instanceId) {
- return instance;
- }
- }
- }
-};
-
export const cloneStyles = (
styles: Styles,
clonedStyleSourceIds: Map<Instance["id"], Instance["id"]>