Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

refactor: generalize insertable lookup (#4398)

Bogdan Chadkinbc0f6bb6a303
diff --git a/apps/builder/app/builder/features/components/insert.ts b/apps/builder/app/builder/features/components/insert.ts
index 628557ea38..a31383990d 100644
--- a/apps/builder/app/builder/features/components/insert.ts
+++ b/apps/builder/app/builder/features/components/insert.ts
@@ -1,18 +1,11 @@
-import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";
import type { WsComponentMeta } from "@webstudio-is/react-sdk";
import { toast } from "@webstudio-is/design-system";
+import { $registeredComponentMetas } from "~/shared/nano-states";
import {
- $instances,
- $registeredComponentMetas,
- $selectedInstanceSelector,
-} from "~/shared/nano-states";
-import {
- computeInstancesConstraints,
- findClosestDroppableTarget,
+ findClosestInsertable,
getComponentTemplateData,
insertTemplateData,
} from "~/shared/instance-utils";
-import { $selectedPage } from "~/shared/awareness";
const formatInsertionError = (component: string, meta: WsComponentMeta) => {
const or = new Intl.ListFormat("en", {
@@ -36,41 +29,18 @@ const formatInsertionError = (component: string, meta: WsComponentMeta) => {
// Insert a component depending on currently selected instance.
// Used for 1-click insert from the components panel.
export const insert = (component: string) => {
- const selectedPage = $selectedPage.get();
- if (selectedPage === undefined) {
- return;
- }
- const templateData = getComponentTemplateData(component);
- if (templateData === undefined) {
- return;
- }
- const newInstances = new Map(
- templateData.instances.map((instance) => [instance.id, instance])
- );
- const rootInstanceIds = templateData.children
- .filter((child) => child.type === "id")
- .map((child) => child.value);
- const instanceSelector = $selectedInstanceSelector.get() ?? [
- selectedPage.rootInstanceId,
- ];
- if (instanceSelector[0] === ROOT_INSTANCE_ID) {
- toast.error(`${component} cannot be added into Global Root`);
+ const fragment = getComponentTemplateData(component);
+ if (fragment === undefined) {
return;
}
- const metas = $registeredComponentMetas.get();
- const dropTarget = findClosestDroppableTarget(
- metas,
- $instances.get(),
- // fallback to root as drop target
- instanceSelector,
- computeInstancesConstraints(metas, newInstances, rootInstanceIds)
- );
- if (dropTarget === undefined) {
+ const insertable = findClosestInsertable(fragment);
+ if (insertable === undefined) {
+ const metas = $registeredComponentMetas.get();
const meta = metas.get(component);
if (meta) {
toast.error(formatInsertionError(component, meta));
}
return;
}
- insertTemplateData(templateData, dropTarget);
+ insertTemplateData(fragment, insertable);
};
diff --git a/apps/builder/app/shared/copy-paste/plugin-embed-template.ts b/apps/builder/app/shared/copy-paste/plugin-embed-template.ts
index 0d0faa97a8..3babb0bce8 100644
--- a/apps/builder/app/shared/copy-paste/plugin-embed-template.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-embed-template.ts
@@ -3,19 +3,9 @@ import {
WsEmbedTemplate,
generateDataFromEmbedTemplate,
} from "@webstudio-is/react-sdk";
-import {
- $selectedInstanceSelector,
- $instances,
- $registeredComponentMetas,
- $breakpoints,
-} from "../nano-states";
-import {
- computeInstancesConstraints,
- findClosestDroppableTarget,
- insertTemplateData,
-} from "../instance-utils";
+import { $registeredComponentMetas, $breakpoints } from "../nano-states";
+import { findClosestInsertable, insertTemplateData } from "../instance-utils";
import { isBaseBreakpoint } from "../breakpoints";
-import { $selectedPage } from "~/shared/awareness";
const version = "@webstudio/template";
@@ -34,44 +24,25 @@ export const mimeType = "text/plain";
export const onPaste = (clipboardData: string) => {
const template = parse(clipboardData);
-
- const selectedPage = $selectedPage.get();
-
- if (template === undefined || selectedPage === undefined) {
+ if (template === undefined) {
return false;
}
-
- // paste to the root if nothing is selected
- const instanceSelector = $selectedInstanceSelector.get() ?? [
- selectedPage.rootInstanceId,
- ];
+ const metas = $registeredComponentMetas.get();
const breakpoints = $breakpoints.get();
const breakpointValues = Array.from(breakpoints.values());
const baseBreakpoint = breakpointValues.find(isBaseBreakpoint);
if (baseBreakpoint === undefined) {
return false;
}
- const metas = $registeredComponentMetas.get();
- const templateData = generateDataFromEmbedTemplate(
+ const fragment = generateDataFromEmbedTemplate(
template,
metas,
baseBreakpoint.id
);
- const newInstances = new Map(
- templateData.instances.map((instance) => [instance.id, instance])
- );
- const rootInstanceIds = templateData.children
- .filter((child) => child.type === "id")
- .map((child) => child.value);
- const dropTarget = findClosestDroppableTarget(
- metas,
- $instances.get(),
- instanceSelector,
- computeInstancesConstraints(metas, newInstances, rootInstanceIds)
- );
- if (dropTarget === undefined) {
+ const insertable = findClosestInsertable(fragment);
+ if (insertable === undefined) {
return false;
}
- insertTemplateData(templateData, dropTarget);
+ insertTemplateData(fragment, insertable);
return true;
};
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.ts
index c475d816eb..96fcca307a 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts
@@ -8,26 +8,19 @@ import {
WebstudioFragment,
findTreeInstanceIdsExcludingSlotDescendants,
} from "@webstudio-is/sdk";
-import {
- $selectedInstanceSelector,
- $project,
- $registeredComponentMetas,
- $instances,
-} from "../nano-states";
+import { $selectedInstanceSelector, $instances } from "../nano-states";
import type { InstanceSelector, DroppableTarget } from "../tree-utils";
import {
- computeInstancesConstraints,
deleteInstanceMutable,
findAvailableDataSources,
- findClosestDroppableTarget,
extractWebstudioFragment,
insertWebstudioFragmentCopy,
isInstanceDetachable,
updateWebstudioData,
getWebstudioData,
insertInstanceChildrenMutable,
+ findClosestInsertable,
} from "../instance-utils";
-import { $selectedPage } from "~/shared/awareness";
const version = "@webstudio/instance/v0.1";
@@ -92,14 +85,16 @@ export const getPortalFragmentSelector = (
return [instance.children[0].value, ...instanceSelector];
};
-const getPasteTarget = (
- data: InstanceData,
- instanceSelector: InstanceSelector
-): undefined | DroppableTarget => {
+const findPasteTarget = (data: InstanceData): undefined | DroppableTarget => {
const instances = $instances.get();
+ const instanceSelector = $selectedInstanceSelector.get();
+
// paste after selected instance
- if (shallowEqual(instanceSelector, data.instanceSelector)) {
+ if (
+ instanceSelector &&
+ shallowEqual(instanceSelector, data.instanceSelector)
+ ) {
// body is not allowed to copy
// so clipboard always have at least two level instance selector
const [currentInstanceId, parentInstanceId] = instanceSelector;
@@ -116,22 +111,15 @@ const getPasteTarget = (
};
}
+ const insertable = findClosestInsertable(data);
+ if (insertable === undefined) {
+ return;
+ }
+
const newInstances: Instances = new Map();
for (const instance of data.instances) {
newInstances.set(instance.id, instance);
}
- const metas = $registeredComponentMetas.get();
- const rootInstanceId = data.instances[0].id;
- const pasteTarget = findClosestDroppableTarget(
- metas,
- instances,
- instanceSelector,
- computeInstancesConstraints(metas, newInstances, [rootInstanceId])
- );
- if (pasteTarget === undefined) {
- return;
- }
-
const newInstanceIds = findTreeInstanceIdsExcludingSlotDescendants(
newInstances,
data.instances[0].id
@@ -151,36 +139,25 @@ const getPasteTarget = (
const dropTargetSelector =
// consider portal fragment when check for cycles to avoid cases
// like pasting portal directly into portal
- getPortalFragmentSelector(instances, pasteTarget.parentSelector) ??
- pasteTarget.parentSelector;
+ getPortalFragmentSelector(instances, insertable.parentSelector) ??
+ insertable.parentSelector;
for (const instanceId of dropTargetSelector) {
if (preservedChildIds.has(instanceId)) {
return;
}
}
- return pasteTarget;
+ return insertable;
};
export const onPaste = (clipboardData: string) => {
const fragment = parse(clipboardData);
- const selectedPage = $selectedPage.get();
- const project = $project.get();
-
- if (
- fragment === undefined ||
- selectedPage === undefined ||
- project === undefined
- ) {
+ if (fragment === undefined) {
return false;
}
- // paste to the root if nothing is selected
- const instanceSelector = $selectedInstanceSelector.get() ?? [
- selectedPage.rootInstanceId,
- ];
- const pasteTarget = getPasteTarget(fragment, instanceSelector);
+ const pasteTarget = findPasteTarget(fragment);
if (pasteTarget === undefined) {
return false;
}
@@ -192,7 +169,7 @@ export const onPaste = (clipboardData: string) => {
availableDataSources: findAvailableDataSources(
data.dataSources,
data.instances,
- instanceSelector
+ pasteTarget.parentSelector
),
});
const newRootInstanceId = newInstanceIds.get(fragment.instances[0].id);
diff --git a/apps/builder/app/shared/copy-paste/plugin-markdown.ts b/apps/builder/app/shared/copy-paste/plugin-markdown.ts
index 265d056495..31e7bc72fb 100644
--- a/apps/builder/app/shared/copy-paste/plugin-markdown.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-markdown.ts
@@ -7,20 +7,10 @@ import type {
Instance,
WebstudioFragment,
} from "@webstudio-is/sdk";
-import {
- computeInstancesConstraints,
- findClosestDroppableTarget,
- insertTemplateData,
-} from "../instance-utils";
-import {
- $breakpoints,
- $instances,
- $registeredComponentMetas,
- $selectedInstanceSelector,
-} from "../nano-states";
+import { findClosestInsertable, insertTemplateData } from "../instance-utils";
+import { $breakpoints } from "../nano-states";
import { isBaseBreakpoint } from "../breakpoints";
import { denormalizeSrcProps } from "./asset-upload";
-import { $selectedPage } from "~/shared/awareness";
const micromarkOptions = {
extensions: [gfm()],
@@ -221,36 +211,16 @@ const parse = (clipboardData: string, options?: Options) => {
};
export const onPaste = async (clipboardData: string) => {
- let data = parse(clipboardData);
-
- const selectedPage = $selectedPage.get();
- if (data === undefined || selectedPage === undefined) {
+ let fragment = parse(clipboardData);
+ if (fragment === undefined) {
return false;
}
-
- data = await denormalizeSrcProps(data);
-
- const metas = $registeredComponentMetas.get();
- const newInstances = new Map(
- data.instances.map((instance) => [instance.id, instance])
- );
- const rootInstanceIds = data.children
- .filter((child) => child.type === "id")
- .map((child) => child.value);
- // paste to the root if nothing is selected
- const instanceSelector = $selectedInstanceSelector.get() ?? [
- selectedPage.rootInstanceId,
- ];
- const dropTarget = findClosestDroppableTarget(
- metas,
- $instances.get(),
- instanceSelector,
- computeInstancesConstraints(metas, newInstances, rootInstanceIds)
- );
- if (dropTarget === undefined) {
+ fragment = await denormalizeSrcProps(fragment);
+ const insertable = findClosestInsertable(fragment);
+ if (insertable === undefined) {
return false;
}
- insertTemplateData(data, dropTarget);
+ insertTemplateData(fragment, insertable);
return true;
};
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.ts
index e00aa51a59..b1448d4ddf 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
@@ -1,18 +1,12 @@
import type { Instance, WebstudioFragment } from "@webstudio-is/sdk";
import {
- computeInstancesConstraints,
findAvailableDataSources,
- findClosestDroppableTarget,
+ findClosestInsertable,
insertInstanceChildrenMutable,
insertWebstudioFragmentCopy,
updateWebstudioData,
} from "../../instance-utils";
-import {
- $instances,
- $registeredComponentMetas,
- $selectedInstanceSelector,
- $project,
-} from "../../nano-states";
+import { $project } from "../../nano-states";
import {
WfData,
wfNodeTypes,
@@ -25,7 +19,6 @@ import { addStyles } from "./styles";
import { builderApi } from "~/shared/builder-api";
import { denormalizeSrcProps } from "../asset-upload";
import { nanoHash } from "~/shared/nano-hash";
-import { $selectedPage } from "~/shared/awareness";
const { toast } = builderApi;
@@ -179,35 +172,13 @@ export const onPaste = async (clipboardData: string) => {
}
let fragment = await toWebstudioFragment(wfData);
- const selectedPage = $selectedPage.get();
- if (fragment === undefined || selectedPage === undefined) {
+ if (fragment === undefined) {
return false;
}
-
fragment = await denormalizeSrcProps(fragment);
- const metas = $registeredComponentMetas.get();
- const newInstances = new Map(
- fragment.instances.map((instance) => [instance.id, instance])
- );
-
- // paste to the root if nothing is selected
- const instanceSelector = $selectedInstanceSelector.get() ?? [
- selectedPage.rootInstanceId,
- ];
-
- const rootInstanceIds = fragment.children
- .filter((child) => child.type === "id")
- .map((child) => child.value);
-
- const dropTarget = findClosestDroppableTarget(
- metas,
- $instances.get(),
- instanceSelector,
- computeInstancesConstraints(metas, newInstances, rootInstanceIds)
- );
-
- if (dropTarget === undefined) {
+ const insertable = findClosestInsertable(fragment);
+ if (insertable === undefined) {
return false;
}
@@ -218,7 +189,7 @@ export const onPaste = async (clipboardData: string) => {
availableDataSources: findAvailableDataSources(
data.dataSources,
data.instances,
- instanceSelector
+ insertable.parentSelector
),
});
@@ -233,7 +204,7 @@ export const onPaste = async (clipboardData: string) => {
})
.filter(<T>(value: T): value is NonNullable<T> => value !== undefined);
- insertInstanceChildrenMutable(data, children, dropTarget);
+ insertInstanceChildrenMutable(data, children, insertable);
});
return true;
diff --git a/apps/builder/app/shared/instance-utils.test.tsx b/apps/builder/app/shared/instance-utils.test.tsx
index 053f80a80e..0d8b8e9605 100644
--- a/apps/builder/app/shared/instance-utils.test.tsx
+++ b/apps/builder/app/shared/instance-utils.test.tsx
@@ -7,7 +7,7 @@ import {
} from "@webstudio-is/react-sdk";
import type { Project } from "@webstudio-is/project";
import { createDefaultPages } from "@webstudio-is/project-build";
-import { $, ws, renderJsx } from "@webstudio-is/sdk/testing";
+import { $, ws, renderJsx, ExpressionValue } from "@webstudio-is/sdk/testing";
import { parseCss } from "@webstudio-is/css-data";
import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";
import type {
@@ -25,13 +25,13 @@ import type {
StyleSources,
StyleSourceSelections,
WebstudioData,
+ WebstudioFragment,
} from "@webstudio-is/sdk";
import { encodeDataSourceVariable, getStyleDeclKey } from "@webstudio-is/sdk";
import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";
import {
computeInstancesConstraints,
findClosestDroppableComponentIndex,
- findClosestDroppableTarget,
findClosestEditableInstanceSelector,
insertTemplateData,
type InsertConstraints,
@@ -41,6 +41,7 @@ import {
reparentInstance,
getWebstudioData,
insertInstanceChildrenMutable,
+ findClosestInsertable,
} from "./instance-utils";
import {
$assets,
@@ -58,6 +59,7 @@ import {
} from "./nano-states";
import { registerContainers } from "./sync";
import { mapGroupBy } from "./shim";
+import { $awareness, selectInstance } from "./awareness";
enableMapSet();
registerContainers();
@@ -67,6 +69,22 @@ $pages.set(createDefaultPages({ rootInstanceId: "", systemDataSourceId: "" }));
const defaultMetasMap = new Map(Object.entries(defaultMetas));
$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>
@@ -414,204 +432,6 @@ describe("find closest droppable component index", () => {
});
});
-describe("find closest droppable target", () => {
- const createInstancePair = (
- id: Instance["id"],
- component: string,
- children: Instance["children"]
- ): [Instance["id"], Instance] => {
- return [id, { type: "instance", id, component, children }];
- };
-
- test("puts in the end if closest instance is container", () => {
- const instances = new Map([
- createInstancePair("body", "Body", [{ type: "id", value: "box" }]),
- createInstancePair("box", "Box", [{ type: "id", value: "paragraph" }]),
- createInstancePair("paragraph", "Paragraph", [
- { type: "id", value: "bold" },
- ]),
- ]);
- expect(
- findClosestDroppableTarget(
- defaultMetasMap,
- instances,
- ["box", "body"],
- emptyInsertConstraints
- )
- ).toEqual({
- parentSelector: ["box", "body"],
- position: "end",
- });
- });
-
- test("puts in the end of root instance", () => {
- const instances = new Map([
- createInstancePair("body", "Body", [{ type: "id", value: "box" }]),
- createInstancePair("box", "Box", [{ type: "id", value: "paragraph" }]),
- ]);
- expect(
- findClosestDroppableTarget(
- defaultMetasMap,
- instances,
- ["body"],
- emptyInsertConstraints
- )
- ).toEqual({
- parentSelector: ["body"],
- position: "end",
- });
- });
-
- test("puts in the end of root instance when root only has text", () => {
- const instances = new Map([
- createInstancePair("body", "Body", [{ type: "text", value: "text" }]),
- ]);
- expect(
- findClosestDroppableTarget(
- defaultMetasMap,
- instances,
- ["body"],
- emptyInsertConstraints
- )
- ).toEqual({
- parentSelector: ["body"],
- position: "end",
- });
- });
-
- test("finds closest container and puts after its child within selection", () => {
- const instances = new Map([
- createInstancePair("body", "Body", [{ type: "id", value: "paragraph" }]),
- createInstancePair("paragraph", "Paragraph", [
- { type: "id", value: "bold" },
- ]),
- createInstancePair("bold", "Bold", []),
- ]);
- expect(
- findClosestDroppableTarget(
- defaultMetasMap,
- instances,
- ["bold", "paragraph", "body"],
- emptyInsertConstraints
- )
- ).toEqual({
- parentSelector: ["paragraph", "body"],
- position: 1,
- });
- });
-
- test("finds closest container that doesn't have a direct text child", () => {
- const instances = new Map([
- createInstancePair("body", "Body", [
- { type: "id", value: "box1" },
- { type: "id", value: "paragraph" },
- { type: "id", value: "box2" },
- ]),
- createInstancePair("paragraph", "Paragraph", [
- { type: "text", value: "some text" },
- ]),
- createInstancePair("box1", "Box1", []),
- createInstancePair("box2", "Box2", []),
- ]);
- expect(
- findClosestDroppableTarget(
- defaultMetasMap,
- instances,
- ["paragraph", "body"],
- emptyInsertConstraints
- )
- ).toEqual({
- parentSelector: ["body"],
- position: 2,
- });
- });
-
- test("finds closest container that doesn't have an expression as a child", () => {
- const instances = new Map([
- createInstancePair("body", "Body", [
- { type: "id", value: "box1" },
- { type: "id", value: "paragraph" },
- { type: "id", value: "box2" },
- ]),
- createInstancePair("paragraph", "Paragraph", [
- { type: "expression", value: '"bla"' },
- ]),
- createInstancePair("box1", "Box1", []),
- createInstancePair("box2", "Box2", []),
- ]);
- expect(
- findClosestDroppableTarget(
- defaultMetasMap,
- instances,
- ["paragraph", "body"],
- emptyInsertConstraints
- )
- ).toEqual({
- parentSelector: ["body"],
- position: 2,
- });
- });
-
- test("finds closest container that doesn't have an expression as a child", () => {
- const instances = new Map([
- createInstancePair("body", "Body", [
- { type: "id", value: "box1" },
- { type: "id", value: "paragraph" },
- { type: "id", value: "box2" },
- ]),
- createInstancePair("paragraph", "Paragraph", [
- { type: "expression", value: '"bla"' },
- ]),
- createInstancePair("box1", "Box1", []),
- createInstancePair("box2", "Box2", []),
- ]);
- expect(
- findClosestDroppableTarget(
- defaultMetasMap,
- instances,
- ["paragraph", "body"],
- emptyInsertConstraints
- )
- ).toEqual({
- parentSelector: ["body"],
- position: 2,
- });
- });
-
- test("forbids inserting into :root", () => {
- const instances = new Map([createInstancePair("body", "Body", [])]);
- expect(
- findClosestDroppableTarget(
- defaultMetasMap,
- instances,
- [":root"],
- emptyInsertConstraints
- )
- ).toEqual(undefined);
- });
-
- test("allow inserting into collection item", () => {
- const { instances } = renderJsx(
- <$.Body ws:id="bodyId">
- <ws.collection ws:id="collectionId">
- <$.Box ws:id="boxId"></$.Box>
- </ws.collection>
- </$.Body>
- );
- expect(
- findClosestDroppableTarget(
- defaultMetasMap,
- instances,
- ["collectionId[1]", "collectionId", "bodyId"],
- emptyInsertConstraints
- )
- ).toEqual({
- parentSelector: ["collectionId", "bodyId"],
- position: "end",
- });
- });
-});
-
describe("insert instance children", () => {
test("insert instance children into empty target", () => {
const instances = toMap([createInstance("body", "Body", [])]);
@@ -3331,3 +3151,144 @@ describe("copy paste", () => {
`);
});
});
+
+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: "",
+ systemDataSourceId: "",
+ })
+ );
+ $awareness.set({
+ pageId: "homePageId",
+ instanceSelector: ["collectionId[1]", "collectionId", "bodyId"],
+ });
+ $registeredComponentMetas.set(defaultMetasMap);
+ });
+
+ test("puts in the end if closest instance is container", () => {
+ const { instances } = renderJsx(
+ <$.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 } = renderJsx(
+ <$.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 } = renderJsx(<$.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 } = renderJsx(
+ <$.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: ["paragraphId", "bodyId"],
+ position: 1,
+ });
+ });
+
+ test("finds closest container that doesn't have an expression as a child", () => {
+ const { instances } = renderJsx(
+ <$.Body ws:id="bodyId">
+ <$.Box ws:id="box1Id"></$.Box>
+ <$.Paragraph ws:id="paragraphId">
+ {new ExpressionValue(`"bla"`)}
+ </$.Paragraph>
+ <$.Box ws:id="box2Id"></$.Box>
+ </$.Body>
+ );
+ $instances.set(instances);
+ selectInstance(["paragraphId", "bodyId"]);
+ expect(findClosestInsertable(newBoxFragment)).toEqual({
+ parentSelector: ["bodyId"],
+ position: 2,
+ });
+ });
+
+ test("forbids inserting into :root", () => {
+ const { instances } = renderJsx(<$.Body ws:id="bodyId"></$.Body>);
+ $instances.set(instances);
+ selectInstance([":root"]);
+ expect(findClosestInsertable(newBoxFragment)).toEqual(undefined);
+ });
+
+ test("allow inserting into collection item", () => {
+ const { instances } = renderJsx(
+ <$.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("forbid inserting list item in body", () => {
+ const { instances } = renderJsx(<$.Body ws:id="bodyId"></$.Body>);
+ $instances.set(instances);
+ selectInstance(["bodyId"]);
+ const newListItemFragment = createFragment({
+ children: [{ type: "id", value: "newListItemId" }],
+ instances: [
+ {
+ type: "instance",
+ id: "newListItemId",
+ component: "ListItem",
+ children: [],
+ },
+ ],
+ });
+ expect(findClosestInsertable(newListItemFragment)).toEqual(undefined);
+ });
+});
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index 2ffc4345c5..74465f4305 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -35,7 +35,6 @@ import {
import {
$props,
$styles,
- $selectedInstanceSelector,
$styleSourceSelections,
$styleSources,
$instances,
@@ -63,7 +62,7 @@ import { humanizeString } from "./string-utils";
import { serverSyncStore } from "./sync";
import { setDifference, setUnion } from "./shim";
import { breakCyclesMutable, findCycles } from "@webstudio-is/project-build";
-import { $selectedPage, selectInstance } from "./awareness";
+import { $awareness, $selectedPage, selectInstance } from "./awareness";
export const updateWebstudioData = (mutate: (data: WebstudioData) => void) => {
serverSyncStore.createTransaction(
@@ -420,31 +419,22 @@ export const findClosestDroppableComponentIndex = ({
return -1;
};
-export const findClosestDroppableTarget = (
+const findClosestDroppableTarget = (
metas: Map<string, WsComponentMeta>,
instances: Instances,
instanceSelector: InstanceSelector,
insertConstraints: InsertConstraints
): undefined | DroppableTarget => {
- if (instanceSelector[0] === ROOT_INSTANCE_ID) {
- return;
- }
- // We want to always allow dropping into the root.
- // For example when body has text content and the only viable option is to insert at the end.
- if (instanceSelector.length === 1) {
- return {
- parentSelector: instanceSelector,
- position: "end",
- };
- }
const droppableIndex = findClosestDroppableComponentIndex({
metas,
constraints: insertConstraints,
instances,
instanceSelector,
- allowInsertIntoTextContainer: false,
+ // We want to always allow dropping into the root.
+ // For example when body has text content
+ // and the only viable option is to insert at the end.
+ allowInsertIntoTextContainer: instanceSelector.length === 1,
});
-
if (droppableIndex === -1) {
return;
}
@@ -517,30 +507,8 @@ export const insertInstanceChildrenMutable = (
export const findTargetAndInsertFragment = (fragment: WebstudioFragment) => {
let isSuccess = false;
-
- const selectedPage = $selectedPage.get();
- if (selectedPage === undefined) {
- return isSuccess;
- }
- const metas = $registeredComponentMetas.get();
- const newInstances = new Map(
- fragment.instances.map((instance) => [instance.id, instance])
- );
- const rootInstanceIds = fragment.children
- .filter((child) => child.type === "id")
- .map((child) => child.value);
- // paste to the root if nothing is selected
- const instanceSelector = $selectedInstanceSelector.get() ?? [
- selectedPage.rootInstanceId,
- ];
- const target = findClosestDroppableTarget(
- metas,
- $instances.get(),
- instanceSelector,
- computeInstancesConstraints(metas, newInstances, rootInstanceIds)
- );
-
- if (target === undefined) {
+ const insertable = findClosestInsertable(fragment);
+ if (insertable === undefined) {
return isSuccess;
}
@@ -551,7 +519,7 @@ export const findTargetAndInsertFragment = (fragment: WebstudioFragment) => {
availableDataSources: findAvailableDataSources(
data.dataSources,
data.instances,
- instanceSelector
+ insertable.parentSelector
),
});
const newRootInstanceId = newInstanceIds.get(fragment.instances[0].id);
@@ -562,7 +530,7 @@ export const findTargetAndInsertFragment = (fragment: WebstudioFragment) => {
const children: Instance["children"] = [
{ type: "id", value: newRootInstanceId },
];
- insertInstanceChildrenMutable(data, children, target);
+ insertInstanceChildrenMutable(data, children, insertable);
isSuccess = true;
});
@@ -1621,3 +1589,40 @@ export const findClosestSlot = (
}
}
};
+
+export type Insertable = {
+ parentSelector: InstanceSelector;
+ position: number | "end";
+};
+
+export const findClosestInsertable = (
+ fragment: WebstudioFragment
+): undefined | Insertable => {
+ const selectedPage = $selectedPage.get();
+ const awareness = $awareness.get();
+ if (selectedPage === undefined) {
+ return;
+ }
+ // paste to the page root if nothing is selected
+ const instanceSelector = awareness?.instanceSelector ?? [
+ 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 rootInstanceIds = fragment.children
+ .filter((child) => child.type === "id")
+ .map((child) => child.value);
+ const newInstances = new Map(
+ fragment.instances.map((instance) => [instance.id, instance])
+ );
+ return findClosestDroppableTarget(
+ metas,
+ instances,
+ instanceSelector,
+ computeInstancesConstraints(metas, newInstances, rootInstanceIds)
+ );
+};
diff --git a/packages/sdk/src/jsx.ts b/packages/sdk/src/jsx.ts
index d2ea45bc09..27eaceba91 100644
--- a/packages/sdk/src/jsx.ts
+++ b/packages/sdk/src/jsx.ts
@@ -62,6 +62,9 @@ const traverseJsx = (
if (typeof child === "string") {
continue;
}
+ if (child instanceof ExpressionValue) {
+ continue;
+ }
traverseJsx(child, callback);
}
};
@@ -137,7 +140,9 @@ export const renderJsx = (root: JSX.Element) => {
children: children.map((child) =>
typeof child === "string"
? { type: "text", value: child }
- : { type: "id", value: child.props?.["ws:id"] ?? getId(child) }
+ : child instanceof ExpressionValue
+ ? { type: "expression", value: child.value }
+ : { type: "id", value: child.props?.["ws:id"] ?? getId(child) }
),
});
});
@@ -151,7 +156,7 @@ type ComponentProps = Record<string, unknown> &
Record<`${string}:expression`, string> & {
"ws:id"?: string;
"ws:label"?: string;
- children?: ReactNode;
+ children?: ReactNode | ExpressionValue;
};
type Component = { displayName: string } & ((