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
Move instances to build (#1144)
Bogdan Chadkin5d5172f846a2
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsxindex 38258d0180..255630a78c 100644--- a/apps/builder/app/canvas/canvas.tsx+++ b/apps/builder/app/canvas/canvas.tsx@@ -107,7 +107,7 @@ export const Canvas = ({useSetStyles(data.build.styles);useSetStyleSources(data.build.styleSources);useSetStyleSourceSelections(data.build.styleSourceSelections);- useSetInstances(data.tree.instances);+ useSetInstances(data.build.instances);useSetSelectedPage(data.page);setParams(data.params ?? null);useCanvasStore(publish);diff --git a/apps/builder/app/routes/rest/patch.ts b/apps/builder/app/routes/rest/patch.tsindex ba14d4bc4c..8b1499e6ae 100644--- a/apps/builder/app/routes/rest/patch.ts+++ b/apps/builder/app/routes/rest/patch.ts@@ -42,7 +42,7 @@ export const action = async ({ request }: ActionArgs) => {const { namespace, patches } = change;if (namespace === "instances") {- await patchInstances({ treeId, projectId }, patches, context);+ await patchInstances({ buildId, projectId }, patches, context);} else if (namespace === "styleSourceSelections") {await patchStyleSourceSelections({ buildId, projectId },diff --git a/packages/prisma-client/prisma/migrations/20230228194425_build_instances/migration.sql b/packages/prisma-client/prisma/migrations/20230228194425_build_instances/migration.sqlnew file mode 100644index 0000000000..b83d654ee5--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230228194425_build_instances/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "Build" ADD COLUMN "instances" TEXT NOT NULL DEFAULT '[]';diff --git a/packages/prisma-client/prisma/migrations/20230228194553_build_instances_data/migration.ts b/packages/prisma-client/prisma/migrations/20230228194553_build_instances_data/migration.tsnew file mode 100644index 0000000000..fd4d71e48e--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230228194553_build_instances_data/migration.ts@@ -0,0 +1,99 @@+import { PrismaClient } from "./client";++type InstanceId = string;+type BuildId = string;++type Child =+ | { type: "text"; value: string }+ | { type: "id"; value: InstanceId };++type Instance = {+ id: InstanceId;+ children: Child[];+};++export default async () => {+ const client = new PrismaClient({+ // Uncomment to see the queries in console as the migration runs+ // log: ["query", "info", "warn", "error"],+ });++ await client.$transaction(+ async (prisma) => {+ let instancesByBuildId = new Map<BuildId, Instance[]>();++ const chunkSize = 1000;+ let cursor: undefined | { id: string; projectId: string } = undefined;+ let hasNext = true;+ while (hasNext) {+ const trees = await prisma.tree.findMany({+ take: chunkSize,+ orderBy: {+ id: "asc",+ },+ ...(cursor+ ? {+ skip: 1, // Skip the cursor+ cursor: { id_projectId: cursor },+ }+ : null),+ });+ const lastTree = trees.at(-1);+ if (lastTree) {+ cursor = { id: lastTree.id, projectId: lastTree?.projectId };+ }+ hasNext = trees.length === chunkSize;++ for (const tree of trees) {+ try {+ const treeInstances: Instance[] = JSON.parse(tree.instances);+ const buildInstances = instancesByBuildId.get(tree.buildId) ?? [];+ instancesByBuildId.set(tree.buildId, [+ ...buildInstances,+ ...treeInstances,+ ]);+ } catch {+ console.info(`Tree ${tree.id} cannot be converted`);+ }+ }+ }++ cursor = undefined;+ hasNext = true;+ while (hasNext) {+ const builds = await prisma.build.findMany({+ take: chunkSize,+ orderBy: {+ id: "asc",+ },+ ...(cursor+ ? {+ skip: 1, // Skip the cursor+ cursor: { id_projectId: cursor },+ }+ : null),+ });+ const lastBuild = builds.at(-1);+ if (lastBuild) {+ cursor = { id: lastBuild.id, projectId: lastBuild.projectId };+ }+ hasNext = builds.length === chunkSize;++ for (const build of builds) {+ const instances = instancesByBuildId.get(build.id) ?? [];+ build.instances = JSON.stringify(instances);+ }++ await Promise.all(+ builds.map(({ id, projectId, instances }) =>+ prisma.build.update({+ where: { id_projectId: { id, projectId } },+ data: { instances },+ })+ )+ );+ }+ },+ { timeout: 1000 * 60 * 8 }+ );+};diff --git a/packages/prisma-client/prisma/migrations/20230228194553_build_instances_data/schema.prisma b/packages/prisma-client/prisma/migrations/20230228194553_build_instances_data/schema.prismanew file mode 100644index 0000000000..3afc67aa01--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230228194553_build_instances_data/schema.prisma@@ -0,0 +1,145 @@+// DO NOT EDIT THIS FILE!+// This is a copy of your schema.prisma that corresponds to the state of the database+// when all migrations up until this one are applied.+// It's used to generate a Prisma Client for the migration.++// This is your Prisma schema file,+// learn more about it in the docs: https://pris.ly/d/prisma-schema++generator client {+ provider = "prisma-client-js"+ previewFeatures = ["views", "clientExtensions"]+ output = "client"+}++datasource db {+ provider = "postgres"+ url = env("DATABASE_URL")+}++model Team {+ id String @id @default(uuid())+ users User[]+}++enum Location {+ FS+ REMOTE+}++enum UploadStatus {+ UPLOADING+ UPLOADED+}++model Asset {+ id String @default(uuid()) // not unique!+ projectId String+ format String+ size Int+ name String+ description String?+ location Location+ createdAt DateTime @default(now())+ meta String @default("{}")+ status UploadStatus @default(UPLOADED)++ @@id([id, projectId])+}++model User {+ id String @id @default(uuid())+ email String? @unique+ provider String?+ image String?+ username String?+ createdAt DateTime @default(now())+ team Team? @relation(fields: [teamId], references: [id])+ teamId String?+ projects Project[]+}++model Project {+ id String @id @default(uuid())+ createdAt DateTime @default(now())+ title String+ domain String @unique+ user User? @relation(fields: [userId], references: [id])+ userId String?+ build Build[]+ trees Tree[]+ isDeleted Boolean @default(false)++ @@unique([id, isDeleted])+ @@unique([domain, isDeleted])+}++model Build {+ id String @default(uuid())+ createdAt DateTime @default(now())+ pages String++ project Project @relation(fields: [projectId], references: [id])+ projectId String+ trees Tree[]++ isDev Boolean // exctly one is true per project+ isProd Boolean // at most one is true per project (none if not published)++ breakpoints String @default("[]")+ styles String @default("[]")+ styleSources String @default("[]")+ styleSourceSelections String @default("[]")+ props String @default("[]")+ instances String @default("[]")++ @@id([id, projectId])+}++model Tree {+ id String @default(uuid())+ project Project @relation(fields: [projectId], references: [id])+ projectId String+ build Build @relation(fields: [buildId, projectId], references: [id, projectId])+ buildId String+ root String+ instances String @default("[]")+ props String @default("[]")+ styles String @default("[]")+ styleSelections String @default("[]")++ @@id([id, projectId])+}++model Breakpoints {+ buildId String @id+ values String @default("[]")+}++enum AuthorizationRelation {+ viewers+ editors+ builders+}++model AuthorizationToken {+ token String @default(uuid())+ // No relation to Project, as the Authorization system is not tied to a project+ projectId String+ name String @default("")+ relation AuthorizationRelation @default(viewers)+ createdAt DateTime @default(now())++ @@id([token, projectId])+}++// Dashboard+view DashboardProject {+ id String @id @default(uuid())+ createdAt DateTime @default(now())+ title String+ domain String+ userId String?+ isDeleted Boolean @default(false)+ isPublished Boolean+}diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prismaindex 94114703a4..54408a8474 100644--- a/packages/prisma-client/prisma/schema.prisma+++ b/packages/prisma-client/prisma/schema.prisma@@ -86,6 +86,7 @@ model Build {styleSources String @default("[]")styleSourceSelections String @default("[]")props String @default("[]")+ instances String @default("[]")@@id([id, projectId])}diff --git a/packages/project-build/src/db/build.ts b/packages/project-build/src/db/build.tsindex 48517333b6..9eaa4be9af 100644--- a/packages/project-build/src/db/build.ts+++ b/packages/project-build/src/db/build.ts@@ -7,7 +7,7 @@ import {} from "@webstudio-is/prisma-client";import type { AppContext } from "@webstudio-is/trpc-interface";import { findPageByIdOrPath } from "../shared/pages-utils";-import type { Build, Tree } from "../types";+import type { Build } from "../types";import { type Page, Pages } from "../schema/pages";import {createInitialBreakpoints,@@ -21,6 +21,7 @@ import {serializeStyleSourceSelections,} from "./style-source-selections";import { parseProps, serializeProps } from "./props";+import { parseInstances, serializeInstances } from "./instances";import { cloneTree, createTree, deleteTreeById } from "./tree";const parseBuild = async (build: DbBuild): Promise<Build> => {@@ -39,6 +40,7 @@ const parseBuild = async (build: DbBuild): Promise<Build> => {parseStyleSourceSelections(build.styleSourceSelections)),props: Array.from(parseProps(build.props)),+ instances: Array.from(parseInstances(build.instances)),};};@@ -115,7 +117,7 @@ const updatePages = async (return parseBuild(updatedBuild);};-const createNewPageInstances = (): Tree["instances"] => {+const createNewPageInstances = (): Build["instances"] => {const instanceId = nanoid();return [[@@ -146,7 +148,6 @@ export const addPage = async ({const tree = await createTree({projectId,buildId,- instances,});return {@@ -227,8 +228,9 @@ export const deletePage = async ({await deleteTreeById({ projectId, treeId: page.treeId });- // @todo cleanup style source selections of deleted instances- // @todo cleanup props of deleted instances+ // @todo cleanup style source selections of deleted pages+ // @todo cleanup props of deleted pages+ // @todo cleanup instances of deleted pagesreturn {homePage: currentPages.homePage,@@ -248,7 +250,6 @@ const createPages = async ({projectId,buildId,- instances,},client);@@ -374,6 +375,7 @@ export async function createBuild(new Map(props.sourceBuild?.styleSourceSelections)),props: serializeProps(new Map(props.sourceBuild?.props)),+ instances: serializeInstances(new Map(props.sourceBuild?.instances)),isDev: props.env === "dev",isProd: props.env === "prod",},diff --git a/packages/project-build/src/db/instances.ts b/packages/project-build/src/db/instances.tsindex 81b5d8a4d0..737ce55416 100644--- a/packages/project-build/src/db/instances.ts+++ b/packages/project-build/src/db/instances.ts@@ -1,10 +1,9 @@import { applyPatches, type Patch } from "immer";-import { type Project, prisma } from "@webstudio-is/prisma-client";+import { type Project, type Build, prisma } from "@webstudio-is/prisma-client";import {authorizeProject,type AppContext,} from "@webstudio-is/trpc-interface/server";-import type { Tree } from "../types";import { Instances, InstancesList } from "../schema/instances";export const parseInstances = (instancesString: string): Instances => {@@ -18,7 +17,7 @@ export const serializeInstances = (instances: Instances) => {};export const patchInstances = async (- { treeId, projectId }: { treeId: Tree["id"]; projectId: Project["id"] },+ { buildId, projectId }: { buildId: Build["id"]; projectId: Project["id"] },patches: Array<Patch>,context: AppContext) => {@@ -31,23 +30,23 @@ export const patchInstances = async (throw new Error("You don't have edit access to this project");}- const tree = await prisma.tree.findUnique({+ const build = await prisma.build.findUnique({where: {- id_projectId: { projectId, id: treeId },+ id_projectId: { projectId, id: buildId },},});- if (tree === null) {+ if (build === null) {return;}- const instances = parseInstances(tree.instances);+ const instances = parseInstances(build.instances);const patchedInstances = Instances.parse(applyPatches(instances, patches));- await prisma.tree.update({+ await prisma.build.update({data: {instances: serializeInstances(patchedInstances),},where: {- id_projectId: { projectId, id: treeId },+ id_projectId: { projectId, id: buildId },},});};diff --git a/packages/project-build/src/db/tree.ts b/packages/project-build/src/db/tree.tsindex 9d33105e0d..e155635577 100644--- a/packages/project-build/src/db/tree.ts+++ b/packages/project-build/src/db/tree.ts@@ -2,7 +2,6 @@ import { v4 as uuid } from "uuid";import { type Project, type Prisma, prisma } from "@webstudio-is/prisma-client";import type { AppContext } from "@webstudio-is/trpc-interface/server";import type { Tree } from "../types";-import { parseInstances, serializeInstances } from "./instances";type TreeData = Omit<Tree, "id">;@@ -19,7 +18,6 @@ export const createTree = async (buildId: treeData.buildId,root: "",styles: "",- instances: serializeInstances(new Map(treeData.instances)),},});};@@ -52,13 +50,10 @@ export const loadTreeById = async (return null;}- const instances = parseInstances(tree.instances);-return {id: tree.id,projectId: tree.projectId,buildId: tree.buildId,- instances: Array.from(instances),};};diff --git a/packages/project-build/src/types.ts b/packages/project-build/src/types.tsindex f06478e471..6065cc960a 100644--- a/packages/project-build/src/types.ts+++ b/packages/project-build/src/types.ts@@ -18,11 +18,11 @@ export type Build = {styleSources: [StyleSource["id"], StyleSource][];styleSourceSelections: [Instance["id"], StyleSourceSelection][];props: [Prop["id"], Prop][];+ instances: [InstancesItem["id"], InstancesItem][];};export type Tree = {id: string;projectId: string;buildId: string;- instances: [InstancesItem["id"], InstancesItem][];};diff --git a/packages/react-sdk/src/tree/root.ts b/packages/react-sdk/src/tree/root.tsindex 77714439f3..dbdfbb4a99 100644--- a/packages/react-sdk/src/tree/root.ts+++ b/packages/react-sdk/src/tree/root.ts@@ -76,7 +76,7 @@ export const InstanceRoot = ({registerComponents(customComponents);const instance = denormalizeTree(- new Map(data.tree.instances),+ new Map(data.build.instances),data.page.rootInstanceId);if (instance === undefined) {