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.

Drop tree id from style sources (#1141)

Bogdan Chadkin33b7b7d9de0c
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsx
index b77a7b9698..af2218f9c9 100644
--- a/apps/builder/app/builder/builder.tsx
+++ b/apps/builder/app/builder/builder.tsx
@@ -31,7 +31,6 @@ import {
useSetAuthPermit,
useSetAuthToken,
useSetIsPreviewMode,
- useSetTreeId,
} from "~/shared/nano-states";
import { useClientSettings } from "./shared/client-settings";
import { Navigator } from "./features/sidebar-left";
@@ -261,7 +260,6 @@ export const Builder = ({
useSetAuthToken(authToken);
useSetAuthPermit(authPermit);
useSetProject(project);
- useSetTreeId(treeId);
useSetPages(pages);
useSetCurrentPageId(pageId);
const [publish, publishRef] = usePublish();
diff --git a/apps/builder/app/builder/features/style-panel/style-source-section.tsx b/apps/builder/app/builder/features/style-panel/style-source-section.tsx
index 22b44074c4..56ceaf4c57 100644
--- a/apps/builder/app/builder/features/style-panel/style-source-section.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-source-section.tsx
@@ -23,7 +23,6 @@ import {
styleSourceSelectionsStore,
styleSourcesStore,
stylesStore,
- treeIdStore,
} from "~/shared/nano-states";
import { removeByMutable } from "~/shared/array-utils";
import { cloneStyles } from "~/shared/tree-utils";
@@ -155,8 +154,7 @@ const duplicateStyleSource = (styleSourceId: StyleSource["id"]) => {
const convertLocalStyleSourceToToken = (styleSourceId: StyleSource["id"]) => {
const selectedInstanceId = selectedInstanceIdStore.get();
- const treeId = treeIdStore.get();
- if (selectedInstanceId === undefined || treeId === undefined) {
+ if (selectedInstanceId === undefined) {
return;
}
const newStyleSource: StyleSource = {
@@ -183,8 +181,7 @@ const convertLocalStyleSourceToToken = (styleSourceId: StyleSource["id"]) => {
const reorderStyleSources = (styleSourceIds: StyleSource["id"][]) => {
const selectedInstanceId = selectedInstanceIdStore.get();
- const treeId = treeIdStore.get();
- if (selectedInstanceId === undefined || treeId === undefined) {
+ if (selectedInstanceId === undefined) {
return;
}
store.createTransaction(
@@ -203,7 +200,6 @@ const reorderStyleSources = (styleSourceIds: StyleSource["id"][]) => {
styleSources.set(styleSourceId, {
type: "local",
id: styleSourceId,
- treeId,
});
}
}
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index 92db151ef5..5381783ad2 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -32,7 +32,6 @@ import {
useSubscribeScrollState,
useIsPreviewMode,
useSetAssets,
- useSetTreeId,
} from "~/shared/nano-states";
import { usePublishScrollState } from "./shared/use-publish-scroll-state";
import { useDragAndDrop } from "./shared/use-drag-drop";
@@ -101,7 +100,6 @@ export const Canvas = ({
throw new Error("Tree is null");
}
const isBuilderReady = useSubscribeBuilderReady();
- useSetTreeId(data.tree.id);
useSetAssets(data.assets);
useSetBreakpoints(data.build.breakpoints);
useSetProps(data.build.props);
diff --git a/apps/builder/app/shared/nano-states/nano-states.ts b/apps/builder/app/shared/nano-states/nano-states.ts
index 89e06ac2cf..a439bc100e 100644
--- a/apps/builder/app/shared/nano-states/nano-states.ts
+++ b/apps/builder/app/shared/nano-states/nano-states.ts
@@ -20,7 +20,6 @@ import type {
StyleSources,
StyleSourceSelection,
StyleSourceSelections,
- Tree,
} from "@webstudio-is/project-build";
import type { Style } from "@webstudio-is/css-data";
import type {
@@ -40,13 +39,6 @@ const useValue = <T>(atom: WritableAtom<T>) => {
return [value, atom.set] as const;
};
-export const treeIdStore = atom<undefined | Tree["id"]>(undefined);
-export const useSetTreeId = (treeId: Tree["id"]) => {
- useSyncInitializeOnce(() => {
- treeIdStore.set(treeId);
- });
-};
-
export const instancesStore = atom<Map<InstancesItem["id"], InstancesItem>>(
new Map()
);
@@ -196,19 +188,14 @@ export const styleSourcesStore = atom<StyleSources>(new Map());
* scoped to current tree or whole project
*/
export const availableStyleSourcesStore = shallowComputed(
- [styleSourcesStore, treeIdStore],
- (styleSources, treeId) => {
- if (treeId === undefined) {
- return [];
- }
+ [styleSourcesStore],
+ (styleSources) => {
const availableStylesSources: StyleSource[] = [];
for (const styleSource of styleSources.values()) {
if (styleSource.type === "local") {
continue;
}
- if (styleSource.treeId === treeId || styleSource.treeId === undefined) {
- availableStylesSources.push(styleSource);
- }
+ availableStylesSources.push(styleSource);
}
return availableStylesSources;
}
@@ -333,13 +320,8 @@ export const selectedInstanceStore = computed(
export const selectedInstanceBrowserStyleStore = atom<undefined | Style>();
export const selectedInstanceStyleSourcesStore = computed(
- [
- styleSourceSelectionsStore,
- styleSourcesStore,
- selectedInstanceIdStore,
- treeIdStore,
- ],
- (styleSourceSelections, styleSources, selectedInstanceId, treeId) => {
+ [styleSourceSelectionsStore, styleSourcesStore, selectedInstanceIdStore],
+ (styleSourceSelections, styleSources, selectedInstanceId) => {
const selectedInstanceStyleSources: StyleSource[] = [];
if (selectedInstanceId === undefined) {
return selectedInstanceStyleSources;
@@ -358,10 +340,9 @@ export const selectedInstanceStyleSourcesStore = computed(
}
// generate style source when selection has not local style sources
// it is synchronized whenever styles are updated
- if (hasLocal === false && treeId !== undefined) {
+ if (hasLocal === false) {
selectedInstanceStyleSources.unshift({
type: "local",
- treeId,
id: nanoid(),
});
}
diff --git a/apps/builder/app/shared/tree-utils.test.ts b/apps/builder/app/shared/tree-utils.test.ts
index 76c97fa68b..57038e3200 100644
--- a/apps/builder/app/shared/tree-utils.test.ts
+++ b/apps/builder/app/shared/tree-utils.test.ts
@@ -62,7 +62,6 @@ const createStyleSource = (
return {
type,
id,
- treeId: "",
};
};
diff --git a/packages/prisma-client/prisma/migrations/20230228132402_drop_style_source_tree_id/migration.ts b/packages/prisma-client/prisma/migrations/20230228132402_drop_style_source_tree_id/migration.ts
new file mode 100644
index 0000000000..4779aa81a2
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230228132402_drop_style_source_tree_id/migration.ts
@@ -0,0 +1,65 @@
+import { PrismaClient } from "./client";
+
+type StyleSource = {
+ type: "local" | "token";
+ id: string;
+ treeId?: string;
+ name?: string;
+};
+
+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 | { id: string; projectId: string } = undefined;
+ let hasNext = true;
+
+ while (hasNext) {
+ const chunkSize = 1000;
+ 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) {
+ try {
+ const styleSources: StyleSource[] = JSON.parse(build.styleSources);
+ for (const styleSource of styleSources) {
+ delete styleSource.treeId;
+ }
+ build.styleSources = JSON.stringify(styleSources);
+ } catch {
+ console.info(`Build ${build.id} cannot be converted`);
+ }
+ }
+
+ await Promise.all(
+ builds.map(({ id, projectId, styleSources }) =>
+ prisma.build.update({
+ where: { id_projectId: { id, projectId } },
+ data: { styleSources },
+ })
+ )
+ );
+ }
+ },
+ { timeout: 1000 * 60 * 5 }
+ );
+};
diff --git a/packages/prisma-client/prisma/migrations/20230228132402_drop_style_source_tree_id/schema.prisma b/packages/prisma-client/prisma/migrations/20230228132402_drop_style_source_tree_id/schema.prisma
new file mode 100644
index 0000000000..4506a47076
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230228132402_drop_style_source_tree_id/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/project-build/src/db/styles.ts b/packages/project-build/src/db/styles.ts
index 6cbd8fb0a2..4b9ba395ea 100644
--- a/packages/project-build/src/db/styles.ts
+++ b/packages/project-build/src/db/styles.ts
@@ -142,7 +142,6 @@ export const patchStyles = async (
return;
}
- // these styles are filtered by treeId
const styles = await parseStyles(build.projectId, build.styles);
const patchedStyles = Styles.parse(applyPatches(styles, patches));
diff --git a/packages/project-build/src/schema/style-sources.ts b/packages/project-build/src/schema/style-sources.ts
index 4752948a02..cfd7537051 100644
--- a/packages/project-build/src/schema/style-sources.ts
+++ b/packages/project-build/src/schema/style-sources.ts
@@ -5,14 +5,12 @@ const StyleSourceId = z.string();
const StyleSourceToken = z.object({
type: z.literal("token"),
id: StyleSourceId,
- treeId: z.string().optional(),
name: z.string(),
});
const StyleSourceLocal = z.object({
type: z.literal("local"),
id: StyleSourceId,
- treeId: z.string(),
});
export const StyleSource = z.union([StyleSourceToken, StyleSourceLocal]);