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: make delete instance composable (#2781)

Bogdan Chadkina84320666d68
diff --git a/apps/builder/app/builder/features/ai/apply-operations.ts b/apps/builder/app/builder/features/ai/apply-operations.ts
index 106b37e79f..21577f05a3 100644
--- a/apps/builder/app/builder/features/ai/apply-operations.ts
+++ b/apps/builder/app/builder/features/ai/apply-operations.ts
@@ -3,8 +3,9 @@ import { generateDataFromEmbedTemplate } from "@webstudio-is/react-sdk";
import { copywriter, type operations } from "@webstudio-is/ai";
import { isBaseBreakpoint } from "~/shared/breakpoints";
import {
- deleteInstance as _deleteInstance,
+ deleteInstanceMutable,
insertTemplateData,
+ updateWebstudioData,
} from "~/shared/instance-utils";
import {
$breakpoints,
@@ -101,14 +102,16 @@ const deleteInstanceByOp = (
) => {
const instanceSelector = computeSelectorForInstanceId(operation.wsId);
if (instanceSelector) {
- _deleteInstance(instanceSelector);
+ updateWebstudioData((data) => {
+ deleteInstanceMutable(data, instanceSelector);
+ });
}
};
const applyStylesByOp = (operation: operations.editStylesWsOperation) => {
serverSyncStore.createTransaction(
- [$instances, $styleSourceSelections, $styleSources, $styles, $breakpoints],
- (instances, styleSourceSelections, styleSources, styles, breakpoints) => {
+ [$styleSourceSelections, $styleSources, $styles, $breakpoints],
+ (styleSourceSelections, styleSources, styles, breakpoints) => {
const newStyles = [...operation.styles.values()];
const breakpointValues = Array.from(breakpoints.values());
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
index 018ae5a9ba..95b5685844 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
@@ -48,9 +48,10 @@ import {
import { useIds } from "~/shared/form-utils";
import { Header, HeaderSuffixSpacer } from "../../header";
import {
- deleteInstance,
+ deleteInstanceMutable,
getInstancesSlice,
insertInstancesSliceCopy,
+ updateWebstudioData,
} from "~/shared/instance-utils";
import {
$assets,
@@ -923,13 +924,12 @@ const deletePage = (pageId: Page["id"]) => {
$selectedInstanceSelector.set(undefined);
}
const rootInstanceId = findPageByIdOrPath(pageId, pages)?.rootInstanceId;
- if (rootInstanceId !== undefined) {
- deleteInstance([rootInstanceId]);
+ if (rootInstanceId === undefined) {
+ return;
}
- serverSyncStore.createTransaction([$pages], (pages) => {
- if (pages === undefined) {
- return;
- }
+ updateWebstudioData((data) => {
+ deleteInstanceMutable(data, [rootInstanceId]);
+ const { pages } = data;
removeByMutable(pages.pages, (page) => page.id === pageId);
cleanupChildRefsMutable(pageId, pages.folders);
});
diff --git a/apps/builder/app/builder/shared/commands.test.ts b/apps/builder/app/builder/shared/commands.test.ts
index 170ae2085e..b96f867930 100644
--- a/apps/builder/app/builder/shared/commands.test.ts
+++ b/apps/builder/app/builder/shared/commands.test.ts
@@ -3,11 +3,13 @@ import type { Instance } from "@webstudio-is/sdk";
import * as baseMetas from "@webstudio-is/sdk-components-react/metas";
import {
$instances,
+ $pages,
$registeredComponentMetas,
$selectedInstanceSelector,
} from "~/shared/nano-states";
import { registerContainers } from "~/shared/sync";
import { emitCommand } from "./commands";
+import { createDefaultPages } from "@webstudio-is/project-build";
registerContainers();
@@ -21,6 +23,8 @@ const createInstancePair = (
const metas = new Map(Object.entries(baseMetas));
+$pages.set(createDefaultPages({ rootInstanceId: "" }));
+
describe("deleteInstance", () => {
// body
// parent
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.ts
index 2b4144590d..f791528273 100644
--- a/apps/builder/app/builder/shared/commands.ts
+++ b/apps/builder/app/builder/shared/commands.ts
@@ -13,11 +13,12 @@ import {
selectBreakpointByOrder,
} from "~/shared/breakpoints";
import {
- deleteInstance,
+ deleteInstanceMutable,
findAvailableDataSources,
getInstancesSlice,
insertInstancesSliceCopy,
isInstanceDetachable,
+ updateWebstudioData,
} from "~/shared/instance-utils";
import type { InstanceSelector } from "~/shared/tree-utils";
import { serverSyncStore } from "~/shared/sync";
@@ -70,10 +71,12 @@ const deleteSelectedInstance = () => {
newSelectedInstanceSelector = selectedInstanceSelector.slice(1);
}
}
- if (deleteInstance(selectedInstanceSelector)) {
- $selectedInstanceSelector.set(newSelectedInstanceSelector);
- $selectedStyleSourceSelector.set(undefined);
- }
+ updateWebstudioData((data) => {
+ if (deleteInstanceMutable(data, selectedInstanceSelector)) {
+ $selectedInstanceSelector.set(newSelectedInstanceSelector);
+ $selectedStyleSourceSelector.set(undefined);
+ }
+ });
};
export const { emitCommand, subscribeCommands } = createCommandsEmitter({
@@ -168,7 +171,8 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
if (instanceSelector === undefined) {
return;
}
- if (isInstanceDetachable(instanceSelector) === false) {
+ const instances = $instances.get();
+ if (isInstanceDetachable(instances, instanceSelector) === false) {
toast.error(
"This instance can not be moved outside of its parent component."
);
@@ -187,7 +191,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
slice,
availableDataSources: findAvailableDataSources(
$dataSources.get(),
- $instances.get(),
+ instances,
parentInstanceSelector
),
beforeTransactionEnd: (rootInstanceId, draft) => {
diff --git a/apps/builder/app/builder/shared/navigator-tree.tsx b/apps/builder/app/builder/shared/navigator-tree.tsx
index 948cf8397c..826ec79ada 100644
--- a/apps/builder/app/builder/shared/navigator-tree.tsx
+++ b/apps/builder/app/builder/shared/navigator-tree.tsx
@@ -143,7 +143,8 @@ export const NavigatorTree = () => {
onSelect={handleSelect}
onHover={$hoveredInstanceSelector.set}
onDragItemChange={(dragInstanceSelector) => {
- if (isInstanceDetachable(dragInstanceSelector) === false) {
+ const instances = $instances.get();
+ if (isInstanceDetachable(instances, dragInstanceSelector) === false) {
toast.error(
"This instance can not be moved outside of its parent component."
);
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.ts
index 9787d58115..5b85529216 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts
@@ -23,12 +23,13 @@ import {
} from "../tree-utils";
import {
computeInstancesConstraints,
- deleteInstance,
+ deleteInstanceMutable,
findAvailableDataSources,
findClosestDroppableTarget,
getInstancesSlice,
insertInstancesSliceCopy,
isInstanceDetachable,
+ updateWebstudioData,
} from "../instance-utils";
import { portalComponent } from "@webstudio-is/react-sdk";
@@ -41,7 +42,8 @@ const InstanceData = WebstudioFragment.extend({
type InstanceData = z.infer<typeof InstanceData>;
const getTreeData = (targetInstanceSelector: InstanceSelector) => {
- if (isInstanceDetachable(targetInstanceSelector) === false) {
+ const instances = $instances.get();
+ if (isInstanceDetachable(instances, targetInstanceSelector) === false) {
toast.error(
"This instance can not be moved outside of its parent component."
);
@@ -253,7 +255,9 @@ export const onCut = () => {
if (data === undefined) {
return;
}
- deleteInstance(selectedInstanceSelector);
+ updateWebstudioData((data) => {
+ deleteInstanceMutable(data, selectedInstanceSelector);
+ });
if (data === undefined) {
return;
}
diff --git a/apps/builder/app/shared/instance-utils.test.ts b/apps/builder/app/shared/instance-utils.test.ts
index 4b1bf57690..4b948275cd 100644
--- a/apps/builder/app/shared/instance-utils.test.ts
+++ b/apps/builder/app/shared/instance-utils.test.ts
@@ -9,11 +9,14 @@ import {
import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";
import type {
Asset,
+ DataSource,
Instance,
Instances,
Prop,
+ Resource,
StyleDecl,
StyleDeclKey,
+ WebstudioData,
} from "@webstudio-is/sdk";
import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";
import {
@@ -23,7 +26,7 @@ import {
findClosestEditableInstanceSelector,
insertTemplateData,
type InsertConstraints,
- deleteInstance,
+ deleteInstanceMutable,
getInstancesSlice,
insertInstancesSliceCopy,
reparentInstance,
@@ -36,7 +39,6 @@ import {
$pages,
$project,
$props,
- $resources,
$styleSourceSelections,
$styleSources,
$styles,
@@ -542,26 +544,39 @@ describe("reparent instance", () => {
});
});
+const getWebstudioData = (data: Partial<WebstudioData>): WebstudioData => ({
+ pages: createDefaultPages({ rootInstanceId: "" }),
+ assets: new Map(),
+ dataSources: new Map(),
+ resources: new Map(),
+ instances: new Map(),
+ props: new Map(),
+ breakpoints: new Map(),
+ styleSourceSelections: new Map(),
+ styleSources: new Map(),
+ styles: new Map(),
+ ...data,
+});
+
describe("delete instance", () => {
test("delete instance with its children", () => {
// body
// box1
// box11
// box2
- $instances.set(
- new Map([
- createInstancePair("body", "Body", [
- { type: "id", value: "box1" },
- { type: "id", value: "box2" },
- ]),
- createInstancePair("box1", "Box", [{ type: "id", value: "box11" }]),
- createInstancePair("box11", "Box", []),
- createInstancePair("box2", "Box", []),
- ])
- );
+ const instances = new Map([
+ createInstancePair("body", "Body", [
+ { type: "id", value: "box1" },
+ { type: "id", value: "box2" },
+ ]),
+ createInstancePair("box1", "Box", [{ type: "id", value: "box11" }]),
+ createInstancePair("box11", "Box", []),
+ createInstancePair("box2", "Box", []),
+ ]);
$registeredComponentMetas.set(createFakeComponentMetas({}));
- deleteInstance(["box1", "body"]);
- expect($instances.get()).toEqual(
+ const data = getWebstudioData({ instances });
+ deleteInstanceMutable(data, ["box1", "body"]);
+ expect(data.instances).toEqual(
new Map([
createInstancePair("body", "Body", [{ type: "id", value: "box2" }]),
createInstancePair("box2", "Box", []),
@@ -572,15 +587,14 @@ describe("delete instance", () => {
test("prevent deleting root instance", () => {
// body
// box1
- $instances.set(
- new Map([
- createInstancePair("body", "Body", [{ type: "id", value: "box1" }]),
- createInstancePair("box1", "Box", []),
- ])
- );
+ const instances = new Map([
+ createInstancePair("body", "Body", [{ type: "id", value: "box1" }]),
+ createInstancePair("box1", "Box", []),
+ ]);
$registeredComponentMetas.set(createFakeComponentMetas({}));
- deleteInstance(["body"]);
- expect($instances.get()).toEqual(
+ const data = getWebstudioData({ instances });
+ deleteInstanceMutable(data, ["body"]);
+ expect(data.instances).toEqual(
new Map([
createInstancePair("body", "Body", [{ type: "id", value: "box1" }]),
createInstancePair("box1", "Box", []),
@@ -592,18 +606,17 @@ describe("delete instance", () => {
// body
// list
// box
- $instances.set(
- new Map([
- createInstancePair("body", "Body", [{ type: "id", value: "list" }]),
- createInstancePair("list", collectionComponent, [
- { type: "id", value: "box" },
- ]),
- createInstancePair("box", "Box", []),
- ])
- );
+ const instances = new Map([
+ createInstancePair("body", "Body", [{ type: "id", value: "list" }]),
+ createInstancePair("list", collectionComponent, [
+ { type: "id", value: "box" },
+ ]),
+ createInstancePair("box", "Box", []),
+ ]);
$registeredComponentMetas.set(createFakeComponentMetas({}));
- deleteInstance(["box", "list[0]", "list", "body"]);
- expect($instances.get()).toEqual(
+ const data = getWebstudioData({ instances });
+ deleteInstanceMutable(data, ["box", "list[0]", "list", "body"]);
+ expect(data.instances).toEqual(
new Map([
createInstancePair("body", "Body", [{ type: "id", value: "list" }]),
createInstancePair("list", collectionComponent, []),
@@ -612,43 +625,36 @@ describe("delete instance", () => {
});
test("delete resource along with variable", () => {
- $instances.set(
- toMap([
- createInstance("body", "Body", [{ type: "id", value: "box" }]),
- createInstance("box", "Box", []),
- ])
- );
- $resources.set(
- toMap([
- {
- id: "resourceId",
- name: "My Resource",
- url: `""`,
- method: "get",
- headers: [],
- },
- ])
- );
- $dataSources.set(
- toMap([
- {
- id: "resourceVariableId",
- scopeInstanceId: "box",
- name: "My Resource Variable",
- type: "resource",
- resourceId: "resourceId",
- },
- ])
- );
+ const instances = toMap([
+ createInstance("body", "Body", [{ type: "id", value: "box" }]),
+ createInstance("box", "Box", []),
+ ]);
+ const resources = toMap<Resource>([
+ {
+ id: "resourceId",
+ name: "My Resource",
+ url: `""`,
+ method: "get",
+ headers: [],
+ },
+ ]);
+ const dataSources = toMap<DataSource>([
+ {
+ id: "resourceVariableId",
+ scopeInstanceId: "box",
+ name: "My Resource Variable",
+ type: "resource",
+ resourceId: "resourceId",
+ },
+ ]);
$registeredComponentMetas.set(createFakeComponentMetas({}));
- deleteInstance(["box", "body"]);
+ const data = getWebstudioData({ instances, resources, dataSources });
+ deleteInstanceMutable(data, ["box", "body"]);
- expect($instances.get()).toEqual(
- toMap([createInstance("body", "Body", [])])
- );
- expect($dataSources.get()).toEqual(new Map());
- expect($resources.get()).toEqual(new Map());
+ expect(data.instances).toEqual(toMap([createInstance("body", "Body", [])]));
+ expect(data.dataSources).toEqual(new Map());
+ expect(data.resources).toEqual(new Map());
});
});
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index c45948af8d..0a08853df1 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -18,6 +18,7 @@ import {
Breakpoint,
Pages,
type WebstudioFragment,
+ type WebstudioData,
} from "@webstudio-is/sdk";
import { findTreeInstanceIdsExcludingSlotDescendants } from "@webstudio-is/sdk";
import {
@@ -59,6 +60,53 @@ import { isBaseBreakpoint } from "./breakpoints";
import { humanizeString } from "./string-utils";
import { serverSyncStore } from "./sync";
+export const updateWebstudioData = (mutate: (data: WebstudioData) => void) => {
+ serverSyncStore.createTransaction(
+ [
+ $pages,
+ $instances,
+ $props,
+ $breakpoints,
+ $styleSourceSelections,
+ $styleSources,
+ $styles,
+ $dataSources,
+ $resources,
+ $assets,
+ ],
+ (
+ pages,
+ instances,
+ props,
+ breakpoints,
+ styleSourceSelections,
+ styleSources,
+ styles,
+ dataSources,
+ resources,
+ assets
+ ) => {
+ // @todo normalize pages
+ if (pages === undefined) {
+ return;
+ }
+ mutate({
+ pages,
+ instances,
+ props,
+ dataSources,
+ resources,
+ breakpoints,
+ styleSourceSelections,
+ styleSources,
+ styles,
+ assets,
+ });
+ //
+ }
+ );
+};
+
const getLabelFromComponentName = (component: Instance["component"]) => {
if (component.includes(":")) {
// strip namespace
@@ -135,8 +183,10 @@ export const findClosestDetachableInstanceSelector = (
}
};
-export const isInstanceDetachable = (instanceSelector: InstanceSelector) => {
- const instances = $instances.get();
+export const isInstanceDetachable = (
+ instances: Instances,
+ instanceSelector: InstanceSelector
+) => {
const metas = $registeredComponentMetas.get();
const [instanceId] = instanceSelector;
const instance = instances.get(instanceId);
@@ -411,113 +461,104 @@ export const reparentInstance = (
$selectedStyleSourceSelector.set(undefined);
};
-export const deleteInstance = (instanceSelector: InstanceSelector) => {
+export const deleteInstanceMutable = (
+ data: WebstudioData,
+ instanceSelector: InstanceSelector
+) => {
// @todo tell user they can't delete root
if (instanceSelector.length === 1) {
return false;
}
- if (isInstanceDetachable(instanceSelector) === false) {
+ if (isInstanceDetachable(data.instances, instanceSelector) === false) {
toast.error(
"This instance can not be moved outside of its parent component."
);
return false;
}
- serverSyncStore.createTransaction(
- [
- $instances,
- $props,
- $styleSourceSelections,
- $styleSources,
- $styles,
- $dataSources,
- $resources,
- ],
- (
- instances,
- props,
- styleSourceSelections,
- styleSources,
- styles,
- dataSources,
- resources
- ) => {
- let targetInstanceId = instanceSelector[0];
- const parentInstanceId = instanceSelector[1];
- let parentInstance =
- parentInstanceId === undefined
- ? undefined
- : instances.get(parentInstanceId);
- const grandparentInstanceId = instanceSelector[2];
- const grandparentInstance = instances.get(grandparentInstanceId);
-
- // delete parent fragment too if its last child is going to be deleted
- // use case for slots: slot became empty and remove display: contents
- // to be displayed properly on canvas
- if (
- parentInstance?.component === "Fragment" &&
- parentInstance.children.length === 1 &&
- grandparentInstance
- ) {
- targetInstanceId = parentInstance.id;
- parentInstance = grandparentInstance;
- }
+ const {
+ instances,
+ props,
+ styleSourceSelections,
+ styleSources,
+ styles,
+ dataSources,
+ resources,
+ } = data;
+ let targetInstanceId = instanceSelector[0];
+ const parentInstanceId = instanceSelector[1];
+ let parentInstance =
+ parentInstanceId === undefined
+ ? undefined
+ : instances.get(parentInstanceId);
+ const grandparentInstanceId = instanceSelector[2];
+ const grandparentInstance = instances.get(grandparentInstanceId);
+
+ // delete parent fragment too if its last child is going to be deleted
+ // use case for slots: slot became empty and remove display: contents
+ // to be displayed properly on canvas
+ if (
+ parentInstance?.component === "Fragment" &&
+ parentInstance.children.length === 1 &&
+ grandparentInstance
+ ) {
+ targetInstanceId = parentInstance.id;
+ parentInstance = grandparentInstance;
+ }
- // skip parent fake "item" instance and use grandparent collection as parent
- if (grandparentInstance?.component === collectionComponent) {
- parentInstance = grandparentInstance;
- }
+ // skip parent fake "item" instance and use grandparent collection as parent
+ if (grandparentInstance?.component === collectionComponent) {
+ parentInstance = grandparentInstance;
+ }
- const instanceIds = findTreeInstanceIdsExcludingSlotDescendants(
- instances,
- targetInstanceId
- );
- const localStyleSourceIds = findLocalStyleSourcesWithinInstances(
- styleSources.values(),
- styleSourceSelections.values(),
- instanceIds
- );
+ const instanceIds = findTreeInstanceIdsExcludingSlotDescendants(
+ instances,
+ targetInstanceId
+ );
+ const localStyleSourceIds = findLocalStyleSourcesWithinInstances(
+ styleSources.values(),
+ styleSourceSelections.values(),
+ instanceIds
+ );
- // may not exist when delete root
- if (parentInstance) {
- removeByMutable(
- parentInstance.children,
- (child) => child.type === "id" && child.value === targetInstanceId
- );
- }
+ // may not exist when delete root
+ if (parentInstance) {
+ removeByMutable(
+ parentInstance.children,
+ (child) => child.type === "id" && child.value === targetInstanceId
+ );
+ }
- for (const instanceId of instanceIds) {
- instances.delete(instanceId);
- }
- // delete props, data sources and styles of deleted instance and its descendants
- for (const prop of props.values()) {
- if (instanceIds.has(prop.instanceId)) {
- props.delete(prop.id);
- }
- }
- for (const dataSource of dataSources.values()) {
- if (
- dataSource.scopeInstanceId !== undefined &&
- instanceIds.has(dataSource.scopeInstanceId)
- ) {
- dataSources.delete(dataSource.id);
- if (dataSource.type === "resource") {
- resources.delete(dataSource.resourceId);
- }
- }
- }
- for (const instanceId of instanceIds) {
- styleSourceSelections.delete(instanceId);
- }
- for (const styleSourceId of localStyleSourceIds) {
- styleSources.delete(styleSourceId);
- }
- for (const [styleDeclKey, styleDecl] of styles) {
- if (localStyleSourceIds.has(styleDecl.styleSourceId)) {
- styles.delete(styleDeclKey);
- }
+ for (const instanceId of instanceIds) {
+ instances.delete(instanceId);
+ }
+ // delete props, data sources and styles of deleted instance and its descendants
+ for (const prop of props.values()) {
+ if (instanceIds.has(prop.instanceId)) {
+ props.delete(prop.id);
+ }
+ }
+ for (const dataSource of dataSources.values()) {
+ if (
+ dataSource.scopeInstanceId !== undefined &&
+ instanceIds.has(dataSource.scopeInstanceId)
+ ) {
+ dataSources.delete(dataSource.id);
+ if (dataSource.type === "resource") {
+ resources.delete(dataSource.resourceId);
}
}
- );
+ }
+ for (const instanceId of instanceIds) {
+ styleSourceSelections.delete(instanceId);
+ }
+ for (const styleSourceId of localStyleSourceIds) {
+ styleSources.delete(styleSourceId);
+ }
+ for (const [styleDeclKey, styleDecl] of styles) {
+ if (localStyleSourceIds.has(styleDecl.styleSourceId)) {
+ styles.delete(styleDeclKey);
+ }
+ }
return true;
};