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.

feat: move project to separate package

Andras Bacsai76cba0342cf7
diff --git a/apps/designer/app/designer/features/breakpoints/breakpoints.tsx b/apps/designer/app/designer/features/breakpoints/breakpoints.tsx
index 589cbdbc2f..3738eeb92c 100644
--- a/apps/designer/app/designer/features/breakpoints/breakpoints.tsx
+++ b/apps/designer/app/designer/features/breakpoints/breakpoints.tsx
@@ -13,7 +13,6 @@ import {
__DEPRECATED__Text,
Flex,
} from "@webstudio-is/design-system";
-import { sort } from "~/shared/breakpoints";
import { useSelectedBreakpoint } from "../../shared/nano-states";
import { BreakpointsEditor } from "./breakpoints-editor";
import { Preview } from "./preview";
@@ -26,6 +25,7 @@ import {
} from "./use-subscribe-shortcuts";
import { ConfirmationDialog } from "./confirmation-dialog";
import { useBreakpoints } from "~/shared/nano-states";
+import { sort } from "@webstudio-is/project";
declare module "~/shared/pubsub" {
export interface PubsubMap {
diff --git a/apps/designer/app/designer/features/breakpoints/use-subscribe-breakpoints.ts b/apps/designer/app/designer/features/breakpoints/use-subscribe-breakpoints.ts
index d0ab8374ed..fe9787f276 100644
--- a/apps/designer/app/designer/features/breakpoints/use-subscribe-breakpoints.ts
+++ b/apps/designer/app/designer/features/breakpoints/use-subscribe-breakpoints.ts
@@ -1,8 +1,8 @@
import { useEffect } from "react";
import { useSubscribe } from "~/shared/pubsub";
import { useSelectedBreakpoint } from "~/designer/shared/nano-states";
-import { sort } from "~/shared/breakpoints";
import { useBreakpoints } from "~/shared/nano-states";
+import { sort } from "@webstudio-is/project";
export const useSubscribeBreakpoints = () => {
const [breakpoints, setBreakpoints] = useBreakpoints();
diff --git a/apps/designer/app/designer/features/breakpoints/use-subscribe-shortcuts.ts b/apps/designer/app/designer/features/breakpoints/use-subscribe-shortcuts.ts
index 517d479434..16b7ed486e 100644
--- a/apps/designer/app/designer/features/breakpoints/use-subscribe-shortcuts.ts
+++ b/apps/designer/app/designer/features/breakpoints/use-subscribe-shortcuts.ts
@@ -1,8 +1,8 @@
import { useSubscribe } from "~/shared/pubsub";
-import { sort } from "~/shared/breakpoints";
import { useBreakpoints } from "~/shared/nano-states";
import { useZoom, useSelectedBreakpoint } from "../../shared/nano-states";
import { minZoom } from "./zoom-setting";
+import { sort } from "@webstudio-is/project";
export const useSubscribeSelectBreakpointFromShortcut = () => {
const [breakpoints] = useBreakpoints();
diff --git a/apps/designer/app/designer/features/breakpoints/width-setting.tsx b/apps/designer/app/designer/features/breakpoints/width-setting.tsx
index ac86eddc24..fae33443d9 100644
--- a/apps/designer/app/designer/features/breakpoints/width-setting.tsx
+++ b/apps/designer/app/designer/features/breakpoints/width-setting.tsx
@@ -4,8 +4,8 @@ import {
useSelectedBreakpoint,
} from "~/designer/shared/nano-states";
import { Slider, __DEPRECATED__Text, Flex } from "@webstudio-is/design-system";
-import { sort } from "~/shared/breakpoints";
import { useBreakpoints, useIsPreviewMode } from "~/shared/nano-states";
+import { sort } from "@webstudio-is/project";
// Doesn't make sense to allow resizing the canvas lower/higher than this.
export const minWidth = 50;
diff --git a/apps/designer/app/routes/rest/breakpoints.$projectId.ts b/apps/designer/app/routes/rest/breakpoints.$projectId.ts
index d623f2602f..e5919884f5 100644
--- a/apps/designer/app/routes/rest/breakpoints.$projectId.ts
+++ b/apps/designer/app/routes/rest/breakpoints.$projectId.ts
@@ -1,6 +1,6 @@
import type { LoaderFunction } from "@remix-run/node";
-import type { Breakpoint } from "@webstudio-is/react-sdk";
-import * as db from "~/shared/db";
+import { Breakpoint } from "@webstudio-is/react-sdk";
+import * as db from "@webstudio-is/project";
export type ErrorData = {
errors: string;
diff --git a/apps/designer/app/routes/rest/pages.$projectId.ts b/apps/designer/app/routes/rest/pages.$projectId.ts
index d623f2602f..5acd1cfa05 100644
--- a/apps/designer/app/routes/rest/pages.$projectId.ts
+++ b/apps/designer/app/routes/rest/pages.$projectId.ts
@@ -1,6 +1,6 @@
import type { LoaderFunction } from "@remix-run/node";
import type { Breakpoint } from "@webstudio-is/react-sdk";
-import * as db from "~/shared/db";
+import * as db from "@webstudio-is/project";
export type ErrorData = {
errors: string;
diff --git a/apps/designer/app/routes/rest/props.$projectId.ts b/apps/designer/app/routes/rest/props.$projectId.ts
index 9e6af9379e..751cc6d199 100644
--- a/apps/designer/app/routes/rest/props.$projectId.ts
+++ b/apps/designer/app/routes/rest/props.$projectId.ts
@@ -1,7 +1,6 @@
import { type LoaderFunction } from "@remix-run/node";
import { type InstanceProps } from "@webstudio-is/react-sdk";
-import * as db from "~/shared/db";
-
+import * as db from "@webstudio-is/project";
type ErrorData = {
errors: string;
};
diff --git a/apps/designer/app/routes/rest/tree.$projectId.ts b/apps/designer/app/routes/rest/tree.$projectId.ts
index 1d50d90686..e9d7960b7a 100644
--- a/apps/designer/app/routes/rest/tree.$projectId.ts
+++ b/apps/designer/app/routes/rest/tree.$projectId.ts
@@ -1,7 +1,6 @@
import { type LoaderFunction } from "@remix-run/node";
import type { Tree } from "@webstudio-is/react-sdk";
-import * as db from "~/shared/db";
-
+import * as db from "@webstudio-is/project";
export type ErrorData = {
errors: string;
};
diff --git a/apps/designer/app/shared/db/canvas.server.ts b/apps/designer/app/shared/db/canvas.server.ts
index 033fbefb72..26f9312344 100644
--- a/apps/designer/app/shared/db/canvas.server.ts
+++ b/apps/designer/app/shared/db/canvas.server.ts
@@ -1,14 +1,13 @@
import { type Data } from "@webstudio-is/react-sdk";
-import * as db from ".";
-import { Project } from "./project.server";
+import * as db from "@webstudio-is/project";
-export type CanvasData = Data & { project: Project };
+export type CanvasData = Data & { project: db.Project };
export type ErrorData = {
errors: string;
};
-const loadData = async (projectId: Project["id"]) => {
+const loadData = async (projectId: db.Project["id"]) => {
const project = await db.project.loadById(projectId);
if (project === null) throw new Error(`Project "${projectId}" not found`);
@@ -40,7 +39,7 @@ const loadData = async (projectId: Project["id"]) => {
export const loadCanvasData = async ({
projectId,
}: {
- projectId: Project["id"];
+ projectId: db.Project["id"];
}): Promise<CanvasData | ErrorData> => {
return await loadData(projectId);
};
@@ -50,7 +49,7 @@ export type PreviewData = Data;
export const loadPreviewData = async ({
projectId,
}: {
- projectId: Project["id"];
+ projectId: db.Project["id"];
}): Promise<PreviewData | ErrorData> => {
const { tree, props, breakpoints } = await loadData(projectId);
return { tree, props, breakpoints };
diff --git a/apps/designer/app/shared/db/index.ts b/apps/designer/app/shared/db/index.ts
index 8e5524eaa7..9ae3bd4ee5 100644
--- a/apps/designer/app/shared/db/index.ts
+++ b/apps/designer/app/shared/db/index.ts
@@ -1,7 +1,3 @@
-export * as tree from "./tree.server";
-export * as project from "./project.server";
-export * as props from "./props.server";
export * as misc from "./misc.server";
export * as user from "./user.server";
export * from "./canvas.server";
-export * as breakpoints from "./breakpoints.server";
diff --git a/apps/designer/app/shared/db/misc.server.ts b/apps/designer/app/shared/db/misc.server.ts
index 462cb10a30..cfb933b6b7 100644
--- a/apps/designer/app/shared/db/misc.server.ts
+++ b/apps/designer/app/shared/db/misc.server.ts
@@ -1,4 +1,4 @@
-import * as db from "./";
+import * as db from "@webstudio-is/project";
/**
* Conceptually publishing is cloning all data that affects user site
* and referencing it under a new tree id.
diff --git a/apps/designer/package.json b/apps/designer/package.json
index 5d053c2552..d36c9c61be 100644
--- a/apps/designer/package.json
+++ b/apps/designer/package.json
@@ -32,6 +32,7 @@
"@webstudio-is/prisma-client": "*",
"@webstudio-is/react-sdk": "*",
"@webstudio-is/css-vars": "*",
+ "@webstudio-is/project": "*",
"bson-objectid": "^2.0.2",
"camelcase": "^6.3.0",
"debug": "^4.3.4",
diff --git a/packages/project/LICENSE b/packages/project/LICENSE
new file mode 100644
index 0000000000..1f6edad9a7
--- /dev/null
+++ b/packages/project/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2022 Webstudio
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/project/README.md b/packages/project/README.md
new file mode 100644
index 0000000000..867393882b
--- /dev/null
+++ b/packages/project/README.md
@@ -0,0 +1,3 @@
+# Webstudio Project
+
+Project related functionalities.
diff --git a/packages/project/index.server.ts b/packages/project/index.server.ts
new file mode 100644
index 0000000000..e910bb060c
--- /dev/null
+++ b/packages/project/index.server.ts
@@ -0,0 +1 @@
+export * from "./src/index";
diff --git a/packages/project/jest.config.js b/packages/project/jest.config.js
new file mode 100644
index 0000000000..4eeecbaf4e
--- /dev/null
+++ b/packages/project/jest.config.js
@@ -0,0 +1 @@
+module.exports = require("@webstudio-is/jest-config");
diff --git a/packages/project/package.json b/packages/project/package.json
new file mode 100644
index 0000000000..1b3a42095c
--- /dev/null
+++ b/packages/project/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "@webstudio-is/project",
+ "version": "0.0.1",
+ "description": "Webstudio Project",
+ "author": "Webstudio <[email protected]>",
+ "homepage": "https://webstudio.is",
+ "scripts": {
+ "typecheck": "tsc --noEmit",
+ "test": "jest",
+ "checks": "yarn typecheck && yarn lint && yarn test",
+ "dev": "tsup src/index.ts --format esm,cjs --watch --out-dir=lib",
+ "build": "rm -fr lib && tsc",
+ "lint": "eslint ./src --ext .ts,.tsx --max-warnings 0"
+ },
+ "dependencies": {},
+ "devDependencies": {
+ "@webstudio-is/asset-uploader": "*",
+ "@webstudio-is/prisma-client": "*",
+ "nanoid": "^4.0.0",
+ "slugify": "^1.6.5",
+ "zod": "^3.19.1",
+ "tsup": "^6.1.3",
+ "typescript": "4.7.4"
+ },
+ "main": "lib/index.js",
+ "types": "lib/index.d.ts",
+ "files": [
+ "lib/*",
+ "README.md",
+ "!*.test.*"
+ ],
+ "license": "MIT",
+ "private": false
+}
diff --git a/apps/designer/app/shared/db/breakpoints.server.ts b/packages/project/src/breakpoints.ts
similarity index 100%
rename from apps/designer/app/shared/db/breakpoints.server.ts
rename to packages/project/src/breakpoints.ts
diff --git a/packages/project/src/index.ts b/packages/project/src/index.ts
new file mode 100644
index 0000000000..1cd8d78c8c
--- /dev/null
+++ b/packages/project/src/index.ts
@@ -0,0 +1,7 @@
+export * as project from "./project";
+export * as breakpoints from "./breakpoints";
+export * as tree from "./tree";
+export * as props from "./props";
+
+export * from "./shared/breakpoints";
+export * from "./shared/tree-utils";
diff --git a/apps/designer/app/shared/db/project.server.ts b/packages/project/src/project.ts
similarity index 99%
rename from apps/designer/app/shared/db/project.server.ts
rename to packages/project/src/project.ts
index 183f749026..b6790b46eb 100644
--- a/apps/designer/app/shared/db/project.server.ts
+++ b/packages/project/src/project.ts
@@ -7,10 +7,9 @@ import {
Prisma,
Project as BaseProject,
} from "@webstudio-is/prisma-client";
-import * as db from ".";
import { formatAsset } from "@webstudio-is/asset-uploader";
import type { Asset } from "@webstudio-is/asset-uploader";
-
+import * as db from "./index";
const TreeHistorySchema = z.array(z.string());
export type Project = Omit<BaseProject, "prodTreeIdHistory" | "assets"> & {
diff --git a/apps/designer/app/shared/db/props.server.ts b/packages/project/src/props.ts
similarity index 98%
rename from apps/designer/app/shared/db/props.server.ts
rename to packages/project/src/props.ts
index 0ee3c47271..ffebfc2cb7 100644
--- a/apps/designer/app/shared/db/props.server.ts
+++ b/packages/project/src/props.ts
@@ -5,7 +5,7 @@ import {
} from "@webstudio-is/react-sdk";
import { applyPatches, type Patch } from "immer";
import { prisma } from "@webstudio-is/prisma-client";
-import { Project } from "./project.server";
+import { Project } from "./project";
export const loadByProject = async (
project: Project | null,
diff --git a/apps/designer/app/shared/breakpoints/index.ts b/packages/project/src/shared/breakpoints/index.ts
similarity index 100%
rename from apps/designer/app/shared/breakpoints/index.ts
rename to packages/project/src/shared/breakpoints/index.ts
diff --git a/apps/designer/app/shared/breakpoints/sort.test.ts b/packages/project/src/shared/breakpoints/sort.test.ts
similarity index 100%
rename from apps/designer/app/shared/breakpoints/sort.test.ts
rename to packages/project/src/shared/breakpoints/sort.test.ts
diff --git a/apps/designer/app/shared/breakpoints/sort.ts b/packages/project/src/shared/breakpoints/sort.ts
similarity index 100%
rename from apps/designer/app/shared/breakpoints/sort.ts
rename to packages/project/src/shared/breakpoints/sort.ts
diff --git a/packages/project/src/shared/canvas-components/index.ts b/packages/project/src/shared/canvas-components/index.ts
new file mode 100644
index 0000000000..e9f7edf109
--- /dev/null
+++ b/packages/project/src/shared/canvas-components/index.ts
@@ -0,0 +1 @@
+export * from "./instance-data";
diff --git a/packages/project/src/shared/canvas-components/instance-data.ts b/packages/project/src/shared/canvas-components/instance-data.ts
new file mode 100644
index 0000000000..9af88bd561
--- /dev/null
+++ b/packages/project/src/shared/canvas-components/instance-data.ts
@@ -0,0 +1,33 @@
+import {
+ type Instance,
+ type InstanceProps,
+ type CssRule,
+ type Style,
+ type StyleProperty,
+ type StyleValue,
+ type Breakpoint,
+} from "@webstudio-is/react-sdk";
+
+export type SelectedInstanceData = {
+ id: Instance["id"];
+ component: Instance["component"];
+ cssRules: Array<CssRule>;
+ browserStyle: Style;
+ props: InstanceProps;
+};
+
+export type HoveredInstanceData = {
+ id: Instance["id"];
+ component: Instance["component"];
+};
+
+type StyleUpdate = {
+ property: StyleProperty;
+ value: StyleValue;
+};
+
+export type StyleUpdates = {
+ id: Instance["id"];
+ updates: Array<StyleUpdate>;
+ breakpoint: Breakpoint;
+};
diff --git a/packages/project/src/shared/tree-utils/__snapshots__/delete-instance.test.ts.snap b/packages/project/src/shared/tree-utils/__snapshots__/delete-instance.test.ts.snap
new file mode 100644
index 0000000000..e9b9078d9c
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/__snapshots__/delete-instance.test.ts.snap
@@ -0,0 +1,33 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Delete instance div 1 > div 2 > [div 3] 1`] = `
+Object {
+ "children": Array [
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "2",
+ },
+ ],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "1",
+}
+`;
+
+exports[`Delete instance div 1 > div 2, [div 3] 1`] = `
+Object {
+ "children": Array [
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "2",
+ },
+ ],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "1",
+}
+`;
diff --git a/packages/project/src/shared/tree-utils/__snapshots__/insert-instance.test.ts.snap b/packages/project/src/shared/tree-utils/__snapshots__/insert-instance.test.ts.snap
new file mode 100644
index 0000000000..99a82e1136
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/__snapshots__/insert-instance.test.ts.snap
@@ -0,0 +1,90 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Insert instance after a nested div using "end": div 1 > div 2, [div 3] 1`] = `
+Object {
+ "children": Array [
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "2",
+ },
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "3",
+ },
+ ],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "1",
+}
+`;
+
+exports[`Insert instance after a nested div using index: div 1 > div 2, [div 3] 1`] = `
+Object {
+ "children": Array [
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "2",
+ },
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "3",
+ },
+ ],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "1",
+}
+`;
+
+exports[`Insert instance before a nested div using index: div 1 > [div 3], div 2 1`] = `
+Object {
+ "children": Array [
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "3",
+ },
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "2",
+ },
+ ],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "1",
+}
+`;
+
+exports[`Insert instance inside a nested div using "end": div 1 > div 2 > [div 3] 1`] = `
+Object {
+ "children": Array [
+ Object {
+ "children": Array [
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "3",
+ },
+ ],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "2",
+ },
+ ],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "1",
+}
+`;
diff --git a/packages/project/src/shared/tree-utils/__snapshots__/reparent-instance.test.ts.snap b/packages/project/src/shared/tree-utils/__snapshots__/reparent-instance.test.ts.snap
new file mode 100644
index 0000000000..ecdb541cb2
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/__snapshots__/reparent-instance.test.ts.snap
@@ -0,0 +1,58 @@
+// Jest Snapshot v1, https://goo.gl/fbAQLP
+
+exports[`Reparent instance new parent 1`] = `
+Object {
+ "children": Array [
+ Object {
+ "children": Array [
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "4",
+ },
+ ],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "2",
+ },
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "3",
+ },
+ ],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "1",
+}
+`;
+
+exports[`Reparent instance same parent different position 1`] = `
+Object {
+ "children": Array [
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "3",
+ },
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "2",
+ },
+ Object {
+ "children": Array [],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "4",
+ },
+ ],
+ "component": "Box",
+ "cssRules": Array [],
+ "id": "1",
+}
+`;
diff --git a/packages/project/src/shared/tree-utils/clone-instance.test.ts b/packages/project/src/shared/tree-utils/clone-instance.test.ts
new file mode 100644
index 0000000000..9bbc8bf24d
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/clone-instance.test.ts
@@ -0,0 +1,42 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+import { cloneInstance } from "./clone-instance";
+
+const getIds = (instance: Instance, ids: Array<Instance["id"]> = []) => {
+ ids.push(instance.id);
+ for (const child of instance.children) {
+ if (typeof child !== "string") getIds(child);
+ }
+ return ids;
+};
+
+describe("Clone instance", () => {
+ test("ensure new ids", () => {
+ const instance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "3",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ },
+ ],
+ };
+
+ const ids = getIds(instance);
+ const clone = cloneInstance(instance);
+ const clonedIds = getIds(clone);
+ ids.forEach((id, index) => {
+ expect(id).not.toBe(clonedIds[index]);
+ });
+ });
+});
diff --git a/packages/project/src/shared/tree-utils/clone-instance.ts b/packages/project/src/shared/tree-utils/clone-instance.ts
new file mode 100644
index 0000000000..c3f549313b
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/clone-instance.ts
@@ -0,0 +1,14 @@
+import ObjectId from "bson-objectid";
+import produce from "immer";
+import { type Instance } from "@webstudio-is/react-sdk";
+
+const updateIds = (instance: Instance) => {
+ instance.id = ObjectId().toString();
+ for (const child of instance.children) {
+ if (typeof child === "string") continue;
+ updateIds(child);
+ }
+};
+
+export const cloneInstance = (instance: Instance): Instance =>
+ produce(updateIds)(instance);
diff --git a/packages/project/src/shared/tree-utils/create-instance.test.ts b/packages/project/src/shared/tree-utils/create-instance.test.ts
new file mode 100644
index 0000000000..2da713f8d6
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/create-instance.test.ts
@@ -0,0 +1,48 @@
+import { createInstance } from "./create-instance";
+
+describe("create instance", () => {
+ test("instance without id should be auto generated", () => {
+ const createdInstance = createInstance({
+ component: "Box",
+ });
+
+ expect(typeof createdInstance.id).toBe("string");
+ });
+
+ test("instance without children should be empty by default", () => {
+ const createdInstance = createInstance({
+ component: "Box",
+ });
+ expect(createdInstance.children.length).toBe(0);
+ });
+
+ test("instance without style should be an object after creation", () => {
+ const createdInstance = createInstance({
+ component: "Box",
+ });
+ expect(Array.isArray(createdInstance.cssRules)).toBeTruthy();
+ });
+
+ test("instance with children ", () => {
+ const createdInstance = createInstance({
+ component: "Box",
+ children: [
+ {
+ id: "1",
+ component: "Box",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ cssRules: [],
+ });
+ expect(createdInstance.children).toEqual([
+ {
+ id: "1",
+ component: "Box",
+ cssRules: [],
+ children: [],
+ },
+ ]);
+ });
+});
diff --git a/packages/project/src/shared/tree-utils/create-instance.ts b/packages/project/src/shared/tree-utils/create-instance.ts
new file mode 100644
index 0000000000..00a88e0053
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/create-instance.ts
@@ -0,0 +1,26 @@
+import ObjectId from "bson-objectid";
+import {
+ type CssRule,
+ type Instance,
+ components,
+} from "@webstudio-is/react-sdk";
+
+export const createInstance = ({
+ component,
+ id,
+ children,
+ cssRules,
+}: {
+ component: Instance["component"];
+ id?: Instance["id"];
+ children?: Instance["children"];
+ cssRules?: Array<CssRule>;
+}): Instance => {
+ const componentMeta = components[component];
+ return {
+ component,
+ id: id === undefined ? ObjectId().toString() : id,
+ cssRules: cssRules ?? [],
+ children: children === undefined ? componentMeta.children ?? [] : children,
+ };
+};
diff --git a/packages/project/src/shared/tree-utils/delete-instance.test.ts b/packages/project/src/shared/tree-utils/delete-instance.test.ts
new file mode 100644
index 0000000000..4091ffdf11
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/delete-instance.test.ts
@@ -0,0 +1,55 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+import { deleteInstanceMutable } from "./delete-instance";
+
+describe("Delete instance", () => {
+ test("div 1 > div 2 > [div 3]", () => {
+ const instance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "3",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ },
+ ],
+ };
+
+ deleteInstanceMutable(instance, "3");
+ expect(instance).toMatchSnapshot();
+ });
+
+ test("div 1 > div 2, [div 3]", () => {
+ const instance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2",
+ cssRules: [],
+ children: [],
+ },
+ {
+ component: "Box",
+ id: "3",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ };
+
+ deleteInstanceMutable(instance, "3");
+ expect(instance).toMatchSnapshot();
+ });
+});
diff --git a/packages/project/src/shared/tree-utils/delete-instance.ts b/packages/project/src/shared/tree-utils/delete-instance.ts
new file mode 100644
index 0000000000..6f0b3dcae6
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/delete-instance.ts
@@ -0,0 +1,19 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+
+export const deleteInstanceMutable = (
+ instance: Instance,
+ instanceId: Instance["id"]
+): boolean => {
+ if (instance.id === instanceId) return true;
+
+ for (const child of instance.children) {
+ if (typeof child === "string") continue;
+ const shouldDelete = deleteInstanceMutable(child, instanceId);
+ if (shouldDelete === true) {
+ const index = instance.children.indexOf(child);
+ instance.children.splice(index, 1);
+ return false;
+ }
+ }
+ return false;
+};
diff --git a/packages/project/src/shared/tree-utils/find-closest-non-inline-parent.test.ts b/packages/project/src/shared/tree-utils/find-closest-non-inline-parent.test.ts
new file mode 100644
index 0000000000..273abe8345
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/find-closest-non-inline-parent.test.ts
@@ -0,0 +1,51 @@
+import { createInstance } from "./create-instance";
+import { findClosestNonInlineParent } from "./find-closest-non-inline-parent";
+
+describe("findClosestNonInlineParent", () => {
+ const italic = createInstance({ component: "Italic" });
+
+ const boldWithItalic = createInstance({
+ component: "Bold",
+ children: [italic],
+ });
+
+ test("when there's no non-inline parent, returns undefined", () => {
+ expect(
+ findClosestNonInlineParent(boldWithItalic, italic.id)
+ ).toBeUndefined();
+ expect(findClosestNonInlineParent(italic, italic.id)).toBeUndefined();
+ });
+
+ test("when the given instance isn't in the tree, returns undefined", () => {
+ const root = createInstance({ component: "Body" });
+ expect(findClosestNonInlineParent(root, italic.id)).toBeUndefined();
+ });
+
+ test("retrunrns the first non-inline parent", () => {
+ const root = createInstance({
+ component: "Body",
+ children: [
+ createInstance({
+ component: "Heading",
+ id: "the-heading",
+ children: [italic],
+ }),
+ ],
+ });
+ expect(findClosestNonInlineParent(root, italic.id)?.id).toBe("the-heading");
+ });
+
+ test("retrunrns the first non-inline parent (nested)", () => {
+ const root = createInstance({
+ component: "Body",
+ children: [
+ createInstance({
+ component: "Heading",
+ id: "the-heading",
+ children: [boldWithItalic],
+ }),
+ ],
+ });
+ expect(findClosestNonInlineParent(root, italic.id)?.id).toBe("the-heading");
+ });
+});
diff --git a/packages/project/src/shared/tree-utils/find-closest-non-inline-parent.ts b/packages/project/src/shared/tree-utils/find-closest-non-inline-parent.ts
new file mode 100644
index 0000000000..da5a74e182
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/find-closest-non-inline-parent.ts
@@ -0,0 +1,11 @@
+import { Instance, components } from "@webstudio-is/react-sdk";
+import { getInstancePath } from "./get-instance-path";
+
+export const findClosestNonInlineParent = (
+ rootInstance: Instance,
+ instanceId: Instance["id"]
+): Instance | undefined => {
+ const path = getInstancePath(rootInstance, instanceId);
+ path.reverse();
+ return path.find((item) => components[item.component].isInlineOnly === false);
+};
diff --git a/packages/project/src/shared/tree-utils/find-closest-sibling-instance.test.ts b/packages/project/src/shared/tree-utils/find-closest-sibling-instance.test.ts
new file mode 100644
index 0000000000..c40bd0bb9c
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/find-closest-sibling-instance.test.ts
@@ -0,0 +1,42 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+import { findClosestSiblingInstance } from "./find-closest-sibling-instance";
+
+describe("Find closest sibling instance", () => {
+ test("find", () => {
+ const rootInstance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "3",
+ cssRules: [],
+ children: [],
+ },
+ "a",
+ {
+ component: "Box",
+ id: "4",
+ cssRules: [],
+ children: [],
+ },
+ "b",
+ {
+ component: "Box",
+ id: "5",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ };
+
+ expect(
+ findClosestSiblingInstance(rootInstance, "notFound")
+ ).toBeUndefined();
+ expect(findClosestSiblingInstance(rootInstance, "1")).toBeUndefined();
+ expect(findClosestSiblingInstance(rootInstance, "3")?.id).toBe("4");
+ expect(findClosestSiblingInstance(rootInstance, "4")?.id).toBe("5");
+ expect(findClosestSiblingInstance(rootInstance, "5")?.id).toBe("4");
+ });
+});
diff --git a/packages/project/src/shared/tree-utils/find-closest-sibling-instance.ts b/packages/project/src/shared/tree-utils/find-closest-sibling-instance.ts
new file mode 100644
index 0000000000..e08cead7fb
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/find-closest-sibling-instance.ts
@@ -0,0 +1,17 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+
+export const findClosestSiblingInstance = (
+ instance: Instance,
+ instanceId: Instance["id"]
+): Instance | undefined => {
+ if (instance.children.length === 0) return;
+ const children = instance.children.filter(
+ (instance) => typeof instance === "object"
+ ) as Array<Instance>;
+ const index = children.findIndex((instance) => instance.id === instanceId);
+ if (index === -1) return;
+ const nextInstance = children[index + 1];
+ if (nextInstance !== undefined) return nextInstance;
+ const previousInstance = children[index - 1];
+ return previousInstance;
+};
diff --git a/packages/project/src/shared/tree-utils/find-instance.ts b/packages/project/src/shared/tree-utils/find-instance.ts
new file mode 100644
index 0000000000..c77b332305
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/find-instance.ts
@@ -0,0 +1,19 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+
+// @todo should be optimized because it will be a frequent operation on a potentially large tree.
+export const findInstanceById = (
+ instance: Instance,
+ id: Instance["id"]
+): Instance | undefined => {
+ if (instance.id === id) {
+ return instance;
+ }
+
+ if (instance.children !== undefined) {
+ for (const child of instance.children) {
+ if (typeof child === "string") continue;
+ const foundInstance = findInstanceById(child, id);
+ if (foundInstance !== undefined) return foundInstance;
+ }
+ }
+};
diff --git a/packages/project/src/shared/tree-utils/find-parent-instance.test.ts b/packages/project/src/shared/tree-utils/find-parent-instance.test.ts
new file mode 100644
index 0000000000..af14509cff
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/find-parent-instance.test.ts
@@ -0,0 +1,31 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+import { findParentInstance } from "./find-parent-instance";
+
+describe("Find parent instance", () => {
+ test("find", () => {
+ const rootInstance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "3",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ },
+ ],
+ };
+
+ expect(findParentInstance(rootInstance, "3")?.id).toBe("2");
+ expect(findParentInstance(rootInstance, "2")?.id).toBe("1");
+ expect(findParentInstance(rootInstance, "1")).toBe(undefined);
+ });
+});
diff --git a/packages/project/src/shared/tree-utils/find-parent-instance.ts b/packages/project/src/shared/tree-utils/find-parent-instance.ts
new file mode 100644
index 0000000000..d17f7f10ef
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/find-parent-instance.ts
@@ -0,0 +1,19 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+
+export const findParentInstance = (
+ instance: Instance,
+ instanceId: Instance["id"]
+): Instance | undefined => {
+ const find = (
+ childInstance: Instance,
+ parentInstance?: Instance
+ ): Instance | undefined => {
+ if (childInstance.id === instanceId) return parentInstance;
+ for (const child of childInstance.children) {
+ if (typeof child === "string") continue;
+ const foundInstance = find(child, childInstance);
+ if (foundInstance !== undefined) return foundInstance;
+ }
+ };
+ return find(instance);
+};
diff --git a/packages/project/src/shared/tree-utils/get-instance-path.test.ts b/packages/project/src/shared/tree-utils/get-instance-path.test.ts
new file mode 100644
index 0000000000..c69fef0010
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/get-instance-path.test.ts
@@ -0,0 +1,158 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+import {
+ getInstancePath,
+ getInstancePathWithPositions,
+} from "./get-instance-path";
+
+const getIds = (array: Array<{ id: string }>) => array.map((item) => item.id);
+
+describe("Get instance path", () => {
+ test("single possible path", () => {
+ const instance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "3",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ },
+ ],
+ };
+ const path = getInstancePath(instance, "3");
+ expect(getIds(path)).toEqual(["1", "2", "3"]);
+ });
+
+ test("two possible paths", () => {
+ const instance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2a",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "3a",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ },
+ {
+ component: "Box",
+ id: "2b",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "3b",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ },
+ ],
+ };
+ const path1 = getInstancePath(instance, "3b");
+ expect(getIds(path1)).toEqual(["1", "2b", "3b"]);
+ const path2 = getInstancePath(instance, "3a");
+ expect(getIds(path2)).toEqual(["1", "2a", "3a"]);
+ });
+});
+
+const getIdAndPosition = (
+ array: Array<{ item: { id: string }; position: number }>
+) => array.map((item) => [item.item.id, item.position]);
+
+describe("Get instance path with positions", () => {
+ test("single possible path", () => {
+ const instance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "3",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ },
+ ],
+ };
+ const path = getInstancePathWithPositions(instance, "3");
+ expect(getIdAndPosition(path)).toEqual([
+ ["1", 0],
+ ["2", 0],
+ ["3", 0],
+ ]);
+ });
+
+ test("two possible paths", () => {
+ const instance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2a",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "3a",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ },
+ {
+ component: "Box",
+ id: "2b",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "3b",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ },
+ ],
+ };
+ const path1 = getInstancePathWithPositions(instance, "3b");
+ expect(getIdAndPosition(path1)).toEqual([
+ ["1", 0],
+ ["2b", 1],
+ ["3b", 0],
+ ]);
+
+ const path2 = getInstancePathWithPositions(instance, "3a");
+ expect(getIdAndPosition(path2)).toEqual([
+ ["1", 0],
+ ["2a", 0],
+ ["3a", 0],
+ ]);
+ });
+});
diff --git a/packages/project/src/shared/tree-utils/get-instance-path.ts b/packages/project/src/shared/tree-utils/get-instance-path.ts
new file mode 100644
index 0000000000..9b2600c8dc
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/get-instance-path.ts
@@ -0,0 +1,52 @@
+import { Instance } from "@webstudio-is/react-sdk";
+
+export const getInstancePath = (
+ instance: Instance,
+ instanceId: Instance["id"]
+) => {
+ const path = [];
+
+ const find = (instance: Instance) => {
+ if (instance.id === instanceId) return true;
+ for (const child of instance.children) {
+ if (typeof child === "string") continue;
+ const found = find(child);
+ if (found) {
+ path.push(child);
+ return true;
+ }
+ }
+ };
+
+ if (find(instance)) {
+ path.push(instance);
+ }
+
+ return path.reverse();
+};
+
+export const getInstancePathWithPositions = (
+ instance: Instance,
+ instanceId: Instance["id"]
+) => {
+ const path = [];
+
+ const find = (instance: Instance) => {
+ if (instance.id === instanceId) return true;
+ for (let index = 0; index < instance.children.length; index++) {
+ const child = instance.children[index];
+ if (typeof child === "string") continue;
+ const found = find(child);
+ if (found) {
+ path.push({ item: child, position: index });
+ return true;
+ }
+ }
+ };
+
+ if (find(instance)) {
+ path.push({ item: instance, position: 0 });
+ }
+
+ return path.reverse();
+};
diff --git a/packages/project/src/shared/tree-utils/index.ts b/packages/project/src/shared/tree-utils/index.ts
new file mode 100644
index 0000000000..4f4109330c
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/index.ts
@@ -0,0 +1,13 @@
+export * from "./create-instance";
+export * from "./delete-instance";
+export * from "./insert-instance";
+export * from "./populate";
+export * from "./find-instance";
+export * from "./set-instance-style";
+export * from "./set-instance-children";
+export * from "./get-instance-path";
+export * from "./find-closest-sibling-instance";
+export * from "./find-parent-instance";
+export * from "./clone-instance";
+export * from "./reparent-instance";
+export * from "./find-closest-non-inline-parent";
diff --git a/packages/project/src/shared/tree-utils/insert-instance.test.ts b/packages/project/src/shared/tree-utils/insert-instance.test.ts
new file mode 100644
index 0000000000..4562b883a8
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/insert-instance.test.ts
@@ -0,0 +1,98 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+import { insertInstanceMutable } from "./insert-instance";
+import { createInstance } from "./create-instance";
+
+const instance = createInstance({ id: "3", component: "Box" });
+
+describe("Insert instance", () => {
+ test(`inside a nested div using "end": div 1 > div 2 > [div 3]`, () => {
+ const rootInstance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ };
+
+ const hasInserted = insertInstanceMutable(rootInstance, instance, {
+ parentId: "2",
+ position: "end",
+ });
+ expect(hasInserted).toBeTruthy();
+ expect(rootInstance).toMatchSnapshot();
+ });
+
+ test("after a nested div using index: div 1 > div 2, [div 3]", () => {
+ const rootInstance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ };
+
+ const hasInserted = insertInstanceMutable(rootInstance, instance, {
+ parentId: "1",
+ position: 1,
+ });
+ expect(hasInserted).toBeTruthy();
+ expect(rootInstance).toMatchSnapshot();
+ });
+
+ test("before a nested div using index: div 1 > [div 3], div 2", () => {
+ const rootInstance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ };
+ const hasInserted = insertInstanceMutable(rootInstance, instance, {
+ parentId: "1",
+ position: 0,
+ });
+ expect(hasInserted).toBeTruthy();
+ expect(rootInstance).toMatchSnapshot();
+ });
+
+ test(`after a nested div using "end": div 1 > div 2, [div 3]`, () => {
+ const rootInstance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ };
+
+ const hasInserted = insertInstanceMutable(rootInstance, instance, {
+ parentId: "1",
+ position: "end",
+ });
+ expect(hasInserted).toBeTruthy();
+ expect(rootInstance).toMatchSnapshot();
+ });
+});
diff --git a/packages/project/src/shared/tree-utils/insert-instance.ts b/packages/project/src/shared/tree-utils/insert-instance.ts
new file mode 100644
index 0000000000..e65f793877
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/insert-instance.ts
@@ -0,0 +1,35 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+
+export type InstanceInsertionSpec = {
+ parentId: Instance["id"];
+ position: number | "end";
+};
+
+export const insertInstanceMutable = (
+ rootInstance: Instance,
+ instance: Instance,
+ spec: InstanceInsertionSpec
+): boolean => {
+ if (spec.parentId !== rootInstance.id) {
+ for (const child of rootInstance.children) {
+ if (typeof child === "string") continue;
+ const hasInserted = insertInstanceMutable(child, instance, spec);
+ if (hasInserted === true) return true;
+ }
+ return false;
+ }
+
+ // Inserting inside the selected/hovered instance.
+ if (typeof spec.position === "number") {
+ rootInstance.children.splice(spec.position, 0, instance);
+ return true;
+ }
+
+ // Inserting after all children
+ if (spec.position === "end") {
+ rootInstance.children.push(instance);
+ return true;
+ }
+
+ return true;
+};
diff --git a/packages/project/src/shared/tree-utils/populate.ts b/packages/project/src/shared/tree-utils/populate.ts
new file mode 100644
index 0000000000..4e30360c57
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/populate.ts
@@ -0,0 +1,26 @@
+import {
+ type Instance,
+ type Breakpoint,
+ components,
+} from "@webstudio-is/react-sdk";
+
+/**
+ * Populate instance with:
+ * - defaultStyles
+ * @todo rewrite using immer
+ */
+export const populateInstance = (
+ instance: Instance,
+ breakpoint: Breakpoint["id"] = ""
+): Instance => {
+ const populatedInstance = { ...instance };
+ const componentMeta = components[instance.component];
+ if (componentMeta !== undefined && "defaultStyle" in componentMeta) {
+ const cssRule = {
+ breakpoint,
+ style: componentMeta.defaultStyle ?? {},
+ };
+ populatedInstance.cssRules.push(cssRule);
+ }
+ return populatedInstance;
+};
diff --git a/packages/project/src/shared/tree-utils/reparent-instance.test.ts b/packages/project/src/shared/tree-utils/reparent-instance.test.ts
new file mode 100644
index 0000000000..b5ad253864
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/reparent-instance.test.ts
@@ -0,0 +1,67 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+import { reparentInstanceMutable } from "./reparent-instance";
+
+describe("Reparent instance", () => {
+ test(`new parent`, () => {
+ const rootInstance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2",
+ cssRules: [],
+ children: [],
+ },
+ {
+ component: "Box",
+ id: "3",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "4",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ },
+ ],
+ };
+
+ reparentInstanceMutable(rootInstance, "4", "2", 0);
+ expect(rootInstance).toMatchSnapshot();
+ });
+
+ test(`same parent different position`, () => {
+ const rootInstance: Instance = {
+ component: "Box",
+ id: "1",
+ cssRules: [],
+ children: [
+ {
+ component: "Box",
+ id: "2",
+ cssRules: [],
+ children: [],
+ },
+ {
+ component: "Box",
+ id: "3",
+ cssRules: [],
+ children: [],
+ },
+ {
+ component: "Box",
+ id: "4",
+ cssRules: [],
+ children: [],
+ },
+ ],
+ };
+
+ reparentInstanceMutable(rootInstance, "2", "1", 2);
+ expect(rootInstance).toMatchSnapshot();
+ });
+});
diff --git a/packages/project/src/shared/tree-utils/reparent-instance.ts b/packages/project/src/shared/tree-utils/reparent-instance.ts
new file mode 100644
index 0000000000..44345f8aba
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/reparent-instance.ts
@@ -0,0 +1,45 @@
+import { type Instance } from "@webstudio-is/react-sdk";
+import { findInstanceById } from "./find-instance";
+import { findParentInstance } from "./find-parent-instance";
+import { deleteInstanceMutable } from "./delete-instance";
+import { insertInstanceMutable } from "./insert-instance";
+
+export const reparentInstanceMutable = (
+ rootInstance: Instance,
+ instanceId: Instance["id"],
+ newParentId: Instance["id"],
+ newPosition: number | "end"
+) => {
+ const instance = findInstanceById(rootInstance, instanceId);
+ if (instance === undefined) {
+ return;
+ }
+
+ if (newPosition === "end") {
+ deleteInstanceMutable(rootInstance, instance.id);
+ insertInstanceMutable(rootInstance, instance, {
+ parentId: newParentId,
+ position: "end",
+ });
+ return;
+ }
+
+ let newPositionAdjusted = newPosition;
+
+ // If parent is the same, we need to adjust the position to account for the removal of the instance.
+ const currentParent = findParentInstance(rootInstance, instance.id);
+ if (currentParent !== undefined && currentParent.id === newParentId) {
+ const currentPosition = currentParent.children.findIndex(
+ (child) => typeof child !== "string" && child.id === instance.id
+ );
+ if (currentPosition < newPosition) {
+ newPositionAdjusted--;
+ }
+ }
+
+ deleteInstanceMutable(rootInstance, instance.id);
+ insertInstanceMutable(rootInstance, instance, {
+ parentId: newParentId,
+ position: newPositionAdjusted,
+ });
+};
diff --git a/packages/project/src/shared/tree-utils/set-instance-children.ts b/packages/project/src/shared/tree-utils/set-instance-children.ts
new file mode 100644
index 0000000000..6c0db9da76
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/set-instance-children.ts
@@ -0,0 +1,53 @@
+import { type ChildrenUpdates } from "@webstudio-is/react-sdk";
+import { type Instance } from "@webstudio-is/react-sdk";
+import { createInstance } from "./create-instance";
+import { findInstanceById } from "./find-instance";
+
+/**
+ * Update children of an instance with new text.
+ * When child is an instance - we update it's children with a single text entry.
+ */
+export const setInstanceChildrenMutable = (
+ id: Instance["id"],
+ // Not a consistent format now, maybe better:
+ // [{set: 'string'}, {set: instance}, {update: {id,text}}]
+ updates: ChildrenUpdates,
+ rootInstance: Instance
+) => {
+ const instance = findInstanceById(rootInstance, id);
+ if (instance === undefined) return false;
+ const children = [];
+
+ for (const update of updates) {
+ // Set a string as a child
+ if (typeof update === "string") {
+ children.push(update);
+ continue;
+ }
+ // We need to create an instance
+ if ("createInstance" in update) {
+ const childInstance = createInstance({
+ id: update.id,
+ component: update.component,
+ children: [update.text],
+ });
+ children.push(childInstance);
+ continue;
+ }
+
+ // Set text as a single child of a child instance
+ if ("text" in update) {
+ const childInstance = findInstanceById(instance, update.id);
+ // It should be impossible to have not found that instance
+ if (childInstance === undefined) continue;
+ children.push({ ...childInstance, children: [update.text] });
+ continue;
+ }
+
+ // It's a new instance.
+ children.push(update);
+ }
+
+ instance.children = children;
+ return true;
+};
diff --git a/packages/project/src/shared/tree-utils/set-instance-style.ts b/packages/project/src/shared/tree-utils/set-instance-style.ts
new file mode 100644
index 0000000000..845dc36075
--- /dev/null
+++ b/packages/project/src/shared/tree-utils/set-instance-style.ts
@@ -0,0 +1,25 @@
+import { Breakpoint, type Instance } from "@webstudio-is/react-sdk";
+import { StyleUpdates } from "../canvas-components";
+import { findInstanceById } from "./find-instance";
+
+export const setInstanceStyleMutable = (
+ rootInstance: Instance,
+ id: Instance["id"],
+ updates: StyleUpdates["updates"],
+ breakpoint: Breakpoint
+) => {
+ const instance = findInstanceById(rootInstance, id);
+ if (instance === undefined) return false;
+ let cssRule = instance.cssRules.find(
+ (cssRule) => cssRule.breakpoint === breakpoint.id
+ );
+ if (cssRule === undefined) {
+ cssRule = { style: {}, breakpoint: breakpoint.id };
+ instance.cssRules.push(cssRule);
+ }
+
+ for (const update of updates) {
+ cssRule.style[update.property] = update.value;
+ }
+ return true;
+};
diff --git a/apps/designer/app/shared/db/tree.server.ts b/packages/project/src/tree.ts
similarity index 93%
rename from apps/designer/app/shared/db/tree.server.ts
rename to packages/project/src/tree.ts
index da500b9155..5ca4894ad0 100644
--- a/apps/designer/app/shared/db/tree.server.ts
+++ b/packages/project/src/tree.ts
@@ -6,10 +6,10 @@ import {
} from "@webstudio-is/react-sdk";
import { applyPatches, type Patch } from "immer";
import { prisma } from "@webstudio-is/prisma-client";
-import { createInstance, populateInstance } from "~/shared/tree-utils";
-import { sort } from "~/shared/breakpoints";
import { Tree as DbTree } from "@prisma/client";
-import { Project } from "./project.server";
+import { Project } from "./project";
+import { sort } from "./shared/breakpoints";
+import { createInstance, populateInstance } from "./shared/tree-utils";
export const createRootInstance = (breakpoints: Array<Breakpoint>) => {
// Take the smallest breakpoint as default
diff --git a/packages/project/tsconfig.json b/packages/project/tsconfig.json
new file mode 100644
index 0000000000..6b67ca9bbf
--- /dev/null
+++ b/packages/project/tsconfig.json
@@ -0,0 +1,12 @@
+// Extends can't use node's resolution rn https://github.com/dividab/tsconfig-paths/issues/209#issuecomment-1177261091
+{
+ "extends": "../../node_modules/@webstudio-is/tsconfig/base.json",
+ "include": ["./src/**/*.ts"],
+ "compilerOptions": {
+ "module": "commonjs",
+ "target": "ES2020",
+ "strict": true,
+ "baseUrl": ".",
+ "outDir": "./lib"
+ }
+}
diff --git a/yarn.lock b/yarn.lock
index 618e51585d..e821573cf6 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -13237,6 +13237,11 @@ nanoid@^3.2.0, nanoid@^3.3.1, nanoid@^3.3.4:
resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-3.3.4.tgz#730b67e3cd09e2deacf03c027c81c9d9dbc5e8ab"
integrity sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==
+nanoid@^4.0.0:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/nanoid/-/nanoid-4.0.0.tgz#6e144dee117609232c3f415c34b0e550e64999a5"
+ integrity sha512-IgBP8piMxe/gf73RTQx7hmnhwz0aaEXYakvqZyE302IXW3HyVNhdNGC+O2MwMAVhLEnvXlvKtGbtJf6wvHihCg==
+
nanomatch@^1.2.9:
version "1.2.13"
resolved "https://registry.yarnpkg.com/nanomatch/-/nanomatch-1.2.13.tgz#b87a8aa4fc0de8fe6be88895b38983ff265bd119"
@@ -18069,6 +18074,11 @@ zod@^3.17.3:
resolved "https://registry.yarnpkg.com/zod/-/zod-3.17.3.tgz#86abbc670ff0063a4588d85a4dcc917d6e4af2ba"
integrity sha512-4oKP5zvG6GGbMlqBkI5FESOAweldEhSOZ6LI6cG+JzUT7ofj1ZOC0PJudpQOpT1iqOFpYYtX5Pw0+o403y4bcg==
+zod@^3.19.1:
+ version "3.19.1"
+ resolved "https://registry.yarnpkg.com/zod/-/zod-3.19.1.tgz#112f074a97b50bfc4772d4ad1576814bd8ac4473"
+ integrity sha512-LYjZsEDhCdYET9ikFu6dVPGp2YH9DegXjdJToSzD9rO6fy4qiRYFoyEYwps88OseJlPyl2NOe2iJuhEhL7IpEA==
+
zwitch@^1.0.0:
version "1.0.5"
resolved "https://registry.yarnpkg.com/zwitch/-/zwitch-1.0.5.tgz#d11d7381ffed16b742f6af7b3f223d5cd9fe9920"