Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
refactor: generalize page copying logic (#3424)
Bogdan Chadkin9980bb9f474d
diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.test.ts b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.test.tsindex c8c88a9186..719ac18555 100644--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.test.ts+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.test.ts@@ -1,12 +1,8 @@import { describe, expect, test } from "@jest/globals";-import type { Project } from "@webstudio-is/project";import { createDefaultPages } from "@webstudio-is/project-build";import {isRoot,type Folder,- Instance,- DataSource,- encodeDataSourceVariable,ROOT_FOLDER_ID,type Page,} from "@webstudio-is/sdk";@@ -20,7 +16,6 @@ import {toTreeData,filterSelfAndChildren,getExistingRoutePaths,- duplicatePage,$editingPagesItemId,$pageRootScope,isPathAvailable,@@ -28,9 +23,7 @@ import {import {$dataSourceVariables,$dataSources,- $instances,$pages,- $project,$resourceValues,$selectedPageId,} from "~/shared/nano-states";@@ -575,302 +568,6 @@ describe("getExistingRoutePaths", () => {});});-describe("duplicate page", () => {- $project.set({ id: "projectId" } as Project);-- test("home page with new root instance and system data source", () => {- $instances.set(- toMap<Instance>([- { type: "instance", id: "body", component: "Body", children: [] },- ])- );- $dataSources.set(- toMap<DataSource>([- {- id: "system",- scopeInstanceId: "body",- name: "system",- type: "parameter",- },- ])- );- $pages.set({- homePage: {- id: "pageId",- name: "My Name",- path: "/",- title: `"My Title"`,- meta: {},- rootInstanceId: "body",- systemDataSourceId: "system",- },- pages: [],- folders: [],- });- duplicatePage("pageId");- const newPage = $pages.get()?.pages[0];- if (newPage === undefined) {- throw Error("New page does not exist");- }- expect(newPage).toEqual({- id: expect.not.stringMatching("pageId"),- name: "My Name (1)",- path: "/copy-1",- title: `"My Title"`,- meta: {},- rootInstanceId: expect.not.stringMatching("body"),- systemDataSourceId: expect.not.stringMatching("system"),- });- expect($dataSources.get()).toEqual(- toMap<DataSource>([- {- id: "system",- scopeInstanceId: "body",- name: "system",- type: "parameter",- },- {- id: newPage.systemDataSourceId,- scopeInstanceId: newPage.rootInstanceId,- name: "system",- type: "parameter",- },- ])- );- expect($instances.get()).toEqual(- toMap<Instance>([- {- type: "instance",- id: "body",- component: "Body",- children: [],- },- {- type: "instance",- id: newPage.rootInstanceId,- component: "Body",- children: [],- },- ])- );- });-- test("non-home page preserving old path and name with prefix", () => {- $instances.set(- toMap([{ type: "instance", id: "body", component: "Body", children: [] }])- );- $pages.set({- homePage: {- id: "homeId",- name: "Home",- path: "/",- title: `"Home"`,- meta: {},- rootInstanceId: "home",- systemDataSourceId: "homeSystem",- },- pages: [- {- id: "pageId",- name: "My Name (1)",- path: "/my-path",- title: `"My Title"`,- meta: {},- rootInstanceId: "body",- systemDataSourceId: "pageSystem",- },- ],- folders: [],- });- duplicatePage("pageId");- expect($pages.get()?.pages[1]).toEqual({- id: expect.not.stringMatching("pageId"),- name: "My Name (2)",- path: "/copy-1/my-path",- title: `"My Title"`,- meta: {},- rootInstanceId: expect.not.stringMatching("body"),- systemDataSourceId: "pageSystem",- });- });-- test("handle wildcards", () => {- $instances.set(- toMap([{ type: "instance", id: "body", component: "Body", children: [] }])- );- $pages.set({- homePage: {- id: "homeId",- name: "Home",- path: "/",- title: `"Home"`,- meta: {},- rootInstanceId: "home",- systemDataSourceId: "system",- },- pages: [- {- id: "pageId1",- name: "My Name 1",- path: "/my-path/*",- title: `"My Title"`,- meta: {},- rootInstanceId: "body",- systemDataSourceId: "system",- },- {- id: "pageId2",- name: "My Name 2",- // Named wildcard- path: "/my-path/name*",- title: `"My Title"`,- meta: {},- rootInstanceId: "body",- systemDataSourceId: "system",- },- ],- folders: [],- });- duplicatePage("pageId1");- duplicatePage("pageId2");- expect($pages.get()?.pages[2]).toEqual({- id: expect.not.stringMatching("pageId1"),- name: "My Name 1 (1)",- path: "/copy-1/my-path/*",- title: `"My Title"`,- meta: {},- rootInstanceId: expect.not.stringMatching("body"),- systemDataSourceId: expect.not.stringMatching("system"),- });- expect($pages.get()?.pages[3]).toEqual({- id: expect.not.stringMatching("pageId2"),- name: "My Name 2 (1)",- path: "/copy-1/my-path/name*",- title: `"My Title"`,- meta: {},- rootInstanceId: expect.not.stringMatching("body"),- systemDataSourceId: expect.not.stringMatching("system"),- });- });-- test("check full page path when duplicating inside a folder", () => {- $instances.set(- toMap([{ type: "instance", id: "body", component: "Body", children: [] }])- );- $pages.set({- homePage: {- id: "homeId",- name: "Home",- path: "/",- title: `"Home"`,- meta: {},- rootInstanceId: "home",- systemDataSourceId: "system",- },- pages: [- {- id: "pageId",- name: "My Name",- path: "/my-path",- title: `"My Title"`,- meta: {},- rootInstanceId: "body",- systemDataSourceId: "system",- },- ],- folders: [- {- id: "folderId",- name: "Folder",- slug: "folder",- children: ["pageId"],- },- ],- });- duplicatePage("pageId");- expect($pages.get()?.pages[1]).toEqual({- id: expect.not.stringMatching("pageId"),- name: "My Name (1)",- path: "/copy-1/my-path",- title: `"My Title"`,- meta: {},- rootInstanceId: expect.not.stringMatching("body"),- systemDataSourceId: expect.not.stringMatching("system"),- });- });-- test("replace variables in page meta", () => {- $instances.set(- toMap([{ type: "instance", id: "body", component: "Body", children: [] }])- );- $dataSources.set(- toMap([- {- id: "variableId",- scopeInstanceId: "body",- name: "My Variable",- type: "variable",- value: { type: "string", value: "value" },- },- {- id: "systemId",- scopeInstanceId: "body",- name: "system",- type: "parameter",- },- ])- );- $pages.set({- homePage: {- id: "pageId",- name: "My Name",- path: "/",- title: `"Title: " + $ws$dataSource$variableId`,- meta: {- description: `"Description: " + $ws$dataSource$variableId`,- excludePageFromSearch: `"Exclude: " + $ws$dataSource$variableId`,- socialImageUrl: `"Image: " + $ws$dataSource$variableId`,- custom: [- {- property: "Name",- content: `"Name: " + $ws$dataSource$variableId`,- },- ],- },- rootInstanceId: "body",- systemDataSourceId: "systemId",- },- pages: [],- folders: [],- });- duplicatePage("pageId");- const [_oldDataSource, _systemDataSource, newDataSource] = $dataSources- .get()- .values();- const newVariableName = encodeDataSourceVariable(newDataSource.id);- expect(newVariableName).not.toEqual("$ws$dataSource$variableId");- expect($pages.get()?.pages[0]).toEqual({- id: expect.not.stringMatching("pageId"),- name: "My Name (1)",- path: "/copy-1",- title: `"Title: " + ${newVariableName}`,- meta: {- description: `"Description: " + ${newVariableName}`,- excludePageFromSearch: `"Exclude: " + ${newVariableName}`,- socialImageUrl: `"Image: " + ${newVariableName}`,- custom: [- {- property: "Name",- content: `"Name: " + ${newVariableName}`,- },- ],- },- rootInstanceId: expect.not.stringMatching("body"),- systemDataSourceId: expect.not.stringMatching("systemId"),- });- });-});-test("page root scope should rely on editing page", () => {const pages = createDefaultPages({rootInstanceId: "homeRootId",diff --git a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.ts b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.tsindex aaa8f29778..040d8fd328 100644--- a/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.ts+++ b/apps/builder/app/builder/features/sidebar-left/panels/pages/page-utils.ts@@ -1,4 +1,3 @@-import { nanoid } from "nanoid";import { atom, computed } from "nanostores";import { createRootFolder } from "@webstudio-is/project-build";import {@@ -11,17 +10,12 @@ import {type WebstudioData,getPagePath,findParentFolderByChildId,- DataSource,- decodeDataSourceVariable,encodeDataSourceVariable,- transpileExpression,type System,} from "@webstudio-is/sdk";import { removeByMutable } from "~/shared/array-utils";import {deleteInstanceMutable,- extractWebstudioFragment,- insertWebstudioFragmentCopy,updateWebstudioData,} from "~/shared/instance-utils";import {@@ -35,6 +29,7 @@ import {getPageDefaultSystem,mergeSystem,} from "~/shared/nano-states";+import { insertPageCopyMutable } from "~/shared/page-utils";type TreePage = {type: "page";@@ -420,119 +415,18 @@ export const $pageRootScope = computed(});-const deduplicatePath = (pages: Pages, page: Page) => {- const fullPath = getPagePath(page.id, pages);- let matchedPage = findPageByIdOrPath(fullPath, pages);- let { path } = page;-- if (matchedPage === undefined) {- return path;- }-- if (path === "/") {- path = "";- }-- let counter = 0;- const folder = findParentFolderByChildId(page.id, pages.folders);- const folderPath = folder ? getPagePath(folder.id, pages) : "";- while (matchedPage !== undefined) {- counter += 1;- matchedPage = findPageByIdOrPath(- `${folderPath}/copy-${counter}${path}`,- pages- );- }- return `/copy-${counter}${path}`;-};--const replaceDataSources = (- expression: string,- replacements: Map<DataSource["id"], DataSource["id"]>-) => {- return transpileExpression({- expression,- replaceVariable: (identifier) => {- const dataSourceId = decodeDataSourceVariable(identifier);- if (dataSourceId === undefined) {- return;- }- return encodeDataSourceVariable(- replacements.get(dataSourceId) ?? dataSourceId- );- },- });-};-export const duplicatePage = (pageId: Page["id"]) => {const pages = $pages.get();- if (pages === undefined) {- return;- }- const page = findPageByIdOrPath(pageId, pages);-- if (page === undefined) {+ const currentFolder = findParentFolderByChildId(pageId, pages?.folders ?? []);+ if (currentFolder === undefined) {return;}-- const newPageId = nanoid();- const { name = page.name, copyNumber } =- // extract a number from "name (copyNumber)"- page.name.match(/^(?<name>.+) \((?<copyNumber>\d+)\)$/)?.groups ?? {};- const newName = `${name} (${Number(copyNumber ?? "0") + 1})`;-+ let newPageId: undefined | string;updateWebstudioData((data) => {- const fragment = extractWebstudioFragment(data, page.rootInstanceId);- const { newInstanceIds, newDataSourceIds } = insertWebstudioFragmentCopy({- data,- fragment,- availableDataSources: new Set(),+ newPageId = insertPageCopyMutable({+ source: { data, pageId },+ target: { data, folderId: currentFolder.id },});- const newRootInstanceId = newInstanceIds.get(page.rootInstanceId);- const newSystemDataSourceId =- newDataSourceIds.get(page.systemDataSourceId) ?? page.systemDataSourceId;-- if (newRootInstanceId === undefined) {- return;- }- const newPage = {- ...page,- id: newPageId,- rootInstanceId: newRootInstanceId,- systemDataSourceId: newSystemDataSourceId,- name: newName,- path: deduplicatePath(pages, page),- title: replaceDataSources(page.title, newDataSourceIds),- meta: {- ...page.meta,- description:- page.meta.description === undefined- ? undefined- : replaceDataSources(page.meta.description, newDataSourceIds),- excludePageFromSearch:- page.meta.excludePageFromSearch === undefined- ? undefined- : replaceDataSources(- page.meta.excludePageFromSearch,- newDataSourceIds- ),- socialImageUrl:- page.meta.socialImageUrl === undefined- ? undefined- : replaceDataSources(page.meta.socialImageUrl, newDataSourceIds),- custom: page.meta.custom?.map(({ property, content }) => ({- property,- content: replaceDataSources(content, newDataSourceIds),- })),- },- } 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/shared/page-utils.test.ts b/apps/builder/app/shared/page-utils.test.tsnew file mode 100644index 0000000000..553fb22134--- /dev/null+++ b/apps/builder/app/shared/page-utils.test.ts@@ -0,0 +1,343 @@+import { describe, expect, test } from "@jest/globals";+import type { Project } from "@webstudio-is/project";+import {+ ROOT_FOLDER_ID,+ encodeDataSourceVariable,+ type DataSource,+ type Instance,+ type WebstudioData,+} from "@webstudio-is/sdk";+import {+ createDefaultPages,+ createRootFolder,+} from "@webstudio-is/project-build";+import { $project } from "./nano-states";+import { insertPageCopyMutable } from "./page-utils";++const toMap = <T extends { id: string }>(list: T[]) =>+ new Map(list.map((item) => [item.id, item]));++const getWebstudioDataStub = (+ data?: Partial<WebstudioData>+): WebstudioData => ({+ pages: createDefaultPages({ rootInstanceId: "", systemDataSourceId: "" }),+ 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("insert page copy", () => {+ $project.set({ id: "projectId" } as Project);++ test("insert home page copy with new path and ids", () => {+ const data = getWebstudioDataStub({+ instances: toMap<Instance>([+ { type: "instance", id: "bodyId", component: "Body", children: [] },+ ]),+ dataSources: toMap<DataSource>([+ {+ id: "systemId",+ scopeInstanceId: "bodyId",+ name: "system",+ type: "parameter",+ },+ ]),+ pages: {+ meta: {},+ homePage: {+ id: "pageId",+ name: "Name",+ path: "/",+ title: `"Title"`,+ meta: {},+ rootInstanceId: "bodyId",+ systemDataSourceId: "systemId",+ },+ pages: [],+ folders: [createRootFolder(["pageId"])],+ },+ });+ insertPageCopyMutable({+ source: { data, pageId: "pageId" },+ target: { data, folderId: ROOT_FOLDER_ID },+ });+ expect(data.pages.pages.length).toEqual(1);+ const newPage = data.pages.pages[0];+ expect(newPage).toEqual({+ id: expect.not.stringMatching("pageId"),+ name: "Name (1)",+ path: "/copy-1",+ title: `"Title"`,+ meta: {},+ rootInstanceId: expect.not.stringMatching("bodyId"),+ systemDataSourceId: expect.not.stringMatching("systemId"),+ });+ expect(data.dataSources.size).toEqual(2);+ expect(Array.from(data.dataSources.values())[1]).toEqual({+ id: newPage.systemDataSourceId,+ scopeInstanceId: newPage.rootInstanceId,+ name: "system",+ type: "parameter",+ });+ expect(data.instances.size).toEqual(2);+ expect(Array.from(data.instances.values())[1]).toEqual({+ type: "instance",+ id: newPage.rootInstanceId,+ component: "Body",+ children: [],+ });+ });++ test("deduplicate path for non-home page copy", () => {+ const data = getWebstudioDataStub({+ instances: toMap<Instance>([+ { type: "instance", id: "bodyId", component: "Body", children: [] },+ ]),+ dataSources: toMap<DataSource>([+ {+ id: "systemId",+ scopeInstanceId: "bodyId",+ name: "system",+ type: "parameter",+ },+ ]),+ pages: {+ meta: {},+ homePage: {+ id: "homePageId",+ name: "Home",+ path: "/",+ title: `"Home"`,+ meta: {},+ rootInstanceId: "bodyId",+ systemDataSourceId: "systemId",+ },+ pages: [+ {+ id: "pageId",+ name: "Name",+ path: "/my-path",+ title: `"Title"`,+ meta: {},+ rootInstanceId: "bodyId",+ systemDataSourceId: "systemId",+ },+ ],+ folders: [createRootFolder(["homePageId", "pageId"])],+ },+ });+ insertPageCopyMutable({+ source: { data, pageId: "pageId" },+ target: { data, folderId: ROOT_FOLDER_ID },+ });+ expect(data.pages.pages.length).toEqual(2);+ const newPage = data.pages.pages[1];+ expect(newPage.path).toEqual("/copy-1/my-path");+ });++ test("deduplicate wildcards in page copy", () => {+ const data = getWebstudioDataStub({+ instances: toMap<Instance>([+ { type: "instance", id: "bodyId", component: "Body", children: [] },+ ]),+ dataSources: toMap<DataSource>([+ {+ id: "systemId",+ scopeInstanceId: "bodyId",+ name: "system",+ type: "parameter",+ },+ ]),+ pages: {+ meta: {},+ homePage: {+ id: "homePageId",+ name: "Home",+ path: "/",+ title: `"Home"`,+ meta: {},+ rootInstanceId: "bodyId",+ systemDataSourceId: "systemId",+ },+ pages: [+ {+ id: "page1Id",+ name: "My Name 1",+ // unnamed wildcard+ path: "/my-path/*",+ title: `"My Title"`,+ meta: {},+ rootInstanceId: "bodyId",+ systemDataSourceId: "systemId",+ },+ {+ id: "page2Id",+ name: "My Name 2",+ // Named wildcard+ path: "/my-path/name*",+ title: `"My Title"`,+ meta: {},+ rootInstanceId: "bodyId",+ systemDataSourceId: "systemId",+ },+ ],+ folders: [createRootFolder(["homePageId", "page1Id", "page2Id"])],+ },+ });+ insertPageCopyMutable({+ source: { data, pageId: "page1Id" },+ target: { data, folderId: ROOT_FOLDER_ID },+ });+ insertPageCopyMutable({+ source: { data, pageId: "page2Id" },+ target: { data, folderId: ROOT_FOLDER_ID },+ });+ expect(data.pages.pages.length).toEqual(4);+ const newPage1 = data.pages.pages[2];+ const newPage2 = data.pages.pages[3];+ expect(newPage1.path).toEqual("/copy-1/my-path/*");+ expect(newPage2.path).toEqual("/copy-1/my-path/name*");+ });++ test("check full page path when duplicate inside a folder", () => {+ const data = getWebstudioDataStub({+ instances: toMap<Instance>([+ { type: "instance", id: "bodyId", component: "Body", children: [] },+ ]),+ dataSources: toMap<DataSource>([+ {+ id: "systemId",+ scopeInstanceId: "bodyId",+ name: "system",+ type: "parameter",+ },+ ]),+ pages: {+ meta: {},+ homePage: {+ id: "homePageId",+ name: "Home",+ path: "/",+ title: `"Home"`,+ meta: {},+ rootInstanceId: "bodyId",+ systemDataSourceId: "systemId",+ },+ pages: [+ {+ id: "pageId",+ name: "My Name",+ path: "/my-path",+ title: `"My Title"`,+ meta: {},+ rootInstanceId: "bodyId",+ systemDataSourceId: "systemId",+ },+ ],+ folders: [+ createRootFolder(["folderId"]),+ {+ id: "folderId",+ name: "Folder",+ slug: "folder",+ children: ["pageId"],+ },+ ],+ },+ });+ insertPageCopyMutable({+ source: { data, pageId: "pageId" },+ target: { data, folderId: "folderId" },+ });+ insertPageCopyMutable({+ source: { data, pageId: "pageId" },+ target: { data, folderId: ROOT_FOLDER_ID },+ });+ expect(data.pages.pages.length).toEqual(3);+ const nestedPage = data.pages.pages[1];+ const rootPage = data.pages.pages[2];+ expect(nestedPage.path).toEqual("/copy-1/my-path");+ expect(rootPage.path).toEqual("/my-path");+ });++ test("replace variables in page copy meta", () => {+ const data = getWebstudioDataStub({+ instances: toMap<Instance>([+ { type: "instance", id: "bodyId", component: "Body", children: [] },+ ]),+ dataSources: toMap<DataSource>([+ {+ id: "systemId",+ scopeInstanceId: "bodyId",+ name: "system",+ type: "parameter",+ },+ ]),+ pages: {+ meta: {},+ homePage: {+ id: "pageId",+ name: "Name",+ path: "/",+ title: `"Title: " + $ws$dataSource$systemId.params.value`,+ meta: {+ description: `"Description: " + $ws$dataSource$systemId.params.value`,+ excludePageFromSearch: `"Exclude: " + $ws$dataSource$systemId.params.value`,+ socialImageUrl: `"Image: " + $ws$dataSource$systemId.params.value`,+ language: `"Language: " + $ws$dataSource$systemId.params.value`,+ status: `"Status: " + $ws$dataSource$systemId.params.value`,+ redirect: `"Redirect: " + $ws$dataSource$systemId.params.value`,+ custom: [+ {+ property: "Property",+ content: `"Value: " + $ws$dataSource$systemId.params.value`,+ },+ ],+ },+ rootInstanceId: "bodyId",+ systemDataSourceId: "systemId",+ },+ pages: [],+ folders: [createRootFolder(["pageId"])],+ },+ });+ insertPageCopyMutable({+ source: { data, pageId: "pageId" },+ target: { data, folderId: ROOT_FOLDER_ID },+ });+ expect(data.pages.pages.length).toEqual(1);+ const newPage = data.pages.pages[0];+ const newSystem = Array.from(data.dataSources.values())[1];+ expect(newSystem.id).not.toEqual("systemId");+ const newSystemName = encodeDataSourceVariable(newSystem.id);+ expect(newPage).toEqual({+ id: expect.not.stringMatching("pageId"),+ name: "Name (1)",+ path: "/copy-1",+ title: `"Title: " + ${newSystemName}.params.value`,+ meta: {+ description: `"Description: " + ${newSystemName}.params.value`,+ excludePageFromSearch: `"Exclude: " + ${newSystemName}.params.value`,+ socialImageUrl: `"Image: " + ${newSystemName}.params.value`,+ language: `"Language: " + ${newSystemName}.params.value`,+ status: `"Status: " + ${newSystemName}.params.value`,+ redirect: `"Redirect: " + ${newSystemName}.params.value`,+ custom: [+ {+ property: "Property",+ content: `"Value: " + ${newSystemName}.params.value`,+ },+ ],+ },+ rootInstanceId: expect.not.stringMatching("bodyId"),+ systemDataSourceId: expect.not.stringMatching("systemId"),+ });+ });+});diff --git a/apps/builder/app/shared/page-utils.ts b/apps/builder/app/shared/page-utils.tsnew file mode 100644index 0000000000..e5301c3f34--- /dev/null+++ b/apps/builder/app/shared/page-utils.ts@@ -0,0 +1,137 @@+import { nanoid } from "nanoid";+import {+ decodeDataSourceVariable,+ encodeDataSourceVariable,+ findPageByIdOrPath,+ getPagePath,+ transpileExpression,+ type Folder,+ type DataSource,+ type Page,+ type Pages,+ type WebstudioData,+} from "@webstudio-is/sdk";+import {+ extractWebstudioFragment,+ insertWebstudioFragmentCopy,+} from "./instance-utils";++const deduplicatePath = (+ pages: Pages,+ folderId: Folder["id"],+ path: Page["path"]+) => {+ const folderPath = getPagePath(folderId, pages);+ if (path === "/") {+ path = "";+ }+ let matchedPage = findPageByIdOrPath(`${folderPath}${path}`, pages);+ if (matchedPage === undefined) {+ return path;+ }+ let counter = 0;+ while (matchedPage) {+ counter += 1;+ matchedPage = findPageByIdOrPath(+ `${folderPath}/copy-${counter}${path}`,+ pages+ );+ }+ return `/copy-${counter}${path}`;+};++const replaceDataSources = (+ expression: string,+ replacements: Map<DataSource["id"], DataSource["id"]>+) => {+ return transpileExpression({+ expression,+ replaceVariable: (identifier) => {+ const dataSourceId = decodeDataSourceVariable(identifier);+ if (dataSourceId === undefined) {+ return;+ }+ return encodeDataSourceVariable(+ replacements.get(dataSourceId) ?? dataSourceId+ );+ },+ });+};++export const insertPageCopyMutable = ({+ source,+ target,+}: {+ source: { data: WebstudioData; pageId: Page["id"] };+ target: { data: WebstudioData; folderId: Folder["id"] };+}) => {+ const page = findPageByIdOrPath(source.pageId, source.data.pages);+ if (page === undefined) {+ return;+ }+ const fragment = extractWebstudioFragment(source.data, page.rootInstanceId);+ const { newInstanceIds, newDataSourceIds } = insertWebstudioFragmentCopy({+ data: target.data,+ fragment,+ availableDataSources: new Set(),+ });+ const newPageId = nanoid();+ const { name = page.name, copyNumber } =+ // extract a number from "name (copyNumber)"+ page.name.match(/^(?<name>.+) \((?<copyNumber>\d+)\)$/)?.groups ?? {};+ const newName = `${name} (${Number(copyNumber ?? "0") + 1})`;+ const newRootInstanceId =+ newInstanceIds.get(page.rootInstanceId) ?? page.rootInstanceId;+ const newSystemDataSourceId =+ newDataSourceIds.get(page.systemDataSourceId) ?? page.systemDataSourceId;+ const newPage: Page = {+ ...page,+ id: newPageId,+ rootInstanceId: newRootInstanceId,+ systemDataSourceId: newSystemDataSourceId,+ name: newName,+ path: deduplicatePath(target.data.pages, target.folderId, page.path),+ title: replaceDataSources(page.title, newDataSourceIds),+ meta: {+ ...page.meta,+ description:+ page.meta.description === undefined+ ? undefined+ : replaceDataSources(page.meta.description, newDataSourceIds),+ excludePageFromSearch:+ page.meta.excludePageFromSearch === undefined+ ? undefined+ : replaceDataSources(+ page.meta.excludePageFromSearch,+ newDataSourceIds+ ),+ socialImageUrl:+ page.meta.socialImageUrl === undefined+ ? undefined+ : replaceDataSources(page.meta.socialImageUrl, newDataSourceIds),+ language:+ page.meta.language === undefined+ ? undefined+ : replaceDataSources(page.meta.language, newDataSourceIds),+ status:+ page.meta.status === undefined+ ? undefined+ : replaceDataSources(page.meta.status, newDataSourceIds),+ redirect:+ page.meta.redirect === undefined+ ? undefined+ : replaceDataSources(page.meta.redirect, newDataSourceIds),+ custom: page.meta.custom?.map(({ property, content }) => ({+ property,+ content: replaceDataSources(content, newDataSourceIds),+ })),+ },+ };+ target.data.pages.pages.push(newPage);+ for (const folder of target.data.pages.folders) {+ if (folder.id === target.folderId) {+ folder.children.push(newPageId);+ }+ }+ return newPageId;+};