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 props to build (#1136)
Bogdan Chadkin3239ae8587c1
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsxindex 5394a2f9b2..92db151ef5 100644--- a/apps/builder/app/canvas/canvas.tsx+++ b/apps/builder/app/canvas/canvas.tsx@@ -104,7 +104,7 @@ export const Canvas = ({useSetTreeId(data.tree.id);useSetAssets(data.assets);useSetBreakpoints(data.build.breakpoints);- useSetProps(data.tree.props);+ useSetProps(data.build.props);useSetStyles(data.build.styles);useSetStyleSources(data.build.styleSources);useSetStyleSourceSelections(data.build.styleSourceSelections);diff --git a/apps/builder/app/routes/rest/patch.ts b/apps/builder/app/routes/rest/patch.tsindex 9a5f57473a..ba14d4bc4c 100644--- a/apps/builder/app/routes/rest/patch.ts+++ b/apps/builder/app/routes/rest/patch.ts@@ -54,7 +54,7 @@ export const action = async ({ request }: ActionArgs) => {} else if (namespace === "styles") {await patchStyles({ buildId, projectId }, patches, context);} else if (namespace === "props") {- await patchProps({ treeId, projectId }, patches, context);+ await patchProps({ buildId, projectId }, patches, context);} else if (namespace === "breakpoints") {await patchBreakpoints({ buildId, projectId }, patches, context);} else {diff --git a/packages/prisma-client/prisma/migrations/20230227180214_build_props/migration.sql b/packages/prisma-client/prisma/migrations/20230227180214_build_props/migration.sqlnew file mode 100644index 0000000000..22ebea0e76--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230227180214_build_props/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "Build" ADD COLUMN "props" TEXT NOT NULL DEFAULT '[]';diff --git a/packages/prisma-client/prisma/migrations/20230227180250_build_props_data/migration.ts b/packages/prisma-client/prisma/migrations/20230227180250_build_props_data/migration.tsnew file mode 100644index 0000000000..369269286c--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230227180250_build_props_data/migration.ts@@ -0,0 +1,102 @@+import { PrismaClient } from "./client";++type PropId = string;+type InstanceId = string;+type BuildId = string;++type Prop = {+ id: PropId;+ instanceId: InstanceId;+};++type Props = Prop[];++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 propsByBuildId = new Map<BuildId, Props>();++ 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 treeProps: Props = JSON.parse(tree.props);+ const buildProps = propsByBuildId.get(tree.buildId) ?? [];+ propsByBuildId.set(tree.buildId, [...buildProps, ...treeProps]);+ } 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) {+ // deduplicate badly migrated data+ const props = Array.from(+ new Map(+ (propsByBuildId.get(build.id) ?? []).map((item) => [+ item.instanceId,+ item,+ ])+ ).values()+ );+ build.props = JSON.stringify(props);+ }+ await Promise.all(+ builds.map(({ id, projectId, props }) =>+ prisma.build.update({+ where: { id_projectId: { id, projectId } },+ data: { props },+ })+ )+ );+ }+ },+ { timeout: 1000 * 60 * 8 }+ );+};diff --git a/packages/prisma-client/prisma/migrations/20230227180250_build_props_data/schema.prisma b/packages/prisma-client/prisma/migrations/20230227180250_build_props_data/schema.prismanew file mode 100644index 0000000000..4506a47076--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230227180250_build_props_data/schema.prisma@@ -0,0 +1,144 @@+// 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("[]")++ @@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 2e9a063d6e..94114703a4 100644--- a/packages/prisma-client/prisma/schema.prisma+++ b/packages/prisma-client/prisma/schema.prisma@@ -85,6 +85,7 @@ model Build {styles String @default("[]")styleSources String @default("[]")styleSourceSelections String @default("[]")+ props String @default("[]")@@id([id, projectId])}diff --git a/packages/project-build/src/db/build.ts b/packages/project-build/src/db/build.tsindex 606e980638..68d53649ba 100644--- a/packages/project-build/src/db/build.ts+++ b/packages/project-build/src/db/build.ts@@ -20,6 +20,7 @@ import {parseStyleSourceSelections,serializeStyleSourceSelections,} from "./style-source-selections";+import { parseProps, serializeProps } from "./props";import {cloneTree,createNewTreeData,@@ -42,6 +43,7 @@ const parseBuild = async (build: DbBuild): Promise<Build> => {styleSourceSelections: Array.from(parseStyleSourceSelections(build.styleSourceSelections)),+ props: Array.from(parseProps(build.props)),};};@@ -208,6 +210,7 @@ export const deletePage = async ({await deleteTreeById({ projectId, treeId: page.treeId });// @todo cleanup style source selections of deleted instances+ // @todo cleanup props of deleted instancesreturn {homePage: currentPages.homePage,@@ -345,6 +348,7 @@ export async function createBuild(styleSourceSelections: serializeStyleSourceSelections(new Map(props.sourceBuild?.styleSourceSelections)),+ props: serializeProps(new Map(props.sourceBuild?.props)),isDev: props.env === "dev",isProd: props.env === "prod",},diff --git a/packages/project-build/src/db/props.ts b/packages/project-build/src/db/props.tsindex e52504d199..7de986cdfe 100644--- a/packages/project-build/src/db/props.ts+++ b/packages/project-build/src/db/props.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 { Props, PropsList } from "../schema/props";export const parseProps = (propsString: string): Props => {@@ -18,7 +17,7 @@ export const serializeProps = (props: Props) => {};export const patchProps = 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 patchProps = 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 props = parseProps(tree.props);+ const props = parseProps(build.props);const patchedProps = Props.parse(applyPatches(props, patches));- await prisma.tree.update({+ await prisma.build.update({data: {props: serializeProps(patchedProps),},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 053b1f013b..228de70653 100644--- a/packages/project-build/src/db/tree.ts+++ b/packages/project-build/src/db/tree.ts@@ -4,7 +4,6 @@ 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";-import { parseProps, serializeProps } from "./props";type TreeData = Omit<Tree, "id">;@@ -31,7 +30,6 @@ export const createNewTreeData = ({},],],- props: [],};};@@ -49,7 +47,6 @@ export const createTree = async (root: "",styles: "",instances: serializeInstances(new Map(treeData.instances)),- props: serializeProps(new Map(treeData.props)),},});};@@ -83,14 +80,12 @@ export const loadTreeById = async (}const instances = parseInstances(tree.instances);- const props = parseProps(tree.props);return {id: tree.id,projectId: tree.projectId,buildId: tree.buildId,instances: Array.from(instances),- props: Array.from(props),};};diff --git a/packages/project-build/src/types.ts b/packages/project-build/src/types.tsindex 44ff6ade19..f06478e471 100644--- a/packages/project-build/src/types.ts+++ b/packages/project-build/src/types.ts@@ -17,6 +17,7 @@ export type Build = {styles: [StyleDeclKey, StyleDecl][];styleSources: [StyleSource["id"], StyleSource][];styleSourceSelections: [Instance["id"], StyleSourceSelection][];+ props: [Prop["id"], Prop][];};export type Tree = {@@ -24,5 +25,4 @@ export type Tree = {projectId: string;buildId: string;instances: [InstancesItem["id"], InstancesItem][];- props: [Prop["id"], Prop][];};diff --git a/packages/react-sdk/src/tree/root.ts b/packages/react-sdk/src/tree/root.tsindex 5b698be4f1..ff91f84de5 100644--- a/packages/react-sdk/src/tree/root.ts+++ b/packages/react-sdk/src/tree/root.ts@@ -1,6 +1,7 @@import type { ComponentProps } from "react";import { atom } from "nanostores";import type {+ Build,Instance,Instances,InstancesItem,@@ -17,6 +18,7 @@ import type { GetComponent } from "../components/components-utils";export type Data = {tree: Tree | null;+ build: Build | null;assets: Array<Asset>;params?: Params;};@@ -57,8 +59,8 @@ export const InstanceRoot = ({customComponents = defaultCustomComponents,getComponent,}: RootProps): JSX.Element | null => {- if (data.tree === null) {- throw new Error("Tree is null");+ if (data.tree === null || data.build === null) {+ throw new Error("Tree and build are required");}setParams(data.params ?? null);@@ -68,7 +70,7 @@ export const InstanceRoot = ({return createElementsTree({instance: denormalizeTree(new Map(data.tree.instances)),propsByInstanceIdStore: atom(- getPropsByInstanceId(new Map(data.tree.props))+ getPropsByInstanceId(new Map(data.build.props))),assetsStore: atom(new Map(data.assets.map((asset) => [asset.id, asset]))),Component: Component ?? WebstudioComponent,