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: reimplement duplicating instances (#2663)
Bogdan Chadkin33509db13907
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex 248aab061b..88b037e9f1 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -1,5 +1,6 @@import { createCommandsEmitter, type Command } from "~/shared/commands-emitter";import {+ $dataSources,$isPreviewMode,editingItemIdStore,instancesStore,@@ -11,12 +12,18 @@ import {$breakpointsMenuView,selectBreakpointByOrder,} from "~/shared/breakpoints";-import { onCopy, onPaste } from "~/shared/copy-paste/plugin-instance";-import { deleteInstance } from "~/shared/instance-utils";+import {+ deleteInstance,+ findAvailableDataSources,+ getInstancesSlice,+ insertInstancesSliceCopy,+ isInstanceDetachable,+} from "~/shared/instance-utils";import type { InstanceSelector } from "~/shared/tree-utils";import { serverSyncStore } from "~/shared/sync";import { $publisher } from "~/shared/pubsub";import { $activeSidebarPanel } from "./nano-states";+import { toast } from "@webstudio-is/design-system";const makeBreakpointCommand = <CommandName extends string>(name: CommandName,@@ -157,7 +164,52 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({name: "duplicateInstance",defaultHotkeys: ["meta+d", "ctrl+d"],handler: () => {- onPaste(onCopy() ?? "");+ const instanceSelector = selectedInstanceSelectorStore.get();+ if (instanceSelector === undefined) {+ return;+ }+ if (isInstanceDetachable(instanceSelector) === false) {+ toast.error(+ "This instance can not be moved outside of its parent component."+ );+ return;+ }+ // @todo tell user they can't copy or cut root+ if (instanceSelector.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 slice = getInstancesSlice(targetInstanceId);+ insertInstancesSliceCopy({+ slice,+ availableDataSources: findAvailableDataSources(+ $dataSources.get(),+ parentInstanceSelector+ ),+ beforeTransactionEnd: (rootInstanceId, draft) => {+ const parentInstance = draft.instances.get(parentInstanceId);+ if (parentInstance === undefined) {+ return;+ }+ // put after current instance+ const indexWithinChildren = parentInstance.children.findIndex(+ (child) => child.type === "id" && child.value === targetInstanceId+ );+ const position = indexWithinChildren + 1;+ parentInstance.children.splice(position, 0, {+ type: "id",+ value: rootInstanceId,+ });+ // select new instance+ selectedInstanceSelectorStore.set([+ rootInstanceId,+ ...parentInstanceSelector,+ ]);+ },+ });},},{diff --git a/apps/builder/app/shared/instance-utils.test.ts b/apps/builder/app/shared/instance-utils.test.tsindex fb2ef91605..d2c8dd7be3 100644--- a/apps/builder/app/shared/instance-utils.test.ts+++ b/apps/builder/app/shared/instance-utils.test.ts@@ -1,6 +1,10 @@import { enableMapSet } from "immer";-import { describe, test, expect } from "@jest/globals";-import type { WsComponentMeta } from "@webstudio-is/react-sdk";+import { describe, test, expect, beforeEach } from "@jest/globals";+import {+ encodeDataSourceVariable,+ portalComponent,+ type WsComponentMeta,+} from "@webstudio-is/react-sdk";import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";import type {Asset,@@ -20,8 +24,18 @@ import {type InsertConstraints,deleteInstance,getInstancesSlice,+ insertInstancesSliceCopy,} from "./instance-utils";import {+ $assets,+ $breakpoints,+ $dataSources,+ $instances,+ $project,+ $props,+ $styleSourceSelections,+ $styleSources,+ $styles,assetsStore,breakpointsStore,dataSourcesStore,@@ -33,6 +47,7 @@ import {stylesStore,} from "./nano-states";import { registerContainers } from "./sync";+import type { Project } from "@webstudio-is/project";enableMapSet();registerContainers();@@ -112,14 +127,14 @@ const createProp = (instanceId: string, id: string, name: string): Prop => ({value: id,});-const createImageAsset = (id: string): Asset => {+const createImageAsset = (id: string, name = "", projectId = ""): Asset => {return {id,type: "image",format: "",- name: "",+ name,description: "",- projectId: "",+ projectId,createdAt: "",size: 0,meta: { width: 0, height: 0 },@@ -951,3 +966,773 @@ describe("get instances slice", () => {]);});});++describe("insert instances slice copy", () => {+ const emptySlice = {+ instances: [+ {+ id: "body",+ type: "instance",+ component: "Body",+ children: [],+ } satisfies Instance,+ ],+ styleSourceSelections: [],+ styleSources: [],+ breakpoints: [],+ styles: [],+ dataSources: [],+ props: [],+ assets: [],+ };++ beforeEach(() => {+ $project.set({ id: "current_project" } as Project);+ $assets.set(new Map());+ $breakpoints.set(new Map());+ $styleSourceSelections.set(new Map());+ $styleSources.set(new Map());+ $styles.set(new Map());+ $instances.set(new Map());+ $props.set(new Map());+ $dataSources.set(new Map());+ });++ test("insert assets with same ids if missing", () => {+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ assets: [createImageAsset("asset1", "name", "another_project")],+ },+ availableDataSources: new Set(),+ });+ expect(Array.from($assets.get().values())).toEqual([+ createImageAsset("asset1", "name", "current_project"),+ ]);++ $assets.set(+ toMap([createImageAsset("asset1", "changed_name", "current_project")])+ );+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ assets: [+ createImageAsset("asset1", "name", "another_project"),+ createImageAsset("asset2", "another_name", "another_project"),+ ],+ },+ availableDataSources: new Set(),+ });+ expect(Array.from($assets.get().values())).toEqual([+ // preserve any user changes+ createImageAsset("asset1", "changed_name", "current_project"),+ // add new assets while preserving old ones+ createImageAsset("asset2", "another_name", "current_project"),+ ]);+ });++ test("merge breakpoints with existing ones", () => {+ $breakpoints.set(+ toMap([+ { id: "existing_base", label: "base" },+ { id: "existing_small", label: "small", minWidth: 768 },+ ])+ );+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ breakpoints: [+ { id: "new_base", label: "Base" },+ {+ id: "new_small",+ label: "Small",+ minWidth: 768,+ },+ {+ id: "new_large",+ label: "Large",+ minWidth: 1200,+ },+ ],+ },+ availableDataSources: new Set(),+ });+ expect(Array.from($breakpoints.get().values())).toEqual([+ { id: "existing_base", label: "base" },+ { id: "existing_small", label: "small", minWidth: 768 },+ { id: "new_large", label: "Large", minWidth: 1200 },+ ]);+ });++ test("insert missing tokens and use merged breakpoint ids", () => {+ $breakpoints.set(toMap([{ id: "base", label: "base" }]));+ $styleSources.set(+ toMap([{ id: "token1", type: "token", name: "oldLabel" }])+ );+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ breakpoints: [{ id: "new_base", label: "Base" }],+ styleSources: [+ { id: "token1", type: "token", name: "newLabel" },+ { id: "token2", type: "token", name: "myToken" },+ ],+ styles: [+ {+ styleSourceId: "token1",+ breakpointId: "new_base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ styleSourceId: "token2",+ breakpointId: "new_base",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ ],+ },+ availableDataSources: new Set(),+ });+ expect(Array.from($styleSources.get().values())).toEqual([+ { id: "token1", type: "token", name: "oldLabel" },+ { id: "token2", type: "token", name: "myToken" },+ ]);+ expect(Array.from($styles.get().values())).toEqual([+ {+ styleSourceId: "token2",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ ]);+ });++ test("insert instances", () => {+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ instances: [+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ },+ availableDataSources: new Set(),+ });+ expect(Array.from($instances.get().keys())).toEqual([+ expect.not.stringMatching("box"),+ ]);+ });++ test("insert instances with portals", () => {+ // portal+ // fragment+ // box+ const instancesWithPortals: Instance[] = [+ {+ type: "instance",+ id: "portal",+ component: portalComponent,+ children: [{ type: "id", value: "fragment" }],+ },+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [{ type: "id", value: "box" }],+ },+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [{ type: "text", value: "First" }],+ },+ ];++ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ instances: instancesWithPortals,+ },+ availableDataSources: new Set(),+ });++ expect(Array.from($instances.get().values())).toEqual([+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [{ type: "id", value: "box" }],+ },+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [{ type: "text", value: "First" }],+ },+ {+ type: "instance",+ id: expect.not.stringMatching("portal"),+ component: portalComponent,+ children: [{ type: "id", value: "fragment" }],+ },+ ]);++ // change portal content and make sure it does not break+ // when stale portal with same id is inserted+ const instancesWithDeletedBoxes = new Map($instances.get());+ instancesWithDeletedBoxes.delete("box");+ instancesWithDeletedBoxes.set("fragment", {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [],+ });+ $instances.set(instancesWithDeletedBoxes);+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ instances: instancesWithPortals,+ },+ availableDataSources: new Set(),+ });++ expect(Array.from($instances.get().values())).toEqual([+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [],+ },+ {+ type: "instance",+ id: expect.not.stringMatching("portal"),+ component: portalComponent,+ children: [{ type: "id", value: "fragment" }],+ },+ {+ type: "instance",+ id: expect.not.stringMatching("portal"),+ component: portalComponent,+ children: [{ type: "id", value: "fragment" }],+ },+ ]);+ });++ test("insert props with new ids", () => {+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ props: [+ {+ id: "prop1",+ instanceId: "body",+ name: "myProp1",+ type: "string",+ value: "",+ },+ ],+ },+ availableDataSources: new Set(),+ });+ expect(Array.from($props.get().values())).toEqual([+ {+ id: expect.not.stringMatching("prop1"),+ instanceId: expect.not.stringMatching("body"),+ name: "myProp1",+ type: "string",+ value: "",+ },+ ]);+ });++ test("insert props from portals with old ids", () => {+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ // portal+ // fragment+ instances: [+ {+ type: "instance",+ id: "portal",+ component: portalComponent,+ children: [{ type: "id", value: "fragment" }],+ },+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [],+ },+ ],+ props: [+ {+ id: "prop1",+ instanceId: "fragment",+ name: "myProp1",+ type: "string",+ value: "",+ },+ ],+ },+ availableDataSources: new Set(),+ });+ expect(Array.from($props.get().values())).toEqual([+ {+ id: "prop1",+ instanceId: "fragment",+ name: "myProp1",+ type: "string",+ value: "",+ },+ ]);+ });++ test("insert data sources with new ids", () => {+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ dataSources: [+ {+ id: "variableId",+ scopeInstanceId: "body",+ type: "variable",+ name: "myVariable",+ value: { type: "string", value: "" },+ },+ ],+ props: [+ {+ id: "expressionId",+ instanceId: "body",+ name: "myProp1",+ type: "expression",+ value: "$ws$dataSource$variableId",+ },+ {+ id: "actionId",+ instanceId: "body",+ name: "myProp2",+ type: "action",+ value: [+ {+ type: "execute",+ args: [],+ code: `$ws$dataSource$variableId = ""`,+ },+ ],+ },+ ],+ },+ availableDataSources: new Set(),+ });+ const [newVariableId] = $dataSources.get().keys();+ expect(newVariableId).not.toEqual("variableId");+ expect(Array.from($dataSources.get().values())).toEqual([+ {+ id: newVariableId,+ scopeInstanceId: expect.not.stringMatching("body"),+ type: "variable",+ name: "myVariable",+ value: { type: "string", value: "" },+ },+ ]);+ expect(Array.from($props.get().values())).toEqual([+ {+ id: expect.not.stringMatching("expressionId"),+ instanceId: expect.not.stringMatching("body"),+ name: "myProp1",+ type: "expression",+ value: encodeDataSourceVariable(newVariableId),+ },+ {+ id: expect.not.stringMatching("actionId"),+ instanceId: expect.not.stringMatching("body"),+ name: "myProp2",+ type: "action",+ value: [+ {+ type: "execute",+ args: [],+ code: `${encodeDataSourceVariable(newVariableId)} = ""`,+ },+ ],+ },+ ]);+ });++ test("inline data sources when not available in scope", () => {+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ dataSources: [+ {+ id: "outsideVariableId",+ scopeInstanceId: "outsideInstanceId",+ type: "variable",+ name: "myOutsideVariable",+ value: { type: "string", value: "outside" },+ },+ {+ id: "insideVariableId",+ scopeInstanceId: "insideInstanceId",+ type: "variable",+ name: "myInsideVariable",+ value: { type: "string", value: "inside" },+ },+ ],+ props: [+ {+ id: "expressionId",+ instanceId: "body",+ name: "myProp1",+ type: "expression",+ value:+ "$ws$dataSource$outsideVariableId + $ws$dataSource$insideVariableId",+ },+ {+ id: "actionId",+ instanceId: "body",+ name: "myProp2",+ type: "action",+ value: [+ {+ type: "execute",+ args: [],+ code: `$ws$dataSource$outsideVariableId = "outside"`,+ },+ {+ type: "execute",+ args: [],+ code: `$ws$dataSource$insideVariableId = "inside"`,+ },+ ],+ },+ ],+ },+ availableDataSources: new Set(["insideVariableId"]),+ });+ expect($dataSources.get()).toEqual(new Map());+ expect(Array.from($props.get().values())).toEqual([+ {+ id: expect.not.stringMatching("expressionId"),+ instanceId: expect.not.stringMatching("body"),+ name: "myProp1",+ type: "expression",+ value: `"outside" + $ws$dataSource$insideVariableId`,+ },+ {+ id: expect.not.stringMatching("actionId"),+ instanceId: expect.not.stringMatching("body"),+ name: "myProp2",+ type: "action",+ value: [+ {+ type: "execute",+ args: [],+ code: `$ws$dataSource$insideVariableId = "inside"`,+ },+ ],+ },+ ]);+ });++ test("insert data sources from portals with old ids", () => {+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ // portal+ // fragment+ instances: [+ {+ type: "instance",+ id: "portal",+ component: portalComponent,+ children: [{ type: "id", value: "fragment" }],+ },+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [{ type: "id", value: "box" }],+ },+ ],+ dataSources: [+ {+ id: "variableId",+ scopeInstanceId: "fragment",+ type: "variable",+ name: "myVariable",+ value: { type: "string", value: "" },+ },+ ],+ props: [+ {+ id: "expressionId",+ instanceId: "fragment",+ name: "myProp1",+ type: "expression",+ value: "$ws$dataSource$variableId",+ },+ {+ id: "actionId",+ instanceId: "fragment",+ name: "myProp2",+ type: "action",+ value: [+ {+ type: "execute",+ args: [],+ code: `$ws$dataSource$variableId = ""`,+ },+ ],+ },+ ],+ },+ availableDataSources: new Set(),+ });+ expect(Array.from($dataSources.get().values())).toEqual([+ {+ id: "variableId",+ scopeInstanceId: "fragment",+ type: "variable",+ name: "myVariable",+ value: { type: "string", value: "" },+ },+ ]);+ expect(Array.from($props.get().values())).toEqual([+ {+ id: "expressionId",+ instanceId: "fragment",+ name: "myProp1",+ type: "expression",+ value: `$ws$dataSource$variableId`,+ },+ {+ id: "actionId",+ instanceId: "fragment",+ name: "myProp2",+ type: "action",+ value: [+ {+ type: "execute",+ args: [],+ code: `$ws$dataSource$variableId = ""`,+ },+ ],+ },+ ]);+ });++ test("inline data sources from portals when not available in scope", () => {+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ // portal+ // fragment+ instances: [+ {+ type: "instance",+ id: "portal",+ component: portalComponent,+ children: [{ type: "id", value: "fragment" }],+ },+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [{ type: "id", value: "box" }],+ },+ ],+ dataSources: [+ {+ id: "outsideVariableId",+ scopeInstanceId: "outsideInstanceId",+ type: "variable",+ name: "myOutsideVariable",+ value: { type: "string", value: "outside" },+ },+ {+ id: "insideVariableId",+ scopeInstanceId: "insideInstanceId",+ type: "variable",+ name: "myInsideVariable",+ value: { type: "string", value: "inside" },+ },+ ],+ props: [+ {+ id: "expressionId",+ instanceId: "fragment",+ name: "myProp1",+ type: "expression",+ value:+ "$ws$dataSource$outsideVariableId + $ws$dataSource$insideVariableId",+ },+ {+ id: "actionId",+ instanceId: "fragment",+ name: "myProp2",+ type: "action",+ value: [+ {+ type: "execute",+ args: [],+ code: `$ws$dataSource$outsideVariableId = "outside"`,+ },+ {+ type: "execute",+ args: [],+ code: `$ws$dataSource$insideVariableId = "inside"`,+ },+ ],+ },+ ],+ },+ availableDataSources: new Set(["insideVariableId"]),+ });+ expect($dataSources.get()).toEqual(new Map());+ expect(Array.from($props.get().values())).toEqual([+ {+ id: "expressionId",+ instanceId: "fragment",+ name: "myProp1",+ type: "expression",+ value: `"outside" + $ws$dataSource$insideVariableId`,+ },+ {+ id: "actionId",+ instanceId: "fragment",+ name: "myProp2",+ type: "action",+ value: [+ {+ type: "execute",+ args: [],+ code: `$ws$dataSource$insideVariableId = "inside"`,+ },+ ],+ },+ ]);+ });++ test("insert local styles with new ids and use merged breakpoint ids", () => {+ $breakpoints.set(toMap([{ id: "base", label: "base" }]));+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ instances: [+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ breakpoints: [{ id: "new_base", label: "Base" }],+ styleSourceSelections: [+ { instanceId: "box", values: ["localId", "tokenId"] },+ { instanceId: "unknown", values: [] },+ ],+ styleSources: [{ id: "localId", type: "local" }],+ styles: [+ {+ styleSourceId: "localId",+ breakpointId: "new_base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ styleSourceId: "tokenId",+ breakpointId: "new_base",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ ],+ },+ availableDataSources: new Set(),+ });+ expect(Array.from($styleSourceSelections.get().values())).toEqual([+ {+ instanceId: expect.not.stringMatching("box"),+ values: [expect.not.stringMatching("localId"), "tokenId"],+ },+ ]);+ expect(Array.from($styleSources.get().values())).toEqual([+ { id: expect.not.stringMatching("localId"), type: "local" },+ ]);+ expect(Array.from($styles.get().values())).toEqual([+ {+ styleSourceId: expect.not.stringMatching("localId"),+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+ });++ test("insert local styles from portal and use merged breakpoint ids", () => {+ $breakpoints.set(toMap([{ id: "base", label: "base" }]));+ insertInstancesSliceCopy({+ slice: {+ ...emptySlice,+ // portal+ // fragment+ instances: [+ {+ type: "instance",+ id: "portal",+ component: portalComponent,+ children: [{ type: "id", value: "fragment" }],+ },+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [{ type: "id", value: "box" }],+ },+ ],+ breakpoints: [{ id: "new_base", label: "Base" }],+ styleSourceSelections: [+ { instanceId: "fragment", values: ["localId", "tokenId"] },+ { instanceId: "unknown", values: [] },+ ],+ styleSources: [{ id: "localId", type: "local" }],+ styles: [+ {+ styleSourceId: "localId",+ breakpointId: "new_base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ styleSourceId: "tokenId",+ breakpointId: "new_base",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ ],+ },+ availableDataSources: new Set(),+ });+ expect(Array.from($styleSourceSelections.get().values())).toEqual([+ { instanceId: "fragment", values: ["localId", "tokenId"] },+ ]);+ expect(Array.from($styleSources.get().values())).toEqual([+ { id: "localId", type: "local" },+ ]);+ expect(Array.from($styles.get().values())).toEqual([+ {+ styleSourceId: "localId",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+ });+});diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex 724487d6ce..4c36817556 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -1,4 +1,6 @@+import { nanoid } from "nanoid";import { toast } from "@webstudio-is/design-system";+import { equalMedia, type StyleValue } from "@webstudio-is/css-engine";import {type Instance,type Instances,@@ -13,6 +15,8 @@ import {DataSources,Props,DataSource,+ Prop,+ Breakpoint,} from "@webstudio-is/sdk";import { findTreeInstanceIdsExcludingSlotDescendants } from "@webstudio-is/sdk";import {@@ -21,6 +25,8 @@ import {type EmbedTemplateData,decodeDataSourceVariable,validateExpression,+ encodeDataSourceVariable,+ portalComponent,} from "@webstudio-is/react-sdk";import {propsStore,@@ -34,6 +40,15 @@ import {registeredComponentMetasStore,dataSourcesStore,assetsStore,+ $instances,+ $assets,+ $project,+ $dataSources,+ $props,+ $breakpoints,+ $styleSources,+ $styles,+ $styleSourceSelections,} from "./nano-states";import {type DroppableTarget,@@ -48,7 +63,6 @@ import { removeByMutable } from "./array-utils";import { isBaseBreakpoint } from "./breakpoints";import { humanizeString } from "./string-utils";import { serverSyncStore } from "./sync";-import type { StyleValue } from "@webstudio-is/css-engine";const getLabelFromComponentName = (component: Instance["component"]) => {if (component.includes(":")) {@@ -533,6 +547,17 @@ const traverseStyleValue = (value satisfies never;};+type InstancesSlice = {+ instances: Instance[];+ styleSourceSelections: StyleSourceSelection[];+ styleSources: StyleSource[];+ breakpoints: Breakpoint[];+ styles: StyleDecl[];+ dataSources: DataSource[];+ props: Prop[];+ assets: Asset[];+};+export const getInstancesSlice = (rootInstanceId: string) => {const assets = assetsStore.get();const instances = instancesStore.get();@@ -687,3 +712,452 @@ export const getInstancesSlice = (rootInstanceId: string) => {assets: slicedAssets,};};++export const findAvailableDataSources = (+ dataSources: DataSources,+ instanceSelector: InstanceSelector+) => {+ const instanceIds = new Set(instanceSelector);+ const availableDataSources = new Set<DataSource["id"]>();+ for (const { id, scopeInstanceId } of dataSources.values()) {+ if (scopeInstanceId && instanceIds.has(scopeInstanceId)) {+ availableDataSources.add(id);+ }+ }+ return availableDataSources;+};++const inlineUnavailableDataSources = ({+ code,+ availableDataSources,+ dataSources,+}: {+ code: string;+ availableDataSources: Set<DataSource["id"]>;+ dataSources: DataSources;+}) => {+ let isDiscarded = false;+ const newCode = validateExpression(code, {+ effectful: true,+ transformIdentifier: (identifier, assignee) => {+ const dataSourceId = decodeDataSourceVariable(identifier);+ if (+ dataSourceId === undefined ||+ availableDataSources.has(dataSourceId)+ ) {+ return identifier;+ }+ // left operand of assign operator cannot be inlined+ if (assignee) {+ isDiscarded = true;+ }+ const dataSource = dataSources.get(dataSourceId);+ // inline variable not scoped to portal content instances+ if (dataSource?.type === "variable") {+ return JSON.stringify(dataSource.value.value);+ }+ dataSource?.type satisfies undefined;+ return identifier;+ },+ });+ return { code: newCode, isDiscarded };+};++const replaceDataSources = (+ code: string,+ replacements: Map<DataSource["id"], DataSource["id"]>+) => {+ return validateExpression(code, {+ effectful: true,+ transformIdentifier: (identifier) => {+ const dataSourceId = decodeDataSourceVariable(identifier);+ if (dataSourceId === undefined) {+ return identifier;+ }+ return encodeDataSourceVariable(+ replacements.get(dataSourceId) ?? dataSourceId+ );+ },+ });+};++export const insertInstancesSliceCopy = ({+ slice,+ availableDataSources,+ beforeTransactionEnd,+}: {+ slice: InstancesSlice;+ availableDataSources: Set<DataSource["id"]>;+ beforeTransactionEnd?: (+ rootInstanceI: Instance["id"],+ draft: { instances: Instances }+ ) => void;+}) => {+ const projectId = $project.get()?.id;+ if (projectId === undefined) {+ return;+ }++ const sliceInstances: Instances = new Map();+ const portalContentIds = new Set<Instance["id"]>();+ for (const instance of slice.instances) {+ sliceInstances.set(instance.id, instance);+ if (instance.component === portalComponent) {+ for (const child of instance.children) {+ if (child.type === "id") {+ portalContentIds.add(child.value);+ }+ }+ }+ }++ const sliceDataSources: DataSources = new Map();+ for (const dataSource of slice.dataSources) {+ sliceDataSources.set(dataSource.id, dataSource);+ }++ serverSyncStore.createTransaction(+ [+ $assets,+ $instances,+ $dataSources,+ $props,+ $breakpoints,+ $styleSources,+ $styles,+ $styleSourceSelections,+ ],+ (+ assets,+ instances,+ dataSources,+ props,+ breakpoints,+ styleSources,+ styles,+ styleSourceSelections+ ) => {+ /**+ * insert reusables without changing their ids to not bloat data+ * and catch up with user changes+ * - assets+ * - breakpoints+ * - token styles+ * - portals+ *+ * breakpoints behave slightly differently and merged with existing ones+ * and those ids are used instead+ */++ // insert assets++ for (const asset of slice.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 });+ }+ }++ // merge breakpoints++ const mergedBreakpointIds = new Map<Breakpoint["id"], Breakpoint["id"]>();+ for (const newBreakpoint of slice.breakpoints) {+ 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);+ }+ }++ // insert tokens with their styles++ const tokenStyleSourceIds = new Set<StyleSource["id"]>();+ for (const styleSource of slice.styleSources) {+ // prevent inserting styles when token is already present+ if (styleSource.type === "local" || styleSources.has(styleSource.id)) {+ continue;+ }+ styleSource.type satisfies "token";+ tokenStyleSourceIds.add(styleSource.id);+ styleSources.set(styleSource.id, styleSource);+ }+ for (const styleDecl of slice.styles) {+ if (tokenStyleSourceIds.has(styleDecl.styleSourceId)) {+ const { breakpointId } = styleDecl;+ const newStyleDecl: StyleDecl = {+ ...styleDecl,+ breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,+ };+ styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);+ }+ }++ // insert portal contents+ // - instances+ // - data sources+ // - props+ // - local styles+ for (const rootInstanceId of portalContentIds) {+ // prevent reinserting portals which could be already changed by user+ if (instances.has(rootInstanceId)) {+ continue;+ }++ const instanceIds = findTreeInstanceIdsExcludingSlotDescendants(+ sliceInstances,+ rootInstanceId+ );+ for (const instance of slice.instances) {+ if (instanceIds.has(instance.id)) {+ instances.set(instance.id, instance);+ }+ }++ const availablePortalDataSources = new Set(availableDataSources);+ for (const dataSource of slice.dataSources) {+ // insert only data sources within portal content+ if (+ dataSource.scopeInstanceId &&+ instanceIds.has(dataSource.scopeInstanceId)+ ) {+ availablePortalDataSources.add(dataSource.id);+ dataSources.set(dataSource.id, dataSource);+ }+ }++ for (let prop of slice.props) {+ if (instanceIds.has(prop.instanceId) === false) {+ continue;+ }+ // inline data sources not available in scope into expressions+ if (prop.type === "expression") {+ const { code } = inlineUnavailableDataSources({+ code: prop.value,+ availableDataSources: availablePortalDataSources,+ dataSources: sliceDataSources,+ });+ prop = { ...prop, value: code };+ }+ if (prop.type === "action") {+ prop = {+ ...prop,+ value: prop.value.flatMap((value) => {+ if (value.type !== "execute") {+ return [value];+ }+ const { code, isDiscarded } = inlineUnavailableDataSources({+ code: value.code,+ availableDataSources: availablePortalDataSources,+ dataSources: sliceDataSources,+ });+ if (isDiscarded) {+ return [];+ }+ return [{ ...value, code }];+ }),+ };+ }+ props.set(prop.id, prop);+ }++ // insert local style sources with their styles++ const instanceStyleSourceIds = new Set<StyleSource["id"]>();+ for (const styleSourceSelection of slice.styleSourceSelections) {+ const { instanceId } = styleSourceSelection;+ if (instanceIds.has(instanceId) === false) {+ continue;+ }+ styleSourceSelections.set(instanceId, styleSourceSelection);+ for (const styleSourceId of styleSourceSelection.values) {+ instanceStyleSourceIds.add(styleSourceId);+ }+ }+ const localStyleSourceIds = new Set<StyleSource["id"]>();+ for (const styleSource of slice.styleSources) {+ if (+ styleSource.type === "local" &&+ instanceStyleSourceIds.has(styleSource.id)+ ) {+ localStyleSourceIds.add(styleSource.id);+ styleSources.set(styleSource.id, styleSource);+ }+ }+ for (const styleDecl of slice.styles) {+ if (localStyleSourceIds.has(styleDecl.styleSourceId)) {+ const { breakpointId } = styleDecl;+ const newStyleDecl: StyleDecl = {+ ...styleDecl,+ breakpointId:+ mergedBreakpointIds.get(breakpointId) ?? breakpointId,+ };+ styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);+ }+ }+ }++ /**+ * inserting unique content is structurally similar to inserting portal content+ * but all ids are regenerated to support duplicating existing content+ * - instances+ * - data sources+ * - props+ * - local styles+ */++ // generate new ids only instances outside of portals+ const sliceInstanceIds = findTreeInstanceIdsExcludingSlotDescendants(+ sliceInstances,+ slice.instances[0].id+ );+ const newInstanceIds = new Map<Instance["id"], Instance["id"]>();+ for (const instanceId of sliceInstanceIds) {+ newInstanceIds.set(instanceId, nanoid());+ }+ for (const instance of slice.instances) {+ if (sliceInstanceIds.has(instance.id)) {+ const newId = newInstanceIds.get(instance.id) ?? instance.id;+ instances.set(newId, {+ ...instance,+ id: newId,+ children: instance.children.map((child) => {+ if (child.type === "id") {+ return {+ type: "id",+ value: newInstanceIds.get(child.value) ?? child.value,+ };+ }+ return child;+ }),+ });+ }+ }++ const availablePortalDataSources = new Set(availableDataSources);+ const newDataSourceIds = new Map<DataSource["id"], DataSource["id"]>();+ for (const dataSource of slice.dataSources) {+ const { scopeInstanceId } = dataSource;+ // insert only data sources within portal content+ if (scopeInstanceId && sliceInstanceIds.has(scopeInstanceId)) {+ availablePortalDataSources.add(dataSource.id);+ const newId = nanoid();+ newDataSourceIds.set(dataSource.id, newId);+ dataSources.set(newId, {+ ...dataSource,+ id: newId,+ scopeInstanceId: newInstanceIds.get(scopeInstanceId),+ });+ }+ }++ for (let prop of slice.props) {+ if (sliceInstanceIds.has(prop.instanceId) === false) {+ continue;+ }+ // inline data sources not available in scope into expressions+ if (prop.type === "expression") {+ const { code } = inlineUnavailableDataSources({+ code: prop.value,+ availableDataSources: availablePortalDataSources,+ dataSources: sliceDataSources,+ });+ prop = { ...prop, value: replaceDataSources(code, newDataSourceIds) };+ }+ if (prop.type === "action") {+ prop = {+ ...prop,+ value: prop.value.flatMap((value) => {+ if (value.type !== "execute") {+ return [value];+ }+ const { code, isDiscarded } = inlineUnavailableDataSources({+ code: value.code,+ availableDataSources: availablePortalDataSources,+ dataSources: sliceDataSources,+ });+ if (isDiscarded) {+ return [];+ }+ return [+ { ...value, code: replaceDataSources(code, newDataSourceIds) },+ ];+ }),+ };+ }+ const newId = nanoid();+ props.set(newId, {+ ...prop,+ id: newId,+ instanceId: newInstanceIds.get(prop.instanceId) ?? prop.instanceId,+ });+ }++ // insert local styles with new ids++ const instanceStyleSourceIds = new Set<StyleSource["id"]>();+ for (const styleSourceSelection of slice.styleSourceSelections) {+ if (sliceInstanceIds.has(styleSourceSelection.instanceId) === false) {+ continue;+ }+ for (const styleSourceId of styleSourceSelection.values) {+ instanceStyleSourceIds.add(styleSourceId);+ }+ }+ const newLocalStyleSourceIds = new Map<+ StyleSource["id"],+ StyleSource["id"]+ >();+ for (const styleSource of slice.styleSources) {+ if (+ styleSource.type === "local" &&+ instanceStyleSourceIds.has(styleSource.id)+ ) {+ const newId = nanoid();+ newLocalStyleSourceIds.set(styleSource.id, newId);+ styleSources.set(newId, { ...styleSource, id: newId });+ }+ }+ for (const styleSourceSelection of slice.styleSourceSelections) {+ const { instanceId, values } = styleSourceSelection;+ if (sliceInstanceIds.has(instanceId) === false) {+ continue;+ }+ const newInstanceId = newInstanceIds.get(instanceId) ?? instanceId;+ styleSourceSelections.set(newInstanceId, {+ instanceId: newInstanceId,+ values: values.map(+ (styleSourceId) =>+ newLocalStyleSourceIds.get(styleSourceId) ?? styleSourceId+ ),+ });+ for (const styleSourceId of styleSourceSelection.values) {+ instanceStyleSourceIds.add(styleSourceId);+ }+ }+ for (const styleDecl of slice.styles) {+ const { breakpointId, styleSourceId } = styleDecl;+ if (newLocalStyleSourceIds.has(styleDecl.styleSourceId)) {+ const newStyleDecl: StyleDecl = {+ ...styleDecl,+ styleSourceId:+ newLocalStyleSourceIds.get(styleSourceId) ?? styleSourceId,+ breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,+ };+ styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);+ }+ }++ // invoke callback to allow additional changes within same transaction+ const rootInstanceId =+ newInstanceIds.get(slice.instances[0].id) ?? slice.instances[0].id;+ beforeTransactionEnd?.(rootInstanceId, { instances });+ }+ );+};diff --git a/apps/builder/app/shared/nano-states/breakpoints.ts b/apps/builder/app/shared/nano-states/breakpoints.tsindex a59f7f5496..a25180002e 100644--- a/apps/builder/app/shared/nano-states/breakpoints.ts+++ b/apps/builder/app/shared/nano-states/breakpoints.ts@@ -3,6 +3,7 @@ import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";import { isBaseBreakpoint } from "../breakpoints";export const breakpointsStore = atom<Breakpoints>(new Map());+export const $breakpoints = breakpointsStore;export const selectedBreakpointIdStore = atom<undefined | Breakpoint["id"]>(undefineddiff --git a/apps/builder/app/shared/nano-states/nano-states.ts b/apps/builder/app/shared/nano-states/nano-states.tsindex 4e166192ba..aba127a5f3 100644--- a/apps/builder/app/shared/nano-states/nano-states.ts+++ b/apps/builder/app/shared/nano-states/nano-states.ts@@ -28,6 +28,7 @@ import type { UnitSizes } from "~/builder/features/style-panel/shared/css-value-import type { Project } from "@webstudio-is/project";export const projectStore = atom<Project | undefined>();+export const $project = projectStore;export const $domains = atom<string[]>([]);@@ -83,10 +84,12 @@ export const useInstanceStyles = (instanceId: undefined | Instance["id"]) => {};export const styleSourcesStore = atom<StyleSources>(new Map());+export const $styleSources = styleSourcesStore;export const styleSourceSelectionsStore = atom<StyleSourceSelections>(new Map());+export const $styleSourceSelections = styleSourceSelectionsStore;export type StyleSourceSelector = {styleSourceId: StyleSource["id"];diff --git a/packages/react-sdk/src/core-components.ts b/packages/react-sdk/src/core-components.tsindex b33e44bec8..b1e00b33a0 100644--- a/packages/react-sdk/src/core-components.ts+++ b/packages/react-sdk/src/core-components.ts@@ -1 +1,3 @@+export const portalComponent = "Slot";+export const collectionComponent = "ws:component";