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
refactor: add instance path (#4614)
Bogdan Chadkin0fa310b69f8b
diff --git a/apps/builder/app/builder/features/footer/breadcrumbs.tsx b/apps/builder/app/builder/features/footer/breadcrumbs.tsxindex 180206a7c8..ca79491751 100644--- a/apps/builder/app/builder/features/footer/breadcrumbs.tsx+++ b/apps/builder/app/builder/features/footer/breadcrumbs.tsx@@ -2,35 +2,24 @@ import { Fragment } from "react";import { useStore } from "@nanostores/react";import { ChevronRightIcon } from "@webstudio-is/icons";import { theme, Button, Flex, Text } from "@webstudio-is/design-system";-import {- $instances,- $registeredComponentMetas,- $selectedInstanceSelector,-} from "~/shared/nano-states";-import { getAncestorInstanceSelector } from "~/shared/tree-utils";+import { $registeredComponentMetas } from "~/shared/nano-states";import { $textEditingInstanceSelector } from "~/shared/nano-states";import { getInstanceLabel } from "~/shared/instance-utils";-import { selectInstance } from "~/shared/awareness";+import { $selectedInstancePath, selectInstance } from "~/shared/awareness";export const Breadcrumbs = () => {- const instances = useStore($instances);- const selectedInstanceSelector = useStore($selectedInstanceSelector);+ const instancePath = useStore($selectedInstancePath);const metas = useStore($registeredComponentMetas);-return (<Flex align="center" css={{ height: "100%", px: theme.spacing[3] }}>- {selectedInstanceSelector === undefined ? (+ {instancePath === undefined ? (<Text>No instance selected</Text>) : (- selectedInstanceSelector+ instancePath// start breadcrumbs from the root.slice().reverse()- .map((instanceId, index) => {- const instance = instances.get(instanceId);- if (instance === undefined) {- return;- }+ .map(({ instance, instanceSelector }, index) => {const meta = metas.get(instance.component);if (meta === undefined) {return;@@ -42,20 +31,14 @@ export const Breadcrumbs = () => {css={{ color: "inherit" }}key={instance.id}onClick={() => {- selectInstance(- getAncestorInstanceSelector(- selectedInstanceSelector,- instance.id- )- );+ selectInstance(instanceSelector);$textEditingInstanceSelector.set(undefined);}}>{getInstanceLabel(instance, meta)}</Button>- {index < selectedInstanceSelector.length - 1 ? (- <ChevronRightIcon />- ) : null}+ {/* hide the last one */}+ {index < instancePath.length - 1 && <ChevronRightIcon />}</Fragment>);})diff --git a/apps/builder/app/builder/features/style-panel/shared/model.tsx b/apps/builder/app/builder/features/style-panel/shared/model.tsxindex 1a4d944755..3856652478 100644--- a/apps/builder/app/builder/features/style-panel/shared/model.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/model.tsx@@ -25,7 +25,6 @@ import {$registeredComponentMetas,$selectedBreakpoint,$selectedInstanceIntanceToTag,- $selectedInstanceSelector,$selectedInstanceStates,$selectedOrLastStyleSourceSelector,$styles,@@ -38,6 +37,7 @@ import {type StyleObjectModel,} from "~/shared/style-object-model";import type { InstanceSelector } from "~/shared/tree-utils";+import { $selectedInstancePath } from "~/shared/awareness";const $presetStyles = computed($registeredComponentMetas, (metas) => {const presetStyles = new Map<string, StyleValue>();@@ -57,26 +57,20 @@ const $presetStyles = computed($registeredComponentMetas, (metas) => {return presetStyles;});-const $instanceComponents = computed(- [$selectedInstanceSelector, $instances],- (instanceSelector, instances) => {- const instanceComponents = new Map<Instance["id"], Instance["component"]>([- [ROOT_INSTANCE_ID, rootComponent],- ]);- if (instanceSelector === undefined) {- return instanceComponents;- }- // store only component for selected instance and ancestors- // to avoid iterating over all instances in the project- for (const instanceId of instanceSelector) {- const instance = instances.get(instanceId);- if (instance) {- instanceComponents.set(instance.id, instance.component);- }- }+const $instanceComponents = computed($selectedInstancePath, (instancePath) => {+ const instanceComponents = new Map<Instance["id"], Instance["component"]>([+ [ROOT_INSTANCE_ID, rootComponent],+ ]);+ if (instancePath === undefined) {return instanceComponents;}-);+ // store only component for selected instance and ancestors+ // to avoid iterating over all instances in the project+ for (const { instance } of instancePath) {+ instanceComponents.set(instance.id, instance.component);+ }+ return instanceComponents;+});export const $matchingBreakpoints = computed([$breakpoints, $selectedBreakpoint],@@ -161,15 +155,16 @@ export const getDefinedStyles = ({};const $instanceAndRootSelector = computed(- $selectedInstanceSelector,- (instanceSelector) => {- if (instanceSelector === undefined) {+ $selectedInstancePath,+ (instancePath) => {+ if (instancePath === undefined) {return;}- if (instanceSelector[0] === ROOT_INSTANCE_ID) {- return instanceSelector;+ const [selectedItem] = instancePath;+ if (selectedItem.instance.id === ROOT_INSTANCE_ID) {+ return selectedItem.instanceSelector;}- return [...instanceSelector, ROOT_INSTANCE_ID];+ return [...selectedItem.instanceSelector, ROOT_INSTANCE_ID];});diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex ccf605bb70..e29ac866b8 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -6,7 +6,6 @@ import { createCommandsEmitter, type Command } from "~/shared/commands-emitter";import {$editingItemSelector,$instances,- $selectedInstanceSelector,$textEditingInstanceSelector,$isDesignMode,toggleBuilderMode,@@ -34,11 +33,7 @@ import {setActiveSidebarPanel,toggleActiveSidebarPanel,} from "./nano-states";-import {- $parentInstance,- $selectedInstance,- selectInstance,-} from "~/shared/awareness";+import { $selectedInstancePath, selectInstance } from "~/shared/awareness";import { openCommandPanel } from "../features/command-panel";import { builderApi } from "~/shared/builder-api";import { findBlockSelector } from "../features/workspace/canvas-tools/outline/block-instance-outline";@@ -67,17 +62,16 @@ export const deleteSelectedInstance = () => {return;}const textEditingInstanceSelector = $textEditingInstanceSelector.get();- const selectedInstanceSelector = $selectedInstanceSelector.get();+ const instancePath = $selectedInstancePath.get();// cannot delete instance while editingif (textEditingInstanceSelector) {return;}- if (selectedInstanceSelector === undefined) {- return;- }- if (selectedInstanceSelector.length === 1) {+ if (instancePath === undefined || instancePath.length === 1) {return;}+ const [selectedItem, parentItem] = instancePath;+ const selectedInstanceSelector = selectedItem.instanceSelector;const instances = $instances.get();if (isInstanceDetachable(instances, selectedInstanceSelector) === false) {toast.error(@@ -115,25 +109,20 @@ export const deleteSelectedInstance = () => {}}+ // find next selected instancelet newSelectedInstanceSelector: undefined | InstanceSelector;- const [selectedInstanceId, parentInstanceId] = selectedInstanceSelector;- const parentInstance = instances.get(parentInstanceId);- if (parentInstance) {- const siblingIds = parentInstance.children- .filter((child) => child.type === "id")- .map((child) => child.value);- const position = siblingIds.indexOf(selectedInstanceId);- const siblingId = siblingIds[position + 1] ?? siblingIds[position - 1];- if (siblingId) {- // select next or previous sibling if possible- newSelectedInstanceSelector = [- siblingId,- ...selectedInstanceSelector.slice(1),- ];- } else {- // fallback to parent- newSelectedInstanceSelector = selectedInstanceSelector.slice(1);- }+ const parentInstanceSelector = parentItem.instanceSelector;+ const siblingIds = parentItem.instance.children+ .filter((child) => child.type === "id")+ .map((child) => child.value);+ const position = siblingIds.indexOf(selectedItem.instance.id);+ const siblingId = siblingIds[position + 1] ?? siblingIds[position - 1];+ if (siblingId) {+ // select next or previous sibling if possible+ newSelectedInstanceSelector = [siblingId, ...parentInstanceSelector];+ } else {+ // fallback to parent+ newSelectedInstanceSelector = parentInstanceSelector;}updateWebstudioData((data) => {if (deleteInstanceMutable(data, selectedInstanceSelector)) {@@ -143,19 +132,15 @@ export const deleteSelectedInstance = () => {};export const wrapIn = (component: string) => {- const selectedInstance = $selectedInstance.get();- const parentInstanceId = $parentInstance.get()?.id;+ const instancePath = $selectedInstancePath.get();// global root or body are selected- if (selectedInstance === undefined || parentInstanceId === undefined) {- return;- }- const selectedInstanceSelector = $selectedInstanceSelector.get();- if (selectedInstanceSelector === undefined) {+ if (instancePath === undefined || instancePath.length === 1) {return;}+ const [selectedItem, parentItem] = instancePath;+ const selectedInstance = selectedItem.instance;const newInstanceId = nanoid();- const parentInstanceSelector = selectedInstanceSelector.slice(1);- const newInstanceSelector = [newInstanceId, ...parentInstanceSelector];+ const newInstanceSelector = [newInstanceId, ...parentItem.instanceSelector];const metas = $registeredComponentMetas.get();try {updateWebstudioData((data) => {@@ -170,7 +155,7 @@ export const wrapIn = (component: string) => {component,children: [{ type: "id", value: selectedInstance.id }],};- const parentInstance = data.instances.get(parentInstanceId);+ const parentInstance = data.instances.get(parentItem.instance.id);data.instances.set(newInstanceId, newInstance);if (parentInstance) {for (const child of parentInstance.children) {@@ -196,48 +181,44 @@ export const wrapIn = (component: string) => {};export const unwrap = () => {- const selectedInstanceId = $selectedInstance.get()?.id;- const parentInstanceId = $parentInstance.get()?.id;+ const instancePath = $selectedInstancePath.get();// global root or body are selected- if (selectedInstanceId === undefined || parentInstanceId === undefined) {- return;- }- const selectedInstanceSelector = $selectedInstanceSelector.get();- if (selectedInstanceSelector === undefined) {+ if (instancePath === undefined || instancePath.length === 1) {return;}- const parentInstanceSelector = selectedInstanceSelector.slice(1);+ const [selectedItem, parentItem] = instancePath;try {updateWebstudioData((data) => {const nonTextualIndex = findClosestNonTextualContainer({metas: $registeredComponentMetas.get(),instances: data.instances,- instanceSelector: selectedInstanceSelector,+ instanceSelector: selectedItem.instanceSelector,});if (nonTextualIndex !== 0) {toast.error(`Cannot unwrap textual instance`);throw Error("Abort transaction");}- const parentInstance = data.instances.get(parentInstanceId);- const selectedInstance = data.instances.get(selectedInstanceId);- data.instances.delete(selectedInstanceId);+ const parentInstance = data.instances.get(parentItem.instance.id);+ const selectedInstance = data.instances.get(selectedItem.instance.id);+ data.instances.delete(selectedItem.instance.id);if (parentInstance && selectedInstance) {const index = parentInstance.children.findIndex(- (child) => child.type === "id" && child.value === selectedInstanceId+ (child) =>+ child.type === "id" && child.value === selectedItem.instance.id);parentInstance.children.splice(index, 1, ...selectedInstance.children);}const matches = isTreeMatching({metas: $registeredComponentMetas.get(),instances: data.instances,- instanceSelector: parentInstanceSelector,+ instanceSelector: parentItem.instanceSelector,});if (matches === false) {toast.error(`Cannot unwrap instance`);throw Error("Abort transaction");}});- selectInstance(parentInstanceSelector);+ selectInstance(parentItem.instanceSelector);} catch {// do nothing}@@ -401,41 +382,41 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({builderApi.toast.info("Duplicating is only allowed in design mode.");return;}-- const instanceSelector = $selectedInstanceSelector.get();- if (instanceSelector === undefined) {- return;- }- // @todo tell user they can't copy or cut root- if (instanceSelector.length === 1) {+ const instancePath = $selectedInstancePath.get();+ // global root or body are selected+ if (instancePath === undefined || instancePath.length === 1) {return;}- // body is not allowed to copy- // so clipboard always have at least two level instance selector- const [targetInstanceId, parentInstanceId] = instanceSelector;- const parentInstanceSelector = instanceSelector.slice(1);+ const [selectedItem, parentItem] = instancePath;+updateWebstudioData((data) => {- const fragment = extractWebstudioFragment(data, targetInstanceId);+ const fragment = extractWebstudioFragment(+ data,+ selectedItem.instance.id+ );const { newInstanceIds } = insertWebstudioFragmentCopy({data,fragment,availableDataSources: findAvailableDataSources(data.dataSources,data.instances,- parentInstanceSelector+ parentItem.instanceSelector),});- const newRootInstanceId = newInstanceIds.get(targetInstanceId);+ const newRootInstanceId = newInstanceIds.get(+ selectedItem.instance.id+ );if (newRootInstanceId === undefined) {return;}- const parentInstance = data.instances.get(parentInstanceId);+ const parentInstance = data.instances.get(parentItem.instance.id);if (parentInstance === undefined) {return;}// put after current instanceconst indexWithinChildren = parentInstance.children.findIndex(- (child) => child.type === "id" && child.value === targetInstanceId+ (child) =>+ child.type === "id" && child.value === selectedItem.instance.id);const position = indexWithinChildren + 1;parentInstance.children.splice(position, 0, {@@ -443,7 +424,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({value: newRootInstanceId,});// select new instance- selectInstance([newRootInstanceId, ...parentInstanceSelector]);+ selectInstance([newRootInstanceId, ...parentItem.instanceSelector]);});},},@@ -451,11 +432,12 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({name: "editInstanceLabel",defaultHotkeys: ["meta+e", "ctrl+e"],handler: () => {- const selectedInstanceSelector = $selectedInstanceSelector.get();- if (selectedInstanceSelector === undefined) {+ const instancePath = $selectedInstancePath.get();+ if (instancePath === undefined) {return;}- $editingItemSelector.set(selectedInstanceSelector);+ const [selectedItem] = instancePath;+ $editingItemSelector.set(selectedItem.instanceSelector);},},{diff --git a/apps/builder/app/shared/awareness.ts b/apps/builder/app/shared/awareness.tsindex c5f0c3eda8..bf45ce2b54 100644--- a/apps/builder/app/shared/awareness.ts+++ b/apps/builder/app/shared/awareness.ts@@ -65,19 +65,6 @@ export const $selectedInstance = computed(});-export const $parentInstance = computed(- [$instances, $virtualInstances, $awareness],- (instances, virtualInstances, awareness) => {- if (awareness?.instanceSelector === undefined) {- return;- }- const [_, parentInstanceId] = awareness.instanceSelector;- return (- instances.get(parentInstanceId) ?? virtualInstances.get(parentInstanceId)- );- }-);-export const getInstanceKey = <InstanceSelector extends undefined | Instance["id"][],>(@@ -89,6 +76,52 @@ export const $selectedInstanceKey = computed($awareness, (awareness) =>getInstanceKey(awareness?.instanceSelector));+type InstancePath = Array<{+ instance: Instance;+ instanceSelector: string[];+}>;++const getInstancePath = (+ instances: Instances,+ virtualInstances: Instances,+ temporaryInstances: Instances,+ instanceSelector: string[]+): InstancePath => {+ const instancePath: InstancePath = [];+ for (let index = 0; index < instanceSelector.length; index += 1) {+ const instanceId = instanceSelector[index];+ const instance =+ instances.get(instanceId) ??+ virtualInstances.get(instanceId) ??+ temporaryInstances.get(instanceId);+ // collection item can be undefined+ if (instance === undefined) {+ continue;+ }+ instancePath.push({+ instance,+ instanceSelector: instanceSelector.slice(index),+ });+ }+ return instancePath;+};++export const $selectedInstancePath = computed(+ [$instances, $virtualInstances, $temporaryInstances, $awareness],+ (instances, virtualInstances, temporaryInstances, awareness) => {+ const instanceSelector = awareness?.instanceSelector;+ if (instanceSelector === undefined) {+ return;+ }+ return getInstancePath(+ instances,+ virtualInstances,+ temporaryInstances,+ instanceSelector+ );+ }+);+export const selectPage = (pageId: Page["id"]) => {const pages = $pages.get();if (pages === undefined) {