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: make inserting fragments copy composable (#2783)

Bogdan Chadkin1e7ef26dc98c
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
index 95b5685844..4261b19076 100644
--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-settings.tsx
@@ -953,31 +953,29 @@ const duplicatePage = (pageId: Page["id"]) => {
const newName = `${name} (${Number(copyNumber ?? "0") + 1})`;
const slice = getInstancesSlice(page.rootInstanceId);
- insertInstancesSliceCopy({
- slice,
- availableDataSources: new Set(),
- beforeTransactionEnd: (rootInstanceId, draft) => {
- if (draft.pages === undefined) {
- return;
- }
- const newPage = {
- ...page,
- id: newPageId,
- rootInstanceId,
- name: newName,
- path: nameToPath(pages, newName),
- } satisfies Page;
- draft.pages.pages.push(newPage);
- const currentFolder = findParentFolderByChildId(
- pageId,
- draft.pages.folders
- );
- registerFolderChildMutable(
- draft.pages.folders,
- newPageId,
- currentFolder?.id
- );
- },
+ updateWebstudioData((data) => {
+ const rootInstanceId = insertInstancesSliceCopy({
+ data,
+ slice,
+ availableDataSources: new Set(),
+ });
+ if (rootInstanceId === undefined) {
+ return;
+ }
+ const newPage = {
+ ...page,
+ id: newPageId,
+ rootInstanceId,
+ name: newName,
+ path: nameToPath(pages, newName),
+ } satisfies Page;
+ data.pages.pages.push(newPage);
+ const currentFolder = findParentFolderByChildId(pageId, data.pages.folders);
+ registerFolderChildMutable(
+ data.pages.folders,
+ newPageId,
+ currentFolder?.id
+ );
});
return newPageId;
};
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.ts
index f791528273..9ee7d21d3e 100644
--- a/apps/builder/app/builder/shared/commands.ts
+++ b/apps/builder/app/builder/shared/commands.ts
@@ -1,6 +1,5 @@
import { createCommandsEmitter, type Command } from "~/shared/commands-emitter";
import {
- $dataSources,
$isPreviewMode,
$editingItemId,
$instances,
@@ -187,33 +186,37 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
const [targetInstanceId, parentInstanceId] = instanceSelector;
const parentInstanceSelector = instanceSelector.slice(1);
const slice = getInstancesSlice(targetInstanceId);
- insertInstancesSliceCopy({
- slice,
- availableDataSources: findAvailableDataSources(
- $dataSources.get(),
- instances,
- parentInstanceSelector
- ),
- beforeTransactionEnd: (rootInstanceId, draft) => {
- const parentInstance = draft.instances.get(parentInstanceId);
- if (parentInstance === undefined) {
- return;
- }
- // put after current instance
- const indexWithinChildren = parentInstance.children.findIndex(
- (child) => child.type === "id" && child.value === targetInstanceId
- );
- const position = indexWithinChildren + 1;
- parentInstance.children.splice(position, 0, {
- type: "id",
- value: rootInstanceId,
- });
- // select new instance
- $selectedInstanceSelector.set([
- rootInstanceId,
- ...parentInstanceSelector,
- ]);
- },
+ updateWebstudioData((data) => {
+ const rootInstanceId = insertInstancesSliceCopy({
+ data,
+ slice,
+ availableDataSources: findAvailableDataSources(
+ data.dataSources,
+ data.instances,
+ parentInstanceSelector
+ ),
+ });
+ if (rootInstanceId === undefined) {
+ return;
+ }
+ const parentInstance = data.instances.get(parentInstanceId);
+ if (parentInstance === undefined) {
+ return;
+ }
+ // put after current instance
+ const indexWithinChildren = parentInstance.children.findIndex(
+ (child) => child.type === "id" && child.value === targetInstanceId
+ );
+ const position = indexWithinChildren + 1;
+ parentInstance.children.splice(position, 0, {
+ type: "id",
+ value: rootInstanceId,
+ });
+ // select new instance
+ $selectedInstanceSelector.set([
+ rootInstanceId,
+ ...parentInstanceSelector,
+ ]);
});
},
},
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.ts
index 5b85529216..61624fab43 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts
@@ -13,7 +13,6 @@ import {
$project,
$registeredComponentMetas,
$instances,
- $dataSources,
} from "../nano-states";
import {
type InstanceSelector,
@@ -167,14 +166,14 @@ const getPasteTarget = (
};
export const onPaste = (clipboardData: string): boolean => {
- const data = parse(clipboardData);
+ const fragment = parse(clipboardData);
const selectedPage = $selectedPage.get();
const project = $project.get();
const metas = $registeredComponentMetas.get();
if (
- data === undefined ||
+ fragment === undefined ||
selectedPage === undefined ||
project === undefined
) {
@@ -185,46 +184,50 @@ export const onPaste = (clipboardData: string): boolean => {
const instanceSelector = $selectedInstanceSelector.get() ?? [
selectedPage.rootInstanceId,
];
- const pasteTarget = getPasteTarget(data, instanceSelector);
+ const pasteTarget = getPasteTarget(fragment, instanceSelector);
if (pasteTarget === undefined) {
return false;
}
- insertInstancesSliceCopy({
- slice: data,
- availableDataSources: findAvailableDataSources(
- $dataSources.get(),
- $instances.get(),
- instanceSelector
- ),
- beforeTransactionEnd: (rootInstanceId, draft) => {
- let dropTarget = pasteTarget;
- dropTarget =
- getInstanceOrCreateFragmentIfNecessary(draft.instances, dropTarget) ??
- dropTarget;
- dropTarget =
- wrapEditableChildrenAroundDropTargetMutable(
- draft.instances,
- draft.props,
- metas,
- dropTarget
- ) ?? dropTarget;
- const [parentId] = dropTarget.parentSelector;
- const parentInstance = draft.instances.get(parentId);
- if (parentInstance === undefined) {
- return;
- }
- const child: Instance["children"][number] = {
- type: "id",
- value: rootInstanceId,
- };
- const { position } = dropTarget;
- if (position === "end") {
- parentInstance.children.push(child);
- } else {
- parentInstance.children.splice(position, 0, child);
- }
- },
+ updateWebstudioData((data) => {
+ const rootInstanceId = insertInstancesSliceCopy({
+ data,
+ slice: fragment,
+ availableDataSources: findAvailableDataSources(
+ data.dataSources,
+ data.instances,
+ instanceSelector
+ ),
+ });
+ if (rootInstanceId === undefined) {
+ return;
+ }
+ let dropTarget = pasteTarget;
+ dropTarget =
+ getInstanceOrCreateFragmentIfNecessary(data.instances, dropTarget) ??
+ dropTarget;
+ dropTarget =
+ wrapEditableChildrenAroundDropTargetMutable(
+ data.instances,
+ data.props,
+ metas,
+ dropTarget
+ ) ?? dropTarget;
+ const [parentId] = dropTarget.parentSelector;
+ const parentInstance = data.instances.get(parentId);
+ if (parentInstance === undefined) {
+ return;
+ }
+ const child: Instance["children"][number] = {
+ type: "id",
+ value: rootInstanceId,
+ };
+ const { position } = dropTarget;
+ if (position === "end") {
+ parentInstance.children.push(child);
+ } else {
+ parentInstance.children.splice(position, 0, child);
+ }
});
return true;
diff --git a/apps/builder/app/shared/instance-utils.test.ts b/apps/builder/app/shared/instance-utils.test.ts
index 4b948275cd..a57532e340 100644
--- a/apps/builder/app/shared/instance-utils.test.ts
+++ b/apps/builder/app/shared/instance-utils.test.ts
@@ -9,6 +9,7 @@ import {
import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";
import type {
Asset,
+ Breakpoint,
DataSource,
Instance,
Instances,
@@ -16,6 +17,7 @@ import type {
Resource,
StyleDecl,
StyleDeclKey,
+ StyleSource,
WebstudioData,
} from "@webstudio-is/sdk";
import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";
@@ -544,7 +546,7 @@ describe("reparent instance", () => {
});
});
-const getWebstudioData = (data: Partial<WebstudioData>): WebstudioData => ({
+const getWebstudioData = (data?: Partial<WebstudioData>): WebstudioData => ({
pages: createDefaultPages({ rootInstanceId: "" }),
assets: new Map(),
dataSources: new Map(),
@@ -1081,9 +1083,10 @@ describe("insert instances slice copy", () => {
assets: [],
};
+ $project.set({ id: "current_project" } as Project);
+
beforeEach(() => {
$pages.set(createDefaultPages({ rootInstanceId: "" }));
- $project.set({ id: "current_project" } as Project);
$assets.set(new Map());
$breakpoints.set(new Map());
$styleSourceSelections.set(new Map());
@@ -1095,21 +1098,24 @@ describe("insert instances slice copy", () => {
});
test("insert assets with same ids if missing", () => {
+ const data = getWebstudioData();
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
assets: [createImageAsset("asset1", "name", "another_project")],
},
availableDataSources: new Set(),
});
- expect(Array.from($assets.get().values())).toEqual([
+ expect(Array.from(data.assets.values())).toEqual([
createImageAsset("asset1", "name", "current_project"),
]);
- $assets.set(
- toMap([createImageAsset("asset1", "changed_name", "current_project")])
- );
+ data.assets = toMap([
+ createImageAsset("asset1", "changed_name", "current_project"),
+ ]);
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
assets: [
@@ -1119,7 +1125,7 @@ describe("insert instances slice copy", () => {
},
availableDataSources: new Set(),
});
- expect(Array.from($assets.get().values())).toEqual([
+ expect(Array.from(data.assets.values())).toEqual([
// preserve any user changes
createImageAsset("asset1", "changed_name", "current_project"),
// add new assets while preserving old ones
@@ -1128,13 +1134,13 @@ describe("insert instances slice copy", () => {
});
test("merge breakpoints with existing ones", () => {
- $breakpoints.set(
- toMap([
- { id: "existing_base", label: "base" },
- { id: "existing_small", label: "small", minWidth: 768 },
- ])
- );
+ const breakpoints = toMap<Breakpoint>([
+ { id: "existing_base", label: "base" },
+ { id: "existing_small", label: "small", minWidth: 768 },
+ ]);
+ const data = getWebstudioData({ breakpoints });
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
breakpoints: [
@@ -1153,7 +1159,7 @@ describe("insert instances slice copy", () => {
},
availableDataSources: new Set(),
});
- expect(Array.from($breakpoints.get().values())).toEqual([
+ 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 },
@@ -1161,11 +1167,13 @@ describe("insert instances slice copy", () => {
});
test("insert missing tokens and use merged breakpoint ids", () => {
- $breakpoints.set(toMap([{ id: "base", label: "base" }]));
- $styleSources.set(
- toMap([{ id: "token1", type: "token", name: "oldLabel" }])
- );
+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);
+ const styleSources = toMap<StyleSource>([
+ { id: "token1", type: "token", name: "oldLabel" },
+ ]);
+ const data = getWebstudioData({ breakpoints, styleSources });
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
breakpoints: [{ id: "new_base", label: "Base" }],
@@ -1190,11 +1198,11 @@ describe("insert instances slice copy", () => {
},
availableDataSources: new Set(),
});
- expect(Array.from($styleSources.get().values())).toEqual([
+ expect(Array.from(data.styleSources.values())).toEqual([
{ id: "token1", type: "token", name: "oldLabel" },
{ id: "token2", type: "token", name: "myToken" },
]);
- expect(Array.from($styles.get().values())).toEqual([
+ expect(Array.from(data.styles.values())).toEqual([
{
styleSourceId: "token2",
breakpointId: "base",
@@ -1205,7 +1213,9 @@ describe("insert instances slice copy", () => {
});
test("insert instances", () => {
+ const data = getWebstudioData();
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
instances: [
@@ -1219,7 +1229,7 @@ describe("insert instances slice copy", () => {
},
availableDataSources: new Set(),
});
- expect(Array.from($instances.get().keys())).toEqual([
+ expect(Array.from(data.instances.keys())).toEqual([
expect.not.stringMatching("box"),
]);
});
@@ -1248,8 +1258,10 @@ describe("insert instances slice copy", () => {
children: [{ type: "text", value: "First" }],
},
];
+ const data = getWebstudioData();
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
instances: instancesWithPortals,
@@ -1257,7 +1269,7 @@ describe("insert instances slice copy", () => {
availableDataSources: new Set(),
});
- expect(Array.from($instances.get().values())).toEqual([
+ expect(Array.from(data.instances.values())).toEqual([
{
type: "instance",
id: "fragment",
@@ -1280,16 +1292,15 @@ describe("insert instances slice copy", () => {
// change portal content and make sure it does not break
// when stale portal with same id is inserted
- const instancesWithDeletedBoxes = new Map($instances.get());
- instancesWithDeletedBoxes.delete("box");
- instancesWithDeletedBoxes.set("fragment", {
+ data.instances.delete("box");
+ data.instances.set("fragment", {
type: "instance",
id: "fragment",
component: "Fragment",
children: [],
});
- $instances.set(instancesWithDeletedBoxes);
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
instances: instancesWithPortals,
@@ -1297,7 +1308,7 @@ describe("insert instances slice copy", () => {
availableDataSources: new Set(),
});
- expect(Array.from($instances.get().values())).toEqual([
+ expect(Array.from(data.instances.values())).toEqual([
{
type: "instance",
id: "fragment",
@@ -1320,7 +1331,9 @@ describe("insert instances slice copy", () => {
});
test("insert props with new ids", () => {
+ const data = getWebstudioData();
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
props: [
@@ -1335,7 +1348,7 @@ describe("insert instances slice copy", () => {
},
availableDataSources: new Set(),
});
- expect(Array.from($props.get().values())).toEqual([
+ expect(Array.from(data.props.values())).toEqual([
{
id: expect.not.stringMatching("prop1"),
instanceId: expect.not.stringMatching("body"),
@@ -1347,7 +1360,9 @@ describe("insert instances slice copy", () => {
});
test("insert props from portals with old ids", () => {
+ const data = getWebstudioData();
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
// portal
@@ -1378,7 +1393,7 @@ describe("insert instances slice copy", () => {
},
availableDataSources: new Set(),
});
- expect(Array.from($props.get().values())).toEqual([
+ expect(Array.from(data.props.values())).toEqual([
{
id: "prop1",
instanceId: "fragment",
@@ -1390,7 +1405,9 @@ describe("insert instances slice copy", () => {
});
test("insert data sources with new ids", () => {
+ const data = getWebstudioData();
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
dataSources: [
@@ -1434,9 +1451,9 @@ describe("insert instances slice copy", () => {
},
availableDataSources: new Set(),
});
- const [newVariableId] = $dataSources.get().keys();
+ const [newVariableId] = data.dataSources.keys();
expect(newVariableId).not.toEqual("variableId");
- expect(Array.from($dataSources.get().values())).toEqual([
+ expect(Array.from(data.dataSources.values())).toEqual([
{
id: newVariableId,
scopeInstanceId: expect.not.stringMatching("body"),
@@ -1445,7 +1462,7 @@ describe("insert instances slice copy", () => {
value: { type: "string", value: "" },
},
]);
- expect(Array.from($props.get().values())).toEqual([
+ expect(Array.from(data.props.values())).toEqual([
{
id: expect.not.stringMatching("expressionId"),
instanceId: expect.not.stringMatching("body"),
@@ -1477,7 +1494,9 @@ describe("insert instances slice copy", () => {
});
test("inline data sources when not available in scope", () => {
+ const data = getWebstudioData();
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
dataSources: [
@@ -1527,8 +1546,8 @@ describe("insert instances slice copy", () => {
},
availableDataSources: new Set(["insideVariableId"]),
});
- expect($dataSources.get()).toEqual(new Map());
- expect(Array.from($props.get().values())).toEqual([
+ expect(data.dataSources).toEqual(new Map());
+ expect(Array.from(data.props.values())).toEqual([
{
id: expect.not.stringMatching("expressionId"),
instanceId: expect.not.stringMatching("body"),
@@ -1553,7 +1572,9 @@ describe("insert instances slice copy", () => {
});
test("insert data sources from portals with old ids", () => {
+ const data = getWebstudioData();
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
// portal
@@ -1613,7 +1634,7 @@ describe("insert instances slice copy", () => {
},
availableDataSources: new Set(),
});
- expect(Array.from($dataSources.get().values())).toEqual([
+ expect(Array.from(data.dataSources.values())).toEqual([
{
id: "variableId",
scopeInstanceId: "fragment",
@@ -1622,7 +1643,7 @@ describe("insert instances slice copy", () => {
value: { type: "string", value: "" },
},
]);
- expect(Array.from($props.get().values())).toEqual([
+ expect(Array.from(data.props.values())).toEqual([
{
id: "expressionId",
instanceId: "fragment",
@@ -1654,7 +1675,9 @@ describe("insert instances slice copy", () => {
});
test("inline data sources from portals when not available in scope", () => {
+ const data = getWebstudioData();
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
// portal
@@ -1720,8 +1743,8 @@ describe("insert instances slice copy", () => {
},
availableDataSources: new Set(["insideVariableId"]),
});
- expect($dataSources.get()).toEqual(new Map());
- expect(Array.from($props.get().values())).toEqual([
+ expect(data.dataSources).toEqual(new Map());
+ expect(Array.from(data.props.values())).toEqual([
{
id: "expressionId",
instanceId: "fragment",
@@ -1746,8 +1769,10 @@ describe("insert instances slice copy", () => {
});
test("insert local styles with new ids and use merged breakpoint ids", () => {
- $breakpoints.set(toMap([{ id: "base", label: "base" }]));
+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);
+ const data = getWebstudioData({ breakpoints });
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
instances: [
@@ -1781,16 +1806,16 @@ describe("insert instances slice copy", () => {
},
availableDataSources: new Set(),
});
- expect(Array.from($styleSourceSelections.get().values())).toEqual([
+ expect(Array.from(data.styleSourceSelections.values())).toEqual([
{
instanceId: expect.not.stringMatching("box"),
values: [expect.not.stringMatching("localId"), "tokenId"],
},
]);
- expect(Array.from($styleSources.get().values())).toEqual([
+ expect(Array.from(data.styleSources.values())).toEqual([
{ id: expect.not.stringMatching("localId"), type: "local" },
]);
- expect(Array.from($styles.get().values())).toEqual([
+ expect(Array.from(data.styles.values())).toEqual([
{
styleSourceId: expect.not.stringMatching("localId"),
breakpointId: "base",
@@ -1801,8 +1826,10 @@ describe("insert instances slice copy", () => {
});
test("insert local styles from portal and use merged breakpoint ids", () => {
- $breakpoints.set(toMap([{ id: "base", label: "base" }]));
+ const breakpoints = toMap<Breakpoint>([{ id: "base", label: "base" }]);
+ const data = getWebstudioData({ breakpoints });
insertInstancesSliceCopy({
+ data,
slice: {
...emptySlice,
// portal
@@ -1844,13 +1871,13 @@ describe("insert instances slice copy", () => {
},
availableDataSources: new Set(),
});
- expect(Array.from($styleSourceSelections.get().values())).toEqual([
+ expect(Array.from(data.styleSourceSelections.values())).toEqual([
{ instanceId: "fragment", values: ["localId", "tokenId"] },
]);
- expect(Array.from($styleSources.get().values())).toEqual([
+ expect(Array.from(data.styleSources.values())).toEqual([
{ id: "localId", type: "local" },
]);
- expect(Array.from($styles.get().values())).toEqual([
+ expect(Array.from(data.styles.values())).toEqual([
{
styleSourceId: "localId",
breakpointId: "base",
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index 0a08853df1..285b2c7cfe 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -16,7 +16,6 @@ import {
Props,
DataSource,
Breakpoint,
- Pages,
type WebstudioFragment,
type WebstudioData,
} from "@webstudio-is/sdk";
@@ -830,16 +829,13 @@ const replaceDataSources = (
};
export const insertInstancesSliceCopy = ({
+ data,
slice,
availableDataSources,
- beforeTransactionEnd,
}: {
+ data: WebstudioData;
slice: WebstudioFragment;
availableDataSources: Set<DataSource["id"]>;
- beforeTransactionEnd?: (
- rootInstanceId: Instance["id"],
- draft: { instances: Instances; props: Props; pages: undefined | Pages }
- ) => void;
}) => {
const projectId = $project.get()?.id;
if (projectId === undefined) {
@@ -864,356 +860,342 @@ export const insertInstancesSliceCopy = ({
sliceDataSources.set(dataSource.id, dataSource);
}
- serverSyncStore.createTransaction(
- [
- $assets,
- $instances,
- $dataSources,
- $props,
- $breakpoints,
- $styleSources,
- $styles,
- $styleSourceSelections,
- $pages,
- ],
- (
- assets,
- instances,
- dataSources,
- props,
- breakpoints,
- styleSources,
- styles,
- styleSourceSelections,
- pages
- ) => {
- /**
- * insert reusables without changing their ids to not bloat data
- * and catch up with user changes
- * - assets
- * - breakpoints
- * - token styles
- * - portals
- *
- * breakpoints behave slightly differently and merged with existing ones
- * and those ids are used instead
- */
-
- // insert assets
-
- for (const asset of slice.assets) {
- // asset can be already present if pasting to the same project
- if (assets.has(asset.id) === false) {
- // we use the same asset.id so the references are preserved
- assets.set(asset.id, { ...asset, projectId });
- }
- }
+ const {
+ assets,
+ instances,
+ dataSources,
+ props,
+ breakpoints,
+ styleSources,
+ styles,
+ styleSourceSelections,
+ } = data;
- // merge breakpoints
+ /**
+ * insert reusables without changing their ids to not bloat data
+ * and catch up with user changes
+ * - assets
+ * - breakpoints
+ * - token styles
+ * - portals
+ *
+ * breakpoints behave slightly differently and merged with existing ones
+ * and those ids are used instead
+ */
+
+ // insert assets
+
+ for (const asset of slice.assets) {
+ // asset can be already present if pasting to the same project
+ if (assets.has(asset.id) === false) {
+ // we use the same asset.id so the references are preserved
+ assets.set(asset.id, { ...asset, projectId });
+ }
+ }
- const mergedBreakpointIds = new Map<Breakpoint["id"], Breakpoint["id"]>();
- for (const newBreakpoint of slice.breakpoints) {
- let matched = false;
- for (const breakpoint of breakpoints.values()) {
- if (equalMedia(breakpoint, newBreakpoint)) {
- matched = true;
- mergedBreakpointIds.set(newBreakpoint.id, breakpoint.id);
- break;
- }
- }
- if (matched === false) {
- breakpoints.set(newBreakpoint.id, newBreakpoint);
- }
+ // merge breakpoints
+
+ const mergedBreakpointIds = new Map<Breakpoint["id"], Breakpoint["id"]>();
+ for (const newBreakpoint of slice.breakpoints) {
+ let matched = false;
+ for (const breakpoint of breakpoints.values()) {
+ if (equalMedia(breakpoint, newBreakpoint)) {
+ matched = true;
+ mergedBreakpointIds.set(newBreakpoint.id, breakpoint.id);
+ break;
}
+ }
+ if (matched === false) {
+ breakpoints.set(newBreakpoint.id, newBreakpoint);
+ }
+ }
- // insert tokens with their styles
+ // insert tokens with their styles
- const tokenStyleSourceIds = new Set<StyleSource["id"]>();
- for (const styleSource of slice.styleSources) {
- // prevent inserting styles when token is already present
- if (styleSource.type === "local" || styleSources.has(styleSource.id)) {
- continue;
- }
- styleSource.type satisfies "token";
- tokenStyleSourceIds.add(styleSource.id);
- styleSources.set(styleSource.id, styleSource);
- }
- for (const styleDecl of slice.styles) {
- if (tokenStyleSourceIds.has(styleDecl.styleSourceId)) {
- const { breakpointId } = styleDecl;
- const newStyleDecl: StyleDecl = {
- ...styleDecl,
- breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,
- };
- styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);
- }
- }
+ const tokenStyleSourceIds = new Set<StyleSource["id"]>();
+ for (const styleSource of slice.styleSources) {
+ // prevent inserting styles when token is already present
+ if (styleSource.type === "local" || styleSources.has(styleSource.id)) {
+ continue;
+ }
+ styleSource.type satisfies "token";
+ tokenStyleSourceIds.add(styleSource.id);
+ styleSources.set(styleSource.id, styleSource);
+ }
+ for (const styleDecl of slice.styles) {
+ if (tokenStyleSourceIds.has(styleDecl.styleSourceId)) {
+ const { breakpointId } = styleDecl;
+ const newStyleDecl: StyleDecl = {
+ ...styleDecl,
+ breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,
+ };
+ styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);
+ }
+ }
- // insert portal contents
- // - instances
- // - data sources
- // - props
- // - local styles
- for (const rootInstanceId of portalContentIds) {
- // prevent reinserting portals which could be already changed by user
- if (instances.has(rootInstanceId)) {
- continue;
- }
+ // insert portal contents
+ // - instances
+ // - data sources
+ // - props
+ // - local styles
+ for (const rootInstanceId of portalContentIds) {
+ // prevent reinserting portals which could be already changed by user
+ if (instances.has(rootInstanceId)) {
+ continue;
+ }
- const instanceIds = findTreeInstanceIdsExcludingSlotDescendants(
- sliceInstances,
- rootInstanceId
- );
- for (const instance of slice.instances) {
- if (instanceIds.has(instance.id)) {
- instances.set(instance.id, instance);
- }
- }
+ const instanceIds = findTreeInstanceIdsExcludingSlotDescendants(
+ sliceInstances,
+ rootInstanceId
+ );
+ for (const instance of slice.instances) {
+ if (instanceIds.has(instance.id)) {
+ instances.set(instance.id, instance);
+ }
+ }
- const availablePortalDataSources = new Set(availableDataSources);
- for (const dataSource of slice.dataSources) {
- // insert only data sources within portal content
- if (
- dataSource.scopeInstanceId &&
- instanceIds.has(dataSource.scopeInstanceId)
- ) {
- availablePortalDataSources.add(dataSource.id);
- dataSources.set(dataSource.id, dataSource);
- }
- }
+ const availablePortalDataSources = new Set(availableDataSources);
+ for (const dataSource of slice.dataSources) {
+ // insert only data sources within portal content
+ if (
+ dataSource.scopeInstanceId &&
+ instanceIds.has(dataSource.scopeInstanceId)
+ ) {
+ availablePortalDataSources.add(dataSource.id);
+ dataSources.set(dataSource.id, dataSource);
+ }
+ }
- for (let prop of slice.props) {
- if (instanceIds.has(prop.instanceId) === false) {
- continue;
- }
- // inline data sources not available in scope into expressions
- if (prop.type === "expression") {
- const { code } = inlineUnavailableDataSources({
- code: prop.value,
+ for (let prop of slice.props) {
+ if (instanceIds.has(prop.instanceId) === false) {
+ continue;
+ }
+ // inline data sources not available in scope into expressions
+ if (prop.type === "expression") {
+ const { code } = inlineUnavailableDataSources({
+ code: prop.value,
+ availableDataSources: availablePortalDataSources,
+ dataSources: sliceDataSources,
+ });
+ prop = { ...prop, value: code };
+ }
+ if (prop.type === "action") {
+ prop = {
+ ...prop,
+ value: prop.value.flatMap((value) => {
+ if (value.type !== "execute") {
+ return [value];
+ }
+ const { code, isDiscarded } = inlineUnavailableDataSources({
+ code: value.code,
availableDataSources: availablePortalDataSources,
dataSources: sliceDataSources,
});
- prop = { ...prop, value: code };
- }
- if (prop.type === "action") {
- prop = {
- ...prop,
- value: prop.value.flatMap((value) => {
- if (value.type !== "execute") {
- return [value];
- }
- const { code, isDiscarded } = inlineUnavailableDataSources({
- code: value.code,
- availableDataSources: availablePortalDataSources,
- dataSources: sliceDataSources,
- });
- if (isDiscarded) {
- return [];
- }
- return [{ ...value, code }];
- }),
- };
- }
- props.set(prop.id, prop);
- }
+ if (isDiscarded) {
+ return [];
+ }
+ return [{ ...value, code }];
+ }),
+ };
+ }
+ props.set(prop.id, prop);
+ }
- // insert local style sources with their styles
+ // insert local style sources with their styles
- const instanceStyleSourceIds = new Set<StyleSource["id"]>();
- for (const styleSourceSelection of slice.styleSourceSelections) {
- const { instanceId } = styleSourceSelection;
- if (instanceIds.has(instanceId) === false) {
- continue;
- }
- styleSourceSelections.set(instanceId, styleSourceSelection);
- for (const styleSourceId of styleSourceSelection.values) {
- instanceStyleSourceIds.add(styleSourceId);
- }
- }
- const localStyleSourceIds = new Set<StyleSource["id"]>();
- for (const styleSource of slice.styleSources) {
- if (
- styleSource.type === "local" &&
- instanceStyleSourceIds.has(styleSource.id)
- ) {
- localStyleSourceIds.add(styleSource.id);
- styleSources.set(styleSource.id, styleSource);
- }
- }
- for (const styleDecl of slice.styles) {
- if (localStyleSourceIds.has(styleDecl.styleSourceId)) {
- const { breakpointId } = styleDecl;
- const newStyleDecl: StyleDecl = {
- ...styleDecl,
- breakpointId:
- mergedBreakpointIds.get(breakpointId) ?? breakpointId,
- };
- styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);
- }
- }
+ const instanceStyleSourceIds = new Set<StyleSource["id"]>();
+ for (const styleSourceSelection of slice.styleSourceSelections) {
+ const { instanceId } = styleSourceSelection;
+ if (instanceIds.has(instanceId) === false) {
+ continue;
}
-
- /**
- * inserting unique content is structurally similar to inserting portal content
- * but all ids are regenerated to support duplicating existing content
- * - instances
- * - data sources
- * - props
- * - local styles
- */
-
- // generate new ids only instances outside of portals
- const sliceInstanceIds = findTreeInstanceIdsExcludingSlotDescendants(
- sliceInstances,
- slice.instances[0].id
- );
- const newInstanceIds = new Map<Instance["id"], Instance["id"]>();
- for (const instanceId of sliceInstanceIds) {
- newInstanceIds.set(instanceId, nanoid());
+ styleSourceSelections.set(instanceId, styleSourceSelection);
+ for (const styleSourceId of styleSourceSelection.values) {
+ instanceStyleSourceIds.add(styleSourceId);
}
- for (const instance of slice.instances) {
- if (sliceInstanceIds.has(instance.id)) {
- const newId = newInstanceIds.get(instance.id) ?? instance.id;
- instances.set(newId, {
- ...instance,
- id: newId,
- children: instance.children.map((child) => {
- if (child.type === "id") {
- return {
- type: "id",
- value: newInstanceIds.get(child.value) ?? child.value,
- };
- }
- return child;
- }),
- });
- }
+ }
+ const localStyleSourceIds = new Set<StyleSource["id"]>();
+ for (const styleSource of slice.styleSources) {
+ if (
+ styleSource.type === "local" &&
+ instanceStyleSourceIds.has(styleSource.id)
+ ) {
+ localStyleSourceIds.add(styleSource.id);
+ styleSources.set(styleSource.id, styleSource);
}
-
- const availablePortalDataSources = new Set(availableDataSources);
- const newDataSourceIds = new Map<DataSource["id"], DataSource["id"]>();
- for (const dataSource of slice.dataSources) {
- const { scopeInstanceId } = dataSource;
- // insert only data sources within portal content
- if (scopeInstanceId && sliceInstanceIds.has(scopeInstanceId)) {
- availablePortalDataSources.add(dataSource.id);
- const newId = nanoid();
- newDataSourceIds.set(dataSource.id, newId);
- dataSources.set(newId, {
- ...dataSource,
- id: newId,
- scopeInstanceId: newInstanceIds.get(scopeInstanceId),
- });
- }
+ }
+ for (const styleDecl of slice.styles) {
+ if (localStyleSourceIds.has(styleDecl.styleSourceId)) {
+ const { breakpointId } = styleDecl;
+ const newStyleDecl: StyleDecl = {
+ ...styleDecl,
+ breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,
+ };
+ styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);
}
+ }
+ }
- for (let prop of slice.props) {
- if (sliceInstanceIds.has(prop.instanceId) === false) {
- continue;
- }
- // inline data sources not available in scope into expressions
- if (prop.type === "expression") {
- const { code } = inlineUnavailableDataSources({
- code: prop.value,
+ /**
+ * inserting unique content is structurally similar to inserting portal content
+ * but all ids are regenerated to support duplicating existing content
+ * - instances
+ * - data sources
+ * - props
+ * - local styles
+ */
+
+ // generate new ids only instances outside of portals
+ const sliceInstanceIds = findTreeInstanceIdsExcludingSlotDescendants(
+ sliceInstances,
+ slice.instances[0].id
+ );
+ const newInstanceIds = new Map<Instance["id"], Instance["id"]>();
+ for (const instanceId of sliceInstanceIds) {
+ newInstanceIds.set(instanceId, nanoid());
+ }
+ for (const instance of slice.instances) {
+ if (sliceInstanceIds.has(instance.id)) {
+ const newId = newInstanceIds.get(instance.id) ?? instance.id;
+ instances.set(newId, {
+ ...instance,
+ id: newId,
+ children: instance.children.map((child) => {
+ if (child.type === "id") {
+ return {
+ type: "id",
+ value: newInstanceIds.get(child.value) ?? child.value,
+ };
+ }
+ return child;
+ }),
+ });
+ }
+ }
+
+ const availablePortalDataSources = new Set(availableDataSources);
+ const newDataSourceIds = new Map<DataSource["id"], DataSource["id"]>();
+ for (const dataSource of slice.dataSources) {
+ const { scopeInstanceId } = dataSource;
+ // insert only data sources within portal content
+ if (scopeInstanceId && sliceInstanceIds.has(scopeInstanceId)) {
+ availablePortalDataSources.add(dataSource.id);
+ const newId = nanoid();
+ newDataSourceIds.set(dataSource.id, newId);
+ dataSources.set(newId, {
+ ...dataSource,
+ id: newId,
+ scopeInstanceId: newInstanceIds.get(scopeInstanceId),
+ });
+ }
+ }
+
+ for (let prop of slice.props) {
+ if (sliceInstanceIds.has(prop.instanceId) === false) {
+ continue;
+ }
+ // inline data sources not available in scope into expressions
+ if (prop.type === "expression") {
+ const { code } = inlineUnavailableDataSources({
+ code: prop.value,
+ availableDataSources: availablePortalDataSources,
+ dataSources: sliceDataSources,
+ });
+ prop = { ...prop, value: replaceDataSources(code, newDataSourceIds) };
+ }
+ if (prop.type === "action") {
+ prop = {
+ ...prop,
+ value: prop.value.flatMap((value) => {
+ if (value.type !== "execute") {
+ return [value];
+ }
+ const { code, isDiscarded } = inlineUnavailableDataSources({
+ code: value.code,
availableDataSources: availablePortalDataSources,
dataSources: sliceDataSources,
});
- prop = { ...prop, value: replaceDataSources(code, newDataSourceIds) };
- }
- if (prop.type === "action") {
- prop = {
- ...prop,
- value: prop.value.flatMap((value) => {
- if (value.type !== "execute") {
- return [value];
- }
- const { code, isDiscarded } = inlineUnavailableDataSources({
- code: value.code,
- availableDataSources: availablePortalDataSources,
- dataSources: sliceDataSources,
- });
- if (isDiscarded) {
- return [];
- }
- return [
- { ...value, code: replaceDataSources(code, newDataSourceIds) },
- ];
- }),
- };
- }
- if (prop.type === "parameter") {
- prop = {
- ...prop,
- value: newDataSourceIds.get(prop.value) ?? prop.value,
- };
- }
- const newId = nanoid();
- props.set(newId, {
- ...prop,
- id: newId,
- instanceId: newInstanceIds.get(prop.instanceId) ?? prop.instanceId,
- });
- }
-
- // insert local styles with new ids
+ if (isDiscarded) {
+ return [];
+ }
+ return [
+ { ...value, code: replaceDataSources(code, newDataSourceIds) },
+ ];
+ }),
+ };
+ }
+ if (prop.type === "parameter") {
+ prop = {
+ ...prop,
+ value: newDataSourceIds.get(prop.value) ?? prop.value,
+ };
+ }
+ const newId = nanoid();
+ props.set(newId, {
+ ...prop,
+ id: newId,
+ instanceId: newInstanceIds.get(prop.instanceId) ?? prop.instanceId,
+ });
+ }
- const instanceStyleSourceIds = new Set<StyleSource["id"]>();
- for (const styleSourceSelection of slice.styleSourceSelections) {
- if (sliceInstanceIds.has(styleSourceSelection.instanceId) === false) {
- continue;
- }
- for (const styleSourceId of styleSourceSelection.values) {
- instanceStyleSourceIds.add(styleSourceId);
- }
- }
- const newLocalStyleSourceIds = new Map<
- StyleSource["id"],
- StyleSource["id"]
- >();
- for (const styleSource of slice.styleSources) {
- if (
- styleSource.type === "local" &&
- instanceStyleSourceIds.has(styleSource.id)
- ) {
- const newId = nanoid();
- newLocalStyleSourceIds.set(styleSource.id, newId);
- styleSources.set(newId, { ...styleSource, id: newId });
- }
- }
- for (const styleSourceSelection of slice.styleSourceSelections) {
- const { instanceId, values } = styleSourceSelection;
- if (sliceInstanceIds.has(instanceId) === false) {
- continue;
- }
- const newInstanceId = newInstanceIds.get(instanceId) ?? instanceId;
- styleSourceSelections.set(newInstanceId, {
- instanceId: newInstanceId,
- values: values.map(
- (styleSourceId) =>
- newLocalStyleSourceIds.get(styleSourceId) ?? styleSourceId
- ),
- });
- for (const styleSourceId of styleSourceSelection.values) {
- instanceStyleSourceIds.add(styleSourceId);
- }
- }
- for (const styleDecl of slice.styles) {
- const { breakpointId, styleSourceId } = styleDecl;
- if (newLocalStyleSourceIds.has(styleDecl.styleSourceId)) {
- const newStyleDecl: StyleDecl = {
- ...styleDecl,
- styleSourceId:
- newLocalStyleSourceIds.get(styleSourceId) ?? styleSourceId,
- breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,
- };
- styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);
- }
- }
+ // insert local styles with new ids
- // invoke callback to allow additional changes within same transaction
- const rootInstanceId =
- newInstanceIds.get(slice.instances[0].id) ?? slice.instances[0].id;
- beforeTransactionEnd?.(rootInstanceId, { instances, props, pages });
+ const instanceStyleSourceIds = new Set<StyleSource["id"]>();
+ for (const styleSourceSelection of slice.styleSourceSelections) {
+ if (sliceInstanceIds.has(styleSourceSelection.instanceId) === false) {
+ continue;
}
- );
+ for (const styleSourceId of styleSourceSelection.values) {
+ instanceStyleSourceIds.add(styleSourceId);
+ }
+ }
+ const newLocalStyleSourceIds = new Map<
+ StyleSource["id"],
+ StyleSource["id"]
+ >();
+ for (const styleSource of slice.styleSources) {
+ if (
+ styleSource.type === "local" &&
+ instanceStyleSourceIds.has(styleSource.id)
+ ) {
+ const newId = nanoid();
+ newLocalStyleSourceIds.set(styleSource.id, newId);
+ styleSources.set(newId, { ...styleSource, id: newId });
+ }
+ }
+ for (const styleSourceSelection of slice.styleSourceSelections) {
+ const { instanceId, values } = styleSourceSelection;
+ if (sliceInstanceIds.has(instanceId) === false) {
+ continue;
+ }
+ const newInstanceId = newInstanceIds.get(instanceId) ?? instanceId;
+ styleSourceSelections.set(newInstanceId, {
+ instanceId: newInstanceId,
+ values: values.map(
+ (styleSourceId) =>
+ newLocalStyleSourceIds.get(styleSourceId) ?? styleSourceId
+ ),
+ });
+ for (const styleSourceId of styleSourceSelection.values) {
+ instanceStyleSourceIds.add(styleSourceId);
+ }
+ }
+ for (const styleDecl of slice.styles) {
+ const { breakpointId, styleSourceId } = styleDecl;
+ if (newLocalStyleSourceIds.has(styleDecl.styleSourceId)) {
+ const newStyleDecl: StyleDecl = {
+ ...styleDecl,
+ styleSourceId:
+ newLocalStyleSourceIds.get(styleSourceId) ?? styleSourceId,
+ breakpointId: mergedBreakpointIds.get(breakpointId) ?? breakpointId,
+ };
+ styles.set(getStyleDeclKey(newStyleDecl), newStyleDecl);
+ }
+ }
+
+ // invoke callback to allow additional changes within same transaction
+ const rootInstanceId =
+ newInstanceIds.get(slice.instances[0].id) ?? slice.instances[0].id;
+
+ return rootInstanceId;
};