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.

Normalize styles in database (#749)

Bogdan Chadkin7c5c737bfbee
diff --git a/packages/prisma-client/prisma/migrations/20230106000103_tree_styles/migration.sql b/packages/prisma-client/prisma/migrations/20230106000103_tree_styles/migration.sql
new file mode 100644
index 0000000000..7fcb76d531
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230106000103_tree_styles/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "Tree" ADD COLUMN "styles" TEXT NOT NULL DEFAULT '[]';
diff --git a/packages/prisma-client/prisma/migrations/20230106000143_tree_styles_data/migration.ts b/packages/prisma-client/prisma/migrations/20230106000143_tree_styles_data/migration.ts
new file mode 100644
index 0000000000..c87ac04f73
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230106000143_tree_styles_data/migration.ts
@@ -0,0 +1,100 @@
+import { PrismaClient } from "./client";
+
+type StylesItem = {
+ breakpointId: string;
+ instanceId: string;
+ property: string;
+ value: unknown;
+};
+
+type Styles = StylesItem[];
+
+type CssRule = {
+ breakpoint: undefined | string;
+ style: Record<string, unknown>;
+};
+
+type Text = {
+ type: "text";
+ value: string;
+};
+
+type Instance = {
+ type: "instance";
+ id: string;
+ component: string;
+ cssRules: Array<CssRule>;
+ children: Array<Instance | Text>;
+};
+
+const convertTree = (instance: Instance, styles: Styles) => {
+ for (const rule of instance.cssRules) {
+ if (rule.breakpoint === undefined) {
+ continue;
+ }
+ for (const [property, value] of Object.entries(rule.style)) {
+ styles.push({
+ breakpointId: rule.breakpoint,
+ instanceId: instance.id,
+ property,
+ value,
+ });
+ }
+ }
+ instance.cssRules = [];
+ for (const child of instance.children) {
+ if (child.type === "instance") {
+ convertTree(child, styles);
+ }
+ }
+};
+
+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 cursor: undefined | string = undefined;
+ let hasNext = true;
+
+ while (hasNext) {
+ const chunkSize = 1000;
+ const trees = await prisma.tree.findMany({
+ take: chunkSize,
+ orderBy: {
+ id: "asc",
+ },
+ ...(cursor
+ ? {
+ skip: 1, // Skip the cursor
+ cursor: { id: cursor },
+ }
+ : null),
+ });
+ cursor = trees.at(-1)?.id;
+ hasNext = trees.length === chunkSize;
+
+ for (const tree of trees) {
+ try {
+ const root = JSON.parse(tree.root);
+ const styles: Styles = [];
+ convertTree(root, styles);
+ tree.root = JSON.stringify(root);
+ tree.styles = JSON.stringify(styles);
+ } catch {
+ console.info(`Tree ${tree.id} cannot be converted`);
+ }
+ }
+ await Promise.all(
+ trees.map(({ id, root, styles }) =>
+ prisma.tree.update({ where: { id }, data: { root, styles } })
+ )
+ );
+ }
+ },
+ { timeout: 1000 * 60 * 5 }
+ );
+};
diff --git a/packages/prisma-client/prisma/migrations/20230106000143_tree_styles_data/schema.prisma b/packages/prisma-client/prisma/migrations/20230106000143_tree_styles_data/schema.prisma
new file mode 100644
index 0000000000..9d6d5b7bb3
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230106000143_tree_styles_data/schema.prisma
@@ -0,0 +1,108 @@
+// 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 = ["interactiveTransactions"]
+ 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[]
+}
+
+model Build {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ pages String
+
+ project Project @relation(fields: [projectId], references: [id])
+ projectId String
+
+ isDev Boolean // exctly one is true per project
+ isProd Boolean // at most one is true per project (none if not published)
+
+ breakpoints Breakpoints?
+ designTokens DesignTokens?
+}
+
+model Tree {
+ id String @id @default(uuid())
+ root String
+ presetStyles String @default("[]")
+ styles String @default("[]")
+}
+
+model InstanceProps {
+ id String @id @default(uuid())
+ instanceId String
+ treeId String
+ props String @default("[]")
+}
+
+model Breakpoints {
+ build Build @relation(fields: [buildId], references: [id])
+ buildId String @id
+ values String @default("[]")
+}
+
+model DesignTokens {
+ build Build @relation(fields: [buildId], references: [id])
+ buildId String @id
+ value String @default("[]")
+}
diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prisma
index b0f53c32f9..864d652783 100644
--- a/packages/prisma-client/prisma/schema.prisma
+++ b/packages/prisma-client/prisma/schema.prisma
@@ -80,6 +80,7 @@ model Tree {
id String @id @default(uuid())
root String
presetStyles String @default("[]")
+ styles String @default("[]")
}
model InstanceProps {
diff --git a/packages/project/src/db/tree.ts b/packages/project/src/db/tree.ts
index 65969e2986..a334e25133 100644
--- a/packages/project/src/db/tree.ts
+++ b/packages/project/src/db/tree.ts
@@ -6,6 +6,7 @@ import {
Text,
PresetStyles,
findMissingPresetStyles,
+ Styles,
} from "@webstudio-is/react-sdk";
import { applyPatches, type Patch } from "immer";
import {
@@ -15,7 +16,12 @@ import {
type Tree as DbTree,
} from "@webstudio-is/prisma-client";
import { utils } from "../index";
-import { SharedStyleValue, ImageValue } from "@webstudio-is/css-data";
+import {
+ SharedStyleValue,
+ ImageValue,
+ type CssRule,
+ type StyleProperty,
+} from "@webstudio-is/css-data";
import { z } from "zod";
import DataLoader from "dataloader";
import warnOnce from "warn-once";
@@ -130,10 +136,12 @@ type TreeData = Omit<Tree, "id">;
export const createTree = (): TreeData => {
const root = utils.tree.createInstance({ component: "Body" });
const presetStyles = findMissingPresetStyles([], [root.component]);
+ const styles: Styles = [];
return {
root,
presetStyles,
+ styles,
};
};
@@ -141,13 +149,13 @@ export const create = async (
treeData: TreeData,
client: Prisma.TransactionClient = prisma
): Promise<DbTree> => {
- treeData.root;
const root = InstanceDbIn.parse(treeData.root);
return await client.tree.create({
data: {
root: JSON.stringify(root),
presetStyles: JSON.stringify(treeData.presetStyles),
+ styles: JSON.stringify(treeData.styles),
},
});
};
@@ -156,6 +164,31 @@ export const deleteById = async (treeId: string): Promise<void> => {
await prisma.tree.delete({ where: { id: treeId } });
};
+const addStylesToInstancesMutable = (instance: Instance, styles: Styles) => {
+ const cssRulesMap = new Map<string, CssRule>();
+ for (const style of styles) {
+ if (instance.id !== style.instanceId) {
+ continue;
+ }
+ let rule = cssRulesMap.get(style.breakpointId);
+ if (rule === undefined) {
+ rule = {
+ breakpoint: style.breakpointId,
+ style: {},
+ };
+ cssRulesMap.set(style.breakpointId, rule);
+ }
+ rule.style[style.property] = style.value;
+ }
+ instance.cssRules = Array.from(cssRulesMap.values());
+
+ for (const child of instance.children) {
+ if (child.type === "instance") {
+ addStylesToInstancesMutable(child, styles);
+ }
+ }
+};
+
export const loadById = async (
treeId: string,
client: Prisma.TransactionClient = prisma
@@ -175,11 +208,14 @@ export const loadById = async (
Instance.parse(root);
const presetStyles = PresetStyles.parse(JSON.parse(tree.presetStyles));
+ const styles = Styles.parse(JSON.parse(tree.styles));
+ addStylesToInstancesMutable(root, styles);
return {
...tree,
root,
presetStyles,
+ styles,
};
};
@@ -203,6 +239,32 @@ const collectUsedComponents = (instance: Instance, components: Set<string>) => {
}
};
+const extractStylesFromInstancesMutable = (
+ instance: Instance,
+ styles: Styles
+) => {
+ for (const rule of instance.cssRules) {
+ if (rule.breakpoint === undefined) {
+ continue;
+ }
+ for (const [property, value] of Object.entries(rule.style)) {
+ styles.push({
+ breakpointId: rule.breakpoint,
+ instanceId: instance.id,
+ property: property as StyleProperty,
+ value,
+ });
+ }
+ }
+ instance.cssRules = [];
+
+ for (const child of instance.children) {
+ if (child.type === "instance") {
+ extractStylesFromInstancesMutable(child, styles);
+ }
+ }
+};
+
export const patch = async (
{ treeId }: { treeId: Tree["id"] },
patches: Array<Patch>
@@ -219,13 +281,17 @@ export const patch = async (
Array.from(components)
);
const presetStyles = [...tree.presetStyles, ...missingPresetStyles];
+ const styles: Styles = [];
const root = InstanceDbIn.parse(clientRoot);
+ extractStylesFromInstancesMutable(root, styles);
+
await prisma.tree.update({
data: {
root: JSON.stringify(root),
presetStyles: JSON.stringify(presetStyles),
+ styles: JSON.stringify(styles),
},
where: { id: treeId },
});
diff --git a/packages/react-sdk/src/db/style.ts b/packages/react-sdk/src/db/style.ts
index 5e4e89c332..9af2f3a2aa 100644
--- a/packages/react-sdk/src/db/style.ts
+++ b/packages/react-sdk/src/db/style.ts
@@ -51,3 +51,22 @@ export const findMissingPresetStyles = (
}
return missingPresetStyles;
};
+
+export type StylesItem = {
+ breakpointId: string;
+ instanceId: string;
+ property: StyleProperty;
+ value: StyleValue;
+};
+
+// @todo can't figure out how to make property to be enum
+export const StylesItem = z.object({
+ breakpointId: z.string(),
+ instanceId: z.string(),
+ property: z.string(),
+ value: SharedStyleValue,
+}) as z.ZodType<StylesItem>;
+
+export const Styles = z.array(StylesItem);
+
+export type Styles = z.infer<typeof Styles>;
diff --git a/packages/react-sdk/src/db/types.ts b/packages/react-sdk/src/db/types.ts
index 2a526ac4c6..07ff61721b 100644
--- a/packages/react-sdk/src/db/types.ts
+++ b/packages/react-sdk/src/db/types.ts
@@ -1,12 +1,13 @@
import type { InstanceProps as DbInstanceProps } from "@webstudio-is/prisma-client";
import type { UserProp } from "../user-props";
import type { Instance } from "./instance";
-import type { PresetStyles } from "./style";
+import type { PresetStyles, Styles } from "./style";
export type Tree = {
id: string;
root: Instance;
presetStyles: PresetStyles;
+ styles: Styles;
};
export type Props = {