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.

Background image DB support (#701)

Ivan Starkov6150dc05995f
diff --git a/packages/css-data/package.json b/packages/css-data/package.json
index cfee3bbd2b..37c4e44bb6 100644
--- a/packages/css-data/package.json
+++ b/packages/css-data/package.json
@@ -18,6 +18,7 @@
"@types/css-tree": "^2.0.0",
"@webstudio-is/scripts": "workspace:^",
"@webstudio-is/tsconfig": "workspace:^",
+ "@webstudio-is/asset-uploader": "workspace:^",
"camelcase": "^6.3.0",
"css-tree": "^2.3.0",
"mdn-data": "2.0.23",
diff --git a/packages/css-data/src/schema.ts b/packages/css-data/src/schema.ts
index 4573cc0794..03b3298e2b 100644
--- a/packages/css-data/src/schema.ts
+++ b/packages/css-data/src/schema.ts
@@ -1,6 +1,7 @@
import { units } from "./__generated__/units";
import { properties } from "./__generated__/properties";
import { z } from "zod";
+import { ImageAsset } from "@webstudio-is/asset-uploader";
type Properties = typeof properties & {
[custom: CustomProperty]: {
@@ -50,6 +51,13 @@ const RgbValue = z.object({
});
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 })),
+});
+
+export 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({
@@ -69,14 +77,22 @@ export const validStaticValueTypes = [
"keyword",
"fontFamily",
"rgb",
+ "image",
] as const;
-const ValidStaticStyleValue = z.union([
+/**
+ * Shared zod types with DB types.
+ * ImageValue in DB has a different type
+ */
+const SharedStaticStyleValue = z.union([
UnitValue,
KeywordValue,
FontFamilyValue,
RgbValue,
]);
+
+const ValidStaticStyleValue = z.union([ImageValue, SharedStaticStyleValue]);
+
export type ValidStaticStyleValue = z.infer<typeof ValidStaticStyleValue>;
const VarValue = z.object({
@@ -91,8 +107,18 @@ const StyleValue = z.union([
InvalidValue,
UnsetValue,
VarValue,
- RgbValue,
]);
+
+/**
+ * Shared types with DB types
+ */
+export const SharedStyleValue = z.union([
+ SharedStaticStyleValue,
+ InvalidValue,
+ UnsetValue,
+ VarValue,
+]);
+
export type StyleValue = z.infer<typeof StyleValue>;
const Style = z.record(z.string(), StyleValue);
diff --git a/packages/css-engine/src/core/to-value.ts b/packages/css-engine/src/core/to-value.ts
index 8300efee39..30e2b254ad 100644
--- a/packages/css-engine/src/core/to-value.ts
+++ b/packages/css-engine/src/core/to-value.ts
@@ -61,6 +61,16 @@ export const toValue = (
return `rgba(${value.r}, ${value.g}, ${value.b}, ${value.alpha})`;
}
+ if (value.type === "image") {
+ // @todo image-set
+ return value.value
+ .map(
+ (imageAsset) =>
+ `url(${imageAsset.value.path}) /* id=${imageAsset.value.id} */`
+ )
+ .join(", ");
+ }
+
// Will give ts error in case of missing type
assertUnreachable(value, `Unknown value type`);
diff --git a/packages/project/package.json b/packages/project/package.json
index afe629d4e2..34c83fc38a 100644
--- a/packages/project/package.json
+++ b/packages/project/package.json
@@ -22,6 +22,7 @@
"@webstudio-is/prisma-client": "workspace:^",
"@webstudio-is/react-sdk": "workspace:^",
"bson-objectid": "^2.0.2",
+ "dataloader": "^2.1.0",
"immer": "^9.0.12",
"nanoid": "^3.2.0",
"react": "^17.0.2",
diff --git a/packages/project/src/db/tree.ts b/packages/project/src/db/tree.ts
index 1aa1ff6eee..3317b88619 100644
--- a/packages/project/src/db/tree.ts
+++ b/packages/project/src/db/tree.ts
@@ -1,12 +1,126 @@
-import { type Tree, Instance } from "@webstudio-is/react-sdk";
+import { formatAsset } from "@webstudio-is/asset-uploader/server";
+import { type Tree, Instance, Text } from "@webstudio-is/react-sdk";
import { applyPatches, type Patch } from "immer";
import {
+ Asset,
prisma,
type Prisma,
type Tree as DbTree,
} from "@webstudio-is/prisma-client";
import { utils } from "../index";
-import type { Breakpoint } from "@webstudio-is/css-data";
+import {
+ type Breakpoint,
+ SharedStyleValue,
+ ImageValue,
+} from "@webstudio-is/css-data";
+import { z } from "zod";
+import DataLoader from "dataloader";
+import warnOnce from "warn-once";
+
+const assetsLoader = new DataLoader<string, Asset | undefined>(
+ async (assetIds) => {
+ const assets = await prisma.asset.findMany({
+ where: {
+ id: {
+ // Spread to remove readonly from assetIds, otherwise ts error.
+ in: [...assetIds],
+ },
+ },
+ });
+
+ /**
+ * Dataloader docs:
+ * The Array of values must be the same length as the Array of keys.
+ * Each index in the Array of values must correspond to the same index in the Array of keys.
+ * (assets returned from DB can have a different order, some could not exist)
+ */
+ return assetIds.map((assetId) =>
+ assets.find((asset) => asset.id === assetId)
+ );
+ }
+);
+
+/**
+ * Use zod + DataLoader to load/format assets from the Assets table.
+ */
+const ImageAssetDbOut = z.object({
+ type: z.literal("asset"),
+ value: z
+ .string()
+ .uuid()
+ .transform(async (assetId) => {
+ const asset = await assetsLoader.load(assetId);
+ if (asset === undefined) {
+ warnOnce(true, `Asset with assetId "${assetId}" not found`);
+ return;
+ }
+
+ return formatAsset(asset);
+ }),
+});
+
+const ImageValueDbOut = z.object({
+ type: z.literal("image"),
+ value: z
+ .array(ImageAssetDbOut)
+ // an Asset can be not present in DB, skip it.
+ .transform((assets) => assets.filter((asset) => asset.value !== undefined)),
+});
+
+const StyleValueDbOut = z.union([SharedStyleValue, ImageValueDbOut]);
+
+const StyleDbOut = z.record(z.string(), StyleValueDbOut);
+
+export const CssRuleDbOut = z.object({
+ style: StyleDbOut,
+ breakpoint: z.optional(z.string()),
+});
+
+/**
+ * validate/transform DB data schema to the client schema.
+ */
+const InstanceDbOut = z.lazy(() =>
+ z.object({
+ type: z.literal("instance"),
+ id: z.string(),
+ component: z.string(),
+ children: z.array(z.union([InstanceDbOut, Text])),
+ cssRules: z.array(CssRuleDbOut),
+ })
+) as z.ZodType<Instance>;
+
+/**
+ * In the DB we hold only assetId
+ **/
+const ImageValueDbIn = ImageValue.transform((imageStyle) => ({
+ type: imageStyle.type,
+ value: imageStyle.value.map((value) =>
+ /* Now value.type is always equal to the "asset", but in the future, it will have additional types */
+ value.type === "asset" ? { type: "asset", value: value.value.id } : value
+ ),
+}));
+
+const StyleValueDbIn = z.union([SharedStyleValue, ImageValueDbIn]);
+
+const StyleDbIn = z.record(z.string(), StyleValueDbIn);
+
+export const CssRuleDbIn = z.object({
+ style: StyleDbIn,
+ breakpoint: z.optional(z.string()),
+});
+
+/**
+ * validate/transform client schema into DB data schema.
+ */
+const InstanceDbIn = z.lazy(() =>
+ z.object({
+ type: z.literal("instance"),
+ id: z.string(),
+ component: z.string(),
+ children: z.array(z.union([InstanceDbIn, Text])),
+ cssRules: z.array(CssRuleDbIn),
+ })
+) as /* Instance is wrong type here, ImageValue is different after transform. We don't use it anyway */ z.ZodType<Instance>;
export const createRootInstance = (breakpoints: Array<Breakpoint>) => {
// Take the smallest breakpoint as default
@@ -19,11 +133,13 @@ export const createRootInstance = (breakpoints: Array<Breakpoint>) => {
};
export const create = async (
- root: Instance,
+ clientRoot: Instance,
client: Prisma.TransactionClient = prisma
): Promise<DbTree> => {
- Instance.parse(root);
+ const root = InstanceDbIn.parse(clientRoot);
+
const rootString = JSON.stringify(root);
+
return await client.tree.create({
data: { root: rootString },
});
@@ -45,8 +161,12 @@ export const loadById = async (
return null;
}
- const root = JSON.parse(tree.root);
+ const dbRoot = JSON.parse(tree.root);
+
+ const root = await InstanceDbOut.parseAsync(dbRoot);
+
Instance.parse(root);
+
return {
...tree,
root,
@@ -72,8 +192,10 @@ export const patch = async (
if (tree === null) {
throw new Error(`Tree ${treeId} not found`);
}
- const root = applyPatches(tree.root, patches);
- Instance.parse(root);
+ const clientRoot = applyPatches(tree.root, patches);
+
+ const root = InstanceDbIn.parse(clientRoot);
+
await prisma.tree.update({
data: { root: JSON.stringify(root) },
where: { id: treeId },
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 25534bf6ea..b63b49d44a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -298,6 +298,7 @@ importers:
packages/css-data:
specifiers:
'@types/css-tree': ^2.0.0
+ '@webstudio-is/asset-uploader': workspace:^
'@webstudio-is/scripts': workspace:^
'@webstudio-is/tsconfig': workspace:^
camelcase: ^6.3.0
@@ -307,6 +308,7 @@ importers:
zod: ^3.19.1
devDependencies:
'@types/css-tree': 2.0.0
+ '@webstudio-is/asset-uploader': link:../asset-uploader
'@webstudio-is/scripts': link:../scripts
'@webstudio-is/tsconfig': link:../tsconfig
camelcase: 6.3.0
@@ -721,6 +723,7 @@ importers:
'@webstudio-is/scripts': workspace:^
'@webstudio-is/tsconfig': workspace:^
bson-objectid: ^2.0.2
+ dataloader: ^2.1.0
immer: ^9.0.12
jest: ^29.3.1
nanoid: ^3.2.0
@@ -739,6 +742,7 @@ importers:
'@webstudio-is/prisma-client': link:../prisma-client
'@webstudio-is/react-sdk': link:../react-sdk
bson-objectid: 2.0.3
+ dataloader: 2.1.0
immer: 9.0.15
nanoid: 3.3.4
react: 17.0.2
@@ -12366,6 +12370,10 @@ packages:
resolution: {integrity: sha512-WboRycPNsVw3B3TL559F7kuBUM4d8CgMEvk6xEJlOp7OBPjt6G7z8WMWlD2rOFZLk6OYfFIUGsCOWzcQH9K2og==}
engines: {node: '>= 6'}
+ /dataloader/2.1.0:
+ resolution: {integrity: sha512-qTcEYLen3r7ojZNgVUaRggOI+KM7jrKxXeSHhogh/TWxYMeONEMqY+hmkobiYQozsGIyg9OYVzO4ZIfoB4I0pQ==}
+ dev: false
+
/deasync/0.1.26:
resolution: {integrity: sha512-YKw0BmJSWxkjtQsbgn6Q9CHSWB7DKMen8vKrgyC006zy0UZ6nWyGidB0IzZgqkVRkOglAeUaFtiRTeLyel72bg==}
engines: {node: '>=0.11.0'}