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.

Move style source selections to build (#1133)

Bogdan Chadkina794970409d9
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index 6b775a7e89..5394a2f9b2 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -107,7 +107,7 @@ export const Canvas = ({
useSetProps(data.tree.props);
useSetStyles(data.build.styles);
useSetStyleSources(data.build.styleSources);
- useSetStyleSourceSelections(data.tree.styleSourceSelections);
+ useSetStyleSourceSelections(data.build.styleSourceSelections);
useSetInstances(data.tree.instances);
setParams(data.params ?? null);
useCanvasStore(publish);
diff --git a/apps/builder/app/routes/rest/patch.ts b/apps/builder/app/routes/rest/patch.ts
index 1025f3cf01..9a5f57473a 100644
--- a/apps/builder/app/routes/rest/patch.ts
+++ b/apps/builder/app/routes/rest/patch.ts
@@ -45,7 +45,7 @@ export const action = async ({ request }: ActionArgs) => {
await patchInstances({ treeId, projectId }, patches, context);
} else if (namespace === "styleSourceSelections") {
await patchStyleSourceSelections(
- { treeId, projectId },
+ { buildId, projectId },
patches,
context
);
diff --git a/apps/builder/app/routes/s/css.ts b/apps/builder/app/routes/s/css.ts
index 8496b1f63c..b80d2b5c81 100644
--- a/apps/builder/app/routes/s/css.ts
+++ b/apps/builder/app/routes/s/css.ts
@@ -6,7 +6,6 @@ import { getBuildParams } from "~/shared/router-utils";
import { sentryException } from "~/shared/sentry";
import { createContext } from "~/shared/context.server";
import { loadCanvasData, loadProductionCanvasData } from "~/shared/db";
-import type { Tree } from "@webstudio-is/project-build";
import { createCssEngine } from "@webstudio-is/css-engine";
import { helperStyles } from "~/canvas/shared/styles";
@@ -47,7 +46,7 @@ export const loader = async ({ request }: ActionArgs) => {
assets: canvasData.assets,
breakpoints: canvasData.build?.breakpoints,
styles: canvasData.build?.styles,
- styleSourceSelections: canvasData.tree?.styleSourceSelections,
+ styleSourceSelections: canvasData.build?.styleSourceSelections,
});
const engine = createCssEngine({ name: "ssr" });
@@ -82,21 +81,11 @@ export const loader = async ({ request }: ActionArgs) => {
const canvasData = pagesCanvasData[0];
- const styleSourceSelections: Tree["styleSourceSelections"] = [];
-
- for (const pageCanvasData of pagesCanvasData) {
- if (pageCanvasData.tree?.styleSourceSelections) {
- styleSourceSelections.push(
- ...pageCanvasData.tree.styleSourceSelections
- );
- }
- }
-
const cssText = generateCssText({
assets: canvasData.assets,
breakpoints: canvasData.build?.breakpoints,
styles: canvasData.build?.styles,
- styleSourceSelections,
+ styleSourceSelections: canvasData.build?.styleSourceSelections,
});
return new Response(cssText, {
diff --git a/packages/prisma-client/prisma/migrations/20230227142607_build_style_source_selections/migration.sql b/packages/prisma-client/prisma/migrations/20230227142607_build_style_source_selections/migration.sql
new file mode 100644
index 0000000000..9c58caef1c
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230227142607_build_style_source_selections/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "Build" ADD COLUMN "styleSourceSelections" TEXT NOT NULL DEFAULT '[]';
diff --git a/packages/prisma-client/prisma/migrations/20230227142622_build_style_source_selections_data/migration.ts b/packages/prisma-client/prisma/migrations/20230227142622_build_style_source_selections_data/migration.ts
new file mode 100644
index 0000000000..79b27c2610
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230227142622_build_style_source_selections_data/migration.ts
@@ -0,0 +1,110 @@
+import { PrismaClient } from "./client";
+
+type InstanceId = string;
+type StyleSourceId = string;
+type BuildId = string;
+
+type StyleSourceSelection = {
+ instanceId: InstanceId;
+ values: StyleSourceId[];
+};
+
+type StyleSourceSelections = StyleSourceSelection[];
+
+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 styleSourceSelectionsByBuildId = new Map<
+ BuildId,
+ StyleSourceSelections
+ >();
+
+ 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 treeStyleSourceSelections: StyleSourceSelections = JSON.parse(
+ tree.styleSelections
+ );
+ const buildStyleSourceSelections =
+ styleSourceSelectionsByBuildId.get(tree.buildId) ?? [];
+ styleSourceSelectionsByBuildId.set(tree.buildId, [
+ ...buildStyleSourceSelections,
+ ...treeStyleSourceSelections,
+ ]);
+ } 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 styleSourceSelections = Array.from(
+ new Map(
+ (styleSourceSelectionsByBuildId.get(build.id) ?? []).map(
+ (item) => [item.instanceId, item]
+ )
+ ).values()
+ );
+ build.styleSourceSelections = JSON.stringify(styleSourceSelections);
+ }
+ await Promise.all(
+ builds.map(({ id, projectId, styleSourceSelections }) =>
+ prisma.build.update({
+ where: { id_projectId: { id, projectId } },
+ data: { styleSourceSelections },
+ })
+ )
+ );
+ }
+ },
+ { timeout: 1000 * 60 * 8 }
+ );
+};
diff --git a/packages/prisma-client/prisma/migrations/20230227142622_build_style_source_selections_data/schema.prisma b/packages/prisma-client/prisma/migrations/20230227142622_build_style_source_selections_data/schema.prisma
new file mode 100644
index 0000000000..6eb65b0873
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230227142622_build_style_source_selections_data/schema.prisma
@@ -0,0 +1,143 @@
+// 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("[]")
+
+ @@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.prisma
index 9aa5ed8a55..2e9a063d6e 100644
--- a/packages/prisma-client/prisma/schema.prisma
+++ b/packages/prisma-client/prisma/schema.prisma
@@ -81,9 +81,10 @@ model Build {
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("[]")
+ breakpoints String @default("[]")
+ styles String @default("[]")
+ styleSources String @default("[]")
+ styleSourceSelections String @default("[]")
@@id([id, projectId])
}
diff --git a/packages/project-build/src/db/build.ts b/packages/project-build/src/db/build.ts
index 7295b4286b..606e980638 100644
--- a/packages/project-build/src/db/build.ts
+++ b/packages/project-build/src/db/build.ts
@@ -16,6 +16,10 @@ import {
} from "./breakpoints";
import { parseStyles, serializeStyles } from "./styles";
import { parseStyleSources, serializeStyleSources } from "./style-sources";
+import {
+ parseStyleSourceSelections,
+ serializeStyleSourceSelections,
+} from "./style-source-selections";
import {
cloneTree,
createNewTreeData,
@@ -35,6 +39,9 @@ const parseBuild = async (build: DbBuild): Promise<Build> => {
breakpoints: Array.from(parseBreakpoints(build.breakpoints)),
styles: Array.from(await parseStyles(build.projectId, build.styles)),
styleSources: Array.from(parseStyleSources(build.styleSources)),
+ styleSourceSelections: Array.from(
+ parseStyleSourceSelections(build.styleSourceSelections)
+ ),
};
};
@@ -200,6 +207,8 @@ export const deletePage = async ({
await deleteTreeById({ projectId, treeId: page.treeId });
+ // @todo cleanup style source selections of deleted instances
+
return {
homePage: currentPages.homePage,
pages: currentPages.pages.filter((page) => page.id !== pageId),
@@ -333,6 +342,9 @@ export async function createBuild(
styleSources: serializeStyleSources(
new Map(props.sourceBuild?.styleSources)
),
+ styleSourceSelections: serializeStyleSourceSelections(
+ new Map(props.sourceBuild?.styleSourceSelections)
+ ),
isDev: props.env === "dev",
isProd: props.env === "prod",
},
diff --git a/packages/project-build/src/db/style-source-selections.ts b/packages/project-build/src/db/style-source-selections.ts
index 52ef532c2f..f90618453c 100644
--- a/packages/project-build/src/db/style-source-selections.ts
+++ b/packages/project-build/src/db/style-source-selections.ts
@@ -1,10 +1,9 @@
import { type Patch, applyPatches } 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 {
StyleSourceSelectionsList,
StyleSourceSelections,
@@ -31,7 +30,7 @@ export const serializeStyleSourceSelections = (
};
export const patchStyleSourceSelections = async (
- { treeId, projectId }: { treeId: Tree["id"]; projectId: Project["id"] },
+ { buildId, projectId }: { buildId: Build["id"]; projectId: Project["id"] },
patches: Array<Patch>,
context: AppContext
) => {
@@ -44,31 +43,31 @@ export const patchStyleSourceSelections = 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 styleSourceSelections = parseStyleSourceSelections(
- tree.styleSelections
+ build.styleSourceSelections
);
const patchedStyleSourceSelections = StyleSourceSelections.parse(
applyPatches(styleSourceSelections, patches)
);
- await prisma.tree.update({
+ await prisma.build.update({
data: {
- styleSelections: serializeStyleSourceSelections(
+ styleSourceSelections: serializeStyleSourceSelections(
patchedStyleSourceSelections
),
},
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.ts
index 6e4e07180f..053b1f013b 100644
--- a/packages/project-build/src/db/tree.ts
+++ b/packages/project-build/src/db/tree.ts
@@ -5,10 +5,6 @@ import type { AppContext } from "@webstudio-is/trpc-interface/server";
import type { Tree } from "../types";
import { parseInstances, serializeInstances } from "./instances";
import { parseProps, serializeProps } from "./props";
-import {
- parseStyleSourceSelections,
- serializeStyleSourceSelections,
-} from "./style-source-selections";
type TreeData = Omit<Tree, "id">;
@@ -36,7 +32,6 @@ export const createNewTreeData = ({
],
],
props: [],
- styleSourceSelections: [],
};
};
@@ -55,9 +50,6 @@ export const createTree = async (
styles: "",
instances: serializeInstances(new Map(treeData.instances)),
props: serializeProps(new Map(treeData.props)),
- styleSelections: serializeStyleSourceSelections(
- new Map(treeData.styleSourceSelections)
- ),
},
});
};
@@ -92,9 +84,6 @@ export const loadTreeById = async (
const instances = parseInstances(tree.instances);
const props = parseProps(tree.props);
- const styleSourceSelections = parseStyleSourceSelections(
- tree.styleSelections
- );
return {
id: tree.id,
@@ -102,7 +91,6 @@ export const loadTreeById = async (
buildId: tree.buildId,
instances: Array.from(instances),
props: Array.from(props),
- styleSourceSelections: Array.from(styleSourceSelections),
};
};
diff --git a/packages/project-build/src/types.ts b/packages/project-build/src/types.ts
index 032168bf45..44ff6ade19 100644
--- a/packages/project-build/src/types.ts
+++ b/packages/project-build/src/types.ts
@@ -16,6 +16,7 @@ export type Build = {
breakpoints: [Breakpoint["id"], Breakpoint][];
styles: [StyleDeclKey, StyleDecl][];
styleSources: [StyleSource["id"], StyleSource][];
+ styleSourceSelections: [Instance["id"], StyleSourceSelection][];
};
export type Tree = {
@@ -24,5 +25,4 @@ export type Tree = {
buildId: string;
instances: [InstancesItem["id"], InstancesItem][];
props: [Prop["id"], Prop][];
- styleSourceSelections: [Instance["id"], StyleSourceSelection][];
};
diff --git a/packages/project/src/shared/styles/css.ts b/packages/project/src/shared/styles/css.ts
index 74d52beff5..e95bc08573 100644
--- a/packages/project/src/shared/styles/css.ts
+++ b/packages/project/src/shared/styles/css.ts
@@ -1,6 +1,6 @@
import { createCssEngine } from "@webstudio-is/css-engine";
import type { Asset } from "@webstudio-is/asset-uploader";
-import type { Build, Tree } from "@webstudio-is/project-build";
+import type { Build } from "@webstudio-is/project-build";
import {
getComponentMeta,
getComponentNames,
@@ -13,7 +13,7 @@ type Data = {
assets: Asset[];
breakpoints?: Build["breakpoints"];
styles?: Build["styles"];
- styleSourceSelections?: Tree["styleSourceSelections"];
+ styleSourceSelections?: Build["styleSourceSelections"];
};
export const generateCssText = (data: Data) => {