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 image value to resolve url (#1405)
Bogdan Chadkin33fd087ecef3
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.tsxindex de37b71c8d..3f0c7ff4f0 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,7 +16,10 @@ export const ImageControl = ({const setValue = setProperty(property);- const valueAsset = styleValue.type === "image" ? styleValue.value : undefined;+ const valueAsset =+ styleValue.type === "image" && styleValue.value.type === "asset"+ ? styleValue.value+ : undefined;return (<FloatingPaneldiff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsxindex e686907e07..a9318adcd0 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsx@@ -56,7 +56,10 @@ const gradientNames = [export const getLayerName = (layerStyle: StyleInfo) => {const backgroundImageStyle = layerStyle.backgroundImage?.value;- if (backgroundImageStyle?.type === "image") {+ if (+ backgroundImageStyle?.type === "image" &&+ backgroundImageStyle.value.type === "asset"+ ) {return backgroundImageStyle.value.value.name;}@@ -74,7 +77,10 @@ export const getLayerName = (layerStyle: StyleInfo) => {export const LayerThumbnail = (props: { layerStyle: StyleInfo }) => {const backgroundImageStyle = props.layerStyle.backgroundImage?.value;- if (backgroundImageStyle?.type === "image") {+ if (+ backgroundImageStyle?.type === "image" &&+ backgroundImageStyle.value.type === "asset"+ ) {const asset = backgroundImageStyle.value.value;const remoteLocation = asset.location === "REMOTE";diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.tsindex dee904adb2..8018fc093b 100644--- a/apps/builder/app/canvas/shared/styles.ts+++ b/apps/builder/app/canvas/shared/styles.ts@@ -1,6 +1,7 @@import { useEffect } from "react";import { useIsomorphicLayoutEffect } from "react-use";import { useStore } from "@nanostores/react";+import type { Assets } from "@webstudio-is/asset-uploader";import {collapsedAttribute,componentAttribute,@@ -8,13 +9,8 @@ import {getComponentNames,idAttribute,addGlobalRules,+ createImageValueTransformer,} from "@webstudio-is/react-sdk";-import {- assetsStore,- isPreviewModeStore,- selectedInstanceSelectorStore,- useBreakpoints,-} from "~/shared/nano-states";import type { StyleDecl } from "@webstudio-is/project-build";import {validStaticValueTypes,@@ -24,6 +20,12 @@ import {type StyleProperty,type Style,} from "@webstudio-is/css-data";+import {+ assetsStore,+ isPreviewModeStore,+ selectedInstanceSelectorStore,+ useBreakpoints,+} from "~/shared/nano-states";import {createCssEngine,toValue,@@ -187,13 +189,17 @@ const toVarStyleWithFallback = (instanceId: string, style: Style): Style => {const wrappedRulesMap = new Map<string, StyleRule | PlaintextRule>();-const addRule = (id: string, cssRule: CssRule) => {+const addRule = (id: string, cssRule: CssRule, assets: Assets) => {const key = id + cssRule.breakpoint;const selectorText = `[${idAttribute}="${id}"]`;- const rule = cssEngine.addStyleRule(selectorText, {- ...cssRule,- style: toVarStyleWithFallback(id, cssRule.style),- });+ const rule = cssEngine.addStyleRule(+ selectorText,+ {+ ...cssRule,+ style: toVarStyleWithFallback(id, cssRule.style),+ },+ createImageValueTransformer(assets)+ );wrappedRulesMap.set(key, rule);return rule;};@@ -214,6 +220,9 @@ export const useCssRules = ({useIsomorphicLayoutEffect(() => {const stylePerBreakpoint = new Map<string, Style>();+ // expect assets to be up to date by the time styles are changed+ // to avoid all styles rerendering when assets are changed+ const assets = assetsStore.get();for (const item of instanceStyles) {let style = stylePerBreakpoint.get(item.breakpointId);@@ -229,7 +238,7 @@ export const useCssRules = ({const rule = getRule(instanceId, breakpointId);// It's the first time the rule is being usedif (rule === undefined) {- addRule(instanceId, { breakpoint: breakpointId, style });+ addRule(instanceId, { breakpoint: breakpointId, style }, assets);continue;}// It's an update to an existing rule@@ -283,7 +292,8 @@ const usePreviewStyle = () => {let rule = getRule(id, breakpoint.id);if (rule === undefined) {- rule = addRule(id, { breakpoint: breakpoint.id, style: {} });+ const assets = assetsStore.get();+ rule = addRule(id, { breakpoint: breakpoint.id, style: {} }, assets);}for (const update of updates) {diff --git a/packages/css-data/src/schema.ts b/packages/css-data/src/schema.tsindex a5e4324653..c776d1f259 100644--- a/packages/css-data/src/schema.ts+++ b/packages/css-data/src/schema.ts@@ -74,7 +74,12 @@ export type RgbValue = z.infer<typeof RgbValue>;export const ImageValue = z.object({type: z.literal("image"),- value: z.object({ type: z.literal("asset"), value: ImageAsset }),+ value: z.union([+ z.object({ type: z.literal("asset"), value: ImageAsset }),+ // url is not stored in db and only used by css-engine transformValue+ // to prepare image value for rendering+ z.object({ type: z.literal("url"), url: z.string() }),+ ]),// For the builder we want to be able to hide imageshidden: z.boolean().optional(),});diff --git a/packages/css-engine/package.json b/packages/css-engine/package.jsonindex 2c87563884..02eb9923c3 100644--- a/packages/css-engine/package.json+++ b/packages/css-engine/package.json@@ -28,6 +28,7 @@"@types/hyphenate-style-name": "^1.0.0","@types/react": "^17.0.24","@types/react-dom": "^17.0.9",+ "@webstudio-is/asset-uploader": "workspace:^","@webstudio-is/css-data": "workspace:^","@webstudio-is/jest-config": "workspace:^","@webstudio-is/scripts": "workspace:^",diff --git a/packages/css-engine/src/core/css-engine.test.ts b/packages/css-engine/src/core/css-engine.test.tsindex 296c5343b4..bb014638d5 100644--- a/packages/css-engine/src/core/css-engine.test.ts+++ b/packages/css-engine/src/core/css-engine.test.ts@@ -1,5 +1,6 @@import { describe, beforeEach, test, expect } from "@jest/globals";import { CssEngine } from "./css-engine";+import type { Assets, ImageAsset } from "@webstudio-is/asset-uploader";const style0 = {display: { type: "keyword", value: "block" },@@ -349,4 +350,63 @@ describe("CssEngine", () => {}"`);});++ test("render images with injected asset url", () => {+ const assets: Assets = new Map([+ [+ "1234",+ {+ type: "image",+ path: "foo.png",+ id: "1234567890",+ projectId: "",+ format: "",+ size: 1212,+ name: "img",+ description: "",+ location: "REMOTE",+ createdAt: "",+ meta: { width: 1, height: 2 },+ },+ ],+ ]);+ const rule = engine.addStyleRule(+ ".c",+ {+ style: {+ backgroundImage: {+ type: "image",+ value: {+ type: "asset",+ value: {+ id: "1234",+ } as ImageAsset,+ },+ },+ },+ breakpoint: "0",+ },+ (styleValue) => {+ if (styleValue.type === "image" && styleValue.value.type === "asset") {+ const asset = assets.get(styleValue.value.value.id);+ if (asset === undefined) {+ return { type: "keyword", value: "none" };+ }+ return {+ type: "image",+ value: {+ type: "url",+ url: asset.path,+ },+ };+ }+ }+ );+ rule.styleMap.delete("display");+ expect(engine.cssText).toMatchInlineSnapshot(`+ "@media all {+ .c { background-image: url(foo.png) }+ }"+ `);+ });});diff --git a/packages/css-engine/src/core/css-engine.ts b/packages/css-engine/src/core/css-engine.tsindex 671800230d..fbc7eeebe1 100644--- a/packages/css-engine/src/core/css-engine.ts+++ b/packages/css-engine/src/core/css-engine.ts@@ -10,6 +10,7 @@ import {import { compareMedia } from "./compare-media";import { StyleElement } from "./style-element";import { StyleSheet } from "./style-sheet";+import type { TransformValue } from "./to-value";const defaultMediaRuleId = "__default-media-rule__";@@ -36,10 +37,14 @@ export class CssEngine {}return mediaRule;}- addStyleRule(selectorText: string, rule: CssRule) {+ addStyleRule(+ selectorText: string,+ rule: CssRule,+ transformValue?: TransformValue+ ) {const mediaRule = this.addMediaRule(rule.breakpoint || defaultMediaRuleId);this.#isDirty = true;- const styleRule = new StyleRule(selectorText, rule.style);+ const styleRule = new StyleRule(selectorText, rule.style, transformValue);styleRule.onChange = this.#onChangeRule;if (mediaRule === undefined) {// Should be impossible to reach.diff --git a/packages/css-engine/src/core/rules.ts b/packages/css-engine/src/core/rules.tsindex 52831a71ff..edaff32f6d 100644--- a/packages/css-engine/src/core/rules.ts+++ b/packages/css-engine/src/core/rules.ts@@ -1,12 +1,16 @@import type { Style, StyleProperty, StyleValue } from "@webstudio-is/css-data";-import { toValue } from "./to-value";+import { toValue, type TransformValue } from "./to-value";import { toProperty } from "./to-property";class StylePropertyMap {#styleMap: Map<StyleProperty, StyleValue | undefined> = new Map();#isDirty = false;#string = "";+ #transformValue?: TransformValue;onChange?: () => void;+ constructor(transformValue?: TransformValue) {+ this.#transformValue = transformValue;+ }set(property: StyleProperty, value?: StyleValue) {this.#styleMap.set(property, value);this.#isDirty = true;@@ -37,7 +41,9 @@ class StylePropertyMap {if (value === undefined) {continue;}- block.push(`${toProperty(property)}: ${toValue(value)}`);+ block.push(+ `${toProperty(property)}: ${toValue(value, this.#transformValue)}`+ );}this.#string = block.join("; ");this.#isDirty = false;@@ -49,8 +55,12 @@ export class StyleRule {styleMap;selectorText;onChange?: () => void;- constructor(selectorText: string, style: Style) {- this.styleMap = new StylePropertyMap();+ constructor(+ selectorText: string,+ style: Style,+ transformValue?: TransformValue+ ) {+ this.styleMap = new StylePropertyMap(transformValue);this.selectorText = selectorText;let property: StyleProperty;for (property in style) {diff --git a/packages/css-engine/src/core/to-value.test.ts b/packages/css-engine/src/core/to-value.test.tsindex 0765390f8e..82bcf24290 100644--- a/packages/css-engine/src/core/to-value.test.ts+++ b/packages/css-engine/src/core/to-value.test.ts@@ -1,4 +1,5 @@import { describe, test, expect } from "@jest/globals";+import type { Assets } from "@webstudio-is/asset-uploader";import { toValue } from "./to-value";describe("Convert WS CSS Values to native CSS strings", () => {@@ -73,39 +74,79 @@ describe("Convert WS CSS Values to native CSS strings", () => {});test("array", () => {- const value = toValue({- type: "layers",- value: [- {- type: "keyword",- value: "auto",- },- { type: "unit", value: 10, unit: "px" },- { type: "unparsed", value: "calc(10px)" },+ const assets: Assets = new Map([+ [+ "1234567890",{type: "image",- value: {- type: "asset",+ path: "foo.png",++ id: "1234567890",+ projectId: "",+ format: "",+ size: 1212,+ name: "img",+ description: "",+ location: "REMOTE",+ createdAt: "",+ meta: { width: 1, height: 2 },+ },+ ],+ ]);++ 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: "image",- path: "foo.png",+ 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 },+ id: "1234567890",+ projectId: "",+ format: "",+ size: 1212,+ name: "img",+ description: "",+ location: "REMOTE",+ createdAt: "",+ meta: { width: 1, height: 2 },+ },},},- },- ],- });+ ],+ },+ (styleValue) => {+ if (styleValue.type === "image" && styleValue.value.type === "asset") {+ const asset = assets.get(styleValue.value.value.id);+ if (asset === undefined) {+ return {+ type: "keyword",+ value: "none",+ };+ }+ return {+ type: "image",+ value: {+ type: "url",+ url: asset.path,+ },+ };+ }+ }+ );- expect(value).toBe("auto,10px,calc(10px),url(foo.png) /* id=1234567890 */");+ expect(value).toBe("auto,10px,calc(10px),url(foo.png)");});test("tuple", () => {diff --git a/packages/css-engine/src/core/to-value.ts b/packages/css-engine/src/core/to-value.tsindex d24d65c2fd..467c4ae4c0 100644--- a/packages/css-engine/src/core/to-value.ts+++ b/packages/css-engine/src/core/to-value.ts@@ -68,7 +68,7 @@ export const toValue = (}if (value.type === "image") {- if (value.hidden) {+ if (value.hidden || value.value.type !== "url") {// We assume that property is background-image and use this to hide background layers// In the future we might want to have a more generic way to hide values// i.e. have knowledge about property-name, as none is property specific@@ -76,7 +76,7 @@ export const toValue = (}// @todo image-set- return `url(${value.value.value.path}) /* id=${value.value.value.id} */`;+ return `url(${value.value.url})`;}if (value.type === "unparsed") {diff --git a/packages/project-build/src/db/styles.ts b/packages/project-build/src/db/styles.tsindex 3c629c38a7..c492a643cc 100644--- a/packages/project-build/src/db/styles.ts+++ b/packages/project-build/src/db/styles.ts@@ -150,6 +150,9 @@ const serializeValue = (styleValue: StyleDecl["value"]): StoredStyleDecl["value"] => {if (styleValue.type === "image") {+ if (styleValue.value.type === "url") {+ return { type: "keyword", value: "none" };+ }const asset = styleValue.value;return {type: "image" as const,@@ -165,6 +168,9 @@ const serializeValue = (type: "layers" as const,value: styleValue.value.map((item) => {if (item.type === "image") {+ if (item.value.type === "url") {+ return { type: "keyword" as const, value: "none" };+ }const asset = item.value;return {type: "image" as const,diff --git a/packages/react-sdk/src/css/css.ts b/packages/react-sdk/src/css/css.tsindex a611376c64..8f9350ac0d 100644--- a/packages/react-sdk/src/css/css.ts+++ b/packages/react-sdk/src/css/css.ts@@ -1,5 +1,5 @@-import { createCssEngine } from "@webstudio-is/css-engine";-import type { Asset } from "@webstudio-is/asset-uploader";+import { createCssEngine, type TransformValue } from "@webstudio-is/css-engine";+import type { Asset, Assets } from "@webstudio-is/asset-uploader";import type { Build } from "@webstudio-is/project-build";import { getComponentNames } from "../components/components-utils";import { getComponentMeta } from "../components";@@ -14,6 +14,24 @@ type Data = {styleSourceSelections?: Build["styleSourceSelections"];};+export const createImageValueTransformer =+ (assets: Assets): TransformValue =>+ (styleValue) => {+ if (styleValue.type === "image" && styleValue.value.type === "asset") {+ const asset = assets.get(styleValue.value.value.id);+ if (asset === undefined) {+ return { type: "keyword", value: "none" };+ }+ return {+ type: "image",+ value: {+ type: "url",+ url: asset.path,+ },+ };+ }+ };+export const generateCssText = (data: Data) => {const assets = new Map<Asset["id"], Asset>(data.assets.map((asset) => [asset.id, asset])@@ -47,10 +65,14 @@ export const generateCssText = (data: Data) => {const styleRules = getStyleRules(styles, styleSourceSelections);for (const { breakpointId, instanceId, style } of styleRules) {- engine.addStyleRule(`[${idAttribute}="${instanceId}"]`, {- breakpoint: breakpointId,- style,- });+ engine.addStyleRule(+ `[${idAttribute}="${instanceId}"]`,+ {+ breakpoint: breakpointId,+ style,+ },+ createImageValueTransformer(assets)+ );}return engine.cssText;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 09043537f2..28a3e30327 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -528,6 +528,9 @@ importers:'@types/react-dom':specifier: ^17.0.9version: 17.0.17+ '@webstudio-is/asset-uploader':+ specifier: workspace:^+ version: link:../asset-uploader'@webstudio-is/css-data':specifier: workspace:^version: link:../css-data