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: switch to instances slice for copy paste (#2666)

Bogdan Chadkin8e1683ed8687
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts
index 5fbdd4b265..d9faeda311 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts
@@ -14,10 +14,13 @@ import {
collectionComponent,
encodeDataSourceVariable,
coreMetas,
+ portalComponent,
} from "@webstudio-is/react-sdk";
import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";
import { registerContainers } from "../sync";
import {
+ $instances,
+ $selectedInstanceSelector,
dataSourcesStore,
instancesStore,
pagesStore,
@@ -29,6 +32,8 @@ import {
} from "../nano-states";
import { onCopy, onPaste } from "./plugin-instance";
+const expectString = expect.any(String) as unknown as string;
+
enableMapSet();
registerContainers();
@@ -452,3 +457,199 @@ describe("data sources", () => {
);
});
});
+
+test("when paste into copied instance insert after it", () => {
+ $instances.set(
+ toMap([
+ createInstance("body", "Body", [{ type: "id", value: "box" }]),
+ createInstance("box", "Box", []),
+ ])
+ );
+ $selectedInstanceSelector.set(["box", "body"]);
+ const clipboardData = onCopy() ?? "";
+ onPaste(clipboardData);
+
+ expect($instances.get()).toEqual(
+ toMap([
+ createInstance("body", "Body", [
+ { type: "id", value: "box" },
+ { type: "id", value: expectString },
+ ]),
+ createInstance("box", "Box", []),
+ createInstance(expectString, "Box", []),
+ ])
+ );
+});
+
+test("prevent pasting portal into own descendents", () => {
+ const instances = toMap([
+ createInstance("body", "Body", [{ type: "id", value: "portal" }]),
+ createInstance("portal", portalComponent, [
+ { type: "id", value: "fragment" },
+ ]),
+ createInstance("fragment", "Fragment", [{ type: "id", value: "box" }]),
+ createInstance("box", "Box", []),
+ ]);
+ $instances.set(instances);
+ $selectedInstanceSelector.set(["portal", "body"]);
+ const clipboardData = onCopy() ?? "";
+ $selectedInstanceSelector.set(["box", "fragment", "portal", "body"]);
+ onPaste(clipboardData);
+ expect($instances.get()).toEqual(instances);
+});
+
+test("prevent pasting portal into copy of it", () => {
+ const instances = toMap([
+ createInstance("body", "Body", [
+ { type: "id", value: "portal1" },
+ { type: "id", value: "portal2" },
+ ]),
+ createInstance("portal1", portalComponent, [
+ { type: "id", value: "fragment" },
+ ]),
+ createInstance("portal2", portalComponent, [
+ { type: "id", value: "fragment" },
+ ]),
+ createInstance("fragment", "Fragment", []),
+ ]);
+ $instances.set(instances);
+ $selectedInstanceSelector.set(["portal1", "body"]);
+ const clipboardData = onCopy() ?? "";
+ $selectedInstanceSelector.set(["portal2", "body"]);
+ onPaste(clipboardData);
+ expect($instances.get()).toEqual(instances);
+});
+
+test("insert portal into its sibling", () => {
+ $instances.set(
+ toMap([
+ createInstance("body", "Body", [
+ { type: "id", value: "portal" },
+ { type: "id", value: "sibling" },
+ ]),
+ createInstance("portal", portalComponent, [
+ { type: "id", value: "fragment" },
+ ]),
+ createInstance("fragment", "Fragment", []),
+ createInstance("sibling", "Box", []),
+ ])
+ );
+ $selectedInstanceSelector.set(["portal", "body"]);
+ const clipboardData = onCopy() ?? "";
+ $selectedInstanceSelector.set(["sibling", "body"]);
+ onPaste(clipboardData);
+
+ expect($instances.get()).toEqual(
+ toMap([
+ createInstance("body", "Body", [
+ { type: "id", value: "portal" },
+ { type: "id", value: "sibling" },
+ ]),
+ createInstance("portal", portalComponent, [
+ { type: "id", value: "fragment" },
+ ]),
+ createInstance("fragment", "Fragment", []),
+ createInstance("sibling", "Box", [{ type: "id", value: expectString }]),
+ createInstance(expectString, portalComponent, [
+ { type: "id", value: "fragment" },
+ ]),
+ ])
+ );
+});
+
+test("insert into portal fragment when portal is a target", () => {
+ $instances.set(
+ toMap([
+ createInstance("body", "Body", [
+ { type: "id", value: "portal" },
+ { type: "id", value: "box" },
+ ]),
+ createInstance("portal", portalComponent, []),
+ createInstance("box", "Box", []),
+ ])
+ );
+ $selectedInstanceSelector.set(["box", "body"]);
+ const clipboardData = onCopy() ?? "";
+ $selectedInstanceSelector.set(["portal", "body"]);
+
+ // fragment not exists
+ const prevInstances = $instances.get();
+ onPaste(clipboardData);
+ const [boxId, fragmentId] = getMapDifference(
+ prevInstances,
+ $instances.get()
+ ).keys();
+ expect($instances.get()).toEqual(
+ toMap([
+ createInstance("body", "Body", [
+ { type: "id", value: "portal" },
+ { type: "id", value: "box" },
+ ]),
+ createInstance("portal", portalComponent, [
+ { type: "id", value: fragmentId },
+ ]),
+ createInstance(fragmentId, "Fragment", [{ type: "id", value: boxId }]),
+ createInstance("box", "Box", []),
+ createInstance(boxId, "Box", []),
+ ])
+ );
+
+ // fragment already exists
+ onPaste(clipboardData);
+ expect($instances.get()).toEqual(
+ toMap([
+ createInstance("body", "Body", [
+ { type: "id", value: "portal" },
+ { type: "id", value: "box" },
+ ]),
+ createInstance("portal", portalComponent, [
+ { type: "id", value: fragmentId },
+ ]),
+ createInstance(fragmentId, "Fragment", [
+ { type: "id", value: boxId },
+ { type: "id", value: expectString },
+ ]),
+ createInstance("box", "Box", []),
+ createInstance(boxId, "Box", []),
+ createInstance(expectString, "Box", []),
+ ])
+ );
+});
+
+test("wrap siblings with span when instance is rich text container", () => {
+ $instances.set(
+ toMap([
+ createInstance("body", "Body", [
+ { type: "id", value: "text" },
+ { type: "id", value: "box" },
+ ]),
+ createInstance("text", "Text", [{ type: "text", value: "My Text" }]),
+ createInstance("box", "Box", []),
+ ])
+ );
+ $selectedInstanceSelector.set(["box", "body"]);
+ const clipboardData = onCopy() ?? "";
+ $selectedInstanceSelector.set(["text", "body"]);
+
+ const prevInstances = $instances.get();
+ onPaste(clipboardData);
+ const [boxId, spanId] = getMapDifference(
+ prevInstances,
+ $instances.get()
+ ).keys();
+ expect($instances.get()).toEqual(
+ toMap([
+ createInstance("body", "Body", [
+ { type: "id", value: "text" },
+ { type: "id", value: "box" },
+ ]),
+ createInstance("text", "Text", [
+ { type: "id", value: spanId },
+ { type: "id", value: boxId },
+ ]),
+ createInstance("box", "Box", []),
+ createInstance(boxId, "Box", []),
+ createInstance(spanId, "Text", [{ type: "text", value: "My Text" }]),
+ ])
+ );
+});
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.ts
index 44bab0e796..0bd5ec4d47 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts
@@ -1,5 +1,4 @@
import { shallowEqual } from "shallow-equal";
-import { nanoid } from "nanoid";
import { z } from "zod";
import { toast } from "@webstudio-is/design-system";
import {
@@ -7,49 +6,37 @@ import {
Breakpoint,
DataSource,
Instance,
+ Instances,
Prop,
StyleDecl,
StyleSource,
StyleSourceSelection,
+ findTreeInstanceIdsExcludingSlotDescendants,
} from "@webstudio-is/sdk";
import {
- encodeDataSourceVariable,
- validateExpression,
- decodeDataSourceVariable,
-} from "@webstudio-is/react-sdk";
-import {
- propsStore,
- stylesStore,
- selectedInstanceSelectorStore,
- styleSourceSelectionsStore,
- styleSourcesStore,
- instancesStore,
- selectedPageStore,
- breakpointsStore,
- assetsStore,
- projectStore,
- registeredComponentMetasStore,
- dataSourcesStore,
+ $selectedInstanceSelector,
+ $selectedPage,
+ $project,
+ $registeredComponentMetas,
+ $instances,
+ $dataSources,
} from "../nano-states";
import {
type InstanceSelector,
- insertInstancesCopyMutable,
- insertPropsCopyMutable,
- insertStylesCopyMutable,
- insertStyleSourcesCopyMutable,
- insertStyleSourceSelectionsCopyMutable,
- findLocalStyleSourcesWithinInstances,
- mergeNewBreakpointsMutable,
type DroppableTarget,
+ getInstanceOrCreateFragmentIfNecessary,
+ wrapEditableChildrenAroundDropTargetMutable,
} from "../tree-utils";
import {
computeInstancesConstraints,
deleteInstance,
+ findAvailableDataSources,
findClosestDroppableTarget,
getInstancesSlice,
+ insertInstancesSliceCopy,
isInstanceDetachable,
} from "../instance-utils";
-import { serverSyncStore } from "../sync";
+import { portalComponent } from "@webstudio-is/react-sdk";
const version = "@webstudio/instance/v0.1";
@@ -105,251 +92,157 @@ const parse = (clipboardData: string): InstanceData | undefined => {
export const mimeType = "application/json";
-export const onPaste = (clipboardData: string): boolean => {
- const data = parse(clipboardData);
-
- const selectedPage = selectedPageStore.get();
- const project = projectStore.get();
-
+export const getPortalFragmentSelector = (
+ instances: Instances,
+ instanceSelector: InstanceSelector
+) => {
+ const instance = instances.get(instanceSelector[0]);
if (
- data === undefined ||
- selectedPage === undefined ||
- project === undefined
+ instance?.component !== portalComponent ||
+ instance.children.length === 0 ||
+ instance.children[0].type !== "id"
) {
- return false;
+ return;
}
+ // first portal child is always fragment
+ return [instance.children[0].value, ...instanceSelector];
+};
- const metas = registeredComponentMetasStore.get();
- const newInstances = new Map(
- data.instances.map((instance) => [instance.id, instance])
- );
- const rootInstanceId = data.instances[0].id;
- // paste to the root if nothing is selected
- const instanceSelector = selectedInstanceSelectorStore.get() ?? [
- selectedPage.rootInstanceId,
- ];
- let potentialDropTarget: undefined | DroppableTarget;
+const getPasteTarget = (
+ data: InstanceData,
+ instanceSelector: InstanceSelector
+): undefined | DroppableTarget => {
+ const instances = $instances.get();
+
+ // paste after selected instance
if (shallowEqual(instanceSelector, data.instanceSelector)) {
- // paste after selected instance
- const instances = instancesStore.get();
// body is not allowed to copy
// so clipboard always have at least two level instance selector
const [currentInstanceId, parentInstanceId] = instanceSelector;
const parentInstance = instances.get(parentInstanceId);
if (parentInstance === undefined) {
- return false;
+ return;
}
const indexWithinChildren = parentInstance.children.findIndex(
(child) => child.type === "id" && child.value === currentInstanceId
);
- potentialDropTarget = {
+ return {
parentSelector: instanceSelector.slice(1),
position: indexWithinChildren + 1,
};
- } else {
- potentialDropTarget = findClosestDroppableTarget(
- metas,
- instancesStore.get(),
- instanceSelector,
- computeInstancesConstraints(metas, newInstances, [rootInstanceId])
- );
}
- if (potentialDropTarget === undefined) {
- return false;
- }
- const dropTarget = potentialDropTarget;
-
- serverSyncStore.createTransaction(
- [
- breakpointsStore,
- instancesStore,
- dataSourcesStore,
- styleSourcesStore,
- propsStore,
- styleSourceSelectionsStore,
- stylesStore,
- assetsStore,
- ],
- (
- breakpoints,
- instances,
- dataSources,
- styleSources,
- props,
- styleSourceSelections,
- styles,
- assets
- ) => {
- for (const asset of data.assets) {
- // asset can be already present if pasting to the same project
- if (assets.has(asset.id) === false) {
- // we use the same asset.id so the references are preserved
- assets.set(asset.id, { ...asset, projectId: project.id });
- }
- }
-
- const mergedBreakpointIds = mergeNewBreakpointsMutable(
- breakpoints,
- data.breakpoints
- );
- const copiedInstanceIds = insertInstancesCopyMutable(
- instances,
- props,
- registeredComponentMetasStore.get(),
- data.instances,
- dropTarget
- );
-
- // duplicate data sources only within copied tree
- const copiedDataSourceIds = new Map<DataSource["id"], DataSource["id"]>();
- const copiedDataSources = new Map<DataSource["id"], DataSource>();
- for (const dataSource of data.dataSources) {
- const { scopeInstanceId } = dataSource;
- if (
- scopeInstanceId !== undefined &&
- copiedInstanceIds.has(scopeInstanceId)
- ) {
- copiedDataSourceIds.set(dataSource.id, nanoid());
- }
- copiedDataSources.set(dataSource.id, dataSource);
- }
-
- for (const dataSource of data.dataSources) {
- let { scopeInstanceId } = dataSource;
- if (scopeInstanceId === undefined) {
- continue;
- }
- // reject data sources outside of copied tree and not scoped to ancestors
- if (
- copiedInstanceIds.has(scopeInstanceId) === false &&
- instanceSelector.includes(scopeInstanceId) === false
- ) {
- continue;
- }
- scopeInstanceId = copiedInstanceIds.get(scopeInstanceId);
+ const newInstances: Instances = new Map();
+ for (const instance of data.instances) {
+ newInstances.set(instance.id, instance);
+ }
+ const metas = $registeredComponentMetas.get();
+ const rootInstanceId = data.instances[0].id;
+ const pasteTarget = findClosestDroppableTarget(
+ metas,
+ instances,
+ instanceSelector,
+ computeInstancesConstraints(metas, newInstances, [rootInstanceId])
+ );
+ if (pasteTarget === undefined) {
+ return;
+ }
- const newId = copiedDataSourceIds.get(dataSource.id);
- if (newId === undefined) {
- continue;
- }
- if (dataSource.type === "variable") {
- dataSources.set(newId, {
- ...dataSource,
- id: newId,
- scopeInstanceId,
- });
- }
+ const newInstanceIds = findTreeInstanceIdsExcludingSlotDescendants(
+ newInstances,
+ data.instances[0].id
+ );
+ const preservedChildIds = new Set<Instance["id"]>();
+ for (const instance of data.instances) {
+ for (const child of instance.children) {
+ if (child.type === "id" && newInstanceIds.has(child.value) === false) {
+ preservedChildIds.add(child.value);
}
+ }
+ }
- const localStyleSourceIds = findLocalStyleSourcesWithinInstances(
- data.styleSources,
- data.styleSourceSelections,
- new Set(copiedInstanceIds.keys())
- );
+ // portal descendants ids are preserved
+ // so need to prevent pasting portal inside its copies
+ // to avoid circular tree
+ const dropTargetSelector =
+ // consider portal fragment when check for cycles to avoid cases
+ // like pasting portal directly into portal
+ getPortalFragmentSelector(instances, pasteTarget.parentSelector) ??
+ pasteTarget.parentSelector;
+ for (const instanceId of dropTargetSelector) {
+ if (preservedChildIds.has(instanceId)) {
+ return;
+ }
+ }
- const copiedStyleSourceIds = insertStyleSourcesCopyMutable(
- styleSources,
- data.styleSources,
- localStyleSourceIds
- );
+ return pasteTarget;
+};
- insertPropsCopyMutable(
- props,
- data.props.map((prop) => {
- let actionDiscarded = false;
- const transformIdentifier = (
- identifier: string,
- assignee: boolean
- ) => {
- const dataSourceId = decodeDataSourceVariable(identifier);
- if (dataSourceId === undefined) {
- return identifier;
- }
- // data source is within copied tree
- const newId = copiedDataSourceIds.get(dataSourceId);
- if (newId !== undefined) {
- return encodeDataSourceVariable(newId);
- }
- const dataSource = copiedDataSources.get(dataSourceId);
- // data source is within paste target
- if (
- dataSource?.scopeInstanceId !== undefined &&
- instanceSelector.includes(dataSource.scopeInstanceId)
- ) {
- return identifier;
- }
- // left operand of assign operator cannot be inlined
- if (assignee) {
- actionDiscarded = true;
- }
- // inline variable not scoped to copied tree or paste target
- if (dataSource?.type === "variable") {
- return JSON.stringify(dataSource.value.value);
- }
- return identifier;
- };
+export const onPaste = (clipboardData: string): boolean => {
+ const data = parse(clipboardData);
- if (prop.type === "parameter") {
- return {
- ...prop,
- value: copiedDataSourceIds.get(prop.value) ?? prop.value,
- };
- }
+ const selectedPage = $selectedPage.get();
+ const project = $project.get();
+ const metas = $registeredComponentMetas.get();
- if (prop.type === "expression") {
- return {
- ...prop,
- value: validateExpression(prop.value, {
- transformIdentifier,
- }),
- };
- }
+ if (
+ data === undefined ||
+ selectedPage === undefined ||
+ project === undefined
+ ) {
+ return false;
+ }
- if (prop.type === "action") {
- return {
- ...prop,
- value: prop.value.flatMap((value) => {
- if (value.type !== "execute") {
- return [value];
- }
- actionDiscarded = false;
- const newCode = validateExpression(value.code, {
- effectful: true,
- transformIdentifier,
- });
- if (actionDiscarded) {
- return [];
- }
- return [{ ...value, code: newCode }];
- }),
- };
- }
+ // paste to the root if nothing is selected
+ const instanceSelector = $selectedInstanceSelector.get() ?? [
+ selectedPage.rootInstanceId,
+ ];
+ const pasteTarget = getPasteTarget(data, instanceSelector);
+ if (pasteTarget === undefined) {
+ return false;
+ }
- return prop;
- }),
- copiedInstanceIds
- );
+ insertInstancesSliceCopy({
+ slice: data,
+ availableDataSources: findAvailableDataSources(
+ $dataSources.get(),
+ instanceSelector
+ ),
+ beforeTransactionEnd: (rootInstanceId, draft) => {
+ let dropTarget = pasteTarget;
+ dropTarget =
+ getInstanceOrCreateFragmentIfNecessary(draft.instances, dropTarget) ??
+ dropTarget;
+ dropTarget =
+ wrapEditableChildrenAroundDropTargetMutable(
+ draft.instances,
+ draft.props,
+ metas,
+ dropTarget
+ ) ?? dropTarget;
+ const [parentId] = dropTarget.parentSelector;
+ const parentInstance = draft.instances.get(parentId);
+ if (parentInstance === undefined) {
+ return;
+ }
+ const child: Instance["children"][number] = {
+ type: "id",
+ value: rootInstanceId,
+ };
+ const { position } = dropTarget;
+ if (position === "end") {
+ parentInstance.children.push(child);
+ } else {
+ parentInstance.children.splice(position, 0, child);
+ }
+ },
+ });
- insertStyleSourceSelectionsCopyMutable(
- styleSourceSelections,
- data.styleSourceSelections,
- copiedInstanceIds,
- copiedStyleSourceIds
- );
- insertStylesCopyMutable(
- styles,
- data.styles,
- copiedStyleSourceIds,
- mergedBreakpointIds
- );
- }
- );
return true;
};
export const onCopy = () => {
- const selectedInstanceSelector = selectedInstanceSelectorStore.get();
+ const selectedInstanceSelector = $selectedInstanceSelector.get();
if (selectedInstanceSelector === undefined) {
return;
}
@@ -361,7 +254,7 @@ export const onCopy = () => {
};
export const onCut = () => {
- const selectedInstanceSelector = selectedInstanceSelectorStore.get();
+ const selectedInstanceSelector = $selectedInstanceSelector.get();
if (selectedInstanceSelector === undefined) {
return;
}
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index cc50e6081d..7143785ccb 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -801,8 +801,8 @@ export const insertInstancesSliceCopy = ({
slice: InstancesSlice;
availableDataSources: Set<DataSource["id"]>;
beforeTransactionEnd?: (
- rootInstanceI: Instance["id"],
- draft: { instances: Instances; pages: undefined | Pages }
+ rootInstanceId: Instance["id"],
+ draft: { instances: Instances; props: Props; pages: undefined | Pages }
) => void;
}) => {
const projectId = $project.get()?.id;
@@ -1177,7 +1177,7 @@ export const insertInstancesSliceCopy = ({
// invoke callback to allow additional changes within same transaction
const rootInstanceId =
newInstanceIds.get(slice.instances[0].id) ?? slice.instances[0].id;
- beforeTransactionEnd?.(rootInstanceId, { instances, pages });
+ beforeTransactionEnd?.(rootInstanceId, { instances, props, pages });
}
);
};
diff --git a/apps/builder/app/shared/nano-states/components.ts b/apps/builder/app/shared/nano-states/components.ts
index 16b6f8bc12..8a7278f165 100644
--- a/apps/builder/app/shared/nano-states/components.ts
+++ b/apps/builder/app/shared/nano-states/components.ts
@@ -125,6 +125,7 @@ export const registeredComponentHooksStore = atom<Hook[]>([]);
export const registeredComponentMetasStore = atom(
new Map<string, WsComponentMeta>()
);
+export const $registeredComponentMetas = registeredComponentMetasStore;
export const registeredComponentPropsMetasStore = atom(
new Map<string, WsComponentPropsMeta>()
diff --git a/apps/builder/app/shared/nano-states/instances.ts b/apps/builder/app/shared/nano-states/instances.ts
index 3d1dfec1c3..1c4b8636f4 100644
--- a/apps/builder/app/shared/nano-states/instances.ts
+++ b/apps/builder/app/shared/nano-states/instances.ts
@@ -7,6 +7,7 @@ export const isResizingCanvasStore = atom(false);
export const selectedInstanceSelectorStore = atom<undefined | InstanceSelector>(
undefined
);
+export const $selectedInstanceSelector = selectedInstanceSelectorStore;
export const editingItemIdStore = atom<undefined | string>(undefined);
diff --git a/apps/builder/app/shared/tree-utils.test.ts b/apps/builder/app/shared/tree-utils.test.ts
index d38437a421..9adbf85a10 100644
--- a/apps/builder/app/shared/tree-utils.test.ts
+++ b/apps/builder/app/shared/tree-utils.test.ts
@@ -1,6 +1,5 @@
import { test, expect, describe } from "@jest/globals";
import type {
- Breakpoint,
Instance,
Instances,
Prop,
@@ -16,32 +15,15 @@ import {
cloneStyles,
findLocalStyleSourcesWithinInstances,
getAncestorInstanceSelector,
- insertInstancesCopyMutable,
insertInstancesMutable,
insertPropsCopyMutable,
- insertStylesCopyMutable,
- insertStyleSourcesCopyMutable,
- insertStyleSourceSelectionsCopyMutable,
reparentInstanceMutable,
- mergeNewBreakpointsMutable,
} from "./tree-utils";
const baseMetasMap = new Map(Object.entries(baseMetas));
const expectString = expect.any(String) as unknown as string;
-const createBreakpoint = (
- id: Breakpoint["id"],
- minWidth: Breakpoint["minWidth"]
-) => ({ id, label: id, minWidth });
-
-const createBreakpointPair = (
- id: Breakpoint["id"],
- minWidth: Breakpoint["minWidth"]
-) => {
- return [id, createBreakpoint(id, minWidth)] as const;
-};
-
const createInstance = (
id: Instance["id"],
component: string,
@@ -627,231 +609,6 @@ test("reparent instance into slot", () => {
);
});
-test("insert tree of instances copy and provide map from ids map", () => {
- const instances = new Map([
- createInstancePair("1", "Body", [
- { type: "id", value: "2" },
- { type: "id", value: "3" },
- ]),
- createInstancePair("2", "Box", []),
- createInstancePair("3", "Box", [{ type: "id", value: "4" }]),
- createInstancePair("4", "Box", []),
- ]);
- const copiedInstances = [
- createInstance("2", "Box", [
- { type: "id", value: "3" },
- { type: "text", value: "text" },
- ]),
- createInstance("3", "Box", []),
- ];
- const copiedInstanceIds = insertInstancesCopyMutable(
- instances,
- new Map(),
- baseMetasMap,
- copiedInstances,
- {
- parentSelector: ["3", "1"],
- position: 0,
- }
- );
- expect(Array.from(copiedInstanceIds.entries())).toEqual([
- ["2", expectString],
- ["3", expectString],
- ]);
- expect(Array.from(instances.entries())).toEqual([
- createInstancePair("1", "Body", [
- { type: "id", value: "2" },
- { type: "id", value: "3" },
- ]),
- createInstancePair("2", "Box", []),
- createInstancePair("3", "Box", [
- { type: "id", value: expectString },
- { type: "id", value: "4" },
- ]),
- createInstancePair("4", "Box", []),
- createInstancePair(expectString, "Box", [
- { type: "id", value: expectString },
- { type: "text", value: "text" },
- ]),
- createInstancePair(expectString, "Box", []),
- ]);
-});
-
-test("insert slot or do nothing when slot is cyclic", () => {
- const instances = new Map([
- createInstancePair("root", "Body", [
- { type: "id", value: "slot" },
- { type: "id", value: "sibling" },
- ]),
- createInstancePair("slot", "Slot", [{ type: "id", value: "fragment" }]),
- createInstancePair("fragment", "Fragment", [
- { type: "id", value: "child" },
- ]),
- createInstancePair("child", "Box", []),
- createInstancePair("sibling", "Box", []),
- ]);
- let copiedInstances = [
- createInstance("slot", "Slot", [{ type: "id", value: "fragment" }]),
- ];
-
- // insert slot own descendant
- let copiedInstanceIds = insertInstancesCopyMutable(
- instances,
- new Map(),
- baseMetasMap,
- copiedInstances,
- {
- parentSelector: ["child", "fragment", "slot", "root"],
- position: "end",
- }
- );
- expect(copiedInstanceIds).toEqual(new Map());
- expect(Array.from(instances.entries())).toEqual([
- createInstancePair("root", "Body", [
- { type: "id", value: "slot" },
- { type: "id", value: "sibling" },
- ]),
- createInstancePair("slot", "Slot", [{ type: "id", value: "fragment" }]),
- createInstancePair("fragment", "Fragment", [
- { type: "id", value: "child" },
- ]),
- createInstancePair("child", "Box", []),
- createInstancePair("sibling", "Box", []),
- ]);
-
- // do not insert slot into itself
- copiedInstanceIds = insertInstancesCopyMutable(
- instances,
- new Map(),
- baseMetasMap,
- copiedInstances,
- {
- parentSelector: ["slot", "root"],
- position: "end",
- }
- );
- expect(copiedInstanceIds).toEqual(new Map());
- expect(Array.from(instances.entries())).toEqual([
- createInstancePair("root", "Body", [
- { type: "id", value: "slot" },
- { type: "id", value: "sibling" },
- ]),
- createInstancePair("slot", "Slot", [{ type: "id", value: "fragment" }]),
- createInstancePair("fragment", "Fragment", [
- { type: "id", value: "child" },
- ]),
- createInstancePair("child", "Box", []),
- createInstancePair("sibling", "Box", []),
- ]);
-
- // insert slot into sibling
- copiedInstanceIds = insertInstancesCopyMutable(
- instances,
- new Map(),
- baseMetasMap,
- copiedInstances,
- {
- parentSelector: ["sibling", "root"],
- position: "end",
- }
- );
- expect(copiedInstanceIds).toEqual(new Map([["slot", expectString]]));
- expect(Array.from(instances.entries())).toEqual([
- createInstancePair("root", "Body", [
- { type: "id", value: "slot" },
- { type: "id", value: "sibling" },
- ]),
- createInstancePair("slot", "Slot", [{ type: "id", value: "fragment" }]),
- createInstancePair("fragment", "Fragment", [
- { type: "id", value: "child" },
- ]),
- createInstancePair("child", "Box", []),
- createInstancePair("sibling", "Box", [{ type: "id", value: expectString }]),
- createInstancePair(expectString, "Slot", [
- { type: "id", value: "fragment" },
- ]),
- ]);
-
- // insert new slot from other project
- copiedInstances = [
- createInstance("slot2", "Slot", [{ type: "id", value: "fragment2" }]),
- createInstance("fragment2", "Fragment", [
- { type: "id", value: "slot2box" },
- ]),
- createInstance("slot2box", "Box", []),
- ];
- copiedInstanceIds = insertInstancesCopyMutable(
- instances,
- new Map(),
- baseMetasMap,
- copiedInstances,
- {
- parentSelector: ["root"],
- position: "end",
- }
- );
- expect(copiedInstanceIds).toEqual(new Map([["slot2", expectString]]));
- expect(Array.from(instances.entries())).toEqual([
- createInstancePair("root", "Body", [
- { type: "id", value: "slot" },
- { type: "id", value: "sibling" },
- { type: "id", value: expectString },
- ]),
- createInstancePair("slot", "Slot", [{ type: "id", value: "fragment" }]),
- createInstancePair("fragment", "Fragment", [
- { type: "id", value: "child" },
- ]),
- createInstancePair("child", "Box", []),
- createInstancePair("sibling", "Box", [{ type: "id", value: expectString }]),
- createInstancePair(expectString, "Slot", [
- { type: "id", value: "fragment" },
- ]),
- createInstancePair("fragment2", "Fragment", [
- { type: "id", value: "slot2box" },
- ]),
- createInstancePair("slot2box", "Box", []),
- createInstancePair(expectString, "Slot", [
- { type: "id", value: "fragment2" },
- ]),
- ]);
-});
-
-test("insert style sources copy with new ids and provide map from old ids", () => {
- const styleSources = new Map([
- ["local1", createStyleSource("local", "local1")],
- ["local2", createStyleSource("local", "local2")],
- ["token3", createStyleSource("token", "token3")],
- ]);
- const copiedStyleSources = [
- createStyleSource("local", "local1"),
- createStyleSource("local", "local2"),
- createStyleSource("local", "local4"),
- createStyleSource("token", "token5"),
- ];
- const newStyleSourceIds = new Set(["local1", "local2"]);
- const copiedStyleSourceIds = insertStyleSourcesCopyMutable(
- styleSources,
- copiedStyleSources,
- newStyleSourceIds
- );
- expect(Array.from(copiedStyleSourceIds.entries())).toEqual([
- ["local1", expectString],
- ["local2", expectString],
- ]);
- expect(Array.from(styleSources.entries())).toEqual([
- ["local1", createStyleSource("local", "local1")],
- ["local2", createStyleSource("local", "local2")],
- // shared prop should not be overriden
- ["token3", createStyleSource("token", "token3")],
- // new style sources are copied
- [expectString, createStyleSource("local", expectString)],
- [expectString, createStyleSource("local", expectString)],
- // shared style sources are inserted without changes
- ["local4", createStyleSource("local", "local4")],
- ["token5", createStyleSource("token", "token5")],
- ]);
-});
-
test("insert props copy with new ids and apply new instance ids", () => {
const props = new Map([
["prop1", createProp("prop1", "instance1")],
@@ -881,106 +638,6 @@ test("insert props copy with new ids and apply new instance ids", () => {
]);
});
-test("insert style source selections copy and apply new instance ids and style source ids", () => {
- const styleSourceSelections = new Map([
- [
- "instance1",
- createStyleSourceSelection("instance1", ["local1", "token2"]),
- ],
- [
- "instance2",
- createStyleSourceSelection("instance2", ["token3", "local4", "token5"]),
- ],
- ["instance3", createStyleSourceSelection("instance3", ["local6"])],
- ]);
- const copiedStyleSourceSelections = [
- createStyleSourceSelection("instance1", ["local1", "token2"]),
- createStyleSourceSelection("instance2", ["token3", "local4", "token5"]),
- createStyleSourceSelection("instance3", ["local6", "token5"]),
- createStyleSourceSelection("instance4", ["token5"]),
- ];
- const copiedStyleSourceIds = new Map<StyleSource["id"], StyleSource["id"]>([
- ["local1", "newLocal1"],
- ["local4", "newLocal4"],
- ]);
- const copiedInstanceIds = new Map<Instance["id"], Instance["id"]>([
- ["instance1", "newInstance1"],
- ["instance2", "newInstance2"],
- ]);
- insertStyleSourceSelectionsCopyMutable(
- styleSourceSelections,
- copiedStyleSourceSelections,
- copiedInstanceIds,
- copiedStyleSourceIds
- );
- expect(Array.from(styleSourceSelections.entries())).toEqual([
- [
- "instance1",
- createStyleSourceSelection("instance1", ["local1", "token2"]),
- ],
- [
- "instance2",
- createStyleSourceSelection("instance2", ["token3", "local4", "token5"]),
- ],
- ["instance3", createStyleSourceSelection("instance3", ["local6"])],
- [
- "newInstance1",
- createStyleSourceSelection("newInstance1", ["newLocal1", "token2"]),
- ],
- [
- "newInstance2",
- createStyleSourceSelection("newInstance2", [
- "token3",
- "newLocal4",
- "token5",
- ]),
- ],
- ["instance4", createStyleSourceSelection("instance4", ["token5"])],
- ]);
-});
-
-test("insert styles copy and apply new style source ids", () => {
- const styles: Styles = new Map([
- createStyleDeclPair("styleSource1", "bp1"),
- createStyleDeclPair("styleSource2", "bp2"),
- createStyleDeclPair("styleSource1", "bp3"),
- createStyleDeclPair("styleSource3", "bp4"),
- createStyleDeclPair("existingSharedStyleSource", "bp4"),
- ]);
- const copiedStyles = [
- createStyleDecl("styleSource2", "bp2"),
- createStyleDecl("styleSource3", "bp4"),
- createStyleDecl("sharedStyleSource", "bp4"),
- createStyleDecl("existingSharedStyleSource", "bp4", "newValue"),
- ];
- const copiedStyleSourceIds = new Map<StyleSource["id"], StyleSource["id"]>([
- ["styleSource2", "newStyleSource2"],
- ["styleSource3", "newStyleSource3"],
- ]);
- const mergedBreakpointIds = new Map<Breakpoint["id"], Breakpoint["id"]>([
- ["bp2", "newBp2"],
- ]);
- insertStylesCopyMutable(
- styles,
- copiedStyles,
- copiedStyleSourceIds,
- mergedBreakpointIds
- );
- expect(Array.from(styles.entries())).toEqual([
- createStyleDeclPair("styleSource1", "bp1"),
- createStyleDeclPair("styleSource2", "bp2"),
- createStyleDeclPair("styleSource1", "bp3"),
- createStyleDeclPair("styleSource3", "bp4"),
- // shared style is not overriden
- createStyleDeclPair("existingSharedStyleSource", "bp4"),
- // new styles are copied
- createStyleDeclPair("newStyleSource2", "newBp2"),
- createStyleDeclPair("newStyleSource3", "bp4"),
- // shared style inserted without changes
- createStyleDeclPair("sharedStyleSource", "bp4"),
- ]);
-});
-
test("clone styles with appled new style source ids", () => {
const styles: Styles = new Map([
createStyleDeclPair("styleSource1", "bp1"),
@@ -1025,28 +682,3 @@ test("find local style sources within instances", () => {
)
).toEqual(new Set(["local2", "local4"]));
});
-
-test("merge new breakpoints", () => {
- const breakpoints = new Map([
- createBreakpointPair("1", 0),
- createBreakpointPair("2", 600),
- createBreakpointPair("3", 1200),
- ]);
- const newBreakpoints = [
- createBreakpoint("4", 600),
- createBreakpoint("5", 768),
- ];
- const mergedBreakpointIds = mergeNewBreakpointsMutable(
- breakpoints,
- newBreakpoints
- );
- expect(mergedBreakpointIds).toEqual(new Map([["4", "2"]]));
- expect(breakpoints).toEqual(
- new Map([
- createBreakpointPair("1", 0),
- createBreakpointPair("2", 600),
- createBreakpointPair("3", 1200),
- createBreakpointPair("5", 768),
- ])
- );
-});
diff --git a/apps/builder/app/shared/tree-utils.ts b/apps/builder/app/shared/tree-utils.ts
index b1d033f09f..57cc0c58b3 100644
--- a/apps/builder/app/shared/tree-utils.ts
+++ b/apps/builder/app/shared/tree-utils.ts
@@ -1,8 +1,5 @@
import { nanoid } from "nanoid";
import {
- Breakpoint,
- Breakpoints,
- getStyleDeclKey,
Instance,
Instances,
Prop,
@@ -10,15 +7,9 @@ import {
StyleDecl,
Styles,
StyleSource,
- StyleSources,
StyleSourceSelection,
- StyleSourceSelections,
} from "@webstudio-is/sdk";
-import {
- findTreeInstanceIds,
- findTreeInstanceIdsExcludingSlotDescendants,
-} from "@webstudio-is/sdk";
-import { equalMedia } from "@webstudio-is/css-engine";
+import { findTreeInstanceIds } from "@webstudio-is/sdk";
import {
collectionComponent,
type WsComponentMeta,
@@ -58,7 +49,7 @@ export type DroppableTarget = {
position: number | "end";
};
-const getInstanceOrCreateFragmentIfNecessary = (
+export const getInstanceOrCreateFragmentIfNecessary = (
instances: Instances,
dropTarget: DroppableTarget
) => {
@@ -128,7 +119,7 @@ const adjustChildrenPosition = (
* to preserve lexical specific components while allowing
* to insert into editable components
*/
-const wrapEditableChildrenAroundDropTargetMutable = (
+export const wrapEditableChildrenAroundDropTargetMutable = (
instances: Instances,
props: Props,
metas: Map<string, WsComponentMeta>,
@@ -205,22 +196,6 @@ const wrapEditableChildrenAroundDropTargetMutable = (
};
};
-const getSlotFragmentSelector = (
- instances: Instances,
- instanceSelector: InstanceSelector
-) => {
- const instance = instances.get(instanceSelector[0]);
- if (
- instance?.component !== "Slot" ||
- instance.children.length === 0 ||
- instance.children[0].type !== "id"
- ) {
- return;
- }
- // first slot child is always fragment
- return [instance.children[0].value, ...instanceSelector];
-};
-
export const reparentInstanceMutable = (
instances: Instances,
props: Props,
@@ -391,116 +366,6 @@ export const insertInstancesMutable = (
}
};
-export const insertInstancesCopyMutable = (
- instances: Instances,
- props: Props,
- metas: Map<string, WsComponentMeta>,
- copiedInstances: Instance[],
- dropTarget: DroppableTarget
-) => {
- const newInstances: Instances = new Map();
- for (const instance of copiedInstances) {
- newInstances.set(instance.id, instance);
- }
- const newInstanceIds = findTreeInstanceIdsExcludingSlotDescendants(
- newInstances,
- copiedInstances[0].id
- );
-
- const copiedInstanceIds = new Map<Instance["id"], Instance["id"]>();
- const copiedInstancesWithNewIds: Instance[] = [];
- for (const instanceId of newInstanceIds) {
- const newInstanceId = nanoid();
- copiedInstanceIds.set(instanceId, newInstanceId);
- }
-
- const preservedChildIds = new Set<Instance["id"]>();
-
- for (const instance of copiedInstances) {
- const newInstanceId = copiedInstanceIds.get(instance.id);
- if (newInstanceId === undefined) {
- if (instances.has(instance.id) === false) {
- instances.set(instance.id, instance);
- }
- continue;
- }
-
- copiedInstancesWithNewIds.push({
- ...instance,
- id: newInstanceId,
- children: instance.children.map((child) => {
- if (child.type === "id") {
- if (newInstanceIds.has(child.value) === false) {
- preservedChildIds.add(child.value);
- }
- return {
- type: "id",
- value: copiedInstanceIds.get(child.value) ?? child.value,
- };
- }
- return child;
- }),
- });
- }
-
- // slot descendants ids are preserved
- // so need to prevent pasting slot inside itself
- // to avoid circular tree
- const dropTargetSelector =
- // consider slot fragment when check for cycles to avoid cases like pasting slot directly into slot
- getSlotFragmentSelector(instances, dropTarget.parentSelector) ??
- dropTarget.parentSelector;
- for (const instanceId of dropTargetSelector) {
- if (preservedChildIds.has(instanceId)) {
- return new Map();
- }
- }
-
- insertInstancesMutable(
- instances,
- props,
- metas,
- copiedInstancesWithNewIds,
- // consider the first instance as child
- [
- {
- type: "id",
- value: copiedInstancesWithNewIds[0].id,
- },
- ],
- dropTarget
- );
-
- return copiedInstanceIds;
-};
-
-export const insertStyleSourcesCopyMutable = (
- styleSources: StyleSources,
- copiedStyleSources: StyleSource[],
- newStyleSourceIds: Set<StyleSource["id"]>
-) => {
- // store map of old ids to new ids to copy dependant data
- const copiedStyleSourceIds = new Map<StyleSource["id"], StyleSource["id"]>();
- for (const styleSource of copiedStyleSources) {
- // insert without changes when style source is shared
- if (newStyleSourceIds.has(styleSource.id) === false) {
- // prevent overriding shared style sources if already exist
- if (styleSources.has(styleSource.id) === false) {
- styleSources.set(styleSource.id, styleSource);
- }
- continue;
- }
-
- const newStyleSourceId = nanoid();
- copiedStyleSourceIds.set(styleSource.id, newStyleSourceId);
- styleSources.set(newStyleSourceId, {
- ...styleSource,
- id: newStyleSourceId,
- });
- }
- return copiedStyleSourceIds;
-};
-
export const insertPropsCopyMutable = (
props: Props,
copiedProps: Prop[],
@@ -526,88 +391,3 @@ export const insertPropsCopyMutable = (
});
}
};
-
-export const insertStyleSourceSelectionsCopyMutable = (
- styleSourceSelections: StyleSourceSelections,
- copiedStyleSourceSelections: StyleSourceSelection[],
- copiedInstanceIds: Map<Instance["id"], Instance["id"]>,
- copiedStyleSourceIds: Map<StyleSource["id"], StyleSource["id"]>
-) => {
- for (const styleSourceSelection of copiedStyleSourceSelections) {
- // insert without changes when style source selection does not have new instance id
- const { instanceId } = styleSourceSelection;
- const newInstanceId = copiedInstanceIds.get(instanceId);
- if (newInstanceId === undefined) {
- // prevent overriding shared style source selections if already exist
- if (styleSourceSelections.has(instanceId) === false) {
- styleSourceSelections.set(instanceId, styleSourceSelection);
- }
- continue;
- }
-
- const newValues = styleSourceSelection.values.map(
- (styleSourceId) =>
- // preserve shared style source ids
- copiedStyleSourceIds.get(styleSourceId) ?? styleSourceId
- );
- styleSourceSelections.set(newInstanceId, {
- instanceId: newInstanceId,
- values: newValues,
- });
- }
-};
-
-export const insertStylesCopyMutable = (
- styles: Styles,
- copiedStyles: StyleDecl[],
- copiedStyleSourceIds: Map<StyleSource["id"], StyleSource["id"]>,
- mergedBreakpointIds: Map<Breakpoint["id"], Breakpoint["id"]>
-) => {
- for (const styleDecl of copiedStyles) {
- const newStyleSourceId = copiedStyleSourceIds.get(styleDecl.styleSourceId);
- // fallback to old id in case breakpoint was added without changes
- const newBreakpointId =
- mergedBreakpointIds.get(styleDecl.breakpointId) ?? styleDecl.breakpointId;
- // insert without changes when style source does not have new id
- if (newStyleSourceId === undefined) {
- const newStyleDecl = {
- ...styleDecl,
- breakpointId: newBreakpointId,
- };
- const styleDeclKey = getStyleDeclKey(newStyleDecl);
- // prevent overriding shared styles if already exist
- if (styles.has(styleDeclKey) === false) {
- styles.set(styleDeclKey, newStyleDecl);
- }
- continue;
- }
-
- const styleDeclCopy = {
- ...styleDecl,
- styleSourceId: newStyleSourceId,
- breakpointId: newBreakpointId,
- };
- styles.set(getStyleDeclKey(styleDeclCopy), styleDeclCopy);
- }
-};
-
-export const mergeNewBreakpointsMutable = (
- breakpoints: Breakpoints,
- newBreakpoints: Breakpoint[]
-) => {
- const mergedBreakpointIds = new Map<Breakpoint["id"], Breakpoint["id"]>();
- for (const newBreakpoint of newBreakpoints) {
- let matched = false;
- for (const breakpoint of breakpoints.values()) {
- if (equalMedia(breakpoint, newBreakpoint)) {
- matched = true;
- mergedBreakpointIds.set(newBreakpoint.id, breakpoint.id);
- break;
- }
- }
- if (matched === false) {
- breakpoints.set(newBreakpoint.id, newBreakpoint);
- }
- }
- return mergedBreakpointIds;
-};