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.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
Transform styles without zod (#822)
Bogdan Chadkin78196958cdf7
diff --git a/packages/project/package.json b/packages/project/package.jsonindex dea835e59b..26f30b4d9f 100644--- a/packages/project/package.json+++ b/packages/project/package.json@@ -22,7 +22,6 @@"@webstudio-is/prisma-client": "workspace:^","@webstudio-is/react-sdk": "workspace:^","bson-objectid": "^2.0.4",- "dataloader": "^2.1.0","immer": "^9.0.12","nanoid": "^3.2.0","react": "^17.0.2",diff --git a/packages/project/src/db/styles.ts b/packages/project/src/db/styles.tsindex 0e904b03f8..a147e21aac 100644--- a/packages/project/src/db/styles.ts+++ b/packages/project/src/db/styles.ts@@ -1,122 +1,122 @@-import { z } from "zod";import warnOnce from "warn-once";-import DataLoader from "dataloader";import { type Patch, applyPatches } from "immer";-import { type Asset, prisma } from "@webstudio-is/prisma-client";+import { prisma } from "@webstudio-is/prisma-client";+import type { Asset } from "@webstudio-is/asset-uploader";import { formatAsset } from "@webstudio-is/asset-uploader/server";-import {- type StyleProperty,- ImageValue,- SharedStyleValue,-} from "@webstudio-is/css-data";+import { StoredStyles, Styles } from "@webstudio-is/react-sdk";-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)- );+const parseValue = (+ styleValue: StoredStyles[number]["value"],+ assetsMap: Map<string, Asset>+) => {+ if (styleValue.type === "image") {+ 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 [];+ }),+ };}-);--/**- * 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 styleValue;+};- return formatAsset(asset);- }),-});+export const parseStyles = async (stylesString: string) => {+ const storedStyles = StoredStyles.parse(JSON.parse(stylesString));-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 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 StyleValueDbOut = z.union([SharedStyleValue, ImageValueDbOut]);+ // Load all assets+ const assets = await prisma.asset.findMany({+ where: {+ id: {+ in: assetIds,+ },+ },+ });+ const assetsMap = new Map<string, Asset>();+ for (const asset of assets) {+ assetsMap.set(asset.id, formatAsset(asset));+ }-const StylesItemDbOut = z.object({- breakpointId: z.string(),- instanceId: z.string(),- // @todo can't figure out how to make property to be enum- property: z.string() as z.ZodType<StyleProperty>,- value: StyleValueDbOut,-});+ const styles: Styles = storedStyles.map((stylesItem) => {+ return {+ breakpointId: stylesItem.breakpointId,+ instanceId: stylesItem.instanceId,+ property: stylesItem.property,+ value: parseValue(stylesItem.value, assetsMap),+ };+ });-export const StylesDbOut = z.array(StylesItemDbOut);+ return styles;+};/**- * 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 StylesItemDbIn = z.object({- breakpointId: z.string(),- instanceId: z.string(),- // @todo can't figure out how to make property to be enum- property: z.string() as z.ZodType<StyleProperty>,- value: StyleValueDbIn,-});--export const StylesDbIn = z.array(StylesItemDbIn);--const loadStylesByTreeId = async (treeId: string) => {- const tree = await prisma.tree.findUnique({- where: { id: treeId },- });-- if (tree === null) {- return [];+ * prepare value to store in db+ */+const serializeValue = (styleValue: Styles[number]["value"]) => {+ if (styleValue.type === "image") {+ return {+ type: "image" as const,+ value: styleValue.value.map((asset) => ({+ type: asset.type,+ // only asset id is stored in db+ value: asset.value.id,+ })),+ };}+ return styleValue;+};- return StylesDbOut.parse(JSON.parse(tree.styles));+export const serializeStyles = (styles: Styles) => {+ const storedStyles: StoredStyles = styles.map((stylesItem) => {+ return {+ breakpointId: stylesItem.breakpointId,+ instanceId: stylesItem.instanceId,+ property: stylesItem.property,+ value: serializeValue(stylesItem.value),+ };+ });+ return JSON.stringify(storedStyles);};export const patch = async ({ treeId }: { treeId: string },patches: Array<Patch>) => {- const styles = await loadStylesByTreeId(treeId);- const patchedStyles = StylesDbIn.parse(applyPatches(styles, patches));+ const tree = await prisma.tree.findUnique({+ where: { id: treeId },+ });+ if (tree === null) {+ return;+ }+ const styles = await parseStyles(tree.styles);+ const patchedStyles = Styles.parse(applyPatches(styles, patches));await prisma.tree.update({data: {- styles: JSON.stringify(patchedStyles),+ styles: serializeStyles(patchedStyles),},where: { id: treeId },});diff --git a/packages/project/src/db/tree.ts b/packages/project/src/db/tree.tsindex 6b8286b0d0..03196843ad 100644--- a/packages/project/src/db/tree.ts+++ b/packages/project/src/db/tree.ts@@ -17,7 +17,7 @@ import {type Tree as DbTree,} from "@webstudio-is/prisma-client";import { utils } from "../index";-import { StylesDbIn, StylesDbOut } from "./styles";+import { parseStyles, serializeStyles } from "./styles";type TreeData = Omit<Tree, "id">;@@ -69,7 +69,7 @@ export const create = async (instances: JSON.stringify(instances),props: JSON.stringify(treeData.props),presetStyles: JSON.stringify(treeData.presetStyles),- styles: JSON.stringify(await StylesDbIn.parseAsync(treeData.styles)),+ styles: serializeStyles(treeData.styles),},});};@@ -119,9 +119,7 @@ export const loadById = async (const props = Props.parse(JSON.parse(tree.props));const presetStyles = PresetStyles.parse(JSON.parse(tree.presetStyles));- const styles = Styles.parse(- await StylesDbOut.parseAsync(JSON.parse(tree.styles))- );+ const styles = await parseStyles(tree.styles);return {...tree,diff --git a/packages/react-sdk/src/db/style.ts b/packages/react-sdk/src/db/style.tsindex 2b783c09ca..66be63c109 100644--- a/packages/react-sdk/src/db/style.ts+++ b/packages/react-sdk/src/db/style.ts@@ -1,6 +1,10 @@import { z } from "zod";-import type { StyleProperty, StyleValue } from "@webstudio-is/css-data";-import { SharedStyleValue } from "@webstudio-is/css-data";+import {+ type StyleProperty,+ StyleValue,+ SharedStyleValue,+ ImageValue,+} from "@webstudio-is/css-data";import {type ComponentName,getComponentMeta,@@ -48,12 +52,31 @@ export const findMissingPresetStyles = (return missingPresetStyles;};+const StoredImageValue = z.object({+ type: z.literal("image"),+ value: z.array(z.object({ type: z.literal("asset"), value: z.string() })),+});++export const StoredStylesItem = z.object({+ breakpointId: z.string(),+ instanceId: z.string(),+ // @todo can't figure out how to make property to be enum+ property: z.string() as z.ZodType<StyleProperty>,+ value: z.union([StoredImageValue, SharedStyleValue]),+});++export type StoredStylesItem = z.infer<typeof StoredStylesItem>;++export const StoredStyles = z.array(StoredStylesItem);++export type StoredStyles = z.infer<typeof StoredStyles>;+export const StylesItem = z.object({breakpointId: z.string(),instanceId: z.string(),// @todo can't figure out how to make property to be enumproperty: z.string() as z.ZodType<StyleProperty>,- value: SharedStyleValue as z.ZodType<StyleValue>,+ value: z.union([ImageValue, SharedStyleValue]),});export type StylesItem = z.infer<typeof StylesItem>;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d4a336a1ff..f5aea22b6e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -747,7 +747,6 @@ importers:'@webstudio-is/scripts': workspace:^'@webstudio-is/tsconfig': workspace:^bson-objectid: ^2.0.4- dataloader: ^2.1.0immer: ^9.0.12jest: ^29.3.1nanoid: ^3.2.0@@ -766,7 +765,6 @@ importers:'@webstudio-is/prisma-client': link:../prisma-client'@webstudio-is/react-sdk': link:../react-sdkbson-objectid: 2.0.4- dataloader: 2.1.0immer: 9.0.15nanoid: 3.3.4react: 17.0.2@@ -12459,10 +12457,6 @@ packages:resolution: {integrity: sha512-WboRycPNsVw3B3TL559F7kuBUM4d8CgMEvk6xEJlOp7OBPjt6G7z8WMWlD2rOFZLk6OYfFIUGsCOWzcQH9K2og==}engines: {node: '>= 6'}- /dataloader/2.1.0:- resolution: {integrity: sha512-qTcEYLen3r7ojZNgVUaRggOI+KM7jrKxXeSHhogh/TWxYMeONEMqY+hmkobiYQozsGIyg9OYVzO4ZIfoB4I0pQ==}- dev: false-/deasync/0.1.28:resolution: {integrity: sha512-QqLF6inIDwiATrfROIyQtwOQxjZuek13WRYZ7donU5wJPLoP67MnYxA6QtqdvdBy2mMqv5m3UefBVdJjvevOYg==}engines: {node: '>=0.11.0'}