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
feat: Keyboard shorthands for instance positioning and slot bug fixes (#5821)
Oleg Isonenac29cf7d1d41
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex 8657d23b29..25557354cb 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -58,7 +58,7 @@ import { CloneProjectDialog } from "~/shared/clone-project";import type { TokenPermissions } from "@webstudio-is/authorization-token";import { useToastErrors } from "~/shared/error/toast-error";import { initBuilderApi } from "~/shared/builder-api";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import { migrateWebstudioDataMutable } from "@webstudio-is/project-migrations";import { Loading, LoadingBackground } from "./shared/loading";import { mergeRefs } from "@react-aria/utils";diff --git a/apps/builder/app/builder/features/command-panel/groups/components-group.tsx b/apps/builder/app/builder/features/command-panel/groups/components-group.tsxindex 1a1e16b554..f2fa1d94bf 100644--- a/apps/builder/app/builder/features/command-panel/groups/components-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/components-group.tsx@@ -1,3 +1,5 @@+import { insertWebstudioElementAt } from "~/shared/instance-utils/insert";+import { insertWebstudioFragmentAt } from "~/shared/instance-utils/insert";import {CommandGroup,CommandGroupHeading,@@ -13,11 +15,7 @@ import {$registeredComponentMetas,$registeredTemplates,} from "~/shared/nano-states";-import {- getComponentTemplateData,- insertWebstudioElementAt,- insertWebstudioFragmentAt,-} from "~/shared/instance-utils";+import { getComponentTemplateData } from "~/shared/instance-utils/insert";import { humanizeString } from "~/shared/string-utils";import { $selectedPage } from "~/shared/nano-states";import {diff --git a/apps/builder/app/builder/features/command-panel/groups/convert-group.tsx b/apps/builder/app/builder/features/command-panel/groups/convert-group.tsxindex 3d5f74bc1e..db55d6fd5d 100644--- a/apps/builder/app/builder/features/command-panel/groups/convert-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/convert-group.tsx@@ -21,7 +21,7 @@ import {getInstanceLabel,InstanceIcon,} from "~/builder/shared/instance-label";-import { canConvertInstance } from "~/shared/instance-utils";+import { canConvertInstance } from "~/shared/instance-utils/mutation";import {$commandContent,$isCommandPanelOpen,@@ -30,7 +30,7 @@ import {} from "../command-state";import { allowsHtmlMutations } from "../shared/document-utils";import { useState } from "react";-import { convertInstance } from "~/shared/instance-utils";+import { convertInstance } from "~/shared/instance-utils/mutation";type ConvertOption = {component: string;diff --git a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsxindex 8e6b07ef14..e9fb82ef70 100644--- a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx@@ -18,7 +18,7 @@ import {} from "../command-state";import { InstanceList, showInstance } from "../shared/instance-list";import { deleteVariableMutable } from "~/shared/data-variables";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import {DeleteDataVariableDialog,RenameDataVariableDialog,diff --git a/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx b/apps/builder/app/builder/features/command-panel/groups/instances-group.tsxindex b84bc44fe4..94bf7ca2c1 100644--- a/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx@@ -15,7 +15,7 @@ import {$selectedPageId,$selectedInstanceSelector,} from "~/shared/nano-states";-import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils";+import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils/lookup";import { closeCommandPanel, $isCommandPanelOpen } from "../command-state";import type { BaseOption } from "../shared/types";import { setActiveSidebarPanel } from "~/builder/shared/nano-states";diff --git a/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx b/apps/builder/app/builder/features/command-panel/groups/tags-group.tsxindex b5350b4a75..f06e049dd7 100644--- a/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx@@ -12,7 +12,7 @@ import type { Instance } from "@webstudio-is/sdk";import { $registeredComponentMetas } from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";import { $props } from "~/shared/sync/data-stores";-import { insertWebstudioFragmentAt } from "~/shared/instance-utils";+import { insertWebstudioFragmentAt } from "~/shared/instance-utils/insert";import { $selectedInstancePath, $selectedPage } from "~/shared/nano-states";import { InstanceIcon } from "~/builder/shared/instance-label";import { isTreeSatisfyingContentModel } from "~/shared/content-model";diff --git a/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx b/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsxindex d846492c7d..9b0011cd60 100644--- a/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx@@ -35,7 +35,7 @@ import {openCommandPanel,} from "../command-state";import { useState } from "react";-import { wrapInstance } from "~/shared/instance-utils";+import { wrapInstance } from "~/shared/instance-utils/mutation";import { allowsHtmlMutations } from "../shared/document-utils";type WrapOption = {diff --git a/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx b/apps/builder/app/builder/features/command-panel/shared/instance-list.tsxindex 8a81d93f09..609ba9b962 100644--- a/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx+++ b/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx@@ -16,9 +16,9 @@ import {import { getPageById, type Instance } from "@webstudio-is/sdk";import { $instances, $pages } from "~/shared/sync/data-stores";import { getInstanceLabel } from "~/builder/shared/instance-label";-import { buildInstancePath } from "~/shared/instance-utils";+import { buildInstancePath } from "~/shared/instance-utils/lookup";import { $commandContent } from "~/builder/features/command-panel/command-state";-import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils";+import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils/lookup";import { $activeInspectorPanel } from "~/builder/shared/nano-states";import {$selectedPageId,diff --git a/apps/builder/app/builder/features/command-panel/shared/instance-path-footer.tsx b/apps/builder/app/builder/features/command-panel/shared/instance-path-footer.tsxindex 285f9e5504..54e9deeff5 100644--- a/apps/builder/app/builder/features/command-panel/shared/instance-path-footer.tsx+++ b/apps/builder/app/builder/features/command-panel/shared/instance-path-footer.tsx@@ -3,7 +3,7 @@ import { useStore } from "@nanostores/react";import { Flex, Text } from "@webstudio-is/design-system";import type { Instance } from "@webstudio-is/sdk";import { $instances, $pages } from "~/shared/sync/data-stores";-import { buildInstancePath } from "~/shared/instance-utils";+import { buildInstancePath } from "~/shared/instance-utils/lookup";type InstancePathFooterProps = {instanceId: Instance["id"];diff --git a/apps/builder/app/builder/features/components/components.tsx b/apps/builder/app/builder/features/components/components.tsxindex 3d949e545e..3c836c6311 100644--- a/apps/builder/app/builder/features/components/components.tsx+++ b/apps/builder/app/builder/features/components/components.tsx@@ -1,3 +1,5 @@+import { insertWebstudioElementAt } from "~/shared/instance-utils/insert";+import { insertWebstudioFragmentAt } from "~/shared/instance-utils/insert";import { useState } from "react";import { matchSorter } from "match-sorter";import { computed } from "nanostores";@@ -31,11 +33,7 @@ import {$registeredComponentMetas,$registeredTemplates,} from "~/shared/nano-states";-import {- getComponentTemplateData,- insertWebstudioElementAt,- insertWebstudioFragmentAt,-} from "~/shared/instance-utils";+import { getComponentTemplateData } from "~/shared/instance-utils/insert";import type { Publish } from "~/shared/pubsub";import { $selectedPage } from "~/shared/nano-states";import { mapGroupBy } from "~/shared/shim";diff --git a/apps/builder/app/builder/features/marketplace/templates.tsx b/apps/builder/app/builder/features/marketplace/templates.tsxindex e2f6489957..05cbbdfa27 100644--- a/apps/builder/app/builder/features/marketplace/templates.tsx+++ b/apps/builder/app/builder/features/marketplace/templates.tsx@@ -1,3 +1,10 @@+import { findClosestInsertable } from "~/shared/instance-utils/insert";+import { insertWebstudioFragmentAt } from "~/shared/instance-utils/insert";+import {+ detectFragmentTokenConflicts,+ detectPageTokenConflicts,+} from "~/shared/instance-utils/fragment";+import { updateWebstudioData } from "~/shared/instance-utils/data";import { useMemo } from "react";import {Button,@@ -24,14 +31,7 @@ import type { MarketplaceProduct } from "@webstudio-is/project-build";import { mapGroupBy } from "~/shared/shim";import { CollapsibleSection } from "~/builder/shared/collapsible-section";import { builderUrl } from "~/shared/router-utils";-import {- extractWebstudioFragment,- findClosestInsertable,- detectFragmentTokenConflicts,- detectPageTokenConflicts,- insertWebstudioFragmentAt,- updateWebstudioData,-} from "~/shared/instance-utils";+import { extractWebstudioFragment } from "~/shared/instance-utils/fragment";import { builderApi } from "~/shared/builder-api";import { insertPageCopyMutable } from "~/shared/page-utils";import { Card } from "./card";diff --git a/apps/builder/app/builder/features/navigator/navigator-tree.tsx b/apps/builder/app/builder/features/navigator/navigator-tree.tsxindex e18232edbf..bed90881e7 100644--- a/apps/builder/app/builder/features/navigator/navigator-tree.tsx+++ b/apps/builder/app/builder/features/navigator/navigator-tree.tsx@@ -1,3 +1,8 @@+import {+ reparentInstance,+ setInstanceLabelMutable,+ toggleInstanceShow,+} from "~/shared/instance-utils/mutation";import { useEffect, useRef } from "react";import { atom, computed } from "nanostores";import { mergeRefs } from "@react-aria/utils";@@ -49,9 +54,11 @@ import {$propValuesByInstanceSelectorWithMemoryProps,} from "~/shared/nano-states";import { $instances, $props } from "~/shared/sync/data-stores";-import { isDescendantOrSelf, type InstanceSelector } from "~/shared/tree-utils";+import {+ isDescendantOrSelf,+ type InstanceSelector,+} from "~/shared/instance-utils/tree";import { serverSyncStore } from "~/shared/sync/sync-stores";-import { reparentInstance, toggleInstanceShow } from "~/shared/instance-utils";import { emitCommand } from "~/builder/shared/commands";import { useContentEditable } from "~/shared/dom-hooks";import {@@ -407,10 +414,7 @@ const TreeNodeContent = ({onChangeValue: (value: string) => {const instanceId = instance.id;serverSyncStore.createTransaction([$instances], (instances) => {- const instance = instances.get(instanceId);- if (instance) {- instance.label = value;- }+ setInstanceLabelMutable(instances, instanceId, value);});editableRef.current?.closest("button")?.focus();},diff --git a/apps/builder/app/builder/features/pages/page-utils.test.ts b/apps/builder/app/builder/features/pages/page-utils.test.tsindex d10deb495c..8754bd04af 100644--- a/apps/builder/app/builder/features/pages/page-utils.test.ts+++ b/apps/builder/app/builder/features/pages/page-utils.test.ts@@ -9,6 +9,7 @@ import {ROOT_FOLDER_ID,ROOT_INSTANCE_ID,type DataSource,+ type Instance,type Page,SYSTEM_VARIABLE_ID,Resource,@@ -26,6 +27,7 @@ import {isPathAvailable,reparentPageOrFolderMutable,deletePageMutable,+ deleteTemplateMutable,instantiateTemplate,} from "./page-utils";import { $dataSourceVariables } from "~/shared/nano-states";@@ -46,6 +48,7 @@ import { registerContainers } from "~/shared/sync/sync-stores";import { $selectedPageId } from "~/shared/nano-states";import { updateCurrentSystem } from "~/shared/system";import { $resourcesCache, getResourceKey } from "~/shared/resources";+import { expectSlotTreeIntegrity } from "~/shared/slot-test-utils";setEnv("*");registerContainers();@@ -121,6 +124,26 @@ const createPages = () => {const toMap = <T extends { id: string }>(list: T[]) =>new Map(list.map((item) => [item.id, item]));+const createWebstudioData = ({+ pages,+ instances = new Map(),+}: {+ pages: Pages;+ instances?: Map<Instance["id"], Instance>;+}) =>+ ({+ pages,+ instances,+ styleSources: new Map(),+ styleSourceSelections: new Map(),+ breakpoints: new Map(),+ styles: new Map(),+ props: new Map(),+ dataSources: new Map(),+ resources: new Map(),+ assets: new Map(),+ }) as unknown as WebstudioData;+describe("reparentOrphansMutable", () => {// We must deal with the fact there can be an orphaned folder or page in a collaborative mode,// because user A can add a page to a folder while user B deletes the folder without receiving the create page yet.@@ -827,6 +850,94 @@ describe("deletePageMutable", () => {expect(data.instances.has(rootInstanceId!)).toBe(false);});+ test("deletes page slot occurrence without deleting shared slot content used by another page", async () => {+ const { pages: pagesData, register, p } = createPages();+ const page1 = p("page1", "/page1");+ const page2 = {+ ...p("page2", "/page2"),+ rootInstanceId: "page2RootId",+ };+ register([page1, page2]);++ const data = createWebstudioData({+ pages: pagesData,+ instances: new Map([+ [+ "rootInstanceId",+ {+ id: "rootInstanceId",+ type: "instance",+ component: "Body",+ children: [{ type: "id", value: "slot1" }],+ },+ ],+ [+ "page2RootId",+ {+ id: "page2RootId",+ type: "instance",+ component: "Body",+ children: [{ type: "id", value: "slot2" }],+ },+ ],+ [+ "slot1",+ {+ id: "slot1",+ type: "instance",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "slot2",+ {+ id: "slot2",+ type: "instance",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "fragment",+ {+ id: "fragment",+ type: "instance",+ component: "Fragment",+ children: [{ type: "id", value: "sharedBox" }],+ },+ ],+ [+ "sharedBox",+ {+ id: "sharedBox",+ type: "instance",+ component: "Box",+ children: [],+ },+ ],+ ]),+ });++ deletePageMutable("page1", data);++ expect(data.instances.has("rootInstanceId")).toBe(false);+ expect(data.instances.has("slot1")).toBe(false);+ expect(data.instances.get("page2RootId")?.children).toEqual([+ { type: "id", value: "slot2" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "sharedBox" },+ ]);+ expect(data.instances.get("sharedBox")).toMatchObject({+ component: "Box",+ });+ expectSlotTreeIntegrity(data.instances);+ });+test("should remove page from folder children", async () => {const { pages: pagesData, register, p, f } = createPages();register([f("folder1", [p("page1", "/page1")])]);@@ -1257,6 +1368,103 @@ describe("duplicateTemplate", () => {});});+describe("deleteTemplateMutable", () => {+ test("deletes template slot occurrence without deleting shared slot content used by a page", () => {+ const { pages: pagesData } = createPages();+ pagesData.pageTemplates = new Map([+ [+ "templateId",+ {+ id: "templateId",+ name: "Template",+ title: `"Template"`,+ rootInstanceId: "templateRootId",+ meta: {},+ },+ ],+ ]);++ const data = createWebstudioData({+ pages: pagesData,+ instances: new Map([+ [+ "rootInstanceId",+ {+ id: "rootInstanceId",+ type: "instance",+ component: "Body",+ children: [{ type: "id", value: "slot1" }],+ },+ ],+ [+ "templateRootId",+ {+ id: "templateRootId",+ type: "instance",+ component: "Body",+ children: [{ type: "id", value: "slot2" }],+ },+ ],+ [+ "slot1",+ {+ id: "slot1",+ type: "instance",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "slot2",+ {+ id: "slot2",+ type: "instance",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "fragment",+ {+ id: "fragment",+ type: "instance",+ component: "Fragment",+ children: [{ type: "id", value: "sharedBox" }],+ },+ ],+ [+ "sharedBox",+ {+ id: "sharedBox",+ type: "instance",+ component: "Box",+ children: [],+ },+ ],+ ]),+ });++ deleteTemplateMutable("templateId", data);++ expect(pagesData.pageTemplates?.has("templateId")).toBe(false);+ expect(data.instances.has("templateRootId")).toBe(false);+ expect(data.instances.has("slot2")).toBe(false);+ expect(data.instances.get("rootInstanceId")?.children).toEqual([+ { type: "id", value: "slot1" },+ ]);+ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "sharedBox" },+ ]);+ expect(data.instances.get("sharedBox")).toMatchObject({+ component: "Box",+ });+ expectSlotTreeIntegrity(data.instances);+ });+});+describe("instantiateTemplate", () => {$project.set({ id: "projectId" } as Project);diff --git a/apps/builder/app/builder/features/pages/page-utils.ts b/apps/builder/app/builder/features/pages/page-utils.tsindex bb7a2aee41..9b60fee855 100644--- a/apps/builder/app/builder/features/pages/page-utils.ts+++ b/apps/builder/app/builder/features/pages/page-utils.ts@@ -1,3 +1,4 @@+import { updateWebstudioData } from "~/shared/instance-utils/data";import { computed } from "nanostores";import slugify from "slugify";import {@@ -17,10 +18,7 @@ import {systemParameter,SYSTEM_VARIABLE_ID,} from "@webstudio-is/sdk";-import {- deleteInstanceMutable,- updateWebstudioData,-} from "~/shared/instance-utils";+import { deleteInstanceMutable } from "~/shared/instance-utils/mutation";import { $variableValuesByInstanceSelector } from "~/shared/nano-states";import { $dataSources, $pages } from "~/shared/sync/data-stores";import {diff --git a/apps/builder/app/builder/features/pages/pages.tsx b/apps/builder/app/builder/features/pages/pages.tsxindex 58f1f17a90..6b78586cd0 100644--- a/apps/builder/app/builder/features/pages/pages.tsx+++ b/apps/builder/app/builder/features/pages/pages.tsx@@ -84,7 +84,7 @@ import {} from "@webstudio-is/sdk";import { atom, computed } from "nanostores";import { isPathnamePattern } from "~/builder/shared/url-pattern";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import { $selectedPage } from "~/shared/nano-states";import { selectPage } from "~/shared/nano-states";diff --git a/apps/builder/app/builder/features/publish/restricted-features.ts b/apps/builder/app/builder/features/publish/restricted-features.tsindex 516c35d9b5..a5bb56d45c 100644--- a/apps/builder/app/builder/features/publish/restricted-features.ts+++ b/apps/builder/app/builder/features/publish/restricted-features.ts@@ -6,7 +6,7 @@ import {type Instance,type Pages,} from "@webstudio-is/sdk";-import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils";+import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils/lookup";export type RestrictedFeature =| undefineddiff --git a/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx b/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsxindex c8b48e0c0e..5ac840c150 100644--- a/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/resource-control.tsx@@ -30,7 +30,7 @@ import { $variableValuesByInstanceSelector } from "~/shared/nano-states";import { $dataSources } from "~/shared/sync/data-stores";import { $props, $resources } from "~/shared/sync/data-stores";import { computeExpression } from "~/shared/data-variables";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import {$selectedInstance,$selectedInstanceKeyWithRoot,diff --git a/apps/builder/app/builder/features/settings-panel/controls/tag-control.tsx b/apps/builder/app/builder/features/settings-panel/controls/tag-control.tsxindex 5bcace0b6c..c3796dfe29 100644--- a/apps/builder/app/builder/features/settings-panel/controls/tag-control.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/tag-control.tsx@@ -5,7 +5,7 @@ import { Box, Combobox, Select, theme } from "@webstudio-is/design-system";import { elementsByTag } from "@webstudio-is/html-data";import { tags } from "@webstudio-is/sdk";import { $selectedInstance, $selectedInstancePath } from "~/shared/nano-states";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import { isTreeSatisfyingContentModel } from "~/shared/content-model";import { $registeredComponentMetas } from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";diff --git a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsxindex 8a52e82613..0b41719636 100644--- a/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx+++ b/apps/builder/app/builder/features/settings-panel/controls/text-content.tsx@@ -19,7 +19,7 @@ import {validatePrimitiveValue,} from "~/builder/shared/binding-popover";import { useDraftValue } from "~/builder/shared/use-draft-value";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import { CodeEditor } from "~/shared/code-editor";import {type ControlProps,diff --git a/apps/builder/app/builder/features/settings-panel/property-label.tsx b/apps/builder/app/builder/features/settings-panel/property-label.tsxindex 8a5b9dda9e..80755b277d 100644--- a/apps/builder/app/builder/features/settings-panel/property-label.tsx+++ b/apps/builder/app/builder/features/settings-panel/property-label.tsx@@ -15,7 +15,7 @@ import {import { AlertIcon } from "@webstudio-is/icons";import type { Prop } from "@webstudio-is/sdk";import { showAttribute } from "@webstudio-is/react-sdk";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import {$authPermit,$isContentMode,diff --git a/apps/builder/app/builder/features/settings-panel/props-section/animation/subject-select.tsx b/apps/builder/app/builder/features/settings-panel/props-section/animation/subject-select.tsxindex 98d4af6845..117befe407 100644--- a/apps/builder/app/builder/features/settings-panel/props-section/animation/subject-select.tsx+++ b/apps/builder/app/builder/features/settings-panel/props-section/animation/subject-select.tsx@@ -8,7 +8,7 @@ import {import { $selectedInstanceSelector } from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";import { getInstanceStyleDecl } from "~/builder/features/style-panel/shared/model";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import { toValue } from "@webstudio-is/css-engine";import type { AnimationAction } from "@webstudio-is/sdk";import { setListedCssProperty } from "./set-css-property";diff --git a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx b/apps/builder/app/builder/features/settings-panel/resource-panel.tsxindex 20768a6998..092ace9292 100644--- a/apps/builder/app/builder/features/settings-panel/resource-panel.tsx+++ b/apps/builder/app/builder/features/settings-panel/resource-panel.tsx@@ -69,7 +69,7 @@ import {getInstanceKey,type InstancePath,} from "~/shared/nano-states";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import { rebindTreeVariablesMutable } from "~/shared/data-variables";import { parseCurl, type CurlRequest } from "./curl";diff --git a/apps/builder/app/builder/features/settings-panel/settings-section.tsx b/apps/builder/app/builder/features/settings-panel/settings-section.tsxindex 295ea86648..7c97c1658e 100644--- a/apps/builder/app/builder/features/settings-panel/settings-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/settings-section.tsx@@ -8,13 +8,11 @@ import { HorizontalLayout, Label, Row } from "./shared";import { serverSyncStore } from "~/shared/sync/sync-stores";import { $selectedInstance } from "~/shared/nano-states";import { getInstanceLabel } from "~/builder/shared/instance-label";+import { setInstanceLabelMutable } from "~/shared/instance-utils/mutation";const saveLabel = (label: string, selectedInstance: Instance) => {serverSyncStore.createTransaction([$instances], (instances) => {- const instance = instances.get(selectedInstance.id);- if (instance !== undefined) {- instance.label = label.trim();- }+ setInstanceLabelMutable(instances, selectedInstance.id, label.trim());});};diff --git a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx b/apps/builder/app/builder/features/settings-panel/variable-popover.tsxindex 4709542ad9..f5c57a2e42 100644--- a/apps/builder/app/builder/features/settings-panel/variable-popover.tsx+++ b/apps/builder/app/builder/features/settings-panel/variable-popover.tsx@@ -70,7 +70,7 @@ import {EditorDialogControl,foldGutterExtension,} from "~/shared/code-editor-base";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import {findUnsetVariableNames,rebindTreeVariablesMutable,diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.tsxindex ff35e930f4..b66316f173 100644--- a/apps/builder/app/builder/features/settings-panel/variables-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/variables-section.tsx@@ -41,7 +41,7 @@ import {$selectedInstanceKeyWithRoot,$selectedPage,} from "~/shared/nano-states";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import {deleteVariableMutable,findAvailableVariables,diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsxindex 1c5f515946..54942e36cf 100644--- a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx@@ -30,7 +30,7 @@ import { $gridCellData } from "~/shared/nano-states";import { $selectedInstanceSelector } from "~/shared/nano-states";import { $breakpoints } from "~/shared/sync/data-stores";import { $instances } from "~/shared/sync/data-stores";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import { DEFAULT_GRID_TRACK_COUNT } from "./constants";/**diff --git a/apps/builder/app/builder/features/style-panel/shared/model.tsx b/apps/builder/app/builder/features/style-panel/shared/model.tsxindex bf15415449..5bd9d423fa 100644--- a/apps/builder/app/builder/features/style-panel/shared/model.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/model.tsx@@ -44,7 +44,7 @@ import {$selectedInstancePathWithRoot,type InstancePath,} from "~/shared/nano-states";-import type { InstanceSelector } from "~/shared/tree-utils";+import type { InstanceSelector } from "~/shared/instance-utils/tree";const $presetStyles = computed($registeredComponentMetas, (metas) => {const presetStyles = new Map<string, StyleValue>();diff --git a/apps/builder/app/builder/features/style-panel/style-source-section.tsx b/apps/builder/app/builder/features/style-panel/style-source-section.tsxindex 90d57a8bf6..7b72b41946 100644--- a/apps/builder/app/builder/features/style-panel/style-source-section.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source-section.tsx@@ -35,7 +35,7 @@ import {$styles,} from "~/shared/sync/data-stores";import { removeByMutable } from "~/shared/array-utils";-import { cloneStyles } from "~/shared/tree-utils";+import { cloneStyles } from "~/shared/instance-utils/tree";import { serverSyncStore } from "~/shared/sync/sync-stores";import { subscribe } from "~/shared/pubsub";import { $selectedInstance } from "~/shared/nano-states";diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.tsxindex 1304f5eec5..76214908db 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/block-editor-context-menu.tsx@@ -15,7 +15,7 @@ import { TemplatesMenu } from "./outline/block-instance-outline";import { insertTemplateAt } from "./outline/block-utils";import { useCallback, useEffect, useState } from "react";import { useEffectEvent } from "~/shared/hook-utils/effect-event";-import type { InstanceSelector } from "~/shared/tree-utils";+import type { InstanceSelector } from "~/shared/instance-utils/tree";import type { Instance } from "@webstudio-is/sdk";import { shallowEqual } from "shallow-equal";diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsxindex 08cfe474c3..dd9f161854 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx@@ -1,3 +1,5 @@+import { deleteInstanceMutable } from "~/shared/instance-utils/mutation";+import { updateWebstudioData } from "~/shared/instance-utils/data";import { useRef, useState } from "react";import { useStore } from "@nanostores/react";import { shallowEqual } from "shallow-equal";@@ -32,12 +34,8 @@ import {} from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";import { $clampingRect, $scale } from "~/builder/shared/nano-states";-import type { InstanceSelector } from "~/shared/tree-utils";-import {- canDeleteInstanceInContentMode,- deleteInstanceMutable,- updateWebstudioData,-} from "~/shared/instance-utils";+import type { InstanceSelector } from "~/shared/instance-utils/tree";+import { canDeleteInstanceInContentMode } from "~/shared/instance-utils/data";import { skipInertHandlersAttribute } from "~/builder/shared/inert-handlers";import { useEffectEvent } from "~/shared/hook-utils/effect-event";import { getInstancePath } from "~/shared/nano-states";diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.tsindex 9757a90163..41d2718d83 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts@@ -1,18 +1,20 @@import type { Instance, Instances, WebstudioFragment } from "@webstudio-is/sdk";+import { findAllEditableInstanceSelector } from "~/shared/instance-utils/lookup";+import {+ getWebstudioData,+ updateWebstudioData,+} from "~/shared/instance-utils/data";+import { insertInstanceChildrenMutable } from "~/shared/instance-utils/insert";+import {+ insertWebstudioFragmentCopy,+ detectFragmentTokenConflicts,+} from "~/shared/instance-utils/fragment";import { blockTemplateComponent } from "@webstudio-is/sdk";import { shallowEqual } from "shallow-equal";import { selectInstance } from "~/shared/nano-states";import { builderApi } from "~/shared/builder-api";import { findAvailableVariables } from "~/shared/data-variables";-import {- extractWebstudioFragment,- findAllEditableInstanceSelector,- getWebstudioData,- insertInstanceChildrenMutable,- insertWebstudioFragmentCopy,- updateWebstudioData,- detectFragmentTokenConflicts,-} from "~/shared/instance-utils";+import { extractWebstudioFragment } from "~/shared/instance-utils/fragment";import {$registeredComponentMetas,$isContentMode,@@ -22,7 +24,10 @@ import {} from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";import { $project } from "~/shared/sync/data-stores";-import type { DroppableTarget, InstanceSelector } from "~/shared/tree-utils";+import type {+ DroppableTarget,+ InstanceSelector,+} from "~/shared/instance-utils/tree";const getInsertionIndex = (anchor: InstanceSelector,diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/hovered-instance-outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/hovered-instance-outline.tsxindex cdf9afec20..313edb4499 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/hovered-instance-outline.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/hovered-instance-outline.tsx@@ -9,8 +9,8 @@ import {} from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";import { $clampingRect, $scale } from "~/builder/shared/nano-states";-import { findClosestSlot } from "~/shared/instance-utils";-import { isDescendantOrSelf } from "~/shared/tree-utils";+import { findClosestSlot } from "~/shared/instance-utils/slot";+import { isDescendantOrSelf } from "~/shared/instance-utils/tree";import { Outline } from "./outline";import { Label } from "./label";import { applyScale } from "../apply-scale";diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/selected-instance-outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/selected-instance-outline.tsxindex 1fbd70676a..d8292458f2 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/selected-instance-outline.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/selected-instance-outline.tsx@@ -3,11 +3,11 @@ import { $selectedInstanceOutlineAndInstance } from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";import { $textEditingInstanceSelector } from "~/shared/nano-states";import { $selectedInstanceSelector } from "~/shared/nano-states";-import { isDescendantOrSelf } from "~/shared/tree-utils";+import { isDescendantOrSelf } from "~/shared/instance-utils/tree";import { Outline } from "./outline";import { applyScale } from "../apply-scale";import { $clampingRect, $scale } from "~/builder/shared/nano-states";-import { findClosestSlot } from "~/shared/instance-utils";+import { findClosestSlot } from "~/shared/instance-utils/slot";import { $ephemeralStyles } from "~/canvas/stores";export const SelectedInstanceOutline = () => {diff --git a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx b/apps/builder/app/builder/shared/asset-manager/asset-info.tsxindex 6b5466ed97..886e13ad33 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx@@ -65,9 +65,9 @@ import { $openProjectSettings } from "~/shared/nano-states/project-settings";import { $styles } from "~/shared/sync/data-stores";import { $selectedInstanceSelector } from "~/shared/nano-states";import { selectPage } from "~/shared/nano-states";-import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils";+import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils/lookup";import { $selectedPageId } from "~/shared/nano-states";-import { updateWebstudioData } from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import { deleteAssets, replaceAsset } from "~/builder/shared/assets";import { validateFiles } from "~/builder/shared/assets/asset-upload";import {diff --git a/apps/builder/app/builder/shared/commands.test.ts b/apps/builder/app/builder/shared/commands.test.tsindex dd40756ddf..2522907063 100644--- a/apps/builder/app/builder/shared/commands.test.ts+++ b/apps/builder/app/builder/shared/commands.test.ts@@ -1,24 +1,44 @@import { describe, expect, test } from "vitest";import { createDefaultPages } from "@webstudio-is/project-build";import type { Instance, PageTemplate } from "@webstudio-is/sdk";+import type { Project } from "@webstudio-is/project";import {$editingPageId,$editingTemplateId,$folderIdToDelete,+ $builderMode,$pageIdToDelete,$selectedPageId,+ $selectedInstanceSelector,$templateIdToDelete,+ selectInstance,selectPage,} from "~/shared/nano-states";-import { $instances, $pages } from "~/shared/sync/data-stores";+import {+ $assets,+ $breakpoints,+ $dataSources,+ $instances,+ $pages,+ $project,+ $props,+ $resources,+ $styles,+ $styleSources,+ $styleSourceSelections,+} from "~/shared/sync/data-stores";+import { registerContainers } from "~/shared/sync/sync-stores";import {getDeletablePageActionTarget,getPageActionTarget,} from "~/shared/page-action-target";-import { __testing__ } from "./commands";+import { expectSlotsShareFragment } from "~/shared/slot-test-utils";+import { __testing__, emitCommand } from "./commands";const { canRunDesignModeCommand, guardDesignModeCommand } = __testing__;+registerContainers();+const resetPageActionStores = () => {$editingPageId.set(undefined);$editingTemplateId.set(undefined);@@ -30,6 +50,84 @@ const resetPageActionStores = () => {$pages.set(undefined);};+const resetDataStores = () => {+ $assets.set(new Map());+ $breakpoints.set(new Map());+ $dataSources.set(new Map());+ $instances.set(new Map());+ $pages.set(undefined);+ $project.set(undefined);+ $props.set(new Map());+ $resources.set(new Map());+ $styles.set(new Map());+ $styleSources.set(new Map());+ $styleSourceSelections.set(new Map());+ $builderMode.set("design");+};++const setupMoveInstanceProject = () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ { type: "id", value: "paragraph" },+ ],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [{ type: "id", value: "nested" }],+ },+ ],+ [+ "nested",+ {+ type: "instance",+ id: "nested",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: "Heading",+ children: [],+ },+ ],+ [+ "paragraph",+ {+ type: "instance",+ id: "paragraph",+ component: "Paragraph",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+};+describe("canRunDesignModeCommand", () => {test("keeps design commands design-only", () => {expect(canRunDesignModeCommand({ isDesignMode: true })).toBe(true);@@ -65,6 +163,1133 @@ describe("guardDesignModeCommand", () => {});});+describe("duplicateInstance", () => {+ test("duplicates shared slot child in shared slot content", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ],+ },+ ],+ [+ "slot1",+ {+ type: "instance",+ id: "slot1",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "slot2",+ {+ type: "instance",+ id: "slot2",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "fragment",+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [{ type: "id", value: "div" }],+ },+ ],+ [+ "div",+ {+ type: "instance",+ id: "div",+ component: "Box",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstance(["div", "fragment", "slot1", "body"]);++ emitCommand("duplicateInstance");++ expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ { type: "id", value: expect.any(String) },+ ]);+ });++ test("duplicates nested shared slot child in shared slot content", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ],+ },+ ],+ [+ "slot1",+ {+ type: "instance",+ id: "slot1",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "slot2",+ {+ type: "instance",+ id: "slot2",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "fragment",+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [{ type: "id", value: "div" }],+ },+ ],+ [+ "div",+ {+ type: "instance",+ id: "div",+ component: "Box",+ children: [{ type: "id", value: "box" }],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstance(["box", "div", "fragment", "slot1", "body"]);++ emitCommand("duplicateInstance");++ expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect($instances.get().get("div")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ ]);+ });++ test("duplicates shared slot child and preserves shared siblings", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ],+ },+ ],+ [+ "slot1",+ {+ type: "instance",+ id: "slot1",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "slot2",+ {+ type: "instance",+ id: "slot2",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "fragment",+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: "Heading",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstance(["box", "fragment", "slot1", "body"]);++ emitCommand("duplicateInstance");++ expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ { type: "id", value: "heading" },+ ]);+ });++ test("duplicates legacy shared slot child in shared slot content", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ],+ },+ ],+ [+ "slot1",+ {+ type: "instance",+ id: "slot1",+ component: "Slot",+ children: [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ],+ },+ ],+ [+ "slot2",+ {+ type: "instance",+ id: "slot2",+ component: "Slot",+ children: [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: "Heading",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstance(["box", "slot1", "body"]);++ emitCommand("duplicateInstance");++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ const duplicateId = $instances.get().get(fragmentId ?? "")+ ?.children[1]?.value;+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ { type: "id", value: "heading" },+ ]);+ expect(duplicateId).toEqual(expect.any(String));+ expect(duplicateId).not.toBe("box");+ expect($selectedInstanceSelector.get()).toEqual([+ duplicateId,+ fragmentId,+ "slot1",+ "body",+ ]);+ });+});++describe("move instance commands", () => {+ test("moves the selected instance above the previous sibling", () => {+ setupMoveInstanceProject();+ selectInstance(["heading", "body"]);++ emitCommand("moveInstanceUp");++ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "heading" },+ { type: "id", value: "box" },+ { type: "id", value: "paragraph" },+ ]);+ });++ test("moves the first child above its parent", () => {+ setupMoveInstanceProject();+ selectInstance(["nested", "box", "body"]);++ emitCommand("moveInstanceUp");++ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "nested" },+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ { type: "id", value: "paragraph" },+ ]);+ expect($instances.get().get("box")?.children).toEqual([]);+ });++ test("moves the selected instance below the next sibling", () => {+ setupMoveInstanceProject();+ selectInstance(["heading", "body"]);++ emitCommand("moveInstanceDown");++ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "paragraph" },+ { type: "id", value: "heading" },+ ]);+ });++ test("moves the last child below its parent", () => {+ setupMoveInstanceProject();+ selectInstance(["nested", "box", "body"]);++ emitCommand("moveInstanceDown");++ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "nested" },+ { type: "id", value: "heading" },+ { type: "id", value: "paragraph" },+ ]);+ expect($instances.get().get("box")?.children).toEqual([]);+ });++ test("moves the selected instance into the previous sibling", () => {+ setupMoveInstanceProject();+ selectInstance(["heading", "body"]);++ emitCommand("moveInstanceIntoPreviousSibling");++ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "paragraph" },+ ]);+ expect($instances.get().get("box")?.children).toEqual([+ { type: "id", value: "nested" },+ { type: "id", value: "heading" },+ ]);+ });++ test("moves a middle child out after its parent", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "box" },+ { type: "id", value: "paragraph" },+ ],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [+ { type: "id", value: "nested" },+ { type: "id", value: "middle" },+ { type: "id", value: "heading" },+ ],+ },+ ],+ [+ "nested",+ {+ type: "instance",+ id: "nested",+ component: "Box",+ children: [],+ },+ ],+ [+ "middle",+ {+ type: "instance",+ id: "middle",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: "Heading",+ children: [],+ },+ ],+ [+ "paragraph",+ {+ type: "instance",+ id: "paragraph",+ component: "Paragraph",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstance(["middle", "box", "body"]);++ emitCommand("moveInstanceOut");++ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "middle" },+ { type: "id", value: "paragraph" },+ ]);+ expect($instances.get().get("box")?.children).toEqual([+ { type: "id", value: "nested" },+ { type: "id", value: "heading" },+ ]);+ });++ test("moves the first child out above its parent", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "box" },+ { type: "id", value: "paragraph" },+ ],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [+ { type: "id", value: "nested" },+ { type: "id", value: "heading" },+ ],+ },+ ],+ [+ "nested",+ {+ type: "instance",+ id: "nested",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: "Heading",+ children: [],+ },+ ],+ [+ "paragraph",+ {+ type: "instance",+ id: "paragraph",+ component: "Paragraph",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstance(["nested", "box", "body"]);++ emitCommand("moveInstanceOut");++ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "nested" },+ { type: "id", value: "box" },+ { type: "id", value: "paragraph" },+ ]);+ expect($instances.get().get("box")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ });++ test("moves the last child out below its parent", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "box" },+ { type: "id", value: "paragraph" },+ ],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [+ { type: "id", value: "nested" },+ { type: "id", value: "heading" },+ ],+ },+ ],+ [+ "nested",+ {+ type: "instance",+ id: "nested",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: "Heading",+ children: [],+ },+ ],+ [+ "paragraph",+ {+ type: "instance",+ id: "paragraph",+ component: "Paragraph",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstance(["heading", "box", "body"]);++ emitCommand("moveInstanceOut");++ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ { type: "id", value: "paragraph" },+ ]);+ expect($instances.get().get("box")?.children).toEqual([+ { type: "id", value: "nested" },+ ]);+ });++ test("moves a shared slot child into the previous sibling in every slot occurrence", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ],+ },+ ],+ [+ "slot1",+ {+ type: "instance",+ id: "slot1",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "slot2",+ {+ type: "instance",+ id: "slot2",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "fragment",+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: "Heading",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstance(["heading", "fragment", "slot1", "body"]);++ emitCommand("moveInstanceIntoPreviousSibling");++ expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ expect($instances.get().get("box")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ });++ test("moves a direct shared slot child out of all slot occurrences", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ],+ },+ ],+ [+ "slot1",+ {+ type: "instance",+ id: "slot1",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "slot2",+ {+ type: "instance",+ id: "slot2",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "fragment",+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: "Heading",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstance(["heading", "fragment", "slot1", "body"]);++ emitCommand("moveInstanceOut");++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ const bodyChildren = $instances.get().get("body")?.children;+ const movedHeadingId = bodyChildren?.[1]?.value;+ expect(bodyChildren).toEqual([+ { type: "id", value: "slot1" },+ { type: "id", value: "heading" },+ { type: "id", value: "slot2" },+ ]);+ expect(movedHeadingId).toBe("heading");+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ });++ test("moves the first direct shared slot child out of all slot occurrences above the slot", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ],+ },+ ],+ [+ "slot1",+ {+ type: "instance",+ id: "slot1",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "slot2",+ {+ type: "instance",+ id: "slot2",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "fragment",+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: "Heading",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstance(["box", "fragment", "slot1", "body"]);++ emitCommand("moveInstanceOut");++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ const bodyChildren = $instances.get().get("body")?.children;+ const movedBoxId = bodyChildren?.[0]?.value;+ expect(bodyChildren).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]);+ expect(movedBoxId).toBe("box");+ expect($instances.get().get(movedBoxId ?? "")?.component).toBe("Box");+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ });++ test("moves the first direct shared slot child above all slot occurrences", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ],+ },+ ],+ [+ "slot1",+ {+ type: "instance",+ id: "slot1",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "slot2",+ {+ type: "instance",+ id: "slot2",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "fragment",+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: "Heading",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstance(["box", "fragment", "slot1", "body"]);++ emitCommand("moveInstanceUp");++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ const bodyChildren = $instances.get().get("body")?.children;+ const movedBoxId = bodyChildren?.[0]?.value;+ expect(bodyChildren).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]);+ expect(movedBoxId).toBe("box");+ expect($instances.get().get(movedBoxId ?? "")?.component).toBe("Box");+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ });++ test("moves the last direct shared slot child below all slot occurrences", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ],+ },+ ],+ [+ "slot1",+ {+ type: "instance",+ id: "slot1",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "slot2",+ {+ type: "instance",+ id: "slot2",+ component: "Slot",+ children: [{ type: "id", value: "fragment" }],+ },+ ],+ [+ "fragment",+ {+ type: "instance",+ id: "fragment",+ component: "Fragment",+ children: [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading",+ {+ type: "instance",+ id: "heading",+ component: "Heading",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstance(["heading", "fragment", "slot1", "body"]);++ emitCommand("moveInstanceDown");++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ const bodyChildren = $instances.get().get("body")?.children;+ const movedHeadingId = bodyChildren?.[1]?.value;+ expect(bodyChildren).toEqual([+ { type: "id", value: "slot1" },+ { type: "id", value: "heading" },+ { type: "id", value: "slot2" },+ ]);+ expect(movedHeadingId).toBe("heading");+ expect($instances.get().get(movedHeadingId ?? "")?.component).toBe(+ "Heading"+ );+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ });+});+describe("getPageActionTarget", () => {test("uses the open page settings target", () => {resetPageActionStores();diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex 591723e1f5..4b2247528e 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -1,5 +1,16 @@+import {+ unwrapInstance,+ deleteSelectedInstance,+ reparentInstance,+} from "~/shared/instance-utils/mutation";+import { toggleInstanceShow } from "~/shared/instance-utils/mutation";+import {+ extractWebstudioFragment,+ insertWebstudioFragmentCopy,+} from "~/shared/instance-utils/fragment";+import { insertWebstudioFragmentAt } from "~/shared/instance-utils/insert";import { toast } from "@webstudio-is/design-system";-import { type WebstudioFragment } from "@webstudio-is/sdk";+import { type Instance, type WebstudioFragment } from "@webstudio-is/sdk";import {isAutoGridPlacement,resetGridChildPlacement,@@ -33,15 +44,7 @@ import {$breakpointsMenuView,selectBreakpointByOrder,} from "~/shared/breakpoints";-import {- updateWebstudioData,- unwrapInstance,- detachSharedSlotContentMutable,- deleteSelectedInstance,- extractWebstudioFragment,- insertWebstudioFragmentAt,- insertWebstudioFragmentCopy,-} from "~/shared/instance-utils";+import { updateWebstudioData } from "~/shared/instance-utils/data";import { serverSyncStore } from "~/shared/sync/sync-stores";import { $publisher } from "~/shared/pubsub";import {@@ -76,11 +79,14 @@ import {emitPaste,cutInstance,} from "~/shared/copy-paste/copy-paste";-import { toggleInstanceShow } from "~/shared/instance-utils";import {getDeletablePageActionTarget,getPageActionTarget,} from "~/shared/page-action-target";+import {+ getDirectSharedSlotChildBoundary,+ normalizeLegacySlotInstancePathMutable,+} from "~/shared/instance-utils/slot";const makeBreakpointCommand = <CommandName extends string>(name: CommandName,@@ -197,6 +203,140 @@ const requestSelectedPageItemDelete = () => {return true;};+type InstanceMoveDirection = "up" | "down" | "intoPreviousSibling" | "out";++const getIdChildIndex = (children: Instance["children"], instanceId: string) =>+ children.findIndex(+ (child) => child.type === "id" && child.value === instanceId+ );++const getOutdentMoveTarget = (+ instancePath: NonNullable<ReturnType<typeof $selectedInstancePath.get>>,+ positionRelativeToParent: "before" | "after"+) => {+ const parentItem = instancePath[1];+ const grandparentItem = instancePath[2];+ if (parentItem === undefined || grandparentItem === undefined) {+ return;+ }++ const directSlotBoundary = getDirectSharedSlotChildBoundary(instancePath);+ if (directSlotBoundary !== undefined) {+ const slotParentItem = directSlotBoundary.slotParentItem;+ if (slotParentItem === undefined) {+ return;+ }+ const slotPosition = getIdChildIndex(+ slotParentItem.instance.children,+ directSlotBoundary.slotId+ );+ if (slotPosition === -1) {+ return;+ }+ return {+ parentSelector: slotParentItem.instanceSelector,+ position:+ positionRelativeToParent === "before" ? slotPosition : slotPosition + 1,+ };+ }++ const parent = parentItem.instance;+ const parentIndex = getIdChildIndex(+ grandparentItem.instance.children,+ parent.id+ );+ if (parentIndex === -1) {+ return;+ }+ return {+ parentSelector: grandparentItem.instanceSelector,+ position:+ positionRelativeToParent === "before" ? parentIndex : parentIndex + 1,+ };+};++const getInstanceMoveTarget = (direction: InstanceMoveDirection) => {+ const instancePath = $selectedInstancePath.get();+ const selectedItem = instancePath?.[0];+ const parentItem = instancePath?.[1];+ if (+ instancePath === undefined ||+ selectedItem === undefined ||+ parentItem === undefined+ ) {+ return;+ }++ const parent = parentItem.instance;+ const selectedIndex = getIdChildIndex(+ parent.children,+ selectedItem.instance.id+ );+ if (selectedIndex === -1) {+ return;+ }++ if (direction === "up") {+ if (selectedIndex === 0) {+ return getOutdentMoveTarget(instancePath, "before");+ }+ return {+ parentSelector: parentItem.instanceSelector,+ position: selectedIndex - 1,+ };+ }++ if (direction === "down") {+ if (selectedIndex >= parent.children.length - 1) {+ return getOutdentMoveTarget(instancePath, "after");+ }+ return {+ parentSelector: parentItem.instanceSelector,+ position: selectedIndex + 2,+ };+ }++ if (direction === "intoPreviousSibling") {+ if (selectedIndex === 0) {+ return;+ }+ const previousChild = parent.children[selectedIndex - 1];+ if (previousChild?.type !== "id") {+ return;+ }+ return {+ parentSelector: [previousChild.value, ...parentItem.instanceSelector],+ position: "end" as const,+ };+ }++ return getOutdentMoveTarget(+ instancePath,+ selectedIndex === 0 ? "before" : "after"+ );+};++const moveSelectedInstance = (direction: InstanceMoveDirection) => {+ if (+ guardDesignModeCommand({+ isDesignMode: $isDesignMode.get(),+ message: "Moving is only allowed in design mode.",+ }) === false+ ) {+ return;+ }+ const instancePath = $selectedInstancePath.get();+ const selectedItem = instancePath?.[0];+ if (selectedItem === undefined) {+ return;+ }+ const target = getInstanceMoveTarget(direction);+ if (target === undefined) {+ return;+ }+ reparentInstance(selectedItem.instanceSelector, target);+};+export const { emitCommand, subscribeCommands } = createCommandsEmitter({source: "builder",externalCommands: [@@ -484,6 +624,42 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({}},},+ {+ name: "moveInstanceUp",+ label: "Move up",+ description: "Move selected instance above the previous sibling",+ category: "Navigator",+ defaultHotkeys: ["meta+arrowup", "ctrl+arrowup"],+ disableOnInputLikeControls: true,+ handler: () => moveSelectedInstance("up"),+ },+ {+ name: "moveInstanceDown",+ label: "Move down",+ description: "Move selected instance below the next sibling",+ category: "Navigator",+ defaultHotkeys: ["meta+arrowdown", "ctrl+arrowdown"],+ disableOnInputLikeControls: true,+ handler: () => moveSelectedInstance("down"),+ },+ {+ name: "moveInstanceOut",+ label: "Move out",+ description: "Move selected instance out of its parent",+ category: "Navigator",+ defaultHotkeys: ["meta+arrowleft", "ctrl+arrowleft"],+ disableOnInputLikeControls: true,+ handler: () => moveSelectedInstance("out"),+ },+ {+ name: "moveInstanceIntoPreviousSibling",+ label: "Move in",+ description: "Move selected instance into the previous sibling",+ category: "Navigator",+ defaultHotkeys: ["meta+arrowright", "ctrl+arrowright"],+ disableOnInputLikeControls: true,+ handler: () => moveSelectedInstance("intoPreviousSibling"),+ },{name: "deleteInstanceBuilder",label: "Delete",@@ -528,11 +704,11 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({}updateWebstudioData((data) => {- const detachedInstancePath = detachSharedSlotContentMutable(- data,+ const normalizedInstancePath = normalizeLegacySlotInstancePathMutable(+ data.instances,instancePath);- const [selectedItem, parentItem] = detachedInstancePath;+ const [selectedItem, parentItem] = normalizedInstancePath;if (parentItem === undefined) {return;}diff --git a/apps/builder/app/builder/shared/instance-context-menu.tsx b/apps/builder/app/builder/shared/instance-context-menu.tsxindex 9e74920838..43e9c268fa 100644--- a/apps/builder/app/builder/shared/instance-context-menu.tsx+++ b/apps/builder/app/builder/shared/instance-context-menu.tsx@@ -1,4 +1,5 @@import type { ReactNode } from "react";+import { canUnwrapInstance } from "~/shared/instance-utils/mutation";import { useStore } from "@nanostores/react";import {ContextMenu,@@ -20,10 +21,7 @@ import {$isDesignMode,getInstanceKey,} from "~/shared/nano-states";-import {- canDeleteInstanceInContentMode,- canUnwrapInstance,-} from "~/shared/instance-utils";+import { canDeleteInstanceInContentMode } from "~/shared/instance-utils/data";import { $propValuesByInstanceSelector } from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";import { ROOT_INSTANCE_ID, type Instances } from "@webstudio-is/sdk";diff --git a/apps/builder/app/canvas/elements.tsx b/apps/builder/app/canvas/elements.tsxindex 6a45386be3..421d89ca88 100644--- a/apps/builder/app/canvas/elements.tsx+++ b/apps/builder/app/canvas/elements.tsx@@ -7,7 +7,7 @@ import {} from "react";import type { Instance, Instances } from "@webstudio-is/sdk";import type { Components } from "@webstudio-is/react-sdk";-import type { InstanceSelector } from "~/shared/tree-utils";+import type { InstanceSelector } from "~/shared/instance-utils/tree";export type WebstudioComponentProps = {instance: Instance;diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsxindex d25098cc5a..7b1ac56a21 100644--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx@@ -1,3 +1,5 @@+import { findAllEditableInstanceSelector } from "~/shared/instance-utils/lookup";+import { updateWebstudioData } from "~/shared/instance-utils/data";import { color } from "@webstudio-is/css-engine";import {useState,@@ -29,8 +31,7 @@ import {KEY_ARROW_LEFT_COMMAND,$createRangeSelection,COMMAND_PRIORITY_CRITICAL,- $getNearestNodeFromDOMNode,- // eslint-disable-next-line camelcase+ $getNearestNodeFromDOMNode, // eslint-disable-next-line camelcase$normalizeSelection__EXPERIMENTAL,type LexicalEditor,type SerializedEditorState,@@ -58,15 +59,14 @@ import {idAttribute,selectorIdAttribute,} from "@webstudio-is/react-sdk";-import { isDescendantOrSelf, type InstanceSelector } from "~/shared/tree-utils";+import {+ isDescendantOrSelf,+ type InstanceSelector,+} from "~/shared/instance-utils/tree";import { ToolbarConnectorPlugin } from "./toolbar-connector";import { type Refs, $convertToLexical, $convertToUpdates } from "./interop";import { useEffectEvent } from "~/shared/hook-utils/effect-event";-import {- deleteInstanceMutable,- findAllEditableInstanceSelector,- updateWebstudioData,-} from "~/shared/instance-utils";+import { deleteInstanceMutable } from "~/shared/instance-utils/mutation";import {$blockChildOutline,$hoveredInstanceOutline,diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsxindex 94e6f1a916..e23b332f97 100644--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx@@ -62,7 +62,7 @@ import { $instances } from "~/shared/sync/data-stores";import {type InstanceSelector,areInstanceSelectorsEqual,-} from "~/shared/tree-utils";+} from "~/shared/instance-utils/tree";import { inflateInstance } from "~/canvas/inflator";import { getIsVisuallyHidden } from "~/shared/visually-hidden";import { serverSyncStore } from "~/shared/sync/sync-stores";diff --git a/apps/builder/app/canvas/grid-guide-utils.ts b/apps/builder/app/canvas/grid-guide-utils.tsindex 7f4142e8e9..f8e3ca2616 100644--- a/apps/builder/app/canvas/grid-guide-utils.ts+++ b/apps/builder/app/canvas/grid-guide-utils.ts@@ -7,7 +7,7 @@ import { $instances } from "~/shared/sync/data-stores";import { $gridCellData, type GridCellData } from "~/shared/nano-states";import { subscribeScrollState } from "~/canvas/shared/scroll-state";import { subscribeWindowResize } from "~/shared/dom-hooks";-import type { InstanceSelector } from "~/shared/tree-utils";+import type { InstanceSelector } from "~/shared/instance-utils/tree";import { $selectedInstanceSelector } from "~/shared/nano-states";import { getElementByInstanceSelector } from "~/shared/dom-utils";import { parseGridTemplateTrackList } from "@webstudio-is/css-data";diff --git a/apps/builder/app/canvas/instance-hovering.ts b/apps/builder/app/canvas/instance-hovering.tsindex a16d60e661..54e90b1f95 100644--- a/apps/builder/app/canvas/instance-hovering.ts+++ b/apps/builder/app/canvas/instance-hovering.ts@@ -13,7 +13,10 @@ import {getInstanceSelectorFromElement,} from "~/shared/dom-utils";import { subscribeScrollState } from "./shared/scroll-state";-import { isDescendantOrSelf, type InstanceSelector } from "~/shared/tree-utils";+import {+ isDescendantOrSelf,+ type InstanceSelector,+} from "~/shared/instance-utils/tree";import { $selectedInstanceSelector } from "~/shared/nano-states";type TimeoutId = undefined | ReturnType<typeof setTimeout>;diff --git a/apps/builder/app/canvas/instance-selected.ts b/apps/builder/app/canvas/instance-selected.tsindex ac824184cd..b2f5e6b0ab 100644--- a/apps/builder/app/canvas/instance-selected.ts+++ b/apps/builder/app/canvas/instance-selected.ts@@ -27,7 +27,7 @@ import { subscribeScrollState } from "~/canvas/shared/scroll-state";import { $selectedInstanceOutline } from "~/shared/nano-states";import { $instances, $styles } from "~/shared/sync/data-stores";import { inflateInstance } from "~/canvas/inflator";-import type { InstanceSelector } from "~/shared/tree-utils";+import type { InstanceSelector } from "~/shared/instance-utils/tree";import { $selectedInstanceSelector } from "~/shared/nano-states";const setOutline = (instanceId: Instance["id"], elements: HTMLElement[]) => {diff --git a/apps/builder/app/canvas/shared/commands.ts b/apps/builder/app/canvas/shared/commands.tsindex f192aac6fe..df815bbc0a 100644--- a/apps/builder/app/canvas/shared/commands.ts+++ b/apps/builder/app/canvas/shared/commands.ts@@ -2,7 +2,7 @@ import { FORMAT_TEXT_COMMAND } from "lexical";import { TOGGLE_LINK_COMMAND } from "@lexical/link";import { createCommandsEmitter } from "~/shared/commands-emitter";import { getElementByInstanceSelector } from "~/shared/dom-utils";-import { findAllEditableInstanceSelector } from "~/shared/instance-utils";+import { findAllEditableInstanceSelector } from "~/shared/instance-utils/lookup";import {$registeredComponentMetas,$textEditingInstanceSelector,@@ -18,8 +18,11 @@ import {} from "../features/text-editor/toolbar-connector";import { $selectedInstanceSelector } from "~/shared/nano-states";import { selectInstance } from "~/shared/nano-states";-import { isDescendantOrSelf, type InstanceSelector } from "~/shared/tree-utils";-import { deleteSelectedInstance } from "~/shared/instance-utils";+import {+ isDescendantOrSelf,+ type InstanceSelector,+} from "~/shared/instance-utils/tree";+import { deleteSelectedInstance } from "~/shared/instance-utils/mutation";import { findClosestRichText } from "~/shared/content-model";import { getDeletablePageActionTarget } from "~/shared/page-action-target";@@ -34,7 +37,14 @@ const deleteSelectedPageOrInstance = () => {export const { emitCommand, subscribeCommands } = createCommandsEmitter({source: "canvas",- externalCommands: ["clickCanvas", "deleteInstanceBuilder"],+ externalCommands: [+ "clickCanvas",+ "deleteInstanceBuilder",+ "moveInstanceUp",+ "moveInstanceDown",+ "moveInstanceOut",+ "moveInstanceIntoPreviousSibling",+ ],commands: [{name: "deleteInstanceCanvas",diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.tsindex 292c1ae510..a4f17e22e1 100644--- a/apps/builder/app/canvas/shared/styles.ts+++ b/apps/builder/app/canvas/shared/styles.ts@@ -49,8 +49,8 @@ import {$selectedInstanceSelector,$selectedPage,} from "~/shared/nano-states";-import { findAllEditableInstanceSelector } from "~/shared/instance-utils";-import type { InstanceSelector } from "~/shared/tree-utils";+import { findAllEditableInstanceSelector } from "~/shared/instance-utils/lookup";+import type { InstanceSelector } from "~/shared/instance-utils/tree";import { getAllElementsByInstanceSelector } from "~/shared/dom-utils";import { createComputedStyleDeclStore } from "~/builder/features/style-panel/shared/model";diff --git a/apps/builder/app/canvas/shared/use-drag-drop.ts b/apps/builder/app/canvas/shared/use-drag-drop.tsindex b2838b5e0f..e97a766b7b 100644--- a/apps/builder/app/canvas/shared/use-drag-drop.ts+++ b/apps/builder/app/canvas/shared/use-drag-drop.ts@@ -1,3 +1,6 @@+import { insertWebstudioElementAt } from "~/shared/instance-utils/insert";+import { insertWebstudioFragmentAt } from "~/shared/instance-utils/insert";+import { reparentInstance } from "~/shared/instance-utils/mutation";import { useLayoutEffect, useRef } from "react";import { elementComponent, type Instance } from "@webstudio-is/sdk";import {@@ -14,12 +17,7 @@ import {} from "~/shared/nano-states";import { $instances, $props } from "~/shared/sync/data-stores";import { publish, useSubscribe } from "~/shared/pubsub";-import {- getComponentTemplateData,- insertWebstudioElementAt,- insertWebstudioFragmentAt,- reparentInstance,-} from "~/shared/instance-utils";+import { getComponentTemplateData } from "~/shared/instance-utils/insert";import {getElementByInstanceSelector,getInstanceIdFromElement,@@ -28,7 +26,7 @@ import {import {type InstanceSelector,areInstanceSelectorsEqual,-} from "~/shared/tree-utils";+} from "~/shared/instance-utils/tree";import { findClosestInstanceMatchingFragment } from "~/shared/matcher";import {findClosestContainer,diff --git a/apps/builder/app/shared/awareness.test.tsx b/apps/builder/app/shared/awareness.test.tsxindex a274b0a727..601607fd1a 100644--- a/apps/builder/app/shared/awareness.test.tsx+++ b/apps/builder/app/shared/awareness.test.tsx@@ -1,8 +1,8 @@import { afterEach, expect, test, vi } from "vitest";-import { $awareness, __testing__, startPointerTracking } from "./awareness";+import { $awareness, startPointerTracking, __testing__ } from "./awareness";const { $pointerPosition, getUserAwareness } = __testing__;-import { findPageAndSelectorByInstanceId } from "./instance-utils";+import { findPageAndSelectorByInstanceId } from "./instance-utils/lookup";import { $selectedPageId } from "./nano-states/pages";import { $user } from "./nano-states/misc";import { createDefaultPages } from "@webstudio-is/project-build";diff --git a/apps/builder/app/shared/content-model.ts b/apps/builder/app/shared/content-model.tsindex fa7eade5b5..e76412d964 100644--- a/apps/builder/app/shared/content-model.ts+++ b/apps/builder/app/shared/content-model.ts@@ -10,7 +10,7 @@ import {type Props,type WsComponentMeta,} from "@webstudio-is/sdk";-import type { InstanceSelector } from "./tree-utils";+import type { InstanceSelector } from "./instance-utils/tree";import { setIsSubsetOf } from "./shim";type Metas = Map<Instance["component"], WsComponentMeta>;diff --git a/apps/builder/app/shared/copy-paste.test.tsx b/apps/builder/app/shared/copy-paste.test.tsxindex 841e9e5f34..eed63c817f 100644--- a/apps/builder/app/shared/copy-paste.test.tsx+++ b/apps/builder/app/shared/copy-paste.test.tsx@@ -1,3 +1,4 @@+import { insertWebstudioFragmentCopy } from "./instance-utils/fragment";import { describe, expect, test } from "vitest";import stripIndent from "strip-indent";import { createRegularStyleSheet } from "@webstudio-is/css-engine";@@ -22,10 +23,7 @@ import {Parameter,} from "@webstudio-is/template";import type { Project } from "@webstudio-is/project";-import {- extractWebstudioFragment,- insertWebstudioFragmentCopy,-} from "./instance-utils";+import { extractWebstudioFragment } from "./instance-utils/fragment";import { $project } from "~/shared/sync/data-stores";import { findAvailableVariables } from "./data-variables";import { camelCaseProperty } from "@webstudio-is/css-data";diff --git a/apps/builder/app/shared/copy-paste/plugin-html.test.tsx b/apps/builder/app/shared/copy-paste/plugin-html.test.tsxindex c7d14eaa01..7a0e076392 100644--- a/apps/builder/app/shared/copy-paste/plugin-html.test.tsx+++ b/apps/builder/app/shared/copy-paste/plugin-html.test.tsx@@ -3,14 +3,23 @@ import { setEnv } from "@webstudio-is/feature-flags";import { renderData, ws } from "@webstudio-is/template";import { createDefaultPages } from "@webstudio-is/project-build";import type { Project } from "@webstudio-is/project";+import { coreMetas } from "@webstudio-is/sdk";+import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";import { registerContainers } from "../sync/sync-stores";import { $instances } from "~/shared/sync/data-stores";import { $pages, $project } from "~/shared/sync/data-stores";-import { $selectedPageId, $selectedInstanceSelector } from "../nano-states";+import {+ $registeredComponentMetas,+ $selectedPageId,+ $selectedInstanceSelector,+} from "../nano-states";import { html } from "./plugin-html";setEnv("*");registerContainers();+$registeredComponentMetas.set(+ new Map(Object.entries({ ...defaultMetas, ...coreMetas }))+);test("paste html fragment", async () => {const data = renderData(diff --git a/apps/builder/app/shared/copy-paste/plugin-html.ts b/apps/builder/app/shared/copy-paste/plugin-html.tsindex bdf445b995..c9bd238b10 100644--- a/apps/builder/app/shared/copy-paste/plugin-html.ts+++ b/apps/builder/app/shared/copy-paste/plugin-html.ts@@ -1,6 +1,6 @@import type { WebstudioFragment } from "@webstudio-is/sdk";import { generateFragmentFromHtml } from "../html";-import { insertWebstudioFragmentAt } from "../instance-utils";+import { insertWebstudioFragmentAt } from "../instance-utils/insert";import { generateFragmentFromTailwind } from "../tailwind/tailwind";import { denormalizeSrcProps } from "./asset-upload";import type { Plugin } from "./copy-paste";diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts b/apps/builder/app/shared/copy-paste/plugin-instance.test.tsindex 2364807228..33168cb1dc 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts@@ -7,11 +7,14 @@ import type {Props,DataSource,DataSources,+ Resource,+ Resources,} from "@webstudio-is/sdk";import {encodeDataSourceVariable,collectionComponent,coreMetas,+ elementComponent,portalComponent,} from "@webstudio-is/sdk";import type { Project } from "@webstudio-is/project";@@ -24,12 +27,18 @@ import {$pages,$project,$props,+ $resources,} from "~/shared/sync/data-stores";import { instanceText } from "./plugin-instance";import { createDefaultPages } from "@webstudio-is/project-build";import { selectInstance } from "~/shared/nano-states";import { $selectedPageId } from "../nano-states/pages";-import * as instanceUtils from "../instance-utils";+import * as instanceFragmentUtils from "../instance-utils/fragment";+import * as instanceMutationUtils from "../instance-utils/mutation";+import {+ expectSlotTreeIntegrity,+ expectSlotsShareFragment,+} from "../slot-test-utils";const expectString = expect.any(String) as unknown as string;@@ -38,7 +47,10 @@ registerContainers();// Mock detectFragmentTokenConflicts to always return no conflictsbeforeAll(() => {- vi.spyOn(instanceUtils, "detectFragmentTokenConflicts").mockReturnValue([]);+ vi.spyOn(+ instanceFragmentUtils,+ "detectFragmentTokenConflicts"+ ).mockReturnValue([]);});$registeredComponentMetas.set(@@ -135,6 +147,555 @@ describe("paste target", () => {toMap([createInstance(newBox1, "Box", [])]));});++ test("pastes into shared slot content", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "source" },+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]),+ createInstance("source", "Box", []),+ createInstance("slot1", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("slot2", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("fragment", "Fragment", [{ type: "id", value: "box" }]),+ createInstance("box", "Box", []),+ ] satisfies Instance[])+ );+ selectInstance(["source", "body0"]);+ const clipboardData = instanceText.onCopy?.() ?? "";+ selectInstance(["slot1", "body0"]);++ await instanceText.onPaste?.(clipboardData);++ expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ ]);+ });++ test("pastes into legacy shared slot content", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "source" },+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]),+ createInstance("source", "Box", []),+ createInstance("slot1", "Slot", [{ type: "id", value: "box" }]),+ createInstance("slot2", "Slot", [{ type: "id", value: "box" }]),+ createInstance("box", "Box", []),+ ] satisfies Instance[])+ );+ selectInstance(["source", "body0"]);+ const clipboardData = instanceText.onCopy?.() ?? "";+ selectInstance(["slot1", "body0"]);++ await instanceText.onPaste?.(clipboardData);++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ ]);+ });++ test("pastes after selected shared slot child in shared slot content", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]),+ createInstance("slot1", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("slot2", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("fragment", "Fragment", [{ type: "id", value: "box" }]),+ createInstance("box", "Box", []),+ ] satisfies Instance[])+ );+ selectInstance(["box", "fragment", "slot1", "body0"]);++ await instanceText.onPaste?.(instanceText.onCopy?.() ?? "");++ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ ]);+ });++ test("pastes after selected legacy shared slot child in shared slot content", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]),+ createInstance("slot1", "Slot", [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]),+ createInstance("slot2", "Slot", [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]),+ createInstance("box", "Box", []),+ createInstance("heading", "Heading", []),+ ] satisfies Instance[])+ );+ selectInstance(["box", "slot1", "body0"]);++ await instanceText.onPaste?.(instanceText.onCopy?.() ?? "");++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ { type: "id", value: "heading" },+ ]);+ expectSlotTreeIntegrity($instances.get());+ });++ test("pastes after selected nested shared slot child in shared slot content", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]),+ createInstance("slot1", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("slot2", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("fragment", "Fragment", [{ type: "id", value: "div" }]),+ createInstance("div", "Box", [{ type: "id", value: "box" }]),+ createInstance("box", "Box", []),+ ] satisfies Instance[])+ );+ selectInstance(["box", "div", "fragment", "slot1", "body0"]);++ await instanceText.onPaste?.(instanceText.onCopy?.() ?? "");++ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect($instances.get().get("div")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ ]);+ });++ test("pastes into nested shared slot container", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "source" },+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]),+ createInstance("source", "Box", []),+ createInstance("slot1", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("slot2", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("fragment", "Fragment", [{ type: "id", value: "div" }]),+ createInstance("div", "Box", []),+ ] satisfies Instance[])+ );+ selectInstance(["source", "body0"]);+ const clipboardData = instanceText.onCopy?.() ?? "";+ selectInstance(["div", "fragment", "slot1", "body0"]);++ await instanceText.onPaste?.(clipboardData);++ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect($instances.get().get("div")?.children).toEqual([+ { type: "id", value: expect.any(String) },+ ]);+ });++ test("copies shared slot child and pastes independent copy outside", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ { type: "id", value: "target" },+ ]),+ createInstance("slot1", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("slot2", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("fragment", "Fragment", [{ type: "id", value: "box" }]),+ createInstance("box", "Box", []),+ createInstance("target", "Box", []),+ ] satisfies Instance[])+ );+ selectInstance(["box", "fragment", "slot1", "body0"]);+ const clipboardData = instanceText.onCopy?.() ?? "";+ selectInstance(["target", "body0"]);++ await instanceText.onPaste?.(clipboardData);++ expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);+ const pastedBoxId = $instances.get().get("target")?.children[0]?.value;+ expect(pastedBoxId).toEqual(expect.any(String));+ expect(pastedBoxId).not.toBe("box");+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ expect($instances.get().get(pastedBoxId ?? "")?.children).toEqual([]);+ });++ test("copies legacy shared slot child and pastes independent copy outside", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ { type: "id", value: "target" },+ ]),+ createInstance("slot1", "Slot", [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]),+ createInstance("slot2", "Slot", [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]),+ createInstance("box", "Box", []),+ createInstance("heading", "Heading", []),+ createInstance("target", "Box", []),+ ] satisfies Instance[])+ );+ selectInstance(["box", "slot1", "body0"]);+ const clipboardData = instanceText.onCopy?.() ?? "";+ selectInstance(["target", "body0"]);++ await instanceText.onPaste?.(clipboardData);++ const pastedBoxId = $instances.get().get("target")?.children[0]?.value;+ expect(pastedBoxId).toEqual(expect.any(String));+ expect(pastedBoxId).not.toBe("box");+ expect($instances.get().get(pastedBoxId ?? "")?.component).toBe("Box");++ selectInstance(["box", "slot1", "body0"]);+ instanceMutationUtils.convertInstance(elementComponent, "section");++ expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);+ expect($instances.get().get("box")?.component).toBe(elementComponent);+ expect($instances.get().get("box")?.tag).toBe("section");+ expect($instances.get().get(pastedBoxId ?? "")?.component).toBe("Box");+ });++ test("copies nested shared slot child with scoped data and pastes independent copy outside", async () => {+ const dataSources: DataSources = toMap([+ {+ id: "boxVariable",+ scopeInstanceId: "box",+ type: "variable",+ name: "Box Variable",+ value: { type: "string", value: "value" },+ },+ ] satisfies DataSource[]);+ const props: Props = toMap([+ {+ id: "boxExpressionProp",+ instanceId: "box",+ name: "children",+ type: "expression",+ value: "$ws$dataSource$boxVariable",+ },+ {+ id: "boxResourceProp",+ instanceId: "box",+ name: "resource",+ type: "resource",+ value: "boxResource",+ },+ ] satisfies Prop[]);+ const resources: Resources = toMap([+ {+ id: "boxResource",+ name: "Box Resource",+ method: "get",+ url: "$ws$dataSource$boxVariable",+ headers: [+ {+ name: "authorization",+ value: "$ws$dataSource$boxVariable",+ },+ ],+ searchParams: [+ {+ name: "query",+ value: "$ws$dataSource$boxVariable",+ },+ ],+ },+ ] satisfies Resource[]);+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ { type: "id", value: "target" },+ ]),+ createInstance("slot1", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("slot2", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("fragment", "Fragment", [{ type: "id", value: "div" }]),+ createInstance("div", "Box", [{ type: "id", value: "box" }]),+ createInstance("box", "Box", []),+ createInstance("target", "Box", []),+ ] satisfies Instance[])+ );+ $dataSources.set(dataSources);+ $props.set(props);+ $resources.set(resources);+ selectInstance(["box", "div", "fragment", "slot1", "body0"]);+ const clipboardData = instanceText.onCopy?.() ?? "";+ selectInstance(["target", "body0"]);++ await instanceText.onPaste?.(clipboardData);++ const pastedBoxId = $instances.get().get("target")?.children[0]?.value;+ const dataSourcesDifference = getMapDifference(+ dataSources,+ $dataSources.get()+ );+ const [newDataSourceId] = dataSourcesDifference.keys();+ const propsDifference = getMapDifference(props, $props.get());+ const resourcesDifference = getMapDifference(resources, $resources.get());+ const [newResourceId] = resourcesDifference.keys();+ expect(pastedBoxId).toEqual(expect.any(String));+ expect(pastedBoxId).not.toBe("box");+ expect(dataSourcesDifference).toEqual(+ toMap([+ {+ ...dataSources.get("boxVariable"),+ id: newDataSourceId,+ scopeInstanceId: pastedBoxId,+ },+ ])+ );+ expect(Array.from(propsDifference.values())).toEqual(+ expect.arrayContaining([+ {+ id: expectString,+ instanceId: pastedBoxId,+ name: "children",+ type: "expression",+ value: encodeDataSourceVariable(newDataSourceId),+ },+ {+ id: expectString,+ instanceId: pastedBoxId,+ name: "resource",+ type: "resource",+ value: newResourceId,+ },+ ])+ );+ expect(resourcesDifference).toEqual(+ toMap([+ {+ id: newResourceId,+ name: "Box Resource",+ method: "get",+ url: encodeDataSourceVariable(newDataSourceId),+ headers: [+ {+ name: "authorization",+ value: encodeDataSourceVariable(newDataSourceId),+ },+ ],+ searchParams: [+ {+ name: "query",+ value: encodeDataSourceVariable(newDataSourceId),+ },+ ],+ },+ ])+ );+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect($instances.get().get("div")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ });++ test("cuts shared slot child from all slot occurrences", () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]),+ createInstance("slot1", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("slot2", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("fragment", "Fragment", [{ type: "id", value: "box" }]),+ createInstance("box", "Box", []),+ ] satisfies Instance[])+ );+ selectInstance(["box", "fragment", "slot1", "body0"]);++ expect(instanceText.onCut?.()).toBeDefined();++ expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([]);+ expect($instances.get().has("box")).toBe(false);+ });++ test("cuts legacy shared slot child from all slot occurrences", () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]),+ createInstance("slot1", "Slot", [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]),+ createInstance("slot2", "Slot", [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]),+ createInstance("box", "Box", []),+ createInstance("heading", "Heading", []),+ ] satisfies Instance[])+ );+ selectInstance(["box", "slot1", "body0"]);++ expect(instanceText.onCut?.()).toBeDefined();++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ expect($instances.get().has("box")).toBe(false);+ });++ test("cuts nested shared slot child from all slot occurrences", () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]),+ createInstance("slot1", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("slot2", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("fragment", "Fragment", [{ type: "id", value: "div" }]),+ createInstance("div", "Box", [{ type: "id", value: "box" }]),+ createInstance("box", "Box", []),+ ] satisfies Instance[])+ );+ selectInstance(["box", "div", "fragment", "slot1", "body0"]);++ expect(instanceText.onCut?.()).toBeDefined();++ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect($instances.get().get("div")?.children).toEqual([]);+ expect($instances.get().has("box")).toBe(false);+ });++ test("cuts shared slot child and preserves shared siblings", () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]),+ createInstance("slot1", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("slot2", "Slot", [{ type: "id", value: "fragment" }]),+ createInstance("fragment", "Fragment", [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]),+ createInstance("box", "Box", []),+ createInstance("heading", "Heading", []),+ ] satisfies Instance[])+ );+ selectInstance(["box", "fragment", "slot1", "body0"]);++ expect(instanceText.onCut?.()).toBeDefined();++ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ expect($instances.get().has("box")).toBe(false);+ });});describe("data sources", () => {diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex 8619b2b96e..fd74491e70 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -1,3 +1,14 @@+import {+ extractWebstudioFragment,+ insertWebstudioFragmentCopy,+} from "../instance-utils/fragment";+import { findClosestInsertable } from "../instance-utils/insert";+import { detectFragmentTokenConflicts } from "../instance-utils/fragment";+import { updateWebstudioData, getWebstudioData } from "../instance-utils/data";+import {+ insertInstanceChildrenMutable,+ type Insertable,+} from "../instance-utils/insert";import { shallowEqual } from "shallow-equal";import { z } from "zod";import { toast } from "@webstudio-is/design-system";@@ -10,18 +21,8 @@ import {portalComponent,} from "@webstudio-is/sdk";import { $instances, $project } from "~/shared/sync/data-stores";-import type { InstanceSelector } from "../tree-utils";-import {- deleteInstanceMutable,- extractWebstudioFragment,- insertWebstudioFragmentCopy,- updateWebstudioData,- getWebstudioData,- insertInstanceChildrenMutable,- findClosestInsertable,- detectFragmentTokenConflicts,- type Insertable,-} from "../instance-utils";+import type { InstanceSelector } from "../instance-utils/tree";+import { deleteInstanceMutable } from "../instance-utils/mutation";import {$selectedInstancePath,$selectedInstanceSelector,diff --git a/apps/builder/app/shared/copy-paste/plugin-markdown.ts b/apps/builder/app/shared/copy-paste/plugin-markdown.tsindex 6a9b6067f2..3cab7261a8 100644--- a/apps/builder/app/shared/copy-paste/plugin-markdown.ts+++ b/apps/builder/app/shared/copy-paste/plugin-markdown.ts@@ -1,6 +1,6 @@import { gfm, gfmHtml } from "micromark-extension-gfm";import { micromark } from "micromark";-import { insertWebstudioFragmentAt } from "../instance-utils";+import { insertWebstudioFragmentAt } from "../instance-utils/insert";import { denormalizeSrcProps } from "./asset-upload";import { generateFragmentFromHtml } from "../html";import type { Plugin } from "./copy-paste";diff --git a/apps/builder/app/shared/copy-paste/plugin-page.ts b/apps/builder/app/shared/copy-paste/plugin-page.tsindex 2c1ca90e9c..59a4526edc 100644--- a/apps/builder/app/shared/copy-paste/plugin-page.ts+++ b/apps/builder/app/shared/copy-paste/plugin-page.ts@@ -1,3 +1,5 @@+import { getWebstudioData } from "../instance-utils/data";+import { updateWebstudioData } from "../instance-utils/data";import { z } from "zod";import { toast } from "@webstudio-is/design-system";import {@@ -9,11 +11,7 @@ import {type PageTemplate,} from "@webstudio-is/sdk";import { $pages } from "~/shared/sync/data-stores";-import {- detectFragmentTokenConflicts,- getWebstudioData,- updateWebstudioData,-} from "../instance-utils";+import { detectFragmentTokenConflicts } from "../instance-utils/fragment";import { builderApi } from "../builder-api";import {createFolderCopyData,diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.ts b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.tsindex de135deb15..2815305ff7 100644--- a/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.ts+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/plugin-webflow.ts@@ -2,9 +2,9 @@ import type { Instance, WebstudioFragment } from "@webstudio-is/sdk";import {findClosestInsertable,insertInstanceChildrenMutable,- insertWebstudioFragmentCopy,- updateWebstudioData,-} from "../../instance-utils";+} from "../../instance-utils/insert";+import { insertWebstudioFragmentCopy } from "../../instance-utils/fragment";+import { updateWebstudioData } from "../../instance-utils/data";import { $project } from "~/shared/sync/data-stores";import {WfData,diff --git a/apps/builder/app/shared/dom-utils.ts b/apps/builder/app/shared/dom-utils.tsindex 7ce61ac76a..1692d0ed5a 100644--- a/apps/builder/app/shared/dom-utils.ts+++ b/apps/builder/app/shared/dom-utils.ts@@ -1,6 +1,6 @@import type { Instance } from "@webstudio-is/sdk";import { idAttribute, selectorIdAttribute } from "@webstudio-is/react-sdk";-import type { InstanceSelector } from "./tree-utils";+import type { InstanceSelector } from "./instance-utils/tree";import { getIsVisuallyHidden } from "./visually-hidden";export const getInstanceIdFromElement = (diff --git a/apps/builder/app/shared/instance-utils.test.tsx b/apps/builder/app/shared/instance-utils.test.tsxdeleted file mode 100644index 9a0fb8907a..0000000000--- a/apps/builder/app/shared/instance-utils.test.tsx+++ /dev/null@@ -1,4903 +0,0 @@-import { enableMapSet } from "immer";-import { describe, test, expect, beforeEach } from "vitest";-import type { Project } from "@webstudio-is/project";-import { createDefaultPages } from "@webstudio-is/project-build";-import {- $,- ws,- css,- expression,- renderTemplate,- renderData,- ResourceValue,- token,-} from "@webstudio-is/template";-import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";-import * as radixMetas from "@webstudio-is/sdk-components-react-radix/metas";-import type {- Asset,- Breakpoint,- Instance,- StyleDecl,- StyleDeclKey,- StyleSource,- WebstudioData,- WebstudioFragment,- WsComponentMeta,-} from "@webstudio-is/sdk";-import {- coreMetas,- getStyleDeclKey,- blockComponent,- blockTemplateComponent,- portalComponent,- elementComponent,- ROOT_INSTANCE_ID,-} from "@webstudio-is/sdk";-import { showAttribute } from "@webstudio-is/react-sdk";-import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";-import {- deleteInstanceMutable,- extractWebstudioFragment,- insertWebstudioFragmentCopy,- reparentInstanceMutable,- getWebstudioData,- insertInstanceChildrenMutable,- findClosestInsertable,- insertWebstudioFragmentAt,- insertWebstudioElementAt,- buildInstancePath,- wrapInstance,- toggleInstanceShow,- detachSharedSlotContentMutable,- unwrapInstance,- unwrapInstanceMutable,- canUnwrapInstance,- canConvertInstance,- convertInstance,- deleteSelectedInstance,- detectPageTokenConflicts,- canDeleteInstanceInContentMode,- __testing__,-} from "./instance-utils";-import type { InstancePath } from "./nano-states";-import { $registeredComponentMetas } from "./nano-states";-import { $assets } from "~/shared/sync/data-stores";-import {- $breakpoints,- $dataSources,- $instances,- $pages,- $project,- $props,- $styleSourceSelections,- $styleSources,- $styles,- $resources,-} from "~/shared/sync/data-stores";-import { registerContainers } from "./sync/sync-stores";-import { $selectedInstanceSelector, getInstancePath } from "./nano-states";-import { selectPage } from "./nano-states";-import { selectInstance } from "./nano-states";-import { $selectedPageId } from "./nano-states/pages";--const {- getFragmentContentModeCapabilities,- getFragmentInstancesData,- insertFragmentAssetsMutable,- insertFragmentBreakpointsMutable,-} = __testing__;--enableMapSet();-registerContainers();--$pages.set(createDefaultPages({ rootInstanceId: "" }));--const defaultMetasMap = new Map(- Object.entries({ ...defaultMetas, ...coreMetas })-);-$registeredComponentMetas.set(defaultMetasMap);--const createFragment = (- fragment: Partial<WebstudioFragment>-): WebstudioFragment => ({- children: [],- instances: [],- styleSourceSelections: [],- styleSources: [],- breakpoints: [],- styles: [],- dataSources: [],- resources: [],- props: [],- assets: [],- ...fragment,-});--const createFakeComponentMetas = (- itemMeta: Partial<WsComponentMeta>,- anotherItemMeta?: Partial<WsComponentMeta>-): Map<string, WsComponentMeta> => {- const base = {- label: "",- Icon: () => null,- };- const configs = {- Item: { ...base, ...itemMeta },- AnotherItem: { ...base, ...anotherItemMeta },- Bold: base,- Text: base,- Form: base,- Box: base,- Div: base,- Body: base,- } as const;- return new Map(Object.entries(configs)) as Map<string, WsComponentMeta>;-};--const getIdValuePair = <T extends { id: string }>(item: T) =>- [item.id, item] as const;--const toMap = <T extends { id: string }>(list: T[]) =>- new Map(list.map(getIdValuePair));--const setDataStores = (data: Omit<WebstudioData, "pages">) => {- $instances.set(data.instances);- $breakpoints.set(data.breakpoints);- $styleSources.set(data.styleSources);- $styles.set(data.styles);- $styleSourceSelections.set(data.styleSourceSelections);- $dataSources.set(data.dataSources);- $props.set(data.props);- $assets.set(data.assets);- $resources.set(data.resources);-};--const createInstance = (- id: Instance["id"],- component: string,- children: Instance["children"]-): Instance => {- return { type: "instance", id, component, children };-};--const createStyleDecl = (- styleSourceId: string,- breakpointId: string,- property: StyleProperty,- value: StyleValue | string-): StyleDecl => ({- styleSourceId,- breakpointId,- property,- value: typeof value === "string" ? { type: "unparsed", value } : value,-});--const createStyleDeclPair = (- styleSourceId: string,- breakpointId: string,- property: StyleProperty,- value: StyleValue | string-): [StyleDeclKey, StyleDecl] => [- `${styleSourceId}:${breakpointId}:${property}:`,- createStyleDecl(styleSourceId, breakpointId, property, value),-];--const createImageAsset = (id: string, name = "", projectId = ""): Asset => {- return {- id,- type: "image",- format: "",- name,- description: "",- projectId,- createdAt: "",- size: 0,- meta: { width: 0, height: 0 },- };-};--const createFontAsset = (id: string, family: string): Asset => {- return {- id,- type: "font",- format: "woff",- name: "",- description: "",- projectId: "",- createdAt: "",- size: 0,- meta: { style: "normal", family, variationAxes: {} },- };-};--describe("fragment copy helpers", () => {- test("builds fragment instance maps and portal content roots", () => {- const fragment = createFragment({- instances: [- createInstance("portal", portalComponent, [- { type: "id", value: "portal-root" },- ]),- createInstance("portal-root", "Box", []),- ],- });-- const { fragmentInstances, portalContentRootIds } =- getFragmentInstancesData(fragment);-- expect(Array.from(fragmentInstances.keys())).toEqual([- "portal",- "portal-root",- ]);- expect(portalContentRootIds).toEqual(new Set(["portal-root"]));- });-- test("inserts fragment assets without overwriting existing assets", () => {- const existingAsset = createImageAsset(- "existing-asset",- "Existing",- "target-project"- );- const assets = new Map<Asset["id"], Asset>([- [existingAsset.id, existingAsset],- ]);-- insertFragmentAssetsMutable({- fragment: createFragment({- assets: [- createImageAsset("existing-asset", "Source Existing", "source"),- createImageAsset("new-asset", "New", "source"),- ],- }),- projectId: "target-project",- assets,- });-- expect(assets.get("existing-asset")).toBe(existingAsset);- expect(assets.get("new-asset")).toEqual({- ...createImageAsset("new-asset", "New", "source"),- projectId: "target-project",- });- });-- test("inserts fragment breakpoints and reports limit merges", () => {- const baseBreakpoint: Breakpoint = { id: "base", label: "Base" };- const breakpoints = new Map<Breakpoint["id"], Breakpoint>([- [baseBreakpoint.id, baseBreakpoint],- ]);- let didMergeDueToLimit = false;-- const mergedBreakpointIds = insertFragmentBreakpointsMutable({- fragment: createFragment({- breakpoints: [- baseBreakpoint,- { id: "desktop", label: "Desktop", minWidth: 1024 },- ],- }),- breakpoints,- onBreakpointLimitMerge: () => {- didMergeDueToLimit = true;- },- });-- expect(mergedBreakpointIds.get("base")).toBe("base");- expect(breakpoints.get("desktop")).toEqual({- id: "desktop",- label: "Desktop",- minWidth: 1024,- });- expect(didMergeDueToLimit).toBe(false);- });-- test("builds content-mode capabilities for fragment roots", () => {- const registeredComponentMetas = $registeredComponentMetas.get();- $registeredComponentMetas.set(- createFakeComponentMetas({- props: {- href: {- type: "string",- control: "url",- required: false,- contentMode: true,- },- },- })- );- try {- const fragment = createFragment({- children: [{ type: "id", value: "link" }],- instances: [createInstance("link", "Item", [])],- props: [- {- id: "href-prop",- instanceId: "link",- name: "href",- type: "string",- value: "/",- },- ],- });- const { fragmentInstances } = getFragmentInstancesData(fragment);-- const capabilities = getFragmentContentModeCapabilities({- fragment,- fragmentInstances,- styleSources: new Map(),- });-- expect(capabilities.contentRootIds).toEqual(new Set(["link"]));- expect(capabilities.editablePropIds.has("href-prop")).toBe(true);- } finally {- $registeredComponentMetas.set(registeredComponentMetas);- }- });-});--describe("canDeleteInstanceInContentMode", () => {- const instances = new Map([- ["body", createInstance("body", "Body", [{ type: "id", value: "block" }])],- [- "block",- createInstance("block", blockComponent, [- { type: "id", value: "child" },- { type: "id", value: "template" },- ]),- ],- [- "child",- createInstance("child", "Box", [{ type: "id", value: "nested" }]),- ],- ["nested", createInstance("nested", "Box", [])],- ["template", createInstance("template", blockTemplateComponent, [])],- ]);-- test("allows deleting direct content block children", () => {- expect(- canDeleteInstanceInContentMode({- instanceSelector: ["child", "block", "body"],- instances,- })- ).toBe(true);- });-- test("protects content block roots, nested descendants, and templates", () => {- expect(- canDeleteInstanceInContentMode({- instanceSelector: ["block", "body"],- instances,- })- ).toBe(false);- expect(- canDeleteInstanceInContentMode({- instanceSelector: ["nested", "child", "block", "body"],- instances,- })- ).toBe(false);- expect(- canDeleteInstanceInContentMode({- instanceSelector: ["template", "block", "body"],- instances,- })- ).toBe(false);- });-});--describe("insert instance children", () => {- test("insert instance children into empty target", () => {- const data = renderData(- <ws.element ws:tag="body" ws:id="bodyId"></ws.element>- );- const [div] = renderTemplate(- <ws.element ws:tag="div" ws:id="divId"></ws.element>- ).instances;- data.instances.set(div.id, div);- insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {- parentSelector: ["bodyId"],- position: "end",- });- expect(data).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="divId"></ws.element>- </ws.element>- )- );- });-- test("insert instance children into the end of target", () => {- const data = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="textId"></ws.element>- </ws.element>- );- const [div] = renderTemplate(- <ws.element ws:tag="div" ws:id="divId"></ws.element>- ).instances;- data.instances.set(div.id, div);- insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {- parentSelector: ["bodyId"],- position: "end",- });- expect(data).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="textId"></ws.element>- <ws.element ws:tag="div" ws:id="divId"></ws.element>- </ws.element>- )- );- });-- test("insert instance children into legacy slot with direct children", () => {- const data = renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slotId">- <$.Box ws:id="boxId"></$.Box>- </$.Slot>- </$.Body>- );- const [div] = renderTemplate(- <ws.element ws:tag="div" ws:id="divId"></ws.element>- ).instances;- data.instances.set(div.id, div);-- insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {- parentSelector: ["slotId", "bodyId"],- position: "end",- });-- const fragmentId = data.instances.get("slotId")?.children[0]?.value;- expect(data).toEqual(- renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slotId">- <$.Fragment ws:id={fragmentId}>- <$.Box ws:id="boxId"></$.Box>- <ws.element ws:tag="div" ws:id="divId"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>- )- );- });-- test("insert instance children into the start of target", () => {- const data = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="textId"></ws.element>- </ws.element>- );- const [div] = renderTemplate(- <ws.element ws:tag="div" ws:id="divId"></ws.element>- ).instances;- data.instances.set(div.id, div);- insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {- parentSelector: ["bodyId"],- position: 0,- });- expect(data).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="divId"></ws.element>- <ws.element ws:tag="div" ws:id="textId"></ws.element>- </ws.element>- )- );- });-- test("insert instance children at the start of text", () => {- const data = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="textId">- text- </ws.element>- </ws.element>- );- const [div] = renderTemplate(- <ws.element ws:tag="div" ws:id="divId"></ws.element>- ).instances;- data.instances.set(div.id, div);- insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {- parentSelector: ["textId", "bodyId"],- position: 0,- });- const [_bodyId, _textId, _divId, spanId] = data.instances.keys();- expect(data).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="textId">- <ws.element ws:tag="div" ws:id="divId"></ws.element>- <ws.element ws:tag="span" ws:id={spanId}>- text- </ws.element>- </ws.element>- </ws.element>- )- );- });-- test("insert instance children at the end of text", () => {- const data = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="textId">- text- </ws.element>- </ws.element>- );- const [div] = renderTemplate(- <ws.element ws:tag="div" ws:id="divId"></ws.element>- ).instances;- data.instances.set(div.id, div);- insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {- parentSelector: ["textId", "bodyId"],- position: "end",- });- const [_bodyId, _textId, _divId, spanId] = data.instances.keys();- expect(data).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="textId">- <ws.element ws:tag="span" ws:id={spanId}>- text- </ws.element>- <ws.element ws:tag="div" ws:id="divId"></ws.element>- </ws.element>- </ws.element>- )- );- });-- test("insert instance children between text children", () => {- const data = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="textId">- <ws.element ws:tag="strong" ws:id="strongId">- strong- </ws.element>- text- <ws.element ws:tag="em" ws:id="emId">- emphasis- </ws.element>- </ws.element>- </ws.element>- );- const [div] = renderTemplate(- <ws.element ws:tag="div" ws:id="divId"></ws.element>- ).instances;- data.instances.set(div.id, div);- insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {- parentSelector: ["textId", "bodyId"],- position: 1,- });- const [- _bodyId,- _textId,- _strongId,- _emId,- _divId,- leftSpanId,- rightSpanId,- ] = data.instances.keys();- expect(data).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="textId">- <ws.element ws:tag="span" ws:id={leftSpanId}>- <ws.element ws:tag="strong" ws:id="strongId">- strong- </ws.element>- </ws.element>- <ws.element ws:tag="div" ws:id="divId"></ws.element>- <ws.element ws:tag="span" ws:id={rightSpanId}>- text- <ws.element ws:tag="em" ws:id="emId">- emphasis- </ws.element>- </ws.element>- </ws.element>- </ws.element>- )- );- });-});--describe("insert webstudio element at", () => {- beforeEach(() => {- $styleSourceSelections.set(new Map());- $styleSources.set(new Map());- $breakpoints.set(new Map());- $styles.set(new Map());- $dataSources.set(new Map());- $resources.set(new Map());- $props.set(new Map());- $assets.set(new Map());- });-- test("insert element with div tag into body", () => {- $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);- insertWebstudioElementAt({- parentSelector: ["bodyId"],- position: "end",- });- const [_bodyId, newInstanceId] = $instances.get().keys();- expect($instances.get()).toEqual(- renderData(- <$.Body ws:id="bodyId">- <ws.element ws:id={newInstanceId} ws:tag="div" />- </$.Body>- ).instances- );- });-- test("insert element with li tag into ul", () => {- $instances.set(- renderData(- <$.Body ws:id="bodyId">- <ws.element ws:id="listId" ws:tag="ul"></ws.element>- </$.Body>- ).instances- );- insertWebstudioElementAt({- parentSelector: ["listId", "bodyId"],- position: "end",- });- const [_bodyId, _listId, newInstanceId] = $instances.get().keys();- expect($instances.get()).toEqual(- renderData(- <$.Body ws:id="bodyId">- <ws.element ws:id="listId" ws:tag="ul">- <ws.element ws:id={newInstanceId} ws:tag="li" />- </ws.element>- </$.Body>- ).instances- );- });-- test("insert element into selected instance", () => {- $pages.set(- createDefaultPages({ homePageId: "homePageId", rootInstanceId: "bodyId" })- );- $instances.set(- renderData(- <$.Body ws:id="bodyId">- <ws.element ws:id="divId" ws:tag="div"></ws.element>- </$.Body>- ).instances- );- selectPage("homePageId");- selectInstance(["divId", "bodyId"]);- insertWebstudioElementAt();- const [_bodyId, _divId, newInstanceId] = $instances.get().keys();- expect($instances.get()).toEqual(- renderData(- <$.Body ws:id="bodyId">- <ws.element ws:id="divId" ws:tag="div">- <ws.element ws:id={newInstanceId} ws:tag="div" />- </ws.element>- </$.Body>- ).instances- );- });-- test("insert element into selected legacy slot with direct children", () => {- $pages.set(- createDefaultPages({ homePageId: "homePageId", rootInstanceId: "bodyId" })- );- $instances.set(- renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slotId">- <$.Box ws:id="boxId"></$.Box>- </$.Slot>- </$.Body>- ).instances- );- selectPage("homePageId");- selectInstance(["slotId", "bodyId"]);-- insertWebstudioElementAt();-- const instances = $instances.get();- const fragmentId = instances.get("slotId")?.children[0]?.value;- const newInstanceId = Array.from(instances.keys()).find(- (id) =>- id !== "bodyId" &&- id !== "slotId" &&- id !== "boxId" &&- id !== fragmentId- );- expect(instances).toEqual(- renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slotId">- <$.Fragment ws:id={fragmentId}>- <$.Box ws:id="boxId"></$.Box>- <ws.element ws:id={newInstanceId} ws:tag="div" />- </$.Fragment>- </$.Slot>- </$.Body>- ).instances- );- });-- test("insert element into closest non-textual container", () => {- $pages.set(- createDefaultPages({ homePageId: "homePageId", rootInstanceId: "bodyId" })- );- $instances.set(- renderData(- <$.Body ws:id="bodyId">- <ws.element ws:id="divId" ws:tag="div">- text- </ws.element>- <ws.element ws:id="spanId" ws:tag="span"></ws.element>- </$.Body>- ).instances- );- selectPage("homePageId");- selectInstance(["divId", "bodyId"]);- insertWebstudioElementAt();- const [_bodyId, _divId, _spanId, newInstanceId] = $instances.get().keys();- expect($instances.get()).toEqual(- renderData(- <$.Body ws:id="bodyId">- <ws.element ws:id="divId" ws:tag="div">- text- </ws.element>- <ws.element ws:id={newInstanceId} ws:tag="div" />- <ws.element ws:id="spanId" ws:tag="span"></ws.element>- </$.Body>- ).instances- );- });-- test("insert element into closest non-empty container", () => {- $pages.set(- createDefaultPages({ homePageId: "homePageId", rootInstanceId: "bodyId" })- );- $instances.set(- renderData(- <$.Body ws:id="bodyId">- <ws.element ws:id="imgId" ws:tag="img"></ws.element>- <ws.element ws:id="spanId" ws:tag="span"></ws.element>- </$.Body>- ).instances- );- selectPage("homePageId");- selectInstance(["imgId", "bodyId"]);- insertWebstudioElementAt();- const [_bodyId, _imgId, _spanId, newInstanceId] = $instances.get().keys();- expect($instances.get()).toEqual(- renderData(- <$.Body ws:id="bodyId">- <ws.element ws:id="imgId" ws:tag="img"></ws.element>- <ws.element ws:id={newInstanceId} ws:tag="div" />- <ws.element ws:id="spanId" ws:tag="span"></ws.element>- </$.Body>- ).instances- );- });-});--describe("insert webstudio fragment at", () => {- beforeEach(() => {- $styleSourceSelections.set(new Map());- $styleSources.set(new Map());- $breakpoints.set(new Map());- $styles.set(new Map());- $dataSources.set(new Map());- $resources.set(new Map());- $props.set(new Map());- $assets.set(new Map());- });-- test("insert multiple instances", () => {- $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);- insertWebstudioFragmentAt(- renderTemplate(- <>- <$.Heading ws:id="headingId"></$.Heading>- <$.Paragraph ws:id="paragraphId"></$.Paragraph>- </>- ),- {- parentSelector: ["bodyId"],- position: "end",- }- );- expect($instances.get()).toEqual(- renderData(- <$.Body ws:id="bodyId">- <$.Heading ws:id={expect.any(String)}></$.Heading>- <$.Paragraph ws:id={expect.any(String)}></$.Paragraph>- </$.Body>- ).instances- );- });-- test("insert fragment after insertable", () => {- $instances.set(- renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId"></$.Box>- </$.Body>- ).instances- );- insertWebstudioFragmentAt(- renderTemplate(<$.Heading ws:id="headingId"></$.Heading>),- {- parentSelector: ["boxId", "bodyId"],- position: "after",- }- );- expect($instances.get()).toEqual(- renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId"></$.Box>- <$.Heading ws:id={expect.any(String)}></$.Heading>- </$.Body>- ).instances- );- });-- test("insert fragment inside of body when configured to place after insertable", () => {- $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);- insertWebstudioFragmentAt(- renderTemplate(<$.Heading ws:id="headingId"></$.Heading>),- {- parentSelector: ["bodyId"],- position: "after",- }- );- expect($instances.get()).toEqual(- renderData(- <$.Body ws:id="bodyId">- <$.Heading ws:id={expect.any(String)}></$.Heading>- </$.Body>- ).instances- );- });-});--describe("reparent instance", () => {- test("between instances", () => {- const data = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box">- <$.Text ws:id="text"></$.Text>- </$.Box>- <$.Button ws:id="button"></$.Button>- </$.Body>- );- $registeredComponentMetas.set(createFakeComponentMetas({}));- reparentInstanceMutable(data, ["text", "box", "body"], {- parentSelector: ["body"],- position: 1,- });- const newTextId = data.instances.get("body")?.children[1].value as string;- expect(data.instances).toEqual(- renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- <$.Text ws:id={newTextId}></$.Text>- <$.Button ws:id="button"></$.Button>- </$.Body>- ).instances- );- });-- test("to the end", () => {- const data = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box">- <$.Text ws:id="text"></$.Text>- </$.Box>- </$.Body>- );- $registeredComponentMetas.set(createFakeComponentMetas({}));- reparentInstanceMutable(data, ["text", "box", "body"], {- parentSelector: ["body"],- position: "end",- });- const newTextId = data.instances.get("body")?.children[1].value as string;- expect(data.instances).toEqual(- renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- <$.Text ws:id={newTextId}></$.Text>- </$.Body>- ).instances- );- });-- test("before itself", () => {- const data = renderData(- <$.Body ws:id="body">- <$.Text ws:id="text"></$.Text>- <$.Box ws:id="box"></$.Box>- <$.Button ws:id="button"></$.Button>- </$.Body>- );- $registeredComponentMetas.set(createFakeComponentMetas({}));- reparentInstanceMutable(data, ["box", "body"], {- parentSelector: ["body"],- position: 1,- });- expect(data.instances).toEqual(- renderData(- <$.Body ws:id="body">- <$.Text ws:id="text"></$.Text>- <$.Box ws:id="box"></$.Box>- <$.Button ws:id="button"></$.Button>- </$.Body>- ).instances- );- });-- test("after itself", () => {- const data = renderData(- <$.Body ws:id="body">- <$.Text ws:id="text"></$.Text>- <$.Box ws:id="box"></$.Box>- <$.Button ws:id="button"></$.Button>- </$.Body>- );- $registeredComponentMetas.set(createFakeComponentMetas({}));- reparentInstanceMutable(data, ["box", "body"], {- parentSelector: ["body"],- position: 2,- });- expect(data.instances).toEqual(- renderData(- <$.Body ws:id="body">- <$.Text ws:id="text"></$.Text>- <$.Box ws:id="box"></$.Box>- <$.Button ws:id="button"></$.Button>- </$.Body>- ).instances- );- });-- test("wrap with fragment when reparent into empty slot", () => {- const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot"></$.Slot>- <$.Box ws:id="box"></$.Box>- </$.Body>- );- $registeredComponentMetas.set(createFakeComponentMetas({}));- reparentInstanceMutable(data, ["box", "body"], {- parentSelector: ["slot", "body"],- position: "end",- });- const newFragmentId = data.instances.get("slot")?.children[0]- .value as string;- const newBoxId = data.instances.get(newFragmentId)?.children[0]- .value as string;- expect(data.instances).toEqual(- renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id={newFragmentId}>- <$.Box ws:id={newBoxId}></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>- ).instances- );- });-- test("reuse existing fragment when reparent into slot", () => {- const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id="fragment"></$.Fragment>- </$.Slot>- <$.Box ws:id="box"></$.Box>- </$.Body>- );- $registeredComponentMetas.set(createFakeComponentMetas({}));- reparentInstanceMutable(data, ["box", "body"], {- parentSelector: ["slot", "body"],- position: "end",- });- const newBoxId = data.instances.get("fragment")?.children[0]- .value as string;- expect(data.instances).toEqual(- renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id="fragment">- <$.Box ws:id={newBoxId}></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>- ).instances- );- });-- test("reparent slot child from one instance of this slot into another", () => {- const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">- {/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>- );- $registeredComponentMetas.set(createFakeComponentMetas({}));- reparentInstanceMutable(data, ["box", "fragment", "slot1", "body"], {- parentSelector: ["slot2", "body"],- position: "end",- });- expect(data.instances).toEqual(- renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">- {/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>- ).instances- );- });-- test("sort shared slot content through visible slot drop target", () => {- const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <$.Box ws:id="box1"></$.Box>- <$.Box ws:id="box2"></$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">- {/* same ids */}- <$.Fragment ws:id="fragment">- <$.Box ws:id="box1"></$.Box>- <$.Box ws:id="box2"></$.Box>- <$.Box ws:id="box3"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>- );- $registeredComponentMetas.set(createFakeComponentMetas({}));-- reparentInstanceMutable(data, ["box1", "fragment", "slot1", "body"], {- parentSelector: ["slot2", "body"],- position: 3,- });-- expect(data.instances.get("slot1")?.children).toEqual([- { type: "id", value: "fragment" },- ]);- expect(data.instances.get("slot2")?.children).toEqual([- { type: "id", value: "fragment" },- ]);- expect(data.instances.get("fragment")?.children).toEqual([- { type: "id", value: "box2" },- { type: "id", value: "box3" },- { type: "id", value: "box1" },- ]);- });-- test("reparent only selected slot occurrence", () => {- const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">- {/* same ids */}- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>- );- $project.set({ id: "projectId" } as Project);- $registeredComponentMetas.set(createFakeComponentMetas({}));-- reparentInstanceMutable(data, ["div", "fragment", "slot1", "body"], {- parentSelector: ["body"],- position: "end",- });-- expect(data.instances.get("slot1")?.children).toEqual([]);- expect(data.instances.get("slot2")?.children).toEqual([- { type: "id", value: "fragment" },- ]);- expect(data.instances.get("fragment")?.children).toEqual([- { type: "id", value: "div" },- ]);- expect(data.instances.get("body")?.children.at(-1)?.type).toBe("id");- expect(data.instances.get("body")?.children.at(-1)?.value).not.toBe(- "slot2"- );- });-- test("prevent slot reparenting into own children to avoid infinite loop", () => {- const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id="fragment"></$.Fragment>- </$.Slot>- </$.Body>- );- $registeredComponentMetas.set(createFakeComponentMetas({}));- reparentInstanceMutable(data, ["slot", "body"], {- parentSelector: ["fragment", "slot", "body"],- position: "end",- });- expect(data.instances).toEqual(- renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id="fragment"></$.Fragment>- </$.Slot>- </$.Body>- ).instances- );- });-- test("from collection item", () => {- const data = renderData(- <$.Body ws:id="body">- <ws.collection ws:id="collection">- <$.Box ws:id="box"></$.Box>- </ws.collection>- </$.Body>- );- $registeredComponentMetas.set(createFakeComponentMetas({}));- reparentInstanceMutable(- data,- ["box", "collection[0]", "collection", "body"],- { parentSelector: ["body"], position: "end" }- );- const newBoxId = data.instances.get("body")?.children[1].value as string;- expect(data.instances).toEqual(- renderData(- <$.Body ws:id="body">- <ws.collection ws:id="collection"></ws.collection>- <$.Box ws:id={newBoxId}></$.Box>- </$.Body>- ).instances- );- });-- test("move required child within same instance", () => {- const data = renderData(- <$.Body ws:id="body">- <$.Tooltip ws:id="tooltip">- <$.TooltipTrigger ws:id="trigger"></$.TooltipTrigger>- <$.TooltipContent ws:id="content"></$.TooltipContent>- </$.Tooltip>- </$.Body>- );- $registeredComponentMetas.set(- new Map(Object.entries({ ...defaultMetas, ...radixMetas }))- );- reparentInstanceMutable(data, ["trigger", "tooltip", "body"], {- parentSelector: ["tooltip", "body"],- position: "end",- });- expect(data.instances).toEqual(- renderData(- <$.Body ws:id="body">- <$.Tooltip ws:id="tooltip">- <$.TooltipContent ws:id="content"></$.TooltipContent>- <$.TooltipTrigger ws:id={expect.any(String)}></$.TooltipTrigger>- </$.Tooltip>- </$.Body>- ).instances- );- });-});--const getWebstudioDataStub = (- 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", () => {- const data = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.Box ws:id="sectionId"></$.Box>- </$.Box>- <$.Box ws:id="divId"></$.Box>- </$.Body>- );- expect(data.instances.size).toEqual(4);- expect(data.instances.get("bodyId")?.children.length).toEqual(2);- deleteInstanceMutable(- data,- // clone to make sure data is mutated instead of instance path- structuredClone(getInstancePath(["boxId", "bodyId"], data.instances))- );- expect(data.instances.size).toEqual(2);- expect(data.instances.get("bodyId")?.children.length).toEqual(1);- });-- test("delete instance from collection", () => {- const data = renderData(- <$.Body ws:id="bodyId">- <ws.collection ws:id="collectionId">- <$.Box ws:id="boxId"></$.Box>- </ws.collection>- </$.Body>- );- expect(data.instances.size).toEqual(3);- expect(data.instances.get("collectionId")?.children.length).toEqual(1);- deleteInstanceMutable(- data,- getInstancePath(- ["boxId", "collectionId[0]", "collectionId", "bodyId"],- data.instances- )- );- expect(data.instances.size).toEqual(2);- expect(data.instances.get("collectionId")?.children.length).toEqual(0);- });-- test("delete instance from collection item", () => {- const data = renderData(- <$.Body ws:id="bodyId">- <ws.collection ws:id="collectionId">- <$.Box ws:id="boxId">- <$.Text ws:id="textId"></$.Text>- </$.Box>- </ws.collection>- </$.Body>- );- expect(data.instances.size).toEqual(4);- expect(data.instances.get("boxId")?.children.length).toEqual(1);- deleteInstanceMutable(- data,- getInstancePath(- ["textId", "boxId", "collectionId[0]", "collectionId", "bodyId"],- data.instances- )- );- expect(data.instances.size).toEqual(3);- expect(data.instances.get("boxId")?.children.length).toEqual(0);- });-- test("delete resource bound to variable", () => {- const myResource = new ResourceValue("My Resource", {- url: expression`""`,- method: "get",- searchParams: [],- headers: [],- });- const data = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId" vars={expression`${myResource}`}></$.Box>- </$.Body>- );- expect(data.resources.size).toEqual(1);- expect(data.dataSources.size).toEqual(1);- deleteInstanceMutable(- data,- getInstancePath(["boxId", "bodyId"], data.instances)- );- expect(data.resources.size).toEqual(0);- expect(data.dataSources.size).toEqual(0);- });-- test("delete resource bound to prop", () => {- const myResource = new ResourceValue("My Resource", {- url: expression`""`,- method: "get",- searchParams: [],- headers: [],- });- const data = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId" action={myResource}></$.Box>- </$.Body>- );- expect(data.resources.size).toEqual(1);- expect(data.props.size).toEqual(1);- deleteInstanceMutable(- data,- getInstancePath(["boxId", "bodyId"], data.instances)- );- expect(data.resources.size).toEqual(0);- expect(data.props.size).toEqual(0);- });-- test("delete unknown instance (just in case)", () => {- const data = renderData(- <$.Body ws:id="bodyId">- <$.Invalid ws:id="invalidId"></$.Invalid>- </$.Body>- );- expect(data.instances.size).toEqual(2);- deleteInstanceMutable(- data,- getInstancePath(["invalidId", "bodyId"], data.instances)- );- expect(data.instances.size).toEqual(1);- });-- test("delete slot fragment along with last child", () => {- const data = renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slotId">- <$.Fragment ws:id="fragmentId">- <$.Box ws:id="boxId"></$.Box>- </$.Fragment>- </$.Slot>- </$.Body>- );- expect(data.instances.size).toEqual(4);- expect(data.instances.get("fragmentId")?.children.length).toEqual(1);- deleteInstanceMutable(- data,- getInstancePath(- ["boxId", "fragmentId", "slotId", "bodyId"],- data.instances- )- );- expect(data.instances.size).toEqual(2);- expect(data.instances.get("slotId")?.children.length).toEqual(0);- });-- test("delete shared slot content from all slot occurrences", () => {- const data = renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">- {/* same ids */}- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>- );-- deleteInstanceMutable(- data,- getInstancePath(["div", "fragment", "slot1", "bodyId"], data.instances)- );-- expect(data.instances.get("slot1")?.children).toEqual([- { type: "id", value: "fragment" },- ]);- expect(data.instances.get("slot2")?.children).toEqual([- { type: "id", value: "fragment" },- ]);- expect(data.instances.get("fragment")?.children).toEqual([]);- expect(data.instances.has("div")).toEqual(false);- });-});--describe("wrap in", () => {- test("wrap instance in link", () => {- $instances.set(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="divId"></ws.element>- </ws.element>- ).instances- );- selectInstance(["divId", "bodyId"]);- wrapInstance(elementComponent, "a");- expect($instances.get()).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="a" ws:id={expect.any(String)}>- <ws.element ws:tag="div" ws:id="divId"></ws.element>- </ws.element>- </ws.element>- ).instances- );- });-- test("wrap image in element", () => {- $instances.set(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="img" ws:id="imageId"></ws.element>- </ws.element>- ).instances- );- selectInstance(["imageId", "bodyId"]);- wrapInstance(elementComponent);- expect($instances.get()).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id={expect.any(String)}>- <ws.element ws:tag="img" ws:id="imageId"></ws.element>- </ws.element>- </ws.element>- ).instances- );- });-- test("wrap only selected slot occurrence", () => {- $registeredComponentMetas.set(defaultMetasMap);- $instances.set(- renderData(- <$.Body ws:id="bodyId">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">- {/* same ids */}- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>- ).instances- );- selectInstance(["div", "fragment", "slot1", "bodyId"]);-- wrapInstance(elementComponent, "div");-- expect($instances.get().get("slot1")?.children).not.toEqual(- $instances.get().get("slot2")?.children- );- expect($instances.get().get("slot2")?.children).toEqual([- { type: "id", value: "fragment" },- ]);- expect($instances.get().get("fragment")?.children).toEqual([- { type: "id", value: "div" },- ]);- });-- test("avoid wrapping text with link in link", () => {- const { instances } = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="p" ws:id="textId">- <ws.element ws:tag="a" ws:id="linkId"></ws.element>- </ws.element>- </ws.element>- );- $instances.set(instances);- selectInstance(["textId", "bodyId"]);- wrapInstance(elementComponent, "a");- // nothing is changed- expect($instances.get()).toEqual(instances);- });-- test("avoid wrapping textual content", () => {- const { instances } = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="textId">- <ws.element ws:tag="bold" ws:id="boldId"></ws.element>- </ws.element>- </ws.element>- );- $instances.set(instances);- selectInstance(["boldId", "textId", "bodyId"]);- wrapInstance(elementComponent);- // nothing is changed- expect($instances.get()).toEqual(instances);- });-- test("avoid wrapping list item", () => {- const { instances } = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="ul" ws:id="listId">- <ws.element ws:tag="li" ws:id="listItemId"></ws.element>- </ws.element>- </ws.element>- );- $instances.set(instances);- selectInstance(["listItemId", "listId", "bodyId"]);- wrapInstance(elementComponent);- // nothing is changed- expect($instances.get()).toEqual(instances);- });-});--describe("extract webstudio fragment", () => {- test("collect all styles and breakpoints bound to fragment instances", () => {- // body- // box1- // box2- $instances.set(- toMap([- createInstance("body", "Body", [{ type: "id", value: "box1" }]),- createInstance("box1", "Box", [{ type: "id", value: "box2" }]),- createInstance("box2", "Box", []),- ])- );- $styleSourceSelections.set(- new Map([- ["body", { instanceId: "box1", values: ["localBody", "token1"] }],- ["box1", { instanceId: "box1", values: ["localBox1", "token2"] }],- ["box2", { instanceId: "box2", values: ["localBox2", "token2"] }],- ])- );- $styleSources.set(- new Map([- ["localBody", { id: "localBody", type: "local" }],- ["localBox1", { id: "localBox1", type: "local" }],- ["localBox2", { id: "localBox2", type: "local" }],- ["token1", { id: "token1", type: "token", name: "token1" }],- ["token2", { id: "token2", type: "token", name: "token2" }],- ])- );- $styles.set(- new Map([- createStyleDeclPair("localBody1", "base", "color", "red"),- createStyleDeclPair("localBox1", "base", "color", "green"),- createStyleDeclPair("localBox2", "base", "color", "blue"),- createStyleDeclPair("token1", "base", "color", "yellow"),- createStyleDeclPair("token2", "base", "color", "orange"),- ])- );- $breakpoints.set(- new Map([- ["base", { id: "base", label: "base" }],- ["big", { id: "big", label: "big", minWidth: 768 }],- ])- );- const { styleSources, styleSourceSelections, styles, breakpoints } =- extractWebstudioFragment(getWebstudioData(), "box1");-- // exclude localBody and token1 bound to body- expect(styleSources).toEqual([- { id: "localBox1", type: "local" },- { id: "token2", type: "token", name: "token2" },- { id: "localBox2", type: "local" },- ]);- expect(styleSourceSelections).toEqual([- { instanceId: "box1", values: ["localBox1", "token2"] },- { instanceId: "box2", values: ["localBox2", "token2"] },- ]);- expect(styles).toEqual([- createStyleDecl("localBox1", "base", "color", "green"),- createStyleDecl("localBox2", "base", "color", "blue"),- createStyleDecl("token2", "base", "color", "orange"),- ]);- expect(breakpoints).toEqual([{ id: "base", label: "base" }]);- });-- test("collect assets from props and styles withiin fragment instances", () => {- // body- // box1- // box2- $instances.set(- toMap([- createInstance("body", "Body", [{ type: "id", value: "box1" }]),- createInstance("box1", "Box", [{ type: "id", value: "box2" }]),- createInstance("box2", "Box", []),- ])- );- $props.set(- new Map([- [- "bodyProp",- {- id: "bodyProp",- instanceId: "body",- name: "data-body",- type: "asset",- value: "asset1",- },- ],- [- "box1Prop",- {- id: "box1Prop",- instanceId: "box1",- name: "data-box1",- type: "asset",- value: "asset2",- },- ],- ])- );- $styleSourceSelections.set(- new Map([- ["body", { instanceId: "box1", values: ["localBody"] }],- ["box1", { instanceId: "box1", values: ["localBox1"] }],- ])- );- $styleSources.set(- new Map([- ["localBody", { id: "localBody", type: "local" }],- ["localBox1", { id: "localBox1", type: "local" }],- ])- );- $styles.set(- new Map([- createStyleDeclPair("localBody1", "base", "fontFamily", {- type: "fontFamily",- value: ["font1"],- }),- createStyleDeclPair("localBody1", "base", "backgroundImage", {- type: "image",- value: { type: "asset", value: "asset3" },- }),- createStyleDeclPair("localBox1", "base", "fontFamily", {- type: "fontFamily",- value: ["font2"],- }),- createStyleDeclPair("localBox1", "base", "color", {- type: "image",- value: { type: "asset", value: "asset4" },- }),- ])- );- $breakpoints.set(new Map([["base", { id: "base", label: "base" }]]));- $assets.set(- toMap([- createImageAsset("asset1"),- createImageAsset("asset2"),- createImageAsset("asset3"),- createImageAsset("asset4"),- createFontAsset("asset5", "font1"),- createFontAsset("asset6", "font2"),- ])- );- const { assets } = extractWebstudioFragment(getWebstudioData(), "box1");-- expect(assets).toEqual([- createImageAsset("asset2"),- createImageAsset("asset4"),- createFontAsset("asset6", "font2"),- ]);- });-});--describe("insert webstudio fragment copy", () => {- const emptyFragment = {- children: [],- instances: [- {- id: "body",- type: "instance",- component: "Body",- children: [],- } satisfies Instance,- ],- styleSourceSelections: [],- styleSources: [],- breakpoints: [],- styles: [],- dataSources: [],- resources: [],- props: [],- assets: [],- };-- $project.set({ id: "current_project" } as Project);-- beforeEach(() => {- $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("duplicate only selected slot occurrence", () => {- const data = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">- {/* same ids */}- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>- );-- const instancePath = detachSharedSlotContentMutable(- data,- getInstancePath(["div", "fragment", "slot1", "body"], data.instances) ??- []- );- const selectedItem = instancePath[0];- const parentItem = instancePath[1];- if (selectedItem === undefined || parentItem === undefined) {- throw Error("Expected selected and parent items");- }-- const fragment = extractWebstudioFragment(data, selectedItem.instance.id);- const { newInstanceIds } = insertWebstudioFragmentCopy({- data,- fragment,- availableVariables: [],- projectId: "current_project",- });- const newRootInstanceId = newInstanceIds.get(selectedItem.instance.id);- if (newRootInstanceId === undefined) {- throw Error("Expected duplicate instance id");- }- data.instances.get(parentItem.instance.id)?.children.splice(1, 0, {- type: "id",- value: newRootInstanceId,- });-- expect(data.instances.get("slot2")?.children).toEqual([- { type: "id", value: "fragment" },- ]);- expect(data.instances.get("fragment")?.children).toEqual([- { type: "id", value: "div" },- ]);- });-- test("insert assets with same ids if missing", () => {- const data = getWebstudioDataStub();- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- assets: [createImageAsset("asset1", "name", "another_project")],- },- availableVariables: [],- projectId: "current_project",- });- expect(Array.from(data.assets.values())).toEqual([- createImageAsset("asset1", "name", "current_project"),- ]);-- data.assets = toMap([- createImageAsset("asset1", "changed_name", "current_project"),- ]);- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- assets: [- createImageAsset("asset1", "name", "another_project"),- createImageAsset("asset2", "another_name", "another_project"),- ],- },- availableVariables: [],- projectId: "current_project",- });- expect(Array.from(data.assets.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("copies local styles with new ids and reuses existing token styles in content mode", () => {- const localStyleSource: StyleSource = { type: "local", id: "localBox" };- const unsupportedLocalStyleSource: StyleSource = {- type: "local",- id: "unsupportedLocal",- };- const tokenStyleSource: StyleSource = {- type: "token",- id: "token",- name: "Token",- };- const style = createStyleDecl("localBox", "base", "color", "red");- const unsupportedBreakpointStyle = createStyleDecl(- "localBox",- "desktop",- "backgroundColor",- "blue"- );- const unsupportedLocalStyle = createStyleDecl(- "unsupportedLocal",- "desktop",- "color",- "green"- );- const data = getWebstudioDataStub({- breakpoints: toMap<Breakpoint>([{ id: "base", label: "Base" }]),- instances: toMap([- createInstance("body", "Body", []),- createInstance("templateBox", "Box", []),- ]),- styleSources: toMap([- localStyleSource,- unsupportedLocalStyleSource,- tokenStyleSource,- ]),- styleSourceSelections: new Map([- [- "templateBox",- {- instanceId: "templateBox",- values: ["localBox", "unsupportedLocal", "token"],- },- ],- ]),- styles: new Map([- [getStyleDeclKey(style), style],- [- getStyleDeclKey(unsupportedBreakpointStyle),- unsupportedBreakpointStyle,- ],- [getStyleDeclKey(unsupportedLocalStyle), unsupportedLocalStyle],- ]),- });- const fragment = createFragment({- children: [{ type: "id", value: "templateBox" }],- instances: [createInstance("templateBox", "Box", [])],- styleSources: [- localStyleSource,- unsupportedLocalStyleSource,- tokenStyleSource,- ],- styleSourceSelections: [- {- instanceId: "templateBox",- values: ["localBox", "unsupportedLocal", "token"],- },- ],- styles: [style, unsupportedBreakpointStyle, unsupportedLocalStyle],- });-- const { newInstanceIds } = insertWebstudioFragmentCopy({- data,- fragment,- availableVariables: [],- projectId: "current_project",- contentMode: true,- });- const newInstanceId = newInstanceIds.get("templateBox");-- expect(newInstanceId).toBeDefined();- const selection = data.styleSourceSelections.get(newInstanceId ?? "");- expect(selection).toEqual({- instanceId: newInstanceId,- values: [expect.any(String), "token"],- });- const newLocalStyleSourceId = selection?.values[0];- expect(newLocalStyleSourceId).not.toBe("localBox");- expect(data.styleSources.get(newLocalStyleSourceId ?? "")).toEqual({- type: "local",- id: newLocalStyleSourceId,- });- expect(data.styles.get(getStyleDeclKey(style))).toEqual(style);- expect(- data.styles.get(- getStyleDeclKey({- ...style,- styleSourceId: newLocalStyleSourceId ?? "",- })- )- ).toEqual({ ...style, styleSourceId: newLocalStyleSourceId });- expect(- data.styles.has(- getStyleDeclKey({- ...unsupportedBreakpointStyle,- styleSourceId: newLocalStyleSourceId ?? "",- })- )- ).toBe(false);- expect(- Array.from(data.styleSources.values()).some(- (styleSource) =>- styleSource.type === "local" &&- styleSource.id !== "localBox" &&- styleSource.id !== "unsupportedLocal" &&- styleSource.id !== newLocalStyleSourceId- )- ).toBe(false);- });-- test("copies assets and asset props in content mode", () => {- const asset = createImageAsset("asset", "Template image", "source_project");- const data = getWebstudioDataStub();- $registeredComponentMetas.set(- new Map([- ...defaultMetasMap,- [- "Item",- {- label: "Item",- icon: "",- props: {- image: {- type: "string",- control: "text",- required: false,- contentMode: true,- },- },- } satisfies WsComponentMeta,- ],- ])- );- const fragment = createFragment({- children: [{ type: "id", value: "item" }],- instances: [createInstance("item", "Item", [])],- props: [- {- id: "image",- instanceId: "item",- name: "image",- type: "asset",- value: "asset",- },- ],- assets: [asset],- });-- const { newInstanceIds } = insertWebstudioFragmentCopy({- data,- fragment,- availableVariables: [],- projectId: "current_project",- contentMode: true,- });- const newInstanceId = newInstanceIds.get("item");-- expect(data.assets.get("asset")).toEqual({- ...asset,- projectId: "current_project",- });- expect(Array.from(data.props.values())).toEqual([- expect.objectContaining({- instanceId: newInstanceId,- name: "image",- type: "asset",- value: "asset",- }),- ]);- });-- test("copies tag-derived content mode props for generic elements", () => {- const data = getWebstudioDataStub();- const fragment = createFragment({- children: [{ type: "id", value: "image" }],- instances: [- {- type: "instance",- id: "image",- component: elementComponent,- tag: "img",- children: [],- },- ],- props: [- {- id: "alt",- instanceId: "image",- name: "alt",- type: "string",- value: "Description",- },- {- id: "class",- instanceId: "image",- name: "class",- type: "string",- value: "card",- },- ],- });-- const { newInstanceIds } = insertWebstudioFragmentCopy({- data,- fragment,- availableVariables: [],- projectId: "current_project",- contentMode: true,- });- const newInstanceId = newInstanceIds.get("image");-- expect(newInstanceId).toBeDefined();- expect(Array.from(data.props.values())).toEqual([- expect.objectContaining({- instanceId: newInstanceId,- name: "alt",- type: "string",- value: "Description",- }),- ]);- });-- test("merge breakpoints with existing ones", () => {- const breakpoints = toMap<Breakpoint>([- { id: "existing_base", label: "base" },- { id: "existing_small", label: "small", minWidth: 768 },- ]);- const data = getWebstudioDataStub({ breakpoints });- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- breakpoints: [- { id: "new_base", label: "Base" },- {- id: "new_small",- label: "Small",- minWidth: 768,- },- {- id: "new_large",- label: "Large",- minWidth: 1200,- },- ],- },- availableVariables: [],- projectId: "",- });- expect(Array.from(data.breakpoints.values())).toEqual([- { id: "existing_base", label: "base" },- { id: "existing_small", label: "small", minWidth: 768 },- { id: "new_large", label: "Large", minWidth: 1200 },- ]);- });-- test("reports breakpoint limit merge once when inserting fragment", () => {- const breakpoints = toMap<Breakpoint>([- { id: "base", label: "base" },- { id: "0", label: "320", maxWidth: 320 },- { id: "1", label: "480", maxWidth: 480 },- { id: "2", label: "768", maxWidth: 768 },- { id: "3", label: "1024", maxWidth: 1024 },- { id: "4", label: "1280", minWidth: 1280 },- { id: "5", label: "1440", minWidth: 1440 },- { id: "6", label: "1920", minWidth: 1920 },- { id: "7", label: "2560", minWidth: 2560 },- ]);- const data = getWebstudioDataStub({ breakpoints });- let mergeCount = 0;-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- breakpoints: [- { id: "new_medium", label: "Medium", minWidth: 1500 },- { id: "new_large", label: "Large", minWidth: 1700 },- ],- },- availableVariables: [],- projectId: "",- onBreakpointLimitMerge: () => {- mergeCount += 1;- },- });-- expect(mergeCount).toBe(1);- });-- // Case 2: Same styles AND same name -> reuse existing token- test("token with same styles and same name reuses existing token", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources = toMap<StyleSource>([- { id: "existingToken", type: "token", name: "primaryColor" },- ]);- const styles = new Map([- createStyleDeclPair("existingToken", "base", "color", {- type: "keyword",- value: "red",- }),- createStyleDeclPair("existingToken", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ]);- const data = getWebstudioDataStub({ breakpoints, styleSources, styles });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- breakpoints: [{ id: "base", label: "base" }],- styleSources: [- // Same name "primaryColor", same styles, different id- { id: "newToken", type: "token", name: "primaryColor" },- ],- styles: [- {- styleSourceId: "newToken",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- {- styleSourceId: "newToken",- breakpointId: "base",- property: "fontSize",- value: { type: "unit", value: 16, unit: "px" },- },- ],- },- availableVariables: [],- projectId: "",- });-- // Should reuse existing token, not create a new one- expect(Array.from(data.styleSources.values())).toEqual([- { id: "existingToken", type: "token", name: "primaryColor" },- ]);- // No new styles should be added- expect(Array.from(data.styles.values())).toEqual([- {- styleSourceId: "existingToken",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- {- styleSourceId: "existingToken",- breakpointId: "base",- property: "fontSize",- value: { type: "unit", value: 16, unit: "px" },- },- ]);- });-- // Case 3: Same styles but different name -> insert new token with original name- test("token with same styles but different name inserts new token", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "primaryColor" },- ]);- const styles = new Map([- createStyleDeclPair("token1", "base", "color", {- type: "keyword",- value: "red",- }),- ]);- const data = getWebstudioDataStub({ breakpoints, styleSources, styles });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- breakpoints: [{ id: "base", label: "base" }],- styleSources: [- // Different name "accentColor", same styles- { id: "token2", type: "token", name: "accentColor" },- ],- styles: [- {- styleSourceId: "token2",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- },- availableVariables: [],- projectId: "",- });-- // Should insert new token with its original name- const tokens = Array.from(data.styleSources.values());- expect(tokens).toHaveLength(2);- expect(tokens[0]).toEqual({- id: "token1",- type: "token",- name: "primaryColor",- });- expect(tokens[1]).toMatchObject({ type: "token", name: "accentColor" });- expect(tokens[1].id).not.toBe("token2"); // Should have new ID-- const tokenStyles = Array.from(data.styles.values());- expect(tokenStyles).toHaveLength(2);- expect(tokenStyles[0]).toEqual({- styleSourceId: "token1",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- });- expect(tokenStyles[1]).toMatchObject({- styleSourceId: tokens[1].id, // Should reference new token ID- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- });- });-- // Case 4: Different styles but same name -> add counter suffix- test("token with different styles but same name adds counter suffix", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "myToken" },- ]);- const styles = new Map([- createStyleDeclPair("token1", "base", "color", {- type: "keyword",- value: "blue",- }),- ]);- const data = getWebstudioDataStub({ breakpoints, styleSources, styles });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- breakpoints: [{ id: "base", label: "base" }],- styleSources: [- // Same name "myToken", different styles- { id: "token2", type: "token", name: "myToken" },- ],- styles: [- {- styleSourceId: "token2",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- },- availableVariables: [],- projectId: "",- });-- // Should add counter suffix to the new token- const tokens = Array.from(data.styleSources.values());- expect(tokens).toHaveLength(2);- expect(tokens[0]).toEqual({ id: "token1", type: "token", name: "myToken" });- expect(tokens[1]).toMatchObject({ type: "token", name: "myToken-1" });- expect(tokens[1].id).not.toBe("token2"); // Should have new ID-- const tokenStyles = Array.from(data.styles.values());- expect(tokenStyles).toHaveLength(2);- expect(tokenStyles[0]).toEqual({- styleSourceId: "token1",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "blue" },- });- expect(tokenStyles[1]).toMatchObject({- styleSourceId: tokens[1].id,- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- });- });-- // Case 4b: Multiple counter suffixes- test("token with name conflict increments counter correctly", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "myToken" },- { id: "token2", type: "token", name: "myToken-1" },- { id: "token3", type: "token", name: "myToken-2" },- ]);- const styles = new Map([- createStyleDeclPair("token1", "base", "color", {- type: "keyword",- value: "blue",- }),- createStyleDeclPair("token2", "base", "color", {- type: "keyword",- value: "green",- }),- createStyleDeclPair("token3", "base", "color", {- type: "keyword",- value: "yellow",- }),- ]);- const data = getWebstudioDataStub({ breakpoints, styleSources, styles });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- breakpoints: [{ id: "base", label: "base" }],- styleSources: [{ id: "token4", type: "token", name: "myToken" }],- styles: [- {- styleSourceId: "token4",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- },- availableVariables: [],- projectId: "",- });-- // Should use counter 3- const tokens = Array.from(data.styleSources.values());- expect(tokens).toHaveLength(4);- expect(tokens[0]).toEqual({ id: "token1", type: "token", name: "myToken" });- expect(tokens[1]).toEqual({- id: "token2",- type: "token",- name: "myToken-1",- });- expect(tokens[2]).toEqual({- id: "token3",- type: "token",- name: "myToken-2",- });- expect(tokens[3]).toMatchObject({ type: "token", name: "myToken-3" });- expect(tokens[3].id).not.toBe("token4"); // Should have new ID- });-- // Case 6: Different styles and different name -> insert as-is- test("token with different styles and different name inserts normally", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "primaryColor" },- ]);- const styles = new Map([- createStyleDeclPair("token1", "base", "color", {- type: "keyword",- value: "blue",- }),- ]);- const data = getWebstudioDataStub({ breakpoints, styleSources, styles });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- breakpoints: [{ id: "base", label: "base" }],- styleSources: [{ id: "token2", type: "token", name: "secondaryColor" }],- styles: [- {- styleSourceId: "token2",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- },- availableVariables: [],- projectId: "",- });-- // Should insert new token normally- const tokens = Array.from(data.styleSources.values());- expect(tokens).toHaveLength(2);- expect(tokens[0]).toEqual({- id: "token1",- type: "token",- name: "primaryColor",- });- expect(tokens[1]).toMatchObject({ type: "token", name: "secondaryColor" });- expect(tokens[1].id).not.toBe("token2"); // Should have new ID-- const tokenStyles = Array.from(data.styles.values());- expect(tokenStyles).toHaveLength(2);- expect(tokenStyles[0]).toEqual({- styleSourceId: "token1",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "blue" },- });- expect(tokenStyles[1]).toMatchObject({- styleSourceId: tokens[1].id,- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- });- });-- // Test that instance with matching token gets the token reference updated- test("instance with reused token updates styleSourceSelection to existing token id", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources = toMap<StyleSource>([- { id: "existingToken", type: "token", name: "primaryColor" },- ]);- const styles = new Map([- createStyleDeclPair("existingToken", "base", "color", {- type: "keyword",- value: "red",- }),- ]);- const data = getWebstudioDataStub({ breakpoints, styleSources, styles });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- instances: [- {- type: "instance",- id: "box",- component: "Box",- children: [],- },- ],- breakpoints: [{ id: "base", label: "base" }],- styleSources: [- // Same name and same styles as existingToken- { id: "newToken", type: "token", name: "primaryColor" },- ],- styleSourceSelections: [{ instanceId: "box", values: ["newToken"] }],- styles: [- {- styleSourceId: "newToken",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- },- availableVariables: [],- projectId: "",- });-- // Should reuse existing token- expect(Array.from(data.styleSources.values())).toEqual([- { id: "existingToken", type: "token", name: "primaryColor" },- ]);-- // The instance should reference the existing token, not the new one- const newBoxId = Array.from(data.instances.keys())[0];- expect(data.styleSourceSelections.get(newBoxId)).toEqual({- instanceId: newBoxId,- values: ["existingToken"], // Should use existing token id, not "newToken"- });- });-- // Case 3 safeguard: Same styles but different name gets suffix when name conflicts- test("token with same styles but different name adds suffix when name already exists", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "primaryColor" },- { id: "token2", type: "token", name: "accentColor" }, // This name is taken- ]);- const styles = new Map([- createStyleDeclPair("token1", "base", "color", {- type: "keyword",- value: "red",- }),- createStyleDeclPair("token2", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ]);- const data = getWebstudioDataStub({ breakpoints, styleSources, styles });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- breakpoints: [{ id: "base", label: "base" }],- styleSources: [- // Same styles as token1, but wants to use name "accentColor" which is already taken- { id: "token3", type: "token", name: "accentColor" },- ],- styles: [- {- styleSourceId: "token3",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- },- availableVariables: [],- projectId: "",- });-- // Should add counter suffix to prevent duplicate name- const tokens = Array.from(data.styleSources.values());- expect(tokens).toHaveLength(3);- expect(tokens[0]).toEqual({- id: "token1",- type: "token",- name: "primaryColor",- });- expect(tokens[1]).toEqual({- id: "token2",- type: "token",- name: "accentColor",- });- expect(tokens[2]).toMatchObject({ type: "token", name: "accentColor-1" });- expect(tokens[2].id).not.toBe("token3"); // Should have new ID-- const tokenStyles = Array.from(data.styles.values());- expect(tokenStyles).toHaveLength(3);- expect(tokenStyles[0]).toEqual({- styleSourceId: "token1",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- });- expect(tokenStyles[1]).toEqual({- styleSourceId: "token2",- breakpointId: "base",- property: "fontSize",- value: { type: "unit", value: 16, unit: "px" },- });- expect(tokenStyles[2]).toMatchObject({- styleSourceId: tokens[2].id,- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- });- });-- // Case 6 safeguard: Different styles and different name gets suffix when name conflicts- test("token with different styles and name adds suffix when name already exists", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources = toMap<StyleSource>([- { id: "token1", type: "token", name: "primaryColor" },- { id: "token2", type: "token", name: "secondaryColor" }, // This name is taken- ]);- const styles = new Map([- createStyleDeclPair("token1", "base", "color", {- type: "keyword",- value: "blue",- }),- createStyleDeclPair("token2", "base", "color", {- type: "keyword",- value: "green",- }),- ]);- const data = getWebstudioDataStub({ breakpoints, styleSources, styles });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- breakpoints: [{ id: "base", label: "base" }],- styleSources: [- // Different styles from both existing tokens, but wants name "secondaryColor"- { id: "token3", type: "token", name: "secondaryColor" },- ],- styles: [- {- styleSourceId: "token3",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- },- availableVariables: [],- projectId: "",- });-- // Should add counter suffix to prevent duplicate name- const tokens = Array.from(data.styleSources.values());- expect(tokens).toHaveLength(3);- expect(tokens[0]).toEqual({- id: "token1",- type: "token",- name: "primaryColor",- });- expect(tokens[1]).toEqual({- id: "token2",- type: "token",- name: "secondaryColor",- });- expect(tokens[2]).toMatchObject({- type: "token",- name: "secondaryColor-1",- });- expect(tokens[2].id).not.toBe("token3"); // Should have new ID-- const tokenStyles = Array.from(data.styles.values());- expect(tokenStyles).toHaveLength(3);- expect(tokenStyles[0]).toEqual({- styleSourceId: "token1",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "blue" },- });- expect(tokenStyles[1]).toEqual({- styleSourceId: "token2",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "green" },- });- expect(tokenStyles[2]).toMatchObject({- styleSourceId: tokens[2].id,- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- });- });-- // Test that existing token with same styles but different name stays untouched- test("existing token with matching styles but different name stays untouched when inserting new token", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources = toMap<StyleSource>([- { id: "existingToken", type: "token", name: "primaryColor" },- ]);- const styles = new Map([- createStyleDeclPair("existingToken", "base", "color", {- type: "keyword",- value: "red",- }),- createStyleDeclPair("existingToken", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ]);- const data = getWebstudioDataStub({ breakpoints, styleSources, styles });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- breakpoints: [{ id: "base", label: "base" }],- styleSources: [- // Different name "accentColor", same styles as existingToken- { id: "newToken", type: "token", name: "accentColor" },- ],- styles: [- {- styleSourceId: "newToken",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- {- styleSourceId: "newToken",- breakpointId: "base",- property: "fontSize",- value: { type: "unit", value: 16, unit: "px" },- },- ],- },- availableVariables: [],- projectId: "",- });-- // Should insert new token with its own name, leaving existing one untouched- const tokens = Array.from(data.styleSources.values());- expect(tokens).toHaveLength(2);- expect(tokens[0]).toEqual({- id: "existingToken",- type: "token",- name: "primaryColor",- });- expect(tokens[1]).toMatchObject({ type: "token", name: "accentColor" });- expect(tokens[1].id).not.toBe("newToken"); // Should have new ID-- // Both tokens should have their own styles- const tokenStyles = Array.from(data.styles.values());- expect(tokenStyles).toHaveLength(4);- expect(tokenStyles[0]).toEqual({- styleSourceId: "existingToken",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- });- expect(tokenStyles[1]).toEqual({- styleSourceId: "existingToken",- breakpointId: "base",- property: "fontSize",- value: { type: "unit", value: 16, unit: "px" },- });- expect(tokenStyles[2]).toMatchObject({- styleSourceId: tokens[1].id,- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- });- expect(tokenStyles[3]).toMatchObject({- styleSourceId: tokens[1].id,- breakpointId: "base",- property: "fontSize",- value: { type: "unit", value: 16, unit: "px" },- });- });-- // Critical test: inserting base name when suffixed version exists- test("inserting token 'bbb' when 'bbb-1' with same styles exists inserts both tokens", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources = toMap<StyleSource>([- { id: "existingToken", type: "token", name: "bbb-1" },- ]);- const styles = new Map([- createStyleDeclPair("existingToken", "base", "color", {- type: "keyword",- value: "blue",- }),- ]);- const data = getWebstudioDataStub({ breakpoints, styleSources, styles });-- // Add an instance that uses the existing token- const existingInstance = createInstance("existingInstance", "Box", []);- data.instances.set("existingInstance", existingInstance);- data.styleSourceSelections.set("existingInstance", {- instanceId: "existingInstance",- values: ["existingToken"],- });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- instances: [- {- type: "instance",- id: "box",- component: "Box",- children: [],- },- ],- breakpoints: [{ id: "base", label: "base" }],- styleSources: [- // Inserting "bbb" with same styles as "bbb-1"- { id: "newToken", type: "token", name: "bbb" },- ],- styleSourceSelections: [{ instanceId: "box", values: ["newToken"] }],- styles: [- {- styleSourceId: "newToken",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "blue" },- },- ],- },- availableVariables: [],- projectId: "",- });-- // Both tokens should exist- const tokens = Array.from(data.styleSources.values());- expect(tokens).toHaveLength(2);- expect(tokens[0]).toEqual({- id: "existingToken",- type: "token",- name: "bbb-1",- });- expect(tokens[1]).toMatchObject({ type: "token", name: "bbb" }); // Different name, so inserted as-is- expect(tokens[1].id).not.toBe("newToken"); // Should have new ID-- // Both should have their own styles- const tokenStyles = Array.from(data.styles.values());- expect(tokenStyles).toHaveLength(2);- expect(tokenStyles[0]).toEqual({- styleSourceId: "existingToken",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "blue" },- });- expect(tokenStyles[1]).toMatchObject({- styleSourceId: tokens[1].id,- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "blue" },- });-- // The EXISTING instance should still reference "bbb-1" (existingToken)- expect(data.styleSourceSelections.get("existingInstance")).toEqual({- instanceId: "existingInstance",- values: ["existingToken"],- });-- // The new instance should reference the new token "bbb" (tokens[1].id)- const newBoxId = Array.from(data.instances.keys()).find(- (id) => id !== "existingInstance"- );- expect(data.styleSourceSelections.get(newBoxId!)).toEqual({- instanceId: newBoxId,- values: [tokens[1].id],- });- });-- test("insert local styles with new ids and use merged breakpoint ids", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const data = getWebstudioDataStub({ breakpoints });- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- 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" },- },- ],- },- availableVariables: [],- projectId: "",- });- expect(Array.from(data.styleSourceSelections.values())).toEqual([- {- instanceId: expect.not.stringMatching("box"),- values: [expect.not.stringMatching("localId"), "tokenId"],- },- ]);- expect(Array.from(data.styleSources.values())).toEqual([- { id: expect.not.stringMatching("localId"), type: "local" },- ]);- expect(Array.from(data.styles.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", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const data = getWebstudioDataStub({ breakpoints });- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- // 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" },- },- ],- },- availableVariables: [],- projectId: "",- });- expect(Array.from(data.styleSourceSelections.values())).toEqual([- { instanceId: "fragment", values: ["localId", "tokenId"] },- ]);- expect(Array.from(data.styleSources.values())).toEqual([- { id: "localId", type: "local" },- ]);- expect(Array.from(data.styles.values())).toEqual([- {- styleSourceId: "localId",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- ]);- });-- test("merge local styles into existing ROOT_INSTANCE_ID local source", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources = toMap<StyleSource>([- { id: "existingLocal", type: "local" },- ]);- const styleSourceSelections = new Map([- [- ROOT_INSTANCE_ID,- { instanceId: ROOT_INSTANCE_ID, values: ["existingLocal"] },- ],- ]);- const styles = new Map([- createStyleDeclPair("existingLocal", "base", "fontSize", {- type: "unit",- value: 16,- unit: "px",- }),- ]);- const data = getWebstudioDataStub({- breakpoints,- styleSources,- styleSourceSelections,- styles,- });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- instances: [- {- type: "instance",- id: ROOT_INSTANCE_ID,- component: "Body",- children: [],- },- ],- breakpoints: [{ id: "base", label: "base" }],- styleSourceSelections: [- { instanceId: ROOT_INSTANCE_ID, values: ["newLocal"] },- ],- styleSources: [{ id: "newLocal", type: "local" }],- styles: [- {- styleSourceId: "newLocal",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- ],- },- availableVariables: [],- projectId: "",- });-- // Should merge into existing local source- expect(Array.from(data.styleSources.values())).toEqual([- { id: "existingLocal", type: "local" },- ]);- expect(data.styleSourceSelections.get(ROOT_INSTANCE_ID)).toEqual({- instanceId: ROOT_INSTANCE_ID,- values: ["existingLocal"],- });- // Both styles should be present under the same source- expect(Array.from(data.styles.values())).toEqual([- {- styleSourceId: "existingLocal",- breakpointId: "base",- property: "fontSize",- value: { type: "unit", value: 16, unit: "px" },- },- {- styleSourceId: "existingLocal",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- ]);- });-- test("insert instances with new ids and update child references", () => {- const data = getWebstudioDataStub();- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- instances: [- {- type: "instance",- id: "parent",- component: "Box",- children: [- { type: "id", value: "child1" },- { type: "id", value: "child2" },- ],- },- {- type: "instance",- id: "child1",- component: "Text",- children: [],- },- {- type: "instance",- id: "child2",- component: "Text",- children: [],- },- ],- },- availableVariables: [],- projectId: "",- });-- const newInstances = Array.from(data.instances.values());- expect(newInstances).toHaveLength(3);-- const parentInstance = newInstances.find((i) => i.component === "Box");- const childInstances = newInstances.filter((i) => i.component === "Text");-- expect(parentInstance).toBeDefined();- expect(childInstances).toHaveLength(2);-- // Verify parent's children reference the new child ids- expect(parentInstance?.children).toEqual([- { type: "id", value: childInstances[0].id },- { type: "id", value: childInstances[1].id },- ]);-- // Verify new ids were generated (not same as original)- expect(parentInstance?.id).not.toBe("parent");- expect(childInstances[0].id).not.toBe("child1");- expect(childInstances[1].id).not.toBe("child2");- });-- test("skip portal content that already exists", () => {- const instances = new Map([- [- "existingPortalContent",- {- type: "instance" as const,- id: "existingPortalContent",- component: "Box",- children: [{ type: "text" as const, value: "existing" }],- },- ],- ]);- const data = getWebstudioDataStub({ instances });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- instances: [- {- type: "instance",- id: "portal",- component: portalComponent,- children: [{ type: "id", value: "existingPortalContent" }],- },- {- type: "instance",- id: "existingPortalContent",- component: "Box",- children: [{ type: "text", value: "new version" }],- },- ],- },- availableVariables: [],- projectId: "",- });-- // Should preserve existing portal content- const existingInstance = data.instances.get("existingPortalContent");- expect(existingInstance?.children).toEqual([- { type: "text", value: "existing" },- ]);- });-- test("insert instance with expression child and update variable references", () => {- const data = getWebstudioDataStub();-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- instances: [- {- type: "instance",- id: "box",- component: "Box",- children: [{ type: "expression", value: "$ws$dataSource$oldVar" }],- },- ],- dataSources: [- {- id: "oldVar",- scopeInstanceId: "box",- type: "variable",- name: "myVar",- value: { type: "string", value: "hello" },- },- ],- },- availableVariables: [],- projectId: "",- });-- const newBoxId = Array.from(data.instances.keys())[0];- const newBox = data.instances.get(newBoxId);- const newVarId = Array.from(data.dataSources.keys())[0];-- // Verify the expression was updated with the new variable id- expect(newBox?.children[0].type).toBe("expression");- if (newBox?.children[0].type === "expression") {- // The encoding replaces - with __DASH__- const encodedId = newVarId.replace(/-/g, "__DASH__");- expect(newBox.children[0].value).toBe(`$ws$dataSource$${encodedId}`);- }- expect(newVarId).not.toBe("oldVar");- });-- test("skip global variables that already exist by id", () => {- const dataSources = new Map([- [- "globalVar1",- {- id: "globalVar1",- scopeInstanceId: ROOT_INSTANCE_ID,- type: "variable" as const,- name: "Global Var",- value: { type: "string" as const, value: "existing" },- },- ],- ]);- const data = getWebstudioDataStub({ dataSources });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- dataSources: [- {- id: "globalVar1",- scopeInstanceId: ROOT_INSTANCE_ID,- type: "variable",- name: "Global Var",- value: { type: "string", value: "new value" },- },- ],- },- availableVariables: [],- projectId: "",- });-- // Should preserve existing global variable- const existingVar = data.dataSources.get("globalVar1");- expect(existingVar?.type).toBe("variable");- if (existingVar?.type === "variable") {- expect(existingVar.value).toEqual({- type: "string",- value: "existing",- });- }- });-- test("skip global variables that have conflicting names with availableVariables", () => {- const data = getWebstudioDataStub();-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- dataSources: [- {- id: "newGlobal",- scopeInstanceId: ROOT_INSTANCE_ID,- type: "variable",- name: "conflictingName",- value: { type: "string", value: "value" },- },- ],- },- availableVariables: [- {- id: "existingId",- scopeInstanceId: ROOT_INSTANCE_ID,- type: "variable",- name: "conflictingName",- value: { type: "string", value: "existing" },- },- ],- projectId: "",- });-- // Should not insert the global variable due to name conflict- expect(data.dataSources.has("newGlobal")).toBe(false);- });-- test("handle mixed token and local style sources in styleSourceSelections", () => {- const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);- const styleSources = toMap<StyleSource>([- { id: "existingToken", type: "token", name: "Primary" },- ]);- const data = getWebstudioDataStub({ breakpoints, styleSources });-- insertWebstudioFragmentCopy({- data,- fragment: {- ...emptyFragment,- instances: [- {- type: "instance",- id: "box",- component: "Box",- children: [],- },- ],- breakpoints: [{ id: "base", label: "base" }],- styleSourceSelections: [- {- instanceId: "box",- values: ["localStyle1", "existingToken", "localStyle2"],- },- ],- styleSources: [- { id: "localStyle1", type: "local" },- { id: "localStyle2", type: "local" },- ],- styles: [- {- styleSourceId: "localStyle1",- breakpointId: "base",- property: "color",- value: { type: "keyword", value: "red" },- },- {- styleSourceId: "localStyle2",- breakpointId: "base",- property: "fontSize",- value: { type: "unit", value: 16, unit: "px" },- },- ],- },- availableVariables: [],- projectId: "",- });-- const newBoxId = Array.from(data.instances.keys())[0];- const selection = data.styleSourceSelections.get(newBoxId);-- expect(selection?.values).toHaveLength(3);- expect(selection?.values[1]).toBe("existingToken"); // Token preserved- expect(selection?.values[0]).not.toBe("localStyle1"); // Local regenerated- expect(selection?.values[2]).not.toBe("localStyle2"); // Local regenerated-- // Verify both local styles were created with new ids- const localStyles = Array.from(data.styleSources.values()).filter(- (s) => s.type === "local"- );- expect(localStyles).toHaveLength(2);- });-});--describe("find closest insertable", () => {- const newBoxFragment = createFragment({- children: [{ type: "id", value: "newBoxId" }],- instances: [- { type: "instance", id: "newBoxId", component: "Box", children: [] },- ],- });-- beforeEach(() => {- $pages.set(- createDefaultPages({- homePageId: "homePageId",- rootInstanceId: "",- })- );- $selectedPageId.set("homePageId");- $selectedInstanceSelector.set([- "collectionId[1]",- "collectionId",- "bodyId",- ]);- $registeredComponentMetas.set(defaultMetasMap);- });-- test("puts in the end if closest instance is container", () => {- const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="boxId">- <$.Paragraph ws:id="paragraphId">- <$.Bold ws:id="boldId"></$.Bold>- </$.Paragraph>- </$.Box>- </$.Body>- );- $instances.set(instances);- selectInstance(["boxId", "bodyId"]);- expect(findClosestInsertable(newBoxFragment)).toEqual({- parentSelector: ["boxId", "bodyId"],- position: "end",- });- });-- test("puts in the end of root instance", () => {- const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Paragraph ws:id="paragraphId"></$.Paragraph>- </$.Body>- );- $instances.set(instances);- selectInstance(["bodyId"]);- expect(findClosestInsertable(newBoxFragment)).toEqual({- parentSelector: ["bodyId"],- position: "end",- });- });-- test("puts in the end of root instance when page root only has text", () => {- const { instances } = renderData(<$.Body ws:id="bodyId">text</$.Body>);- $instances.set(instances);- selectInstance(["bodyId"]);- expect(findClosestInsertable(newBoxFragment)).toEqual({- parentSelector: ["bodyId"],- position: "end",- });- });-- test("finds closest container and puts after its child within selection", () => {- const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Paragraph ws:id="paragraphId">- <$.Bold ws:id="boldId"></$.Bold>- </$.Paragraph>- </$.Body>- );- $instances.set(instances);- selectInstance(["boldId", "paragraphId", "bodyId"]);- expect(findClosestInsertable(newBoxFragment)).toEqual({- parentSelector: ["bodyId"],- position: 1,- });- });-- test("finds closest container that doesn't have an expression as a child", () => {- const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Box ws:id="box1Id"></$.Box>- <$.Paragraph ws:id="paragraphId">{expression`"bla"`}</$.Paragraph>- <$.Box ws:id="box2Id"></$.Box>- </$.Body>- );- $instances.set(instances);- selectInstance(["paragraphId", "bodyId"]);- expect(findClosestInsertable(newBoxFragment)).toEqual({- parentSelector: ["bodyId"],- position: 2,- });- });-- test("finds closest container without textual placeholder", () => {- const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Paragraph ws:id="paragraphId"></$.Paragraph>- </$.Body>- );- $instances.set(instances);- selectInstance(["paragraphId", "bodyId"]);- expect(findClosestInsertable(newBoxFragment)).toEqual({- parentSelector: ["bodyId"],- position: 1,- });- });-- test("finds closest container even with when parent has placeholder", () => {- const { instances } = renderData(- <$.Body ws:id="bodyId">- <$.Paragraph ws:id="paragraphId">- <$.Image ws:id="imageId"></$.Image>- </$.Paragraph>- </$.Body>- );- $instances.set(instances);- selectInstance(["imageId", "paragraphId", "bodyId"]);- expect(- findClosestInsertable(renderTemplate(<$.Box ws:tag="span"></$.Box>))- ).toEqual({- parentSelector: ["paragraphId", "bodyId"],- position: 1,- });- });-- test("forbids inserting into :root", () => {- const { instances } = renderData(<$.Body ws:id="bodyId"></$.Body>);- $instances.set(instances);- selectInstance([":root"]);- expect(findClosestInsertable(newBoxFragment)).toEqual(undefined);- });-- test("allow inserting into collection item", () => {- const { instances } = renderData(- <$.Body ws:id="bodyId">- <ws.collection ws:id="collectionId">- <$.Box ws:id="boxId"></$.Box>- </ws.collection>- </$.Body>- );- $instances.set(instances);- selectInstance(["collectionId[1]", "collectionId", "bodyId"]);- expect(findClosestInsertable(newBoxFragment)).toEqual({- parentSelector: ["collectionId", "bodyId"],- position: "end",- });- });-- test("allow inserting list item in body even though validation fails", () => {- const { instances } = renderData(<$.Body ws:id="bodyId"></$.Body>);- $instances.set(instances);- selectInstance(["bodyId"]);- const newListItemFragment = renderTemplate(- <$.ListItem ws:id="newListItemId"></$.ListItem>- );- expect(findClosestInsertable(newListItemFragment)).toEqual({- parentSelector: ["bodyId"],- position: "end",- });- });-});--test("get undefined instead of instance path when no instances found", () => {- expect(getInstancePath(["boxId"], new Map())).toEqual(undefined);-});--describe("buildInstancePath", () => {- const createPages = () =>- createDefaultPages({- homePageId: "homePageId",- rootInstanceId: "rootId",- systemDataSourceId: "systemId",- });-- test("returns empty array when instance has no selector", () => {- const pages = createPages();- const instances = new Map();-- const result = buildInstancePath("nonexistent", pages, instances);- expect(result).toEqual([]);- });-- test("returns empty array for root instance (no ancestors)", () => {- const { instances } = renderData(- <$.Body ws:id="rootId">- <$.Box ws:id="boxId"></$.Box>- </$.Body>- );- const pages = createPages();-- const result = buildInstancePath("rootId", pages, instances);- expect(result).toEqual([]);- });-- test("builds path for single-level nesting", () => {- const { instances } = renderData(- <$.Body ws:id="rootId">- <$.Box ws:id="boxId"></$.Box>- </$.Body>- );- const pages = createPages();-- const result = buildInstancePath("boxId", pages, instances);- expect(result).toEqual(["Body"]);- });-- test("builds path for multi-level nesting", () => {- const { instances } = renderData(- <$.Body ws:id="rootId">- <$.Box ws:id="containerId">- <$.Heading ws:id="headingId"></$.Heading>- </$.Box>- </$.Body>- );- const pages = createPages();-- const result = buildInstancePath("headingId", pages, instances);- expect(result).toEqual(["Body", "Box"]);- });-- test("builds path for deeply nested instance", () => {- const { instances } = renderData(- <$.Body ws:id="rootId">- <$.Box ws:id="sectionId">- <$.Box ws:id="articleId">- <$.Box ws:id="divId">- <$.Text ws:id="textId"></$.Text>- </$.Box>- </$.Box>- </$.Box>- </$.Body>- );- const pages = createPages();-- const result = buildInstancePath("textId", pages, instances);- expect(result).toEqual(["Body", "Box", "Box", "Box"]);- });-- test("handles instances with custom labels", () => {- const { instances } = renderData(- <$.Body ws:id="rootId" ws:label="Main Body">- <$.Box ws:id="navId" ws:label="Navigation">- <$.Link ws:id="linkId" ws:label="Home Link"></$.Link>- </$.Box>- </$.Body>- );- const pages = createPages();-- const result = buildInstancePath("linkId", pages, instances);- expect(result).toEqual(["Main Body", "Navigation"]);- });-});--describe("toggleInstanceShow", () => {- test("creates show prop with false value when it doesn't exist", () => {- const { instances } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>- );- $instances.set(instances);- $props.set(new Map());- $pages.set(createDefaultPages({ rootInstanceId: "body" }));-- toggleInstanceShow("box");-- const props = $props.get();- const showProp = Array.from(props.values()).find(- (prop) => prop.instanceId === "box" && prop.name === showAttribute- );- expect(showProp).toEqual({- id: expect.any(String),- instanceId: "box",- name: showAttribute,- type: "boolean",- value: false,- });- });-- test("toggles show prop from true to false", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box" ws:show={true}></$.Box>- </$.Body>- );- $instances.set(instances);- $props.set(props);- $pages.set(createDefaultPages({ rootInstanceId: "body" }));-- toggleInstanceShow("box");-- const updatedProps = $props.get();- const showProp = Array.from(updatedProps.values()).find(- (prop) => prop.instanceId === "box" && prop.name === showAttribute- );- expect(showProp?.type).toBe("boolean");- if (showProp?.type === "boolean") {- expect(showProp.value).toBe(false);- }- });-- test("toggles show prop from false to true", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box" ws:show={false}></$.Box>- </$.Body>- );- $instances.set(instances);- $props.set(props);- $pages.set(createDefaultPages({ rootInstanceId: "body" }));-- toggleInstanceShow("box");-- const updatedProps = $props.get();- const showProp = Array.from(updatedProps.values()).find(- (prop) => prop.instanceId === "box" && prop.name === showAttribute- );- expect(showProp?.type).toBe("boolean");- if (showProp?.type === "boolean") {- expect(showProp.value).toBe(true);- }- });-});--describe("unwrap instance", () => {- test("unwraps instance and moves children to parent", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="wrapper">- <$.Box ws:id="child1"></$.Box>- <$.Box ws:id="child2"></$.Box>- </$.Box>- </$.Box>- </$.Body>- );-- const selectedItem = {- instanceSelector: ["wrapper", "parent", "body"],- instance: instances.get("wrapper")!,- };- const parentItem = {- instanceSelector: ["parent", "body"],- instance: instances.get("parent")!,- };-- const result = unwrapInstanceMutable({- instances,- props,- metas: defaultMetasMap,- selectedItem,- parentItem,- });-- expect(result.success).toBe(true);- expect(instances.has("parent")).toBe(false);- const bodyInstance = instances.get("body")!;- expect(bodyInstance.children).toEqual([{ type: "id", value: "wrapper" }]);- });-- test("fails to unwrap textual instance", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box">- <$.Paragraph ws:id="paragraph">- <$.Bold ws:id="bold">text</$.Bold>- </$.Paragraph>- </$.Box>- </$.Body>- );-- const selectedItem = {- instanceSelector: ["bold", "paragraph", "box", "body"],- instance: instances.get("bold")!,- };- const parentItem = {- instanceSelector: ["paragraph", "box", "body"],- instance: instances.get("paragraph")!,- };-- const result = unwrapInstanceMutable({- instances,- props,- metas: defaultMetasMap,- selectedItem,- parentItem,- });-- expect(result.success).toBe(false);- expect(result.error).toBe("Cannot unwrap textual instance");- });-- test("fails to unwrap if content model is violated", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="outerBox">- <$.Form ws:id="form">- <$.Box ws:id="innerBox">- <$.Form ws:id="nestedForm"></$.Form>- </$.Box>- </$.Form>- </$.Box>- </$.Body>- );-- const selectedItem = {- instanceSelector: ["form", "outerBox", "body"],- instance: instances.get("form")!,- };- const parentItem = {- instanceSelector: ["outerBox", "body"],- instance: instances.get("outerBox")!,- };-- const result = unwrapInstanceMutable({- instances,- props,- metas: defaultMetasMap,- selectedItem,- parentItem,- });-- expect(result.success).toBe(false);- expect(result.error).toBe("Cannot unwrap instance");- });-- test("unwrapping replaces parent with selected in grandparent", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="child"></$.Box>- </$.Box>- </$.Body>- );-- const selectedItem = {- instanceSelector: ["child", "parent", "body"],- instance: instances.get("child")!,- };- const parentItem = {- instanceSelector: ["parent", "body"],- instance: instances.get("parent")!,- };-- const result = unwrapInstanceMutable({- instances,- props,- metas: defaultMetasMap,- selectedItem,- parentItem,- });-- expect(result.success).toBe(true);- expect(instances.has("parent")).toBe(false);- expect(instances.has("child")).toBe(true);- const bodyInstance = instances.get("body")!;- expect(bodyInstance.children).toEqual([{ type: "id", value: "child" }]);- });-- test("unwrapping removes selected from parent and moves it to grandparent", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Image ws:id="image"></$.Image>- <$.Link ws:id="link"></$.Link>- </$.Box>- </$.Body>- );-- const selectedItem = {- instanceSelector: ["image", "parent", "body"],- instance: instances.get("image")!,- };- const parentItem = {- instanceSelector: ["parent", "body"],- instance: instances.get("parent")!,- };-- const result = unwrapInstanceMutable({- instances,- props,- metas: defaultMetasMap,- selectedItem,- parentItem,- });-- expect(result.success).toBe(true);- expect(instances.has("parent")).toBe(true); // Parent still exists- expect(instances.has("image")).toBe(true);- expect(instances.has("link")).toBe(true);-- const bodyInstance = instances.get("body")!;- expect(bodyInstance.children).toEqual([- { type: "id", value: "parent" },- { type: "id", value: "image" },- ]);-- const parentInstance = instances.get("parent")!;- expect(parentInstance.children).toEqual([{ type: "id", value: "link" }]);- });-- test("unwraps selected slot occurrence instead of hidden slot fragment", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">- {/* same ids */}- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>- );-- const result = unwrapInstanceMutable({- instances,- props,- metas: defaultMetasMap,- selectedItem: {- instanceSelector: ["div", "fragment", "slot1", "body"],- instance: instances.get("div")!,- },- parentItem: {- instanceSelector: ["slot1", "body"],- instance: instances.get("slot1")!,- },- });-- expect(result.success).toBe(true);- expect(instances.get("body")?.children).toEqual([- { type: "id", value: "div" },- { type: "id", value: "slot2" },- ]);- expect(instances.has("slot1")).toBe(false);- expect(instances.get("slot2")?.children).toEqual([- { type: "id", value: "fragment" },- ]);- expect(instances.get("fragment")?.children).toEqual([- { type: "id", value: "div" },- ]);- });-- test("unwrap command skips hidden slot fragment", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot">- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>- );- $instances.set(instances);- $props.set(props);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);- selectInstance(["div", "fragment", "slot", "body"]);-- unwrapInstance();-- expect($selectedInstanceSelector.get()).toEqual(["div", "body"]);- expect($instances.get().get("body")?.children).toEqual([- { type: "id", value: "div" },- ]);- expect($instances.get().has("slot")).toBe(false);- expect($instances.get().has("fragment")).toBe(false);- });-- test("unwrap command detaches selected duplicated slot occurrence", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">- {/* same ids */}- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>- );- $instances.set(instances);- $props.set(props);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);- selectInstance(["div", "fragment", "slot1", "body"]);-- unwrapInstance();-- const bodyChildren = $instances.get().get("body")?.children;- const unwrappedDivId =- bodyChildren?.[0]?.type === "id" ? bodyChildren[0].value : undefined;-- expect(unwrappedDivId).toBeDefined();- expect(unwrappedDivId).not.toBe("div");- expect($selectedInstanceSelector.get()).toEqual([unwrappedDivId, "body"]);- expect($instances.get().get("slot1")).toBeUndefined();- expect($instances.get().get("slot2")?.children).toEqual([- { type: "id", value: "fragment" },- ]);- expect($instances.get().get("fragment")?.children).toEqual([- { type: "id", value: "div" },- ]);- });-});--describe("canUnwrapInstance", () => {- beforeEach(() => {- $project.set({ id: "projectId" } as Project);- $registeredComponentMetas.set(defaultMetasMap);- });-- test("returns true for unwrappable instance", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="wrapper">- <$.Box ws:id="child"></$.Box>- </$.Box>- </$.Box>- </$.Body>- );-- $instances.set(instances);- $props.set(props);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);-- const instancePath = [- {- instanceSelector: ["wrapper", "parent", "body"],- instance: instances.get("wrapper")!,- },- {- instanceSelector: ["parent", "body"],- instance: instances.get("parent")!,- },- {- instanceSelector: ["body"],- instance: instances.get("body")!,- },- ] satisfies InstancePath;-- expect(canUnwrapInstance(instancePath)).toBe(true);- });-- test("returns false if parent is root instance", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="box"></$.Box>- </$.Body>- );-- $instances.set(instances);- $props.set(props);- $registeredComponentMetas.set(defaultMetasMap);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);-- const instancePath = [- {- instanceSelector: ["box", "body"],- instance: instances.get("box")!,- },- {- instanceSelector: ["body"],- instance: instances.get("body")!,- },- ] satisfies InstancePath;-- expect(canUnwrapInstance(instancePath)).toBe(false);- });-- test("returns false for textual instance", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Paragraph ws:id="paragraph">- <$.Bold ws:id="bold">text</$.Bold>- </$.Paragraph>- </$.Body>- );-- $instances.set(instances);- $props.set(props);- $registeredComponentMetas.set(defaultMetasMap);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);-- const instancePath = [- {- instanceSelector: ["bold", "paragraph", "body"],- instance: instances.get("bold")!,- },- {- instanceSelector: ["paragraph", "body"],- instance: instances.get("paragraph")!,- },- ] satisfies InstancePath;-- expect(canUnwrapInstance(instancePath)).toBe(false);- });-- test("returns true for Body > div > a scenario", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <ws.element ws:tag="div" ws:id="div">- <ws.element ws:tag="a" ws:id="link">- Link text- </ws.element>- </ws.element>- </$.Body>- );-- $instances.set(instances);- $props.set(props);- $registeredComponentMetas.set(defaultMetasMap);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);-- const instancePath = [- {- instanceSelector: ["link", "div", "body"],- instance: instances.get("link")!,- },- {- instanceSelector: ["div", "body"],- instance: instances.get("div")!,- },- {- instanceSelector: ["body"],- instance: instances.get("body")!,- },- ] satisfies InstancePath;-- // Should be able to unwrap the link from the div- expect(canUnwrapInstance(instancePath)).toBe(true);- });-- test("unwrapInstanceMutable works for Body > div > a scenario", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <ws.element ws:tag="div" ws:id="div">- <ws.element ws:tag="a" ws:id="link">- Link text- </ws.element>- </ws.element>- </$.Body>- );-- const result = unwrapInstanceMutable({- instances,- props,- metas: defaultMetasMap,- selectedItem: {- instanceSelector: ["link", "div", "body"],- instance: instances.get("link")!,- },- parentItem: {- instanceSelector: ["div", "body"],- instance: instances.get("div")!,- },- });-- expect(result.success).toBe(true);-- // Verify the link is now a direct child of body- const body = instances.get("body")!;- expect(body.children).toContainEqual({ type: "id", value: "link" });-- // Verify the div was deleted since it has no more children- expect(instances.has("div")).toBe(false);- });-});--describe("canConvertInstance", () => {- test("returns true for valid conversion", () => {- const { instances, props } = renderData(- <ws.element ws:tag="body" ws:id="body">- <$.Box ws:id="box"></$.Box>- </ws.element>- );-- const result = canConvertInstance(- "box",- ["box", "body"],- elementComponent,- "div",- instances,- props,- defaultMetasMap- );-- expect(result).toBe(true);- });-- test("returns false for non-existent instance", () => {- const { instances, props } = renderData(- <ws.element ws:tag="body" ws:id="body"></ws.element>- );-- const result = canConvertInstance(- "nonexistent",- ["nonexistent", "body"],- elementComponent,- "div",- instances,- props,- defaultMetasMap- );-- expect(result).toBe(false);- });-- test("returns true when converting Box to Heading", () => {- const { instances, props } = renderData(- <ws.element ws:tag="body" ws:id="body">- <$.Box ws:id="box"></$.Box>- </ws.element>- );-- const result = canConvertInstance(- "box",- ["box", "body"],- "@webstudio-is/sdk-components-react:Heading",- undefined,- instances,- props,- defaultMetasMap- );-- expect(result).toBe(true);- });-- test("uses preset tag when available", () => {- const { instances, props } = renderData(- <ws.element ws:tag="body" ws:id="body">- <$.Box ws:id="box"></$.Box>- </ws.element>- );-- const result = canConvertInstance(- "box",- ["box", "body"],- "@webstudio-is/sdk-components-react:Heading",- undefined,- instances,- props,- defaultMetasMap- );-- expect(result).toBe(true);- });-});--describe("convertInstance", () => {- beforeEach(() => {- $registeredComponentMetas.set(defaultMetasMap);- });-- test("detach shared slot children when converting slot", () => {- const { instances, props } = renderData(- <$.Body ws:id="body">- <$.Slot ws:id="slot1">- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- <$.Slot ws:id="slot2">- {/* same ids */}- <$.Fragment ws:id="fragment">- <ws.element ws:tag="div" ws:id="div"></ws.element>- </$.Fragment>- </$.Slot>- </$.Body>- );- $instances.set(instances);- $props.set(props);- selectInstance(["slot1", "body"]);-- convertInstance(elementComponent, "section");-- const convertedSlot = $instances.get().get("slot1");- expect(convertedSlot?.component).toBe(elementComponent);- expect(convertedSlot?.tag).toBe("section");- expect(convertedSlot?.children).not.toEqual(- $instances.get().get("slot2")?.children- );- expect($instances.get().get("slot2")?.children).toEqual([- { type: "id", value: "fragment" },- ]);- expect($instances.get().get("fragment")?.children).toEqual([- { type: "id", value: "div" },- ]);- });-- test("converts legacy tag to element", () => {- const { instances, props } = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <$.Box tag="article" ws:id="articleId"></$.Box>- </ws.element>- );- $instances.set(instances);- $props.set(props);- selectInstance(["articleId", "bodyId"]);- convertInstance(elementComponent);- const { instances: newInstances, props: newProps } = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="article" ws:id="articleId"></ws.element>- </ws.element>- );- expect({ instances: $instances.get(), props: $props.get() }).toEqual({- instances: newInstances,- props: newProps,- });- });-- test("migrates legacy properties", () => {- const { instances, props } = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <$.Box- ws:tag="div"- ws:id="divId"- className="my-class"- htmlFor="my-id"- ></$.Box>- </ws.element>- );- $instances.set(instances);- $props.set(props);- selectInstance(["divId", "bodyId"]);- convertInstance(elementComponent);- const { instances: newInstances, props: newProps } = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element- ws:tag="div"- ws:id="divId"- class="my-class"- for="my-id"- ></ws.element>- </ws.element>- );- expect({ instances: $instances.get(), props: $props.get() }).toEqual({- instances: newInstances,- props: newProps,- });- });-- test("preserves currently specified tag", () => {- $instances.set(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <$.Box ws:tag="article" ws:id="articleId"></$.Box>- </ws.element>- ).instances- );- selectInstance(["articleId", "bodyId"]);- convertInstance(elementComponent);- expect($instances.get()).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="article" ws:id="articleId"></ws.element>- </ws.element>- ).instances- );- });-- test("converts to first tag from presets", () => {- $instances.set(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <$.Heading ws:id="headingId"></$.Heading>- </ws.element>- ).instances- );- selectInstance(["headingId", "bodyId"]);- convertInstance(elementComponent);- expect($instances.get()).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="h1" ws:id="headingId"></ws.element>- </ws.element>- ).instances- );- });-- test("falls back to div", () => {- $instances.set(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <$.Box ws:id="divId"></$.Box>- </ws.element>- ).instances- );- selectInstance(["divId", "bodyId"]);- convertInstance(elementComponent);- expect($instances.get()).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="divId"></ws.element>- </ws.element>- ).instances- );- });-- test("converts with specific tag", () => {- $instances.set(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <$.Box ws:id="divId"></$.Box>- </ws.element>- ).instances- );- selectInstance(["divId", "bodyId"]);- convertInstance(elementComponent, "a");- expect($instances.get()).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="a" ws:id="divId"></ws.element>- </ws.element>- ).instances- );- });-- test("converts between components", () => {- $instances.set(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <$.Box ws:id="boxId"></$.Box>- </ws.element>- ).instances- );- selectInstance(["boxId", "bodyId"]);- convertInstance("@webstudio-is/sdk-components-react:Heading");- const result = $instances.get();- const boxInstance = result.get("boxId");- expect(boxInstance?.component).toBe(- "@webstudio-is/sdk-components-react:Heading"- );- });-- test("prevents converting root instance", () => {- const initialInstances = renderData(- <ws.element ws:tag="html" ws:id="rootId">- <ws.element ws:tag="body" ws:id="bodyId"></ws.element>- </ws.element>- ).instances;- $instances.set(initialInstances);- selectInstance(["rootId"]);- convertInstance(elementComponent, "div");- // Should not change- expect($instances.get()).toEqual(initialInstances);- });-- test("prevents converting body instance", () => {- const pages = createDefaultPages({ rootInstanceId: "bodyId" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);-- const initialInstances = renderData(- <ws.element ws:tag="html" ws:id="rootId">- <ws.element ws:tag="body" ws:id="bodyId">- <$.Box ws:id="boxId"></$.Box>- </ws.element>- </ws.element>- ).instances;- $instances.set(initialInstances);- selectInstance(["bodyId", "rootId"]);- convertInstance(elementComponent, "div");- // Should not change- expect($instances.get()).toEqual(initialInstances);- });-});--describe("deleteSelectedInstance", () => {- test("delete selected instance and select next one", () => {- const { instances } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="child1"></$.Box>- <$.Box ws:id="child2"></$.Box>- <$.Box ws:id="child3"></$.Box>- </$.Box>- </$.Body>- );- $instances.set(instances);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);- selectInstance(["child2", "parent", "body"]);- deleteSelectedInstance();- expect($selectedInstanceSelector.get()).toEqual([- "child3",- "parent",- "body",- ]);- });-- test("delete selected instance and select previous one", () => {- const { instances } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="child1"></$.Box>- <$.Box ws:id="child2"></$.Box>- <$.Box ws:id="child3"></$.Box>- </$.Box>- </$.Body>- );- $instances.set(instances);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);- selectInstance(["child3", "parent", "body"]);- deleteSelectedInstance();- expect($selectedInstanceSelector.get()).toEqual([- "child2",- "parent",- "body",- ]);- });-- test("delete selected instance and select parent one", () => {- const { instances } = renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="child1"></$.Box>- </$.Box>- </$.Body>- );- $instances.set(instances);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);- selectInstance(["child1", "parent", "body"]);- deleteSelectedInstance();- expect($selectedInstanceSelector.get()).toEqual(["parent", "body"]);- });-});--describe("insertWebstudioFragmentAt with conflictResolution", () => {- beforeEach(() => {- $project.set({ id: "project-id" } as Project);- });-- test("uses conflictResolution='theirs' by default (creates new token with suffix)", () => {- // Existing project with a "primary" token (used by existing-box)- const data = renderData(- <$.Body ws:id="body">- <$.Box- ws:id="existing-box"- ws:tokens={[- token(- "primary",- css`- color: blue;- `- ),- ]}- ></$.Box>- </$.Body>- );-- // Create fragment with token that has same name but different styles- const fragment = renderTemplate(- <$.Box- ws:id="box"- ws:tokens={[- token(- "primary",- css`- color: red;- `- ),- ]}- ></$.Box>- );-- setDataStores(data);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);- selectInstance(["body"]);-- // Insert without explicit conflictResolution (defaults to "theirs")- insertWebstudioFragmentAt(fragment, {- parentSelector: ["body"],- position: "end",- });-- // The existing token should still have blue color (unchanged)- const styles = Array.from($styles.get().values());- const styleSources = Array.from($styleSources.get().values());- const existingToken = styleSources.find(- (s) => s.type === "token" && s.name === "primary"- );- const existingTokenStyle = styles.find(- (s) =>- s.styleSourceId === existingToken?.id &&- s.property === "color" &&- s.breakpointId === "base"- );- expect(existingTokenStyle?.value).toEqual({- type: "keyword",- value: "blue",- });-- // A new token "primary-1" should be created with red color- const newToken = styleSources.find(- (s) => s.type === "token" && s.name === "primary-1"- );- expect(newToken).toBeDefined();- const newTokenStyle = styles.find(- (s) =>- s.styleSourceId === newToken?.id &&- s.property === "color" &&- s.breakpointId === "base"- );- expect(newTokenStyle?.value).toEqual({ type: "keyword", value: "red" });- });-- test("uses conflictResolution='ours' to keep existing token styles", () => {- // Existing project with a "primary" token (used by existing-box)- const data = renderData(- <$.Body ws:id="body">- <$.Box- ws:id="existing-box"- ws:tokens={[- token(- "primary",- css`- color: blue;- `- ),- ]}- ></$.Box>- </$.Body>- );-- const fragment = renderTemplate(- <$.Box- ws:id="box"- ws:tokens={[- token(- "primary",- css`- color: red;- `- ),- ]}- ></$.Box>- );-- setDataStores(data);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);- selectInstance(["body"]);-- // Insert with conflictResolution="ours" to keep existing styles- insertWebstudioFragmentAt(- fragment,- {- parentSelector: ["body"],- position: "end",- },- "ours"- );-- // The existing token should still have blue color (kept original)- const styles = Array.from($styles.get().values());- const styleSources = Array.from($styleSources.get().values());- const existingToken = styleSources.find(- (s) => s.type === "token" && s.name === "primary"- );- const primaryTokenStyle = styles.find(- (s) =>- s.styleSourceId === existingToken?.id &&- s.property === "color" &&- s.breakpointId === "base"- );- expect(primaryTokenStyle?.value).toEqual({- type: "keyword",- value: "blue",- });-- // No new token should be created- const newToken = styleSources.find(- (s) => s.type === "token" && s.name === "primary-1"- );- expect(newToken).toBeUndefined();- });-- test("uses conflictResolution='merge' to merge styles (theirs overrides)", () => {- // Existing project with a "primary" token that has color and fontSize- const data = renderData(- <$.Body ws:id="body">- <$.Box- ws:id="existing-box"- ws:tokens={[- token(- "primary",- css`- color: blue;- font-size: 16px;- `- ),- ]}- ></$.Box>- </$.Body>- );-- // Fragment with same "primary" token but different color and new property- const fragment = renderTemplate(- <$.Box- ws:id="box"- ws:tokens={[- token(- "primary",- css`- color: red;- font-weight: bold;- `- ),- ]}- ></$.Box>- );-- setDataStores(data);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);- $selectedPageId.set(pages.homePageId);- selectInstance(["body"]);-- // Insert with conflictResolution="merge"- insertWebstudioFragmentAt(- fragment,- {- parentSelector: ["body"],- position: "end",- },- "merge"- );-- // The existing token should now have red color (overridden by fragment)- const styles = Array.from($styles.get().values());- const styleSources = Array.from($styleSources.get().values());- const existingToken = styleSources.find(- (s) => s.type === "token" && s.name === "primary"- );- const colorStyle = styles.find(- (s) =>- s.styleSourceId === existingToken?.id &&- s.property === "color" &&- s.breakpointId === "base"- );- expect(colorStyle?.value).toEqual({ type: "keyword", value: "red" });-- // fontSize should still be there (not in fragment, so kept)- const fontSizeStyle = styles.find(- (s) =>- s.styleSourceId === existingToken?.id &&- s.property === "fontSize" &&- s.breakpointId === "base"- );- expect(fontSizeStyle?.value).toEqual({- type: "unit",- value: 16,- unit: "px",- });-- // fontWeight should be added from fragment- const fontWeightStyle = styles.find(- (s) =>- s.styleSourceId === existingToken?.id &&- s.property === "fontWeight" &&- s.breakpointId === "base"- );- expect(fontWeightStyle?.value).toEqual({ type: "keyword", value: "bold" });-- // No new token should be created- const newToken = styleSources.find(- (s) => s.type === "token" && s.name === "primary-1"- );- expect(newToken).toBeUndefined();- });-});--describe("detectPageTokenConflicts", () => {- beforeEach(() => {- $project.set({ id: "project-id" } as Project);- });-- test("returns empty array when no conflicts exist", () => {- // Set up target project data (no tokens)- const targetData = renderData(- <$.Body ws:id="body">- <$.Box ws:id="existing-box"></$.Box>- </$.Body>- );- setDataStores(targetData);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);-- // Create source data with a token- const sourceData = renderData(- <$.Body ws:id="source-body">- <$.Box- ws:id="source-box"- ws:tokens={[- token(- "primary",- css`- color: red;- `- ),- ]}- ></$.Box>- </$.Body>- );- const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });- const sourceWebstudioData: WebstudioData = {- ...sourceData,- pages: sourcePages,- };-- const conflicts = detectPageTokenConflicts({- sourceData: sourceWebstudioData,- pageId: sourcePages.homePageId,- });-- // No conflicts- expect(conflicts).toEqual([]);- });-- test("returns conflicts when token conflicts exist", () => {- // Set up target project with a "primary" token- const targetData = renderData(- <$.Body ws:id="body">- <$.Box- ws:id="existing-box"- ws:tokens={[- token(- "primary",- css`- color: blue;- `- ),- ]}- ></$.Box>- </$.Body>- );- setDataStores(targetData);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);-- // Create source data with same "primary" token but different styles- const sourceData = renderData(- <$.Body ws:id="source-body">- <$.Box- ws:id="source-box"- ws:tokens={[- token(- "primary",- css`- color: red;- `- ),- ]}- ></$.Box>- </$.Body>- );- const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });- const sourceWebstudioData: WebstudioData = {- ...sourceData,- pages: sourcePages,- };-- const conflicts = detectPageTokenConflicts({- sourceData: sourceWebstudioData,- pageId: sourcePages.homePageId,- });-- // Should return conflicts- expect(conflicts.length).toBeGreaterThan(0);- expect(conflicts[0].tokenName).toBe("primary");- });-- test("detects conflicts from ROOT_INSTANCE tokens", () => {- // Set up target project with a "header" token- const targetData = renderData(- <$.Body ws:id="body">- <$.Box- ws:id="existing-box"- ws:tokens={[- token(- "header",- css`- background: white;- `- ),- ]}- ></$.Box>- </$.Body>- );- setDataStores(targetData);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);-- // Create source data with a ROOT_INSTANCE that has conflicting "header" token- const sourceBodyData = renderData(- <$.Body ws:id="source-body">- <$.Box ws:id="source-box"></$.Box>- </$.Body>- );- // Add a global "header" token with different styles (simulating ROOT_INSTANCE content)- const headerTokenId = "header-token-id";- sourceBodyData.styleSources.set(headerTokenId, {- type: "token",- id: headerTokenId,- name: "header",- });- const baseBreakpointId = Array.from(- sourceBodyData.breakpoints.values()- ).find((b) => b.minWidth === undefined)?.id;- if (baseBreakpointId) {- sourceBodyData.styles.set(`${headerTokenId}:base:backgroundColor`, {- styleSourceId: headerTokenId,- breakpointId: baseBreakpointId,- property: "backgroundColor",- value: { type: "keyword", value: "black" },- });- }- // Add ROOT_INSTANCE with the header token- sourceBodyData.instances.set(ROOT_INSTANCE_ID, {- type: "instance",- id: ROOT_INSTANCE_ID,- component: "Box",- children: [],- });- sourceBodyData.styleSourceSelections.set(ROOT_INSTANCE_ID, {- instanceId: ROOT_INSTANCE_ID,- values: [headerTokenId],- });-- const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });- const sourceWebstudioData: WebstudioData = {- ...sourceBodyData,- pages: sourcePages,- };-- const conflicts = detectPageTokenConflicts({- sourceData: sourceWebstudioData,- pageId: sourcePages.homePageId,- });-- // Should detect conflict from ROOT_INSTANCE token- expect(conflicts.length).toBeGreaterThan(0);- expect(conflicts[0].tokenName).toBe("header");- });-- test("throws error when page not found", () => {- const targetData = renderData(<$.Body ws:id="body"></$.Body>);- setDataStores(targetData);- const pages = createDefaultPages({ rootInstanceId: "body" });- $pages.set(pages);-- const sourceData = renderData(<$.Body ws:id="source-body"></$.Body>);- const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });- const sourceWebstudioData: WebstudioData = {- ...sourceData,- pages: sourcePages,- };-- expect(() =>- detectPageTokenConflicts({- sourceData: sourceWebstudioData,- pageId: "non-existent-page-id",- })- ).toThrow("Page not found");- });-});diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsdeleted file mode 100644index 3fc55b6c77..0000000000--- a/apps/builder/app/shared/instance-utils.ts+++ /dev/null@@ -1,2282 +0,0 @@-import { current, isDraft } from "immer";-import { nanoid } from "nanoid";-import { toast } from "@webstudio-is/design-system";-import { builderApi } from "~/shared/builder-api";-import type { StyleValue } from "@webstudio-is/css-engine";-import { showAttribute } from "@webstudio-is/react-sdk";-import {- type Instances,- type Instance,- type StyleDecl,- type Asset,- type Breakpoints,- type DataSources,- type DataSource,- type WebstudioFragment,- type WebstudioData,- type Resource,- type WsComponentMeta,- type Pages,- findTreeInstanceIds,- findTreeInstanceIdsExcludingSlotDescendants,- getAllPages,- getHomePage,- findPageByIdOrPath,- ROOT_INSTANCE_ID,- portalComponent,- collectionComponent,- type Prop,- type Props,- elementComponent,- tags,- blockTemplateComponent,- isComponentDetachable,- isPageTemplate,-} from "@webstudio-is/sdk";-import { detectTokenConflicts } from "./style-source-utils";-import { type ConflictResolution } from "./token-conflict-dialog";-import { buildMergedBreakpointIds, maxBreakpoints } from "./breakpoints-utils";-import {- $registeredComponentMetas,- $registeredTemplates,- $isPreviewMode,- $textEditingInstanceSelector,- $isContentMode,- $canOpenPageTemplates,- findBlockSelector,-} from "./nano-states";-import { $props } from "~/shared/sync/data-stores";-import {- $styles,- $styleSourceSelections,- $styleSources,- $instances,- $dataSources,- $assets,- $breakpoints,- $pages,- $resources,- $project,-} from "~/shared/sync/data-stores";-import {- type DroppableTarget,- type InstanceSelector,- findLocalStyleSourcesWithinInstances,- getReparentDropTargetMutable,- getInstanceOrCreateFragmentIfNecessary,- wrapEditableChildrenAroundDropTargetMutable,-} from "./tree-utils";-import {- insertTokenStyleSources,- insertPortalLocalStyleSources,- insertLocalStyleSourcesWithNewIds,- deleteLocalStyleSourcesMutable,- collectStyleSourcesFromInstances,-} from "./style-source-utils";-import { removeByMutable } from "./array-utils";-import { serverSyncStore } from "./sync/sync-stores";-import { setDifference, setUnion } from "./shim";-import { breakCyclesMutable, findCycles } from "@webstudio-is/project-build";-import {- $selectedInstancePath,- $selectedInstanceSelector,- $selectedPage,- getInstancePath,- type InstancePath,-} from "./nano-states";-import { selectInstance } from "./nano-states";-import { findClosestInstanceMatchingFragment } from "./matcher";-import {- findAvailableVariables,- replaceDataSourcesInExpression,- restoreExpressionVariables,- unsetExpressionVariables,-} from "./data-variables";-import {- findClosestNonTextualContainer,- isRichTextTree,- isTreeSatisfyingContentModel,- isRichTextContent,-} from "./content-model";-import type { Project } from "@webstudio-is/project";-import {- getContentModeCapabilities,- isContentModeCopyableProp,-} from "@webstudio-is/project/content-mode-permissions";-import { getInstanceLabel } from "~/builder/shared/instance-label";-import { $instanceTags } from "~/builder/features/style-panel/shared/model";-import { reactPropsToStandardAttributes } from "@webstudio-is/react-sdk";--/**- * structuredClone can be invoked on draft and throw error- * extract current snapshot before cloning- */-export const unwrap = <Value>(value: Value) =>- isDraft(value) ? current(value) : value;--export const canDeleteInstanceInContentMode = ({- instanceSelector,- instances,-}: {- instanceSelector: InstanceSelector;- instances: Instances;-}) => {- const blockSelector = findBlockSelector(instanceSelector, instances);- if (blockSelector === undefined) {- return false;- }-- const isDirectBlockChild =- instanceSelector.length - blockSelector.length === 1;- if (isDirectBlockChild === false) {- return false;- }-- return (- instances.get(instanceSelector[0])?.component !== blockTemplateComponent- );-};--export const updateWebstudioData = (mutate: (data: WebstudioData) => void) => {- const selectedPage = $selectedPage.get();- if (isPageTemplate(selectedPage) && $canOpenPageTemplates.get() === false) {- return;- }- 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 cycles = findCycles(instances.values());-- // Detect and fix cycles in the instance tree, then report- if (cycles.length > 0) {- toast.info("Detected and fixed cycles in the instance tree.");-- breakCyclesMutable(- instances.values(),- (node) => node.component === "Slot"- );- }- }- );-};--export const getWebstudioData = (): WebstudioData => {- const pages = $pages.get();- if (pages === undefined) {- throw Error(`Cannot get webstudio data with empty pages`);- }- return {- pages,- instances: $instances.get(),- props: $props.get(),- dataSources: $dataSources.get(),- resources: $resources.get(),- breakpoints: $breakpoints.get(),- styleSourceSelections: $styleSourceSelections.get(),- styleSources: $styleSources.get(),- styles: $styles.get(),- assets: $assets.get(),- };-};--export const findAllEditableInstanceSelector = ({- instanceSelector,- instances,- props,- metas,- results,-}: {- instanceSelector: InstanceSelector;- instances: Instances;- props: Props;- metas: Map<string, WsComponentMeta>;- results: InstanceSelector[];-}) => {- const [instanceId] = instanceSelector;-- if (instanceId === undefined) {- return;- }-- // Check if current instance is text editing instance- if (isRichTextTree({ instanceId, instances, props, metas })) {- results.push(instanceSelector);- return;- }-- const instance = instances.get(instanceId);- if (instance) {- for (const child of instance.children) {- if (child.type === "id") {- findAllEditableInstanceSelector({- instanceSelector: [child.value, ...instanceSelector],- instances,- props,- metas,- results,- });- }- }- }-};--export const insertInstanceChildrenMutable = (- data: Omit<WebstudioData, "pages">,- children: Instance["children"],- insertTarget: Insertable-) => {- const dropTarget: DroppableTarget = {- parentSelector: insertTarget.parentSelector,- position: insertTarget.position === "after" ? "end" : insertTarget.position,- };- const metas = $registeredComponentMetas.get();- insertTarget =- getInstanceOrCreateFragmentIfNecessary(data.instances, dropTarget) ??- insertTarget;- insertTarget =- wrapEditableChildrenAroundDropTargetMutable(- data.instances,- data.props,- metas,- dropTarget- ) ?? insertTarget;- const [parentInstanceId] = insertTarget.parentSelector;- const parentInstance = data.instances.get(parentInstanceId);- if (parentInstance === undefined) {- return;- }- if (dropTarget.position === "end") {- parentInstance.children.push(...children);- } else {- parentInstance.children.splice(dropTarget.position, 0, ...children);- }-};--export const insertWebstudioElementAt = (insertable?: Insertable) => {- const instances = $instances.get();- const props = $props.get();- const metas = $registeredComponentMetas.get();- // find closest container and try to match new element with it- if (insertable === undefined) {- const instancePath = $selectedInstancePath.get();- if (instancePath === undefined) {- return false;- }- const [{ instanceSelector }] = instancePath;- const containerSelector = findClosestNonTextualContainer({- instances,- props,- metas,- instanceSelector,- });- const insertableIndex = instanceSelector.length - containerSelector.length;- if (insertableIndex === 0) {- insertable = {- parentSelector: containerSelector,- position: "end",- };- } else {- const containerInstance = instances.get(containerSelector[0]);- if (containerInstance === undefined) {- return false;- }- const lastChildInstanceId = instanceSelector[insertableIndex - 1];- const lastChildPosition = containerInstance.children.findIndex(- (child) => child.type === "id" && child.value === lastChildInstanceId- );- insertable = {- parentSelector: containerSelector,- position: lastChildPosition + 1,- };- }- }- // create element and find matching tag- const element: Instance = {- type: "instance",- id: nanoid(),- component: elementComponent,- children: [],- };- const newInstances = new Map(instances);- newInstances.set(element.id, element);- let matchingTag: undefined | string;- for (const tag of tags) {- element.tag = tag;- const isSatisfying = isTreeSatisfyingContentModel({- instances: newInstances,- props,- metas,- instanceSelector: [element.id, ...insertable.parentSelector],- });- if (isSatisfying) {- matchingTag = tag;- break;- }- }- if (matchingTag === undefined) {- return false;- }- // insert element- updateWebstudioData((data) => {- data.instances.set(element.id, element);- const children: Instance["children"] = [{ type: "id", value: element.id }];- insertInstanceChildrenMutable(data, children, insertable);- });- selectInstance([element.id, ...insertable.parentSelector]);- return true;-};--export const insertWebstudioFragmentAt = (- fragment: WebstudioFragment,- insertable?: Insertable,- conflictResolution?: ConflictResolution,- options?: { onBreakpointLimitMerge?: () => void }-): boolean => {- const hasChildren = fragment.children.length > 0;- const hasTokens = fragment.styleSources.length > 0;- if (!hasChildren && !hasTokens) {- return false;- }- // Tokens-only fragment: insert tokens/breakpoints/styles without instances- if (!hasChildren && hasTokens) {- const project = $project.get();- if (project === undefined) {- return false;- }- updateWebstudioData((data) => {- insertWebstudioFragmentCopy({- data,- fragment,- availableVariables: [],- projectId: project.id,- conflictResolution,- onBreakpointLimitMerge: options?.onBreakpointLimitMerge,- });- });- return true;- }- const project = $project.get();- insertable = findClosestInsertable(fragment, insertable) ?? insertable;- if (project === undefined || insertable === undefined) {- return false;- }- let newInstanceSelector: undefined | InstanceSelector;- updateWebstudioData((data) => {- const instancePath = getInstancePath(- insertable.parentSelector,- data.instances- );- if (instancePath === undefined) {- return;- }- const { newInstanceIds } = insertWebstudioFragmentCopy({- data,- fragment,- availableVariables: findAvailableVariables({- ...data,- startingInstanceId: instancePath[0].instance.id,- }),- projectId: project.id,- conflictResolution,- onBreakpointLimitMerge: options?.onBreakpointLimitMerge,- });- const children: Instance["children"] = fragment.children.map((child) => {- if (child.type === "id") {- return {- type: "id",- value: newInstanceIds.get(child.value) ?? child.value,- };- }- return child;- });- let parentSelector;- let position: number | "end";- if (insertable.position === "after") {- if (instancePath.length === 1) {- parentSelector = insertable.parentSelector;- position = "end";- } else {- parentSelector = instancePath[1].instanceSelector;- const [{ instance }, { instance: parentInstance }] = instancePath;- const index = parentInstance.children.findIndex(- (child) => child.type === "id" && child.value === instance.id- );- position = 1 + index;- }- } else {- parentSelector = insertable.parentSelector;- position = insertable.position;- }- insertInstanceChildrenMutable(data, children, {- parentSelector,- position,- });- newInstanceSelector = [children[0].value, ...parentSelector];- });- if (newInstanceSelector) {- selectInstance(newInstanceSelector);- }- return true;-};--export const getComponentTemplateData = (- componentOrTemplate: string-): WebstudioFragment => {- const templates = $registeredTemplates.get();- const templateMeta = templates.get(componentOrTemplate);- if (templateMeta) {- return templateMeta.template;- }- const newInstance: Instance = {- id: nanoid(),- type: "instance",- component: componentOrTemplate,- children: [],- };- return {- children: [{ type: "id", value: newInstance.id }],- instances: [newInstance],- props: [],- dataSources: [],- styleSourceSelections: [],- styleSources: [],- styles: [],- breakpoints: [],- assets: [],- resources: [],- };-};--export const reparentInstanceMutable = (- data: Omit<WebstudioData, "pages">,- sourceInstanceSelector: InstanceSelector,- dropTarget: DroppableTarget-) => {- const project = $project.get();- if (project === undefined) {- return;- }- const initialSourceInstancePath = getInstancePath(- sourceInstanceSelector,- data.instances- );- const sourceFragmentId =- initialSourceInstancePath?.[1]?.instance.component === "Fragment" &&- initialSourceInstancePath[2]?.instance.component === "Slot"- ? initialSourceInstancePath[1].instance.id- : undefined;- const targetSlot = data.instances.get(dropTarget.parentSelector[0]);- const isSameSharedSlotFragment =- sourceFragmentId !== undefined &&- targetSlot?.component === "Slot" &&- targetSlot.children[0]?.type === "id" &&- targetSlot.children[0].value === sourceFragmentId;- const sourceInstancePath = isSameSharedSlotFragment- ? (initialSourceInstancePath ?? [])- : detachSharedSlotContentMutable(data, initialSourceInstancePath ?? []);- sourceInstanceSelector = sourceInstancePath[0]?.instanceSelector;- if (sourceInstanceSelector === undefined) {- return;- }- const [rootInstanceId] = sourceInstanceSelector;- // delect is target is one of own descendants- // prevent reparenting to avoid infinite loop- const instanceDescendants = findTreeInstanceIds(- data.instances,- rootInstanceId- );- for (const instanceId of instanceDescendants) {- if (dropTarget.parentSelector.includes(instanceId)) {- return;- }- }- // try to use slot fragment as target instead of slot itself- const parentInstance = data.instances.get(dropTarget.parentSelector[0]);- if (- parentInstance?.component === portalComponent &&- parentInstance.children.length > 0 &&- parentInstance.children[0].type === "id"- ) {- const fragmentId = parentInstance.children[0].value;- dropTarget = {- parentSelector: [fragmentId, ...dropTarget.parentSelector],- position: dropTarget.position,- };- }- // move within same parent- if (sourceInstanceSelector[1] === dropTarget.parentSelector[0]) {- const [parentId] = dropTarget.parentSelector;- const parent = data.instances.get(parentId);- if (parent === undefined) {- return;- }- const prevPosition = parent.children.findIndex(- (child) => child.type === "id" && child.value === rootInstanceId- );- const child = parent.children[prevPosition];- parent?.children.splice(prevPosition, 1);- if (dropTarget.position === "end") {- parent?.children.push(child);- } else {- // when parent is the same, we need to adjust the position- // to account for the removal of the instance.- let nextPosition = dropTarget.position;- if (prevPosition < nextPosition) {- nextPosition -= 1;- }- parent?.children.splice(nextPosition, 0, child);- }- return sourceInstanceSelector;- }- // move into another parent- const fragment = extractWebstudioFragment(data, rootInstanceId);- deleteInstanceMutable(- data,- getInstancePath(sourceInstanceSelector, data.instances)- );- // prepare drop target after deleting instance to recreate new slot fragment- dropTarget =- getReparentDropTargetMutable(- data.instances,- data.props,- $registeredComponentMetas.get(),- dropTarget- ) ?? dropTarget;- const { newInstanceIds } = insertWebstudioFragmentCopy({- data,- fragment,- availableVariables: findAvailableVariables({- ...data,- startingInstanceId: dropTarget.parentSelector[0],- }),- projectId: project.id,- });- const [newParentId] = dropTarget.parentSelector;- const newRootInstanceId =- newInstanceIds.get(rootInstanceId) ?? rootInstanceId;- const newParent = data.instances.get(newParentId);- const newChild = { type: "id" as const, value: newRootInstanceId };- if (dropTarget.position === "end") {- newParent?.children.push(newChild);- } else {- newParent?.children.splice(dropTarget.position, 0, newChild);- }- return [newRootInstanceId, ...dropTarget.parentSelector];-};--export const reparentInstance = (- sourceInstanceSelector: InstanceSelector,- dropTarget: DroppableTarget-) => {- updateWebstudioData((data) => {- const newSelector = reparentInstanceMutable(- data,- sourceInstanceSelector,- dropTarget- );- selectInstance(newSelector);- });-};--const countInstanceChildReferences = (- instances: Instances,- instanceId: Instance["id"]-) => {- let count = 0;- for (const instance of instances.values()) {- for (const child of instance.children) {- if (child.type === "id" && child.value === instanceId) {- count += 1;- }- }- }- return count;-};--export const deleteInstanceMutable = (- data: Omit<WebstudioData, "pages">,- instancePath: undefined | InstancePath-) => {- if (instancePath === undefined) {- return false;- }- const {- instances,- props,- styleSourceSelections,- styleSources,- styles,- dataSources,- resources,- } = data;- let targetInstance = instancePath[0].instance;- let parentInstance =- instancePath.length > 1 ? instancePath[1]?.instance : undefined;- const grandparentInstance =- instancePath.length > 2 ? instancePath[2]?.instance : undefined;-- // 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 &&- countInstanceChildReferences(instances, parentInstance.id) < 2- ) {- targetInstance = parentInstance;- parentInstance = grandparentInstance;- }-- const instanceIds = findTreeInstanceIdsExcludingSlotDescendants(- instances,- targetInstance.id- );- const localStyleSourceIds = findLocalStyleSourcesWithinInstances(- styleSources.values(),- styleSourceSelections.values(),- instanceIds- );-- // mutate instances from data instead of instance path- parentInstance = data.instances.get(parentInstance?.id as string);- // may not exist when delete root- if (parentInstance) {- removeByMutable(- parentInstance.children,- (child) => child.type === "id" && child.value === targetInstance.id- );- }-- 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);- if (prop.type === "resource") {- resources.delete(prop.value);- }- }- }- for (const dataSource of dataSources.values()) {- if (instanceIds.has(dataSource.scopeInstanceId ?? "")) {- dataSources.delete(dataSource.id);- if (dataSource.type === "resource") {- resources.delete(dataSource.resourceId);- }- }- }- for (const instanceId of instanceIds) {- styleSourceSelections.delete(instanceId);- }- deleteLocalStyleSourcesMutable({- localStyleSourceIds,- styleSources,- styles,- });- return true;-};--const cloneSharedSlotFragmentMutable = (- data: Omit<WebstudioData, "pages">,- slotId: Instance["id"],- fragmentId: Instance["id"]-) => {- if (countInstanceChildReferences(data.instances, fragmentId) < 2) {- return;- }- const projectId = $project.get()?.id ?? "";- const fragment = extractWebstudioFragment(data, fragmentId);- const { newInstanceIds } = insertWebstudioFragmentCopy({- data,- fragment,- availableVariables: findAvailableVariables({- ...data,- startingInstanceId: slotId,- }),- projectId,- });- const newFragmentId = newInstanceIds.get(fragmentId);- const slot = data.instances.get(slotId);- if (slot === undefined || newFragmentId === undefined) {- return;- }- for (const child of slot.children) {- if (child.type === "id" && child.value === fragmentId) {- child.value = newFragmentId;- }- }- return newInstanceIds;-};--export const detachSharedSlotChildrenMutable = (- data: Omit<WebstudioData, "pages">,- slotId: Instance["id"]-) => {- const slot = data.instances.get(slotId);- const fragmentId =- slot?.children[0]?.type === "id" ? slot.children[0].value : undefined;- if (slot?.component !== "Slot" || fragmentId === undefined) {- return;- }- cloneSharedSlotFragmentMutable(data, slotId, fragmentId);-};--export const detachSharedSlotContentMutable = (- data: Omit<WebstudioData, "pages">,- instancePath: InstancePath-) => {- const slotIndex = instancePath.findIndex(- (item, index) =>- item.instance.component === "Slot" &&- instancePath[index - 1]?.instance.component === "Fragment"- );- if (slotIndex === -1) {- return instancePath;- }- const fragmentItem = instancePath[slotIndex - 1];- const slotItem = instancePath[slotIndex];- const newInstanceIds = cloneSharedSlotFragmentMutable(- data,- slotItem.instance.id,- fragmentItem.instance.id- );- if (newInstanceIds === undefined) {- return instancePath;- }- const newInstanceSelector = instancePath[0].instanceSelector.map(- (instanceId, index) =>- index < slotIndex- ? (newInstanceIds.get(instanceId) ?? instanceId)- : instanceId- );- return getInstancePath(newInstanceSelector, data.instances) ?? instancePath;-};--export const unwrapInstanceMutable = ({- instances,- props,- metas,- selectedItem,- parentItem,-}: {- instances: Map<string, Instance>;- props: Props;- metas: Map<string, WsComponentMeta>;- selectedItem: {- instanceSelector: InstanceSelector;- instance: { id: string };- };- parentItem: { instanceSelector: InstanceSelector; instance: { id: string } };-}): { success: boolean; error?: string } => {- // Check if the selected instance is rich text content (like Bold, Italic in Paragraph)- if (- isRichTextContent({- instanceSelector: selectedItem.instanceSelector,- instances,- props,- metas,- })- ) {- return { success: false, error: "Cannot unwrap textual instance" };- }-- const parentInstance = instances.get(parentItem.instance.id);- const selectedInstance = instances.get(selectedItem.instance.id);- if (!parentInstance || !selectedInstance) {- return { success: false, error: "Instance not found" };- }-- // Get grandparent to replace parent with selected- const grandparentId = parentItem.instanceSelector[1];- if (!grandparentId) {- return { success: false, error: "Cannot unwrap instance at root level" };- }- const grandparentInstance = instances.get(grandparentId);- if (!grandparentInstance) {- return { success: false, error: "Grandparent instance not found" };- }-- const selectedParentId = selectedItem.instanceSelector[1];- const selectedParentInstance = instances.get(selectedParentId);- if (- parentInstance.component === "Slot" &&- selectedParentInstance?.component === "Fragment" &&- selectedItem.instanceSelector[2] === parentItem.instance.id &&- selectedParentInstance.children.length === 1 &&- selectedParentInstance.children[0]?.type === "id" &&- selectedParentInstance.children[0].value === selectedItem.instance.id- ) {- const parentIndex = grandparentInstance.children.findIndex(- (child) => child.type === "id" && child.value === parentItem.instance.id- );- if (parentIndex !== -1) {- grandparentInstance.children[parentIndex] = {- type: "id",- value: selectedItem.instance.id,- };- }-- const isInstanceReferenced = (instanceId: Instance["id"]) => {- for (const instance of instances.values()) {- if (- instance.children.some(- (child) => child.type === "id" && child.value === instanceId- )- ) {- return true;- }- }- return false;- };- if (isInstanceReferenced(parentItem.instance.id) === false) {- instances.delete(parentItem.instance.id);- }- if (isInstanceReferenced(selectedParentInstance.id) === false) {- instances.delete(selectedParentInstance.id);- }-- const matches = isTreeSatisfyingContentModel({- instances,- props,- metas,- instanceSelector: [- selectedItem.instance.id,- ...parentItem.instanceSelector.slice(1),- ],- });- if (matches === false) {- return { success: false, error: "Cannot unwrap instance" };- }-- return { success: true };- }-- // Slot children may be rendered through multiple slot instances with the same- // ids. In that case use the selected path to unwrap only the selected slot- // occurrence and preserve the shared parent tree for other slot occurrences.- if (instances.get(parentItem.instanceSelector[1])?.component === "Slot") {- const parentIndex = grandparentInstance.children.findIndex(- (child) => child.type === "id" && child.value === parentItem.instance.id- );- if (parentIndex !== -1) {- grandparentInstance.children[parentIndex] = {- type: "id",- value: selectedItem.instance.id,- };- }-- const matches = isTreeSatisfyingContentModel({- instances,- props,- metas,- instanceSelector: [- selectedItem.instance.id,- ...parentItem.instanceSelector.slice(1),- ],- });- if (matches === false) {- return { success: false, error: "Cannot unwrap instance" };- }-- return { success: true };- }-- // Remove selected instance from parent's children- const selectedIndexInParent = parentInstance.children.findIndex(- (child) => child.type === "id" && child.value === selectedItem.instance.id- );- if (selectedIndexInParent !== -1) {- parentInstance.children.splice(selectedIndexInParent, 1);- }-- // If parent has no more children, delete it- if (parentInstance.children.length === 0) {- instances.delete(parentItem.instance.id);- }-- // Add selected instance to grandparent at parent's position- const parentIndex = grandparentInstance.children.findIndex(- (child) => child.type === "id" && child.value === parentItem.instance.id- );- if (parentIndex !== -1) {- if (parentInstance.children.length === 0) {- // Replace parent with selected if parent is now empty- grandparentInstance.children[parentIndex] = {- type: "id",- value: selectedItem.instance.id,- };- } else {- // Insert selected after parent if parent still has children- grandparentInstance.children.splice(parentIndex + 1, 0, {- type: "id",- value: selectedItem.instance.id,- });- }- }-- const matches = isTreeSatisfyingContentModel({- instances,- props,- metas,- instanceSelector: [- selectedItem.instance.id,- ...parentItem.instanceSelector.slice(1),- ],- });- if (matches === false) {- return { success: false, error: "Cannot unwrap instance" };- }-- return { success: true };-};--export const canUnwrapInstance = (instancePath: InstancePath) => {- // Need at least 3 levels: selected, parent, and grandparent- // Can't unwrap if there's no grandparent to move the selected instance to- if (instancePath.length < 3) {- return false;- }- const [selectedItem, parentItem] = instancePath;-- // Prevent unwrapping if parent is the root instance (e.g., Body)- const rootInstanceId = $selectedPage.get()?.rootInstanceId;- if (- rootInstanceId !== undefined &&- parentItem.instance.id === rootInstanceId- ) {- return false;- }-- // Check if the selected instance is rich text content (like Bold, Italic in Paragraph)- const instances = $instances.get();- const props = $props.get();- const metas = $registeredComponentMetas.get();-- if (- isRichTextContent({- instanceSelector: selectedItem.instanceSelector,- instances,- props,- metas,- })- ) {- return false;- }-- return true;-};--export const toggleInstanceShow = (instanceId: Instance["id"]) => {- serverSyncStore.createTransaction([$props], (props) => {- const allProps = Array.from(props.values());- const instanceProps = allProps.filter(- (prop) => prop.instanceId === instanceId- );- let showProp = instanceProps.find((prop) => prop.name === showAttribute);-- // Toggle the show value- const newValue = showProp?.type === "boolean" ? !showProp.value : false;-- if (showProp === undefined) {- showProp = {- id: nanoid(),- instanceId,- name: showAttribute,- type: "boolean",- value: newValue,- };- }- if (showProp.type === "boolean") {- props.set(showProp.id, { ...showProp, value: newValue });- }- });-};--export const wrapInstance = (component: string, tag?: string) => {- const instancePath = $selectedInstancePath.get();- // global root or body are selected- if (instancePath === undefined || instancePath.length === 1) {- return;- }- const newInstanceId = nanoid();- let newInstanceSelector: InstanceSelector | undefined;- const metas = $registeredComponentMetas.get();-- try {- updateWebstudioData((data) => {- const detachedInstancePath = detachSharedSlotContentMutable(- data,- instancePath- );- const [selectedItem, parentItem] = detachedInstancePath;- if (parentItem === undefined) {- return;- }- const selectedInstance = selectedItem.instance;- const nextInstanceSelector = [- newInstanceId,- ...parentItem.instanceSelector,- ];- newInstanceSelector = nextInstanceSelector;- const isContent = isRichTextContent({- instanceSelector: selectedItem.instanceSelector,- instances: data.instances,- props: data.props,- metas,- });- if (isContent) {- toast.error(`Cannot wrap textual content`);- throw Error("Abort transaction");- }- const newInstance: Instance = {- type: "instance",- id: newInstanceId,- component,- children: [{ type: "id", value: selectedInstance.id }],- };-- if (tag || component === elementComponent) {- newInstance.tag = tag ?? "div";- }- const parentInstance = data.instances.get(parentItem.instance.id);- data.instances.set(newInstanceId, newInstance);- if (parentInstance) {- for (const child of parentInstance.children) {- if (child.type === "id" && child.value === selectedInstance.id) {- child.value = newInstanceId;- }- }- }-- const isSatisfying = isTreeSatisfyingContentModel({- instances: data.instances,- props: data.props,- metas,- instanceSelector: nextInstanceSelector,- });-- if (isSatisfying === false) {- const label = getInstanceLabel({ component, tag });- toast.error(`Cannot wrap in ${label}`);- throw Error("Abort transaction");- }- });- selectInstance(newInstanceSelector);- } catch {- // do nothing- }-};--// Check if an instance can be converted to a specific component or tag-export const canConvertInstance = (- selectedInstanceId: string,- selectedInstanceSelector: string[],- component: string,- tag: string | undefined,- instances: Instances,- props: Props,- metas: Map<Instance["component"], WsComponentMeta>-): boolean => {- const selectedInstance = instances.get(selectedInstanceId);-- if (!selectedInstance) {- return false;- }-- // Create a test instance with the new component/tag- const testInstance: Instance = {- ...selectedInstance,- component,- };-- if (tag || component === elementComponent) {- testInstance.tag = tag ?? "div";- } else {- // For components with presetStyle (like Heading, Box), infer default tag- const meta = metas.get(component);- const defaultTag = Object.keys(- (meta as { presetStyle?: Record<string, unknown> })?.presetStyle ?? {}- ).at(0);- if (defaultTag) {- testInstance.tag = defaultTag;- }- }-- const newInstances = new Map(instances);- newInstances.set(testInstance.id, testInstance);-- // Validate the converted instance satisfies content model- return isTreeSatisfyingContentModel({- instances: newInstances,- props,- metas,- instanceSelector: selectedInstanceSelector,- });-};--export const convertInstance = (component: string, tag?: string) => {- const instancePath = $selectedInstancePath.get();- // global root or body are selected- if (instancePath === undefined || instancePath.length === 1) {- return;- }- const [selectedItem] = instancePath;- const selectedInstance = selectedItem.instance;- const selectedInstanceSelector = selectedItem.instanceSelector;- const metas = $registeredComponentMetas.get();- const instanceTags = $instanceTags.get();- try {- updateWebstudioData((data) => {- if (selectedInstance.component === "Slot" && component !== "Slot") {- detachSharedSlotChildrenMutable(data, selectedInstance.id);- }- const instance = data.instances.get(selectedInstance.id);- if (instance === undefined) {- return;- }- instance.component = component;- // convert to specified tag or with currently used- if (tag || component === elementComponent) {- instance.tag = tag ?? instanceTags.get(selectedInstance.id) ?? "div";- // delete legacy tag prop if specified- for (const prop of data.props.values()) {- if (prop.instanceId !== selectedInstance.id) {- continue;- }- if (prop.name === "tag") {- data.props.delete(prop.id);- continue;- }- const newName = reactPropsToStandardAttributes[prop.name];- if (newName) {- const newId = `${prop.instanceId}:${newName}`;- data.props.delete(prop.id);- data.props.set(newId, { ...prop, id: newId, name: newName });- }- }- }- const isSatisfying = isTreeSatisfyingContentModel({- instances: data.instances,- props: data.props,- metas,- instanceSelector: selectedInstanceSelector,- });- if (isSatisfying === false) {- const label = getInstanceLabel({ component, tag });- toast.error(`Cannot convert to ${label}`);- throw Error("Abort transaction");- }- });- } catch {- // do nothing- }-};--export const unwrapInstance = () => {- const instancePath = $selectedInstancePath.get();- if (instancePath === undefined || !canUnwrapInstance(instancePath)) {- return;- }-- try {- updateWebstudioData((data) => {- const detachedInstancePath = detachSharedSlotContentMutable(- data,- instancePath- );- const [selectedItem, defaultParentItem] = detachedInstancePath;- const parentItem =- defaultParentItem?.instance.component === "Fragment" &&- detachedInstancePath[2]?.instance.component === "Slot"- ? detachedInstancePath[2]- : defaultParentItem;- if (parentItem === undefined) {- return;- }-- const result = unwrapInstanceMutable({- instances: data.instances,- props: data.props,- metas: $registeredComponentMetas.get(),- selectedItem,- parentItem,- });-- if (!result.success) {- toast.error(result.error ?? "Cannot unwrap instance");- throw Error("Abort transaction");- }-- // After unwrap, select the child that replaced the parent.- selectInstance([- selectedItem.instance.id,- ...parentItem.instanceSelector.slice(1),- ]);- });- } catch {- // do nothing- }-};--export const deleteSelectedInstance = () => {- if ($isPreviewMode.get()) {- return;- }- const textEditingInstanceSelector = $textEditingInstanceSelector.get();- const instancePath = $selectedInstancePath.get();- // cannot delete instance while editing- if (textEditingInstanceSelector) {- return;- }- if (instancePath === undefined || instancePath.length === 1) {- return;- }- const [selectedItem, parentItem] = instancePath;- const selectedInstanceSelector = selectedItem.instanceSelector;- const instances = $instances.get();- if (!isComponentDetachable(selectedItem.instance.component)) {- toast.error(- "This instance can not be moved outside of its parent component."- );- return false;- }-- if ($isContentMode.get()) {- if (- canDeleteInstanceInContentMode({- instanceSelector: selectedInstanceSelector,- instances,- }) === false- ) {- builderApi.toast.info("You can't delete this instance in content mode.");- return;- }- }-- // find next selected instance- let newSelectedInstanceSelector: undefined | InstanceSelector;- const parentInstanceSelector = parentItem.instanceSelector;- const siblingIds = parentItem.instance.children- .filter((child) => child.type === "id")- .map((child) => child.value);- const position = siblingIds.indexOf(selectedItem.instance.id);- const siblingId = siblingIds[position + 1] ?? siblingIds[position - 1];- if (siblingId) {- // select next or previous sibling if possible- newSelectedInstanceSelector = [siblingId, ...parentInstanceSelector];- } else {- // fallback to parent- newSelectedInstanceSelector = parentInstanceSelector;- }- updateWebstudioData((data) => {- if (deleteInstanceMutable(data, instancePath)) {- selectInstance(newSelectedInstanceSelector);- }- });-};--const traverseStyleValue = (- value: StyleValue,- callback: (value: StyleValue) => void-) => {- if (- value.type === "fontFamily" ||- value.type === "image" ||- value.type === "unit" ||- value.type === "keyword" ||- value.type === "unparsed" ||- value.type === "invalid" ||- value.type === "unset" ||- value.type === "color" ||- value.type === "rgb" ||- value.type === "function" ||- value.type === "guaranteedInvalid"- ) {- callback(value);- return;- }- if (value.type === "var") {- if (value.fallback) {- traverseStyleValue(value.fallback, callback);- }- return;- }- if (value.type === "tuple" || value.type === "layers") {- for (const item of value.value) {- traverseStyleValue(item, callback);- }- return;- }- if (value.type === "shadow") {- traverseStyleValue(value.offsetX, callback);- traverseStyleValue(value.offsetY, callback);- if (value.blur) {- traverseStyleValue(value.blur, callback);- }- if (value.spread) {- traverseStyleValue(value.spread, callback);- }- if (value.color) {- traverseStyleValue(value.color, callback);- }- return;- }- value satisfies never;-};--export const extractWebstudioFragment = (- data: Omit<WebstudioData, "pages">,- rootInstanceId: string,- options: { unsetVariables?: Set<DataSource["id"]> } = {}-): WebstudioFragment => {- const {- assets,- instances,- dataSources,- resources,- props,- styleSourceSelections,- styleSources,- breakpoints,- styles,- } = data;-- // collect the instance by id and all its descendants including portal instances- const fragmentInstanceIds = findTreeInstanceIds(instances, rootInstanceId);- let fragmentInstances: Instance[] = [];-- // Collect style sources and selections from instances- const {- styleSourceSelectionsArray: fragmentStyleSourceSelections,- styleSourcesMap: fragmentStyleSources,- stylesArray: fragmentStyles,- } = collectStyleSourcesFromInstances({- instanceIds: fragmentInstanceIds,- styleSourceSelections,- styleSources,- styles,- });-- for (const instanceId of fragmentInstanceIds) {- const instance = instances.get(instanceId);- if (instance) {- fragmentInstances.push(instance);- }- }-- const fragmentAssetIds = new Set<Asset["id"]>();- const fragmentFontFamilies = new Set<string>();-- // collect breakpoints and assets from styles- const fragmentBreapoints: Breakpoints = new Map();- for (const styleDecl of fragmentStyles) {- // collect breakpoints- if (fragmentBreapoints.has(styleDecl.breakpointId) === false) {- const breakpoint = breakpoints.get(styleDecl.breakpointId);- if (breakpoint) {- fragmentBreapoints.set(styleDecl.breakpointId, breakpoint);- }- }-- // collect assets including fonts- traverseStyleValue(styleDecl.value, (value) => {- if (value.type === "fontFamily") {- for (const fontFamily of value.value) {- fragmentFontFamilies.add(fontFamily);- }- }- if (value.type === "image") {- if (value.value.type === "asset") {- fragmentAssetIds.add(value.value.value);- }- }- });- }-- // collect variables scoped to fragment instances- // and variables outside of scope to unset- const fragmentDataSources: DataSources = new Map();- const fragmentResourceIds = new Set<Resource["id"]>();- const unsetNameById = new Map<DataSource["id"], DataSource["name"]>();- const unsetVariables = options.unsetVariables ?? new Set();- for (const dataSource of dataSources.values()) {- if (- fragmentInstanceIds.has(dataSource.scopeInstanceId ?? "") &&- unsetVariables.has(dataSource.id) === false- ) {- fragmentDataSources.set(dataSource.id, dataSource);- if (dataSource.type === "resource") {- fragmentResourceIds.add(dataSource.resourceId);- }- } else {- unsetNameById.set(dataSource.id, dataSource.name);- }- }-- // unset variables outside of scope- fragmentInstances = fragmentInstances.map((instance) => {- instance = structuredClone(unwrap(instance));- for (const child of instance.children) {- if (child.type === "expression") {- const expression = child.value;- child.value = unsetExpressionVariables({ expression, unsetNameById });- }- }- return instance;- });-- // collect props bound to these instances- // and unset variables outside of scope- const fragmentProps: Prop[] = [];- for (const prop of props.values()) {- if (fragmentInstanceIds.has(prop.instanceId) === false) {- continue;- }-- if (prop.type === "expression") {- const newProp = structuredClone(unwrap(prop));- const expression = prop.value;- newProp.value = unsetExpressionVariables({ expression, unsetNameById });- fragmentProps.push(newProp);- continue;- }-- if (prop.type === "action") {- const newProp = structuredClone(unwrap(prop));- for (const value of newProp.value) {- const expression = value.code;- value.code = unsetExpressionVariables({ expression, unsetNameById });- }- fragmentProps.push(newProp);- continue;- }-- fragmentProps.push(prop);-- // collect assets- if (prop.type === "asset") {- fragmentAssetIds.add(prop.value);- }-- // collect resources from props- if (prop.type === "resource") {- fragmentResourceIds.add(prop.value);- }- }-- // collect resources bound to all fragment data sources- // and unset variables which are defined outside of scope- // and used in resource- const fragmentResources: Resource[] = [];- for (const resourceId of fragmentResourceIds) {- const resource = resources.get(resourceId);- if (resource === undefined) {- continue;- }- const newResource = structuredClone(unwrap(resource));- newResource.url = unsetExpressionVariables({- expression: newResource.url,- unsetNameById,- });- for (const header of newResource.headers) {- header.value = unsetExpressionVariables({- expression: header.value,- unsetNameById,- });- }- if (newResource.searchParams) {- for (const searchParam of newResource.searchParams) {- searchParam.value = unsetExpressionVariables({- expression: searchParam.value,- unsetNameById,- });- }- }- if (newResource.body) {- newResource.body = unsetExpressionVariables({- expression: newResource.body,- unsetNameById,- });- }- fragmentResources.push(newResource);- }-- const fragmentAssets: Asset[] = [];- for (const asset of assets.values()) {- if (- fragmentAssetIds.has(asset.id) ||- (asset.type === "font" && fragmentFontFamilies.has(asset.meta.family))- ) {- fragmentAssets.push(asset);- }- }-- return {- children: [{ type: "id", value: rootInstanceId }],- instances: fragmentInstances,- styleSourceSelections: fragmentStyleSourceSelections,- styleSources: Array.from(fragmentStyleSources.values()),- breakpoints: Array.from(fragmentBreapoints.values()),- styles: fragmentStyles,- dataSources: Array.from(fragmentDataSources.values()),- resources: fragmentResources,- props: fragmentProps,- assets: fragmentAssets,- };-};--const getFragmentInstancesData = (fragment: WebstudioFragment) => {- const fragmentInstances: Instances = new Map();- const portalContentRootIds = new Set<Instance["id"]>();- for (const instance of fragment.instances) {- fragmentInstances.set(instance.id, instance);- if (instance.component === portalComponent) {- for (const child of instance.children) {- if (child.type === "id") {- portalContentRootIds.add(child.value);- }- }- }- }- return { fragmentInstances, portalContentRootIds };-};--const insertFragmentAssetsMutable = ({- fragment,- projectId,- assets,-}: {- fragment: WebstudioFragment;- projectId: Project["id"];- assets: WebstudioData["assets"];-}) => {- for (const asset of fragment.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 });- }- }-};--const insertFragmentBreakpointsMutable = ({- fragment,- breakpoints,- onBreakpointLimitMerge,-}: {- fragment: WebstudioFragment;- breakpoints: Breakpoints;- onBreakpointLimitMerge?: () => void;-}) => {- let didMergeBreakpointsDueToLimit = false;- const mergedBreakpointIds = buildMergedBreakpointIds(- fragment.breakpoints,- breakpoints,- {- maxBreakpointCount: maxBreakpoints,- onBreakpointMergedDueToLimit: () => {- didMergeBreakpointsDueToLimit = true;- },- }- );- if (didMergeBreakpointsDueToLimit) {- onBreakpointLimitMerge?.();- }- for (const newBreakpoint of fragment.breakpoints) {- if (mergedBreakpointIds.has(newBreakpoint.id) === false) {- breakpoints.set(newBreakpoint.id, newBreakpoint);- }- }- return mergedBreakpointIds;-};--const getFragmentContentModeCapabilities = ({- fragment,- fragmentInstances,- styleSources,-}: {- fragment: WebstudioFragment;- fragmentInstances: Instances;- styleSources: WebstudioData["styleSources"];-}) =>- getContentModeCapabilities({- instances: fragmentInstances,- metas: $registeredComponentMetas.get(),- props: new Map(fragment.props.map((prop) => [prop.id, prop])),- styleSources,- contentRootIds: new Set(- fragment.children- .filter((child) => child.type === "id")- .map((child) => child.value)- ),- });--export const __testing__ = {- getFragmentInstancesData,- insertFragmentAssetsMutable,- insertFragmentBreakpointsMutable,- getFragmentContentModeCapabilities,-};--export const insertWebstudioFragmentCopy = ({- data,- fragment,- availableVariables,- projectId,- conflictResolution = "theirs",- onBreakpointLimitMerge,- // In content mode, insertion keeps content-editable instance data, creates- // local styles for inserted instances, and avoids data/resource records.- contentMode = false,-}: {- data: Omit<WebstudioData, "pages">;- fragment: WebstudioFragment;- availableVariables: DataSource[];- projectId: Project["id"];- conflictResolution?: ConflictResolution;- onBreakpointLimitMerge?: () => void;- contentMode?: boolean;-}) => {- const newInstanceIds = new Map<Instance["id"], Instance["id"]>();- const newDataSourceIds = new Map<DataSource["id"], DataSource["id"]>();- const newDataIds = {- newInstanceIds,- newDataSourceIds,- };-- const { fragmentInstances, portalContentRootIds } =- getFragmentInstancesData(fragment);-- const {- assets,- instances,- resources,- dataSources,- props,- breakpoints,- styleSources,- styles,- styleSourceSelections,- } = data;-- /**- * 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- */-- const mergedBreakpointIds =- contentMode === false- ? insertFragmentBreakpointsMutable({- fragment,- breakpoints,- onBreakpointLimitMerge,- })- : new Map<StyleDecl["breakpointId"], StyleDecl["breakpointId"]>();-- insertFragmentAssetsMutable({ fragment, projectId, assets });-- let styleSourceIdMap = new Map<- StyleDecl["styleSourceId"],- StyleDecl["styleSourceId"]- >();-- if (contentMode === false) {- // insert tokens with their styles-- styleSourceIdMap = insertTokenStyleSources({- fragmentStyleSources: fragment.styleSources,- fragmentStyles: fragment.styles,- styleSources,- styles,- breakpoints,- mergedBreakpointIds,- conflictResolution,- });- }-- let portalContentIds = new Set<Instance["id"]>();-- // insert portal contents- // - instances- // - data sources- // - props- // - local styles- for (const rootInstanceId of portalContentRootIds) {- const instanceIds = findTreeInstanceIdsExcludingSlotDescendants(- fragmentInstances,- rootInstanceId- );- portalContentIds = setUnion(portalContentIds, instanceIds);-- // prevent reinserting portals which could be already changed by user- if (instances.has(rootInstanceId)) {- continue;- }-- if (contentMode === false) {- const usedResourceIds = new Set<Resource["id"]>();- for (const dataSource of fragment.dataSources) {- // insert only data sources within portal content- if (instanceIds.has(dataSource.scopeInstanceId ?? "")) {- dataSources.set(dataSource.id, dataSource);- if (dataSource.type === "resource") {- usedResourceIds.add(dataSource.resourceId);- }- }- }-- for (const prop of fragment.props) {- if (instanceIds.has(prop.instanceId)) {- props.set(prop.id, prop);- if (prop.type === "resource") {- usedResourceIds.add(prop.value);- }- }- }-- for (const resource of fragment.resources) {- if (usedResourceIds.has(resource.id)) {- resources.set(resource.id, resource);- }- }- }-- for (const instance of fragment.instances) {- if (instanceIds.has(instance.id)) {- instances.set(instance.id, instance);- }- }-- if (contentMode === false) {- // insert local style sources with their styles-- insertPortalLocalStyleSources({- fragmentStyleSources: fragment.styleSources,- fragmentStyleSourceSelections: fragment.styleSourceSelections,- fragmentStyles: fragment.styles,- instanceIds,- styleSources,- styleSourceSelections,- styles,- mergedBreakpointIds,- });- }- }-- /**- * 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 fragmentInstanceIds = setDifference(- new Set(fragmentInstances.keys()),- portalContentIds- );- for (const instanceId of fragmentInstanceIds) {- newInstanceIds.set(instanceId, nanoid());- }- fragmentInstanceIds.add(ROOT_INSTANCE_ID);- newInstanceIds.set(ROOT_INSTANCE_ID, ROOT_INSTANCE_ID);-- const maskedIdByName = new Map<DataSource["name"], DataSource["id"]>();- for (const dataSource of availableVariables) {- maskedIdByName.set(dataSource.name, dataSource.id);- }- const newResourceIds = new Map<Resource["id"], Resource["id"]>();- if (contentMode === false) {- for (let dataSource of fragment.dataSources) {- const scopeInstanceId = dataSource.scopeInstanceId ?? "";- if (scopeInstanceId === ROOT_INSTANCE_ID) {- // add global variable only if not exist already- if (- dataSources.has(dataSource.id) === false &&- maskedIdByName.has(dataSource.name) === false- ) {- dataSources.set(dataSource.id, dataSource);- }- continue;- }- // insert only data sources within portal content- if (fragmentInstanceIds.has(scopeInstanceId)) {- const newDataSourceId = nanoid();- newDataSourceIds.set(dataSource.id, newDataSourceId);- dataSource = structuredClone(unwrap(dataSource));- dataSource.id = newDataSourceId;- dataSource.scopeInstanceId =- newInstanceIds.get(scopeInstanceId) ?? scopeInstanceId;- if (dataSource.type === "resource") {- const newResourceId = nanoid();- newResourceIds.set(dataSource.resourceId, newResourceId);- dataSource.resourceId = newResourceId;- }- dataSources.set(dataSource.id, dataSource);- }- }- }-- const fragmentContentModeCapabilities =- contentMode === false- ? undefined- : getFragmentContentModeCapabilities({- fragment,- fragmentInstances,- styleSources,- });- for (let prop of fragment.props) {- if (fragmentInstanceIds.has(prop.instanceId) === false) {- continue;- }- if (- contentMode &&- (fragmentContentModeCapabilities === undefined ||- isContentModeCopyableProp({- capabilities: fragmentContentModeCapabilities,- prop,- }) === false)- ) {- continue;- }- prop = structuredClone(unwrap(prop));- prop.id = nanoid();- prop.instanceId = newInstanceIds.get(prop.instanceId) ?? prop.instanceId;- if (prop.type === "expression") {- prop.value = restoreExpressionVariables({- expression: prop.value,- maskedIdByName,- });- prop.value = replaceDataSourcesInExpression(prop.value, newDataSourceIds);- }- if (prop.type === "action") {- for (const value of prop.value) {- value.code = restoreExpressionVariables({- expression: value.code,- maskedIdByName,- });- value.code = replaceDataSourcesInExpression(- value.code,- newDataSourceIds- );- }- }- if (prop.type === "parameter") {- prop.value = newDataSourceIds.get(prop.value) ?? prop.value;- }- if (prop.type === "resource") {- const newResourceId = nanoid();- newResourceIds.set(prop.value, newResourceId);- prop.value = newResourceId;- }- props.set(prop.id, prop);- }-- if (contentMode === false) {- for (let resource of fragment.resources) {- if (newResourceIds.has(resource.id) === false) {- continue;- }- resource = structuredClone(unwrap(resource));- resource.id = newResourceIds.get(resource.id) ?? resource.id;- resource.url = restoreExpressionVariables({- expression: resource.url,- maskedIdByName,- });- resource.url = replaceDataSourcesInExpression(- resource.url,- newDataSourceIds- );- for (const header of resource.headers) {- header.value = restoreExpressionVariables({- expression: header.value,- maskedIdByName,- });- header.value = replaceDataSourcesInExpression(- header.value,- newDataSourceIds- );- }- if (resource.searchParams) {- for (const searchParam of resource.searchParams) {- searchParam.value = restoreExpressionVariables({- expression: searchParam.value,- maskedIdByName,- });- searchParam.value = replaceDataSourcesInExpression(- searchParam.value,- newDataSourceIds- );- }- }- if (resource.body) {- resource.body = restoreExpressionVariables({- expression: resource.body,- maskedIdByName,- });- resource.body = replaceDataSourcesInExpression(- resource.body,- newDataSourceIds- );- }- resources.set(resource.id, resource);- }- }-- for (let instance of fragment.instances) {- if (fragmentInstanceIds.has(instance.id)) {- instance = structuredClone(unwrap(instance));- instance.id = newInstanceIds.get(instance.id) ?? instance.id;- for (const child of instance.children) {- if (child.type === "id") {- child.value = newInstanceIds.get(child.value) ?? child.value;- }- if (child.type === "expression") {- child.value = restoreExpressionVariables({- expression: child.value,- maskedIdByName,- });- child.value = replaceDataSourcesInExpression(- child.value,- newDataSourceIds- );- }- }- instances.set(instance.id, instance);- }- }-- const localStyleSourceInput = {- fragmentStyleSources: fragment.styleSources,- fragmentStyleSourceSelections: fragment.styleSourceSelections,- fragmentStyles: fragment.styles,- fragmentInstanceIds,- newInstanceIds,- styleSources,- styleSourceSelections,- styles,- };- if (contentMode) {- insertLocalStyleSourcesWithNewIds({- ...localStyleSourceInput,- contentMode: true,- breakpoints,- });- } else {- insertLocalStyleSourcesWithNewIds({- ...localStyleSourceInput,- contentMode: false,- styleSourceIdMap,- mergedBreakpointIds,- breakpoints,- });- }-- return newDataIds;-};--export const findClosestSlot = (- instances: Instances,- instanceSelector: InstanceSelector-) => {- for (const instanceId of instanceSelector) {- const instance = instances.get(instanceId);- if (instance?.component === "Slot") {- return instance;- }- }-};--export type Insertable = {- parentSelector: InstanceSelector;- position: number | "end" | "after";-};--export const findClosestInsertable = (- fragment: WebstudioFragment,- from?: Insertable-): undefined | Insertable => {- const selectedPage = $selectedPage.get();- if (selectedPage === undefined) {- return;- }- // paste to the page root if nothing is selected- const instanceSelector = from?.parentSelector ??- $selectedInstanceSelector.get() ?? [selectedPage.rootInstanceId];- if (instanceSelector[0] === ROOT_INSTANCE_ID) {- toast.error(`Cannot insert into Global root`);- return;- }- const metas = $registeredComponentMetas.get();- const instances = $instances.get();- const props = $props.get();- const containerSelector = findClosestNonTextualContainer({- metas,- props,- instances,- instanceSelector,- });- const closestContainerIndex =- instanceSelector.length - containerSelector.length;- if (closestContainerIndex === -1) {- return;- }- let insertableIndex = findClosestInstanceMatchingFragment({- metas,- instances,- props,- instanceSelector: instanceSelector.slice(closestContainerIndex),- fragment,- onError: (message) => {- const component = fragment.instances[0].component;- const label = getInstanceLabel({ component });- toast.warn(message || `"${label}" has no place here`);- },- });- if (insertableIndex === -1) {- // fallback to closest container to always insert something- // even when validation fails- insertableIndex = 0;- }-- // adjust with container lookup- insertableIndex = insertableIndex + closestContainerIndex;- const parentSelector = instanceSelector.slice(insertableIndex);- if (insertableIndex === 0) {- return from ?? { parentSelector, position: "end" };- }- const instance = instances.get(instanceSelector[insertableIndex]);- if (instance === undefined) {- return;- }- // skip collection item when inserting something and go straight into collection instance- if (instance?.component === collectionComponent && insertableIndex === 1) {- return {- parentSelector,- position: "end",- };- }- const lastChildInstanceId = instanceSelector[insertableIndex - 1];- const lastChildPosition = instance.children.findIndex(- (child) => child.type === "id" && child.value === lastChildInstanceId- );- return {- parentSelector,- position: lastChildPosition + 1,- };-};--/**- * Build the ancestor path array for an instance.- * Returns an array of labels for all ancestors from root to parent.- */-export const buildInstancePath = (- instanceId: Instance["id"],- pages: Pages,- instances: Instances-): string[] => {- const awareness = findPageAndSelectorByInstanceId(- pages,- instances,- instanceId- );- if (!awareness.instanceSelector) {- return [];- }-- const instancePath = getInstancePath(- awareness.instanceSelector,- instances,- undefined,- undefined- );-- if (!instancePath) {- return [];- }-- return instancePath- .slice()- .reverse()- .slice(0, -1) // Remove the instance itself (last element after reverse), keep only ancestors- .map(({ instance }) => getInstanceLabel(instance));-};--/**- * Detects token conflicts for a fragment insertion.- *- * @param fragment - The fragment to check for conflicts- * @returns Array of token conflicts (empty if no conflicts)- */-const parentInstanceByIdCache = new WeakMap<- Instances,- Map<Instance["id"], Instance["id"]>->();--/**- * Traverse the instance tree up to the root to find the page and full instance- * selector for a given instance id. When an instance appears via a slot,- * the last matching parent is used.- */-export const findPageAndSelectorByInstanceId = (- pages: Pages,- instances: Instances,- startingInstanceId: Instance["id"]-): { pageId: string; instanceSelector: string[] } => {- let parentInstanceById = parentInstanceByIdCache.get(instances);- if (parentInstanceById === undefined) {- parentInstanceById = new Map<Instance["id"], Instance["id"]>();- for (const instance of instances.values()) {- for (const child of instance.children) {- if (child.type === "id") {- parentInstanceById.set(child.value, instance.id);- }- }- }- parentInstanceByIdCache.set(instances, parentInstanceById);- }- const instanceSelector: string[] = [];- let currentInstanceId: undefined | Instance["id"] = startingInstanceId;- while (currentInstanceId) {- instanceSelector.push(currentInstanceId);- currentInstanceId = parentInstanceById.get(currentInstanceId);- }- const rootInstanceId = instanceSelector.at(-1);- for (const page of getAllPages(pages)) {- if (page.rootInstanceId === rootInstanceId) {- return { pageId: page.id, instanceSelector };- }- }- return { pageId: pages.homePageId, instanceSelector };-};--export const detectFragmentTokenConflicts = ({- fragment,-}: {- fragment: WebstudioFragment;-}) => {- const data = getWebstudioData();-- const mergedBreakpointIds = buildMergedBreakpointIds(- fragment.breakpoints,- data.breakpoints,- { maxBreakpointCount: maxBreakpoints }- );-- return detectTokenConflicts({- fragmentStyleSources: fragment.styleSources,- fragmentStyles: fragment.styles,- existingStyleSources: data.styleSources,- existingStyles: data.styles,- breakpoints: data.breakpoints,- mergedBreakpointIds,- });-};--/**- * Detects token conflicts for a page insertion.- * Combines fragments from ROOT_INSTANCE and page body for conflict detection.- *- * @param sourceData - The source webstudio data containing the page- * @param pageId - The page ID to check for conflicts- * @returns Array of token conflicts (empty if no conflicts)- */-export const detectPageTokenConflicts = ({- sourceData,- pageId,-}: {- sourceData: WebstudioData;- pageId: string;-}) => {- const data = getWebstudioData();-- const page = findPageByIdOrPath(pageId, sourceData.pages);- if (page === undefined) {- throw new Error("Page not found");- }- const targetPage = page ?? getHomePage(sourceData.pages);-- // Extract fragments for both ROOT_INSTANCE and page body- const rootFragment = extractWebstudioFragment(sourceData, ROOT_INSTANCE_ID);- const pageFragment = extractWebstudioFragment(- sourceData,- targetPage.rootInstanceId- );-- // Combine style sources and styles from both fragments- const combinedStyleSources = [- ...rootFragment.styleSources,- ...pageFragment.styleSources,- ];- const combinedStyles = [...rootFragment.styles, ...pageFragment.styles];- const combinedBreakpoints = [- ...rootFragment.breakpoints,- ...pageFragment.breakpoints,- ];-- const mergedBreakpointIds = buildMergedBreakpointIds(- combinedBreakpoints,- data.breakpoints,- { maxBreakpointCount: maxBreakpoints }- );-- return detectTokenConflicts({- fragmentStyleSources: combinedStyleSources,- fragmentStyles: combinedStyles,- existingStyleSources: data.styleSources,- existingStyles: data.styles,- breakpoints: data.breakpoints,- mergedBreakpointIds,- });-};diff --git a/apps/builder/app/shared/instance-utils/data.test.tsx b/apps/builder/app/shared/instance-utils/data.test.tsxnew file mode 100644index 0000000000..46d0727779--- /dev/null+++ b/apps/builder/app/shared/instance-utils/data.test.tsx@@ -0,0 +1,193 @@+import { describe, expect, test } from "vitest";+import { produce } from "immer";+import type { Instance, PageTemplate } from "@webstudio-is/sdk";+import { blockComponent, blockTemplateComponent } from "@webstudio-is/sdk";+import { createDefaultPages, findCycles } from "@webstudio-is/project-build";+import {+ canDeleteInstanceInContentMode,+ getWebstudioData,+ unwrap,+ updateWebstudioData,+} from "./data";+import { registerContainers } from "../sync/sync-stores";+import {+ $assets,+ $breakpoints,+ $dataSources,+ $instances,+ $pages,+ $props,+ $resources,+ $styleSourceSelections,+ $styleSources,+ $styles,+} from "../sync/data-stores";+import { $selectedPageId } from "../nano-states/pages";+import { $authPermit, $builderMode } from "../nano-states/misc";++const createInstance = (+ id: Instance["id"],+ component: string,+ children: Instance["children"]+): Instance => {+ return { type: "instance", id, component, children };+};++registerContainers();++describe("canDeleteInstanceInContentMode", () => {+ const instances = new Map([+ ["body", createInstance("body", "Body", [{ type: "id", value: "block" }])],+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "child" },+ { type: "id", value: "template" },+ ]),+ ],+ [+ "child",+ createInstance("child", "Box", [{ type: "id", value: "nested" }]),+ ],+ ["nested", createInstance("nested", "Box", [])],+ ["template", createInstance("template", blockTemplateComponent, [])],+ ]);++ test("allows deleting direct content block children", () => {+ expect(+ canDeleteInstanceInContentMode({+ instanceSelector: ["child", "block", "body"],+ instances,+ })+ ).toBe(true);+ });++ test("protects content block roots, nested descendants, and templates", () => {+ expect(+ canDeleteInstanceInContentMode({+ instanceSelector: ["block", "body"],+ instances,+ })+ ).toBe(false);+ expect(+ canDeleteInstanceInContentMode({+ instanceSelector: ["nested", "child", "block", "body"],+ instances,+ })+ ).toBe(false);+ expect(+ canDeleteInstanceInContentMode({+ instanceSelector: ["template", "block", "body"],+ instances,+ })+ ).toBe(false);+ });+});++describe("data store helpers", () => {+ test("unwrap returns current value for immer drafts and original value otherwise", () => {+ const source = { count: 1 };+ expect(unwrap(source)).toBe(source);++ produce(source, (draft) => {+ draft.count = 2;+ expect(unwrap(draft)).toEqual({ count: 2 });+ });+ });++ test("getWebstudioData reads all instance-related stores", () => {+ const pages = createDefaultPages({ rootInstanceId: "body" });+ const instances = new Map([["body", createInstance("body", "Body", [])]]);+ $pages.set(pages);+ $instances.set(instances);+ $props.set(new Map());+ $breakpoints.set(new Map());+ $styleSourceSelections.set(new Map());+ $styleSources.set(new Map());+ $styles.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $assets.set(new Map());++ expect(getWebstudioData()).toMatchObject({+ pages,+ instances,+ });+ });++ test("updateWebstudioData mutates stores through a transaction", () => {+ $pages.set(createDefaultPages({ rootInstanceId: "body" }));+ $instances.set(new Map());+ $props.set(new Map());+ $breakpoints.set(new Map());+ $styleSourceSelections.set(new Map());+ $styleSources.set(new Map());+ $styles.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $assets.set(new Map());++ updateWebstudioData((data) => {+ data.instances.set("body", createInstance("body", "Body", []));+ });++ expect($instances.get().get("body")).toEqual(+ createInstance("body", "Body", [])+ );+ });++ test("updateWebstudioData skips page templates without build access", () => {+ const pages = createDefaultPages({ rootInstanceId: "body" });+ const template: PageTemplate = {+ id: "template",+ name: "Template",+ title: "Template",+ rootInstanceId: "template-root",+ meta: {},+ };+ pages.pageTemplates = new Map([[template.id, template]]);+ $pages.set(pages);+ $selectedPageId.set(template.id);+ $builderMode.set("design");+ $authPermit.set("view");+ $instances.set(new Map());++ updateWebstudioData((data) => {+ data.instances.set(+ "template-root",+ createInstance("template-root", "Body", [])+ );+ });++ expect($instances.get().has("template-root")).toBe(false);+ });++ test("updateWebstudioData repairs cycles created during transaction", () => {+ const pages = createDefaultPages({ rootInstanceId: "body" });+ const instances = new Map([+ [+ "body",+ createInstance("body", "Body", [{ type: "id", value: "parent" }]),+ ],+ [+ "parent",+ createInstance("parent", "Box", [{ type: "id", value: "child" }]),+ ],+ ["child", createInstance("child", "Box", [])],+ ]);+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $builderMode.set("design");+ $authPermit.set("build");+ $instances.set(instances);++ updateWebstudioData((data) => {+ data.instances.get("child")?.children.push({+ type: "id",+ value: "parent",+ });+ });++ expect(findCycles($instances.get().values())).toEqual([]);+ });+});diff --git a/apps/builder/app/shared/instance-utils/data.ts b/apps/builder/app/shared/instance-utils/data.tsnew file mode 100644index 0000000000..1d1a139fd3--- /dev/null+++ b/apps/builder/app/shared/instance-utils/data.ts@@ -0,0 +1,139 @@+// Data utilities own access to Webstudio's instance-related stores and+// transaction boundaries. Put generic store reads/writes and content-mode data+// guards here, not tree-shape mutations.+import { current, isDraft } from "immer";+import { toast } from "@webstudio-is/design-system";+import {+ type Instances,+ type WebstudioData,+ blockTemplateComponent,+ isPageTemplate,+} from "@webstudio-is/sdk";+import { breakCyclesMutable, findCycles } from "@webstudio-is/project-build";+import { findBlockSelector } from "../nano-states";+import { $canOpenPageTemplates, $selectedPage } from "../nano-states";+import { serverSyncStore } from "../sync/sync-stores";+import {+ $assets,+ $breakpoints,+ $dataSources,+ $instances,+ $pages,+ $props,+ $resources,+ $styles,+ $styleSourceSelections,+ $styleSources,+} from "../sync/data-stores";+import type { InstanceSelector } from "./tree";++/**+ * structuredClone can be invoked on draft and throw error+ * extract current snapshot before cloning+ */+export const unwrap = <Value>(value: Value) =>+ isDraft(value) ? current(value) : value;++export const canDeleteInstanceInContentMode = ({+ instanceSelector,+ instances,+}: {+ instanceSelector: InstanceSelector;+ instances: Instances;+}) => {+ const blockSelector = findBlockSelector(instanceSelector, instances);+ if (blockSelector === undefined) {+ return false;+ }++ const isDirectBlockChild =+ instanceSelector.length - blockSelector.length === 1;+ if (isDirectBlockChild === false) {+ return false;+ }++ return (+ instances.get(instanceSelector[0])?.component !== blockTemplateComponent+ );+};++export const updateWebstudioData = (mutate: (data: WebstudioData) => void) => {+ const selectedPage = $selectedPage.get();+ if (isPageTemplate(selectedPage) && $canOpenPageTemplates.get() === false) {+ return;+ }+ 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 cycles = findCycles(instances.values());++ // Detect and fix cycles in the instance tree, then report+ if (cycles.length > 0) {+ toast.info("Detected and fixed cycles in the instance tree.");++ breakCyclesMutable(+ instances.values(),+ (node) => node.component === "Slot"+ );+ }+ }+ );+};++export const getWebstudioData = (): WebstudioData => {+ const pages = $pages.get();+ if (pages === undefined) {+ throw Error(`Cannot get webstudio data with empty pages`);+ }+ return {+ pages,+ instances: $instances.get(),+ props: $props.get(),+ dataSources: $dataSources.get(),+ resources: $resources.get(),+ breakpoints: $breakpoints.get(),+ styleSourceSelections: $styleSourceSelections.get(),+ styleSources: $styleSources.get(),+ styles: $styles.get(),+ assets: $assets.get(),+ };+};diff --git a/apps/builder/app/shared/instance-utils/fragment.test.tsx b/apps/builder/app/shared/instance-utils/fragment.test.tsxnew file mode 100644index 0000000000..45ff1e9b70--- /dev/null+++ b/apps/builder/app/shared/instance-utils/fragment.test.tsx@@ -0,0 +1,2456 @@+import {+ detectFragmentTokenConflicts,+ extractWebstudioFragment,+ insertWebstudioFragmentCopy,+ detectPageTokenConflicts,+} from "./fragment";+import { __testing__ } from "./fragment";+import { getWebstudioData } from "./data";+import { enableMapSet } from "immer";+import { describe, test, expect, beforeEach } from "vitest";+import type { Project } from "@webstudio-is/project";+import { createDefaultPages } from "@webstudio-is/project-build";+import { $, ws, css, renderData, token } from "@webstudio-is/template";+import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";+import type {+ Asset,+ Breakpoint,+ Instance,+ StyleDecl,+ StyleDeclKey,+ StyleSource,+ WebstudioData,+ WebstudioFragment,+ WsComponentMeta,+} from "@webstudio-is/sdk";+import {+ coreMetas,+ getStyleDeclKey,+ portalComponent,+ elementComponent,+ ROOT_INSTANCE_ID,+} from "@webstudio-is/sdk";+import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";+import { $registeredComponentMetas } from "../nano-states";+import { $assets } from "~/shared/sync/data-stores";+import {+ $breakpoints,+ $dataSources,+ $instances,+ $pages,+ $project,+ $props,+ $styleSourceSelections,+ $styleSources,+ $styles,+ $resources,+} from "~/shared/sync/data-stores";+import { registerContainers } from "../sync/sync-stores";+import { getInstancePath } from "../nano-states";++const {+ getFragmentContentModeCapabilities,+ getFragmentInstancesData,+ insertFragmentAssetsMutable,+ insertFragmentBreakpointsMutable,+} = __testing__;++enableMapSet();+registerContainers();++$pages.set(createDefaultPages({ rootInstanceId: "" }));++const defaultMetasMap = new Map(+ Object.entries({ ...defaultMetas, ...coreMetas })+);+$registeredComponentMetas.set(defaultMetasMap);++const createFragment = (+ fragment: Partial<WebstudioFragment>+): WebstudioFragment => ({+ children: [],+ instances: [],+ styleSourceSelections: [],+ styleSources: [],+ breakpoints: [],+ styles: [],+ dataSources: [],+ resources: [],+ props: [],+ assets: [],+ ...fragment,+});++const createFakeComponentMetas = (+ itemMeta: Partial<WsComponentMeta>,+ anotherItemMeta?: Partial<WsComponentMeta>+): Map<string, WsComponentMeta> => {+ const base = {+ label: "",+ Icon: () => null,+ };+ const configs = {+ Item: { ...base, ...itemMeta },+ AnotherItem: { ...base, ...anotherItemMeta },+ Bold: base,+ Text: base,+ Form: base,+ Box: base,+ Div: base,+ Body: base,+ } as const;+ return new Map(Object.entries(configs)) as Map<string, WsComponentMeta>;+};++const getIdValuePair = <T extends { id: string }>(item: T) =>+ [item.id, item] as const;++const toMap = <T extends { id: string }>(list: T[]) =>+ new Map(list.map(getIdValuePair));++const setDataStores = (data: Omit<WebstudioData, "pages">) => {+ $instances.set(data.instances);+ $breakpoints.set(data.breakpoints);+ $styleSources.set(data.styleSources);+ $styles.set(data.styles);+ $styleSourceSelections.set(data.styleSourceSelections);+ $dataSources.set(data.dataSources);+ $props.set(data.props);+ $assets.set(data.assets);+ $resources.set(data.resources);+};++const createInstance = (+ id: Instance["id"],+ component: string,+ children: Instance["children"]+): Instance => {+ return { type: "instance", id, component, children };+};++const createStyleDecl = (+ styleSourceId: string,+ breakpointId: string,+ property: StyleProperty,+ value: StyleValue | string+): StyleDecl => ({+ styleSourceId,+ breakpointId,+ property,+ value: typeof value === "string" ? { type: "unparsed", value } : value,+});++const createStyleDeclPair = (+ styleSourceId: string,+ breakpointId: string,+ property: StyleProperty,+ value: StyleValue | string+): [StyleDeclKey, StyleDecl] => [+ `${styleSourceId}:${breakpointId}:${property}:`,+ createStyleDecl(styleSourceId, breakpointId, property, value),+];++const createImageAsset = (id: string, name = "", projectId = ""): Asset => {+ return {+ id,+ type: "image",+ format: "",+ name,+ description: "",+ projectId,+ createdAt: "",+ size: 0,+ meta: { width: 0, height: 0 },+ };+};++const createFontAsset = (id: string, family: string): Asset => {+ return {+ id,+ type: "font",+ format: "woff",+ name: "",+ description: "",+ projectId: "",+ createdAt: "",+ size: 0,+ meta: { style: "normal", family, variationAxes: {} },+ };+};++describe("fragment copy helpers", () => {+ test("builds fragment instance maps and portal content roots", () => {+ const fragment = createFragment({+ instances: [+ createInstance("portal", portalComponent, [+ { type: "id", value: "portal-root" },+ ]),+ createInstance("portal-root", "Box", []),+ ],+ });++ const { fragmentInstances, portalContentRootIds } =+ getFragmentInstancesData(fragment);++ expect(Array.from(fragmentInstances.keys())).toEqual([+ "portal",+ "portal-root",+ ]);+ expect(portalContentRootIds).toEqual(new Set(["portal-root"]));+ });++ test("inserts fragment assets without overwriting existing assets", () => {+ const existingAsset = createImageAsset(+ "existing-asset",+ "Existing",+ "target-project"+ );+ const assets = new Map<Asset["id"], Asset>([+ [existingAsset.id, existingAsset],+ ]);++ insertFragmentAssetsMutable({+ fragment: createFragment({+ assets: [+ createImageAsset("existing-asset", "Source Existing", "source"),+ createImageAsset("new-asset", "New", "source"),+ ],+ }),+ projectId: "target-project",+ assets,+ });++ expect(assets.get("existing-asset")).toBe(existingAsset);+ expect(assets.get("new-asset")).toEqual({+ ...createImageAsset("new-asset", "New", "source"),+ projectId: "target-project",+ });+ });++ test("inserts fragment breakpoints and reports limit merges", () => {+ const baseBreakpoint: Breakpoint = { id: "base", label: "Base" };+ const breakpoints = new Map<Breakpoint["id"], Breakpoint>([+ [baseBreakpoint.id, baseBreakpoint],+ ]);+ let didMergeDueToLimit = false;++ const mergedBreakpointIds = insertFragmentBreakpointsMutable({+ fragment: createFragment({+ breakpoints: [+ baseBreakpoint,+ { id: "desktop", label: "Desktop", minWidth: 1024 },+ ],+ }),+ breakpoints,+ onBreakpointLimitMerge: () => {+ didMergeDueToLimit = true;+ },+ });++ expect(mergedBreakpointIds.get("base")).toBe("base");+ expect(breakpoints.get("desktop")).toEqual({+ id: "desktop",+ label: "Desktop",+ minWidth: 1024,+ });+ expect(didMergeDueToLimit).toBe(false);+ });++ test("builds content-mode capabilities for fragment roots", () => {+ const registeredComponentMetas = $registeredComponentMetas.get();+ $registeredComponentMetas.set(+ createFakeComponentMetas({+ props: {+ href: {+ type: "string",+ control: "url",+ required: false,+ contentMode: true,+ },+ },+ })+ );+ try {+ const fragment = createFragment({+ children: [{ type: "id", value: "link" }],+ instances: [createInstance("link", "Item", [])],+ props: [+ {+ id: "href-prop",+ instanceId: "link",+ name: "href",+ type: "string",+ value: "/",+ },+ ],+ });+ const { fragmentInstances } = getFragmentInstancesData(fragment);++ const capabilities = getFragmentContentModeCapabilities({+ fragment,+ fragmentInstances,+ styleSources: new Map(),+ });++ expect(capabilities.contentRootIds).toEqual(new Set(["link"]));+ expect(capabilities.editablePropIds.has("href-prop")).toBe(true);+ } finally {+ $registeredComponentMetas.set(registeredComponentMetas);+ }+ });+});++const getWebstudioDataStub = (+ 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("extract webstudio fragment", () => {+ test("collect all styles and breakpoints bound to fragment instances", () => {+ // body+ // box1+ // box2+ $instances.set(+ toMap([+ createInstance("body", "Body", [{ type: "id", value: "box1" }]),+ createInstance("box1", "Box", [{ type: "id", value: "box2" }]),+ createInstance("box2", "Box", []),+ ])+ );+ $styleSourceSelections.set(+ new Map([+ ["body", { instanceId: "box1", values: ["localBody", "token1"] }],+ ["box1", { instanceId: "box1", values: ["localBox1", "token2"] }],+ ["box2", { instanceId: "box2", values: ["localBox2", "token2"] }],+ ])+ );+ $styleSources.set(+ new Map([+ ["localBody", { id: "localBody", type: "local" }],+ ["localBox1", { id: "localBox1", type: "local" }],+ ["localBox2", { id: "localBox2", type: "local" }],+ ["token1", { id: "token1", type: "token", name: "token1" }],+ ["token2", { id: "token2", type: "token", name: "token2" }],+ ])+ );+ $styles.set(+ new Map([+ createStyleDeclPair("localBody1", "base", "color", "red"),+ createStyleDeclPair("localBox1", "base", "color", "green"),+ createStyleDeclPair("localBox2", "base", "color", "blue"),+ createStyleDeclPair("token1", "base", "color", "yellow"),+ createStyleDeclPair("token2", "base", "color", "orange"),+ ])+ );+ $breakpoints.set(+ new Map([+ ["base", { id: "base", label: "base" }],+ ["big", { id: "big", label: "big", minWidth: 768 }],+ ])+ );+ const { styleSources, styleSourceSelections, styles, breakpoints } =+ extractWebstudioFragment(getWebstudioData(), "box1");++ // exclude localBody and token1 bound to body+ expect(styleSources).toEqual([+ { id: "localBox1", type: "local" },+ { id: "token2", type: "token", name: "token2" },+ { id: "localBox2", type: "local" },+ ]);+ expect(styleSourceSelections).toEqual([+ { instanceId: "box1", values: ["localBox1", "token2"] },+ { instanceId: "box2", values: ["localBox2", "token2"] },+ ]);+ expect(styles).toEqual([+ createStyleDecl("localBox1", "base", "color", "green"),+ createStyleDecl("localBox2", "base", "color", "blue"),+ createStyleDecl("token2", "base", "color", "orange"),+ ]);+ expect(breakpoints).toEqual([{ id: "base", label: "base" }]);+ });++ test("collect assets from props and styles withiin fragment instances", () => {+ // body+ // box1+ // box2+ $instances.set(+ toMap([+ createInstance("body", "Body", [{ type: "id", value: "box1" }]),+ createInstance("box1", "Box", [{ type: "id", value: "box2" }]),+ createInstance("box2", "Box", []),+ ])+ );+ $props.set(+ new Map([+ [+ "bodyProp",+ {+ id: "bodyProp",+ instanceId: "body",+ name: "data-body",+ type: "asset",+ value: "asset1",+ },+ ],+ [+ "box1Prop",+ {+ id: "box1Prop",+ instanceId: "box1",+ name: "data-box1",+ type: "asset",+ value: "asset2",+ },+ ],+ ])+ );+ $styleSourceSelections.set(+ new Map([+ ["body", { instanceId: "box1", values: ["localBody"] }],+ ["box1", { instanceId: "box1", values: ["localBox1"] }],+ ])+ );+ $styleSources.set(+ new Map([+ ["localBody", { id: "localBody", type: "local" }],+ ["localBox1", { id: "localBox1", type: "local" }],+ ])+ );+ $styles.set(+ new Map([+ createStyleDeclPair("localBody1", "base", "fontFamily", {+ type: "fontFamily",+ value: ["font1"],+ }),+ createStyleDeclPair("localBody1", "base", "backgroundImage", {+ type: "image",+ value: { type: "asset", value: "asset3" },+ }),+ createStyleDeclPair("localBox1", "base", "fontFamily", {+ type: "fontFamily",+ value: ["font2"],+ }),+ createStyleDeclPair("localBox1", "base", "color", {+ type: "image",+ value: { type: "asset", value: "asset4" },+ }),+ ])+ );+ $breakpoints.set(new Map([["base", { id: "base", label: "base" }]]));+ $assets.set(+ toMap([+ createImageAsset("asset1"),+ createImageAsset("asset2"),+ createImageAsset("asset3"),+ createImageAsset("asset4"),+ createFontAsset("asset5", "font1"),+ createFontAsset("asset6", "font2"),+ ])+ );+ const { assets } = extractWebstudioFragment(getWebstudioData(), "box1");++ expect(assets).toEqual([+ createImageAsset("asset2"),+ createImageAsset("asset4"),+ createFontAsset("asset6", "font2"),+ ]);+ });+});++describe("insert webstudio fragment copy", () => {+ const emptyFragment = {+ children: [],+ instances: [+ {+ id: "body",+ type: "instance",+ component: "Body",+ children: [],+ } satisfies Instance,+ ],+ styleSourceSelections: [],+ styleSources: [],+ breakpoints: [],+ styles: [],+ dataSources: [],+ resources: [],+ props: [],+ assets: [],+ };++ $project.set({ id: "current_project" } as Project);++ beforeEach(() => {+ $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("duplicate shared slot child in shared slot content", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );++ const instancePath =+ getInstancePath(["div", "fragment", "slot1", "body"], data.instances) ??+ [];+ const selectedItem = instancePath[0];+ const parentItem = instancePath[1];+ if (selectedItem === undefined || parentItem === undefined) {+ throw Error("Expected selected and parent items");+ }++ const fragment = extractWebstudioFragment(data, selectedItem.instance.id);+ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: "current_project",+ });+ const newRootInstanceId = newInstanceIds.get(selectedItem.instance.id);+ if (newRootInstanceId === undefined) {+ throw Error("Expected duplicate instance id");+ }+ data.instances.get(parentItem.instance.id)?.children.splice(1, 0, {+ type: "id",+ value: newRootInstanceId,+ });++ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ { type: "id", value: expect.any(String) },+ ]);+ });++ test("copy shared slot child outside keeps copy independent from slot content", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );++ const fragment = extractWebstudioFragment(data, "div");+ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: "current_project",+ });+ const copiedDivId = newInstanceIds.get("div");+ if (copiedDivId === undefined) {+ throw Error("Expected copied instance id");+ }+ data.instances.get("body")?.children.push({+ type: "id",+ value: copiedDivId,+ });+ data.instances.get("fragment")?.children.push({+ type: "id",+ value: "newSlotChild",+ });+ data.instances.set("newSlotChild", {+ type: "instance",+ id: "newSlotChild",+ component: "Box",+ children: [],+ });++ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ { type: "id", value: "newSlotChild" },+ ]);+ expect(data.instances.get("body")?.children.at(-1)).toEqual({+ type: "id",+ value: copiedDivId,+ });+ expect(data.instances.get(copiedDivId)?.children).toEqual([]);+ });++ test("copy nested shared slot child outside keeps copy independent from slot content", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );++ const fragment = extractWebstudioFragment(data, "box");+ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: "current_project",+ });+ const copiedBoxId = newInstanceIds.get("box");+ if (copiedBoxId === undefined) {+ throw Error("Expected copied instance id");+ }+ data.instances.get("body")?.children.push({+ type: "id",+ value: copiedBoxId,+ });+ data.instances.get("div")?.children.push({+ type: "id",+ value: "newSlotChild",+ });+ data.instances.set("newSlotChild", {+ type: "instance",+ id: "newSlotChild",+ component: "Box",+ children: [],+ });++ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect(data.instances.get("div")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "newSlotChild" },+ ]);+ expect(data.instances.get("body")?.children.at(-1)).toEqual({+ type: "id",+ value: copiedBoxId,+ });+ expect(data.instances.get(copiedBoxId)?.children).toEqual([]);+ });++ test("insert assets with same ids if missing", () => {+ const data = getWebstudioDataStub();+ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ assets: [createImageAsset("asset1", "name", "another_project")],+ },+ availableVariables: [],+ projectId: "current_project",+ });+ expect(Array.from(data.assets.values())).toEqual([+ createImageAsset("asset1", "name", "current_project"),+ ]);++ data.assets = toMap([+ createImageAsset("asset1", "changed_name", "current_project"),+ ]);+ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ assets: [+ createImageAsset("asset1", "name", "another_project"),+ createImageAsset("asset2", "another_name", "another_project"),+ ],+ },+ availableVariables: [],+ projectId: "current_project",+ });+ expect(Array.from(data.assets.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("copies local styles with new ids and reuses existing token styles in content mode", () => {+ const localStyleSource: StyleSource = { type: "local", id: "localBox" };+ const unsupportedLocalStyleSource: StyleSource = {+ type: "local",+ id: "unsupportedLocal",+ };+ const tokenStyleSource: StyleSource = {+ type: "token",+ id: "token",+ name: "Token",+ };+ const style = createStyleDecl("localBox", "base", "color", "red");+ const unsupportedBreakpointStyle = createStyleDecl(+ "localBox",+ "desktop",+ "backgroundColor",+ "blue"+ );+ const unsupportedLocalStyle = createStyleDecl(+ "unsupportedLocal",+ "desktop",+ "color",+ "green"+ );+ const data = getWebstudioDataStub({+ breakpoints: toMap<Breakpoint>([{ id: "base", label: "Base" }]),+ instances: toMap([+ createInstance("body", "Body", []),+ createInstance("templateBox", "Box", []),+ ]),+ styleSources: toMap([+ localStyleSource,+ unsupportedLocalStyleSource,+ tokenStyleSource,+ ]),+ styleSourceSelections: new Map([+ [+ "templateBox",+ {+ instanceId: "templateBox",+ values: ["localBox", "unsupportedLocal", "token"],+ },+ ],+ ]),+ styles: new Map([+ [getStyleDeclKey(style), style],+ [+ getStyleDeclKey(unsupportedBreakpointStyle),+ unsupportedBreakpointStyle,+ ],+ [getStyleDeclKey(unsupportedLocalStyle), unsupportedLocalStyle],+ ]),+ });+ const fragment = createFragment({+ children: [{ type: "id", value: "templateBox" }],+ instances: [createInstance("templateBox", "Box", [])],+ styleSources: [+ localStyleSource,+ unsupportedLocalStyleSource,+ tokenStyleSource,+ ],+ styleSourceSelections: [+ {+ instanceId: "templateBox",+ values: ["localBox", "unsupportedLocal", "token"],+ },+ ],+ styles: [style, unsupportedBreakpointStyle, unsupportedLocalStyle],+ });++ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: "current_project",+ contentMode: true,+ });+ const newInstanceId = newInstanceIds.get("templateBox");++ expect(newInstanceId).toBeDefined();+ const selection = data.styleSourceSelections.get(newInstanceId ?? "");+ expect(selection).toEqual({+ instanceId: newInstanceId,+ values: [expect.any(String), "token"],+ });+ const newLocalStyleSourceId = selection?.values[0];+ expect(newLocalStyleSourceId).not.toBe("localBox");+ expect(data.styleSources.get(newLocalStyleSourceId ?? "")).toEqual({+ type: "local",+ id: newLocalStyleSourceId,+ });+ expect(data.styles.get(getStyleDeclKey(style))).toEqual(style);+ expect(+ data.styles.get(+ getStyleDeclKey({+ ...style,+ styleSourceId: newLocalStyleSourceId ?? "",+ })+ )+ ).toEqual({ ...style, styleSourceId: newLocalStyleSourceId });+ expect(+ data.styles.has(+ getStyleDeclKey({+ ...unsupportedBreakpointStyle,+ styleSourceId: newLocalStyleSourceId ?? "",+ })+ )+ ).toBe(false);+ expect(+ Array.from(data.styleSources.values()).some(+ (styleSource) =>+ styleSource.type === "local" &&+ styleSource.id !== "localBox" &&+ styleSource.id !== "unsupportedLocal" &&+ styleSource.id !== newLocalStyleSourceId+ )+ ).toBe(false);+ });++ test("copies assets and asset props in content mode", () => {+ const asset = createImageAsset("asset", "Template image", "source_project");+ const data = getWebstudioDataStub();+ $registeredComponentMetas.set(+ new Map([+ ...defaultMetasMap,+ [+ "Item",+ {+ label: "Item",+ icon: "",+ props: {+ image: {+ type: "string",+ control: "text",+ required: false,+ contentMode: true,+ },+ },+ } satisfies WsComponentMeta,+ ],+ ])+ );+ const fragment = createFragment({+ children: [{ type: "id", value: "item" }],+ instances: [createInstance("item", "Item", [])],+ props: [+ {+ id: "image",+ instanceId: "item",+ name: "image",+ type: "asset",+ value: "asset",+ },+ ],+ assets: [asset],+ });++ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: "current_project",+ contentMode: true,+ });+ const newInstanceId = newInstanceIds.get("item");++ expect(data.assets.get("asset")).toEqual({+ ...asset,+ projectId: "current_project",+ });+ expect(Array.from(data.props.values())).toEqual([+ expect.objectContaining({+ instanceId: newInstanceId,+ name: "image",+ type: "asset",+ value: "asset",+ }),+ ]);+ });++ test("copies tag-derived content mode props for generic elements", () => {+ const data = getWebstudioDataStub();+ const fragment = createFragment({+ children: [{ type: "id", value: "image" }],+ instances: [+ {+ type: "instance",+ id: "image",+ component: elementComponent,+ tag: "img",+ children: [],+ },+ ],+ props: [+ {+ id: "alt",+ instanceId: "image",+ name: "alt",+ type: "string",+ value: "Description",+ },+ {+ id: "class",+ instanceId: "image",+ name: "class",+ type: "string",+ value: "card",+ },+ ],+ });++ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: "current_project",+ contentMode: true,+ });+ const newInstanceId = newInstanceIds.get("image");++ expect(newInstanceId).toBeDefined();+ expect(Array.from(data.props.values())).toEqual([+ expect.objectContaining({+ instanceId: newInstanceId,+ name: "alt",+ type: "string",+ value: "Description",+ }),+ ]);+ });++ test("merge breakpoints with existing ones", () => {+ const breakpoints = toMap<Breakpoint>([+ { id: "existing_base", label: "base" },+ { id: "existing_small", label: "small", minWidth: 768 },+ ]);+ const data = getWebstudioDataStub({ breakpoints });+ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [+ { id: "new_base", label: "Base" },+ {+ id: "new_small",+ label: "Small",+ minWidth: 768,+ },+ {+ id: "new_large",+ label: "Large",+ minWidth: 1200,+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });+ expect(Array.from(data.breakpoints.values())).toEqual([+ { id: "existing_base", label: "base" },+ { id: "existing_small", label: "small", minWidth: 768 },+ { id: "new_large", label: "Large", minWidth: 1200 },+ ]);+ });++ test("reports breakpoint limit merge once when inserting fragment", () => {+ const breakpoints = toMap<Breakpoint>([+ { id: "base", label: "base" },+ { id: "0", label: "320", maxWidth: 320 },+ { id: "1", label: "480", maxWidth: 480 },+ { id: "2", label: "768", maxWidth: 768 },+ { id: "3", label: "1024", maxWidth: 1024 },+ { id: "4", label: "1280", minWidth: 1280 },+ { id: "5", label: "1440", minWidth: 1440 },+ { id: "6", label: "1920", minWidth: 1920 },+ { id: "7", label: "2560", minWidth: 2560 },+ ]);+ const data = getWebstudioDataStub({ breakpoints });+ let mergeCount = 0;++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [+ { id: "new_medium", label: "Medium", minWidth: 1500 },+ { id: "new_large", label: "Large", minWidth: 1700 },+ ],+ },+ availableVariables: [],+ projectId: "",+ onBreakpointLimitMerge: () => {+ mergeCount += 1;+ },+ });++ expect(mergeCount).toBe(1);+ });++ // Case 2: Same styles AND same name -> reuse existing token+ test("token with same styles and same name reuses existing token", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "primaryColor" },+ ]);+ const styles = new Map([+ createStyleDeclPair("existingToken", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDeclPair("existingToken", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Same name "primaryColor", same styles, different id+ { id: "newToken", type: "token", name: "primaryColor" },+ ],+ styles: [+ {+ styleSourceId: "newToken",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ styleSourceId: "newToken",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should reuse existing token, not create a new one+ expect(Array.from(data.styleSources.values())).toEqual([+ { id: "existingToken", type: "token", name: "primaryColor" },+ ]);+ // No new styles should be added+ expect(Array.from(data.styles.values())).toEqual([+ {+ styleSourceId: "existingToken",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ styleSourceId: "existingToken",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ]);+ });++ // Case 3: Same styles but different name -> insert new token with original name+ test("token with same styles but different name inserts new token", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "primaryColor" },+ ]);+ const styles = new Map([+ createStyleDeclPair("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Different name "accentColor", same styles+ { id: "token2", type: "token", name: "accentColor" },+ ],+ styles: [+ {+ styleSourceId: "token2",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should insert new token with its original name+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({+ id: "token1",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toMatchObject({ type: "token", name: "accentColor" });+ expect(tokens[1].id).not.toBe("token2"); // Should have new ID++ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(2);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "token1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ expect(tokenStyles[1]).toMatchObject({+ styleSourceId: tokens[1].id, // Should reference new token ID+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ });++ // Case 4: Different styles but same name -> add counter suffix+ test("token with different styles but same name adds counter suffix", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "myToken" },+ ]);+ const styles = new Map([+ createStyleDeclPair("token1", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Same name "myToken", different styles+ { id: "token2", type: "token", name: "myToken" },+ ],+ styles: [+ {+ styleSourceId: "token2",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should add counter suffix to the new token+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({ id: "token1", type: "token", name: "myToken" });+ expect(tokens[1]).toMatchObject({ type: "token", name: "myToken-1" });+ expect(tokens[1].id).not.toBe("token2"); // Should have new ID++ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(2);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "token1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ });+ expect(tokenStyles[1]).toMatchObject({+ styleSourceId: tokens[1].id,+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ });++ // Case 4b: Multiple counter suffixes+ test("token with name conflict increments counter correctly", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "myToken" },+ { id: "token2", type: "token", name: "myToken-1" },+ { id: "token3", type: "token", name: "myToken-2" },+ ]);+ const styles = new Map([+ createStyleDeclPair("token1", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ createStyleDeclPair("token2", "base", "color", {+ type: "keyword",+ value: "green",+ }),+ createStyleDeclPair("token3", "base", "color", {+ type: "keyword",+ value: "yellow",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [{ id: "token4", type: "token", name: "myToken" }],+ styles: [+ {+ styleSourceId: "token4",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should use counter 3+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(4);+ expect(tokens[0]).toEqual({ id: "token1", type: "token", name: "myToken" });+ expect(tokens[1]).toEqual({+ id: "token2",+ type: "token",+ name: "myToken-1",+ });+ expect(tokens[2]).toEqual({+ id: "token3",+ type: "token",+ name: "myToken-2",+ });+ expect(tokens[3]).toMatchObject({ type: "token", name: "myToken-3" });+ expect(tokens[3].id).not.toBe("token4"); // Should have new ID+ });++ // Case 6: Different styles and different name -> insert as-is+ test("token with different styles and different name inserts normally", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "primaryColor" },+ ]);+ const styles = new Map([+ createStyleDeclPair("token1", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [{ id: "token2", type: "token", name: "secondaryColor" }],+ styles: [+ {+ styleSourceId: "token2",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should insert new token normally+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({+ id: "token1",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toMatchObject({ type: "token", name: "secondaryColor" });+ expect(tokens[1].id).not.toBe("token2"); // Should have new ID++ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(2);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "token1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ });+ expect(tokenStyles[1]).toMatchObject({+ styleSourceId: tokens[1].id,+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ });++ // Test that instance with matching token gets the token reference updated+ test("instance with reused token updates styleSourceSelection to existing token id", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "primaryColor" },+ ]);+ const styles = new Map([+ createStyleDeclPair("existingToken", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Same name and same styles as existingToken+ { id: "newToken", type: "token", name: "primaryColor" },+ ],+ styleSourceSelections: [{ instanceId: "box", values: ["newToken"] }],+ styles: [+ {+ styleSourceId: "newToken",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should reuse existing token+ expect(Array.from(data.styleSources.values())).toEqual([+ { id: "existingToken", type: "token", name: "primaryColor" },+ ]);++ // The instance should reference the existing token, not the new one+ const newBoxId = Array.from(data.instances.keys())[0];+ expect(data.styleSourceSelections.get(newBoxId)).toEqual({+ instanceId: newBoxId,+ values: ["existingToken"], // Should use existing token id, not "newToken"+ });+ });++ // Case 3 safeguard: Same styles but different name gets suffix when name conflicts+ test("token with same styles but different name adds suffix when name already exists", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "primaryColor" },+ { id: "token2", type: "token", name: "accentColor" }, // This name is taken+ ]);+ const styles = new Map([+ createStyleDeclPair("token1", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDeclPair("token2", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Same styles as token1, but wants to use name "accentColor" which is already taken+ { id: "token3", type: "token", name: "accentColor" },+ ],+ styles: [+ {+ styleSourceId: "token3",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should add counter suffix to prevent duplicate name+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(3);+ expect(tokens[0]).toEqual({+ id: "token1",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toEqual({+ id: "token2",+ type: "token",+ name: "accentColor",+ });+ expect(tokens[2]).toMatchObject({ type: "token", name: "accentColor-1" });+ expect(tokens[2].id).not.toBe("token3"); // Should have new ID++ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(3);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "token1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ expect(tokenStyles[1]).toEqual({+ styleSourceId: "token2",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ });+ expect(tokenStyles[2]).toMatchObject({+ styleSourceId: tokens[2].id,+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ });++ // Case 6 safeguard: Different styles and different name gets suffix when name conflicts+ test("token with different styles and name adds suffix when name already exists", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "token1", type: "token", name: "primaryColor" },+ { id: "token2", type: "token", name: "secondaryColor" }, // This name is taken+ ]);+ const styles = new Map([+ createStyleDeclPair("token1", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ createStyleDeclPair("token2", "base", "color", {+ type: "keyword",+ value: "green",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Different styles from both existing tokens, but wants name "secondaryColor"+ { id: "token3", type: "token", name: "secondaryColor" },+ ],+ styles: [+ {+ styleSourceId: "token3",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should add counter suffix to prevent duplicate name+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(3);+ expect(tokens[0]).toEqual({+ id: "token1",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toEqual({+ id: "token2",+ type: "token",+ name: "secondaryColor",+ });+ expect(tokens[2]).toMatchObject({+ type: "token",+ name: "secondaryColor-1",+ });+ expect(tokens[2].id).not.toBe("token3"); // Should have new ID++ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(3);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "token1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ });+ expect(tokenStyles[1]).toEqual({+ styleSourceId: "token2",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "green" },+ });+ expect(tokenStyles[2]).toMatchObject({+ styleSourceId: tokens[2].id,+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ });++ // Test that existing token with same styles but different name stays untouched+ test("existing token with matching styles but different name stays untouched when inserting new token", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "primaryColor" },+ ]);+ const styles = new Map([+ createStyleDeclPair("existingToken", "base", "color", {+ type: "keyword",+ value: "red",+ }),+ createStyleDeclPair("existingToken", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Different name "accentColor", same styles as existingToken+ { id: "newToken", type: "token", name: "accentColor" },+ ],+ styles: [+ {+ styleSourceId: "newToken",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ styleSourceId: "newToken",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should insert new token with its own name, leaving existing one untouched+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({+ id: "existingToken",+ type: "token",+ name: "primaryColor",+ });+ expect(tokens[1]).toMatchObject({ type: "token", name: "accentColor" });+ expect(tokens[1].id).not.toBe("newToken"); // Should have new ID++ // Both tokens should have their own styles+ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(4);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "existingToken",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ expect(tokenStyles[1]).toEqual({+ styleSourceId: "existingToken",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ });+ expect(tokenStyles[2]).toMatchObject({+ styleSourceId: tokens[1].id,+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ });+ expect(tokenStyles[3]).toMatchObject({+ styleSourceId: tokens[1].id,+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ });+ });++ // Critical test: inserting base name when suffixed version exists+ test("inserting token 'bbb' when 'bbb-1' with same styles exists inserts both tokens", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "bbb-1" },+ ]);+ const styles = new Map([+ createStyleDeclPair("existingToken", "base", "color", {+ type: "keyword",+ value: "blue",+ }),+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources, styles });++ // Add an instance that uses the existing token+ const existingInstance = createInstance("existingInstance", "Box", []);+ data.instances.set("existingInstance", existingInstance);+ data.styleSourceSelections.set("existingInstance", {+ instanceId: "existingInstance",+ values: ["existingToken"],+ });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ breakpoints: [{ id: "base", label: "base" }],+ styleSources: [+ // Inserting "bbb" with same styles as "bbb-1"+ { id: "newToken", type: "token", name: "bbb" },+ ],+ styleSourceSelections: [{ instanceId: "box", values: ["newToken"] }],+ styles: [+ {+ styleSourceId: "newToken",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Both tokens should exist+ const tokens = Array.from(data.styleSources.values());+ expect(tokens).toHaveLength(2);+ expect(tokens[0]).toEqual({+ id: "existingToken",+ type: "token",+ name: "bbb-1",+ });+ expect(tokens[1]).toMatchObject({ type: "token", name: "bbb" }); // Different name, so inserted as-is+ expect(tokens[1].id).not.toBe("newToken"); // Should have new ID++ // Both should have their own styles+ const tokenStyles = Array.from(data.styles.values());+ expect(tokenStyles).toHaveLength(2);+ expect(tokenStyles[0]).toEqual({+ styleSourceId: "existingToken",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ });+ expect(tokenStyles[1]).toMatchObject({+ styleSourceId: tokens[1].id,+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "blue" },+ });++ // The EXISTING instance should still reference "bbb-1" (existingToken)+ expect(data.styleSourceSelections.get("existingInstance")).toEqual({+ instanceId: "existingInstance",+ values: ["existingToken"],+ });++ // The new instance should reference the new token "bbb" (tokens[1].id)+ const newBoxId = Array.from(data.instances.keys()).find(+ (id) => id !== "existingInstance"+ );+ expect(data.styleSourceSelections.get(newBoxId!)).toEqual({+ instanceId: newBoxId,+ values: [tokens[1].id],+ });+ });++ test("insert local styles with new ids and use merged breakpoint ids", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const data = getWebstudioDataStub({ breakpoints });+ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ 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" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });+ expect(Array.from(data.styleSourceSelections.values())).toEqual([+ {+ instanceId: expect.not.stringMatching("box"),+ values: [expect.not.stringMatching("localId"), "tokenId"],+ },+ ]);+ expect(Array.from(data.styleSources.values())).toEqual([+ { id: expect.not.stringMatching("localId"), type: "local" },+ ]);+ expect(Array.from(data.styles.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", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const data = getWebstudioDataStub({ breakpoints });+ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ // 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" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });+ expect(Array.from(data.styleSourceSelections.values())).toEqual([+ { instanceId: "fragment", values: ["localId", "tokenId"] },+ ]);+ expect(Array.from(data.styleSources.values())).toEqual([+ { id: "localId", type: "local" },+ ]);+ expect(Array.from(data.styles.values())).toEqual([+ {+ styleSourceId: "localId",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+ });++ test("merge local styles into existing ROOT_INSTANCE_ID local source", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "existingLocal", type: "local" },+ ]);+ const styleSourceSelections = new Map([+ [+ ROOT_INSTANCE_ID,+ { instanceId: ROOT_INSTANCE_ID, values: ["existingLocal"] },+ ],+ ]);+ const styles = new Map([+ createStyleDeclPair("existingLocal", "base", "fontSize", {+ type: "unit",+ value: 16,+ unit: "px",+ }),+ ]);+ const data = getWebstudioDataStub({+ breakpoints,+ styleSources,+ styleSourceSelections,+ styles,+ });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: ROOT_INSTANCE_ID,+ component: "Body",+ children: [],+ },+ ],+ breakpoints: [{ id: "base", label: "base" }],+ styleSourceSelections: [+ { instanceId: ROOT_INSTANCE_ID, values: ["newLocal"] },+ ],+ styleSources: [{ id: "newLocal", type: "local" }],+ styles: [+ {+ styleSourceId: "newLocal",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should merge into existing local source+ expect(Array.from(data.styleSources.values())).toEqual([+ { id: "existingLocal", type: "local" },+ ]);+ expect(data.styleSourceSelections.get(ROOT_INSTANCE_ID)).toEqual({+ instanceId: ROOT_INSTANCE_ID,+ values: ["existingLocal"],+ });+ // Both styles should be present under the same source+ expect(Array.from(data.styles.values())).toEqual([+ {+ styleSourceId: "existingLocal",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ {+ styleSourceId: "existingLocal",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+ });++ test("insert instances with new ids and update child references", () => {+ const data = getWebstudioDataStub();+ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: "parent",+ component: "Box",+ children: [+ { type: "id", value: "child1" },+ { type: "id", value: "child2" },+ ],+ },+ {+ type: "instance",+ id: "child1",+ component: "Text",+ children: [],+ },+ {+ type: "instance",+ id: "child2",+ component: "Text",+ children: [],+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ const newInstances = Array.from(data.instances.values());+ expect(newInstances).toHaveLength(3);++ const parentInstance = newInstances.find((i) => i.component === "Box");+ const childInstances = newInstances.filter((i) => i.component === "Text");++ expect(parentInstance).toBeDefined();+ expect(childInstances).toHaveLength(2);++ // Verify parent's children reference the new child ids+ expect(parentInstance?.children).toEqual([+ { type: "id", value: childInstances[0].id },+ { type: "id", value: childInstances[1].id },+ ]);++ // Verify new ids were generated (not same as original)+ expect(parentInstance?.id).not.toBe("parent");+ expect(childInstances[0].id).not.toBe("child1");+ expect(childInstances[1].id).not.toBe("child2");+ });++ test("skip portal content that already exists", () => {+ const instances = new Map([+ [+ "existingPortalContent",+ {+ type: "instance" as const,+ id: "existingPortalContent",+ component: "Box",+ children: [{ type: "text" as const, value: "existing" }],+ },+ ],+ ]);+ const data = getWebstudioDataStub({ instances });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: "portal",+ component: portalComponent,+ children: [{ type: "id", value: "existingPortalContent" }],+ },+ {+ type: "instance",+ id: "existingPortalContent",+ component: "Box",+ children: [{ type: "text", value: "new version" }],+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should preserve existing portal content+ const existingInstance = data.instances.get("existingPortalContent");+ expect(existingInstance?.children).toEqual([+ { type: "text", value: "existing" },+ ]);+ });++ test("insert instance with expression child and update variable references", () => {+ const data = getWebstudioDataStub();++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [{ type: "expression", value: "$ws$dataSource$oldVar" }],+ },+ ],+ dataSources: [+ {+ id: "oldVar",+ scopeInstanceId: "box",+ type: "variable",+ name: "myVar",+ value: { type: "string", value: "hello" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ const newBoxId = Array.from(data.instances.keys())[0];+ const newBox = data.instances.get(newBoxId);+ const newVarId = Array.from(data.dataSources.keys())[0];++ // Verify the expression was updated with the new variable id+ expect(newBox?.children[0].type).toBe("expression");+ if (newBox?.children[0].type === "expression") {+ // The encoding replaces - with __DASH__+ const encodedId = newVarId.replace(/-/g, "__DASH__");+ expect(newBox.children[0].value).toBe(`$ws$dataSource$${encodedId}`);+ }+ expect(newVarId).not.toBe("oldVar");+ });++ test("skip global variables that already exist by id", () => {+ const dataSources = new Map([+ [+ "globalVar1",+ {+ id: "globalVar1",+ scopeInstanceId: ROOT_INSTANCE_ID,+ type: "variable" as const,+ name: "Global Var",+ value: { type: "string" as const, value: "existing" },+ },+ ],+ ]);+ const data = getWebstudioDataStub({ dataSources });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ dataSources: [+ {+ id: "globalVar1",+ scopeInstanceId: ROOT_INSTANCE_ID,+ type: "variable",+ name: "Global Var",+ value: { type: "string", value: "new value" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ // Should preserve existing global variable+ const existingVar = data.dataSources.get("globalVar1");+ expect(existingVar?.type).toBe("variable");+ if (existingVar?.type === "variable") {+ expect(existingVar.value).toEqual({+ type: "string",+ value: "existing",+ });+ }+ });++ test("skip global variables that have conflicting names with availableVariables", () => {+ const data = getWebstudioDataStub();++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ dataSources: [+ {+ id: "newGlobal",+ scopeInstanceId: ROOT_INSTANCE_ID,+ type: "variable",+ name: "conflictingName",+ value: { type: "string", value: "value" },+ },+ ],+ },+ availableVariables: [+ {+ id: "existingId",+ scopeInstanceId: ROOT_INSTANCE_ID,+ type: "variable",+ name: "conflictingName",+ value: { type: "string", value: "existing" },+ },+ ],+ projectId: "",+ });++ // Should not insert the global variable due to name conflict+ expect(data.dataSources.has("newGlobal")).toBe(false);+ });++ test("handle mixed token and local style sources in styleSourceSelections", () => {+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);+ const styleSources = toMap<StyleSource>([+ { id: "existingToken", type: "token", name: "Primary" },+ ]);+ const data = getWebstudioDataStub({ breakpoints, styleSources });++ insertWebstudioFragmentCopy({+ data,+ fragment: {+ ...emptyFragment,+ instances: [+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ breakpoints: [{ id: "base", label: "base" }],+ styleSourceSelections: [+ {+ instanceId: "box",+ values: ["localStyle1", "existingToken", "localStyle2"],+ },+ ],+ styleSources: [+ { id: "localStyle1", type: "local" },+ { id: "localStyle2", type: "local" },+ ],+ styles: [+ {+ styleSourceId: "localStyle1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ styleSourceId: "localStyle2",+ breakpointId: "base",+ property: "fontSize",+ value: { type: "unit", value: 16, unit: "px" },+ },+ ],+ },+ availableVariables: [],+ projectId: "",+ });++ const newBoxId = Array.from(data.instances.keys())[0];+ const selection = data.styleSourceSelections.get(newBoxId);++ expect(selection?.values).toHaveLength(3);+ expect(selection?.values[1]).toBe("existingToken"); // Token preserved+ expect(selection?.values[0]).not.toBe("localStyle1"); // Local regenerated+ expect(selection?.values[2]).not.toBe("localStyle2"); // Local regenerated++ // Verify both local styles were created with new ids+ const localStyles = Array.from(data.styleSources.values()).filter(+ (s) => s.type === "local"+ );+ expect(localStyles).toHaveLength(2);+ });+});++describe("detectPageTokenConflicts", () => {+ beforeEach(() => {+ $project.set({ id: "project-id" } as Project);+ });++ test("detectFragmentTokenConflicts returns token style conflicts", () => {+ const targetData = renderData(+ <$.Body ws:id="body">+ <$.Box+ ws:id="existing-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: blue;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );+ setDataStores(targetData);+ $pages.set(createDefaultPages({ rootInstanceId: "body" }));++ const sourceData = renderData(+ <$.Body ws:id="source-body">+ <$.Box+ ws:id="source-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );++ const conflicts = detectFragmentTokenConflicts({+ fragment: extractWebstudioFragment(sourceData, "source-box"),+ });++ expect(conflicts).toHaveLength(1);+ expect(conflicts[0]?.existingToken.name).toBe("primary");+ expect(conflicts[0]?.fragmentToken.name).toBe("primary");+ });++ test("returns empty array when no conflicts exist", () => {+ // Set up target project data (no tokens)+ const targetData = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="existing-box"></$.Box>+ </$.Body>+ );+ setDataStores(targetData);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);++ // Create source data with a token+ const sourceData = renderData(+ <$.Body ws:id="source-body">+ <$.Box+ ws:id="source-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );+ const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });+ const sourceWebstudioData: WebstudioData = {+ ...sourceData,+ pages: sourcePages,+ };++ const conflicts = detectPageTokenConflicts({+ sourceData: sourceWebstudioData,+ pageId: sourcePages.homePageId,+ });++ // No conflicts+ expect(conflicts).toEqual([]);+ });++ test("returns conflicts when token conflicts exist", () => {+ // Set up target project with a "primary" token+ const targetData = renderData(+ <$.Body ws:id="body">+ <$.Box+ ws:id="existing-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: blue;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );+ setDataStores(targetData);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);++ // Create source data with same "primary" token but different styles+ const sourceData = renderData(+ <$.Body ws:id="source-body">+ <$.Box+ ws:id="source-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );+ const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });+ const sourceWebstudioData: WebstudioData = {+ ...sourceData,+ pages: sourcePages,+ };++ const conflicts = detectPageTokenConflicts({+ sourceData: sourceWebstudioData,+ pageId: sourcePages.homePageId,+ });++ // Should return conflicts+ expect(conflicts.length).toBeGreaterThan(0);+ expect(conflicts[0].tokenName).toBe("primary");+ });++ test("detects conflicts from ROOT_INSTANCE tokens", () => {+ // Set up target project with a "header" token+ const targetData = renderData(+ <$.Body ws:id="body">+ <$.Box+ ws:id="existing-box"+ ws:tokens={[+ token(+ "header",+ css`+ background: white;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );+ setDataStores(targetData);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);++ // Create source data with a ROOT_INSTANCE that has conflicting "header" token+ const sourceBodyData = renderData(+ <$.Body ws:id="source-body">+ <$.Box ws:id="source-box"></$.Box>+ </$.Body>+ );+ // Add a global "header" token with different styles (simulating ROOT_INSTANCE content)+ const headerTokenId = "header-token-id";+ sourceBodyData.styleSources.set(headerTokenId, {+ type: "token",+ id: headerTokenId,+ name: "header",+ });+ const baseBreakpointId = Array.from(+ sourceBodyData.breakpoints.values()+ ).find((b) => b.minWidth === undefined)?.id;+ if (baseBreakpointId) {+ sourceBodyData.styles.set(`${headerTokenId}:base:backgroundColor`, {+ styleSourceId: headerTokenId,+ breakpointId: baseBreakpointId,+ property: "backgroundColor",+ value: { type: "keyword", value: "black" },+ });+ }+ // Add ROOT_INSTANCE with the header token+ sourceBodyData.instances.set(ROOT_INSTANCE_ID, {+ type: "instance",+ id: ROOT_INSTANCE_ID,+ component: "Box",+ children: [],+ });+ sourceBodyData.styleSourceSelections.set(ROOT_INSTANCE_ID, {+ instanceId: ROOT_INSTANCE_ID,+ values: [headerTokenId],+ });++ const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });+ const sourceWebstudioData: WebstudioData = {+ ...sourceBodyData,+ pages: sourcePages,+ };++ const conflicts = detectPageTokenConflicts({+ sourceData: sourceWebstudioData,+ pageId: sourcePages.homePageId,+ });++ // Should detect conflict from ROOT_INSTANCE token+ expect(conflicts.length).toBeGreaterThan(0);+ expect(conflicts[0].tokenName).toBe("header");+ });++ test("throws error when page not found", () => {+ const targetData = renderData(<$.Body ws:id="body"></$.Body>);+ setDataStores(targetData);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);++ const sourceData = renderData(<$.Body ws:id="source-body"></$.Body>);+ const sourcePages = createDefaultPages({ rootInstanceId: "source-body" });+ const sourceWebstudioData: WebstudioData = {+ ...sourceData,+ pages: sourcePages,+ };++ expect(() =>+ detectPageTokenConflicts({+ sourceData: sourceWebstudioData,+ pageId: "non-existent-page-id",+ })+ ).toThrow("Page not found");+ });+});diff --git a/apps/builder/app/shared/instance-utils/fragment.ts b/apps/builder/app/shared/instance-utils/fragment.tsnew file mode 100644index 0000000000..fe9a6d0d31--- /dev/null+++ b/apps/builder/app/shared/instance-utils/fragment.ts@@ -0,0 +1,834 @@+// Fragment utilities own extracting, copying, and conflict-checking portable+// Webstudio fragments. Put serialization-style instance subtree cloning and+// fragment asset/style/data remapping here, not live tree placement decisions.+import { nanoid } from "nanoid";+import type { StyleValue } from "@webstudio-is/css-engine";+import {+ type Asset,+ type Breakpoints,+ type DataSource,+ type DataSources,+ type Instance,+ type Instances,+ type Prop,+ type Resource,+ type StyleDecl,+ type WebstudioData,+ type WebstudioFragment,+ ROOT_INSTANCE_ID,+ findPageByIdOrPath,+ findTreeInstanceIds,+ findTreeInstanceIdsExcludingSlotDescendants,+ getHomePage,+ portalComponent,+} from "@webstudio-is/sdk";+import type { Project } from "@webstudio-is/project";+import {+ getContentModeCapabilities,+ isContentModeCopyableProp,+} from "@webstudio-is/project/content-mode-permissions";+import { buildMergedBreakpointIds, maxBreakpoints } from "../breakpoints-utils";+import {+ replaceDataSourcesInExpression,+ restoreExpressionVariables,+ unsetExpressionVariables,+} from "../data-variables";+import {+ collectStyleSourcesFromInstances,+ detectTokenConflicts,+ insertLocalStyleSourcesWithNewIds,+ insertPortalLocalStyleSources,+ insertTokenStyleSources,+} from "../style-source-utils";+import type { ConflictResolution } from "../token-conflict-dialog";+import { setDifference, setUnion } from "../shim";+import { $registeredComponentMetas } from "../nano-states";+import { getWebstudioData, unwrap } from "./data";++const traverseStyleValue = (+ value: StyleValue,+ callback: (value: StyleValue) => void+) => {+ if (+ value.type === "fontFamily" ||+ value.type === "image" ||+ value.type === "unit" ||+ value.type === "keyword" ||+ value.type === "unparsed" ||+ value.type === "invalid" ||+ value.type === "unset" ||+ value.type === "color" ||+ value.type === "rgb" ||+ value.type === "function" ||+ value.type === "guaranteedInvalid"+ ) {+ callback(value);+ return;+ }+ if (value.type === "var") {+ if (value.fallback) {+ traverseStyleValue(value.fallback, callback);+ }+ return;+ }+ if (value.type === "tuple" || value.type === "layers") {+ for (const item of value.value) {+ traverseStyleValue(item, callback);+ }+ return;+ }+ if (value.type === "shadow") {+ traverseStyleValue(value.offsetX, callback);+ traverseStyleValue(value.offsetY, callback);+ if (value.blur) {+ traverseStyleValue(value.blur, callback);+ }+ if (value.spread) {+ traverseStyleValue(value.spread, callback);+ }+ if (value.color) {+ traverseStyleValue(value.color, callback);+ }+ return;+ }+ value satisfies never;+};++export const extractWebstudioFragment = (+ data: Omit<WebstudioData, "pages">,+ rootInstanceId: string,+ options: { unsetVariables?: Set<DataSource["id"]> } = {}+): WebstudioFragment => {+ const {+ assets,+ instances,+ dataSources,+ resources,+ props,+ styleSourceSelections,+ styleSources,+ breakpoints,+ styles,+ } = data;++ // collect the instance by id and all its descendants including portal instances+ const fragmentInstanceIds = findTreeInstanceIds(instances, rootInstanceId);+ let fragmentInstances: Instance[] = [];++ // Collect style sources and selections from instances+ const {+ styleSourceSelectionsArray: fragmentStyleSourceSelections,+ styleSourcesMap: fragmentStyleSources,+ stylesArray: fragmentStyles,+ } = collectStyleSourcesFromInstances({+ instanceIds: fragmentInstanceIds,+ styleSourceSelections,+ styleSources,+ styles,+ });++ for (const instanceId of fragmentInstanceIds) {+ const instance = instances.get(instanceId);+ if (instance) {+ fragmentInstances.push(instance);+ }+ }++ const fragmentAssetIds = new Set<Asset["id"]>();+ const fragmentFontFamilies = new Set<string>();++ // collect breakpoints and assets from styles+ const fragmentBreapoints: Breakpoints = new Map();+ for (const styleDecl of fragmentStyles) {+ // collect breakpoints+ if (fragmentBreapoints.has(styleDecl.breakpointId) === false) {+ const breakpoint = breakpoints.get(styleDecl.breakpointId);+ if (breakpoint) {+ fragmentBreapoints.set(styleDecl.breakpointId, breakpoint);+ }+ }++ // collect assets including fonts+ traverseStyleValue(styleDecl.value, (value) => {+ if (value.type === "fontFamily") {+ for (const fontFamily of value.value) {+ fragmentFontFamilies.add(fontFamily);+ }+ }+ if (value.type === "image") {+ if (value.value.type === "asset") {+ fragmentAssetIds.add(value.value.value);+ }+ }+ });+ }++ // collect variables scoped to fragment instances+ // and variables outside of scope to unset+ const fragmentDataSources: DataSources = new Map();+ const fragmentResourceIds = new Set<Resource["id"]>();+ const unsetNameById = new Map<DataSource["id"], DataSource["name"]>();+ const unsetVariables = options.unsetVariables ?? new Set();+ for (const dataSource of dataSources.values()) {+ if (+ fragmentInstanceIds.has(dataSource.scopeInstanceId ?? "") &&+ unsetVariables.has(dataSource.id) === false+ ) {+ fragmentDataSources.set(dataSource.id, dataSource);+ if (dataSource.type === "resource") {+ fragmentResourceIds.add(dataSource.resourceId);+ }+ } else {+ unsetNameById.set(dataSource.id, dataSource.name);+ }+ }++ // unset variables outside of scope+ fragmentInstances = fragmentInstances.map((instance) => {+ instance = structuredClone(unwrap(instance));+ for (const child of instance.children) {+ if (child.type === "expression") {+ const expression = child.value;+ child.value = unsetExpressionVariables({ expression, unsetNameById });+ }+ }+ return instance;+ });++ // collect props bound to these instances+ // and unset variables outside of scope+ const fragmentProps: Prop[] = [];+ for (const prop of props.values()) {+ if (fragmentInstanceIds.has(prop.instanceId) === false) {+ continue;+ }++ if (prop.type === "expression") {+ const newProp = structuredClone(unwrap(prop));+ const expression = prop.value;+ newProp.value = unsetExpressionVariables({ expression, unsetNameById });+ fragmentProps.push(newProp);+ continue;+ }++ if (prop.type === "action") {+ const newProp = structuredClone(unwrap(prop));+ for (const value of newProp.value) {+ const expression = value.code;+ value.code = unsetExpressionVariables({ expression, unsetNameById });+ }+ fragmentProps.push(newProp);+ continue;+ }++ fragmentProps.push(prop);++ // collect assets+ if (prop.type === "asset") {+ fragmentAssetIds.add(prop.value);+ }++ // collect resources from props+ if (prop.type === "resource") {+ fragmentResourceIds.add(prop.value);+ }+ }++ // collect resources bound to all fragment data sources+ // and unset variables which are defined outside of scope+ // and used in resource+ const fragmentResources: Resource[] = [];+ for (const resourceId of fragmentResourceIds) {+ const resource = resources.get(resourceId);+ if (resource === undefined) {+ continue;+ }+ const newResource = structuredClone(unwrap(resource));+ newResource.url = unsetExpressionVariables({+ expression: newResource.url,+ unsetNameById,+ });+ for (const header of newResource.headers) {+ header.value = unsetExpressionVariables({+ expression: header.value,+ unsetNameById,+ });+ }+ if (newResource.searchParams) {+ for (const searchParam of newResource.searchParams) {+ searchParam.value = unsetExpressionVariables({+ expression: searchParam.value,+ unsetNameById,+ });+ }+ }+ if (newResource.body) {+ newResource.body = unsetExpressionVariables({+ expression: newResource.body,+ unsetNameById,+ });+ }+ fragmentResources.push(newResource);+ }++ const fragmentAssets: Asset[] = [];+ for (const asset of assets.values()) {+ if (+ fragmentAssetIds.has(asset.id) ||+ (asset.type === "font" && fragmentFontFamilies.has(asset.meta.family))+ ) {+ fragmentAssets.push(asset);+ }+ }++ return {+ children: [{ type: "id", value: rootInstanceId }],+ instances: fragmentInstances,+ styleSourceSelections: fragmentStyleSourceSelections,+ styleSources: Array.from(fragmentStyleSources.values()),+ breakpoints: Array.from(fragmentBreapoints.values()),+ styles: fragmentStyles,+ dataSources: Array.from(fragmentDataSources.values()),+ resources: fragmentResources,+ props: fragmentProps,+ assets: fragmentAssets,+ };+};++const getFragmentInstancesData = (fragment: WebstudioFragment) => {+ const fragmentInstances: Instances = new Map();+ const portalContentRootIds = new Set<Instance["id"]>();+ for (const instance of fragment.instances) {+ fragmentInstances.set(instance.id, instance);+ if (instance.component === portalComponent) {+ for (const child of instance.children) {+ if (child.type === "id") {+ portalContentRootIds.add(child.value);+ }+ }+ }+ }+ return { fragmentInstances, portalContentRootIds };+};++const insertFragmentAssetsMutable = ({+ fragment,+ projectId,+ assets,+}: {+ fragment: WebstudioFragment;+ projectId: Project["id"];+ assets: WebstudioData["assets"];+}) => {+ for (const asset of fragment.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 });+ }+ }+};++const insertFragmentBreakpointsMutable = ({+ fragment,+ breakpoints,+ onBreakpointLimitMerge,+}: {+ fragment: WebstudioFragment;+ breakpoints: Breakpoints;+ onBreakpointLimitMerge?: () => void;+}) => {+ let didMergeBreakpointsDueToLimit = false;+ const mergedBreakpointIds = buildMergedBreakpointIds(+ fragment.breakpoints,+ breakpoints,+ {+ maxBreakpointCount: maxBreakpoints,+ onBreakpointMergedDueToLimit: () => {+ didMergeBreakpointsDueToLimit = true;+ },+ }+ );+ if (didMergeBreakpointsDueToLimit) {+ onBreakpointLimitMerge?.();+ }+ for (const newBreakpoint of fragment.breakpoints) {+ if (mergedBreakpointIds.has(newBreakpoint.id) === false) {+ breakpoints.set(newBreakpoint.id, newBreakpoint);+ }+ }+ return mergedBreakpointIds;+};++const getFragmentContentModeCapabilities = ({+ fragment,+ fragmentInstances,+ styleSources,+}: {+ fragment: WebstudioFragment;+ fragmentInstances: Instances;+ styleSources: WebstudioData["styleSources"];+}) =>+ getContentModeCapabilities({+ instances: fragmentInstances,+ metas: $registeredComponentMetas.get(),+ props: new Map(fragment.props.map((prop) => [prop.id, prop])),+ styleSources,+ contentRootIds: new Set(+ fragment.children+ .filter((child) => child.type === "id")+ .map((child) => child.value)+ ),+ });++export const __testing__ = {+ getFragmentInstancesData,+ insertFragmentAssetsMutable,+ insertFragmentBreakpointsMutable,+ getFragmentContentModeCapabilities,+};++export const insertWebstudioFragmentCopy = ({+ data,+ fragment,+ availableVariables,+ projectId,+ conflictResolution = "theirs",+ onBreakpointLimitMerge,+ // In content mode, insertion keeps content-editable instance data, creates+ // local styles for inserted instances, and avoids data/resource records.+ contentMode = false,+}: {+ data: Omit<WebstudioData, "pages">;+ fragment: WebstudioFragment;+ availableVariables: DataSource[];+ projectId: Project["id"];+ conflictResolution?: ConflictResolution;+ onBreakpointLimitMerge?: () => void;+ contentMode?: boolean;+}) => {+ const newInstanceIds = new Map<Instance["id"], Instance["id"]>();+ const newDataSourceIds = new Map<DataSource["id"], DataSource["id"]>();+ const newDataIds = {+ newInstanceIds,+ newDataSourceIds,+ };++ const { fragmentInstances, portalContentRootIds } =+ getFragmentInstancesData(fragment);++ const {+ assets,+ instances,+ resources,+ dataSources,+ props,+ breakpoints,+ styleSources,+ styles,+ styleSourceSelections,+ } = data;++ /**+ * 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+ */++ const mergedBreakpointIds =+ contentMode === false+ ? insertFragmentBreakpointsMutable({+ fragment,+ breakpoints,+ onBreakpointLimitMerge,+ })+ : new Map<StyleDecl["breakpointId"], StyleDecl["breakpointId"]>();++ insertFragmentAssetsMutable({ fragment, projectId, assets });++ let styleSourceIdMap = new Map<+ StyleDecl["styleSourceId"],+ StyleDecl["styleSourceId"]+ >();++ if (contentMode === false) {+ // insert tokens with their styles++ styleSourceIdMap = insertTokenStyleSources({+ fragmentStyleSources: fragment.styleSources,+ fragmentStyles: fragment.styles,+ styleSources,+ styles,+ breakpoints,+ mergedBreakpointIds,+ conflictResolution,+ });+ }++ let portalContentIds = new Set<Instance["id"]>();++ // insert portal contents+ // - instances+ // - data sources+ // - props+ // - local styles+ for (const rootInstanceId of portalContentRootIds) {+ const instanceIds = findTreeInstanceIdsExcludingSlotDescendants(+ fragmentInstances,+ rootInstanceId+ );+ portalContentIds = setUnion(portalContentIds, instanceIds);++ // prevent reinserting portals which could be already changed by user+ if (instances.has(rootInstanceId)) {+ continue;+ }++ if (contentMode === false) {+ const usedResourceIds = new Set<Resource["id"]>();+ for (const dataSource of fragment.dataSources) {+ // insert only data sources within portal content+ if (instanceIds.has(dataSource.scopeInstanceId ?? "")) {+ dataSources.set(dataSource.id, dataSource);+ if (dataSource.type === "resource") {+ usedResourceIds.add(dataSource.resourceId);+ }+ }+ }++ for (const prop of fragment.props) {+ if (instanceIds.has(prop.instanceId)) {+ props.set(prop.id, prop);+ if (prop.type === "resource") {+ usedResourceIds.add(prop.value);+ }+ }+ }++ for (const resource of fragment.resources) {+ if (usedResourceIds.has(resource.id)) {+ resources.set(resource.id, resource);+ }+ }+ }++ for (const instance of fragment.instances) {+ if (instanceIds.has(instance.id)) {+ instances.set(instance.id, instance);+ }+ }++ if (contentMode === false) {+ // insert local style sources with their styles++ insertPortalLocalStyleSources({+ fragmentStyleSources: fragment.styleSources,+ fragmentStyleSourceSelections: fragment.styleSourceSelections,+ fragmentStyles: fragment.styles,+ instanceIds,+ styleSources,+ styleSourceSelections,+ styles,+ mergedBreakpointIds,+ });+ }+ }++ /**+ * 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 fragmentInstanceIds = setDifference(+ new Set(fragmentInstances.keys()),+ portalContentIds+ );+ for (const instanceId of fragmentInstanceIds) {+ newInstanceIds.set(instanceId, nanoid());+ }+ fragmentInstanceIds.add(ROOT_INSTANCE_ID);+ newInstanceIds.set(ROOT_INSTANCE_ID, ROOT_INSTANCE_ID);++ const maskedIdByName = new Map<DataSource["name"], DataSource["id"]>();+ for (const dataSource of availableVariables) {+ maskedIdByName.set(dataSource.name, dataSource.id);+ }+ const newResourceIds = new Map<Resource["id"], Resource["id"]>();+ if (contentMode === false) {+ for (let dataSource of fragment.dataSources) {+ const scopeInstanceId = dataSource.scopeInstanceId ?? "";+ if (scopeInstanceId === ROOT_INSTANCE_ID) {+ // add global variable only if not exist already+ if (+ dataSources.has(dataSource.id) === false &&+ maskedIdByName.has(dataSource.name) === false+ ) {+ dataSources.set(dataSource.id, dataSource);+ }+ continue;+ }+ // insert only data sources within portal content+ if (fragmentInstanceIds.has(scopeInstanceId)) {+ const newDataSourceId = nanoid();+ newDataSourceIds.set(dataSource.id, newDataSourceId);+ dataSource = structuredClone(unwrap(dataSource));+ dataSource.id = newDataSourceId;+ dataSource.scopeInstanceId =+ newInstanceIds.get(scopeInstanceId) ?? scopeInstanceId;+ if (dataSource.type === "resource") {+ const newResourceId = nanoid();+ newResourceIds.set(dataSource.resourceId, newResourceId);+ dataSource.resourceId = newResourceId;+ }+ dataSources.set(dataSource.id, dataSource);+ }+ }+ }++ const fragmentContentModeCapabilities =+ contentMode === false+ ? undefined+ : getFragmentContentModeCapabilities({+ fragment,+ fragmentInstances,+ styleSources,+ });+ for (let prop of fragment.props) {+ if (fragmentInstanceIds.has(prop.instanceId) === false) {+ continue;+ }+ if (+ contentMode &&+ (fragmentContentModeCapabilities === undefined ||+ isContentModeCopyableProp({+ capabilities: fragmentContentModeCapabilities,+ prop,+ }) === false)+ ) {+ continue;+ }+ prop = structuredClone(unwrap(prop));+ prop.id = nanoid();+ prop.instanceId = newInstanceIds.get(prop.instanceId) ?? prop.instanceId;+ if (prop.type === "expression") {+ prop.value = restoreExpressionVariables({+ expression: prop.value,+ maskedIdByName,+ });+ prop.value = replaceDataSourcesInExpression(prop.value, newDataSourceIds);+ }+ if (prop.type === "action") {+ for (const value of prop.value) {+ value.code = restoreExpressionVariables({+ expression: value.code,+ maskedIdByName,+ });+ value.code = replaceDataSourcesInExpression(+ value.code,+ newDataSourceIds+ );+ }+ }+ if (prop.type === "parameter") {+ prop.value = newDataSourceIds.get(prop.value) ?? prop.value;+ }+ if (prop.type === "resource") {+ const newResourceId = nanoid();+ newResourceIds.set(prop.value, newResourceId);+ prop.value = newResourceId;+ }+ props.set(prop.id, prop);+ }++ if (contentMode === false) {+ for (let resource of fragment.resources) {+ if (newResourceIds.has(resource.id) === false) {+ continue;+ }+ resource = structuredClone(unwrap(resource));+ resource.id = newResourceIds.get(resource.id) ?? resource.id;+ resource.url = restoreExpressionVariables({+ expression: resource.url,+ maskedIdByName,+ });+ resource.url = replaceDataSourcesInExpression(+ resource.url,+ newDataSourceIds+ );+ for (const header of resource.headers) {+ header.value = restoreExpressionVariables({+ expression: header.value,+ maskedIdByName,+ });+ header.value = replaceDataSourcesInExpression(+ header.value,+ newDataSourceIds+ );+ }+ if (resource.searchParams) {+ for (const searchParam of resource.searchParams) {+ searchParam.value = restoreExpressionVariables({+ expression: searchParam.value,+ maskedIdByName,+ });+ searchParam.value = replaceDataSourcesInExpression(+ searchParam.value,+ newDataSourceIds+ );+ }+ }+ if (resource.body) {+ resource.body = restoreExpressionVariables({+ expression: resource.body,+ maskedIdByName,+ });+ resource.body = replaceDataSourcesInExpression(+ resource.body,+ newDataSourceIds+ );+ }+ resources.set(resource.id, resource);+ }+ }++ for (let instance of fragment.instances) {+ if (fragmentInstanceIds.has(instance.id)) {+ instance = structuredClone(unwrap(instance));+ instance.id = newInstanceIds.get(instance.id) ?? instance.id;+ for (const child of instance.children) {+ if (child.type === "id") {+ child.value = newInstanceIds.get(child.value) ?? child.value;+ }+ if (child.type === "expression") {+ child.value = restoreExpressionVariables({+ expression: child.value,+ maskedIdByName,+ });+ child.value = replaceDataSourcesInExpression(+ child.value,+ newDataSourceIds+ );+ }+ }+ instances.set(instance.id, instance);+ }+ }++ const localStyleSourceInput = {+ fragmentStyleSources: fragment.styleSources,+ fragmentStyleSourceSelections: fragment.styleSourceSelections,+ fragmentStyles: fragment.styles,+ fragmentInstanceIds,+ newInstanceIds,+ styleSources,+ styleSourceSelections,+ styles,+ };+ if (contentMode) {+ insertLocalStyleSourcesWithNewIds({+ ...localStyleSourceInput,+ contentMode: true,+ breakpoints,+ });+ } else {+ insertLocalStyleSourcesWithNewIds({+ ...localStyleSourceInput,+ contentMode: false,+ styleSourceIdMap,+ mergedBreakpointIds,+ breakpoints,+ });+ }++ return newDataIds;+};+export const detectFragmentTokenConflicts = ({+ fragment,+}: {+ fragment: WebstudioFragment;+}) => {+ const data = getWebstudioData();++ const mergedBreakpointIds = buildMergedBreakpointIds(+ fragment.breakpoints,+ data.breakpoints,+ { maxBreakpointCount: maxBreakpoints }+ );++ return detectTokenConflicts({+ fragmentStyleSources: fragment.styleSources,+ fragmentStyles: fragment.styles,+ existingStyleSources: data.styleSources,+ existingStyles: data.styles,+ breakpoints: data.breakpoints,+ mergedBreakpointIds,+ });+};++/**+ * Detects token conflicts for a page insertion.+ * Combines fragments from ROOT_INSTANCE and page body for conflict detection.+ *+ * @param sourceData - The source webstudio data containing the page+ * @param pageId - The page ID to check for conflicts+ * @returns Array of token conflicts (empty if no conflicts)+ */+export const detectPageTokenConflicts = ({+ sourceData,+ pageId,+}: {+ sourceData: WebstudioData;+ pageId: string;+}) => {+ const data = getWebstudioData();++ const page = findPageByIdOrPath(pageId, sourceData.pages);+ if (page === undefined) {+ throw new Error("Page not found");+ }+ const targetPage = page ?? getHomePage(sourceData.pages);++ // Extract fragments for both ROOT_INSTANCE and page body+ const rootFragment = extractWebstudioFragment(sourceData, ROOT_INSTANCE_ID);+ const pageFragment = extractWebstudioFragment(+ sourceData,+ targetPage.rootInstanceId+ );++ // Combine style sources and styles from both fragments+ const combinedStyleSources = [+ ...rootFragment.styleSources,+ ...pageFragment.styleSources,+ ];+ const combinedStyles = [...rootFragment.styles, ...pageFragment.styles];+ const combinedBreakpoints = [+ ...rootFragment.breakpoints,+ ...pageFragment.breakpoints,+ ];++ const mergedBreakpointIds = buildMergedBreakpointIds(+ combinedBreakpoints,+ data.breakpoints,+ { maxBreakpointCount: maxBreakpoints }+ );++ return detectTokenConflicts({+ fragmentStyleSources: combinedStyleSources,+ fragmentStyles: combinedStyles,+ existingStyleSources: data.styleSources,+ existingStyles: data.styles,+ breakpoints: data.breakpoints,+ mergedBreakpointIds,+ });+};diff --git a/apps/builder/app/shared/instance-utils/insert.test.tsx b/apps/builder/app/shared/instance-utils/insert.test.tsxnew file mode 100644index 0000000000..ab6994e32d--- /dev/null+++ b/apps/builder/app/shared/instance-utils/insert.test.tsx@@ -0,0 +1,1387 @@+import {+ findClosestInsertable,+ getComponentTemplateData,+ insertWebstudioFragmentAt,+} from "./insert";+import {+ insertInstanceChildrenMutable,+ insertWebstudioElementAt,+} from "./insert";+import { enableMapSet } from "immer";+import { describe, test, expect, beforeEach, vi } from "vitest";+import { toast } from "@webstudio-is/design-system";+import type { Project } from "@webstudio-is/project";+import { createDefaultPages } from "@webstudio-is/project-build";+import {+ $,+ ws,+ css,+ expression,+ renderTemplate,+ renderData,+ token,+} from "@webstudio-is/template";+import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";+import type { WebstudioData, WebstudioFragment } from "@webstudio-is/sdk";+import { coreMetas, elementComponent } from "@webstudio-is/sdk";+import {+ $registeredComponentMetas,+ $registeredTemplates,+} from "../nano-states";+import { $assets } from "~/shared/sync/data-stores";+import {+ $breakpoints,+ $dataSources,+ $instances,+ $pages,+ $project,+ $props,+ $styleSourceSelections,+ $styleSources,+ $styles,+ $resources,+} from "~/shared/sync/data-stores";+import { registerContainers } from "../sync/sync-stores";+import { $selectedInstanceSelector, getInstancePath } from "../nano-states";+import { selectPage } from "../nano-states";+import { selectInstance } from "../nano-states";+import { $selectedPageId } from "../nano-states/pages";+import { expectSlotsShareFragment } from "../slot-test-utils";++enableMapSet();+registerContainers();++$pages.set(createDefaultPages({ rootInstanceId: "" }));++const defaultMetasMap = new Map(+ Object.entries({ ...defaultMetas, ...coreMetas })+);+$registeredComponentMetas.set(defaultMetasMap);++const createFragment = (+ fragment: Partial<WebstudioFragment>+): WebstudioFragment => ({+ children: [],+ instances: [],+ styleSourceSelections: [],+ styleSources: [],+ breakpoints: [],+ styles: [],+ dataSources: [],+ resources: [],+ props: [],+ assets: [],+ ...fragment,+});++const setDataStores = (data: Omit<WebstudioData, "pages">) => {+ $instances.set(data.instances);+ $breakpoints.set(data.breakpoints);+ $styleSources.set(data.styleSources);+ $styles.set(data.styles);+ $styleSourceSelections.set(data.styleSourceSelections);+ $dataSources.set(data.dataSources);+ $props.set(data.props);+ $assets.set(data.assets);+ $resources.set(data.resources);+};++describe("insert instance children", () => {+ test("insert instance children into empty target", () => {+ const data = renderData(+ <ws.element ws:tag="body" ws:id="bodyId"></ws.element>+ );+ const [div] = renderTemplate(+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ ).instances;+ data.instances.set(div.id, div);+ insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {+ parentSelector: ["bodyId"],+ position: "end",+ });+ expect(data).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ </ws.element>+ )+ );+ });++ test("insert instance children into the end of target", () => {+ const data = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="textId"></ws.element>+ </ws.element>+ );+ const [div] = renderTemplate(+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ ).instances;+ data.instances.set(div.id, div);+ insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {+ parentSelector: ["bodyId"],+ position: "end",+ });+ expect(data).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="textId"></ws.element>+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ </ws.element>+ )+ );+ });++ test("insert instance children into legacy slot with direct children", () => {+ const data = renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slotId">+ <$.Box ws:id="boxId"></$.Box>+ </$.Slot>+ </$.Body>+ );+ const [div] = renderTemplate(+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ ).instances;+ data.instances.set(div.id, div);++ insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {+ parentSelector: ["slotId", "bodyId"],+ position: "end",+ });++ const fragmentId = data.instances.get("slotId")?.children[0]?.value;+ expect(data).toEqual(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slotId">+ <$.Fragment ws:id={fragmentId}>+ <$.Box ws:id="boxId"></$.Box>+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ )+ );+ });++ test("insert instance children into the start of target", () => {+ const data = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="textId"></ws.element>+ </ws.element>+ );+ const [div] = renderTemplate(+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ ).instances;+ data.instances.set(div.id, div);+ insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {+ parentSelector: ["bodyId"],+ position: 0,+ });+ expect(data).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ <ws.element ws:tag="div" ws:id="textId"></ws.element>+ </ws.element>+ )+ );+ });++ test("insert instance children at the start of text", () => {+ const data = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="textId">+ text+ </ws.element>+ </ws.element>+ );+ const [div] = renderTemplate(+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ ).instances;+ data.instances.set(div.id, div);+ insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {+ parentSelector: ["textId", "bodyId"],+ position: 0,+ });+ const [_bodyId, _textId, _divId, spanId] = data.instances.keys();+ expect(data).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="textId">+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ <ws.element ws:tag="span" ws:id={spanId}>+ text+ </ws.element>+ </ws.element>+ </ws.element>+ )+ );+ });++ test("insert instance children at the end of text", () => {+ const data = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="textId">+ text+ </ws.element>+ </ws.element>+ );+ const [div] = renderTemplate(+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ ).instances;+ data.instances.set(div.id, div);+ insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {+ parentSelector: ["textId", "bodyId"],+ position: "end",+ });+ const [_bodyId, _textId, _divId, spanId] = data.instances.keys();+ expect(data).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="textId">+ <ws.element ws:tag="span" ws:id={spanId}>+ text+ </ws.element>+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ </ws.element>+ </ws.element>+ )+ );+ });++ test("insert instance children between text children", () => {+ const data = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="textId">+ <ws.element ws:tag="strong" ws:id="strongId">+ strong+ </ws.element>+ text+ <ws.element ws:tag="em" ws:id="emId">+ emphasis+ </ws.element>+ </ws.element>+ </ws.element>+ );+ const [div] = renderTemplate(+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ ).instances;+ data.instances.set(div.id, div);+ insertInstanceChildrenMutable(data, [{ type: "id", value: "divId" }], {+ parentSelector: ["textId", "bodyId"],+ position: 1,+ });+ const [+ _bodyId,+ _textId,+ _strongId,+ _emId,+ _divId,+ leftSpanId,+ rightSpanId,+ ] = data.instances.keys();+ expect(data).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="textId">+ <ws.element ws:tag="span" ws:id={leftSpanId}>+ <ws.element ws:tag="strong" ws:id="strongId">+ strong+ </ws.element>+ </ws.element>+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ <ws.element ws:tag="span" ws:id={rightSpanId}>+ text+ <ws.element ws:tag="em" ws:id="emId">+ emphasis+ </ws.element>+ </ws.element>+ </ws.element>+ </ws.element>+ )+ );+ });+});++describe("insert webstudio element at", () => {+ beforeEach(() => {+ $styleSourceSelections.set(new Map());+ $styleSources.set(new Map());+ $breakpoints.set(new Map());+ $styles.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $props.set(new Map());+ $assets.set(new Map());+ });++ test("insert element with div tag into body", () => {+ $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);+ insertWebstudioElementAt({+ parentSelector: ["bodyId"],+ position: "end",+ });+ const [_bodyId, newInstanceId] = $instances.get().keys();+ expect($instances.get()).toEqual(+ renderData(+ <$.Body ws:id="bodyId">+ <ws.element ws:id={newInstanceId} ws:tag="div" />+ </$.Body>+ ).instances+ );+ });++ test("insert element with li tag into ul", () => {+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <ws.element ws:id="listId" ws:tag="ul"></ws.element>+ </$.Body>+ ).instances+ );+ insertWebstudioElementAt({+ parentSelector: ["listId", "bodyId"],+ position: "end",+ });+ const [_bodyId, _listId, newInstanceId] = $instances.get().keys();+ expect($instances.get()).toEqual(+ renderData(+ <$.Body ws:id="bodyId">+ <ws.element ws:id="listId" ws:tag="ul">+ <ws.element ws:id={newInstanceId} ws:tag="li" />+ </ws.element>+ </$.Body>+ ).instances+ );+ });++ test("insert element into selected instance", () => {+ $pages.set(+ createDefaultPages({ homePageId: "homePageId", rootInstanceId: "bodyId" })+ );+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <ws.element ws:id="divId" ws:tag="div"></ws.element>+ </$.Body>+ ).instances+ );+ selectPage("homePageId");+ selectInstance(["divId", "bodyId"]);+ insertWebstudioElementAt();+ const [_bodyId, _divId, newInstanceId] = $instances.get().keys();+ expect($instances.get()).toEqual(+ renderData(+ <$.Body ws:id="bodyId">+ <ws.element ws:id="divId" ws:tag="div">+ <ws.element ws:id={newInstanceId} ws:tag="div" />+ </ws.element>+ </$.Body>+ ).instances+ );+ });++ test("insert element into selected legacy slot with direct children", () => {+ $pages.set(+ createDefaultPages({ homePageId: "homePageId", rootInstanceId: "bodyId" })+ );+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slotId">+ <$.Box ws:id="boxId"></$.Box>+ </$.Slot>+ </$.Body>+ ).instances+ );+ selectPage("homePageId");+ selectInstance(["slotId", "bodyId"]);++ insertWebstudioElementAt();++ const instances = $instances.get();+ const fragmentId = instances.get("slotId")?.children[0]?.value;+ const newInstanceId = Array.from(instances.keys()).find(+ (id) =>+ id !== "bodyId" &&+ id !== "slotId" &&+ id !== "boxId" &&+ id !== fragmentId+ );+ expect(instances).toEqual(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slotId">+ <$.Fragment ws:id={fragmentId}>+ <$.Box ws:id="boxId"></$.Box>+ <ws.element ws:id={newInstanceId} ws:tag="div" />+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );+ });++ test("insert element into shared slot content", () => {+ $pages.set(+ createDefaultPages({ homePageId: "homePageId", rootInstanceId: "bodyId" })+ );+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );+ selectPage("homePageId");+ selectInstance(["slot1", "bodyId"]);++ insertWebstudioElementAt();++ const newInstanceId = $instances.get().get("fragment")?.children[1]?.value;+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: newInstanceId },+ ]);+ expect($instances.get().get(newInstanceId ?? "")?.component).toBe(+ elementComponent+ );+ });++ test("insert element at start of shared slot content", () => {+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );++ insertWebstudioElementAt({+ parentSelector: ["slot1", "bodyId"],+ position: 0,+ });++ const newInstanceId = $instances.get().get("fragment")?.children[0]?.value;+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: newInstanceId },+ { type: "id", value: "box" },+ ]);+ expect($instances.get().get(newInstanceId ?? "")?.component).toBe(+ elementComponent+ );+ });++ test("insert element into nested shared slot content", () => {+ $pages.set(+ createDefaultPages({ homePageId: "homePageId", rootInstanceId: "bodyId" })+ );+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:id="div" ws:tag="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:id="div" ws:tag="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );+ selectPage("homePageId");+ selectInstance(["div", "fragment", "slot1", "bodyId"]);++ insertWebstudioElementAt();++ const newInstanceId = $instances.get().get("div")?.children[0]?.value;+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect($instances.get().get("div")?.children).toEqual([+ { type: "id", value: newInstanceId },+ ]);+ expect($instances.get().get(newInstanceId ?? "")?.component).toBe(+ elementComponent+ );+ });++ test("insert element into closest non-textual container", () => {+ $pages.set(+ createDefaultPages({ homePageId: "homePageId", rootInstanceId: "bodyId" })+ );+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <ws.element ws:id="divId" ws:tag="div">+ text+ </ws.element>+ <ws.element ws:id="spanId" ws:tag="span"></ws.element>+ </$.Body>+ ).instances+ );+ selectPage("homePageId");+ selectInstance(["divId", "bodyId"]);+ insertWebstudioElementAt();+ const [_bodyId, _divId, _spanId, newInstanceId] = $instances.get().keys();+ expect($instances.get()).toEqual(+ renderData(+ <$.Body ws:id="bodyId">+ <ws.element ws:id="divId" ws:tag="div">+ text+ </ws.element>+ <ws.element ws:id={newInstanceId} ws:tag="div" />+ <ws.element ws:id="spanId" ws:tag="span"></ws.element>+ </$.Body>+ ).instances+ );+ });++ test("insert element into closest non-empty container", () => {+ $pages.set(+ createDefaultPages({ homePageId: "homePageId", rootInstanceId: "bodyId" })+ );+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <ws.element ws:id="imgId" ws:tag="img"></ws.element>+ <ws.element ws:id="spanId" ws:tag="span"></ws.element>+ </$.Body>+ ).instances+ );+ selectPage("homePageId");+ selectInstance(["imgId", "bodyId"]);+ insertWebstudioElementAt();+ const [_bodyId, _imgId, _spanId, newInstanceId] = $instances.get().keys();+ expect($instances.get()).toEqual(+ renderData(+ <$.Body ws:id="bodyId">+ <ws.element ws:id="imgId" ws:tag="img"></ws.element>+ <ws.element ws:id={newInstanceId} ws:tag="div" />+ <ws.element ws:id="spanId" ws:tag="span"></ws.element>+ </$.Body>+ ).instances+ );+ });++ test("reports unresolved explicit element insert target", () => {+ const toastError = vi.spyOn(toast, "error").mockImplementation(() => "");+ $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);++ expect(+ insertWebstudioElementAt({+ parentSelector: ["missingId"],+ position: "end",+ })+ ).toBe(false);++ expect(toastError).toHaveBeenCalledWith(+ "Cannot insert: the target no longer exists."+ );+ expect($instances.get()).toEqual(+ renderData(<$.Body ws:id="bodyId"></$.Body>).instances+ );+ toastError.mockRestore();+ });+});++describe("insert webstudio fragment at", () => {+ beforeEach(() => {+ $project.set({ id: "current_project" } as Project);+ $styleSourceSelections.set(new Map());+ $styleSources.set(new Map());+ $breakpoints.set(new Map());+ $styles.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $props.set(new Map());+ $assets.set(new Map());+ });++ test("insert multiple instances", () => {+ $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);+ insertWebstudioFragmentAt(+ renderTemplate(+ <>+ <$.Heading ws:id="headingId"></$.Heading>+ <$.Paragraph ws:id="paragraphId"></$.Paragraph>+ </>+ ),+ {+ parentSelector: ["bodyId"],+ position: "end",+ }+ );+ expect($instances.get()).toEqual(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Heading ws:id={expect.any(String)}></$.Heading>+ <$.Paragraph ws:id={expect.any(String)}></$.Paragraph>+ </$.Body>+ ).instances+ );+ });++ test("returns false for empty fragments", () => {+ expect(insertWebstudioFragmentAt(createFragment({}))).toBe(false);+ });++ test("returns false for tokens-only fragments without a project", () => {+ $project.set(undefined);++ expect(+ insertWebstudioFragmentAt(+ createFragment({+ styleSources: [{ type: "token", id: "token", name: "Token" }],+ })+ )+ ).toBe(false);+ });++ test("insert fragment after insertable", () => {+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Box ws:id="boxId"></$.Box>+ </$.Body>+ ).instances+ );+ insertWebstudioFragmentAt(+ renderTemplate(<$.Heading ws:id="headingId"></$.Heading>),+ {+ parentSelector: ["boxId", "bodyId"],+ position: "after",+ }+ );+ expect($instances.get()).toEqual(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Box ws:id="boxId"></$.Box>+ <$.Heading ws:id={expect.any(String)}></$.Heading>+ </$.Body>+ ).instances+ );+ });++ test("insert fragment inside of body when configured to place after insertable", () => {+ $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);+ insertWebstudioFragmentAt(+ renderTemplate(<$.Heading ws:id="headingId"></$.Heading>),+ {+ parentSelector: ["bodyId"],+ position: "after",+ }+ );+ expect($instances.get()).toEqual(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Heading ws:id={expect.any(String)}></$.Heading>+ </$.Body>+ ).instances+ );+ });++ test("reports unresolved explicit insert target", () => {+ const toastError = vi.spyOn(toast, "error").mockImplementation(() => "");+ $instances.set(renderData(<$.Body ws:id="bodyId"></$.Body>).instances);++ expect(+ insertWebstudioFragmentAt(+ renderTemplate(<$.Heading ws:id="headingId"></$.Heading>),+ {+ parentSelector: ["missingId"],+ position: "end",+ }+ )+ ).toBe(false);++ expect(toastError).toHaveBeenCalledWith(+ "Cannot insert: the target no longer exists."+ );+ expect($instances.get()).toEqual(+ renderData(<$.Body ws:id="bodyId"></$.Body>).instances+ );+ toastError.mockRestore();+ });++ test("insert fragment into shared slot content", () => {+ $project.set({ id: "current_project" } as Project);+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );++ insertWebstudioFragmentAt(+ renderTemplate(<$.Heading ws:id="heading"></$.Heading>),+ {+ parentSelector: ["slot1", "bodyId"],+ position: "end",+ }+ );++ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ ]);+ });++ test("insert fragment into legacy shared slot content normalizes all occurrences", () => {+ $project.set({ id: "current_project" } as Project);+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Box ws:id="box"></$.Box>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Box ws:id="box"></$.Box>+ </$.Slot>+ </$.Body>+ ).instances+ );++ insertWebstudioFragmentAt(+ renderTemplate(<$.Heading ws:id="heading"></$.Heading>),+ {+ parentSelector: ["slot1", "bodyId"],+ position: "end",+ }+ );++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ ]);+ });++ test("insert fragment after shared slot child", () => {+ $project.set({ id: "current_project" } as Project);+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );++ insertWebstudioFragmentAt(+ renderTemplate(<$.Heading ws:id="heading"></$.Heading>),+ {+ parentSelector: ["box", "fragment", "slot1", "bodyId"],+ position: "after",+ }+ );++ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ ]);+ });++ test("insert fragment after nested shared slot child", () => {+ $project.set({ id: "current_project" } as Project);+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:id="div" ws:tag="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:id="div" ws:tag="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );++ insertWebstudioFragmentAt(+ renderTemplate(<$.Heading ws:id="heading"></$.Heading>),+ {+ parentSelector: ["box", "div", "fragment", "slot1", "bodyId"],+ position: "after",+ }+ );++ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect($instances.get().get("div")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ ]);+ });+});++describe("find closest insertable", () => {+ const newBoxFragment = createFragment({+ children: [{ type: "id", value: "newBoxId" }],+ instances: [+ { type: "instance", id: "newBoxId", component: "Box", children: [] },+ ],+ });++ beforeEach(() => {+ $pages.set(+ createDefaultPages({+ homePageId: "homePageId",+ rootInstanceId: "",+ })+ );+ $selectedPageId.set("homePageId");+ $selectedInstanceSelector.set([+ "collectionId[1]",+ "collectionId",+ "bodyId",+ ]);+ $registeredComponentMetas.set(defaultMetasMap);+ });++ test("returns undefined without a selected page", () => {+ $selectedPageId.set(undefined);++ expect(findClosestInsertable(newBoxFragment)).toBeUndefined();+ });++ test("puts in the end if closest instance is container", () => {+ const { instances } = renderData(+ <$.Body ws:id="bodyId">+ <$.Box ws:id="boxId">+ <$.Paragraph ws:id="paragraphId">+ <$.Bold ws:id="boldId"></$.Bold>+ </$.Paragraph>+ </$.Box>+ </$.Body>+ );+ $instances.set(instances);+ selectInstance(["boxId", "bodyId"]);+ expect(findClosestInsertable(newBoxFragment)).toEqual({+ parentSelector: ["boxId", "bodyId"],+ position: "end",+ });+ });++ test("puts in the end of root instance", () => {+ const { instances } = renderData(+ <$.Body ws:id="bodyId">+ <$.Paragraph ws:id="paragraphId"></$.Paragraph>+ </$.Body>+ );+ $instances.set(instances);+ selectInstance(["bodyId"]);+ expect(findClosestInsertable(newBoxFragment)).toEqual({+ parentSelector: ["bodyId"],+ position: "end",+ });+ });++ test("puts in the end of root instance when page root only has text", () => {+ const { instances } = renderData(<$.Body ws:id="bodyId">text</$.Body>);+ $instances.set(instances);+ selectInstance(["bodyId"]);+ expect(findClosestInsertable(newBoxFragment)).toEqual({+ parentSelector: ["bodyId"],+ position: "end",+ });+ });++ test("finds closest container and puts after its child within selection", () => {+ const { instances } = renderData(+ <$.Body ws:id="bodyId">+ <$.Paragraph ws:id="paragraphId">+ <$.Bold ws:id="boldId"></$.Bold>+ </$.Paragraph>+ </$.Body>+ );+ $instances.set(instances);+ selectInstance(["boldId", "paragraphId", "bodyId"]);+ expect(findClosestInsertable(newBoxFragment)).toEqual({+ parentSelector: ["bodyId"],+ position: 1,+ });+ });++ test("finds closest container that doesn't have an expression as a child", () => {+ const { instances } = renderData(+ <$.Body ws:id="bodyId">+ <$.Box ws:id="box1Id"></$.Box>+ <$.Paragraph ws:id="paragraphId">{expression`"bla"`}</$.Paragraph>+ <$.Box ws:id="box2Id"></$.Box>+ </$.Body>+ );+ $instances.set(instances);+ selectInstance(["paragraphId", "bodyId"]);+ expect(findClosestInsertable(newBoxFragment)).toEqual({+ parentSelector: ["bodyId"],+ position: 2,+ });+ });++ test("finds closest container without textual placeholder", () => {+ const { instances } = renderData(+ <$.Body ws:id="bodyId">+ <$.Paragraph ws:id="paragraphId"></$.Paragraph>+ </$.Body>+ );+ $instances.set(instances);+ selectInstance(["paragraphId", "bodyId"]);+ expect(findClosestInsertable(newBoxFragment)).toEqual({+ parentSelector: ["bodyId"],+ position: 1,+ });+ });++ test("finds closest container even with when parent has placeholder", () => {+ const { instances } = renderData(+ <$.Body ws:id="bodyId">+ <$.Paragraph ws:id="paragraphId">+ <$.Image ws:id="imageId"></$.Image>+ </$.Paragraph>+ </$.Body>+ );+ $instances.set(instances);+ selectInstance(["imageId", "paragraphId", "bodyId"]);+ expect(+ findClosestInsertable(renderTemplate(<$.Box ws:tag="span"></$.Box>))+ ).toEqual({+ parentSelector: ["paragraphId", "bodyId"],+ position: 1,+ });+ });++ test("forbids inserting into :root", () => {+ const { instances } = renderData(<$.Body ws:id="bodyId"></$.Body>);+ $instances.set(instances);+ selectInstance([":root"]);+ expect(findClosestInsertable(newBoxFragment)).toEqual(undefined);+ });++ test("allow inserting into collection item", () => {+ const { instances } = renderData(+ <$.Body ws:id="bodyId">+ <ws.collection ws:id="collectionId">+ <$.Box ws:id="boxId"></$.Box>+ </ws.collection>+ </$.Body>+ );+ $instances.set(instances);+ selectInstance(["collectionId[1]", "collectionId", "bodyId"]);+ expect(findClosestInsertable(newBoxFragment)).toEqual({+ parentSelector: ["collectionId", "bodyId"],+ position: "end",+ });+ });++ test("prevents inserting list item in body when validation fails", () => {+ const { instances } = renderData(<$.Body ws:id="bodyId"></$.Body>);+ $instances.set(instances);+ selectInstance(["bodyId"]);+ const newListItemFragment = renderTemplate(+ <$.ListItem ws:id="newListItemId"></$.ListItem>+ );+ expect(findClosestInsertable(newListItemFragment)).toBeUndefined();+ });+});++describe("getComponentTemplateData", () => {+ test("returns registered template data when available", () => {+ const template = createFragment({+ children: [{ type: "id", value: "template-root" }],+ instances: [+ {+ type: "instance",+ id: "template-root",+ component: "Box",+ children: [],+ },+ ],+ });+ $registeredTemplates.set(+ new Map([+ [+ "Template",+ {+ category: "general",+ order: 0,+ template,+ },+ ],+ ])+ );++ expect(getComponentTemplateData("Template")).toBe(template);+ });++ test("builds fallback fragment for component names", () => {+ $registeredTemplates.set(new Map());++ const fragment = getComponentTemplateData("Box");++ expect(fragment.children).toEqual([+ { type: "id", value: expect.any(String) },+ ]);+ expect(fragment.instances).toEqual([+ {+ type: "instance",+ id: fragment.children[0].value,+ component: "Box",+ children: [],+ },+ ]);+ });+});++test("get undefined instead of instance path when no instances found", () => {+ expect(getInstancePath(["boxId"], new Map())).toEqual(undefined);+});++describe("insertWebstudioFragmentAt with conflictResolution", () => {+ beforeEach(() => {+ $project.set({ id: "project-id" } as Project);+ });++ test("uses conflictResolution='theirs' by default (creates new token with suffix)", () => {+ // Existing project with a "primary" token (used by existing-box)+ const data = renderData(+ <$.Body ws:id="body">+ <$.Box+ ws:id="existing-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: blue;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );++ // Create fragment with token that has same name but different styles+ const fragment = renderTemplate(+ <$.Box+ ws:id="box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ `+ ),+ ]}+ ></$.Box>+ );++ setDataStores(data);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["body"]);++ // Insert without explicit conflictResolution (defaults to "theirs")+ insertWebstudioFragmentAt(fragment, {+ parentSelector: ["body"],+ position: "end",+ });++ // The existing token should still have blue color (unchanged)+ const styles = Array.from($styles.get().values());+ const styleSources = Array.from($styleSources.get().values());+ const existingToken = styleSources.find(+ (s) => s.type === "token" && s.name === "primary"+ );+ const existingTokenStyle = styles.find(+ (s) =>+ s.styleSourceId === existingToken?.id &&+ s.property === "color" &&+ s.breakpointId === "base"+ );+ expect(existingTokenStyle?.value).toEqual({+ type: "keyword",+ value: "blue",+ });++ // A new token "primary-1" should be created with red color+ const newToken = styleSources.find(+ (s) => s.type === "token" && s.name === "primary-1"+ );+ expect(newToken).toBeDefined();+ const newTokenStyle = styles.find(+ (s) =>+ s.styleSourceId === newToken?.id &&+ s.property === "color" &&+ s.breakpointId === "base"+ );+ expect(newTokenStyle?.value).toEqual({ type: "keyword", value: "red" });+ });++ test("uses conflictResolution='ours' to keep existing token styles", () => {+ // Existing project with a "primary" token (used by existing-box)+ const data = renderData(+ <$.Body ws:id="body">+ <$.Box+ ws:id="existing-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: blue;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );++ const fragment = renderTemplate(+ <$.Box+ ws:id="box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ `+ ),+ ]}+ ></$.Box>+ );++ setDataStores(data);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["body"]);++ // Insert with conflictResolution="ours" to keep existing styles+ insertWebstudioFragmentAt(+ fragment,+ {+ parentSelector: ["body"],+ position: "end",+ },+ "ours"+ );++ // The existing token should still have blue color (kept original)+ const styles = Array.from($styles.get().values());+ const styleSources = Array.from($styleSources.get().values());+ const existingToken = styleSources.find(+ (s) => s.type === "token" && s.name === "primary"+ );+ const primaryTokenStyle = styles.find(+ (s) =>+ s.styleSourceId === existingToken?.id &&+ s.property === "color" &&+ s.breakpointId === "base"+ );+ expect(primaryTokenStyle?.value).toEqual({+ type: "keyword",+ value: "blue",+ });++ // No new token should be created+ const newToken = styleSources.find(+ (s) => s.type === "token" && s.name === "primary-1"+ );+ expect(newToken).toBeUndefined();+ });++ test("uses conflictResolution='merge' to merge styles (theirs overrides)", () => {+ // Existing project with a "primary" token that has color and fontSize+ const data = renderData(+ <$.Body ws:id="body">+ <$.Box+ ws:id="existing-box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: blue;+ font-size: 16px;+ `+ ),+ ]}+ ></$.Box>+ </$.Body>+ );++ // Fragment with same "primary" token but different color and new property+ const fragment = renderTemplate(+ <$.Box+ ws:id="box"+ ws:tokens={[+ token(+ "primary",+ css`+ color: red;+ font-weight: bold;+ `+ ),+ ]}+ ></$.Box>+ );++ setDataStores(data);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["body"]);++ // Insert with conflictResolution="merge"+ insertWebstudioFragmentAt(+ fragment,+ {+ parentSelector: ["body"],+ position: "end",+ },+ "merge"+ );++ // The existing token should now have red color (overridden by fragment)+ const styles = Array.from($styles.get().values());+ const styleSources = Array.from($styleSources.get().values());+ const existingToken = styleSources.find(+ (s) => s.type === "token" && s.name === "primary"+ );+ const colorStyle = styles.find(+ (s) =>+ s.styleSourceId === existingToken?.id &&+ s.property === "color" &&+ s.breakpointId === "base"+ );+ expect(colorStyle?.value).toEqual({ type: "keyword", value: "red" });++ // fontSize should still be there (not in fragment, so kept)+ const fontSizeStyle = styles.find(+ (s) =>+ s.styleSourceId === existingToken?.id &&+ s.property === "fontSize" &&+ s.breakpointId === "base"+ );+ expect(fontSizeStyle?.value).toEqual({+ type: "unit",+ value: 16,+ unit: "px",+ });++ // fontWeight should be added from fragment+ const fontWeightStyle = styles.find(+ (s) =>+ s.styleSourceId === existingToken?.id &&+ s.property === "fontWeight" &&+ s.breakpointId === "base"+ );+ expect(fontWeightStyle?.value).toEqual({ type: "keyword", value: "bold" });++ // No new token should be created+ const newToken = styleSources.find(+ (s) => s.type === "token" && s.name === "primary-1"+ );+ expect(newToken).toBeUndefined();+ });+});diff --git a/apps/builder/app/shared/instance-utils/insert.ts b/apps/builder/app/shared/instance-utils/insert.tsnew file mode 100644index 0000000000..ec87acfdab--- /dev/null+++ b/apps/builder/app/shared/instance-utils/insert.ts@@ -0,0 +1,363 @@+// Insert utilities own deciding where newly created or pasted instance content+// should be placed. Put insert target resolution and insertion commands here,+// while fragment cloning stays in fragment.ts and existing-instance moves stay+// in mutation.ts.+import { nanoid } from "nanoid";+import { toast } from "@webstudio-is/design-system";+import {+ type Instance,+ type WebstudioData,+ type WebstudioFragment,+ ROOT_INSTANCE_ID,+ collectionComponent,+ elementComponent,+ tags,+} from "@webstudio-is/sdk";+import type { ConflictResolution } from "../token-conflict-dialog";+import {+ $registeredComponentMetas,+ $registeredTemplates,+ $selectedInstancePath,+ $selectedInstanceSelector,+ $selectedPage,+ getInstancePath,+ selectInstance,+} from "../nano-states";+import { $instances, $project, $props } from "../sync/data-stores";+import { findClosestInstanceMatchingFragment } from "../matcher";+import {+ findClosestNonTextualContainer,+ isTreeSatisfyingContentModel,+} from "../content-model";+import { findAvailableVariables } from "../data-variables";+import { getInstanceLabel } from "~/builder/shared/instance-label";+import { getSlotFragmentDropTargetMutable } from "./slot";+import {+ type DroppableTarget,+ type InstanceSelector,+ wrapEditableChildrenAroundDropTargetMutable,+} from "./tree";+import { updateWebstudioData } from "./data";+import { insertWebstudioFragmentCopy } from "./fragment";++const getExistingInsertTargetPath = (insertable: Insertable) => {+ const instancePath = getInstancePath(+ insertable.parentSelector,+ $instances.get()+ );+ if (instancePath === undefined) {+ toast.error("Cannot insert: the target no longer exists.");+ return;+ }+ return instancePath;+};++export const insertInstanceChildrenMutable = (+ data: Omit<WebstudioData, "pages">,+ children: Instance["children"],+ insertTarget: Insertable+) => {+ const dropTarget: DroppableTarget = {+ parentSelector: insertTarget.parentSelector,+ position: insertTarget.position === "after" ? "end" : insertTarget.position,+ };+ const metas = $registeredComponentMetas.get();+ let normalizedDropTarget =+ getSlotFragmentDropTargetMutable(data.instances, dropTarget) ?? dropTarget;+ normalizedDropTarget =+ wrapEditableChildrenAroundDropTargetMutable(+ data.instances,+ data.props,+ metas,+ normalizedDropTarget+ ) ?? normalizedDropTarget;+ const [parentInstanceId] = normalizedDropTarget.parentSelector;+ const parentInstance = data.instances.get(parentInstanceId);+ if (parentInstance === undefined) {+ return;+ }+ if (normalizedDropTarget.position === "end") {+ parentInstance.children.push(...children);+ } else {+ parentInstance.children.splice(+ normalizedDropTarget.position,+ 0,+ ...children+ );+ }+};++export const insertWebstudioElementAt = (insertable?: Insertable) => {+ const instances = $instances.get();+ const props = $props.get();+ const metas = $registeredComponentMetas.get();+ // find closest container and try to match new element with it+ if (insertable === undefined) {+ const instancePath = $selectedInstancePath.get();+ if (instancePath === undefined) {+ return false;+ }+ const [{ instanceSelector }] = instancePath;+ const containerSelector = findClosestNonTextualContainer({+ instances,+ props,+ metas,+ instanceSelector,+ });+ const insertableIndex = instanceSelector.length - containerSelector.length;+ if (insertableIndex === 0) {+ insertable = {+ parentSelector: containerSelector,+ position: "end",+ };+ } else {+ const containerInstance = instances.get(containerSelector[0]);+ if (containerInstance === undefined) {+ return false;+ }+ const lastChildInstanceId = instanceSelector[insertableIndex - 1];+ const lastChildPosition = containerInstance.children.findIndex(+ (child) => child.type === "id" && child.value === lastChildInstanceId+ );+ insertable = {+ parentSelector: containerSelector,+ position: lastChildPosition + 1,+ };+ }+ }+ if (getExistingInsertTargetPath(insertable) === undefined) {+ return false;+ }+ // create element and find matching tag+ const element: Instance = {+ type: "instance",+ id: nanoid(),+ component: elementComponent,+ children: [],+ };+ const newInstances = new Map(instances);+ newInstances.set(element.id, element);+ let matchingTag: undefined | string;+ for (const tag of tags) {+ element.tag = tag;+ const isSatisfying = isTreeSatisfyingContentModel({+ instances: newInstances,+ props,+ metas,+ instanceSelector: [element.id, ...insertable.parentSelector],+ });+ if (isSatisfying) {+ matchingTag = tag;+ break;+ }+ }+ if (matchingTag === undefined) {+ return false;+ }+ // insert element+ updateWebstudioData((data) => {+ data.instances.set(element.id, element);+ const children: Instance["children"] = [{ type: "id", value: element.id }];+ insertInstanceChildrenMutable(data, children, insertable);+ });+ selectInstance([element.id, ...insertable.parentSelector]);+ return true;+};++export const insertWebstudioFragmentAt = (+ fragment: WebstudioFragment,+ insertable?: Insertable,+ conflictResolution?: ConflictResolution,+ options?: { onBreakpointLimitMerge?: () => void }+): boolean => {+ const hasChildren = fragment.children.length > 0;+ const hasTokens = fragment.styleSources.length > 0;+ if (!hasChildren && !hasTokens) {+ return false;+ }+ // Tokens-only fragment: insert tokens/breakpoints/styles without instances+ if (!hasChildren && hasTokens) {+ const project = $project.get();+ if (project === undefined) {+ return false;+ }+ updateWebstudioData((data) => {+ insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: project.id,+ conflictResolution,+ onBreakpointLimitMerge: options?.onBreakpointLimitMerge,+ });+ });+ return true;+ }+ const project = $project.get();+ insertable = findClosestInsertable(fragment, insertable) ?? insertable;+ if (project === undefined || insertable === undefined) {+ return false;+ }+ const initialInstancePath = getExistingInsertTargetPath(insertable);+ if (initialInstancePath === undefined) {+ return false;+ }+ let newInstanceSelector: undefined | InstanceSelector;+ updateWebstudioData((data) => {+ const instancePath =+ getInstancePath(insertable.parentSelector, data.instances) ??+ initialInstancePath;+ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: findAvailableVariables({+ ...data,+ startingInstanceId: instancePath[0].instance.id,+ }),+ projectId: project.id,+ conflictResolution,+ onBreakpointLimitMerge: options?.onBreakpointLimitMerge,+ });+ const children: Instance["children"] = fragment.children.map((child) => {+ if (child.type === "id") {+ return {+ type: "id",+ value: newInstanceIds.get(child.value) ?? child.value,+ };+ }+ return child;+ });+ let parentSelector;+ let position: number | "end";+ if (insertable.position === "after") {+ if (instancePath.length === 1) {+ parentSelector = insertable.parentSelector;+ position = "end";+ } else {+ parentSelector = instancePath[1].instanceSelector;+ const [{ instance }, { instance: parentInstance }] = instancePath;+ const index = parentInstance.children.findIndex(+ (child) => child.type === "id" && child.value === instance.id+ );+ position = 1 + index;+ }+ } else {+ parentSelector = insertable.parentSelector;+ position = insertable.position;+ }+ insertInstanceChildrenMutable(data, children, {+ parentSelector,+ position,+ });+ newInstanceSelector = [children[0].value, ...parentSelector];+ });+ if (newInstanceSelector) {+ selectInstance(newInstanceSelector);+ }+ return true;+};++export const getComponentTemplateData = (+ componentOrTemplate: string+): WebstudioFragment => {+ const templates = $registeredTemplates.get();+ const templateMeta = templates.get(componentOrTemplate);+ if (templateMeta) {+ return templateMeta.template;+ }+ const newInstance: Instance = {+ id: nanoid(),+ type: "instance",+ component: componentOrTemplate,+ children: [],+ };+ return {+ children: [{ type: "id", value: newInstance.id }],+ instances: [newInstance],+ props: [],+ dataSources: [],+ styleSourceSelections: [],+ styleSources: [],+ styles: [],+ breakpoints: [],+ assets: [],+ resources: [],+ };+};++export type Insertable = {+ parentSelector: InstanceSelector;+ position: number | "end" | "after";+};++export const findClosestInsertable = (+ fragment: WebstudioFragment,+ from?: Insertable+): undefined | Insertable => {+ const selectedPage = $selectedPage.get();+ if (selectedPage === undefined) {+ return;+ }+ // paste to the page root if nothing is selected+ const instanceSelector = from?.parentSelector ??+ $selectedInstanceSelector.get() ?? [selectedPage.rootInstanceId];+ if (instanceSelector[0] === ROOT_INSTANCE_ID) {+ toast.error(`Cannot insert into Global root`);+ return;+ }+ const metas = $registeredComponentMetas.get();+ const instances = $instances.get();+ const props = $props.get();+ const containerSelector = findClosestNonTextualContainer({+ metas,+ props,+ instances,+ instanceSelector,+ });+ const closestContainerIndex =+ instanceSelector.length - containerSelector.length;+ if (closestContainerIndex === -1) {+ return;+ }+ let insertableIndex = findClosestInstanceMatchingFragment({+ metas,+ instances,+ props,+ instanceSelector: instanceSelector.slice(closestContainerIndex),+ fragment,+ onError: (message) => {+ const component = fragment.instances[0].component;+ const label = getInstanceLabel({ component });+ toast.warn(message || `"${label}" has no place here`);+ },+ });+ if (insertableIndex === -1) {+ return;+ }++ // adjust with container lookup+ insertableIndex = insertableIndex + closestContainerIndex;+ const parentSelector = instanceSelector.slice(insertableIndex);+ if (insertableIndex === 0) {+ return from ?? { parentSelector, position: "end" };+ }+ const instance = instances.get(instanceSelector[insertableIndex]);+ if (instance === undefined) {+ return;+ }+ // skip collection item when inserting something and go straight into collection instance+ if (instance?.component === collectionComponent && insertableIndex === 1) {+ return {+ parentSelector,+ position: "end",+ };+ }+ const lastChildInstanceId = instanceSelector[insertableIndex - 1];+ const lastChildPosition = instance.children.findIndex(+ (child) => child.type === "id" && child.value === lastChildInstanceId+ );+ return {+ parentSelector,+ position: lastChildPosition + 1,+ };+};diff --git a/apps/builder/app/shared/instance-utils/lookup.test.tsx b/apps/builder/app/shared/instance-utils/lookup.test.tsxnew file mode 100644index 0000000000..7b3b4a0ae4--- /dev/null+++ b/apps/builder/app/shared/instance-utils/lookup.test.tsx@@ -0,0 +1,226 @@+import { describe, expect, test } from "vitest";+import type { Instance, Prop, WsComponentMeta } from "@webstudio-is/sdk";+import { createDefaultPages } from "@webstudio-is/project-build";+import { $, renderData } from "@webstudio-is/template";+import {+ buildInstancePath,+ findAllEditableInstanceSelector,+ findPageAndSelectorByInstanceId,+} from "./lookup";++const instance = (+ id: string,+ component: string,+ children: Instance["children"] = []+): Instance => ({+ type: "instance",+ id,+ component,+ children,+});++const meta = (+ children: NonNullable<WsComponentMeta["contentModel"]>["children"]+): WsComponentMeta =>+ ({+ label: "",+ Icon: () => null,+ contentModel: { category: "instance", children },+ }) as WsComponentMeta;++describe("buildInstancePath", () => {+ const createPages = () =>+ createDefaultPages({+ homePageId: "homePageId",+ rootInstanceId: "rootId",+ systemDataSourceId: "systemId",+ });++ test("returns empty array when instance has no selector", () => {+ const pages = createPages();+ const instances = new Map();++ const result = buildInstancePath("nonexistent", pages, instances);+ expect(result).toEqual([]);+ });++ test("returns empty array for root instance (no ancestors)", () => {+ const { instances } = renderData(+ <$.Body ws:id="rootId">+ <$.Box ws:id="boxId"></$.Box>+ </$.Body>+ );+ const pages = createPages();++ const result = buildInstancePath("rootId", pages, instances);+ expect(result).toEqual([]);+ });++ test("builds path for single-level nesting", () => {+ const { instances } = renderData(+ <$.Body ws:id="rootId">+ <$.Box ws:id="boxId"></$.Box>+ </$.Body>+ );+ const pages = createPages();++ const result = buildInstancePath("boxId", pages, instances);+ expect(result).toEqual(["Body"]);+ });++ test("builds path for multi-level nesting", () => {+ const { instances } = renderData(+ <$.Body ws:id="rootId">+ <$.Box ws:id="containerId">+ <$.Heading ws:id="headingId"></$.Heading>+ </$.Box>+ </$.Body>+ );+ const pages = createPages();++ const result = buildInstancePath("headingId", pages, instances);+ expect(result).toEqual(["Body", "Box"]);+ });++ test("builds path for deeply nested instance", () => {+ const { instances } = renderData(+ <$.Body ws:id="rootId">+ <$.Box ws:id="sectionId">+ <$.Box ws:id="articleId">+ <$.Box ws:id="divId">+ <$.Text ws:id="textId"></$.Text>+ </$.Box>+ </$.Box>+ </$.Box>+ </$.Body>+ );+ const pages = createPages();++ const result = buildInstancePath("textId", pages, instances);+ expect(result).toEqual(["Body", "Box", "Box", "Box"]);+ });++ test("handles instances with custom labels", () => {+ const { instances } = renderData(+ <$.Body ws:id="rootId" ws:label="Main Body">+ <$.Box ws:id="navId" ws:label="Navigation">+ <$.Link ws:id="linkId" ws:label="Home Link"></$.Link>+ </$.Box>+ </$.Body>+ );+ const pages = createPages();++ const result = buildInstancePath("linkId", pages, instances);+ expect(result).toEqual(["Main Body", "Navigation"]);+ });+});++describe("findPageAndSelectorByInstanceId", () => {+ test("returns page id and selector for instances in nested pages", () => {+ const pages = createDefaultPages({+ homePageId: "homePageId",+ rootInstanceId: "homeRoot",+ });+ pages.pages.set("nestedPageId", {+ id: "nestedPageId",+ name: "Nested",+ path: "/nested",+ rootInstanceId: "nestedRoot",+ title: "",+ meta: {},+ });+ const instances = new Map([+ [+ "homeRoot",+ instance("homeRoot", "Body", [{ type: "id", value: "homeChild" }]),+ ],+ ["homeChild", instance("homeChild", "Box")],+ [+ "nestedRoot",+ instance("nestedRoot", "Body", [{ type: "id", value: "nestedChild" }]),+ ],+ ["nestedChild", instance("nestedChild", "Box")],+ ]);++ expect(+ findPageAndSelectorByInstanceId(pages, instances, "nestedChild")+ ).toEqual({+ pageId: "nestedPageId",+ instanceSelector: ["nestedChild", "nestedRoot"],+ });+ });++ test("falls back to home page when selector root is not a page root", () => {+ const pages = createDefaultPages({+ homePageId: "homePageId",+ rootInstanceId: "homeRoot",+ });+ const instances = new Map([+ ["orphanRoot", instance("orphanRoot", "Body")],+ [+ "orphanChild",+ instance("orphanChild", "Box", [{ type: "id", value: "target" }]),+ ],+ ["target", instance("target", "Box")],+ ]);++ expect(findPageAndSelectorByInstanceId(pages, instances, "target")).toEqual(+ {+ pageId: "homePageId",+ instanceSelector: ["target", "orphanChild"],+ }+ );+ });++ test("uses the last matching parent for shared slot content paths", () => {+ const pages = createDefaultPages({+ homePageId: "homePageId",+ rootInstanceId: "body",+ });+ const instances = new Map([+ [+ "body",+ instance("body", "Body", [+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]),+ ],+ ["slot1", instance("slot1", "Slot", [{ type: "id", value: "fragment" }])],+ ["slot2", instance("slot2", "Slot", [{ type: "id", value: "fragment" }])],+ [+ "fragment",+ instance("fragment", "Fragment", [{ type: "id", value: "box" }]),+ ],+ ["box", instance("box", "Box")],+ ]);++ expect(findPageAndSelectorByInstanceId(pages, instances, "box")).toEqual({+ pageId: "homePageId",+ instanceSelector: ["box", "fragment", "slot2", "body"],+ });+ });+});++describe("findAllEditableInstanceSelector", () => {+ test("collects editable rich-text descendants", () => {+ const results: string[][] = [];+ findAllEditableInstanceSelector({+ instanceSelector: ["body"],+ instances: new Map([+ [+ "body",+ instance("body", "Body", [{ type: "id", value: "paragraph" }]),+ ],+ ["paragraph", instance("paragraph", "Paragraph")],+ ]),+ props: new Map<string, Prop>(),+ metas: new Map([+ ["Body", meta(["instance"])],+ ["Paragraph", meta(["rich-text"])],+ ]),+ results,+ });++ expect(results).toEqual([["paragraph", "body"]]);+ });+});diff --git a/apps/builder/app/shared/instance-utils/lookup.ts b/apps/builder/app/shared/instance-utils/lookup.tsnew file mode 100644index 0000000000..ae19cd63f6--- /dev/null+++ b/apps/builder/app/shared/instance-utils/lookup.ts@@ -0,0 +1,133 @@+// Lookup utilities answer read-only questions about instance ancestry and+// selection paths. Put path building and cross-page instance discovery here,+// not mutations or store transactions.+import type {+ Instance,+ Instances,+ Pages,+ Props,+ WsComponentMeta,+} from "@webstudio-is/sdk";+import { getAllPages } from "@webstudio-is/sdk";+import { getInstanceLabel } from "~/builder/shared/instance-label";+import { isRichTextTree } from "../content-model";+import { getInstancePath } from "../nano-states";+import type { InstanceSelector } from "./tree";++/**+ * Build the ancestor path array for an instance.+ * Returns an array of labels for all ancestors from root to parent.+ */+export const buildInstancePath = (+ instanceId: Instance["id"],+ pages: Pages,+ instances: Instances+): string[] => {+ const awareness = findPageAndSelectorByInstanceId(+ pages,+ instances,+ instanceId+ );+ if (!awareness.instanceSelector) {+ return [];+ }++ const instancePath = getInstancePath(+ awareness.instanceSelector,+ instances,+ undefined,+ undefined+ );++ if (!instancePath) {+ return [];+ }++ return instancePath+ .slice()+ .reverse()+ .slice(0, -1)+ .map(({ instance }) => getInstanceLabel(instance));+};++const parentInstanceByIdCache = new WeakMap<+ Instances,+ Map<Instance["id"], Instance["id"]>+>();++/**+ * Traverse the instance tree up to the root to find the page and full instance+ * selector for a given instance id. When an instance appears via a slot,+ * the last matching parent is used.+ */+export const findPageAndSelectorByInstanceId = (+ pages: Pages,+ instances: Instances,+ startingInstanceId: Instance["id"]+): { pageId: string; instanceSelector: string[] } => {+ let parentInstanceById = parentInstanceByIdCache.get(instances);+ if (parentInstanceById === undefined) {+ parentInstanceById = new Map<Instance["id"], Instance["id"]>();+ for (const instance of instances.values()) {+ for (const child of instance.children) {+ if (child.type === "id") {+ parentInstanceById.set(child.value, instance.id);+ }+ }+ }+ parentInstanceByIdCache.set(instances, parentInstanceById);+ }+ const instanceSelector: string[] = [];+ let currentInstanceId: undefined | Instance["id"] = startingInstanceId;+ while (currentInstanceId) {+ instanceSelector.push(currentInstanceId);+ currentInstanceId = parentInstanceById.get(currentInstanceId);+ }+ const rootInstanceId = instanceSelector.at(-1);+ for (const page of getAllPages(pages)) {+ if (page.rootInstanceId === rootInstanceId) {+ return { pageId: page.id, instanceSelector };+ }+ }+ return { pageId: pages.homePageId, instanceSelector };+};++export const findAllEditableInstanceSelector = ({+ instanceSelector,+ instances,+ props,+ metas,+ results,+}: {+ instanceSelector: InstanceSelector;+ instances: Instances;+ props: Props;+ metas: Map<string, WsComponentMeta>;+ results: InstanceSelector[];+}) => {+ const [instanceId] = instanceSelector;++ if (instanceId === undefined) {+ return;+ }++ if (isRichTextTree({ instanceId, instances, props, metas })) {+ results.push(instanceSelector);+ return;+ }++ const instance = instances.get(instanceId);+ if (instance) {+ for (const child of instance.children) {+ if (child.type === "id") {+ findAllEditableInstanceSelector({+ instanceSelector: [child.value, ...instanceSelector],+ instances,+ props,+ metas,+ results,+ });+ }+ }+ }+};diff --git a/apps/builder/app/shared/instance-utils/mutation.test.tsx b/apps/builder/app/shared/instance-utils/mutation.test.tsxnew file mode 100644index 0000000000..e0c69f6f9f--- /dev/null+++ b/apps/builder/app/shared/instance-utils/mutation.test.tsx@@ -0,0 +1,4193 @@+import {+ detachSharedSlotChildrenMutable,+ detachSharedSlotContentMutable,+ reparentInstance,+ wrapInstance,+ toggleInstanceShow,+ unwrapInstance,+ unwrapInstanceMutable,+ canUnwrapInstance,+ canConvertInstance,+ convertInstance,+ setInstanceLabelMutable,+} from "./mutation";+import { reparentInstanceMutable, deleteSelectedInstance } from "./mutation";+import { enableMapSet } from "immer";+import { describe, test, expect, beforeEach } from "vitest";+import type { Project } from "@webstudio-is/project";+import { createDefaultPages } from "@webstudio-is/project-build";+import {+ $,+ ws,+ expression,+ renderData,+ ResourceValue,+} from "@webstudio-is/template";+import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";+import * as radixMetas from "@webstudio-is/sdk-components-react-radix/metas";+import type {+ DataSource,+ Instance,+ Prop,+ Resource,+ StyleDecl,+ WebstudioData,+ WsComponentMeta,+} from "@webstudio-is/sdk";+import {+ coreMetas,+ getStyleDeclKey,+ elementComponent,+} from "@webstudio-is/sdk";+import { showAttribute } from "@webstudio-is/react-sdk";+import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";+import { deleteInstanceMutable } from "./mutation";+import type { InstancePath } from "../nano-states";+import { $registeredComponentMetas } from "../nano-states";+import {+ $instances,+ $pages,+ $project,+ $props,+} from "~/shared/sync/data-stores";+import { registerContainers } from "../sync/sync-stores";+import { $selectedInstanceSelector, getInstancePath } from "../nano-states";+import { selectInstance } from "../nano-states";+import { $selectedPageId } from "../nano-states/pages";+import {+ expectSlotTreeIntegrity,+ expectSlotsShareFragment,+ getSlotFragmentId,+} from "../slot-test-utils";+import type { DroppableTarget, InstanceSelector } from "./tree";++enableMapSet();+registerContainers();++$pages.set(createDefaultPages({ rootInstanceId: "" }));++const defaultMetasMap = new Map(+ Object.entries({ ...defaultMetas, ...coreMetas })+);+$registeredComponentMetas.set(defaultMetasMap);++const createFakeComponentMetas = (+ itemMeta: Partial<WsComponentMeta>,+ anotherItemMeta?: Partial<WsComponentMeta>+): Map<string, WsComponentMeta> => {+ const base = {+ label: "",+ Icon: () => null,+ };+ const configs = {+ Item: { ...base, ...itemMeta },+ AnotherItem: { ...base, ...anotherItemMeta },+ Bold: base,+ Text: base,+ Form: base,+ Box: base,+ Div: base,+ Body: base,+ } as const;+ return new Map(Object.entries(configs)) as Map<string, WsComponentMeta>;+};++const createInstance = (+ id: Instance["id"],+ component: string,+ children: Instance["children"]+): Instance => {+ return { type: "instance", id, component, children };+};++const createStyleDecl = (+ styleSourceId: string,+ breakpointId: string,+ property: StyleProperty,+ value: StyleValue | string+): StyleDecl => ({+ styleSourceId,+ breakpointId,+ property,+ value: typeof value === "string" ? { type: "unparsed", value } : value,+});++describe("reparent instance", () => {+ beforeEach(() => {+ $project.set({ id: "projectId" } as Project);+ });++ test("between instances", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box">+ <$.Text ws:id="text"></$.Text>+ </$.Box>+ <$.Button ws:id="button"></$.Button>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));+ reparentInstanceMutable(data, ["text", "box", "body"], {+ parentSelector: ["body"],+ position: 1,+ });+ const newTextId = data.instances.get("body")?.children[1].value as string;+ expect(data.instances).toEqual(+ renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box"></$.Box>+ <$.Text ws:id={newTextId}></$.Text>+ <$.Button ws:id="button"></$.Button>+ </$.Body>+ ).instances+ );+ });++ test("to the end", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box">+ <$.Text ws:id="text"></$.Text>+ </$.Box>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));+ reparentInstanceMutable(data, ["text", "box", "body"], {+ parentSelector: ["body"],+ position: "end",+ });+ const newTextId = data.instances.get("body")?.children[1].value as string;+ expect(data.instances).toEqual(+ renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box"></$.Box>+ <$.Text ws:id={newTextId}></$.Text>+ </$.Body>+ ).instances+ );+ });++ test("reparentInstance wrapper updates stores and selection", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="source"></$.Box>+ <$.Box ws:id="target"></$.Box>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $pages.set(createDefaultPages({ rootInstanceId: "body" }));+ $instances.set(data.instances);+ $props.set(data.props);++ reparentInstance(["source", "body"], {+ parentSelector: ["target", "body"],+ position: "end",+ });++ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "target" },+ ]);+ expect($instances.get().get("target")?.children).toEqual([+ { type: "id", value: "source" },+ ]);+ expect($selectedInstanceSelector.get()).toEqual([+ "source",+ "target",+ "body",+ ]);+ });++ test("before itself", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Text ws:id="text"></$.Text>+ <$.Box ws:id="box"></$.Box>+ <$.Button ws:id="button"></$.Button>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));+ reparentInstanceMutable(data, ["box", "body"], {+ parentSelector: ["body"],+ position: 1,+ });+ expect(data.instances).toEqual(+ renderData(+ <$.Body ws:id="body">+ <$.Text ws:id="text"></$.Text>+ <$.Box ws:id="box"></$.Box>+ <$.Button ws:id="button"></$.Button>+ </$.Body>+ ).instances+ );+ });++ test("after itself", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Text ws:id="text"></$.Text>+ <$.Box ws:id="box"></$.Box>+ <$.Button ws:id="button"></$.Button>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));+ reparentInstanceMutable(data, ["box", "body"], {+ parentSelector: ["body"],+ position: 2,+ });+ expect(data.instances).toEqual(+ renderData(+ <$.Body ws:id="body">+ <$.Text ws:id="text"></$.Text>+ <$.Box ws:id="box"></$.Box>+ <$.Button ws:id="button"></$.Button>+ </$.Body>+ ).instances+ );+ });++ test("wrap with fragment when reparent into empty slot", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot"></$.Slot>+ <$.Box ws:id="box"></$.Box>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));+ reparentInstanceMutable(data, ["box", "body"], {+ parentSelector: ["slot", "body"],+ position: "end",+ });+ const newFragmentId = data.instances.get("slot")?.children[0]+ .value as string;+ expect(data.instances).toEqual(+ renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot">+ <$.Fragment ws:id={newFragmentId}>+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );+ });++ test("reuse existing fragment when reparent into slot", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot">+ <$.Fragment ws:id="fragment"></$.Fragment>+ </$.Slot>+ <$.Box ws:id="box"></$.Box>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));+ reparentInstanceMutable(data, ["box", "body"], {+ parentSelector: ["slot", "body"],+ position: "end",+ });+ expect(data.instances).toEqual(+ renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );+ });++ test("reparent into legacy slot with direct children wraps content in fragment", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot">+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Box ws:id="box"></$.Box>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["box", "body"], {+ parentSelector: ["slot", "body"],+ position: "end",+ });++ const fragmentId = data.instances.get("slot")?.children[0]?.value;+ expect(fragmentId).toEqual(expect.any(String));+ expect(data.instances).toEqual(+ renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot">+ <$.Fragment ws:id={fragmentId}>+ <$.Heading ws:id="heading"></$.Heading>+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );+ });++ test("reparent into legacy shared slot content normalizes all occurrences", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Box ws:id="box"></$.Box>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["box", "body"], {+ parentSelector: ["slot1", "body"],+ position: "end",+ });++ const fragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect(data.instances.get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ { type: "id", value: "box" },+ ]);+ });++ test("reparent into empty legacy shared slot content normalizes all occurrences", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1"></$.Slot>+ <$.Slot ws:id="slot2"></$.Slot>+ <$.Box ws:id="box"></$.Box>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["box", "body"], {+ parentSelector: ["slot1", "body"],+ position: "end",+ });++ const fragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ expect(data.instances.get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ });++ test("reparent into legacy shared slot content preserves text and expression children", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1"></$.Slot>+ <$.Slot ws:id="slot2"></$.Slot>+ <$.Box ws:id="box"></$.Box>+ </$.Body>+ );+ data.instances.set(+ "slot1",+ createInstance("slot1", "Slot", [+ { type: "text", value: "Text child" },+ { type: "expression", value: "expressionChild" },+ { type: "id", value: "heading" },+ ])+ );+ data.instances.set(+ "slot2",+ createInstance("slot2", "Slot", [+ { type: "text", value: "Text child" },+ { type: "expression", value: "expressionChild" },+ { type: "id", value: "heading" },+ ])+ );+ data.instances.set("heading", createInstance("heading", "Heading", []));+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["box", "body"], {+ parentSelector: ["slot1", "body"],+ position: "end",+ });++ const fragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ const textWrapperId = data.instances.get(fragmentId ?? "")?.children[0]+ ?.value;+ expect(data.instances.get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: textWrapperId },+ { type: "id", value: "box" },+ ]);+ expect(data.instances.get(textWrapperId ?? "")?.children).toEqual([+ { type: "text", value: "Text child" },+ { type: "expression", value: "expressionChild" },+ { type: "id", value: "heading" },+ ]);+ });++ test("reparent into legacy slot does not normalize unrelated overlapping slot", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Slot ws:id="slot2">+ <$.Box ws:id="box"></$.Box>+ </$.Slot>+ <$.Text ws:id="text"></$.Text>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["text", "body"], {+ parentSelector: ["slot1", "body"],+ position: "end",+ });++ const fragmentId = getSlotFragmentId(data.instances, "slot1");+ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect(data.instances.get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ { type: "id", value: "text" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ });++ test("sort legacy shared slot content through visible slot drop target", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Box ws:id="box1"></$.Box>+ <$.Box ws:id="box2"></$.Box>+ <$.Box ws:id="box3"></$.Box>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Box ws:id="box1"></$.Box>+ <$.Box ws:id="box2"></$.Box>+ <$.Box ws:id="box3"></$.Box>+ </$.Slot>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["box1", "slot1", "body"], {+ parentSelector: ["slot2", "body"],+ position: 3,+ });++ const fragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect(data.instances.get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box2" },+ { type: "id", value: "box3" },+ { type: "id", value: "box1" },+ ]);+ });++ test("reparent legacy shared slot child outside removes it from all slot occurrences", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["box", "slot1", "body"], {+ parentSelector: ["body"],+ position: "end",+ });++ const fragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ const bodyChildId = data.instances.get("body")?.children.at(-1)?.value;+ expect(data.instances.get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ expect(bodyChildId).toBe("box");+ });++ test("reparent legacy shared slot child into another slot updates both shared slots", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="sourceSlot1">+ <$.Box ws:id="box"></$.Box>+ <$.Text ws:id="text"></$.Text>+ </$.Slot>+ <$.Slot ws:id="sourceSlot2">+ {/* same ids */}+ <$.Box ws:id="box"></$.Box>+ <$.Text ws:id="text"></$.Text>+ </$.Slot>+ <$.Slot ws:id="targetSlot1">+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Slot ws:id="targetSlot2">+ {/* same ids */}+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["box", "sourceSlot1", "body"], {+ parentSelector: ["targetSlot1", "body"],+ position: "end",+ });++ const sourceSlot1FragmentId =+ data.instances.get("sourceSlot1")?.children[0]?.value;+ const sourceSlot2FragmentId =+ data.instances.get("sourceSlot2")?.children[0]?.value;+ const targetFragmentId =+ data.instances.get("targetSlot1")?.children[0]?.value;+ const movedBoxId = data.instances.get(targetFragmentId ?? "")?.children[1]+ ?.value;+ expect(sourceSlot1FragmentId).toBe(sourceSlot2FragmentId);+ expect(data.instances.get(sourceSlot1FragmentId ?? "")?.children).toEqual([+ { type: "id", value: "text" },+ ]);+ expect(data.instances.get("targetSlot1")?.children).toEqual([+ { type: "id", value: targetFragmentId },+ ]);+ expect(data.instances.get("targetSlot2")?.children).toEqual([+ { type: "id", value: targetFragmentId },+ ]);+ expect(data.instances.get(targetFragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ { type: "id", value: "box" },+ ]);+ expect(movedBoxId).toBe("box");+ });++ test("reparent slot child from one instance of this slot into another", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));+ reparentInstanceMutable(data, ["box", "fragment", "slot1", "body"], {+ parentSelector: ["slot2", "body"],+ position: "end",+ });+ expect(data.instances).toEqual(+ renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );+ });++ test("sort shared slot content through visible slot drop target", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box1"></$.Box>+ <$.Box ws:id="box2"></$.Box>+ <$.Box ws:id="box3"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box1"></$.Box>+ <$.Box ws:id="box2"></$.Box>+ <$.Box ws:id="box3"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["box1", "fragment", "slot1", "body"], {+ parentSelector: ["slot2", "body"],+ position: 3,+ });++ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "box2" },+ { type: "id", value: "box3" },+ { type: "id", value: "box1" },+ ]);+ });++ test("reparent shared slot child into sibling in shared slot content", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["heading", "fragment", "slot1", "body"], {+ parentSelector: ["div", "fragment", "slot1", "body"],+ position: "end",+ });++ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect(data.instances.get("div")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ });++ test("reparent nested shared slot child within shared slot content", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Heading ws:id="heading"></$.Heading>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Heading ws:id="heading"></$.Heading>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(+ data,+ ["heading", "div", "fragment", "slot1", "body"],+ {+ parentSelector: ["fragment", "slot1", "body"],+ position: "end",+ }+ );++ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ { type: "id", value: "heading" },+ ]);+ expect(data.instances.get("div")?.children).toEqual([]);+ });++ test("reparent normal child into slot makes it shared slot content", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box"></$.Box>+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["box", "body"], {+ parentSelector: ["slot1", "body"],+ position: "end",+ });++ expect(data.instances.get("body")?.children).toEqual([+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]);+ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "heading" },+ { type: "id", value: "box" },+ ]);+ });++ test("reparent normal child into nested shared slot container makes it shared", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box"></$.Box>+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["box", "body"], {+ parentSelector: ["div", "fragment", "slot1", "body"],+ position: "end",+ });++ expect(data.instances.get("body")?.children).toEqual([+ { type: "id", value: "slot1" },+ { type: "id", value: "slot2" },+ ]);+ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect(data.instances.get("div")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ });++ test("reparent child from one slot into another updates both shared slot contents", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="sourceSlot1">+ <$.Fragment ws:id="sourceFragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="sourceSlot2">+ {/* same ids */}+ <$.Fragment ws:id="sourceFragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="targetSlot1">+ <$.Fragment ws:id="targetFragment">+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="targetSlot2">+ {/* same ids */}+ <$.Fragment ws:id="targetFragment">+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(+ data,+ ["box", "sourceFragment", "sourceSlot1", "body"],+ {+ parentSelector: ["targetSlot1", "body"],+ position: "end",+ }+ );++ expect(data.instances.get("sourceSlot1")?.children).toEqual([+ { type: "id", value: "sourceFragment" },+ ]);+ expect(data.instances.get("sourceSlot2")?.children).toEqual([+ { type: "id", value: "sourceFragment" },+ ]);+ expect(data.instances.get("sourceFragment")?.children).toEqual([]);+ expect(data.instances.get("targetSlot1")?.children).toEqual([+ { type: "id", value: "targetFragment" },+ ]);+ expect(data.instances.get("targetSlot2")?.children).toEqual([+ { type: "id", value: "targetFragment" },+ ]);+ expect(data.instances.get("targetFragment")?.children).toEqual([+ { type: "id", value: "heading" },+ { type: "id", value: "box" },+ ]);+ });++ test("reparent child from one slot into nested container in another slot", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="sourceSlot1">+ <$.Fragment ws:id="sourceFragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="sourceSlot2">+ {/* same ids */}+ <$.Fragment ws:id="sourceFragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="targetSlot1">+ <$.Fragment ws:id="targetFragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="targetSlot2">+ {/* same ids */}+ <$.Fragment ws:id="targetFragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(+ data,+ ["box", "sourceFragment", "sourceSlot1", "body"],+ {+ parentSelector: ["div", "targetFragment", "targetSlot1", "body"],+ position: "end",+ }+ );++ const movedBoxId = data.instances.get("div")?.children[0]?.value;+ expect(data.instances.get("sourceSlot1")?.children).toEqual([+ { type: "id", value: "sourceFragment" },+ ]);+ expect(data.instances.get("sourceSlot2")?.children).toEqual([+ { type: "id", value: "sourceFragment" },+ ]);+ expect(data.instances.get("sourceFragment")?.children).toEqual([]);+ expect(data.instances.get("targetSlot1")?.children).toEqual([+ { type: "id", value: "targetFragment" },+ ]);+ expect(data.instances.get("targetSlot2")?.children).toEqual([+ { type: "id", value: "targetFragment" },+ ]);+ expect(movedBoxId).toBe("box");+ expect(data.instances.get("div")?.children).toEqual([+ { type: "id", value: movedBoxId },+ ]);+ });++ test("reparent child from one slot into another preserves source siblings", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="sourceSlot1">+ <$.Fragment ws:id="sourceFragment">+ <$.Box ws:id="box"></$.Box>+ <$.Text ws:id="text"></$.Text>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="sourceSlot2">+ {/* same ids */}+ <$.Fragment ws:id="sourceFragment">+ <$.Box ws:id="box"></$.Box>+ <$.Text ws:id="text"></$.Text>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="targetSlot1">+ <$.Fragment ws:id="targetFragment">+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="targetSlot2">+ {/* same ids */}+ <$.Fragment ws:id="targetFragment">+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(+ data,+ ["box", "sourceFragment", "sourceSlot1", "body"],+ {+ parentSelector: ["targetSlot1", "body"],+ position: "end",+ }+ );++ const sourceSlot1FragmentId =+ data.instances.get("sourceSlot1")?.children[0]?.value;+ expect(sourceSlot1FragmentId).toBe("sourceFragment");+ expect(data.instances.get(sourceSlot1FragmentId ?? "")?.children).toEqual([+ { type: "id", value: "text" },+ ]);+ expect(data.instances.get("sourceSlot2")?.children).toEqual([+ { type: "id", value: "sourceFragment" },+ ]);+ expect(data.instances.get("sourceFragment")?.children).toEqual([+ { type: "id", value: "text" },+ ]);+ expect(data.instances.get("targetSlot1")?.children).toEqual([+ { type: "id", value: "targetFragment" },+ ]);+ expect(data.instances.get("targetSlot2")?.children).toEqual([+ { type: "id", value: "targetFragment" },+ ]);+ expect(data.instances.get("targetFragment")?.children).toEqual([+ { type: "id", value: "heading" },+ { type: "id", value: "box" },+ ]);+ });++ test("reparent slot operation matrix preserves sharing and detach invariants", () => {+ const random = (() => {+ let seed = 1;+ return () => {+ seed = (seed * 16807) % 2147483647;+ return seed / 2147483647;+ };+ })();+ const operations: Array<+ () => {+ data: Omit<WebstudioData, "pages">;+ sourceSelector: InstanceSelector;+ dropTarget: DroppableTarget;+ assert: (data: Omit<WebstudioData, "pages">) => void;+ }+ > = [+ () => ({+ data: renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box1"></$.Box>+ <$.Box ws:id="box2"></$.Box>+ <$.Box ws:id="box3"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box1"></$.Box>+ <$.Box ws:id="box2"></$.Box>+ <$.Box ws:id="box3"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ),+ sourceSelector: ["box1", "fragment", "slot1", "body"],+ dropTarget: {+ parentSelector: ["slot2", "body"],+ position: 3,+ },+ assert: (data) => {+ const fragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ expect(data.instances.get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box2" },+ { type: "id", value: "box3" },+ { type: "id", value: "box1" },+ ]);+ },+ }),+ () => ({+ data: renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Box ws:id="box1"></$.Box>+ <$.Box ws:id="box2"></$.Box>+ <$.Box ws:id="box3"></$.Box>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Box ws:id="box1"></$.Box>+ <$.Box ws:id="box2"></$.Box>+ <$.Box ws:id="box3"></$.Box>+ </$.Slot>+ </$.Body>+ ),+ sourceSelector: ["box1", "slot1", "body"],+ dropTarget: {+ parentSelector: ["slot2", "body"],+ position: 3,+ },+ assert: (data) => {+ const fragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ expect(data.instances.get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box2" },+ { type: "id", value: "box3" },+ { type: "id", value: "box1" },+ ]);+ },+ }),+ () => ({+ data: renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box"></$.Box>+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ),+ sourceSelector: ["box", "body"],+ dropTarget: {+ parentSelector: ["div", "fragment", "slot1", "body"],+ position: "end",+ },+ assert: (data) => {+ expectSlotsShareFragment(data.instances, ["slot1", "slot2"]);+ expect(data.instances.get("div")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ },+ }),+ () => ({+ data: renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ),+ sourceSelector: ["box", "fragment", "slot1", "body"],+ dropTarget: {+ parentSelector: ["body"],+ position: "end",+ },+ assert: (data) => {+ const fragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ const movedBoxId = data.instances.get("body")?.children.at(-1)?.value;+ expect(data.instances.get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ expect(movedBoxId).toBe("box");+ },+ }),+ ];++ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));+ for (let index = 0; index < 20; index += 1) {+ const operation = operations[Math.floor(random() * operations.length)]();+ reparentInstanceMutable(+ operation.data,+ operation.sourceSelector,+ operation.dropTarget+ );+ operation.assert(operation.data);+ expectSlotTreeIntegrity(operation.data.instances);+ }+ });++ test("slot operation sequence preserves integrity after normalize, reparent out, and delete", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same visible content in legacy direct-child shape */}+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Box ws:id="outside"></$.Box>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["heading", "slot2", "body"], {+ parentSelector: ["slot2", "body"],+ position: 0,+ });++ const sharedFragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ expect(data.instances.get(sharedFragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ { type: "id", value: "box" },+ ]);+ expectSlotTreeIntegrity(data.instances);++ const movedSelector = reparentInstanceMutable(+ data,+ ["box", "fragment", "slot2", "body"],+ {+ parentSelector: ["outside", "body"],+ position: "end",+ }+ );++ expect(movedSelector).toEqual(expect.any(Array));+ expectSlotTreeIntegrity(data.instances, {+ selectedInstanceSelector: movedSelector,+ });+ const fragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ expect(data.instances.get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);++ const movedId = data.instances.get("outside")?.children[0]?.value;+ expect(movedId).toBe(movedSelector?.[0]);+ deleteInstanceMutable(+ data,+ getInstancePath([movedId ?? "", "outside", "body"], data.instances)+ );++ expectSlotTreeIntegrity(data.instances);+ expect(data.instances.get("outside")?.children).toEqual([]);+ });++ test("reparent nested shared slot child outside removes it from all slot occurrences", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["box", "div", "fragment", "slot1", "body"], {+ parentSelector: ["body"],+ position: "end",+ });++ const fragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ const slot1DivId = data.instances.get(fragmentId ?? "")?.children[0]?.value;+ const bodyChildId = data.instances.get("body")?.children.at(-1)?.value;++ expect(fragmentId).toBe("fragment");+ expect(data.instances.get(slot1DivId ?? "")?.children).toEqual([]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect(data.instances.get("div")?.children).toEqual([]);+ expect(bodyChildId).toBe("box");+ });++ test("reparent shared slot child outside preserves moved scoped data and resources", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="card">+ <$.Box ws:id="label"></$.Box>+ </ws.element>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="card">+ <$.Box ws:id="label"></$.Box>+ </ws.element>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ data.dataSources.set("cardVariable", {+ id: "cardVariable",+ scopeInstanceId: "card",+ type: "variable",+ name: "Card Variable",+ value: { type: "string", value: "value" },+ });+ data.props.set("labelProp", {+ id: "labelProp",+ instanceId: "label",+ name: "children",+ type: "expression",+ value: "$ws$dataSource$cardVariable",+ });+ data.props.set("cardResourceProp", {+ id: "cardResourceProp",+ instanceId: "card",+ name: "resource",+ type: "resource",+ value: "cardResource",+ });+ data.resources.set("cardResource", {+ id: "cardResource",+ name: "Card Resource",+ method: "get",+ url: "$ws$dataSource$cardVariable",+ headers: [+ {+ name: "authorization",+ value: "$ws$dataSource$cardVariable",+ },+ ],+ searchParams: [+ {+ name: "query",+ value: "$ws$dataSource$cardVariable",+ },+ ],+ });+ const style = createStyleDecl("cardStyle", "base", "color", "red");+ data.breakpoints.set("base", { id: "base", label: "Base" });+ data.styleSources.set("cardStyle", { id: "cardStyle", type: "local" });+ data.styleSourceSelections.set("card", {+ instanceId: "card",+ values: ["cardStyle"],+ });+ data.styles.set(getStyleDeclKey(style), style);+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["card", "fragment", "slot1", "body"], {+ parentSelector: ["body"],+ position: "end",+ });++ const slotFragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ const movedCardId = data.instances.get("body")?.children.at(-1)?.value;+ const movedLabelId =+ movedCardId === undefined+ ? undefined+ : data.instances.get(movedCardId)?.children[0]?.value;+ const movedCardVariable = Array.from(data.dataSources.values()).find(+ (dataSource) => dataSource.scopeInstanceId === movedCardId+ );+ const movedCardResourceId = Array.from(data.props.values()).find(+ (prop) => prop.instanceId === movedCardId && prop.type === "resource"+ )?.value;+ const movedCardResource =+ typeof movedCardResourceId !== "string"+ ? undefined+ : data.resources.get(movedCardResourceId);+ expect(movedCardVariable).toBeDefined();+ const movedCardVariableExpression = "$ws$dataSource$cardVariable";+ expect(slotFragmentId).toBe("fragment");+ expect(data.instances.get(slotFragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ expect(movedCardId).toBe("card");+ expect(movedLabelId).toBe("label");+ expect(movedCardVariable?.id).toBe("cardVariable");+ expect(+ Array.from(data.props.values()).find(+ (prop) => prop.instanceId === movedLabelId && prop.type === "expression"+ )?.value+ ).toBe(movedCardVariableExpression);+ expect(movedCardResourceId).toBe("cardResource");+ expect(movedCardResource?.url).toBe(movedCardVariableExpression);+ expect(movedCardResource?.headers).toEqual([+ {+ name: "authorization",+ value: movedCardVariableExpression,+ },+ ]);+ expect(movedCardResource?.searchParams).toEqual([+ {+ name: "query",+ value: movedCardVariableExpression,+ },+ ]);+ expect(data.styleSourceSelections.get(movedCardId ?? "")?.values).toEqual([+ "cardStyle",+ ]);+ expect(data.styles.size).toBe(1);+ });++ test("reparent shared slot child outside removes it from all slots and preserves siblings", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["box", "fragment", "slot1", "body"], {+ parentSelector: ["body"],+ position: "end",+ });++ const slotFragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ const bodyChildId = data.instances.get("body")?.children.at(-1)?.value;++ expect(slotFragmentId).toBe("fragment");+ expect(data.instances.get(slotFragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ expect(bodyChildId).toBe("box");+ });++ test("reparent direct slot child outside updates all linked slot occurrences", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["div", "fragment", "slot1", "body"], {+ parentSelector: ["body"],+ position: "end",+ });++ const fragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ expect(data.instances.get(fragmentId ?? "")?.children).toEqual([]);+ expect(data.instances.get("body")?.children.at(-1)?.type).toBe("id");+ expect(data.instances.get("body")?.children.at(-1)?.value).toBe("div");+ });++ test("prevent slot reparenting into own children to avoid infinite loop", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot">+ <$.Fragment ws:id="fragment"></$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));+ reparentInstanceMutable(data, ["slot", "body"], {+ parentSelector: ["fragment", "slot", "body"],+ position: "end",+ });+ expect(data.instances).toEqual(+ renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot">+ <$.Fragment ws:id="fragment"></$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );+ });++ test("from collection item", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <ws.collection ws:id="collection">+ <$.Box ws:id="box"></$.Box>+ </ws.collection>+ </$.Body>+ );+ $registeredComponentMetas.set(createFakeComponentMetas({}));+ reparentInstanceMutable(+ data,+ ["box", "collection[0]", "collection", "body"],+ { parentSelector: ["body"], position: "end" }+ );+ expect(data.instances).toEqual(+ renderData(+ <$.Body ws:id="body">+ <ws.collection ws:id="collection"></ws.collection>+ <$.Box ws:id="box"></$.Box>+ </$.Body>+ ).instances+ );+ });++ test("unsets variables scoped outside of moved subtree", () => {+ const data = getWebstudioDataStub({+ instances: createParentChildInstances([+ { type: "expression", value: "$ws$dataSource$parentVariable" },+ ]),+ dataSources: new Map([["parentVariable", parentScopedVariable]]),+ });+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["child", "parent", "body"], {+ parentSelector: ["body"],+ position: "end",+ });++ expect(data.instances.get("child")?.children).toEqual([+ { type: "expression", value: "Parent$32$Variable" },+ ]);+ });++ test("remaps moved expression props, action props, and resource expressions", () => {+ const data = getWebstudioDataStub({+ instances: createParentChildInstances(),+ dataSources: new Map([+ ["parentVariable", parentScopedVariable],+ ] satisfies [DataSource["id"], DataSource][]),+ props: new Map([+ [+ "expressionProp",+ {+ id: "expressionProp",+ instanceId: "child",+ name: "state",+ type: "expression",+ value: "$ws$dataSource$parentVariable",+ },+ ],+ [+ "actionProp",+ {+ id: "actionProp",+ instanceId: "child",+ name: "onClick",+ type: "action",+ value: [+ {+ type: "execute",+ args: [],+ code: "$ws$dataSource$parentVariable = 'next'",+ },+ ],+ },+ ],+ [+ "resourceProp",+ {+ id: "resourceProp",+ instanceId: "child",+ name: "resource",+ type: "resource",+ value: "resource",+ },+ ],+ ] satisfies [Prop["id"], Prop][]),+ resources: new Map([+ [+ "resource",+ {+ id: "resource",+ name: "Resource",+ method: "post",+ url: "$ws$dataSource$parentVariable",+ headers: [+ {+ name: "authorization",+ value: "$ws$dataSource$parentVariable",+ },+ ],+ searchParams: [+ {+ name: "query",+ value: "$ws$dataSource$parentVariable",+ },+ ],+ body: "$ws$dataSource$parentVariable",+ },+ ],+ ] satisfies [Resource["id"], Resource][]),+ });+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["child", "parent", "body"], {+ parentSelector: ["body"],+ position: "end",+ });++ expect(data.props.get("expressionProp")).toEqual({+ id: "expressionProp",+ instanceId: "child",+ name: "state",+ type: "expression",+ value: "Parent$32$Variable",+ });+ expect(data.props.get("actionProp")).toEqual({+ id: "actionProp",+ instanceId: "child",+ name: "onClick",+ type: "action",+ value: [+ {+ type: "execute",+ args: [],+ code: "Parent$32$Variable = 'next'",+ },+ ],+ });+ expect(data.resources.get("resource")).toEqual({+ id: "resource",+ name: "Resource",+ method: "post",+ url: "Parent$32$Variable",+ headers: [{ name: "authorization", value: "Parent$32$Variable" }],+ searchParams: [{ name: "query", value: "Parent$32$Variable" }],+ body: "Parent$32$Variable",+ });+ });++ test("restores moved expressions to same-name variables in new scope", () => {+ const data = getWebstudioDataStub({+ instances: new Map([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "source" },+ { type: "id", value: "target" },+ ],+ },+ ],+ [+ "source",+ {+ type: "instance",+ id: "source",+ component: "Box",+ children: [{ type: "id", value: "child" }],+ },+ ],+ [+ "target",+ {+ type: "instance",+ id: "target",+ component: "Box",+ children: [],+ },+ ],+ [+ "child",+ {+ type: "instance",+ id: "child",+ component: "Box",+ children: [+ { type: "expression", value: "$ws$dataSource$sourceVariable" },+ ],+ },+ ],+ ]),+ dataSources: new Map([+ [+ "sourceVariable",+ {+ id: "sourceVariable",+ scopeInstanceId: "source",+ type: "variable",+ name: "Shared Name",+ value: { type: "string", value: "source" },+ },+ ],+ [+ "targetVariable",+ {+ id: "targetVariable",+ scopeInstanceId: "target",+ type: "variable",+ name: "Shared Name",+ value: { type: "string", value: "target" },+ },+ ],+ ] satisfies [DataSource["id"], DataSource][]),+ });+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(createFakeComponentMetas({}));++ reparentInstanceMutable(data, ["child", "source", "body"], {+ parentSelector: ["target", "body"],+ position: "end",+ });++ expect(data.instances.get("child")?.children).toEqual([+ { type: "expression", value: "$ws$dataSource$targetVariable" },+ ]);+ });++ test("move required child within same instance", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Tooltip ws:id="tooltip">+ <$.TooltipTrigger ws:id="trigger"></$.TooltipTrigger>+ <$.TooltipContent ws:id="content"></$.TooltipContent>+ </$.Tooltip>+ </$.Body>+ );+ $registeredComponentMetas.set(+ new Map(Object.entries({ ...defaultMetas, ...radixMetas }))+ );+ reparentInstanceMutable(data, ["trigger", "tooltip", "body"], {+ parentSelector: ["tooltip", "body"],+ position: "end",+ });+ expect(data.instances).toEqual(+ renderData(+ <$.Body ws:id="body">+ <$.Tooltip ws:id="tooltip">+ <$.TooltipContent ws:id="content"></$.TooltipContent>+ <$.TooltipTrigger ws:id={expect.any(String)}></$.TooltipTrigger>+ </$.Tooltip>+ </$.Body>+ ).instances+ );+ });+});++const getWebstudioDataStub = (+ 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,+});++const createParentChildInstances = (childChildren: Instance["children"] = []) =>+ new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [{ type: "id", value: "parent" }],+ },+ ],+ [+ "parent",+ {+ type: "instance",+ id: "parent",+ component: "Box",+ children: [{ type: "id", value: "child" }],+ },+ ],+ [+ "child",+ {+ type: "instance",+ id: "child",+ component: "Box",+ children: childChildren,+ },+ ],+ ]);++const parentScopedVariable: DataSource = {+ id: "parentVariable",+ scopeInstanceId: "parent",+ type: "variable",+ name: "Parent Variable",+ value: { type: "string", value: "value" },+};++describe("set instance label", () => {+ test("renames all linked canonical slot occurrences", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1" ws:label="Old Slot">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot3">+ <$.Fragment ws:id="otherFragment">+ <$.Box ws:id="otherBox"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );++ setInstanceLabelMutable(instances, "slot1", "Navigation");++ expect(instances.get("slot1")?.label).toBe("Navigation");+ expect(instances.get("slot2")?.label).toBe("Navigation");+ expect(instances.get("slot3")?.label).toBeUndefined();+ });++ test("renames all linked legacy slot occurrences", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Box ws:id="box"></$.Box>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Box ws:id="box"></$.Box>+ </$.Slot>+ </$.Body>+ );++ setInstanceLabelMutable(instances, "slot1", "Navigation");++ expect(instances.get("slot1")?.label).toBe("Navigation");+ expect(instances.get("slot2")?.label).toBe("Navigation");+ });++ test("renames only selected non-slot instance", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box1"></$.Box>+ <$.Box ws:id="box2"></$.Box>+ </$.Body>+ );++ setInstanceLabelMutable(instances, "box1", "Card");++ expect(instances.get("box1")?.label).toBe("Card");+ expect(instances.get("box2")?.label).toBeUndefined();+ });+});++describe("delete instance", () => {+ test("delete instance with its children", () => {+ const data = renderData(+ <$.Body ws:id="bodyId">+ <$.Box ws:id="boxId">+ <$.Box ws:id="sectionId"></$.Box>+ </$.Box>+ <$.Box ws:id="divId"></$.Box>+ </$.Body>+ );+ expect(data.instances.size).toEqual(4);+ expect(data.instances.get("bodyId")?.children.length).toEqual(2);+ deleteInstanceMutable(+ data,+ // clone to make sure data is mutated instead of instance path+ structuredClone(getInstancePath(["boxId", "bodyId"], data.instances))+ );+ expect(data.instances.size).toEqual(2);+ expect(data.instances.get("bodyId")?.children.length).toEqual(1);+ });++ test("delete instance from collection", () => {+ const data = renderData(+ <$.Body ws:id="bodyId">+ <ws.collection ws:id="collectionId">+ <$.Box ws:id="boxId"></$.Box>+ </ws.collection>+ </$.Body>+ );+ expect(data.instances.size).toEqual(3);+ expect(data.instances.get("collectionId")?.children.length).toEqual(1);+ deleteInstanceMutable(+ data,+ getInstancePath(+ ["boxId", "collectionId[0]", "collectionId", "bodyId"],+ data.instances+ )+ );+ expect(data.instances.size).toEqual(2);+ expect(data.instances.get("collectionId")?.children.length).toEqual(0);+ });++ test("delete instance from collection item", () => {+ const data = renderData(+ <$.Body ws:id="bodyId">+ <ws.collection ws:id="collectionId">+ <$.Box ws:id="boxId">+ <$.Text ws:id="textId"></$.Text>+ </$.Box>+ </ws.collection>+ </$.Body>+ );+ expect(data.instances.size).toEqual(4);+ expect(data.instances.get("boxId")?.children.length).toEqual(1);+ deleteInstanceMutable(+ data,+ getInstancePath(+ ["textId", "boxId", "collectionId[0]", "collectionId", "bodyId"],+ data.instances+ )+ );+ expect(data.instances.size).toEqual(3);+ expect(data.instances.get("boxId")?.children.length).toEqual(0);+ });++ test("delete resource bound to variable", () => {+ const myResource = new ResourceValue("My Resource", {+ url: expression`""`,+ method: "get",+ searchParams: [],+ headers: [],+ });+ const data = renderData(+ <$.Body ws:id="bodyId">+ <$.Box ws:id="boxId" vars={expression`${myResource}`}></$.Box>+ </$.Body>+ );+ expect(data.resources.size).toEqual(1);+ expect(data.dataSources.size).toEqual(1);+ deleteInstanceMutable(+ data,+ getInstancePath(["boxId", "bodyId"], data.instances)+ );+ expect(data.resources.size).toEqual(0);+ expect(data.dataSources.size).toEqual(0);+ });++ test("delete resource bound to prop", () => {+ const myResource = new ResourceValue("My Resource", {+ url: expression`""`,+ method: "get",+ searchParams: [],+ headers: [],+ });+ const data = renderData(+ <$.Body ws:id="bodyId">+ <$.Box ws:id="boxId" action={myResource}></$.Box>+ </$.Body>+ );+ expect(data.resources.size).toEqual(1);+ expect(data.props.size).toEqual(1);+ deleteInstanceMutable(+ data,+ getInstancePath(["boxId", "bodyId"], data.instances)+ );+ expect(data.resources.size).toEqual(0);+ expect(data.props.size).toEqual(0);+ });++ test("delete unknown instance (just in case)", () => {+ const data = renderData(+ <$.Body ws:id="bodyId">+ <$.Invalid ws:id="invalidId"></$.Invalid>+ </$.Body>+ );+ expect(data.instances.size).toEqual(2);+ deleteInstanceMutable(+ data,+ getInstancePath(["invalidId", "bodyId"], data.instances)+ );+ expect(data.instances.size).toEqual(1);+ });++ test("delete slot fragment along with last child", () => {+ const data = renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slotId">+ <$.Fragment ws:id="fragmentId">+ <$.Box ws:id="boxId"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ expect(data.instances.size).toEqual(4);+ expect(data.instances.get("fragmentId")?.children.length).toEqual(1);+ deleteInstanceMutable(+ data,+ getInstancePath(+ ["boxId", "fragmentId", "slotId", "bodyId"],+ data.instances+ )+ );+ expect(data.instances.size).toEqual(2);+ expect(data.instances.get("slotId")?.children.length).toEqual(0);+ });++ test("delete shared slot content from all slot occurrences", () => {+ const data = renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );++ deleteInstanceMutable(+ data,+ getInstancePath(["div", "fragment", "slot1", "bodyId"], data.instances)+ );++ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([]);+ expect(data.instances.has("div")).toEqual(false);+ });++ test("delete legacy shared slot content from all slot occurrences", () => {+ const data = renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ </$.Body>+ );++ deleteInstanceMutable(+ data,+ getInstancePath(["box", "slot1", "bodyId"], data.instances)+ );++ const fragmentId = expectSlotsShareFragment(data.instances, [+ "slot1",+ "slot2",+ ]);+ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect(data.instances.get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ expect(data.instances.has("box")).toBe(false);+ });++ test("delete nested shared slot content from all slot occurrences", () => {+ const data = renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );++ deleteInstanceMutable(+ data,+ getInstancePath(+ ["box", "div", "fragment", "slot1", "bodyId"],+ data.instances+ )+ );++ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect(data.instances.get("div")?.children).toEqual([]);+ expect(data.instances.has("box")).toEqual(false);+ });++ test("delete shared slot content preserves shared siblings", () => {+ const data = renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );++ deleteInstanceMutable(+ data,+ getInstancePath(["box", "fragment", "slot1", "bodyId"], data.instances)+ );++ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ expect(data.instances.has("box")).toEqual(false);+ });++ test("delete last direct shared slot child preserves shared siblings", () => {+ const data = renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );++ deleteInstanceMutable(+ data,+ getInstancePath(+ ["heading", "fragment", "slot1", "bodyId"],+ data.instances+ )+ );++ expect(data.instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ expect(data.instances.has("heading")).toEqual(false);+ });+});++describe("detach shared slot content", () => {+ test("detachSharedSlotChildrenMutable clones shared fragment for selected slot", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);++ detachSharedSlotChildrenMutable(data, "slot1");++ const slot1FragmentId = data.instances.get("slot1")?.children[0]?.value;+ expect(slot1FragmentId).toBeDefined();+ expect(slot1FragmentId).not.toBe("fragment");+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get(slot1FragmentId ?? "")?.children).toEqual([+ { type: "id", value: expect.any(String) },+ ]);+ });++ test("detachSharedSlotContentMutable returns remapped selected path", () => {+ const data = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $project.set({ id: "projectId" } as Project);+ const instancePath =+ getInstancePath(["box", "fragment", "slot1", "body"], data.instances) ??+ [];++ const detachedPath = detachSharedSlotContentMutable(data, instancePath);++ expect(detachedPath[0].instance.id).not.toBe("box");+ expect(detachedPath[1].instance.id).not.toBe("fragment");+ expect(detachedPath[2].instance.id).toBe("slot1");+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ });+});++describe("wrap in", () => {+ test("wrap instance in link", () => {+ $instances.set(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ </ws.element>+ ).instances+ );+ selectInstance(["divId", "bodyId"]);+ wrapInstance(elementComponent, "a");+ expect($instances.get()).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="a" ws:id={expect.any(String)}>+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ </ws.element>+ </ws.element>+ ).instances+ );+ });++ test("wrap image in element", () => {+ $instances.set(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="img" ws:id="imageId"></ws.element>+ </ws.element>+ ).instances+ );+ selectInstance(["imageId", "bodyId"]);+ wrapInstance(elementComponent);+ expect($instances.get()).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id={expect.any(String)}>+ <ws.element ws:tag="img" ws:id="imageId"></ws.element>+ </ws.element>+ </ws.element>+ ).instances+ );+ });++ test("wrap shared slot child in shared slot content", () => {+ $registeredComponentMetas.set(defaultMetasMap);+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );+ selectInstance(["div", "fragment", "slot1", "bodyId"]);++ wrapInstance(elementComponent, "div");++ const wrapperId = $instances.get().get("fragment")?.children[0]?.value;+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: wrapperId },+ ]);+ expect($instances.get().get(wrapperId ?? "")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ });++ test("wrap legacy shared slot child in shared slot content", () => {+ $registeredComponentMetas.set(defaultMetasMap);+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ </$.Body>+ ).instances+ );+ selectInstance(["div", "slot1", "bodyId"]);++ wrapInstance(elementComponent, "div");++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ const wrapperId = $instances.get().get(fragmentId ?? "")+ ?.children[0]?.value;+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: wrapperId },+ { type: "id", value: "heading" },+ ]);+ expect($instances.get().get(wrapperId ?? "")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ });++ test("wrap shared slot child preserves shared siblings", () => {+ $registeredComponentMetas.set(defaultMetasMap);+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );+ selectInstance(["div", "fragment", "slot1", "bodyId"]);++ wrapInstance(elementComponent, "div");++ const wrapperId = $instances.get().get("fragment")?.children[0]?.value;+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: wrapperId },+ { type: "id", value: "heading" },+ ]);+ expect($instances.get().get(wrapperId ?? "")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ });++ test.each([+ {+ selectedId: "box",+ expectedSiblingIds: [expect.any(String), "heading"],+ },+ {+ selectedId: "heading",+ expectedSiblingIds: ["box", expect.any(String)],+ },+ ])(+ "wrap direct shared slot child in $selectedId position preserves sibling order",+ ({ selectedId, expectedSiblingIds }) => {+ $registeredComponentMetas.set(defaultMetasMap);+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );+ selectInstance([selectedId, "fragment", "slot1", "bodyId"]);++ wrapInstance(elementComponent, "div");++ const wrapperId = $instances+ .get()+ .get("fragment")+ ?.children.find(+ (child) =>+ child.type === "id" &&+ child.value !== "box" &&+ child.value !== "heading"+ )?.value;+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual(+ expectedSiblingIds.map((value) => ({ type: "id", value }))+ );+ expect(wrapperId).toEqual(expect.any(String));+ expect($instances.get().get(wrapperId ?? "")?.children).toEqual([+ { type: "id", value: selectedId },+ ]);+ }+ );++ test("wrap nested shared slot child in shared slot content", () => {+ $registeredComponentMetas.set(defaultMetasMap);+ $instances.set(+ renderData(+ <$.Body ws:id="bodyId">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ ).instances+ );+ selectInstance(["box", "div", "fragment", "slot1", "bodyId"]);++ wrapInstance(elementComponent, "div");++ const wrapperId = $instances.get().get("div")?.children[0]?.value;+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect($instances.get().get("div")?.children).toEqual([+ { type: "id", value: wrapperId },+ ]);+ expect($instances.get().get(wrapperId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ });++ test("avoid wrapping text with link in link", () => {+ const { instances } = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="p" ws:id="textId">+ <ws.element ws:tag="a" ws:id="linkId"></ws.element>+ </ws.element>+ </ws.element>+ );+ $instances.set(instances);+ selectInstance(["textId", "bodyId"]);+ wrapInstance(elementComponent, "a");+ // nothing is changed+ expect($instances.get()).toEqual(instances);+ });++ test("avoid wrapping textual content", () => {+ const { instances } = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="textId">+ <ws.element ws:tag="bold" ws:id="boldId"></ws.element>+ </ws.element>+ </ws.element>+ );+ $instances.set(instances);+ selectInstance(["boldId", "textId", "bodyId"]);+ wrapInstance(elementComponent);+ // nothing is changed+ expect($instances.get()).toEqual(instances);+ });++ test("avoid wrapping list item", () => {+ const { instances } = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="ul" ws:id="listId">+ <ws.element ws:tag="li" ws:id="listItemId"></ws.element>+ </ws.element>+ </ws.element>+ );+ $instances.set(instances);+ selectInstance(["listItemId", "listId", "bodyId"]);+ wrapInstance(elementComponent);+ // nothing is changed+ expect($instances.get()).toEqual(instances);+ });+});++describe("toggleInstanceShow", () => {+ test("creates show prop with false value when it doesn't exist", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box"></$.Box>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(new Map());+ $pages.set(createDefaultPages({ rootInstanceId: "body" }));++ toggleInstanceShow("box");++ const props = $props.get();+ const showProp = Array.from(props.values()).find(+ (prop) => prop.instanceId === "box" && prop.name === showAttribute+ );+ expect(showProp).toEqual({+ id: expect.any(String),+ instanceId: "box",+ name: showAttribute,+ type: "boolean",+ value: false,+ });+ });++ test("toggles show prop from true to false", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box" ws:show={true}></$.Box>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ $pages.set(createDefaultPages({ rootInstanceId: "body" }));++ toggleInstanceShow("box");++ const updatedProps = $props.get();+ const showProp = Array.from(updatedProps.values()).find(+ (prop) => prop.instanceId === "box" && prop.name === showAttribute+ );+ expect(showProp?.type).toBe("boolean");+ if (showProp?.type === "boolean") {+ expect(showProp.value).toBe(false);+ }+ });++ test("toggles show prop from false to true", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box" ws:show={false}></$.Box>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ $pages.set(createDefaultPages({ rootInstanceId: "body" }));++ toggleInstanceShow("box");++ const updatedProps = $props.get();+ const showProp = Array.from(updatedProps.values()).find(+ (prop) => prop.instanceId === "box" && prop.name === showAttribute+ );+ expect(showProp?.type).toBe("boolean");+ if (showProp?.type === "boolean") {+ expect(showProp.value).toBe(true);+ }+ });+});++describe("unwrap instance", () => {+ test("unwraps instance and moves children to parent", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="parent">+ <$.Box ws:id="wrapper">+ <$.Box ws:id="child1"></$.Box>+ <$.Box ws:id="child2"></$.Box>+ </$.Box>+ </$.Box>+ </$.Body>+ );++ const selectedItem = {+ instanceSelector: ["wrapper", "parent", "body"],+ instance: instances.get("wrapper")!,+ };+ const parentItem = {+ instanceSelector: ["parent", "body"],+ instance: instances.get("parent")!,+ };++ const result = unwrapInstanceMutable({+ instances,+ props,+ metas: defaultMetasMap,+ selectedItem,+ parentItem,+ });++ expect(result.success).toBe(true);+ expect(instances.has("parent")).toBe(false);+ const bodyInstance = instances.get("body")!;+ expect(bodyInstance.children).toEqual([{ type: "id", value: "wrapper" }]);+ });++ test("fails to unwrap textual instance", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box">+ <$.Paragraph ws:id="paragraph">+ <$.Bold ws:id="bold">text</$.Bold>+ </$.Paragraph>+ </$.Box>+ </$.Body>+ );++ const selectedItem = {+ instanceSelector: ["bold", "paragraph", "box", "body"],+ instance: instances.get("bold")!,+ };+ const parentItem = {+ instanceSelector: ["paragraph", "box", "body"],+ instance: instances.get("paragraph")!,+ };++ const result = unwrapInstanceMutable({+ instances,+ props,+ metas: defaultMetasMap,+ selectedItem,+ parentItem,+ });++ expect(result.success).toBe(false);+ expect(result.error).toBe("Cannot unwrap textual instance");+ });++ test("fails to unwrap if content model is violated", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="outerBox">+ <$.Form ws:id="form">+ <$.Box ws:id="innerBox">+ <$.Form ws:id="nestedForm"></$.Form>+ </$.Box>+ </$.Form>+ </$.Box>+ </$.Body>+ );++ const selectedItem = {+ instanceSelector: ["form", "outerBox", "body"],+ instance: instances.get("form")!,+ };+ const parentItem = {+ instanceSelector: ["outerBox", "body"],+ instance: instances.get("outerBox")!,+ };++ const result = unwrapInstanceMutable({+ instances,+ props,+ metas: defaultMetasMap,+ selectedItem,+ parentItem,+ });++ expect(result.success).toBe(false);+ expect(result.error).toBe("Cannot unwrap instance");+ });++ test("unwrapping replaces parent with selected in grandparent", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="parent">+ <$.Box ws:id="child"></$.Box>+ </$.Box>+ </$.Body>+ );++ const selectedItem = {+ instanceSelector: ["child", "parent", "body"],+ instance: instances.get("child")!,+ };+ const parentItem = {+ instanceSelector: ["parent", "body"],+ instance: instances.get("parent")!,+ };++ const result = unwrapInstanceMutable({+ instances,+ props,+ metas: defaultMetasMap,+ selectedItem,+ parentItem,+ });++ expect(result.success).toBe(true);+ expect(instances.has("parent")).toBe(false);+ expect(instances.has("child")).toBe(true);+ const bodyInstance = instances.get("body")!;+ expect(bodyInstance.children).toEqual([{ type: "id", value: "child" }]);+ });++ test("unwrapping removes selected from parent and moves it to grandparent", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="parent">+ <$.Image ws:id="image"></$.Image>+ <$.Link ws:id="link"></$.Link>+ </$.Box>+ </$.Body>+ );++ const selectedItem = {+ instanceSelector: ["image", "parent", "body"],+ instance: instances.get("image")!,+ };+ const parentItem = {+ instanceSelector: ["parent", "body"],+ instance: instances.get("parent")!,+ };++ const result = unwrapInstanceMutable({+ instances,+ props,+ metas: defaultMetasMap,+ selectedItem,+ parentItem,+ });++ expect(result.success).toBe(true);+ expect(instances.has("parent")).toBe(true); // Parent still exists+ expect(instances.has("image")).toBe(true);+ expect(instances.has("link")).toBe(true);++ const bodyInstance = instances.get("body")!;+ expect(bodyInstance.children).toEqual([+ { type: "id", value: "parent" },+ { type: "id", value: "image" },+ ]);++ const parentInstance = instances.get("parent")!;+ expect(parentInstance.children).toEqual([{ type: "id", value: "link" }]);+ });++ test("unwraps direct slot child out of shared slot content", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );++ const result = unwrapInstanceMutable({+ instances,+ props,+ metas: defaultMetasMap,+ selectedItem: {+ instanceSelector: ["div", "fragment", "slot1", "body"],+ instance: instances.get("div")!,+ },+ parentItem: {+ instanceSelector: ["slot1", "body"],+ instance: instances.get("slot1")!,+ },+ });++ expect(result.success).toBe(true);+ expect(instances.get("body")?.children).toEqual([+ { type: "id", value: "div" },+ { type: "id", value: "slot2" },+ ]);+ expect(instances.has("slot1")).toBe(false);+ expect(instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(instances.get("fragment")?.children).toEqual([]);+ });++ test("unwrap command skips hidden slot fragment", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["div", "fragment", "slot", "body"]);++ unwrapInstance();++ expect($selectedInstanceSelector.get()).toEqual(["div", "body"]);+ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect($instances.get().has("slot")).toBe(false);+ expect($instances.get().has("fragment")).toBe(false);+ });++ test("unwrap command moves only shared slot child out of all slot occurrences", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["div", "fragment", "slot1", "body"]);++ unwrapInstance();++ const bodyChildren = $instances.get().get("body")?.children;+ const unwrappedDivId =+ bodyChildren?.[0]?.type === "id" ? bodyChildren[0].value : undefined;++ expect(unwrappedDivId).toBeDefined();+ expect(unwrappedDivId).toBe("div");+ expect($selectedInstanceSelector.get()).toEqual([unwrappedDivId, "body"]);+ expect($instances.get().get("slot1")).toBeUndefined();+ const fragmentId = getSlotFragmentId($instances.get(), "slot2");+ expect(fragmentId).toBe("fragment");+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([]);+ });++ test("unwrap command moves direct shared slot child out of all slots and preserves siblings", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["box", "fragment", "slot1", "body"]);++ unwrapInstance();++ const bodyChildren = $instances.get().get("body")?.children;+ const slot1Id = bodyChildren?.find(+ (child) => child.type === "id" && child.value === "slot1"+ )?.value;+ const unwrappedBoxId = bodyChildren?.find(+ (child) =>+ child.type === "id" &&+ child.value !== "slot1" &&+ child.value !== "slot2"+ )?.value;+ const slot1FragmentId =+ slot1Id === undefined+ ? undefined+ : $instances.get().get(slot1Id)?.children[0]?.value;++ expect(slot1Id).toBe("slot1");+ const sharedFragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ expect(slot1FragmentId).toBe(sharedFragmentId);+ expect(unwrappedBoxId).toBeDefined();+ expect(unwrappedBoxId).toBe("box");+ expect($selectedInstanceSelector.get()).toEqual([unwrappedBoxId, "body"]);+ expect($instances.get().get(sharedFragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ });++ test("unwrap command moves direct legacy shared slot child out of all slots and preserves siblings", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["box", "slot1", "body"]);++ unwrapInstance();++ const bodyChildren = $instances.get().get("body")?.children;+ const slot1Id =+ bodyChildren?.[0]?.type === "id" ? bodyChildren[0].value : undefined;+ const unwrappedBoxId =+ bodyChildren?.[1]?.type === "id" ? bodyChildren[1].value : undefined;+ const sharedFragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ const slot1FragmentId =+ slot1Id === undefined+ ? undefined+ : getSlotFragmentId($instances.get(), slot1Id);++ expect(slot1Id).toBe("slot1");+ expect(slot1FragmentId).toBe(sharedFragmentId);+ expect(unwrappedBoxId).toBeDefined();+ expect(unwrappedBoxId).toBe("box");+ expect($selectedInstanceSelector.get()).toEqual([unwrappedBoxId, "body"]);+ expect($instances.get().get(sharedFragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ });++ test.each([+ {+ selectedId: "box1",+ remainingIds: ["box2", "box3"],+ },+ {+ selectedId: "box2",+ remainingIds: ["box1", "box3"],+ },+ {+ selectedId: "box3",+ remainingIds: ["box1", "box2"],+ },+ ])(+ "unwrap command moves direct shared slot child in $selectedId position out of all slots",+ ({ selectedId, remainingIds }) => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box1"></$.Box>+ <$.Box ws:id="box2"></$.Box>+ <$.Box ws:id="box3"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box1"></$.Box>+ <$.Box ws:id="box2"></$.Box>+ <$.Box ws:id="box3"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance([selectedId, "fragment", "slot1", "body"]);++ unwrapInstance();++ const bodyChildren = $instances.get().get("body")?.children ?? [];+ const unwrappedId = bodyChildren.find(+ (child) =>+ child.type === "id" &&+ child.value !== "slot1" &&+ child.value !== "slot2"+ )?.value;+ const sharedFragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ expect(unwrappedId).toBe(selectedId);+ expect($selectedInstanceSelector.get()).toEqual([unwrappedId, "body"]);+ expect($instances.get().get(sharedFragmentId ?? "")?.children).toEqual(+ remainingIds.map((id) => ({ type: "id", value: id }))+ );+ }+ );++ test("unwrap command keeps nested shared slot child in shared slot content", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["box", "div", "fragment", "slot1", "body"]);++ unwrapInstance();++ expect($selectedInstanceSelector.get()).toEqual([+ "box",+ "fragment",+ "slot1",+ "body",+ ]);+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ expect($instances.get().has("div")).toBe(false);+ });++ test("unwrap command keeps nested shared slot child with siblings in shared slot content", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["box", "div", "fragment", "slot1", "body"]);++ unwrapInstance();++ expect($selectedInstanceSelector.get()).toEqual([+ "box",+ "fragment",+ "slot1",+ "body",+ ]);+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ { type: "id", value: "box" },+ ]);+ expect($instances.get().get("div")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ });+});++describe("canUnwrapInstance", () => {+ beforeEach(() => {+ $project.set({ id: "projectId" } as Project);+ $registeredComponentMetas.set(defaultMetasMap);+ });++ test("returns true for unwrappable instance", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="parent">+ <$.Box ws:id="wrapper">+ <$.Box ws:id="child"></$.Box>+ </$.Box>+ </$.Box>+ </$.Body>+ );++ $instances.set(instances);+ $props.set(props);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);++ const instancePath = [+ {+ instanceSelector: ["wrapper", "parent", "body"],+ instance: instances.get("wrapper")!,+ },+ {+ instanceSelector: ["parent", "body"],+ instance: instances.get("parent")!,+ },+ {+ instanceSelector: ["body"],+ instance: instances.get("body")!,+ },+ ] satisfies InstancePath;++ expect(canUnwrapInstance(instancePath)).toBe(true);+ });++ test("returns false if parent is root instance", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="box"></$.Box>+ </$.Body>+ );++ $instances.set(instances);+ $props.set(props);+ $registeredComponentMetas.set(defaultMetasMap);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);++ const instancePath = [+ {+ instanceSelector: ["box", "body"],+ instance: instances.get("box")!,+ },+ {+ instanceSelector: ["body"],+ instance: instances.get("body")!,+ },+ ] satisfies InstancePath;++ expect(canUnwrapInstance(instancePath)).toBe(false);+ });++ test("returns false for textual instance", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Paragraph ws:id="paragraph">+ <$.Bold ws:id="bold">text</$.Bold>+ </$.Paragraph>+ </$.Body>+ );++ $instances.set(instances);+ $props.set(props);+ $registeredComponentMetas.set(defaultMetasMap);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);++ const instancePath = [+ {+ instanceSelector: ["bold", "paragraph", "body"],+ instance: instances.get("bold")!,+ },+ {+ instanceSelector: ["paragraph", "body"],+ instance: instances.get("paragraph")!,+ },+ ] satisfies InstancePath;++ expect(canUnwrapInstance(instancePath)).toBe(false);+ });++ test("returns true for Body > div > a scenario", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <ws.element ws:tag="div" ws:id="div">+ <ws.element ws:tag="a" ws:id="link">+ Link text+ </ws.element>+ </ws.element>+ </$.Body>+ );++ $instances.set(instances);+ $props.set(props);+ $registeredComponentMetas.set(defaultMetasMap);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);++ const instancePath = [+ {+ instanceSelector: ["link", "div", "body"],+ instance: instances.get("link")!,+ },+ {+ instanceSelector: ["div", "body"],+ instance: instances.get("div")!,+ },+ {+ instanceSelector: ["body"],+ instance: instances.get("body")!,+ },+ ] satisfies InstancePath;++ // Should be able to unwrap the link from the div+ expect(canUnwrapInstance(instancePath)).toBe(true);+ });++ test("unwrapInstanceMutable works for Body > div > a scenario", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <ws.element ws:tag="div" ws:id="div">+ <ws.element ws:tag="a" ws:id="link">+ Link text+ </ws.element>+ </ws.element>+ </$.Body>+ );++ const result = unwrapInstanceMutable({+ instances,+ props,+ metas: defaultMetasMap,+ selectedItem: {+ instanceSelector: ["link", "div", "body"],+ instance: instances.get("link")!,+ },+ parentItem: {+ instanceSelector: ["div", "body"],+ instance: instances.get("div")!,+ },+ });++ expect(result.success).toBe(true);++ // Verify the link is now a direct child of body+ const body = instances.get("body")!;+ expect(body.children).toContainEqual({ type: "id", value: "link" });++ // Verify the div was deleted since it has no more children+ expect(instances.has("div")).toBe(false);+ });+});++describe("canConvertInstance", () => {+ test("returns true for valid conversion", () => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="body">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ );++ const result = canConvertInstance(+ "box",+ ["box", "body"],+ elementComponent,+ "div",+ instances,+ props,+ defaultMetasMap+ );++ expect(result).toBe(true);+ });++ test("returns false for non-existent instance", () => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="body"></ws.element>+ );++ const result = canConvertInstance(+ "nonexistent",+ ["nonexistent", "body"],+ elementComponent,+ "div",+ instances,+ props,+ defaultMetasMap+ );++ expect(result).toBe(false);+ });++ test("returns true when converting Box to Heading", () => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="body">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ );++ const result = canConvertInstance(+ "box",+ ["box", "body"],+ "@webstudio-is/sdk-components-react:Heading",+ undefined,+ instances,+ props,+ defaultMetasMap+ );++ expect(result).toBe(true);+ });++ test("uses preset tag when available", () => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="body">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ );++ const result = canConvertInstance(+ "box",+ ["box", "body"],+ "@webstudio-is/sdk-components-react:Heading",+ undefined,+ instances,+ props,+ defaultMetasMap+ );++ expect(result).toBe(true);+ });+});++describe("convertInstance", () => {+ beforeEach(() => {+ $registeredComponentMetas.set(defaultMetasMap);+ });++ test("detach shared slot children when converting slot", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div"></ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ selectInstance(["slot1", "body"]);++ convertInstance(elementComponent, "section");++ const convertedSlot = $instances.get().get("slot1");+ expect(convertedSlot?.component).toBe(elementComponent);+ expect(convertedSlot?.tag).toBe("section");+ expect(convertedSlot?.children).not.toEqual(+ $instances.get().get("slot2")?.children+ );+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ });++ test("detach shared slot children with siblings when converting slot", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ selectInstance(["slot1", "body"]);++ convertInstance(elementComponent, "section");++ const convertedSlot = $instances.get().get("slot1");+ const convertedFragmentId = convertedSlot?.children[0]?.value;+ expect(convertedSlot?.component).toBe(elementComponent);+ expect(convertedSlot?.tag).toBe("section");+ expect(convertedFragmentId).toBeDefined();+ expect(convertedFragmentId).not.toBe("fragment");+ expect($instances.get().get(convertedFragmentId ?? "")?.children).toEqual([+ { type: "id", value: expect.any(String) },+ { type: "id", value: expect.any(String) },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]);+ });++ test("detach legacy shared slot children when converting slot", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ selectInstance(["slot1", "body"]);++ convertInstance(elementComponent, "section");++ const convertedSlot = $instances.get().get("slot1");+ const convertedFragmentId = convertedSlot?.children[0]?.value;+ const slot2FragmentId = getSlotFragmentId($instances.get(), "slot2");+ expect(convertedSlot?.component).toBe(elementComponent);+ expect(convertedSlot?.tag).toBe("section");+ expect(convertedFragmentId).toBeDefined();+ expect(slot2FragmentId).toBeDefined();+ expect(convertedFragmentId).not.toBe(slot2FragmentId);+ expect($instances.get().get(convertedFragmentId ?? "")?.component).toBe(+ "Fragment"+ );+ expect($instances.get().get(convertedFragmentId ?? "")?.children).toEqual([+ { type: "id", value: expect.any(String) },+ { type: "id", value: expect.any(String) },+ ]);+ expect($instances.get().get(slot2FragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]);+ });++ test("converts shared slot child in shared slot content", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ selectInstance(["box", "fragment", "slot1", "body"]);++ convertInstance(elementComponent, "section");++ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ expect($instances.get().get("box")?.component).toBe(elementComponent);+ expect($instances.get().get("box")?.tag).toBe("section");+ });++ test("converts legacy shared slot child in shared slot content", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ selectInstance(["box", "slot1", "body"]);++ convertInstance(elementComponent, "section");++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]);+ expect($instances.get().get("box")?.component).toBe(elementComponent);+ expect($instances.get().get("box")?.tag).toBe("section");+ });++ test("converts nested shared slot child in shared slot content", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ selectInstance(["box", "div", "fragment", "slot1", "body"]);++ convertInstance(elementComponent, "section");++ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect($instances.get().get("div")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ expect($instances.get().get("box")?.component).toBe(elementComponent);+ expect($instances.get().get("box")?.tag).toBe("section");+ });++ test("converts nested shared slot child and preserves siblings", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <ws.element ws:tag="div" ws:id="div">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </ws.element>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ selectInstance(["box", "div", "fragment", "slot1", "body"]);++ convertInstance(elementComponent, "section");++ expect($instances.get().get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ expect($instances.get().get("div")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]);+ expect($instances.get().get("box")?.component).toBe(elementComponent);+ expect($instances.get().get("box")?.tag).toBe("section");+ });++ test("command sequence preserves shared slot content through wrap, convert, and unwrap", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ $props.set(props);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["box", "fragment", "slot1", "body"]);++ wrapInstance(elementComponent, "div");++ const wrapperId = $selectedInstanceSelector.get()?.[0];+ expect(wrapperId).toEqual(expect.any(String));+ if (wrapperId === undefined) {+ throw new Error("Expected wrapper to be selected");+ }+ expectSlotTreeIntegrity($instances.get(), {+ selectedInstanceSelector: $selectedInstanceSelector.get(),+ });+ expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: wrapperId },+ { type: "id", value: "heading" },+ ]);++ convertInstance(elementComponent, "section");++ expect($instances.get().get(wrapperId)?.component).toBe(elementComponent);+ expect($instances.get().get(wrapperId)?.tag).toBe("section");+ expectSlotTreeIntegrity($instances.get(), {+ selectedInstanceSelector: $selectedInstanceSelector.get(),+ });+ expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);++ selectInstance(["box", wrapperId, "fragment", "slot1", "body"]);+ unwrapInstance();++ expect($selectedInstanceSelector.get()).toEqual([+ "box",+ "fragment",+ "slot1",+ "body",+ ]);+ expectSlotTreeIntegrity($instances.get(), {+ selectedInstanceSelector: $selectedInstanceSelector.get(),+ });+ expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);+ expect($instances.get().get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]);+ expect($instances.get().has(wrapperId)).toBe(false);+ });++ test("converts legacy tag to element", () => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box tag="article" ws:id="articleId"></$.Box>+ </ws.element>+ );+ $instances.set(instances);+ $props.set(props);+ selectInstance(["articleId", "bodyId"]);+ convertInstance(elementComponent);+ const { instances: newInstances, props: newProps } = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="article" ws:id="articleId"></ws.element>+ </ws.element>+ );+ expect({ instances: $instances.get(), props: $props.get() }).toEqual({+ instances: newInstances,+ props: newProps,+ });+ });++ test("migrates legacy properties", () => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box+ ws:tag="div"+ ws:id="divId"+ className="my-class"+ htmlFor="my-id"+ ></$.Box>+ </ws.element>+ );+ $instances.set(instances);+ $props.set(props);+ selectInstance(["divId", "bodyId"]);+ convertInstance(elementComponent);+ const { instances: newInstances, props: newProps } = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element+ ws:tag="div"+ ws:id="divId"+ class="my-class"+ for="my-id"+ ></ws.element>+ </ws.element>+ );+ expect({ instances: $instances.get(), props: $props.get() }).toEqual({+ instances: newInstances,+ props: newProps,+ });+ });++ test("preserves currently specified tag", () => {+ $instances.set(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box ws:tag="article" ws:id="articleId"></$.Box>+ </ws.element>+ ).instances+ );+ selectInstance(["articleId", "bodyId"]);+ convertInstance(elementComponent);+ expect($instances.get()).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="article" ws:id="articleId"></ws.element>+ </ws.element>+ ).instances+ );+ });++ test("converts to first tag from presets", () => {+ $instances.set(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Heading ws:id="headingId"></$.Heading>+ </ws.element>+ ).instances+ );+ selectInstance(["headingId", "bodyId"]);+ convertInstance(elementComponent);+ expect($instances.get()).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="h1" ws:id="headingId"></ws.element>+ </ws.element>+ ).instances+ );+ });++ test("falls back to div", () => {+ $instances.set(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box ws:id="divId"></$.Box>+ </ws.element>+ ).instances+ );+ selectInstance(["divId", "bodyId"]);+ convertInstance(elementComponent);+ expect($instances.get()).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ </ws.element>+ ).instances+ );+ });++ test("converts with specific tag", () => {+ $instances.set(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box ws:id="divId"></$.Box>+ </ws.element>+ ).instances+ );+ selectInstance(["divId", "bodyId"]);+ convertInstance(elementComponent, "a");+ expect($instances.get()).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="a" ws:id="divId"></ws.element>+ </ws.element>+ ).instances+ );+ });++ test("converts between components", () => {+ $instances.set(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box ws:id="boxId"></$.Box>+ </ws.element>+ ).instances+ );+ selectInstance(["boxId", "bodyId"]);+ convertInstance("@webstudio-is/sdk-components-react:Heading");+ const result = $instances.get();+ const boxInstance = result.get("boxId");+ expect(boxInstance?.component).toBe(+ "@webstudio-is/sdk-components-react:Heading"+ );+ });++ test("prevents converting root instance", () => {+ const initialInstances = renderData(+ <ws.element ws:tag="html" ws:id="rootId">+ <ws.element ws:tag="body" ws:id="bodyId"></ws.element>+ </ws.element>+ ).instances;+ $instances.set(initialInstances);+ selectInstance(["rootId"]);+ convertInstance(elementComponent, "div");+ // Should not change+ expect($instances.get()).toEqual(initialInstances);+ });++ test("prevents converting body instance", () => {+ const pages = createDefaultPages({ rootInstanceId: "bodyId" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);++ const initialInstances = renderData(+ <ws.element ws:tag="html" ws:id="rootId">+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box ws:id="boxId"></$.Box>+ </ws.element>+ </ws.element>+ ).instances;+ $instances.set(initialInstances);+ selectInstance(["bodyId", "rootId"]);+ convertInstance(elementComponent, "div");+ // Should not change+ expect($instances.get()).toEqual(initialInstances);+ });+});++describe("deleteSelectedInstance", () => {+ test("delete selected instance and select next one", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="parent">+ <$.Box ws:id="child1"></$.Box>+ <$.Box ws:id="child2"></$.Box>+ <$.Box ws:id="child3"></$.Box>+ </$.Box>+ </$.Body>+ );+ $instances.set(instances);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["child2", "parent", "body"]);+ deleteSelectedInstance();+ expect($selectedInstanceSelector.get()).toEqual([+ "child3",+ "parent",+ "body",+ ]);+ });++ test("delete selected instance and select previous one", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="parent">+ <$.Box ws:id="child1"></$.Box>+ <$.Box ws:id="child2"></$.Box>+ <$.Box ws:id="child3"></$.Box>+ </$.Box>+ </$.Body>+ );+ $instances.set(instances);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["child3", "parent", "body"]);+ deleteSelectedInstance();+ expect($selectedInstanceSelector.get()).toEqual([+ "child2",+ "parent",+ "body",+ ]);+ });++ test("delete selected instance and select parent one", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="parent">+ <$.Box ws:id="child1"></$.Box>+ </$.Box>+ </$.Body>+ );+ $instances.set(instances);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["child1", "parent", "body"]);+ deleteSelectedInstance();+ expect($selectedInstanceSelector.get()).toEqual(["parent", "body"]);+ });++ test("delete selected legacy shared slot child and select next normalized sibling", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Box ws:id="box"></$.Box>+ <$.Heading ws:id="heading"></$.Heading>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["box", "slot1", "body"]);++ deleteSelectedInstance();++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ expect($selectedInstanceSelector.get()).toEqual([+ "heading",+ fragmentId,+ "slot1",+ "body",+ ]);+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "heading" },+ ]);+ });++ test("delete last selected shared slot child and select visible slot occurrence", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Fragment ws:id="fragment">+ <$.Box ws:id="box"></$.Box>+ </$.Fragment>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["box", "fragment", "slot1", "body"]);++ deleteSelectedInstance();++ expect($selectedInstanceSelector.get()).toEqual(["slot1", "body"]);+ expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);+ expect($instances.get().get("fragment")?.children).toEqual([]);+ });++ test("delete last selected legacy shared slot child and select visible slot occurrence", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Slot ws:id="slot1">+ <$.Box ws:id="box"></$.Box>+ </$.Slot>+ <$.Slot ws:id="slot2">+ {/* same ids */}+ <$.Box ws:id="box"></$.Box>+ </$.Slot>+ </$.Body>+ );+ $instances.set(instances);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ selectInstance(["box", "slot1", "body"]);++ deleteSelectedInstance();++ const fragmentId = expectSlotsShareFragment($instances.get(), [+ "slot1",+ "slot2",+ ]);+ expect($selectedInstanceSelector.get()).toEqual(["slot1", "body"]);+ expect($instances.get().get(fragmentId ?? "")?.children).toEqual([]);+ });+});diff --git a/apps/builder/app/shared/instance-utils/mutation.ts b/apps/builder/app/shared/instance-utils/mutation.tsnew file mode 100644index 0000000000..deaeab0133--- /dev/null+++ b/apps/builder/app/shared/instance-utils/mutation.ts@@ -0,0 +1,1152 @@+// Mutation utilities own changing existing instances in the live tree: delete,+// reparent, wrap, unwrap, convert, and visibility toggles. Put operations that+// move or transform existing nodes here; use insert.ts for new content and+// slot.ts for shared Slot boundary rules.+import { nanoid } from "nanoid";+import { toast } from "@webstudio-is/design-system";+import { builderApi } from "~/shared/builder-api";+import { showAttribute } from "@webstudio-is/react-sdk";+import {+ type Instance,+ type Instances,+ type Props,+ type WebstudioData,+ type WsComponentMeta,+ elementComponent,+ findTreeInstanceIds,+ findTreeInstanceIdsExcludingSlotDescendants,+ isComponentDetachable,+} from "@webstudio-is/sdk";+import { reactPropsToStandardAttributes } from "@webstudio-is/react-sdk";+import {+ $isContentMode,+ $isPreviewMode,+ $registeredComponentMetas,+ $selectedInstancePath,+ $selectedPage,+ $textEditingInstanceSelector,+ getInstancePath,+ selectInstance,+ type InstancePath,+} from "../nano-states";+import { $instances, $project, $props } from "../sync/data-stores";+import { removeByMutable } from "../array-utils";+import { serverSyncStore } from "../sync/sync-stores";+import {+ findAvailableVariables,+ rebindTreeVariablesMutable,+} from "../data-variables";+import {+ isRichTextContent,+ isTreeSatisfyingContentModel,+} from "../content-model";+import { getInstanceLabel } from "~/builder/shared/instance-label";+import { $instanceTags } from "~/builder/features/style-panel/shared/model";+import {+ getDirectSharedSlotChildBoundary,+ getSharedSlotBoundary,+ getSlotFragmentDropTargetMutable,+ getSlotFragmentId,+ normalizeLegacySlotInstancePathMutable,+ normalizeLegacySlotParentInSelectorMutable,+ prepareSlotReparentMutable,+ type SharedSlotDetachResult,+} from "./slot";+import {+ type DroppableTarget,+ type InstanceSelector,+ findLocalStyleSourcesWithinInstances,+ getReparentDropTargetMutable,+} from "./tree";+import { canDeleteInstanceInContentMode, updateWebstudioData } from "./data";+import {+ extractWebstudioFragment,+ insertWebstudioFragmentCopy,+} from "./fragment";+import { deleteLocalStyleSourcesMutable } from "../style-source-utils";++const getSlotChildrenSignature = (instance: Instance) => {+ return JSON.stringify(instance.children);+};++export const setInstanceLabelMutable = (+ instances: Instances,+ instanceId: Instance["id"],+ label: undefined | string+) => {+ const instance = instances.get(instanceId);+ if (instance === undefined) {+ return;+ }+ if (instance.component !== "Slot") {+ instance.label = label;+ return;+ }+ const slotChildrenSignature = getSlotChildrenSignature(instance);+ for (const currentInstance of instances.values()) {+ if (+ currentInstance.component === "Slot" &&+ getSlotChildrenSignature(currentInstance) === slotChildrenSignature+ ) {+ currentInstance.label = label;+ }+ }+};++export const reparentInstanceMutable = (+ data: Omit<WebstudioData, "pages">,+ sourceInstanceSelector: InstanceSelector,+ dropTarget: DroppableTarget+) => {+ const project = $project.get();+ if (project === undefined) {+ return;+ }+ sourceInstanceSelector = normalizeLegacySlotParentInSelectorMutable(+ data.instances,+ sourceInstanceSelector+ );+ const initialSourceInstancePath = getInstancePath(+ sourceInstanceSelector,+ data.instances+ );+ const reparentSource = prepareSharedSlotReparentMutable(+ initialSourceInstancePath ?? [],+ dropTarget+ );+ const sourceInstancePath = reparentSource.instancePath;+ dropTarget = reparentSource.dropTarget;+ sourceInstanceSelector = sourceInstancePath[0]?.instanceSelector;+ if (sourceInstanceSelector === undefined) {+ return;+ }+ const [rootInstanceId] = sourceInstanceSelector;+ // detect if target is one of own descendants+ // prevent reparenting to avoid infinite loop+ const instanceDescendants = findTreeInstanceIds(+ data.instances,+ rootInstanceId+ );+ for (const instanceId of instanceDescendants) {+ if (dropTarget.parentSelector.includes(instanceId)) {+ return;+ }+ }+ // Slot drops must target the shared Fragment before same-parent detection.+ // Legacy slots may still store content directly under Slot, and delaying this+ // normalization lets the first child look like the parent drop container.+ dropTarget =+ getSlotFragmentDropTargetMutable(data.instances, dropTarget) ?? dropTarget;+ // move within same parent+ if (sourceInstanceSelector[1] === dropTarget.parentSelector[0]) {+ reorderInstanceWithinParentMutable(data, rootInstanceId, dropTarget);+ return sourceInstanceSelector;+ }+ // move into another parent+ return moveInstanceToParentMutable(+ data,+ rootInstanceId,+ sourceInstancePath,+ dropTarget+ );+};++export const reparentInstance = (+ sourceInstanceSelector: InstanceSelector,+ dropTarget: DroppableTarget+) => {+ updateWebstudioData((data) => {+ const newSelector = reparentInstanceMutable(+ data,+ sourceInstanceSelector,+ dropTarget+ );+ selectInstance(newSelector);+ });+};++const countInstanceChildReferences = (+ instances: Instances,+ instanceId: Instance["id"]+) => {+ let count = 0;+ for (const instance of instances.values()) {+ for (const child of instance.children) {+ if (child.type === "id" && child.value === instanceId) {+ count += 1;+ }+ }+ }+ return count;+};++const createInstanceChild = (instanceId: Instance["id"]) =>+ ({ type: "id", value: instanceId }) as const;++const findChildReferenceIndex = (+ children: Instance["children"],+ instanceId: Instance["id"]+) =>+ children.findIndex(+ (child) => child.type === "id" && child.value === instanceId+ );++const removeChildReferenceMutable = (+ children: Instance["children"],+ instanceId: Instance["id"]+) => {+ removeByMutable(+ children,+ (child) => child.type === "id" && child.value === instanceId+ );+};++const replaceChildReferenceMutable = (+ parentInstance: Instance,+ previousChildId: Instance["id"],+ nextChildId: Instance["id"]+) => {+ const childIndex = findChildReferenceIndex(+ parentInstance.children,+ previousChildId+ );+ if (childIndex !== -1) {+ parentInstance.children[childIndex] = createInstanceChild(nextChildId);+ }+};++const removeMovedInstanceFromParentMutable = (+ data: Omit<WebstudioData, "pages">,+ instancePath: InstancePath+) => {+ const targetInstance = instancePath[0]?.instance;+ const parentItem = instancePath[1];+ const grandparentItem = instancePath[2];+ if (targetInstance === undefined || parentItem === undefined) {+ return;+ }+ const parentInstance = data.instances.get(parentItem.instance.id);+ if (parentInstance === undefined) {+ return;+ }+ removeChildReferenceMutable(parentInstance.children, targetInstance.id);+ if (+ parentInstance.component === "Fragment" &&+ parentInstance.children.length === 0 &&+ grandparentItem !== undefined &&+ countInstanceChildReferences(data.instances, parentInstance.id) < 2+ ) {+ const grandparentInstance = data.instances.get(grandparentItem.instance.id);+ removeChildReferenceMutable(+ grandparentInstance?.children ?? [],+ parentInstance.id+ );+ data.instances.delete(parentInstance.id);+ }+};++const reorderInstanceWithinParentMutable = (+ data: Omit<WebstudioData, "pages">,+ rootInstanceId: Instance["id"],+ dropTarget: DroppableTarget+) => {+ const [parentId] = dropTarget.parentSelector;+ const parent = data.instances.get(parentId);+ if (parent === undefined) {+ return;+ }+ const prevPosition = findChildReferenceIndex(parent.children, rootInstanceId);+ const child = parent.children[prevPosition];+ if (child === undefined) {+ return;+ }+ parent.children.splice(prevPosition, 1);+ if (dropTarget.position === "end") {+ parent.children.push(child);+ return;+ }+ // When parent is the same, account for removal before reinserting.+ let nextPosition = dropTarget.position;+ if (prevPosition < nextPosition) {+ nextPosition -= 1;+ }+ parent.children.splice(nextPosition, 0, child);+};++const moveInstanceToParentMutable = (+ data: Omit<WebstudioData, "pages">,+ rootInstanceId: Instance["id"],+ sourceInstancePath: InstancePath,+ dropTarget: DroppableTarget+) => {+ // Prepare drop target before removing the instance so empty Slot fragments can+ // be created or reused while the current tree is still intact.+ dropTarget =+ getReparentDropTargetMutable(+ data.instances,+ data.props,+ $registeredComponentMetas.get(),+ dropTarget+ ) ?? dropTarget;+ removeMovedInstanceFromParentMutable(data, sourceInstancePath);+ const [newParentId] = dropTarget.parentSelector;+ const newParent = data.instances.get(newParentId);+ const newChild = createInstanceChild(rootInstanceId);+ if (dropTarget.position === "end") {+ newParent?.children.push(newChild);+ } else {+ newParent?.children.splice(dropTarget.position, 0, newChild);+ }+ rebindTreeVariablesMutable({+ startingInstanceId: rootInstanceId,+ pages: undefined,+ instances: data.instances,+ props: data.props,+ dataSources: data.dataSources,+ resources: data.resources,+ });+ return [rootInstanceId, ...dropTarget.parentSelector];+};++const getDeleteTarget = (+ instances: Instances,+ instancePath: InstancePath+): {+ targetInstance: Instance;+ parentInstance?: Instance;+} => {+ let targetInstance = instancePath[0].instance;+ let parentInstance = instancePath[1]?.instance;+ const grandparentInstance = instancePath[2]?.instance;++ // Delete the wrapper Fragment too when deleting its last child. Empty Slot+ // Fragments use display: contents and do not render correctly on canvas.+ if (+ parentInstance?.component === "Fragment" &&+ parentInstance.children.length === 1 &&+ grandparentInstance &&+ countInstanceChildReferences(instances, parentInstance.id) < 2+ ) {+ targetInstance = parentInstance;+ parentInstance = grandparentInstance;+ }++ return { targetInstance, parentInstance };+};++export const deleteInstanceMutable = (+ data: Omit<WebstudioData, "pages">,+ instancePath: undefined | InstancePath+) => {+ if (instancePath === undefined) {+ return false;+ }+ instancePath = normalizeLegacySlotInstancePathMutable(+ data.instances,+ instancePath+ );+ const {+ instances,+ props,+ styleSourceSelections,+ styleSources,+ styles,+ dataSources,+ resources,+ } = data;+ const { targetInstance, parentInstance } = getDeleteTarget(+ instances,+ instancePath+ );++ const instanceIds = findTreeInstanceIdsExcludingSlotDescendants(+ instances,+ targetInstance.id+ );+ const localStyleSourceIds = findLocalStyleSourcesWithinInstances(+ styleSources.values(),+ styleSourceSelections.values(),+ instanceIds+ );++ // mutate instances from data instead of instance path+ const parentToMutate = data.instances.get(parentInstance?.id as string);+ // may not exist when delete root+ if (parentToMutate) {+ removeChildReferenceMutable(parentToMutate.children, targetInstance.id);+ }++ 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);+ if (prop.type === "resource") {+ resources.delete(prop.value);+ }+ }+ }+ for (const dataSource of dataSources.values()) {+ if (instanceIds.has(dataSource.scopeInstanceId ?? "")) {+ dataSources.delete(dataSource.id);+ if (dataSource.type === "resource") {+ resources.delete(dataSource.resourceId);+ }+ }+ }+ for (const instanceId of instanceIds) {+ styleSourceSelections.delete(instanceId);+ }+ deleteLocalStyleSourcesMutable({+ localStyleSourceIds,+ styleSources,+ styles,+ });+ return true;+};++const cloneSharedSlotFragmentMutable = (+ data: Omit<WebstudioData, "pages">,+ slotId: Instance["id"],+ fragmentId: Instance["id"]+) => {+ if (countInstanceChildReferences(data.instances, fragmentId) < 2) {+ return;+ }+ const projectId = $project.get()?.id ?? "";+ const fragment = extractWebstudioFragment(data, fragmentId);+ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: findAvailableVariables({+ ...data,+ startingInstanceId: slotId,+ }),+ projectId,+ });+ const newFragmentId = newInstanceIds.get(fragmentId);+ const slot = data.instances.get(slotId);+ if (slot === undefined || newFragmentId === undefined) {+ return;+ }+ replaceChildReferenceMutable(slot, fragmentId, newFragmentId);+ return newInstanceIds;+};++export const detachSharedSlotChildrenMutable = (+ data: Omit<WebstudioData, "pages">,+ slotId: Instance["id"]+) => {+ const slot = data.instances.get(slotId);+ const fragmentId = getSlotFragmentId(slot);+ if (fragmentId === undefined) {+ return;+ }+ cloneSharedSlotFragmentMutable(data, slotId, fragmentId);+};++const detachSharedSlotContentMutableWithMap = (+ data: Omit<WebstudioData, "pages">,+ instancePath: InstancePath+): SharedSlotDetachResult => {+ const boundary = getSharedSlotBoundary(instancePath);+ if (boundary === undefined) {+ return { instancePath };+ }+ const newInstanceIds = cloneSharedSlotFragmentMutable(+ data,+ boundary.slotId,+ boundary.fragmentId+ );+ if (newInstanceIds === undefined) {+ return { instancePath };+ }+ const newInstanceSelector = instancePath[0].instanceSelector.map(+ (instanceId, index) =>+ index < boundary.slotIndex+ ? (newInstanceIds.get(instanceId) ?? instanceId)+ : instanceId+ );+ return {+ instancePath:+ getInstancePath(newInstanceSelector, data.instances) ?? instancePath,+ newInstanceIds,+ fragmentId: boundary.fragmentId,+ slotId: boundary.slotId,+ };+};++const prepareSharedSlotReparentMutable = (+ instancePath: InstancePath,+ dropTarget: DroppableTarget+): { instancePath: InstancePath; dropTarget: DroppableTarget } => {+ // Reparenting a Slot child mutates the shared Fragment. When the target is+ // outside the Slot, the moved instance becomes independent at its new+ // location and is removed from every occurrence of that Slot.+ return prepareSlotReparentMutable({+ instancePath,+ dropTarget,+ });+};++export const detachSharedSlotContentMutable = (+ data: Omit<WebstudioData, "pages">,+ instancePath: InstancePath+) => {+ return detachSharedSlotContentMutableWithMap(data, instancePath).instancePath;+};++const unwrapDirectSharedSlotChildWithSiblingsMutable = ({+ data,+ selectedItem,+ fragmentItem,+ slotItem,+}: {+ data: WebstudioData;+ selectedItem: InstancePath[number];+ fragmentItem: InstancePath[number];+ slotItem: InstancePath[number];+}) => {+ if (fragmentItem.instance.children.length <= 1) {+ return;+ }+ const slotParentId = slotItem.instanceSelector[1];+ const slotParent = data.instances.get(slotParentId);+ if (slotParent === undefined) {+ return;+ }+ removeChildReferenceMutable(+ fragmentItem.instance.children,+ selectedItem.instance.id+ );+ const slotPosition = findChildReferenceIndex(+ slotParent.children,+ slotItem.instance.id+ );+ if (slotPosition === -1) {+ return;+ }+ slotParent.children.splice(+ slotPosition + 1,+ 0,+ createInstanceChild(selectedItem.instance.id)+ );+ const nextSelectedInstanceSelector = [+ selectedItem.instance.id,+ ...slotItem.instanceSelector.slice(1),+ ];+ const matches = isTreeSatisfyingContentModel({+ instances: data.instances,+ props: data.props,+ metas: $registeredComponentMetas.get(),+ instanceSelector: nextSelectedInstanceSelector,+ });+ if (matches === false) {+ toast.error("Cannot unwrap instance");+ throw Error("Abort transaction");+ }+ return nextSelectedInstanceSelector;+};++const prepareUnwrapInstancePathMutable = (+ data: WebstudioData,+ instancePath: InstancePath+): {+ instancePath: InstancePath;+ directSlotBoundary?: ReturnType<typeof getDirectSharedSlotChildBoundary>;+} => {+ const normalizedInstancePath = normalizeLegacySlotInstancePathMutable(+ data.instances,+ instancePath+ );+ if (getDirectSharedSlotChildBoundary(normalizedInstancePath) === undefined) {+ return { instancePath: normalizedInstancePath };+ }+ return {+ instancePath: normalizedInstancePath,+ directSlotBoundary: getDirectSharedSlotChildBoundary(+ normalizedInstancePath+ ),+ };+};++const getUnwrappedInstanceSelector = ({+ selectedItem,+ parentItem,+}: {+ selectedItem: { instance: { id: Instance["id"] } };+ parentItem: { instanceSelector: InstanceSelector };+}) => [selectedItem.instance.id, ...parentItem.instanceSelector.slice(1)];++const validateUnwrappedInstance = ({+ instances,+ props,+ metas,+ selectedItem,+ parentItem,+}: {+ instances: Map<string, Instance>;+ props: Props;+ metas: Map<string, WsComponentMeta>;+ selectedItem: { instance: { id: Instance["id"] } };+ parentItem: { instanceSelector: InstanceSelector };+}) => {+ return isTreeSatisfyingContentModel({+ instances,+ props,+ metas,+ instanceSelector: getUnwrappedInstanceSelector({+ selectedItem,+ parentItem,+ }),+ });+};++export const unwrapInstanceMutable = ({+ instances,+ props,+ metas,+ selectedItem,+ parentItem,+}: {+ instances: Map<string, Instance>;+ props: Props;+ metas: Map<string, WsComponentMeta>;+ selectedItem: {+ instanceSelector: InstanceSelector;+ instance: { id: string };+ };+ parentItem: { instanceSelector: InstanceSelector; instance: { id: string } };+}): { success: boolean; error?: string } => {+ // Check if the selected instance is rich text content (like Bold, Italic in Paragraph)+ if (+ isRichTextContent({+ instanceSelector: selectedItem.instanceSelector,+ instances,+ props,+ metas,+ })+ ) {+ return { success: false, error: "Cannot unwrap textual instance" };+ }++ const parentInstance = instances.get(parentItem.instance.id);+ const selectedInstance = instances.get(selectedItem.instance.id);+ if (!parentInstance || !selectedInstance) {+ return { success: false, error: "Instance not found" };+ }++ // Get grandparent to replace parent with selected+ const grandparentId = parentItem.instanceSelector[1];+ if (!grandparentId) {+ return { success: false, error: "Cannot unwrap instance at root level" };+ }+ const grandparentInstance = instances.get(grandparentId);+ if (!grandparentInstance) {+ return { success: false, error: "Grandparent instance not found" };+ }++ const selectedParentId = selectedItem.instanceSelector[1];+ const selectedParentInstance = instances.get(selectedParentId);+ if (+ parentInstance.component === "Slot" &&+ selectedParentInstance?.component === "Fragment" &&+ selectedItem.instanceSelector[2] === parentItem.instance.id &&+ selectedParentInstance.children.length === 1 &&+ selectedParentInstance.children[0]?.type === "id" &&+ selectedParentInstance.children[0].value === selectedItem.instance.id+ ) {+ removeChildReferenceMutable(+ selectedParentInstance.children,+ selectedItem.instance.id+ );+ replaceChildReferenceMutable(+ grandparentInstance,+ parentItem.instance.id,+ selectedItem.instance.id+ );++ if (countInstanceChildReferences(instances, parentItem.instance.id) === 0) {+ instances.delete(parentItem.instance.id);+ }+ if (+ countInstanceChildReferences(instances, selectedParentInstance.id) === 0+ ) {+ instances.delete(selectedParentInstance.id);+ }++ const matches = validateUnwrappedInstance({+ instances,+ props,+ metas,+ selectedItem,+ parentItem,+ });+ if (matches === false) {+ return { success: false, error: "Cannot unwrap instance" };+ }++ return { success: true };+ }++ // Slot children may be rendered through multiple slot instances with the same+ // ids. Unwrapping a direct Slot child moves the child out of shared Slot+ // content, so the child is removed from all occurrences of that Slot.+ if (instances.get(parentItem.instanceSelector[1])?.component === "Slot") {+ replaceChildReferenceMutable(+ grandparentInstance,+ parentItem.instance.id,+ selectedItem.instance.id+ );++ const matches = validateUnwrappedInstance({+ instances,+ props,+ metas,+ selectedItem,+ parentItem,+ });+ if (matches === false) {+ return { success: false, error: "Cannot unwrap instance" };+ }++ return { success: true };+ }++ // Remove selected instance from parent's children+ const selectedIndexInParent = findChildReferenceIndex(+ parentInstance.children,+ selectedItem.instance.id+ );+ if (selectedIndexInParent !== -1) {+ parentInstance.children.splice(selectedIndexInParent, 1);+ }++ // If parent has no more children, delete it+ if (parentInstance.children.length === 0) {+ instances.delete(parentItem.instance.id);+ }++ // Add selected instance to grandparent at parent's position+ const parentIndex = findChildReferenceIndex(+ grandparentInstance.children,+ parentItem.instance.id+ );+ if (parentIndex !== -1) {+ if (parentInstance.children.length === 0) {+ // Replace parent with selected if parent is now empty+ replaceChildReferenceMutable(+ grandparentInstance,+ parentItem.instance.id,+ selectedItem.instance.id+ );+ } else {+ // Insert selected after parent if parent still has children+ grandparentInstance.children.splice(+ parentIndex + 1,+ 0,+ createInstanceChild(selectedItem.instance.id)+ );+ }+ }++ const matches = validateUnwrappedInstance({+ instances,+ props,+ metas,+ selectedItem,+ parentItem,+ });+ if (matches === false) {+ return { success: false, error: "Cannot unwrap instance" };+ }++ return { success: true };+};++export const canUnwrapInstance = (instancePath: InstancePath) => {+ // Need at least 3 levels: selected, parent, and grandparent+ // Can't unwrap if there's no grandparent to move the selected instance to+ if (instancePath.length < 3) {+ return false;+ }+ const [selectedItem, parentItem] = instancePath;++ // Prevent unwrapping if parent is the root instance (e.g., Body)+ const rootInstanceId = $selectedPage.get()?.rootInstanceId;+ if (+ rootInstanceId !== undefined &&+ parentItem.instance.id === rootInstanceId+ ) {+ return false;+ }+ if (parentItem.instance.component === "Slot") {+ return true;+ }++ // Check if the selected instance is rich text content (like Bold, Italic in Paragraph)+ const instances = $instances.get();+ const props = $props.get();+ const metas = $registeredComponentMetas.get();++ if (+ isRichTextContent({+ instanceSelector: selectedItem.instanceSelector,+ instances,+ props,+ metas,+ })+ ) {+ return false;+ }++ return true;+};++export const toggleInstanceShow = (instanceId: Instance["id"]) => {+ serverSyncStore.createTransaction([$props], (props) => {+ const allProps = Array.from(props.values());+ const instanceProps = allProps.filter(+ (prop) => prop.instanceId === instanceId+ );+ let showProp = instanceProps.find((prop) => prop.name === showAttribute);++ // Toggle the show value+ const newValue = showProp?.type === "boolean" ? !showProp.value : false;++ if (showProp === undefined) {+ showProp = {+ id: nanoid(),+ instanceId,+ name: showAttribute,+ type: "boolean",+ value: newValue,+ };+ }+ if (showProp.type === "boolean") {+ props.set(showProp.id, { ...showProp, value: newValue });+ }+ });+};++export const wrapInstance = (component: string, tag?: string) => {+ const instancePath = $selectedInstancePath.get();+ // global root or body are selected+ if (instancePath === undefined || instancePath.length === 1) {+ return;+ }+ const newInstanceId = nanoid();+ let newInstanceSelector: InstanceSelector | undefined;+ const metas = $registeredComponentMetas.get();++ try {+ updateWebstudioData((data) => {+ const nextInstancePath = normalizeLegacySlotInstancePathMutable(+ data.instances,+ instancePath+ );+ const [selectedItem, parentItem] = nextInstancePath;+ if (parentItem === undefined) {+ return;+ }+ const selectedInstance = selectedItem.instance;+ const nextInstanceSelector = [+ newInstanceId,+ ...parentItem.instanceSelector,+ ];+ newInstanceSelector = nextInstanceSelector;+ const isContent = isRichTextContent({+ instanceSelector: selectedItem.instanceSelector,+ instances: data.instances,+ props: data.props,+ metas,+ });+ if (isContent) {+ toast.error(`Cannot wrap textual content`);+ throw Error("Abort transaction");+ }+ const newInstance: Instance = {+ type: "instance",+ id: newInstanceId,+ component,+ children: [createInstanceChild(selectedInstance.id)],+ };++ if (tag || component === elementComponent) {+ newInstance.tag = tag ?? "div";+ }+ const parentInstance = data.instances.get(parentItem.instance.id);+ data.instances.set(newInstanceId, newInstance);+ if (parentInstance) {+ replaceChildReferenceMutable(+ parentInstance,+ selectedInstance.id,+ newInstanceId+ );+ }++ const isSatisfying = isTreeSatisfyingContentModel({+ instances: data.instances,+ props: data.props,+ metas,+ instanceSelector: nextInstanceSelector,+ });++ if (isSatisfying === false) {+ const label = getInstanceLabel({ component, tag });+ toast.error(`Cannot wrap in ${label}`);+ throw Error("Abort transaction");+ }+ });+ selectInstance(newInstanceSelector);+ } catch {+ // do nothing+ }+};++// Check if an instance can be converted to a specific component or tag+export const canConvertInstance = (+ selectedInstanceId: string,+ selectedInstanceSelector: string[],+ component: string,+ tag: string | undefined,+ instances: Instances,+ props: Props,+ metas: Map<Instance["component"], WsComponentMeta>+): boolean => {+ const selectedInstance = instances.get(selectedInstanceId);++ if (!selectedInstance) {+ return false;+ }++ // Create a test instance with the new component/tag+ const testInstance: Instance = {+ ...selectedInstance,+ component,+ };++ if (tag || component === elementComponent) {+ testInstance.tag = tag ?? "div";+ } else {+ // For components with presetStyle (like Heading, Box), infer default tag+ const meta = metas.get(component);+ const defaultTag = Object.keys(+ (meta as { presetStyle?: Record<string, unknown> })?.presetStyle ?? {}+ ).at(0);+ if (defaultTag) {+ testInstance.tag = defaultTag;+ }+ }++ const newInstances = new Map(instances);+ newInstances.set(testInstance.id, testInstance);++ // Validate the converted instance satisfies content model+ return isTreeSatisfyingContentModel({+ instances: newInstances,+ props,+ metas,+ instanceSelector: selectedInstanceSelector,+ });+};++export const convertInstance = (component: string, tag?: string) => {+ const instancePath = $selectedInstancePath.get();+ // global root or body are selected+ if (instancePath === undefined || instancePath.length === 1) {+ return;+ }+ const metas = $registeredComponentMetas.get();+ const instanceTags = $instanceTags.get();+ try {+ updateWebstudioData((data) => {+ const [initialSelectedItem] = instancePath;+ if (initialSelectedItem.instance.component === "Slot") {+ getSlotFragmentDropTargetMutable(data.instances, {+ parentSelector: initialSelectedItem.instanceSelector,+ position: "end",+ });+ }+ const nextInstancePath = normalizeLegacySlotInstancePathMutable(+ data.instances,+ instancePath+ );+ const [selectedItem] = nextInstancePath;+ const selectedInstance = selectedItem.instance;+ const selectedInstanceSelector = selectedItem.instanceSelector;+ if (selectedInstance.component === "Slot" && component !== "Slot") {+ detachSharedSlotChildrenMutable(data, selectedInstance.id);+ }+ const instance = data.instances.get(selectedInstance.id);+ if (instance === undefined) {+ return;+ }+ instance.component = component;+ // convert to specified tag or with currently used+ if (tag || component === elementComponent) {+ instance.tag = tag ?? instanceTags.get(selectedInstance.id) ?? "div";+ // delete legacy tag prop if specified+ for (const prop of data.props.values()) {+ if (prop.instanceId !== selectedInstance.id) {+ continue;+ }+ if (prop.name === "tag") {+ data.props.delete(prop.id);+ continue;+ }+ const newName = reactPropsToStandardAttributes[prop.name];+ if (newName) {+ const newId = `${prop.instanceId}:${newName}`;+ data.props.delete(prop.id);+ data.props.set(newId, { ...prop, id: newId, name: newName });+ }+ }+ }+ const isSatisfying = isTreeSatisfyingContentModel({+ instances: data.instances,+ props: data.props,+ metas,+ instanceSelector: selectedInstanceSelector,+ });+ if (isSatisfying === false) {+ const label = getInstanceLabel({ component, tag });+ toast.error(`Cannot convert to ${label}`);+ throw Error("Abort transaction");+ }+ });+ } catch {+ // do nothing+ }+};++export const unwrapInstance = () => {+ const instancePath = $selectedInstancePath.get();+ if (instancePath === undefined || !canUnwrapInstance(instancePath)) {+ return;+ }++ try {+ updateWebstudioData((data) => {+ const { instancePath: nextInstancePath, directSlotBoundary } =+ prepareUnwrapInstancePathMutable(data, instancePath);+ const [selectedItem, defaultParentItem] = nextInstancePath;+ // Unwrapping a direct Slot child places that child outside the Slot, so it+ // intentionally leaves shared Slot content and must use the Slot item as+ // the parent to replace.+ const parentItem = directSlotBoundary?.slotItem ?? defaultParentItem;+ if (parentItem === undefined) {+ return;+ }++ const directSlotUnwrapSelector = directSlotBoundary+ ? unwrapDirectSharedSlotChildWithSiblingsMutable({+ data,+ selectedItem,+ fragmentItem: directSlotBoundary.fragmentItem,+ slotItem: parentItem,+ })+ : undefined;+ if (directSlotUnwrapSelector !== undefined) {+ selectInstance(directSlotUnwrapSelector);+ return;+ }++ const result = unwrapInstanceMutable({+ instances: data.instances,+ props: data.props,+ metas: $registeredComponentMetas.get(),+ selectedItem,+ parentItem,+ });++ if (!result.success) {+ toast.error(result.error ?? "Cannot unwrap instance");+ throw Error("Abort transaction");+ }++ // After unwrap, select the child that replaced the parent.+ selectInstance(+ getUnwrappedInstanceSelector({ selectedItem, parentItem })+ );+ });+ } catch {+ // do nothing+ }+};++export const deleteSelectedInstance = () => {+ if ($isPreviewMode.get()) {+ return;+ }+ const textEditingInstanceSelector = $textEditingInstanceSelector.get();+ const instancePath = $selectedInstancePath.get();+ // cannot delete instance while editing+ if (textEditingInstanceSelector) {+ return;+ }+ if (instancePath === undefined || instancePath.length === 1) {+ return;+ }+ const [selectedItem] = instancePath;+ const selectedInstanceSelector = selectedItem.instanceSelector;+ const instances = $instances.get();+ if (!isComponentDetachable(selectedItem.instance.component)) {+ toast.error(+ "This instance can not be moved outside of its parent component."+ );+ return false;+ }++ if ($isContentMode.get()) {+ if (+ canDeleteInstanceInContentMode({+ instanceSelector: selectedInstanceSelector,+ instances,+ }) === false+ ) {+ builderApi.toast.info("You can't delete this instance in content mode.");+ return;+ }+ }++ updateWebstudioData((data) => {+ const normalizedInstancePath = normalizeLegacySlotInstancePathMutable(+ data.instances,+ instancePath+ );+ const [normalizedSelectedItem, parentItem] = normalizedInstancePath;+ if (parentItem === undefined) {+ return;+ }++ // Find next selection after any legacy Slot normalization, otherwise the+ // command can select a direct Slot child path that no longer exists.+ let newSelectedInstanceSelector: undefined | InstanceSelector;+ const parentInstanceSelector = parentItem.instanceSelector;+ const siblingIds = parentItem.instance.children+ .filter((child) => child.type === "id")+ .map((child) => child.value);+ const position = siblingIds.indexOf(normalizedSelectedItem.instance.id);+ const siblingId = siblingIds[position + 1] ?? siblingIds[position - 1];+ if (siblingId) {+ // select next or previous sibling if possible+ newSelectedInstanceSelector = [siblingId, ...parentInstanceSelector];+ } else {+ const grandparentItem = normalizedInstancePath[2];+ // The Slot Fragment is an implementation detail and should never become+ // the visible selection when deleting the last Slot child.+ newSelectedInstanceSelector = getDirectSharedSlotChildBoundary(+ normalizedInstancePath+ )+ ? grandparentItem?.instanceSelector+ : parentInstanceSelector;+ }++ if (deleteInstanceMutable(data, normalizedInstancePath)) {+ selectInstance(newSelectedInstanceSelector);+ }+ });+};diff --git a/apps/builder/app/shared/instance-utils/slot.test.ts b/apps/builder/app/shared/instance-utils/slot.test.tsnew file mode 100644index 0000000000..89d57b0018--- /dev/null+++ b/apps/builder/app/shared/instance-utils/slot.test.ts@@ -0,0 +1,457 @@+import { describe, expect, test } from "vitest";+import type { Instance } from "@webstudio-is/sdk";+import type { InstancePath } from "../nano-states";+import {+ findClosestSlot,+ getDirectSharedSlotChildBoundary,+ getSharedSlotBoundary,+ getSlotFragmentId,+ getSlotFragmentDropTargetMutable,+ normalizeLegacySlotParentInSelectorMutable,+ prepareSlotReparentMutable,+} from "./slot";+import {+ expectSlotTreeIntegrity,+ expectSlotsShareFragment,+} from "../slot-test-utils";++const instance = (+ id: string,+ component: string,+ children: Instance["children"] = []+): Instance => ({+ type: "instance",+ id,+ component,+ children,+});++const item = (selector: string[], component: string, children = []) => ({+ instanceSelector: selector,+ instance: instance(selector[0], component, children),+});++describe("slot utils", () => {+ test("finds closest slot in an instance selector", () => {+ const slot = instance("slot", "Slot");+ expect(+ findClosestSlot(+ new Map([+ ["body", instance("body", "Body")],+ ["slot", slot],+ ["box", instance("box", "Box")],+ ]),+ ["box", "slot", "body"]+ )+ ).toBe(slot);+ });++ test("finds shared slot fragment in an instance path", () => {+ const path = [+ item(["box", "fragment", "slot", "body"], "Box"),+ item(["fragment", "slot", "body"], "Fragment"),+ item(["slot", "body"], "Slot"),+ item(["body"], "Body"),+ ] satisfies InstancePath;++ expect(getSharedSlotBoundary(path)).toMatchObject({+ slotIndex: 2,+ slotParentItem: path[3],+ fragmentId: "fragment",+ slotId: "slot",+ isDirectChild: true,+ });+ expect(getDirectSharedSlotChildBoundary(path)).toMatchObject({+ fragmentId: "fragment",+ slotId: "slot",+ });+ expect(+ getSlotFragmentId(+ instance("slot", "Slot", [{ type: "id", value: "fragment" }])+ )+ ).toBe("fragment");+ expect(+ getSharedSlotBoundary([+ item(["box", "body"], "Box"),+ item(["body"], "Body"),+ ])+ ).toBeUndefined();++ const nestedPath = [+ item(["text", "box", "fragment", "slot", "body"], "Text"),+ item(["box", "fragment", "slot", "body"], "Box"),+ item(["fragment", "slot", "body"], "Fragment"),+ item(["slot", "body"], "Slot"),+ item(["body"], "Body"),+ ] satisfies InstancePath;+ expect(getSharedSlotBoundary(nestedPath)).toMatchObject({+ slotIndex: 3,+ fragmentId: "fragment",+ slotId: "slot",+ isDirectChild: false,+ });+ expect(getDirectSharedSlotChildBoundary(nestedPath)).toBeUndefined();+ });++ test("keeps same-slot reparent shared without detaching", () => {+ const path = [+ item(["heading", "fragment", "slot1", "body"], "Heading"),+ item(["fragment", "slot1", "body"], "Fragment"),+ item(["slot1", "body"], "Slot"),+ item(["body"], "Body"),+ ] satisfies InstancePath;+ const result = prepareSlotReparentMutable({+ instancePath: path,+ dropTarget: {+ parentSelector: ["fragment", "slot1", "body"],+ position: "end",+ },+ });++ expect(result.instancePath).toBe(path);+ expect(result.dropTarget).toEqual({+ parentSelector: ["fragment", "slot1", "body"],+ position: "end",+ });+ });++ test("keeps reparent shared when target path is inside the same slot fragment", () => {+ const path = [+ item(["box", "fragment", "slot", "body"], "Box"),+ item(["fragment", "slot", "body"], "Fragment"),+ item(["slot", "body"], "Slot"),+ item(["body"], "Body"),+ ] satisfies InstancePath;+ const result = prepareSlotReparentMutable({+ instancePath: path,+ dropTarget: {+ parentSelector: ["box", "fragment", "slot", "body"],+ position: "end",+ },+ });++ expect(result.instancePath).toBe(path);+ expect(result.dropTarget).toEqual({+ parentSelector: ["box", "fragment", "slot", "body"],+ position: "end",+ });+ });++ test("keeps reparent shared when target is the visible slot occurrence", () => {+ const path = [+ item(["box", "fragment", "slot", "body"], "Box"),+ item(["fragment", "slot", "body"], "Fragment"),+ item(["slot", "body"], "Slot"),+ item(["body"], "Body"),+ ] satisfies InstancePath;+ const result = prepareSlotReparentMutable({+ instancePath: path,+ dropTarget: {+ parentSelector: ["slot", "body"],+ position: "end",+ },+ });++ expect(result.instancePath).toBe(path);+ expect(result.dropTarget).toEqual({+ parentSelector: ["slot", "body"],+ position: "end",+ });+ });++ test("keeps reparent shared when target leaves shared slot content", () => {+ const path = [+ item(["box", "fragment", "slot", "body"], "Box"),+ item(["fragment", "slot", "body"], "Fragment"),+ item(["slot", "body"], "Slot"),+ item(["body"], "Body"),+ ] satisfies InstancePath;+ const result = prepareSlotReparentMutable({+ instancePath: path,+ dropTarget: {+ parentSelector: ["body"],+ position: "end",+ },+ });++ expect(result.instancePath).toBe(path);+ expect(result.dropTarget).toEqual({+ parentSelector: ["body"],+ position: "end",+ });+ });++ test("normalizes matching legacy slot occurrences to one shared fragment", () => {+ const instances = new Map([+ [+ "slot1",+ instance("slot1", "Slot", [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]),+ ],+ [+ "slot2",+ instance("slot2", "Slot", [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]),+ ],+ ["box", instance("box", "Box")],+ ["heading", instance("heading", "Heading")],+ ]);++ const dropTarget = getSlotFragmentDropTargetMutable(instances, {+ parentSelector: ["slot1", "body"],+ position: "end",+ });++ const fragmentId = instances.get("slot1")?.children[0]?.value;+ expect(dropTarget).toEqual({+ parentSelector: [fragmentId, "slot1", "body"],+ position: "end",+ });+ expect(instances.get("slot1")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect(instances.get("slot2")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect(instances.get(fragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]);+ });++ test("keeps canonical slot fragment drop target without normalizing", () => {+ const instances = new Map([+ ["slot", instance("slot", "Slot", [{ type: "id", value: "fragment" }])],+ [+ "fragment",+ instance("fragment", "Fragment", [{ type: "id", value: "box" }]),+ ],+ ["box", instance("box", "Box")],+ ]);++ const dropTarget = getSlotFragmentDropTargetMutable(instances, {+ parentSelector: ["slot", "body"],+ position: "end",+ });++ expect(dropTarget).toEqual({+ parentSelector: ["fragment", "slot", "body"],+ position: "end",+ });+ expect(instances.get("slot")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(instances.get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ });++ test("normalizes legacy slot occurrence to existing canonical shared fragment", () => {+ const instances = new Map([+ ["slot1", instance("slot1", "Slot", [{ type: "id", value: "fragment" }])],+ [+ "fragment",+ instance("fragment", "Fragment", [{ type: "id", value: "box" }]),+ ],+ ["slot2", instance("slot2", "Slot", [{ type: "id", value: "box" }])],+ ["box", instance("box", "Box")],+ ]);++ const dropTarget = getSlotFragmentDropTargetMutable(instances, {+ parentSelector: ["slot2", "body"],+ position: "end",+ });++ expect(dropTarget).toEqual({+ parentSelector: ["fragment", "slot2", "body"],+ position: "end",+ });+ expect(instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(instances.get("fragment")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ });++ test("normalizes matching empty legacy slot occurrences to one shared fragment", () => {+ const instances = new Map([+ ["slot1", instance("slot1", "Slot")],+ ["slot2", instance("slot2", "Slot")],+ ]);++ const dropTarget = getSlotFragmentDropTargetMutable(instances, {+ parentSelector: ["slot1", "body"],+ position: "end",+ });++ const fragmentId = instances.get("slot1")?.children[0]?.value;+ expect(dropTarget).toEqual({+ parentSelector: [fragmentId, "slot1", "body"],+ position: "end",+ });+ expect(instances.get("slot1")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect(instances.get("slot2")?.children).toEqual([+ { type: "id", value: fragmentId },+ ]);+ expect(instances.get(fragmentId ?? "")?.children).toEqual([]);+ });++ test("normalizes empty legacy slot occurrence to existing empty canonical fragment", () => {+ const instances = new Map([+ ["slot1", instance("slot1", "Slot", [{ type: "id", value: "fragment" }])],+ ["fragment", instance("fragment", "Fragment")],+ ["slot2", instance("slot2", "Slot")],+ ]);++ const dropTarget = getSlotFragmentDropTargetMutable(instances, {+ parentSelector: ["slot2", "body"],+ position: "end",+ });++ expect(dropTarget).toEqual({+ parentSelector: ["fragment", "slot2", "body"],+ position: "end",+ });+ expect(instances.get("slot1")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(instances.get("fragment")?.children).toEqual([]);+ });++ test("normalizes only legacy slots with the same children", () => {+ const instances = new Map([+ [+ "slot1",+ instance("slot1", "Slot", [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]),+ ],+ ["slot2", instance("slot2", "Slot", [{ type: "id", value: "box" }])],+ ["box", instance("box", "Box")],+ ["heading", instance("heading", "Heading")],+ ]);++ const normalizedSelector = normalizeLegacySlotParentInSelectorMutable(+ instances,+ ["box", "slot1", "body"]+ );++ const slot1FragmentId = instances.get("slot1")?.children[0]?.value;+ expect(normalizedSelector).toEqual([+ "box",+ slot1FragmentId,+ "slot1",+ "body",+ ]);+ expect(instances.get("slot1")?.children).toEqual([+ { type: "id", value: slot1FragmentId },+ ]);+ expect(instances.get(slot1FragmentId ?? "")?.children).toEqual([+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]);+ expect(instances.get("slot2")?.children).toEqual([+ { type: "id", value: "box" },+ ]);+ });++ test("normalizes generated mixed slot shapes to canonical shared fragments", () => {+ const childSets = [+ ["box"],+ ["box", "heading"],+ ["box", "heading", "paragraph"],+ [],+ ];++ for (const [childSetIndex, childIds] of childSets.entries()) {+ for (let shapeMask = 0; shapeMask < 16; shapeMask += 1) {+ const fragmentId = `fragment${childSetIndex}-${shapeMask}`;+ const instances = new Map<Instance["id"], Instance>();+ instances.set("body", instance("body", "Body"));+ for (const childId of childIds) {+ instances.set(childId, instance(childId, "Box"));+ }+ instances.set(+ fragmentId,+ instance(+ fragmentId,+ "Fragment",+ childIds.map((childId) => ({ type: "id" as const, value: childId }))+ )+ );++ const canonicalSlotIds: string[] = [];+ const legacySlotIds: string[] = [];+ for (let slotIndex = 0; slotIndex < 4; slotIndex += 1) {+ const slotId = `slot${childSetIndex}-${shapeMask}-${slotIndex}`;+ const isCanonical = (shapeMask & (1 << slotIndex)) !== 0;+ if (isCanonical) {+ canonicalSlotIds.push(slotId);+ instances.set(+ slotId,+ instance(slotId, "Slot", [{ type: "id", value: fragmentId }])+ );+ } else {+ legacySlotIds.push(slotId);+ instances.set(+ slotId,+ instance(+ slotId,+ "Slot",+ childIds.map((childId) => ({+ type: "id" as const,+ value: childId,+ }))+ )+ );+ }+ }+ if (legacySlotIds.length === 0) {+ continue;+ }++ const targetSlotId = legacySlotIds[0];+ const dropTarget = getSlotFragmentDropTargetMutable(instances, {+ parentSelector: [targetSlotId, "body"],+ position: "end",+ });+ expect(dropTarget).toBeDefined();+ if (dropTarget === undefined) {+ throw new Error("Expected slot drop target");+ }+ const normalizedFragmentId =+ canonicalSlotIds.length === 0+ ? dropTarget.parentSelector[0]+ : fragmentId;++ expect(dropTarget).toEqual({+ parentSelector: [normalizedFragmentId, targetSlotId, "body"],+ position: "end",+ });+ if (canonicalSlotIds.length === 0) {+ expect(normalizedFragmentId).not.toBe(fragmentId);+ }+ expectSlotTreeIntegrity(instances);+ const slotIds = [...canonicalSlotIds, ...legacySlotIds];+ expectSlotsShareFragment(+ instances,+ slotIds as [string, string, ...string[]]+ );+ }+ }+ });+});diff --git a/apps/builder/app/shared/instance-utils/slot.ts b/apps/builder/app/shared/instance-utils/slot.tsnew file mode 100644index 0000000000..b4b7ebae7e--- /dev/null+++ b/apps/builder/app/shared/instance-utils/slot.ts@@ -0,0 +1,253 @@+// Slot utilities own the business rules for shared Slot content. Put Slot+// Fragment normalization, boundary detection, and Slot-specific drop/reparent+// helpers here; callers decide which user operation is being performed.+import { nanoid } from "nanoid";+import type { Instance, Instances } from "@webstudio-is/sdk";+import type { DroppableTarget, InstanceSelector } from "./tree";+import type { InstancePath } from "../nano-states/instances";++export type SharedSlotDetachResult = {+ instancePath: InstancePath;+ newInstanceIds?: Map<Instance["id"], Instance["id"]>;+ fragmentId?: Instance["id"];+ slotId?: Instance["id"];+};++export type SharedSlotBoundary = {+ slotIndex: number;+ fragmentItem: InstancePath[number];+ slotItem: InstancePath[number];+ slotParentItem?: InstancePath[number];+ fragmentId: Instance["id"];+ slotId: Instance["id"];+ isDirectChild: boolean;+};++// Slot content contract:+// - Slot children are shared content, stored under the Slot's Fragment child.+// - Any edit that stays inside that Fragment must update all occurrences of+// the same Slot: insert, delete, reorder, wrap, duplicate, and reparent.+// - Moving or copying content into a Slot makes it part of that shared content.+// - Content becomes independent only when it crosses out of the Slot boundary.+// - Unwrapping a direct Slot child crosses that boundary; unwrapping nested+// descendants inside the Fragment does not.+const findSharedSlotIndex = (instancePath: InstancePath) => {+ return instancePath.findIndex(+ (item, index) =>+ item.instance.component === "Slot" &&+ instancePath[index - 1]?.instance.component === "Fragment"+ );+};++export const getSharedSlotBoundary = (+ instancePath: InstancePath+): undefined | SharedSlotBoundary => {+ const slotIndex = findSharedSlotIndex(instancePath);+ if (slotIndex === -1) {+ return;+ }+ const fragmentItem = instancePath[slotIndex - 1];+ const slotItem = instancePath[slotIndex];+ if (fragmentItem === undefined || slotItem === undefined) {+ return;+ }+ return {+ slotIndex,+ fragmentItem,+ slotItem,+ slotParentItem: instancePath[slotIndex + 1],+ fragmentId: fragmentItem.instance.id,+ slotId: slotItem.instance.id,+ isDirectChild: slotIndex === 2,+ };+};++export const getDirectSharedSlotChildBoundary = (+ instancePath: InstancePath+) => {+ const boundary = getSharedSlotBoundary(instancePath);+ if (boundary?.isDirectChild !== true) {+ return;+ }+ return boundary;+};++export const findClosestSlot = (+ instances: Instances,+ instanceSelector: InstanceSelector+) => {+ for (const instanceId of instanceSelector) {+ const instance = instances.get(instanceId);+ if (instance?.component === "Slot") {+ return instance;+ }+ }+};++const areInstanceChildrenEqual = (+ left: Instance["children"],+ right: Instance["children"]+) => {+ if (left.length !== right.length) {+ return false;+ }+ return left.every((leftChild, index) => {+ const rightChild = right[index];+ if (rightChild === undefined || leftChild.type !== rightChild.type) {+ return false;+ }+ if (leftChild.type === "id") {+ return rightChild.type === "id" && leftChild.value === rightChild.value;+ }+ return leftChild.value === rightChild.value;+ });+};++export const getSlotFragmentDropTargetMutable = (+ instances: Instances,+ dropTarget: DroppableTarget+) => {+ const [parentId] = dropTarget.parentSelector;+ const instance = instances.get(parentId);+ if (instance === undefined) {+ return;+ }+ // Slot content is shared by every rendered occurrence of the same Slot.+ // The Slot stores a single Fragment child as the shared content root; editing+ // inside that Fragment should update all occurrences of the Slot.+ if (instance.component === "Slot") {+ const findReusableFragmentId = (legacyChildren: Instance["children"]) => {+ for (const candidate of instances.values()) {+ if (+ candidate.component !== "Slot" ||+ candidate.children[0]?.type !== "id"+ ) {+ continue;+ }+ const fragment = instances.get(candidate.children[0].value);+ if (+ fragment?.component === "Fragment" &&+ areInstanceChildrenEqual(fragment.children, legacyChildren)+ ) {+ return fragment.id;+ }+ }+ };++ const wrapSlotChildrenWithFragment = () => {+ const legacyChildren = instance.children.map((child) => ({ ...child }));+ const id = findReusableFragmentId(legacyChildren) ?? nanoid();+ if (instances.has(id) === false) {+ instances.set(id, {+ type: "instance",+ id,+ component: "Fragment",+ children: legacyChildren,+ });+ }+ for (const candidate of instances.values()) {+ if (+ candidate.component === "Slot" &&+ (areInstanceChildrenEqual(candidate.children, legacyChildren) ||+ getSlotFragmentId(candidate) === id)+ ) {+ candidate.children = [{ type: "id", value: id }];+ }+ }+ return {+ parentSelector: [id, ...dropTarget.parentSelector],+ position: dropTarget.position,+ };+ };++ if (instance.children.length === 0) {+ return wrapSlotChildrenWithFragment();+ }+ if (instance.children[0].type === "id") {+ const fragmentId = instance.children[0].value;+ const fragment = instances.get(fragmentId);+ if (fragment?.component !== "Fragment") {+ // Legacy slots stored content directly under Slot. Normalize before+ // inserting so the first content child is not mistaken for Fragment.+ return wrapSlotChildrenWithFragment();+ }+ return {+ parentSelector: [fragmentId, ...dropTarget.parentSelector],+ position: dropTarget.position,+ };+ }+ return wrapSlotChildrenWithFragment();+ }+ return;+};++export const normalizeLegacySlotParentInSelectorMutable = (+ instances: Instances,+ instanceSelector: InstanceSelector+) => {+ const parentSelector = instanceSelector.slice(1);+ const dropTarget = getSlotFragmentDropTargetMutable(instances, {+ parentSelector,+ position: "end",+ });+ if (dropTarget === undefined) {+ return instanceSelector;+ }+ return [instanceSelector[0], ...dropTarget.parentSelector];+};++export const normalizeLegacySlotInstancePathMutable = (+ instances: Instances,+ instancePath: InstancePath+) => {+ const normalizedInstanceSelector = normalizeLegacySlotParentInSelectorMutable(+ instances,+ instancePath[0].instanceSelector+ );+ return (+ getInstancePathFromInstances(normalizedInstanceSelector, instances) ??+ instancePath+ );+};++const getInstancePathFromInstances = (+ instanceSelector: InstanceSelector,+ instances: Instances+): undefined | InstancePath => {+ const instancePath: InstancePath = [];+ for (let index = 0; index < instanceSelector.length; index += 1) {+ const instanceId = instanceSelector[index];+ const instance = instances.get(instanceId);+ if (instance === undefined) {+ continue;+ }+ instancePath.push({+ instance,+ instanceSelector: instanceSelector.slice(index),+ });+ }+ if (instancePath.length === 0) {+ return;+ }+ return instancePath;+};++export const getSlotFragmentId = (slot: undefined | Instance) => {+ if (slot?.component !== "Slot" || slot.children[0]?.type !== "id") {+ return;+ }+ return slot.children[0].value;+};++export const prepareSlotReparentMutable = ({+ instancePath,+ dropTarget,+}: {+ instancePath: InstancePath;+ dropTarget: DroppableTarget;+}): { instancePath: InstancePath; dropTarget: DroppableTarget } => {+ return {+ instancePath,+ dropTarget,+ };+};diff --git a/apps/builder/app/shared/instance-utils/tree.test.ts b/apps/builder/app/shared/instance-utils/tree.test.tsnew file mode 100644index 0000000000..b997eb6d73--- /dev/null+++ b/apps/builder/app/shared/instance-utils/tree.test.ts@@ -0,0 +1,325 @@+import { test, expect } from "vitest";+import type {+ Instance,+ Props,+ StyleDecl,+ Styles,+ StyleSource,+ StyleSourceSelection,+ WsComponentMeta,+} from "@webstudio-is/sdk";+import {+ collectionComponent,+ elementComponent,+ getStyleDeclKey,+} from "@webstudio-is/sdk";+import {+ areInstanceSelectorsEqual,+ cloneStyles,+ findLocalStyleSourcesWithinInstances,+ getReparentDropTargetMutable,+ isDescendantOrSelf,+ wrapEditableChildrenAroundDropTargetMutable,+} from "./tree";++const createStyleSource = (+ type: StyleSource["type"],+ id: StyleSource["id"]+): StyleSource => {+ if (type === "token") {+ return {+ type,+ id,+ name: id,+ };+ }+ return {+ type,+ id,+ };+};++const createStyleSourceSelection = (+ instanceId: Instance["id"],+ values: StyleSource["id"][]+): StyleSourceSelection => {+ return {+ instanceId,+ values,+ };+};++const createStyleDecl = (+ styleSourceId: string,+ breakpointId: string,+ value?: string+): StyleDecl => {+ return {+ styleSourceId,+ breakpointId,+ property: "width",+ value: {+ type: "keyword",+ value: value ?? "value",+ },+ };+};++const createStyleDeclPair = (+ styleSourceId: string,+ breakpointId: string,+ state?: string,+ value?: string+) => {+ return [+ getStyleDeclKey({+ styleSourceId,+ breakpointId,+ state,+ property: "width",+ }),+ createStyleDecl(styleSourceId, breakpointId, value),+ ] as const;+};++const createInstance = (+ id: Instance["id"],+ component: string,+ children: Instance["children"] = []+): Instance => ({+ type: "instance",+ id,+ component,+ children,+});++const metas = new Map<string, WsComponentMeta>();+const props = new Map<string, never>() as Props;++test("compares instance selectors", () => {+ expect(areInstanceSelectorsEqual(["child", "body"], ["child", "body"])).toBe(+ true+ );+ expect(areInstanceSelectorsEqual(["child"], ["other"])).toBe(false);+ expect(areInstanceSelectorsEqual(undefined, ["child"])).toBe(false);+ expect(areInstanceSelectorsEqual(undefined, undefined)).toBe(false);+});++test("clone styles with appled new style source ids", () => {+ const styles: Styles = new Map([+ createStyleDeclPair("styleSource1", "bp1"),+ createStyleDeclPair("styleSource2", "bp2"),+ createStyleDeclPair("styleSource1", "bp3"),+ createStyleDeclPair("styleSource3", "bp4"),+ createStyleDeclPair("styleSource1", "bp5"),+ createStyleDeclPair("styleSource3", "bp6"),+ ]);+ const clonedStyleSourceIds = new Map<StyleSource["id"], StyleSource["id"]>();+ clonedStyleSourceIds.set("styleSource2", "newStyleSource2");+ clonedStyleSourceIds.set("styleSource3", "newStyleSource3");+ expect(cloneStyles(styles, clonedStyleSourceIds)).toEqual([+ createStyleDecl("newStyleSource2", "bp2"),+ createStyleDecl("newStyleSource3", "bp4"),+ createStyleDecl("newStyleSource3", "bp6"),+ ]);+});++test("find local style sources within instances", () => {+ const instanceIds = new Set(["instance2", "instance4"]);+ const styleSources = [+ createStyleSource("local", "local1"),+ createStyleSource("local", "local2"),+ createStyleSource("token", "token3"),+ createStyleSource("local", "local4"),+ createStyleSource("token", "token5"),+ createStyleSource("local", "local6"),+ ];+ const styleSourceSelections = [+ createStyleSourceSelection("instance1", ["local1"]),+ createStyleSourceSelection("instance2", ["local2"]),+ createStyleSourceSelection("instance3", ["token3"]),+ createStyleSourceSelection("instance4", ["local4", "token5"]),+ createStyleSourceSelection("instance5", ["local6"]),+ ];+ expect(+ findLocalStyleSourcesWithinInstances(+ styleSources,+ styleSourceSelections,+ instanceIds+ )+ ).toEqual(new Set(["local2", "local4"]));+});++test("is descendant or self", () => {+ expect(isDescendantOrSelf(["1", "2", "3"], [])).toBe(true);+ expect(isDescendantOrSelf(["1", "2", "3"], ["1", "2", "3"])).toBe(true);+ expect(isDescendantOrSelf(["0", "1", "2", "3"], ["1", "2", "3"])).toBe(true);+ expect(isDescendantOrSelf(["1", "2", "3"], ["0", "1", "2", "3"])).toBe(false);+ expect(+ isDescendantOrSelf(+ ["item-child", "collection:entry-1", "collection", "body", "page-root"],+ ["collection", "body", "page-root"]+ )+ ).toBe(true);+});++test("wrap editable children around drop target", () => {+ const instances = new Map([+ [+ "paragraph",+ createInstance("paragraph", "Paragraph", [+ { type: "text", value: "left" },+ { type: "id", value: "bold" },+ { type: "text", value: "right" },+ ]),+ ],+ ["bold", createInstance("bold", "Bold")],+ ]);++ const dropTarget = wrapEditableChildrenAroundDropTargetMutable(+ instances,+ props,+ metas,+ { parentSelector: ["paragraph", "body"], position: 1 }+ );++ expect(dropTarget).toEqual({+ parentSelector: ["paragraph", "body"],+ position: 1,+ });+ const paragraphChildren = instances.get("paragraph")?.children;+ expect(paragraphChildren).toEqual([+ { type: "id", value: expect.any(String) },+ { type: "id", value: expect.any(String) },+ ]);+ const [leftSpanChild, rightSpanChild] = paragraphChildren ?? [];+ expect(instances.get(leftSpanChild?.value ?? "")).toMatchObject({+ component: elementComponent,+ tag: "span",+ children: [+ { type: "text", value: "left" },+ { type: "id", value: "bold" },+ ],+ });+ expect(instances.get(rightSpanChild?.value ?? "")).toMatchObject({+ component: elementComponent,+ tag: "span",+ children: [{ type: "text", value: "right" }],+ });+});++test("wrap editable children around drop target skips missing and non-rich parents", () => {+ expect(+ wrapEditableChildrenAroundDropTargetMutable(new Map(), props, metas, {+ parentSelector: ["missing"],+ position: 0,+ })+ ).toBeUndefined();++ const instances = new Map([+ ["box", createInstance("box", "Box", [{ type: "id", value: "child" }])],+ ["child", createInstance("child", "Box")],+ ]);++ expect(+ wrapEditableChildrenAroundDropTargetMutable(instances, props, metas, {+ parentSelector: ["box"],+ position: 0,+ })+ ).toBeUndefined();+ expect(instances.get("box")?.children).toEqual([+ { type: "id", value: "child" },+ ]);+});++test("wrap editable children around start and end drop targets", () => {+ const startInstances = new Map([+ [+ "paragraph",+ createInstance("paragraph", "Paragraph", [+ { type: "text", value: "left" },+ { type: "id", value: "bold" },+ ]),+ ],+ ["bold", createInstance("bold", "Bold")],+ ]);++ expect(+ wrapEditableChildrenAroundDropTargetMutable(startInstances, props, metas, {+ parentSelector: ["paragraph"],+ position: 0,+ })+ ).toEqual({ parentSelector: ["paragraph"], position: 0 });+ const [rightSpanChild] = startInstances.get("paragraph")?.children ?? [];+ expect(startInstances.get(rightSpanChild?.value ?? "")).toMatchObject({+ component: elementComponent,+ tag: "span",+ children: [+ { type: "text", value: "left" },+ { type: "id", value: "bold" },+ ],+ });++ const endInstances = new Map([+ [+ "paragraph",+ createInstance("paragraph", "Paragraph", [+ { type: "text", value: "left" },+ { type: "id", value: "bold" },+ ]),+ ],+ ["bold", createInstance("bold", "Bold")],+ ]);++ expect(+ wrapEditableChildrenAroundDropTargetMutable(endInstances, props, metas, {+ parentSelector: ["paragraph"],+ position: "end",+ })+ ).toEqual({ parentSelector: ["paragraph"], position: 1 });+ const [leftSpanChild] = endInstances.get("paragraph")?.children ?? [];+ expect(endInstances.get(leftSpanChild?.value ?? "")).toMatchObject({+ component: elementComponent,+ tag: "span",+ children: [+ { type: "text", value: "left" },+ { type: "id", value: "bold" },+ ],+ });+});++test("get reparent drop target resolves collection item and slot targets", () => {+ const instances = new Map([+ [+ "collection",+ createInstance("collection", collectionComponent, [+ { type: "id", value: "slot" },+ ]),+ ],+ [+ "slot",+ createInstance("slot", "Slot", [{ type: "id", value: "fragment" }]),+ ],+ ["fragment", createInstance("fragment", "Fragment")],+ ]);++ expect(+ getReparentDropTargetMutable(instances, props, metas, {+ parentSelector: ["missing-item", "collection", "body"],+ position: "end",+ })+ ).toEqual({+ parentSelector: ["collection", "body"],+ position: "end",+ });++ expect(+ getReparentDropTargetMutable(instances, props, metas, {+ parentSelector: ["slot", "collection", "body"],+ position: "end",+ })+ ).toEqual({+ parentSelector: ["fragment", "slot", "collection", "body"],+ position: "end",+ });+});diff --git a/apps/builder/app/shared/tree-utils.ts b/apps/builder/app/shared/instance-utils/tree.tssimilarity index 75%rename from apps/builder/app/shared/tree-utils.tsrename to apps/builder/app/shared/instance-utils/tree.tsindex cad091cd3a..7c3e9aa58a 100644--- a/apps/builder/app/shared/tree-utils.ts+++ b/apps/builder/app/shared/instance-utils/tree.ts@@ -1,3 +1,6 @@+// Tree utilities own generic instance-tree mechanics that are not tied to a+// specific command: selector comparison, ancestry checks, drop target shaping,+// and style-source traversal within instance trees.import { nanoid } from "nanoid";import { shallowEqual } from "shallow-equal";import type {@@ -11,7 +14,8 @@ import type {WsComponentMeta,} from "@webstudio-is/sdk";import { collectionComponent, elementComponent } from "@webstudio-is/sdk";-import { isRichTextTree } from "./content-model";+import { isRichTextTree } from "../content-model";+import { getSlotFragmentDropTargetMutable } from "./slot";// slots can have multiple parents so instance should be addressed// with full rendered path to avoid double selections with slots@@ -66,67 +70,6 @@ const getCollectionDropTarget = (}};-export const getInstanceOrCreateFragmentIfNecessary = (- instances: Instances,- dropTarget: DroppableTarget-) => {- const [parentId] = dropTarget.parentSelector;- const instance = instances.get(parentId);- if (instance === undefined) {- return;- }- // slot should accept only single child- // otherwise multiple slots will have to maintain own children- // here all slot children are wrapped with fragment instance- if (instance.component === "Slot") {- const wrapSlotChildrenWithFragment = () => {- const id = nanoid();- instances.set(id, {- type: "instance",- id,- component: "Fragment",- children: instance.children,- });- instance.children = [{ type: "id", value: id }];- return {- parentSelector: [id, ...dropTarget.parentSelector],- position: dropTarget.position,- };- };-- if (instance.children.length === 0) {- const id = nanoid();- const fragment: Instance = {- type: "instance",- id,- component: "Fragment",- children: [],- };- instances.set(id, fragment);- instance.children.push({ type: "id", value: id });- return {- parentSelector: [fragment.id, ...dropTarget.parentSelector],- position: dropTarget.position,- };- }- if (instance.children[0].type === "id") {- const fragmentId = instance.children[0].value;- const fragment = instances.get(fragmentId);- if (fragment?.component !== "Fragment") {- // Legacy slots stored content directly under Slot. Normalize before- // inserting so the first content child is not mistaken for Fragment.- return wrapSlotChildrenWithFragment();- }- return {- parentSelector: [fragmentId, ...dropTarget.parentSelector],- position: dropTarget.position,- };- }- return wrapSlotChildrenWithFragment();- }- return;-};-/*** Navigator tree and canvas dnd do not have text representation* and position does not consider it and include only instances.@@ -225,7 +168,7 @@ export const getReparentDropTargetMutable = (): undefined | DroppableTarget => {dropTarget = getCollectionDropTarget(instances, dropTarget) ?? dropTarget;dropTarget =- getInstanceOrCreateFragmentIfNecessary(instances, dropTarget) ?? dropTarget;+ getSlotFragmentDropTargetMutable(instances, dropTarget) ?? dropTarget;dropTarget =wrapEditableChildrenAroundDropTargetMutable(instances,diff --git a/apps/builder/app/shared/matcher.ts b/apps/builder/app/shared/matcher.tsindex a918b5bc30..51cff4fe74 100644--- a/apps/builder/app/shared/matcher.ts+++ b/apps/builder/app/shared/matcher.ts@@ -4,7 +4,7 @@ import type {WebstudioFragment,WsComponentMeta,} from "@webstudio-is/sdk";-import type { InstanceSelector } from "./tree-utils";+import type { InstanceSelector } from "./instance-utils/tree";import { isTreeSatisfyingContentModel } from "./content-model";export const findClosestInstanceMatchingFragment = ({diff --git a/apps/builder/app/shared/nano-states/canvas.ts b/apps/builder/app/shared/nano-states/canvas.tsindex 158d245f5f..7bdcab0968 100644--- a/apps/builder/app/shared/nano-states/canvas.ts+++ b/apps/builder/app/shared/nano-states/canvas.ts@@ -3,7 +3,7 @@ import type { Instance, Instances } from "@webstudio-is/sdk";import { blockComponent, blockTemplateComponent } from "@webstudio-is/sdk";import type { FontWeight } from "@webstudio-is/fonts";import { $instances } from "../sync/data-stores";-import type { InstanceSelector } from "../tree-utils";+import type { InstanceSelector } from "../instance-utils/tree";export type TextToolbarState = {selectionRect: undefined | DOMRect;diff --git a/apps/builder/app/shared/nano-states/components.ts b/apps/builder/app/shared/nano-states/components.tsindex 9d5895674e..1fa71f445a 100644--- a/apps/builder/app/shared/nano-states/components.ts+++ b/apps/builder/app/shared/nano-states/components.ts@@ -13,7 +13,7 @@ import {type Instance,type WsComponentMeta,} from "@webstudio-is/sdk";-import type { InstanceSelector } from "../tree-utils";+import type { InstanceSelector } from "../instance-utils/tree";import { $props, $instances } from "../sync/data-stores";import { $memoryProps } from "./misc";import { $selectedPage } from "./pages";diff --git a/apps/builder/app/shared/nano-states/instance-selection.ts b/apps/builder/app/shared/nano-states/instance-selection.tsindex 5fc2e3ebe5..c841b3c247 100644--- a/apps/builder/app/shared/nano-states/instance-selection.ts+++ b/apps/builder/app/shared/nano-states/instance-selection.ts@@ -1,5 +1,5 @@import { atom } from "nanostores";-import type { InstanceSelector } from "../tree-utils";+import type { InstanceSelector } from "../instance-utils/tree";export const $selectedInstanceSelector = atom<undefined | InstanceSelector>(undefineddiff --git a/apps/builder/app/shared/nano-states/instances.ts b/apps/builder/app/shared/nano-states/instances.tsindex 91beba6e6f..0bdd8114f9 100644--- a/apps/builder/app/shared/nano-states/instances.ts+++ b/apps/builder/app/shared/nano-states/instances.ts@@ -6,7 +6,7 @@ import {rootComponent,} from "@webstudio-is/sdk";import { $instances } from "../sync/data-stores";-import type { InstanceSelector } from "../tree-utils";+import type { InstanceSelector } from "../instance-utils/tree";import { $selectedPage } from "./pages";import { $selectedInstanceSelector } from "./instance-selection";export {diff --git a/apps/builder/app/shared/nano-states/misc.ts b/apps/builder/app/shared/nano-states/misc.tsindex c75d1daa9c..d421ff7f27 100644--- a/apps/builder/app/shared/nano-states/misc.ts+++ b/apps/builder/app/shared/nano-states/misc.ts@@ -25,7 +25,7 @@ import type { CssProperty, UnitValue } from "@webstudio-is/css-engine";import type { TokenPermissions } from "@webstudio-is/authorization-token";import type { AssetType } from "@webstudio-is/asset-uploader";import type { DragStartPayload } from "~/canvas/shared/use-drag-drop";-import { type InstanceSelector } from "../tree-utils";+import { type InstanceSelector } from "../instance-utils/tree";import type { ChildrenOrientation } from "@webstudio-is/design-system";import { $selectedInstance, $selectedInstanceSelector } from "./instances";import { getPermissions } from "../permissions";diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.tsindex d4326fe2d3..8af1e5a129 100644--- a/apps/builder/app/shared/nano-states/props.ts+++ b/apps/builder/app/shared/nano-states/props.ts@@ -26,7 +26,7 @@ import { $instances } from "../sync/data-stores";import { $dataSources, $props, $assets, $resources } from "../sync/data-stores";import { $uploadingFilesDataStore, $memoryProps, $isPreviewMode } from "./misc";import { $pages } from "../sync/data-stores";-import type { InstanceSelector } from "../tree-utils";+import type { InstanceSelector } from "../instance-utils/tree";import { $dataSourceVariables } from "./variables";import { uploadingFileDataToAsset } from "~/builder/shared/assets/asset-utils";import { $selectedPage } from "./pages";diff --git a/apps/builder/app/shared/page-utils.ts b/apps/builder/app/shared/page-utils.tsindex f2ab90df3a..b57e997116 100644--- a/apps/builder/app/shared/page-utils.ts+++ b/apps/builder/app/shared/page-utils.ts@@ -1,3 +1,5 @@+import { insertWebstudioFragmentCopy } from "./instance-utils/fragment";+import { unwrap } from "./instance-utils/data";import { nanoid } from "nanoid";import {findPageByIdOrPath,@@ -13,11 +15,7 @@ import {ROOT_INSTANCE_ID,} from "@webstudio-is/sdk";import { contentModePageMetaFields } from "@webstudio-is/project/content-mode-permissions";-import {- extractWebstudioFragment,- insertWebstudioFragmentCopy,- unwrap,-} from "./instance-utils";+import { extractWebstudioFragment } from "./instance-utils/fragment";import {findAvailableVariables,replaceDataSourcesInExpression,diff --git a/apps/builder/app/shared/slot-test-utils.ts b/apps/builder/app/shared/slot-test-utils.tsnew file mode 100644index 0000000000..e382694b89--- /dev/null+++ b/apps/builder/app/shared/slot-test-utils.ts@@ -0,0 +1,153 @@+import { expect } from "vitest";+import type { Instance } from "@webstudio-is/sdk";++export const getSlotFragmentId = (+ instances: Map<Instance["id"], Instance>,+ slotId: Instance["id"]+) => {+ const slot = instances.get(slotId);+ expect(slot?.component).toBe("Slot");+ const [fragmentChild] = slot?.children ?? [];+ expect(fragmentChild?.type).toBe("id");+ const fragmentId = fragmentChild?.value;+ expect(fragmentId).toEqual(expect.any(String));+ expect(instances.get(fragmentId ?? "")?.component).toBe("Fragment");+ return fragmentId;+};++export const expectCanonicalSlots = (+ instances: Map<Instance["id"], Instance>,+ slotIds: Instance["id"][]+) => {+ for (const slotId of slotIds) {+ getSlotFragmentId(instances, slotId);+ expect(instances.get(slotId)?.children).toHaveLength(1);+ }+};++export const expectSlotsShareFragment = (+ instances: Map<Instance["id"], Instance>,+ slotIds: [Instance["id"], Instance["id"], ...Instance["id"][]]+) => {+ expectCanonicalSlots(instances, slotIds);+ const [firstSlotId, ...otherSlotIds] = slotIds;+ const fragmentId = getSlotFragmentId(instances, firstSlotId);+ for (const slotId of otherSlotIds) {+ expect(getSlotFragmentId(instances, slotId)).toBe(fragmentId);+ }+ return fragmentId;+};++export const expectSlotsDoNotShareFragment = (+ instances: Map<Instance["id"], Instance>,+ leftSlotId: Instance["id"],+ rightSlotId: Instance["id"]+) => {+ expectCanonicalSlots(instances, [leftSlotId, rightSlotId]);+ expect(getSlotFragmentId(instances, leftSlotId)).not.toBe(+ getSlotFragmentId(instances, rightSlotId)+ );+};++export const expectSlotTreeIntegrity = (+ instances: Map<Instance["id"], Instance>,+ options: {+ selectedInstanceSelector?: Instance["id"][];+ } = {}+) => {+ const childRefCounts = new Map<Instance["id"], number>();++ for (const instance of instances.values()) {+ const childIds = new Set<Instance["id"]>();+ for (const child of instance.children) {+ if (child.type !== "id") {+ continue;+ }+ expect(+ childIds.has(child.value),+ `${instance.id} references child ${child.value} more than once`+ ).toBe(false);+ childIds.add(child.value);+ childRefCounts.set(+ child.value,+ (childRefCounts.get(child.value) ?? 0) + 1+ );+ expect(+ instances.has(child.value),+ `${instance.id} references missing child ${child.value}`+ ).toBe(true);+ }++ if (instance.component !== "Slot") {+ continue;+ }++ expect(+ instance.children,+ `Slot ${instance.id} must have one Fragment`+ ).toHaveLength(1);+ const fragmentChild = instance.children[0];+ expect(+ fragmentChild?.type,+ `Slot ${instance.id} must reference a Fragment`+ ).toBe("id");+ const fragment = instances.get(fragmentChild?.value ?? "");+ expect(+ fragment?.component,+ `Slot ${instance.id} child must be a Fragment`+ ).toBe("Fragment");+ }++ const selectedInstanceSelector = options.selectedInstanceSelector;+ if (selectedInstanceSelector !== undefined) {+ const [selectedInstanceId] = selectedInstanceSelector;+ expect(instances.has(selectedInstanceId), "selection must resolve").toBe(+ true+ );+ const selectedInstance = instances.get(selectedInstanceId);+ expect(+ selectedInstance?.component,+ "selection must not point at an internal Slot Fragment"+ ).not.toBe("Fragment");++ for (let index = 0; index < selectedInstanceSelector.length; index += 1) {+ const instanceId = selectedInstanceSelector[index];+ const parentId = selectedInstanceSelector[index + 1];+ const instance = instances.get(instanceId);+ expect(+ instance,+ `selector segment ${instanceId} must resolve`+ ).toBeDefined();+ if (parentId === undefined) {+ continue;+ }+ const parent = instances.get(parentId);+ expect(parent, `selector parent ${parentId} must resolve`).toBeDefined();+ expect(+ parent?.children.some(+ (child) => child.type === "id" && child.value === instanceId+ ),+ `selector parent ${parentId} must contain ${instanceId}`+ ).toBe(true);+ }+ }++ for (const instance of instances.values()) {+ if (instance.component !== "Fragment") {+ continue;+ }+ const parentSlots = Array.from(instances.values()).filter(+ (candidate) =>+ candidate.component === "Slot" &&+ candidate.children[0]?.type === "id" &&+ candidate.children[0].value === instance.id+ );+ if (parentSlots.length === 0) {+ continue;+ }+ expect(+ childRefCounts.get(instance.id),+ `Slot Fragment ${instance.id} reference count must match Slot parents`+ ).toBe(parentSlots.length);+ }+};diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex a05528a820..be4edad983 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -70,7 +70,7 @@ import { $selectedInstanceSelector } from "../nano-states/instances";import { $selectedPageId } from "../nano-states/pages";import { $systemDataByPage } from "../system";import { $resourcesCache } from "../resources";-import type { InstanceSelector } from "../tree-utils";+import type { InstanceSelector } from "../instance-utils/tree";enableMapSet();// safari structuredClone fixdiff --git a/apps/builder/app/shared/tree-utils.test.ts b/apps/builder/app/shared/tree-utils.test.tsdeleted file mode 100644index 5cdf4b0813..0000000000--- a/apps/builder/app/shared/tree-utils.test.ts+++ /dev/null@@ -1,131 +0,0 @@-import { test, expect } from "vitest";-import type {- Instance,- StyleDecl,- Styles,- StyleSource,- StyleSourceSelection,-} from "@webstudio-is/sdk";-import { getStyleDeclKey } from "@webstudio-is/sdk";-import {- cloneStyles,- findLocalStyleSourcesWithinInstances,- isDescendantOrSelf,-} from "./tree-utils";--const createStyleSource = (- type: StyleSource["type"],- id: StyleSource["id"]-): StyleSource => {- if (type === "token") {- return {- type,- id,- name: id,- };- }- return {- type,- id,- };-};--const createStyleSourceSelection = (- instanceId: Instance["id"],- values: StyleSource["id"][]-): StyleSourceSelection => {- return {- instanceId,- values,- };-};--const createStyleDecl = (- styleSourceId: string,- breakpointId: string,- value?: string-): StyleDecl => {- return {- styleSourceId,- breakpointId,- property: "width",- value: {- type: "keyword",- value: value ?? "value",- },- };-};--const createStyleDeclPair = (- styleSourceId: string,- breakpointId: string,- state?: string,- value?: string-) => {- return [- getStyleDeclKey({- styleSourceId,- breakpointId,- state,- property: "width",- }),- createStyleDecl(styleSourceId, breakpointId, value),- ] as const;-};--test("clone styles with appled new style source ids", () => {- const styles: Styles = new Map([- createStyleDeclPair("styleSource1", "bp1"),- createStyleDeclPair("styleSource2", "bp2"),- createStyleDeclPair("styleSource1", "bp3"),- createStyleDeclPair("styleSource3", "bp4"),- createStyleDeclPair("styleSource1", "bp5"),- createStyleDeclPair("styleSource3", "bp6"),- ]);- const clonedStyleSourceIds = new Map<StyleSource["id"], StyleSource["id"]>();- clonedStyleSourceIds.set("styleSource2", "newStyleSource2");- clonedStyleSourceIds.set("styleSource3", "newStyleSource3");- expect(cloneStyles(styles, clonedStyleSourceIds)).toEqual([- createStyleDecl("newStyleSource2", "bp2"),- createStyleDecl("newStyleSource3", "bp4"),- createStyleDecl("newStyleSource3", "bp6"),- ]);-});--test("find local style sources within instances", () => {- const instanceIds = new Set(["instance2", "instance4"]);- const styleSources = [- createStyleSource("local", "local1"),- createStyleSource("local", "local2"),- createStyleSource("token", "token3"),- createStyleSource("local", "local4"),- createStyleSource("token", "token5"),- createStyleSource("local", "local6"),- ];- const styleSourceSelections = [- createStyleSourceSelection("instance1", ["local1"]),- createStyleSourceSelection("instance2", ["local2"]),- createStyleSourceSelection("instance3", ["token3"]),- createStyleSourceSelection("instance4", ["local4", "token5"]),- createStyleSourceSelection("instance5", ["local6"]),- ];- expect(- findLocalStyleSourcesWithinInstances(- styleSources,- styleSourceSelections,- instanceIds- )- ).toEqual(new Set(["local2", "local4"]));-});--test("is descendant or self", () => {- expect(isDescendantOrSelf(["1", "2", "3"], ["1", "2", "3"])).toBe(true);- expect(isDescendantOrSelf(["0", "1", "2", "3"], ["1", "2", "3"])).toBe(true);- expect(isDescendantOrSelf(["1", "2", "3"], ["0", "1", "2", "3"])).toBe(false);- expect(- isDescendantOrSelf(- ["item-child", "collection:entry-1", "collection", "body", "page-root"],- ["collection", "body", "page-root"]- )- ).toBe(true);-});diff --git a/apps/builder/e2e/fixtures/slot-keyboard-project.ts b/apps/builder/e2e/fixtures/slot-keyboard-project.tsnew file mode 100644index 0000000000..4a9c572a70--- /dev/null+++ b/apps/builder/e2e/fixtures/slot-keyboard-project.ts@@ -0,0 +1,203 @@+import { insertAuthorizationToken, loadDevBuild, updateBuild } from "../db";+import { loginAndCreateBlankProject } from "../flows/dashboard";+import { newPage } from "../harness";++export type SeededSlotKeyboardProject = {+ projectId: string;+ builderToken: string;+};++const getBaseBreakpointId = (breakpoints: string) => {+ const parsedBreakpoints = JSON.parse(breakpoints) as Array<{+ id: string;+ minWidth?: number;+ maxWidth?: number;+ }>;+ return (+ parsedBreakpoints.find(+ (breakpoint) =>+ breakpoint.minWidth === undefined && breakpoint.maxWidth === undefined+ )?.id ??+ parsedBreakpoints.at(0)?.id ??+ "base"+ );+};++const createSlotKeyboardBuildData = ({+ pages,+ breakpoints,+}: {+ pages: string;+ breakpoints: string;+}) => {+ const rootInstanceId = "slot-keyboard-body";+ const wrapperId = "slot-keyboard-wrapper";+ const slotAId = "slot-keyboard-slot-a";+ const slotBId = "slot-keyboard-slot-b";+ const fragmentId = "slot-keyboard-fragment";+ const divId = "slot-keyboard-div";+ const headingId = "slot-keyboard-heading";+ const baseBreakpointId = getBaseBreakpointId(breakpoints);+ const wrapperStyleSourceId = "slot-keyboard-wrapper-style";+ const divStyleSourceId = "slot-keyboard-div-style";+ const headingStyleSourceId = "slot-keyboard-heading-style";++ const nextPages = JSON.parse(pages) as {+ homePageId: string;+ pages: Array<{ id: string; rootInstanceId: string }>;+ };+ const homePage = nextPages.pages.find(+ (page) => page.id === nextPages.homePageId+ );+ if (homePage === undefined) {+ throw new Error("Expected existing build to have a home page");+ }+ homePage.rootInstanceId = rootInstanceId;++ return {+ pages: JSON.stringify(nextPages),+ instances: JSON.stringify([+ {+ type: "instance",+ id: rootInstanceId,+ component: "ws:element",+ tag: "body",+ children: [{ type: "id", value: wrapperId }],+ },+ {+ type: "instance",+ id: wrapperId,+ component: "ws:element",+ tag: "main",+ label: "Slot Keyboard Wrapper",+ children: [+ { type: "id", value: slotAId },+ { type: "id", value: slotBId },+ ],+ },+ {+ type: "instance",+ id: slotAId,+ component: "Slot",+ label: "Slot A",+ children: [{ type: "id", value: fragmentId }],+ },+ {+ type: "instance",+ id: slotBId,+ component: "Slot",+ label: "Slot B",+ children: [{ type: "id", value: fragmentId }],+ },+ {+ type: "instance",+ id: fragmentId,+ component: "Fragment",+ children: [+ { type: "id", value: divId },+ { type: "id", value: headingId },+ ],+ },+ {+ type: "instance",+ id: divId,+ component: "ws:element",+ tag: "div",+ label: "Drop Div",+ children: [{ type: "text", value: "Drop zone" }],+ },+ {+ type: "instance",+ id: headingId,+ component: "ws:element",+ tag: "h1",+ label: "Slot Heading",+ children: [{ type: "text", value: "Slot heading" }],+ },+ ]),+ props: JSON.stringify([]),+ styleSources: JSON.stringify([+ { type: "local", id: wrapperStyleSourceId },+ { type: "local", id: divStyleSourceId },+ { type: "local", id: headingStyleSourceId },+ ]),+ styleSourceSelections: JSON.stringify([+ { instanceId: wrapperId, values: [wrapperStyleSourceId] },+ { instanceId: divId, values: [divStyleSourceId] },+ { instanceId: headingId, values: [headingStyleSourceId] },+ ]),+ styles: JSON.stringify([+ {+ styleSourceId: wrapperStyleSourceId,+ breakpointId: baseBreakpointId,+ property: "display",+ value: { type: "keyword", value: "grid" },+ },+ {+ styleSourceId: wrapperStyleSourceId,+ breakpointId: baseBreakpointId,+ property: "gap",+ value: { type: "unit", unit: "px", value: 32 },+ },+ {+ styleSourceId: divStyleSourceId,+ breakpointId: baseBreakpointId,+ property: "minHeight",+ value: { type: "unit", unit: "px", value: 120 },+ },+ {+ styleSourceId: divStyleSourceId,+ breakpointId: baseBreakpointId,+ property: "padding",+ value: { type: "unit", unit: "px", value: 24 },+ },+ {+ styleSourceId: headingStyleSourceId,+ breakpointId: baseBreakpointId,+ property: "marginTop",+ value: { type: "unit", unit: "px", value: 24 },+ },+ ]),+ dataSources: JSON.stringify([]),+ resources: JSON.stringify([]),+ marketplaceProduct: JSON.stringify({}),+ };+};++export const createSlotKeyboardProject = async ({+ email = "[email protected]",+ title = "Slot Keyboard E2E",+ builderToken = "slot-keyboard-e2e-builder-token",+}: {+ email?: string;+ title?: string;+ builderToken?: string;+} = {}): Promise<SeededSlotKeyboardProject> => {+ const ownerPage = await newPage();++ try {+ const projectId = await loginAndCreateBlankProject({+ page: ownerPage,+ email,+ title,+ });+ const build = await loadDevBuild({ projectId });+ await updateBuild(build.id, {+ version: 0,+ ...createSlotKeyboardBuildData({+ pages: build.pages,+ breakpoints: build.breakpoints,+ }),+ });+ await insertAuthorizationToken({+ token: builderToken,+ projectId,+ name: "E2E slot keyboard builder token",+ relation: "builders",+ });++ return { projectId, builderToken };+ } finally {+ await ownerPage.close();+ }+};diff --git a/apps/builder/e2e/run.ts b/apps/builder/e2e/run.tsindex 9963bdad72..0c7f732597 100644--- a/apps/builder/e2e/run.ts+++ b/apps/builder/e2e/run.ts@@ -17,6 +17,7 @@ import "./tests/content-mode-editing.e2e";import "./tests/pages-actions.e2e";import "./tests/preview-links.e2e";import "./tests/share-link-permissions.e2e";+import "./tests/slot-keyboard.e2e";const testTimeoutMs =Number.parseInt(process.env.E2E_TEST_TIMEOUT_MS ?? "", 10) || 60_000;diff --git a/apps/builder/e2e/tests/slot-keyboard.e2e.ts b/apps/builder/e2e/tests/slot-keyboard.e2e.tsnew file mode 100644index 0000000000..9c3d5468ca--- /dev/null+++ b/apps/builder/e2e/tests/slot-keyboard.e2e.ts@@ -0,0 +1,697 @@+import type { Frame, Page } from "playwright";+import { openProjectBuilder } from "../flows/builder";+import { waitForSyncStatus } from "../flows/sync-status";+import {+ createSlotKeyboardProject,+ type SeededSlotKeyboardProject,+} from "../fixtures/slot-keyboard-project";+import { newIsolatedPage, test } from "../harness";+import { measure } from "../perf";++let fixture: SeededSlotKeyboardProject;+let detachFixture: SeededSlotKeyboardProject;+let navigatorFixture: SeededSlotKeyboardProject;+let navigatorOutdentFixture: SeededSlotKeyboardProject;+let topChildFixture: SeededSlotKeyboardProject;+let bottomChildFixture: SeededSlotKeyboardProject;+let navigatorTopChildFixture: SeededSlotKeyboardProject;+let navigatorBottomChildFixture: SeededSlotKeyboardProject;++const selector = (instanceSelector: string[]) =>+ `[data-ws-selector="${instanceSelector.join(",")}"]`;++const canvasInstance = ({+ canvas,+ instanceSelector,+}: {+ canvas: Frame;+ instanceSelector: string[];+}) => canvas.locator(selector(instanceSelector)).first();++const expectCanvasInstanceVisible = async ({+ canvas,+ instanceSelector,+}: {+ canvas: Frame;+ instanceSelector: string[];+}) => {+ await canvasInstance({ canvas, instanceSelector }).waitFor({+ state: "visible",+ timeout: 30_000,+ });+};++const openNavigatorPanel = async ({ page }: { page: Page }) => {+ const tab = page.getByRole("tab", { name: "Navigator" });+ if ((await tab.getAttribute("aria-selected")) !== "true") {+ await tab.click();+ }+ await page.getByText("Navigator", { exact: true }).first().waitFor({+ state: "visible",+ timeout: 10_000,+ });+};++test.beforeAll(async () => {+ fixture = await createSlotKeyboardProject();+ detachFixture = await createSlotKeyboardProject({+ email: "[email protected]",+ title: "Slot Keyboard Detach E2E",+ builderToken: "slot-keyboard-detach-e2e-builder-token",+ });+ navigatorFixture = await createSlotKeyboardProject({+ email: "[email protected]",+ title: "Slot Keyboard Navigator E2E",+ builderToken: "slot-keyboard-navigator-e2e-builder-token",+ });+ navigatorOutdentFixture = await createSlotKeyboardProject({+ email: "[email protected]",+ title: "Slot Keyboard Navigator Outdent E2E",+ builderToken: "slot-keyboard-navigator-outdent-e2e-builder-token",+ });+ topChildFixture = await createSlotKeyboardProject({+ email: "[email protected]",+ title: "Slot Keyboard Top Child E2E",+ builderToken: "slot-keyboard-top-child-e2e-builder-token",+ });+ bottomChildFixture = await createSlotKeyboardProject({+ email: "[email protected]",+ title: "Slot Keyboard Bottom Child E2E",+ builderToken: "slot-keyboard-bottom-child-e2e-builder-token",+ });+ navigatorTopChildFixture = await createSlotKeyboardProject({+ email: "[email protected]",+ title: "Slot Keyboard Navigator Top Child E2E",+ builderToken: "slot-keyboard-navigator-top-child-e2e-builder-token",+ });+ navigatorBottomChildFixture = await createSlotKeyboardProject({+ email: "[email protected]",+ title: "Slot Keyboard Navigator Bottom Child E2E",+ builderToken: "slot-keyboard-navigator-bottom-child-e2e-builder-token",+ });+});++const expectCanvasInstancePrecedes = async ({+ canvas,+ beforeSelector,+ afterSelector,+}: {+ canvas: Frame;+ beforeSelector: string[];+ afterSelector: string[];+}) => {+ const beforeLocator = canvasInstance({+ canvas,+ instanceSelector: beforeSelector,+ });+ const afterLocator = canvasInstance({+ canvas,+ instanceSelector: afterSelector,+ });+ await beforeLocator.waitFor({ state: "visible", timeout: 30_000 });+ await afterLocator.waitFor({ state: "visible", timeout: 30_000 });+ const precedes = await beforeLocator.evaluate((beforeElement, after) => {+ const afterElement = document.querySelector(after);+ if (afterElement === null) {+ return false;+ }+ return Boolean(+ beforeElement.compareDocumentPosition(afterElement) &+ Node.DOCUMENT_POSITION_FOLLOWING+ );+ }, selector(afterSelector));+ if (precedes === false) {+ throw new Error(+ `Expected ${beforeSelector.join(",")} to precede ${afterSelector.join(",")}`+ );+ }+};++const getFocusedTreeButtonText = async ({ page }: { page: Page }) => {+ return await page.evaluate(() => {+ const activeElement = document.activeElement;+ if (activeElement?.hasAttribute("data-tree-button") === false) {+ return;+ }+ return activeElement?.textContent?.trim();+ });+};++test("Keyboard shortcut moves a shared slot child into the previous sibling", async () => {+ const { page, close } = await newIsolatedPage();++ try {+ const canvas = await measure("slot keyboard open builder", async () => {+ return await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ });++ const headingSelector = [+ "slot-keyboard-heading",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-a",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await expectCanvasInstanceVisible({+ canvas,+ instanceSelector: headingSelector,+ });+ await canvasInstance({ canvas, instanceSelector: headingSelector }).click();++ await page.keyboard.press("Control+ArrowRight");+ await waitForSyncStatus({ page, status: "idle" });++ await expectCanvasInstanceVisible({+ canvas,+ instanceSelector: [+ "slot-keyboard-heading",+ "slot-keyboard-div",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-a",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ],+ });+ await expectCanvasInstanceVisible({+ canvas,+ instanceSelector: [+ "slot-keyboard-heading",+ "slot-keyboard-div",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-b",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ],+ });+ } finally {+ await close();+ }+});++test("Keyboard shortcut keeps Navigator arrows working after outdenting a row", async () => {+ const { page, close } = await newIsolatedPage();++ try {+ const canvas = await measure(+ "slot keyboard navigator outdent open builder",+ async () => {+ return await openProjectBuilder({+ page,+ projectId: navigatorOutdentFixture.projectId,+ authToken: navigatorOutdentFixture.builderToken,+ });+ }+ );++ const slotAHeadingSelector = [+ "slot-keyboard-heading",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-a",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await canvasInstance({+ canvas,+ instanceSelector: slotAHeadingSelector,+ }).click();+ await openNavigatorPanel({ page });+ await page.getByRole("button", { name: "Slot Heading" }).first().click();++ await page.keyboard.press("Control+ArrowLeft");+ await waitForSyncStatus({ page, status: "idle" });++ const focusedTextAfterMove = await getFocusedTreeButtonText({ page });+ if (focusedTextAfterMove?.includes("Slot Heading") !== true) {+ throw new Error(+ `Expected moved Navigator row to keep focus, received ${focusedTextAfterMove}`+ );+ }++ await page.keyboard.press("ArrowUp");+ const focusedTextAfterArrow = await getFocusedTreeButtonText({ page });+ if (+ focusedTextAfterArrow === undefined ||+ focusedTextAfterArrow === focusedTextAfterMove+ ) {+ throw new Error(+ `Expected ArrowUp to move Navigator focus from ${focusedTextAfterMove}, received ${focusedTextAfterArrow}`+ );+ }+ } finally {+ await close();+ }+});++test("Keyboard shortcut moves a direct shared slot child out of all slot occurrences", async () => {+ const { page, close } = await newIsolatedPage();++ try {+ const canvas = await measure(+ "slot keyboard detach open builder",+ async () => {+ return await openProjectBuilder({+ page,+ projectId: detachFixture.projectId,+ authToken: detachFixture.builderToken,+ });+ }+ );++ const slotAHeadingSelector = [+ "slot-keyboard-heading",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-a",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await expectCanvasInstanceVisible({+ canvas,+ instanceSelector: slotAHeadingSelector,+ });+ await canvasInstance({+ canvas,+ instanceSelector: slotAHeadingSelector,+ }).click();++ await page.keyboard.press("Control+ArrowLeft");+ await waitForSyncStatus({ page, status: "idle" });++ await canvasInstance({+ canvas,+ instanceSelector: slotAHeadingSelector,+ }).waitFor({ state: "hidden", timeout: 30_000 });+ await canvasInstance({+ canvas,+ instanceSelector: [+ "slot-keyboard-heading",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-b",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ],+ }).waitFor({ state: "hidden", timeout: 30_000 });++ await expectCanvasInstanceVisible({+ canvas,+ instanceSelector: [+ "slot-keyboard-heading",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ],+ });+ } finally {+ await close();+ }+});++test("Keyboard shortcut moves the first shared slot child above all slot occurrences", async () => {+ const { page, close } = await newIsolatedPage();++ try {+ const canvas = await measure(+ "slot keyboard top child open builder",+ async () => {+ return await openProjectBuilder({+ page,+ projectId: navigatorTopChildFixture.projectId,+ authToken: navigatorTopChildFixture.builderToken,+ });+ }+ );++ const slotADivSelector = [+ "slot-keyboard-div",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-a",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await expectCanvasInstanceVisible({+ canvas,+ instanceSelector: slotADivSelector,+ });+ await canvasInstance({+ canvas,+ instanceSelector: slotADivSelector,+ }).click();++ await page.keyboard.press("Control+ArrowUp");+ await waitForSyncStatus({ page, status: "idle" });++ await canvasInstance({+ canvas,+ instanceSelector: slotADivSelector,+ }).waitFor({ state: "hidden", timeout: 30_000 });+ await canvasInstance({+ canvas,+ instanceSelector: [+ "slot-keyboard-div",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-b",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ],+ }).waitFor({ state: "hidden", timeout: 30_000 });++ const movedDivSelector = [+ "slot-keyboard-div",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await expectCanvasInstanceVisible({+ canvas,+ instanceSelector: movedDivSelector,+ });++ const movedDivPrecedesSlotA = await canvas+ .locator(selector(movedDivSelector))+ .evaluate((movedElement) => {+ const slotA = document.querySelector(+ '[data-ws-selector="slot-keyboard-slot-a,slot-keyboard-wrapper,slot-keyboard-body"]'+ );+ if (slotA === null) {+ return false;+ }+ return Boolean(+ movedElement.compareDocumentPosition(slotA) &+ Node.DOCUMENT_POSITION_FOLLOWING+ );+ });+ if (movedDivPrecedesSlotA === false) {+ throw new Error("Expected moved div to be positioned before Slot A");+ }+ } finally {+ await close();+ }+});++test("Keyboard shortcut moves the last shared slot child below all slot occurrences", async () => {+ const { page, close } = await newIsolatedPage();++ try {+ const canvas = await measure(+ "slot keyboard bottom child open builder",+ async () => {+ return await openProjectBuilder({+ page,+ projectId: navigatorBottomChildFixture.projectId,+ authToken: navigatorBottomChildFixture.builderToken,+ });+ }+ );++ const slotAHeadingSelector = [+ "slot-keyboard-heading",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-a",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await expectCanvasInstanceVisible({+ canvas,+ instanceSelector: slotAHeadingSelector,+ });+ await canvasInstance({+ canvas,+ instanceSelector: slotAHeadingSelector,+ }).click();++ await page.keyboard.press("Control+ArrowDown");+ await waitForSyncStatus({ page, status: "idle" });++ await canvasInstance({+ canvas,+ instanceSelector: slotAHeadingSelector,+ }).waitFor({ state: "hidden", timeout: 30_000 });+ await canvasInstance({+ canvas,+ instanceSelector: [+ "slot-keyboard-heading",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-b",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ],+ }).waitFor({ state: "hidden", timeout: 30_000 });++ const movedHeadingSelector = [+ "slot-keyboard-heading",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await expectCanvasInstanceVisible({+ canvas,+ instanceSelector: movedHeadingSelector,+ });++ const slotAPrecedesMovedHeading = await canvas+ .locator(+ '[data-ws-selector="slot-keyboard-slot-a,slot-keyboard-wrapper,slot-keyboard-body"]'+ )+ .evaluate((slotA, movedSelector) => {+ const movedElement = document.querySelector(movedSelector);+ if (movedElement === null) {+ return false;+ }+ return Boolean(+ slotA.compareDocumentPosition(movedElement) &+ Node.DOCUMENT_POSITION_FOLLOWING+ );+ }, selector(movedHeadingSelector));+ if (slotAPrecedesMovedHeading === false) {+ throw new Error("Expected moved heading to be positioned after Slot A");+ }+ } finally {+ await close();+ }+});++test("Keyboard shortcut reorders a shared slot child from navigator focus", async () => {+ const { page, close } = await newIsolatedPage();++ try {+ const canvas = await measure(+ "slot keyboard navigator open builder",+ async () => {+ return await openProjectBuilder({+ page,+ projectId: navigatorFixture.projectId,+ authToken: navigatorFixture.builderToken,+ });+ }+ );++ const slotAHeadingSelector = [+ "slot-keyboard-heading",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-a",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await canvasInstance({+ canvas,+ instanceSelector: slotAHeadingSelector,+ }).click();+ await openNavigatorPanel({ page });+ await page.getByRole("button", { name: "Slot Heading" }).first().click();+ await page.keyboard.press("Control+ArrowUp");+ await waitForSyncStatus({ page, status: "idle" });++ const slotADivSelector = [+ "slot-keyboard-div",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-a",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ const slotBHeadingSelector = [+ "slot-keyboard-heading",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-b",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ const slotBDivSelector = [+ "slot-keyboard-div",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-b",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];++ await expectCanvasInstancePrecedes({+ canvas,+ beforeSelector: slotAHeadingSelector,+ afterSelector: slotADivSelector,+ });+ await expectCanvasInstancePrecedes({+ canvas,+ beforeSelector: slotBHeadingSelector,+ afterSelector: slotBDivSelector,+ });+ } finally {+ await close();+ }+});++test("Keyboard shortcut moves the first shared slot child above all slot occurrences from navigator focus", async () => {+ const { page, close } = await newIsolatedPage();++ try {+ const canvas = await measure(+ "slot keyboard navigator top child open builder",+ async () => {+ return await openProjectBuilder({+ page,+ projectId: topChildFixture.projectId,+ authToken: topChildFixture.builderToken,+ });+ }+ );++ const slotADivSelector = [+ "slot-keyboard-div",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-a",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await canvasInstance({+ canvas,+ instanceSelector: slotADivSelector,+ }).click();+ await openNavigatorPanel({ page });+ await page.getByRole("button", { name: "Drop Div" }).first().click();++ await page.keyboard.press("Control+ArrowUp");+ await waitForSyncStatus({ page, status: "idle" });++ await canvasInstance({+ canvas,+ instanceSelector: slotADivSelector,+ }).waitFor({ state: "hidden", timeout: 30_000 });+ await canvasInstance({+ canvas,+ instanceSelector: [+ "slot-keyboard-div",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-b",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ],+ }).waitFor({ state: "hidden", timeout: 30_000 });++ const movedDivSelector = [+ "slot-keyboard-div",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await expectCanvasInstanceVisible({+ canvas,+ instanceSelector: movedDivSelector,+ });++ const movedDivPrecedesSlotA = await canvas+ .locator(selector(movedDivSelector))+ .evaluate((movedElement) => {+ const slotA = document.querySelector(+ '[data-ws-selector="slot-keyboard-slot-a,slot-keyboard-wrapper,slot-keyboard-body"]'+ );+ if (slotA === null) {+ return false;+ }+ return Boolean(+ movedElement.compareDocumentPosition(slotA) &+ Node.DOCUMENT_POSITION_FOLLOWING+ );+ });+ if (movedDivPrecedesSlotA === false) {+ throw new Error("Expected moved div to be positioned before Slot A");+ }+ } finally {+ await close();+ }+});++test("Keyboard shortcut moves the last shared slot child below all slot occurrences from navigator focus", async () => {+ const { page, close } = await newIsolatedPage();++ try {+ const canvas = await measure(+ "slot keyboard navigator bottom child open builder",+ async () => {+ return await openProjectBuilder({+ page,+ projectId: bottomChildFixture.projectId,+ authToken: bottomChildFixture.builderToken,+ });+ }+ );++ const slotAHeadingSelector = [+ "slot-keyboard-heading",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-a",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await canvasInstance({+ canvas,+ instanceSelector: slotAHeadingSelector,+ }).click();+ await openNavigatorPanel({ page });+ await page.getByRole("button", { name: "Slot Heading" }).first().click();++ await page.keyboard.press("Control+ArrowDown");+ await waitForSyncStatus({ page, status: "idle" });++ await canvasInstance({+ canvas,+ instanceSelector: slotAHeadingSelector,+ }).waitFor({ state: "hidden", timeout: 30_000 });+ await canvasInstance({+ canvas,+ instanceSelector: [+ "slot-keyboard-heading",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-b",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ],+ }).waitFor({ state: "hidden", timeout: 30_000 });++ const movedHeadingSelector = [+ "slot-keyboard-heading",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await expectCanvasInstanceVisible({+ canvas,+ instanceSelector: movedHeadingSelector,+ });++ const slotAPrecedesMovedHeading = await canvas+ .locator(+ '[data-ws-selector="slot-keyboard-slot-a,slot-keyboard-wrapper,slot-keyboard-body"]'+ )+ .evaluate((slotA, movedSelector) => {+ const movedElement = document.querySelector(movedSelector);+ if (movedElement === null) {+ return false;+ }+ return Boolean(+ slotA.compareDocumentPosition(movedElement) &+ Node.DOCUMENT_POSITION_FOLLOWING+ );+ }, selector(movedHeadingSelector));+ if (slotAPrecedesMovedHeading === false) {+ throw new Error("Expected moved heading to be positioned after Slot A");+ }+ } finally {+ await close();+ }+});diff --git a/packages/design-system/src/components/tree.tsx b/packages/design-system/src/components/tree.tsxindex 11d5e23674..cc727034f9 100644--- a/packages/design-system/src/components/tree.tsx+++ b/packages/design-system/src/components/tree.tsx@@ -1,10 +1,13 @@import {+ createContext,useEffect,useInsertionEffect,+ useContext,useRef,useState,type ComponentPropsWithoutRef,type KeyboardEvent,+ type MutableRefObject,type ReactNode,} from "react";import { FocusScope, useFocusManager } from "@react-aria/focus";@@ -32,6 +35,13 @@ const treeNodeOutline = "--tree-node-outline";const treeNodeBackgroundColor = "--tree-node-background-color";const treeActionOpacity = "--tree-action-opacity";+const TreeFocusRestoreContext = createContext<+ | undefined+ | {+ shouldRestoreFocusRef: MutableRefObject<boolean>;+ }+>(undefined);+type TreeSelectionState = "none" | "selected" | "selected-descendant";const getTreeSelectionState = ({@@ -60,40 +70,52 @@ const EXPAND_WIDTH = 24;const TreeContainer = ({ children }: { children: ReactNode }) => {const focusManager = useFocusManager();+ const shouldRestoreFocusRef = useRef(false);return (- <Box- onKeyDown={(event) => {- if (event.defaultPrevented) {- return;- }- if (event.key === "ArrowUp" || event.key === "ArrowLeft") {- focusManager?.focusPrevious({- accept: (node) => node.hasAttribute("data-tree-button"),- });- // prevent scrolling- event.preventDefault();- }- if (event.key === "ArrowDown") {- focusManager?.focusNext({- accept: (node) => node.hasAttribute("data-tree-button"),- });- // prevent scrolling- event.preventDefault();- }- if (event.key === "ArrowRight") {- focusManager?.focusNext({- accept: (node) =>- node.hasAttribute("data-tree-button") ||- // try to focus button inside action- node.closest("[data-tree-action]") !== null,- });- // prevent scrolling- event.preventDefault();- }- }}- >- {children}- </Box>+ <TreeFocusRestoreContext.Provider value={{ shouldRestoreFocusRef }}>+ <Box+ onKeyDown={(event) => {+ if (event.defaultPrevented) {+ return;+ }+ if (event.metaKey || event.ctrlKey) {+ if (event.key.startsWith("Arrow")) {+ shouldRestoreFocusRef.current = true;+ window.setTimeout(() => {+ shouldRestoreFocusRef.current = false;+ }, 1000);+ }+ return;+ }+ if (event.key === "ArrowUp" || event.key === "ArrowLeft") {+ focusManager?.focusPrevious({+ accept: (node) => node.hasAttribute("data-tree-button"),+ });+ // prevent scrolling+ event.preventDefault();+ }+ if (event.key === "ArrowDown") {+ focusManager?.focusNext({+ accept: (node) => node.hasAttribute("data-tree-button"),+ });+ // prevent scrolling+ event.preventDefault();+ }+ if (event.key === "ArrowRight") {+ focusManager?.focusNext({+ accept: (node) =>+ node.hasAttribute("data-tree-button") ||+ // try to focus button inside action+ node.closest("[data-tree-action]") !== null,+ });+ // prevent scrolling+ event.preventDefault();+ }+ }}+ >+ {children}+ </Box>+ </TreeFocusRestoreContext.Provider>);};@@ -430,6 +452,7 @@ export const TreeNode = ({children: ReactNode;}) => {const buttonRef = useRef<HTMLButtonElement>(null);+ const focusRestoreContext = useContext(TreeFocusRestoreContext);const selectionState = getTreeSelectionState({isSelected,isSelectedDescendant,@@ -444,6 +467,13 @@ export const TreeNode = ({});}}, [isSelected]);+ useEffect(() => {+ const shouldRestoreFocusRef = focusRestoreContext?.shouldRestoreFocusRef;+ if (isSelected && shouldRestoreFocusRef?.current === true) {+ buttonRef.current?.focus({ preventScroll: true });+ shouldRestoreFocusRef.current = false;+ }+ }, [focusRestoreContext, isSelected]);const handleKeydown = (event: KeyboardEvent<HTMLDivElement>) => {nodeProps?.onKeyDown?.(event);@@ -451,6 +481,9 @@ export const TreeNode = ({if (event.defaultPrevented) {return;}+ if (event.metaKey || event.ctrlKey) {+ return;+ }if (event.key === "ArrowLeft" && isExpanded === true) {onExpand?.(false, event.altKey);// allow to collapse and then navigate to previous node