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
refactor: support css vars in repeated values (#4255)
Bogdan Chadkin666b7e3efb35
diff --git a/apps/builder/app/shared/style-object-model.test.tsx b/apps/builder/app/shared/style-object-model.test.tsxindex 256c2527ab..72fc9f32a5 100644--- a/apps/builder/app/shared/style-object-model.test.tsx+++ b/apps/builder/app/shared/style-object-model.test.tsx@@ -328,7 +328,7 @@ test("support custom properties", () => {const instanceSelector = ["body"];expect(getComputedStyleDecl({ model, instanceSelector, property: "--my-property" })- .usedValue+ .cascadedValue).toEqual({ type: "unparsed", value: "blue" });expect(getComputedStyleDecl({ model, instanceSelector, property: "color" })@@ -336,6 +336,99 @@ test("support custom properties", () => {).toEqual({ type: "unparsed", value: "blue" });});+test("compute single custom property without layers", () => {+ const model = createModel({+ css: `+ bodyLocal {+ --gradient: linear-gradient(#fff, #000), linear-gradient(#000, #fff);+ background-image: var(--gradient);+ }+ `,+ jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ });+ expect(+ getComputedStyleDecl({+ model,+ instanceSelector: ["body"],+ property: "backgroundImage",+ }).computedValue+ ).toEqual({+ type: "unparsed",+ value: "linear-gradient(#fff,#000),linear-gradient(#000,#fff)",+ });+});++test("support custom properties in layers", () => {+ const model = createModel({+ css: `+ bodyLocal {+ --gradient-1: linear-gradient(#fff, #000);+ --gradient-2: linear-gradient(#000, #fff);+ background-image: var(--gradient-1), var(--gradient-2);+ }+ `,+ jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ });+ expect(+ getComputedStyleDecl({+ model,+ instanceSelector: ["body"],+ property: "backgroundImage",+ }).computedValue+ ).toEqual({+ type: "layers",+ value: [+ { type: "unparsed", value: "linear-gradient(#fff,#000)" },+ { type: "unparsed", value: "linear-gradient(#000,#fff)" },+ ],+ });+});++test("parse single custom property without tuples", () => {+ const model = createModel({+ css: `+ bodyLocal {+ --noise: contrast(300%) brightness(100%);+ filter: var(--noise);+ }+ `,+ jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ });+ expect(+ getComputedStyleDecl({+ model,+ instanceSelector: ["body"],+ property: "filter",+ }).computedValue+ ).toEqual({ type: "unparsed", value: "contrast(300%) brightness(100%)" });+});++test("support custom properties in tuples", () => {+ const model = createModel({+ css: `+ bodyLocal {+ --noise-1: contrast(300%);+ --noise-2: brightness(100%);+ filter: var(--noise-1) var(--noise-2);+ }+ `,+ jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ });+ expect(+ getComputedStyleDecl({+ model,+ instanceSelector: ["body"],+ property: "filter",+ }).computedValue+ ).toEqual({+ type: "tuple",+ value: [+ { type: "unparsed", value: "contrast(300%)" },+ { type: "unparsed", value: "brightness(100%)" },+ ],+ });+});+test("use fallback value when custom property does not exist", () => {const model = createModel({css: `diff --git a/apps/builder/app/shared/style-object-model.ts b/apps/builder/app/shared/style-object-model.tsindex afffe282e4..d83d739cb6 100644--- a/apps/builder/app/shared/style-object-model.ts+++ b/apps/builder/app/shared/style-object-model.ts@@ -4,6 +4,8 @@ import type {StyleValue,StyleProperty,VarFallback,+ VarValue,+ UnparsedValue,} from "@webstudio-is/css-engine";import {type Instance,@@ -245,6 +247,31 @@ const invalidPropertyData = {initial: invalidValue,};+const substituteVars = (+ styleValue: StyleValue,+ mapper: (value: VarValue) => StyleValue+): StyleValue => {+ if (styleValue.type === "var") {+ return mapper(styleValue);+ }+ if (styleValue.type === "layers" || styleValue.type === "tuple") {+ const newItems: UnparsedValue[] = [];+ let hasVars = false;+ for (const item of styleValue.value) {+ if (item.type === "var") {+ hasVars = true;+ newItems.push(mapper(item) as UnparsedValue);+ } else {+ newItems.push(item as UnparsedValue);+ }+ }+ if (hasVars) {+ return { ...styleValue, value: newItems };+ }+ }+ return styleValue;+};+export type ComputedStyleDecl = {property: string;source: StyleValueSource;@@ -345,16 +372,17 @@ export const getComputedStyleDecl = ({// https://drafts.csswg.org/css-cascade-5/#computedcomputedValue = specifiedValue;- if (computedValue.type === "var") {- const customProperty = `--${computedValue.value}`;+ let invalid = false;+ computedValue = substituteVars(computedValue, (varValue) => {+ const customProperty = `--${varValue.value}`;// https://www.w3.org/TR/css-variables-1/#cyclesif (usedCustomProperties.has(customProperty)) {- computedValue = invalidValue;- break;+ invalid = true;+ return varValue;}usedCustomProperties.add(customProperty);- const fallback: undefined | VarFallback = computedValue.fallback;+ const fallback: undefined | VarFallback = varValue.fallback;const customPropertyValue = getComputedStyleDecl({model,// resolve custom properties on instance they are defined@@ -363,18 +391,23 @@ export const getComputedStyleDecl = ({property: customProperty,customPropertiesGraph,});- computedValue = customPropertyValue.computedValue;+ let replacement = customPropertyValue.computedValue;// https://www.w3.org/TR/css-variables-1/#invalid-variablesif (- computedValue.type === "guaranteedInvalid" ||- (isCustomProperty === false && computedValue.type === "invalid")+ replacement.type === "guaranteedInvalid" ||+ (isCustomProperty === false && replacement.type === "invalid")) {if (inherited) {- computedValue = fallback ?? inheritedValue;+ replacement = fallback ?? inheritedValue;} else {- computedValue = fallback ?? initialValue;+ replacement = fallback ?? initialValue;}}+ return replacement;+ });+ if (invalid) {+ computedValue = invalidValue;+ break;}}diff --git a/packages/css-data/src/parse-css-value.test.ts b/packages/css-data/src/parse-css-value.test.tsindex 3f06721981..b91b771ec4 100644--- a/packages/css-data/src/parse-css-value.test.ts+++ b/packages/css-data/src/parse-css-value.test.ts@@ -535,6 +535,14 @@ test("support custom properties as unparsed values", () => {type: "unparsed",value: "url(https://my-image.com)",});+ expect(parseCssValue("--my-property", "blue red")).toEqual({+ type: "unparsed",+ value: "blue red",+ });+ expect(parseCssValue("--my-property", "blue, red")).toEqual({+ type: "unparsed",+ value: "blue, red",+ });});test("support custom properties var reference", () => {@@ -549,21 +557,6 @@ test("support custom properties var reference", () => {});});-test("support deeply nested var reference", () => {- expect(parseCssValue("color", "rgb(var(--r), var(--g), var(--b))")).toEqual({- type: "unparsed",- value: "rgb(var(--r), var(--g), var(--b))",- });- expect(parseCssValue("transitionDuration", "var(--time)")).toEqual({- type: "layers",- value: [{ type: "unparsed", value: "var(--time)" }],- });- expect(parseCssValue("filter", "var(--filter)")).toEqual({- type: "tuple",- value: [{ type: "unparsed", value: "var(--filter)" }],- });-});-test("support unit in custom property", () => {expect(parseCssValue("--size", "10")).toEqual({type: "unit",@@ -622,6 +615,52 @@ test("support custom properties var reference in custom property", () => {});});+test("parse single var in repeated value without layers or tuples", () => {+ expect(parseCssValue("backgroundImage", "var(--gradient)")).toEqual({+ type: "var",+ value: "gradient",+ });+ expect(parseCssValue("filter", "var(--noise)")).toEqual({+ type: "var",+ value: "noise",+ });+});++test("parse multiple var in repeated value as layers and tuples", () => {+ expect(+ parseCssValue("backgroundImage", "var(--gradient-1), var(--gradient-2)")+ ).toEqual({+ type: "layers",+ value: [+ { type: "var", value: "gradient-1" },+ { type: "var", value: "gradient-2" },+ ],+ });+ expect(parseCssValue("filter", "var(--noise-1) var(--noise-2)")).toEqual({+ type: "tuple",+ value: [+ { type: "var", value: "noise-1" },+ { type: "var", value: "noise-2" },+ ],+ });+});++test("parse var in box-shadow", () => {+ expect(parseCssValue("boxShadow", "var(--shadow)")).toEqual({+ type: "var",+ value: "shadow",+ });+ expect(+ parseCssValue("boxShadow", "var(--shadow-1), var(--shadow-2)")+ ).toEqual({+ type: "layers",+ value: [+ { type: "var", value: "shadow-1" },+ { type: "var", value: "shadow-2" },+ ],+ });+});+describe("parse shadows", () => {test("parses value and returns invalid when used a invalid boxShadow is passed", () => {expect(parseCssValue("boxShadow", `10px 10px 5px foo`)).toEqual({diff --git a/packages/css-data/src/parse-css-value.ts b/packages/css-data/src/parse-css-value.tsindex e5dc978654..f0e96a9489 100644--- a/packages/css-data/src/parse-css-value.ts+++ b/packages/css-data/src/parse-css-value.ts@@ -165,8 +165,7 @@ const parseColor = (colorString: string): undefined | RgbValue => {const parseLiteral = (node: undefined | null | CssNode,- keywords?: readonly string[],- customProperties: boolean = false+ keywords?: readonly string[]):| undefined| UnitValue@@ -234,9 +233,6 @@ const parseLiteral = (}}if (node.name === "var") {- if (customProperties === false) {- return;- }const [name, _comma, ...fallback] = node.children;const fallbackString = generate({type: "Value",@@ -368,10 +364,35 @@ export const parseCssValue = ();return invalidValue;}+ const nodes = "children" in ast ? (ast.children?.toArray() ?? []) : [ast];++ // support only following types in custom properties+ if (property.startsWith("--")) {+ if (nodes.length === 1) {+ const parsedValue = parseLiteral(nodes[0]);+ if (+ parsedValue?.type === "var" ||+ parsedValue?.type === "unit" ||+ parsedValue?.type === "rgb"+ ) {+ return parsedValue;+ }+ }+ return { type: "unparsed", value: input };+ }++ // parse single var() without wrapping with layers or tuples+ // which can possibly get nested when variables are computed+ if (+ nodes.length === 1 &&+ nodes[0].type === "Function" &&+ nodes[0].name === "var"+ ) {+ return parseLiteral(nodes[0]) ?? invalidValue;+ }// prevent infinite splitting into layers for itemsif (repeatedProps.has(property) && topLevel) {- const nodes = "children" in ast ? (ast.children?.toArray() ?? []) : [ast];let invalid = false;const layersValue: StyleValue = {type: "layers",@@ -406,7 +427,6 @@ export const parseCssValue = (}if (property === "fontFamily") {- const nodes = "children" in ast ? (ast.children?.toArray() ?? []) : [ast];return {type: "fontFamily",value: splitRepeated(nodes).map((nodes) => {@@ -449,22 +469,7 @@ export const parseCssValue = (if (ast.type === "Value" && ast.children.size === 1) {// Try extract units from 1st childrenconst first = ast.children.first;- const matchedValue = parseLiteral(- first,- keywordValues[property as never],- topLevel- );- // parse only references in custom properties- if (property.startsWith("--")) {- if (- matchedValue?.type === "var" ||- matchedValue?.type === "unit" ||- matchedValue?.type === "rgb"- ) {- return matchedValue;- }- return { type: "unparsed", value: input };- }+ const matchedValue = parseLiteral(first, keywordValues[property as never]);if (matchedValue) {return matchedValue;}diff --git a/packages/css-data/src/parse-css.ts b/packages/css-data/src/parse-css.tsindex 1f4fc285cc..292c3b5fef 100644--- a/packages/css-data/src/parse-css.ts+++ b/packages/css-data/src/parse-css.ts@@ -71,7 +71,7 @@ const parseCssValue = (}// @todo https://github.com/webstudio-is/webstudio/issues/3399- if (customProperties === false && value.startsWith("var(")) {+ if (customProperties === false && value.includes("var(")) {final.set(property, { type: "keyword", value: "unset" });continue;}diff --git a/packages/css-engine/src/schema.ts b/packages/css-engine/src/schema.tsindex 47fe0ef29a..89a3b55648 100644--- a/packages/css-engine/src/schema.ts+++ b/packages/css-engine/src/schema.ts@@ -110,6 +110,17 @@ const UnsetValue = z.object({});export type UnsetValue = z.infer<typeof UnsetValue>;+export const VarFallback = z.union([UnparsedValue, KeywordValue]);+export type VarFallback = z.infer<typeof VarFallback>;++const VarValue = z.object({+ type: z.literal("var"),+ value: z.string(),+ fallback: VarFallback.optional(),+ hidden: z.boolean().optional(),+});+export type VarValue = z.infer<typeof VarValue>;+export const TupleValueItem = z.union([UnitValue,KeywordValue,@@ -117,6 +128,7 @@ export const TupleValueItem = z.union([ImageValue,RgbValue,FunctionValue,+ VarValue,]);export type TupleValueItem = z.infer<typeof TupleValueItem>;@@ -137,6 +149,7 @@ const LayerValueItem = z.union([RgbValue,InvalidValue,FunctionValue,+ VarValue,]);export type LayerValueItem = z.infer<typeof LayerValueItem>;@@ -151,17 +164,6 @@ export const LayersValue = z.object({export type LayersValue = z.infer<typeof LayersValue>;-export const VarFallback = z.union([UnparsedValue, KeywordValue]);-export type VarFallback = z.infer<typeof VarFallback>;--const VarValue = z.object({- type: z.literal("var"),- value: z.string(),- fallback: VarFallback.optional(),- hidden: z.boolean().optional(),-});-export type VarValue = z.infer<typeof VarValue>;-export const StyleValue = z.union([ImageValue,LayersValue,