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.

Make Image value not an Array (#1148)

Ivan Starkova82825bfe862
diff --git a/apps/builder/app/builder/features/style-panel/controls/image/image-control.tsx b/apps/builder/app/builder/features/style-panel/controls/image/image-control.tsx
index 03f7aed6c5..d0338061c9 100644
--- a/apps/builder/app/builder/features/style-panel/controls/image/image-control.tsx
+++ b/apps/builder/app/builder/features/style-panel/controls/image/image-control.tsx
@@ -16,10 +16,7 @@ export const ImageControl = ({
const setValue = setProperty(property);
- const valueAssets =
- styleValue.type === "image"
- ? styleValue.value.filter((image) => image.type === "asset")
- : [];
+ const valueAsset = styleValue.type === "image" ? styleValue.value : undefined;
return (
<FloatingPanel
@@ -29,13 +26,13 @@ export const ImageControl = ({
onChange={(asset) => {
setValue({
type: "image",
- value: [{ type: "asset", value: asset }],
+ value: { type: "asset", value: asset },
});
}}
/>
}
>
- <TextField defaultValue={valueAssets?.[0]?.value.name} />
+ <TextField defaultValue={valueAsset?.value.name} />
</FloatingPanel>
);
};
diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx b/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx
index 3fb3fe6ef2..fa65cddaf2 100644
--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx
+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx
@@ -236,7 +236,7 @@ const itemToString = (item: CssValueInputValue | null) => {
return item === null
? ""
: item.type === "keyword"
- ? toPascalCase(item.value)
+ ? toPascalCase(toValue(item))
: item.type === "intermediate" || item.type === "unit"
? String(item.value)
: toValue(item);
diff --git a/apps/builder/app/builder/shared/floating-panel/floating-panel.tsx b/apps/builder/app/builder/shared/floating-panel/floating-panel.tsx
index c15e68a24d..85f2b3dd3c 100644
--- a/apps/builder/app/builder/shared/floating-panel/floating-panel.tsx
+++ b/apps/builder/app/builder/shared/floating-panel/floating-panel.tsx
@@ -59,7 +59,7 @@ type FloatingPanelProps = {
onOpenChange?: (isOpen: boolean) => void;
};
-const contetnStyles = css({ width: theme.spacing[30] });
+const contentStyles = css({ width: theme.spacing[30] });
export const FloatingPanel = ({
title,
@@ -84,7 +84,7 @@ export const FloatingPanel = ({
sideOffset={sideOffset}
side="left"
align="start"
- className={contetnStyles()}
+ className={contentStyles()}
>
{content}
<FloatingPanelPopoverTitle>{title}</FloatingPanelPopoverTitle>
diff --git a/packages/css-data/src/schema.ts b/packages/css-data/src/schema.ts
index def971175c..617a746d78 100644
--- a/packages/css-data/src/schema.ts
+++ b/packages/css-data/src/schema.ts
@@ -19,7 +19,7 @@ export type AppliesTo = Properties[StyleProperty]["appliesTo"];
export type UnitGroup = keyof typeof units;
-type UnitEnum = typeof units[UnitGroup][number];
+type UnitEnum = (typeof units)[UnitGroup][number];
const Unit = z.union([
// expected tuple with at least single element
@@ -70,7 +70,7 @@ export type RgbValue = z.infer<typeof RgbValue>;
export const ImageValue = z.object({
type: z.literal("image"),
- value: z.array(z.object({ type: z.literal("asset"), value: ImageAsset })),
+ value: z.object({ type: z.literal("asset"), value: ImageAsset }),
});
export type ImageValue = z.infer<typeof ImageValue>;
@@ -89,6 +89,14 @@ const UnsetValue = z.object({
});
export type UnsetValue = z.infer<typeof UnsetValue>;
+// To support background layers https://developer.mozilla.org/en-US/docs/Web/CSS/background
+// and similar comma separated css properties
+const ArrayValue = z.object({
+ type: z.literal("layers"),
+ value: z.array(z.union([UnitValue, KeywordValue, UnparsedValue, ImageValue])),
+});
+export type ArrayValue = z.infer<typeof ArrayValue>;
+
export const validStaticValueTypes = [
"unit",
"keyword",
@@ -96,6 +104,7 @@ export const validStaticValueTypes = [
"rgb",
"image",
"unparsed",
+ "array",
] as const;
/**
@@ -108,6 +117,7 @@ const SharedStaticStyleValue = z.union([
FontFamilyValue,
RgbValue,
UnparsedValue,
+ ArrayValue,
]);
const ValidStaticStyleValue = z.union([ImageValue, SharedStaticStyleValue]);
diff --git a/packages/css-engine/src/core/to-value.test.ts b/packages/css-engine/src/core/to-value.test.ts
index 949eb038ed..abe388a906 100644
--- a/packages/css-engine/src/core/to-value.test.ts
+++ b/packages/css-engine/src/core/to-value.test.ts
@@ -64,4 +64,40 @@ describe("Convert WS CSS Values to native CSS strings", () => {
);
expect(value).toBe("Courier New");
});
+
+ test("array", () => {
+ const value = toValue({
+ type: "layers",
+ value: [
+ {
+ type: "keyword",
+ value: "auto",
+ },
+ { type: "unit", value: 10, unit: "px" },
+ { type: "unparsed", value: "calc(10px)" },
+ {
+ type: "image",
+ value: {
+ type: "asset",
+ value: {
+ type: "image",
+ path: "foo.png",
+
+ id: "1234567890",
+ projectId: "",
+ format: "",
+ size: 1212,
+ name: "img",
+ description: "",
+ location: "REMOTE",
+ createdAt: "",
+ meta: { width: 1, height: 2 },
+ },
+ },
+ },
+ ],
+ });
+
+ expect(value).toBe("auto,10px,calc(10px),url(foo.png) /* id=1234567890 */");
+ });
});
diff --git a/packages/css-engine/src/core/to-value.ts b/packages/css-engine/src/core/to-value.ts
index 3cb667b6ab..29566f757c 100644
--- a/packages/css-engine/src/core/to-value.ts
+++ b/packages/css-engine/src/core/to-value.ts
@@ -63,18 +63,17 @@ export const toValue = (
if (value.type === "image") {
// @todo image-set
- return value.value
- .map(
- (imageAsset) =>
- `url(${imageAsset.value.path}) /* id=${imageAsset.value.id} */`
- )
- .join(", ");
+ return `url(${value.value.value.path}) /* id=${value.value.value.id} */`;
}
if (value.type === "unparsed") {
return value.value;
}
+ if (value.type === "layers") {
+ return value.value.map((v) => toValue(v, options)).join(",");
+ }
+
// Will give ts error in case of missing type
assertUnreachable(value, `Unknown value type`);
diff --git a/packages/prisma-client/prisma/migrations/20230228222541_convert-image-style/migration.ts b/packages/prisma-client/prisma/migrations/20230228222541_convert-image-style/migration.ts
new file mode 100644
index 0000000000..f5e3af32e1
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230228222541_convert-image-style/migration.ts
@@ -0,0 +1,215 @@
+import { z } from "zod";
+import { PrismaClient } from "./client";
+
+const Unit = z.string();
+
+type Unit = z.infer<typeof Unit>;
+
+const UnitValue = z.object({
+ type: z.literal("unit"),
+ unit: Unit,
+ value: z.number(),
+});
+
+type UnitValue = z.infer<typeof UnitValue>;
+
+const KeywordValue = z.object({
+ type: z.literal("keyword"),
+ // @todo use exact type
+ value: z.string(),
+});
+type KeywordValue = z.infer<typeof KeywordValue>;
+
+/**
+ * Valid unparsed css value
+ **/
+const UnparsedValue = z.object({
+ type: z.literal("unparsed"),
+ value: z.string(),
+});
+
+const FontFamilyValue = z.object({
+ type: z.literal("fontFamily"),
+ value: z.array(z.string()),
+});
+type FontFamilyValue = z.infer<typeof FontFamilyValue>;
+
+const RgbValue = z.object({
+ type: z.literal("rgb"),
+ r: z.number(),
+ g: z.number(),
+ b: z.number(),
+ alpha: z.number(),
+});
+type RgbValue = z.infer<typeof RgbValue>;
+
+const ImageValue = z.object({
+ type: z.literal("image"),
+ value: z.array(z.object({ type: z.literal("asset"), value: z.unknown() })),
+});
+
+type ImageValue = z.infer<typeof ImageValue>;
+
+// We want to be able to render the invalid value
+// and show it is invalid visually, without saving it to the db
+const InvalidValue = z.object({
+ type: z.literal("invalid"),
+ value: z.string(),
+});
+type InvalidValue = z.infer<typeof InvalidValue>;
+
+const UnsetValue = z.object({
+ type: z.literal("unset"),
+ value: z.literal(""),
+});
+type UnsetValue = z.infer<typeof UnsetValue>;
+
+const ArrayValue = z.object({
+ type: z.literal("array"),
+ value: z.array(z.union([UnitValue, KeywordValue, UnparsedValue, ImageValue])),
+});
+type ArrayValue = z.infer<typeof ArrayValue>;
+
+const validStaticValueTypes = [
+ "unit",
+ "keyword",
+ "fontFamily",
+ "rgb",
+ "image",
+ "unparsed",
+ "array",
+] as const;
+
+/**
+ * Shared zod types with DB types.
+ * ImageValue in DB has a different type
+ */
+const SharedStaticStyleValue = z.union([
+ UnitValue,
+ KeywordValue,
+ FontFamilyValue,
+ RgbValue,
+ UnparsedValue,
+ ArrayValue,
+]);
+
+const ValidStaticStyleValue = z.union([ImageValue, SharedStaticStyleValue]);
+
+type ValidStaticStyleValue = z.infer<typeof ValidStaticStyleValue>;
+
+const VarValue = z.object({
+ type: z.literal("var"),
+ value: z.string(),
+ fallbacks: z.array(ValidStaticStyleValue),
+});
+type VarValue = z.infer<typeof VarValue>;
+
+const StyleValue = z.union([
+ ValidStaticStyleValue,
+ InvalidValue,
+ UnsetValue,
+ VarValue,
+]);
+
+/**
+ * Shared types with DB types
+ */
+const SharedStyleValue = z.union([
+ SharedStaticStyleValue,
+ InvalidValue,
+ UnsetValue,
+ VarValue,
+]);
+
+const StoredImageValue = z.object({
+ type: z.literal("image"),
+ value: z.union([
+ z.object({ type: z.literal("asset"), value: z.string() }),
+ z.array(z.object({ type: z.literal("asset"), value: z.string() })),
+ ]),
+});
+
+const StoredStyleDecl = z.object({
+ styleSourceId: z.string(),
+ breakpointId: z.string(),
+ // @todo can't figure out how to make property to be enum
+ property: z.string(),
+ value: z.union([StoredImageValue, SharedStyleValue]),
+});
+
+type StoredStyleDecl = z.infer<typeof StoredStyleDecl>;
+
+// NOTE ON IMPORTS:
+//
+// We want to be able to run old migrations at any point.
+// For example, when we setting up a fresh database or making a reset.
+//
+// You shouldn't import code that may change later
+// and become incompatible with the migration.
+// It's better to copy it to the migration directory.
+
+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) => {
+ let cursor: undefined | { id: string; projectId: string } = undefined;
+ let hasNext = true;
+ const chunkSize = 1000;
+
+ 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;
+
+ const buildsToUpdate = [];
+
+ for (const build of builds) {
+ let hasConversion = false;
+
+ const styles: StoredStyleDecl[] = JSON.parse(build.styles);
+ for (const style of styles) {
+ if (style.value.type === "image") {
+ const value = style.value.value;
+ if (Array.isArray(value)) {
+ style.value.value = style.value.value[0];
+ hasConversion = true;
+ }
+ }
+ }
+ if (hasConversion) {
+ build.styles = JSON.stringify(styles);
+ buildsToUpdate.push(build as never);
+ }
+ }
+
+ await Promise.all(
+ buildsToUpdate.map(({ id, projectId, styles }) =>
+ prisma.build.update({
+ where: { id_projectId: { id, projectId } },
+ data: { styles },
+ })
+ )
+ );
+ }
+ },
+ { timeout: 1000 * 60 * 8 }
+ );
+};
diff --git a/packages/prisma-client/prisma/migrations/20230228222541_convert-image-style/schema.prisma b/packages/prisma-client/prisma/migrations/20230228222541_convert-image-style/schema.prisma
new file mode 100644
index 0000000000..4506a47076
--- /dev/null
+++ b/packages/prisma-client/prisma/migrations/20230228222541_convert-image-style/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 4b9ba395ea..091d3572ee 100644
--- a/packages/project-build/src/db/styles.ts
+++ b/packages/project-build/src/db/styles.ts
@@ -21,24 +21,32 @@ const parseValue = (
assetsMap: Map<string, Asset>
) => {
if (styleValue.type === "image") {
+ const item = styleValue.value;
+ const asset = assetsMap.get(item.value);
+
+ if (asset === undefined) {
+ warnOnce(true, `Asset with assetId "${item.value}" not found`);
+
+ return {
+ type: "invalid" as const,
+ value: JSON.stringify(styleValue.value),
+ };
+ }
+
+ if (asset.type !== "image") {
+ warnOnce(true, `Asset with assetId "${item.value}" not an image`);
+ return {
+ type: "invalid" as const,
+ value: JSON.stringify(styleValue.value),
+ };
+ }
+
return {
type: "image" as const,
- value: styleValue.value.flatMap((item) => {
- const asset = assetsMap.get(item.value);
- if (asset === undefined) {
- warnOnce(true, `Asset with assetId "${item.value}" not found`);
- return [];
- }
- if (asset.type === "image") {
- return [
- {
- type: "asset" as const,
- value: asset,
- },
- ];
- }
- return [];
- }),
+ value: {
+ type: "asset" as const,
+ value: asset,
+ },
};
}
return styleValue;
@@ -53,10 +61,9 @@ export const parseStyles = async (
const assetIds: string[] = [];
for (const { value: styleValue } of storedStyles) {
if (styleValue.type === "image") {
- for (const item of styleValue.value) {
- if (item.type === "asset") {
- assetIds.push(item.value);
- }
+ const item = styleValue.value;
+ if (item.type === "asset") {
+ assetIds.push(item.value);
}
}
}
@@ -92,13 +99,14 @@ export const parseStyles = async (
*/
const serializeValue = (styleValue: StyleDecl["value"]) => {
if (styleValue.type === "image") {
+ const asset = styleValue.value;
return {
type: "image" as const,
- value: styleValue.value.map((asset) => ({
+ value: {
type: asset.type,
// only asset id is stored in db
value: asset.value.id,
- })),
+ },
};
}
return styleValue;
diff --git a/packages/project-build/src/schema/styles.ts b/packages/project-build/src/schema/styles.ts
index dbd66508ae..6c6d10bc46 100644
--- a/packages/project-build/src/schema/styles.ts
+++ b/packages/project-build/src/schema/styles.ts
@@ -7,7 +7,7 @@ import {
const StoredImageValue = z.object({
type: z.literal("image"),
- value: z.array(z.object({ type: z.literal("asset"), value: z.string() })),
+ value: z.object({ type: z.literal("asset"), value: z.string() }),
});
export const StoredStyleDecl = z.object({