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
fix: Convert slot instance, unwrap slot children (#5788)
Oleg Isonen8bbb64952327
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex ae92938a70..3c72959655 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -27,6 +27,7 @@ import {import {updateWebstudioData,unwrapInstance,+ detachSharedSlotContentMutable,deleteSelectedInstance,extractWebstudioFragment,insertWebstudioFragmentAt,@@ -373,9 +374,16 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({if (instancePath === undefined || instancePath.length === 1) {return;}- const [selectedItem, parentItem] = instancePath;updateWebstudioData((data) => {+ const detachedInstancePath = detachSharedSlotContentMutable(+ data,+ instancePath+ );+ const [selectedItem, parentItem] = detachedInstancePath;+ if (parentItem === undefined) {+ return;+ }const fragment = extractWebstudioFragment(data,selectedItem.instance.iddiff --git a/apps/builder/app/shared/instance-utils.test.tsx b/apps/builder/app/shared/instance-utils.test.tsxindex 1afda156e7..2ec9f62369 100644--- a/apps/builder/app/shared/instance-utils.test.tsx+++ b/apps/builder/app/shared/instance-utils.test.tsx@@ -46,6 +46,8 @@ import {buildInstancePath,wrapInstance,toggleInstanceShow,+ detachSharedSlotContentMutable,+ unwrapInstance,unwrapInstanceMutable,canUnwrapInstance,canConvertInstance,@@ -797,6 +799,43 @@ describe("reparent instance", () => {);});+ 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">@@ -1036,6 +1075,37 @@ describe("delete instance", () => {expect(data.instances.size).toEqual(2);expect(data.instances.get("slotId")?.children.length).toEqual(0);});++ test("delete only selected slot occurrence", () => {+ 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([]);+ expect(data.instances.get("slot2")?.children).toEqual([+ { type: "id", value: "fragment" },+ ]);+ expect(data.instances.get("fragment")?.children).toEqual([+ { type: "id", value: "div" },+ ]);+ });});describe("wrap in", () => {@@ -1081,6 +1151,40 @@ describe("wrap in", () => {);});+ 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">@@ -1313,6 +1417,58 @@ describe("insert webstudio fragment copy", () => {$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({@@ -3123,6 +3279,78 @@ describe("unwrap instance", () => {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);+ });});describe("canUnwrapInstance", () => {@@ -3382,6 +3610,42 @@ describe("convertInstance", () => {$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">diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex 4cee4e494e..b7533c629a 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -465,6 +465,32 @@ export const reparentInstanceMutable = (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]);+ if (+ sourceFragmentId !== undefined &&+ targetSlot?.component === "Slot" &&+ targetSlot.children[0]?.type === "id" &&+ targetSlot.children[0].value === sourceFragmentId+ ) {+ return sourceInstanceSelector;+ }+ const sourceInstancePath = 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@@ -572,6 +598,7 @@ export const deleteInstanceMutable = (if (instancePath === undefined) {return false;}+ instancePath = detachSharedSlotContentMutable(data, instancePath);const {instances,props,@@ -650,6 +677,97 @@ export const deleteInstanceMutable = (return true;};+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 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,@@ -694,6 +812,91 @@ export const unwrapInstanceMutable = ({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 childrenconst selectedIndexInParent = parentInstance.children.findIndex((child) => child.type === "id" && child.value === selectedItem.instance.id@@ -811,14 +1014,26 @@ export const wrapInstance = (component: string, tag?: string) => {if (instancePath === undefined || instancePath.length === 1) {return;}- const [selectedItem, parentItem] = instancePath;- const selectedInstance = selectedItem.instance;const newInstanceId = nanoid();- const newInstanceSelector = [newInstanceId, ...parentItem.instanceSelector];+ 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,@@ -853,7 +1068,7 @@ export const wrapInstance = (component: string, tag?: string) => {instances: data.instances,props: data.props,metas,- instanceSelector: newInstanceSelector,+ instanceSelector: nextInstanceSelector,});if (isSatisfying === false) {@@ -928,6 +1143,9 @@ export const convertInstance = (component: string, tag?: string) => {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;@@ -976,7 +1194,15 @@ export const unwrapInstance = () => {return;}- const [selectedItem, parentItem] = instancePath;+ const [selectedItem, defaultParentItem] = instancePath;+ const parentItem =+ defaultParentItem?.instance.component === "Fragment" &&+ instancePath[2]?.instance.component === "Slot"+ ? instancePath[2]+ : defaultParentItem;+ if (parentItem === undefined) {+ return;+ }try {updateWebstudioData((data) => {