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 breakpoints to Build table (#926)
Bogdan Chadkin073062a4bfdd
diff --git a/apps/designer/app/canvas/canvas.tsx b/apps/designer/app/canvas/canvas.tsxindex 5850dcc508..e9436b7828 100644--- a/apps/designer/app/canvas/canvas.tsx+++ b/apps/designer/app/canvas/canvas.tsx@@ -127,7 +127,7 @@ export const Canvas = ({ data }: CanvasProps): JSX.Element | null => {}const isDesignerReady = useSubscribeDesignerReady();const assets = useAssets(data.assets);- useSetBreakpoints(data.breakpoints);+ useSetBreakpoints(data.build.breakpoints);useSetProps(data.tree.props);// inject props store to sdksetPropsByInstanceIdStore(propsByInstanceIdStore);diff --git a/apps/designer/app/shared/css-utils/generate-css-text.ts b/apps/designer/app/shared/css-utils/generate-css-text.tsindex ef46a63cd8..fcc66b8a3b 100644--- a/apps/designer/app/shared/css-utils/generate-css-text.ts+++ b/apps/designer/app/shared/css-utils/generate-css-text.ts@@ -35,7 +35,7 @@ export const generateCssText = async (addGlobalRules(engine, canvasData);- for (const breakpoint of canvasData.breakpoints) {+ for (const breakpoint of canvasData.build?.breakpoints ?? []) {engine.addMediaRule(breakpoint.id, breakpoint);}diff --git a/apps/designer/app/shared/db/canvas.server.ts b/apps/designer/app/shared/db/canvas.server.tsindex 9e443f7418..ed2129e654 100644--- a/apps/designer/app/shared/db/canvas.server.ts+++ b/apps/designer/app/shared/db/canvas.server.ts@@ -23,9 +23,8 @@ export const loadCanvasData = async (throw new Error(`Page ${pageIdOrPath} not found`);}- const [tree, breakpoints, assets] = await Promise.all([+ const [tree, assets] = await Promise.all([projectDb.tree.loadById(page.treeId),- projectDb.breakpoints.load(build.id),loadByProject(project.id),]);@@ -33,14 +32,9 @@ export const loadCanvasData = async (throw new Error(`Tree not found for project ${project.id}`);}- if (breakpoints === null) {- throw new Error(`Breakpoints not found for project ${project.id}`);- }-return {build,tree,- breakpoints: breakpoints.values,buildId: build.id,page,assets,diff --git a/packages/css-data/src/schema.ts b/packages/css-data/src/schema.tsindex 27517bcb33..ed53a08abe 100644--- a/packages/css-data/src/schema.ts+++ b/packages/css-data/src/schema.ts@@ -149,6 +149,8 @@ export const Breakpoint = z.object({minWidth: z.number(),});+export type Breakpoint = z.infer<typeof Breakpoint>;+export const Breakpoints = z.array(Breakpoint);-export type Breakpoint = z.infer<typeof Breakpoint>;+export type Breakpoints = z.infer<typeof Breakpoints>;diff --git a/packages/prisma-client/prisma/migrations/20230202174408_build_breakpoints/migration.sql b/packages/prisma-client/prisma/migrations/20230202174408_build_breakpoints/migration.sqlnew file mode 100644index 0000000000..ae492cbf9e--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230202174408_build_breakpoints/migration.sql@@ -0,0 +1,5 @@+-- DropForeignKey+ALTER TABLE "Breakpoints" DROP CONSTRAINT "Breakpoints_buildId_fkey";++-- AlterTable+ALTER TABLE "Build" ADD COLUMN "breakpoints" TEXT NOT NULL DEFAULT '[]';diff --git a/packages/prisma-client/prisma/migrations/20230202174456_build_breakpoints_data/migration.ts b/packages/prisma-client/prisma/migrations/20230202174456_build_breakpoints_data/migration.tsnew file mode 100644index 0000000000..cf6198c590--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230202174456_build_breakpoints_data/migration.ts@@ -0,0 +1,19 @@+import { PrismaClient } from "./client";++export default () => {+ const client = new PrismaClient({+ // Uncomment to see the queries in console as the migration runs+ // log: ["query", "info", "warn", "error"],+ });+ return client.$transaction(+ async (prisma) => {+ await prisma.$executeRaw`+ UPDATE "Build"+ SET breakpoints="Breakpoints".values+ FROM "Breakpoints"+ WHERE "Build".id="Breakpoints"."buildId";+ `;+ },+ { timeout: 1000 * 60 }+ );+};diff --git a/packages/prisma-client/prisma/migrations/20230202174456_build_breakpoints_data/schema.prisma b/packages/prisma-client/prisma/migrations/20230202174456_build_breakpoints_data/schema.prismanew file mode 100644index 0000000000..4939b404ec--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230202174456_build_breakpoints_data/schema.prisma@@ -0,0 +1,131 @@+// 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 @id @default(uuid())+ projectId String+ format String+ size Int+ name String+ description String?+ location Location+ createdAt DateTime @default(now())+ meta String @default("{}")+ status UploadStatus @default(UPLOADED)+}++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())+ title String+ domain String @unique+ user User? @relation(fields: [userId], references: [id])+ userId String?+ build Build[]+ trees Tree[]+ isDeleted Boolean @default(false)+}++model Build {+ id String @id @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("[]")+}++model Tree {+ id String @id @default(uuid())+ project Project @relation(fields: [projectId], references: [id])+ projectId String+ build Build @relation(fields: [buildId], references: [id])+ buildId String+ root String+ instances String @default("[]")+ props String @default("[]")+ styles String @default("[]")+ styleSelections String @default("[]")+}++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())+ 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 958b1a3d12..a09196e056 100644--- a/packages/prisma-client/prisma/schema.prisma+++ b/packages/prisma-client/prisma/schema.prisma@@ -75,8 +75,7 @@ model Build {isDev Boolean // exctly one is true per projectisProd Boolean // at most one is true per project (none if not published)- breakpoints Breakpoints?-+ breakpoints String @default("[]")styles String @default("[]")styleSources String @default("[]")}@@ -95,7 +94,6 @@ model Tree {}model Breakpoints {- build Build @relation(fields: [buildId], references: [id])buildId String @idvalues String @default("[]")}diff --git a/packages/project/src/db/breakpoints.ts b/packages/project/src/db/breakpoints.tsindex d7a5732ff1..6fbb7c5863 100644--- a/packages/project/src/db/breakpoints.ts+++ b/packages/project/src/db/breakpoints.ts@@ -4,55 +4,19 @@ import { initialBreakpoints } from "@webstudio-is/react-sdk";import {type Breakpoints as DbBreakpoints,prisma,- Prisma,} from "@webstudio-is/prisma-client";-import { type Breakpoint, Breakpoints } from "@webstudio-is/css-data";+import { Breakpoints } from "@webstudio-is/css-data";import type { Project } from "./schema";import {authorizeProject,type AppContext,} from "@webstudio-is/trpc-interface/server";-export const load = async (buildId: DbBreakpoints["buildId"]) => {- const breakpoints = await prisma.breakpoints.findUnique({- where: { buildId },- });-- if (breakpoints === null) {- throw new Error("Breakpoints not found");- }- const values: Array<Breakpoint> = JSON.parse(breakpoints.values);- Breakpoints.parse(values);- return {- ...breakpoints,- values,- };-};--export const createValues = () =>- Breakpoints.parse(- initialBreakpoints.map((breakpoint) => ({- ...breakpoint,- id: nanoid(),- }))- );--export const create = async (- buildId: DbBreakpoints["buildId"],- values: Array<Breakpoint>,- client: Prisma.TransactionClient = prisma-) => {- const breakpoints = await client.breakpoints.create({- data: {- values: JSON.stringify(values),- buildId,- },- });-- return {- ...breakpoints,- values,- };+export const createValues = (): Breakpoints => {+ return initialBreakpoints.map((breakpoint) => ({+ ...breakpoint,+ id: nanoid(),+ }));};export const patch = async (@@ -72,13 +36,20 @@ export const patch = async (throw new Error("You don't have edit access to this project");}- const breakpoints = await load(buildId);- const nextValues = applyPatches(breakpoints.values, patches);+ const build = await prisma.build.findUnique({+ where: { id: buildId },+ });- Breakpoints.parse(nextValues);+ if (build === null) {+ return;+ }+ const breakpoints = Breakpoints.parse(JSON.parse(build.breakpoints));+ const patchedBreakpoints = Breakpoints.parse(+ applyPatches(breakpoints, patches)+ );- await prisma.breakpoints.update({- where: { buildId: breakpoints.buildId },- data: { values: JSON.stringify(nextValues) },+ await prisma.build.update({+ where: { id: buildId },+ data: { breakpoints: JSON.stringify(patchedBreakpoints) },});};diff --git a/packages/project/src/db/build.ts b/packages/project/src/db/build.tsindex 2599234763..0299981376 100644--- a/packages/project/src/db/build.ts+++ b/packages/project/src/db/build.ts@@ -5,6 +5,7 @@ import {Prisma,Project,} from "@webstudio-is/prisma-client";+import { Breakpoints } from "@webstudio-is/css-data";import { StyleSources } from "@webstudio-is/project-build";import * as db from ".";import { Build, Page, Pages } from "./schema";@@ -14,9 +15,13 @@ import { parseStyles, serializeStyles } from "./styles";export const parseBuild = async (build: DbBuild): Promise<Build> => {const pages = Pages.parse(JSON.parse(build.pages));return {- ...build,+ id: build.id,+ projectId: build.projectId,+ isDev: build.isDev,+ isProd: build.isProd,createdAt: build.createdAt.toISOString(),pages,+ breakpoints: Breakpoints.parse(JSON.parse(build.breakpoints)),styles: await parseStyles(build.styles),styleSources: StyleSources.parse(JSON.parse(build.styleSources)),};@@ -254,10 +259,6 @@ export async function create(throw new Error("Source build required for production build");}- const breakpointsValues = sourceBuild- ? (await db.breakpoints.load(sourceBuild.id)).values- : db.breakpoints.createValues();-if (env === "prod") {await client.build.updateMany({where: { projectId: projectId, isProd: true },@@ -269,6 +270,9 @@ export async function create(data: {projectId,pages: JSON.stringify([]),+ breakpoints: JSON.stringify(+ sourceBuild?.breakpoints ?? db.breakpoints.createValues()+ ),styles: serializeStyles(sourceBuild?.styles ?? []),styleSources: JSON.stringify(sourceBuild?.styleSources ?? []),isDev: env === "dev",@@ -289,6 +293,4 @@ export async function create(pages: JSON.stringify(pages),},});-- await db.breakpoints.create(build.id, breakpointsValues, client);}diff --git a/packages/project/src/db/schema.ts b/packages/project/src/db/schema.tsindex 956920105a..f91daf00a7 100644--- a/packages/project/src/db/schema.ts+++ b/packages/project/src/db/schema.ts@@ -1,5 +1,6 @@import { z, type ZodType } from "zod";import { Project } from "@webstudio-is/prisma-client";+import type { Breakpoints } from "@webstudio-is/css-data";import type { Styles, StyleSources } from "@webstudio-is/project-build";import type { Data } from "@webstudio-is/react-sdk";@@ -78,6 +79,7 @@ export type Build = {isDev: boolean;isProd: boolean;pages: Pages;+ breakpoints: Breakpoints;styles: Styles;styleSources: StyleSources;};diff --git a/packages/react-sdk/src/tree/root.ts b/packages/react-sdk/src/tree/root.tsindex 15a9ae19c9..59fde2ed31 100644--- a/packages/react-sdk/src/tree/root.ts+++ b/packages/react-sdk/src/tree/root.ts@@ -1,6 +1,5 @@import type { ComponentProps } from "react";import { atom } from "nanostores";-import type { Breakpoint } from "@webstudio-is/css-data";import type { Tree } from "@webstudio-is/project-build";import type { Asset } from "@webstudio-is/asset-uploader";import { createElementsTree } from "./create-elements-tree";@@ -12,7 +11,6 @@ import { getPropsByInstanceId, setPropsByInstanceIdStore } from "../props";export type Data = {tree: Tree | null;- breakpoints: Array<Breakpoint>;assets: Array<Asset>;params?: Params;};