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
feat: Parse color functions with CSS variable alpha channel (#5660)
Oleg Isonen44a5c5f265af
diff --git a/apps/builder/app/builder/features/style-panel/controls/color/color-control.tsx b/apps/builder/app/builder/features/style-panel/controls/color/color-control.tsxindex 32d6b0376f..1f4f28d2cb 100644--- a/apps/builder/app/builder/features/style-panel/controls/color/color-control.tsx+++ b/apps/builder/app/builder/features/style-panel/controls/color/color-control.tsx@@ -10,7 +10,20 @@ import { deleteProperty, setProperty } from "../../shared/use-style-data";export const ColorControl = ({ property }: { property: CssProperty }) => {const computedStyleDecl = useComputedStyleDecl(property);const value = computedStyleDecl.cascadedValue;- const currentColor = computedStyleDecl.usedValue;+ const usedColor = computedStyleDecl.usedValue;+ // When the alpha channel is an unresolved CSS variable (substituteVars couldn't+ // resolve it to a number), use the var's fallback value if available, otherwise+ // fall back to fully opaque so the color picker always receives a number.+ const currentColor =+ usedColor.type === "color" && typeof usedColor.alpha !== "number"+ ? {+ ...usedColor,+ alpha:+ usedColor.alpha.fallback?.type === "unit"+ ? usedColor.alpha.fallback.value+ : 1,+ }+ : usedColor;const setValue = setProperty(property);return (<ColorPickerControldiff --git a/apps/builder/app/shared/style-object-model.test.tsx b/apps/builder/app/shared/style-object-model.test.tsxindex 0603f74000..e7acb83476 100644--- a/apps/builder/app/shared/style-object-model.test.tsx+++ b/apps/builder/app/shared/style-object-model.test.tsx@@ -12,6 +12,7 @@ import {import { $, renderData } from "@webstudio-is/template";import { camelCaseProperty, parseCss } from "@webstudio-is/css-data";import type {+ ColorValue,CssProperty,LayersValue,ShadowValue,@@ -449,6 +450,39 @@ test("compute custom properties in shadows", () => {});});+test("resolve custom property in color alpha channel", () => {+ const model = createModel({+ css: `+ bodyLocal {+ --tw-opacity: 0.5;+ color: #ff0000;+ }+ `,+ jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,+ });+ // Mutate the color value to have a VarValue alpha, simulating parsed+ // Tailwind output like `rgb(28 25 23 / var(--tw-opacity))`+ const colorDecl = model.styles.get("bodyLocal:base:color:")!;+ const colorValue = colorDecl.value as ColorValue;+ colorValue.alpha = {+ type: "var",+ value: "tw-opacity",+ fallback: { type: "unit", unit: "number", value: 1 },+ };+ expect(+ getComputedStyleDecl({+ model,+ instanceSelector: ["body"],+ property: "color",+ }).computedValue+ ).toEqual({+ type: "color",+ colorSpace: "srgb",+ components: [1, 0, 0],+ alpha: 0.5,+ });+});+test("support custom properties in tuples", () => {const model = createModel({css: `diff --git a/apps/builder/app/shared/style-object-model.ts b/apps/builder/app/shared/style-object-model.tsindex d4fc00bff0..5462ab4f8c 100644--- a/apps/builder/app/shared/style-object-model.ts+++ b/apps/builder/app/shared/style-object-model.ts@@ -328,6 +328,16 @@ const substituteVars = (}return styleValue;}+ if (+ styleValue.type === "color" &&+ typeof styleValue.alpha === "object" &&+ styleValue.alpha.type === "var"+ ) {+ const resolved = mapper(styleValue.alpha);+ // Keep as a number when the variable resolves to a numeric unit value+ const alpha = resolved.type === "unit" ? resolved.value : styleValue.alpha;+ return { ...styleValue, alpha };+ }if (styleValue.type === "layers" || styleValue.type === "tuple") {const newItems = styleValue.value.map((item) => {return substituteVars(item, mapper) as UnparsedValue;diff --git a/packages/css-data/src/parse-css-value.test.ts b/packages/css-data/src/parse-css-value.test.tsindex 1afa98bde9..c0a16af641 100644--- a/packages/css-data/src/parse-css-value.test.ts+++ b/packages/css-data/src/parse-css-value.test.ts@@ -162,12 +162,69 @@ describe("Parse CSS value", () => {});});- test("fallback to unparsed type when color has variable inside", () => {+ test("parse rgb color with CSS variable as alpha channel", () => {expect(parseCssValue("color", "rgb(24 24 27 / var(--tw-bg-opacity))")).toEqual({- type: "unparsed",- value: "rgb(24 24 27 / var(--tw-bg-opacity))",+ type: "color",+ colorSpace: "srgb",+ components: [0.0941, 0.0941, 0.1059],+ alpha: {+ type: "var",+ value: "tw-bg-opacity",+ fallback: { type: "unit", unit: "number", value: 1 },+ },+ });+ });++ test("parse color() function with CSS variable as alpha channel", () => {+ expect(+ parseCssValue(+ "background-color",+ "color(display-p3 0.4 0.6 0.3 / var(--tw-bg-opacity))"+ )+ ).toEqual({+ type: "color",+ colorSpace: "p3",+ components: [0.4, 0.6, 0.3],+ alpha: {+ type: "var",+ value: "tw-bg-opacity",+ fallback: { type: "unit", unit: "number", value: 1 },+ },+ });+ });++ test("parse oklch color with CSS variable as alpha channel", () => {+ expect(+ parseCssValue(+ "color",+ "oklch(59.686% 0.1009 29.234 / var(--tw-text-opacity))"+ )+ ).toEqual({+ type: "color",+ colorSpace: "oklch",+ components: [0.5969, 0.1009, 29.234],+ alpha: {+ type: "var",+ value: "tw-text-opacity",+ fallback: { type: "unit", unit: "number", value: 1 },+ },+ });+ });++ test("preserve explicit CSS fallback in var alpha channel", () => {+ expect(+ parseCssValue("color", "rgb(24 24 27 / var(--tw-bg-opacity, 0.5))")+ ).toEqual({+ type: "color",+ colorSpace: "srgb",+ components: [0.0941, 0.0941, 0.1059],+ alpha: {+ type: "var",+ value: "tw-bg-opacity",+ fallback: { type: "unparsed", value: "0.5" },+ },});});});diff --git a/packages/css-data/src/parse-css-value.ts b/packages/css-data/src/parse-css-value.tsindex ad21b337b3..718478b38d 100644--- a/packages/css-data/src/parse-css-value.ts+++ b/packages/css-data/src/parse-css-value.ts@@ -203,6 +203,75 @@ export const parseColor = (colorString: string): undefined | ColorValue => {}};+// Parse a color function node that uses a CSS var() as its alpha channel.+// e.g. rgb(28 25 23 / var(--tw-text-opacity)) or color(display-p3 0.4 0.6 0.3 / var(--tw-bg-opacity))+//+// Neither colorjs nor css-tree's lexer support var() in the alpha slot, so we use+// css-tree's AST to locate the var(), extract the color components by substituting+// "1" for the var node (AST-level, no string replacement), then store the var as alpha.+const parseColorWithVarAlpha = (node: FunctionNode): undefined | ColorValue => {+ // Find the "/" operator followed by a var() function in the css-tree AST+ let foundSlash = false;+ let varNode: FunctionNode | undefined;+ for (const child of node.children) {+ if (child.type === "Operator" && child.value === "/") {+ foundSlash = true;+ } else if (+ foundSlash &&+ child.type === "Function" &&+ child.name === "var"+ ) {+ varNode = child;+ break;+ }+ }++ if (!foundSlash || varNode === undefined) {+ return;+ }++ const alphaVar = parseCssVar(varNode);+ if (alphaVar === undefined) {+ return;+ }++ // Use css-tree to rebuild the function node with "1" substituted for the var()+ // so colorjs can parse the color components. This is AST-based — no fragile+ // string replacement that could match the wrong occurrence.+ const substituteChildren = new List<CssNode>();+ for (const child of node.children) {+ if (child === varNode) {+ substituteChildren.appendData({+ type: "Number",+ loc: null,+ value: "1",+ });+ } else {+ substituteChildren.appendData(child);+ }+ }+ const substituteStr = generate({+ type: "Function",+ loc: null,+ name: node.name,+ children: substituteChildren,+ });++ const color = parseColor(substituteStr);+ if (color === undefined) {+ return;+ }++ // If the var has no CSS-level fallback, use "1" (fully opaque) as the fallback+ // so renderers have a safe value when the variable is unset.+ const alpha: VarValue =+ alphaVar.fallback !== undefined+ ? alphaVar+ : { ...alphaVar, fallback: { type: "unit", unit: "number", value: 1 } };++ return { ...color, alpha };+};+const parseShadow = (nodes: CssNode[],input: string@@ -345,6 +414,12 @@ const parseLiteral = (if (color) {return color;}+ // Try to parse with CSS variable as alpha channel (CSS Color Level 4)+ // e.g. rgb(28 25 23 / var(--tw-text-opacity))+ const colorWithVarAlpha = parseColorWithVarAlpha(node);+ if (colorWithVarAlpha) {+ return colorWithVarAlpha;+ }}if (node.name === "var") {return parseCssVar(node);diff --git a/packages/css-engine/src/core/to-value.test.ts b/packages/css-engine/src/core/to-value.test.tsindex ea69d3ccfb..01b7bb12de 100644--- a/packages/css-engine/src/core/to-value.test.ts+++ b/packages/css-engine/src/core/to-value.test.ts@@ -344,6 +344,26 @@ describe("Convert WS CSS Values to native CSS strings", () => {expect(value).toBe("color(xyz-d65 0.5 0.3 0.2 / 1)");});+ test("color with CSS variable as alpha channel (srgb)", () => {+ const value = toValue({+ type: "color",+ colorSpace: "srgb",+ components: [0.1098, 0.098, 0.0902],+ alpha: { type: "var", value: "tw-text-opacity" },+ });+ expect(value).toBe("rgb(28 25 23 / var(--tw-text-opacity))");+ });++ test("color with CSS variable as alpha channel (p3)", () => {+ const value = toValue({+ type: "color",+ colorSpace: "p3",+ components: [0.4, 0.6, 0.3],+ alpha: { type: "var", value: "tw-bg-opacity" },+ });+ expect(value).toBe("color(p3 0.4 0.6 0.3 / var(--tw-bg-opacity))");+ });+test("color in tuple", () => {const value = toValue({type: "tuple",diff --git a/packages/css-engine/src/core/to-value.ts b/packages/css-engine/src/core/to-value.tsindex d08d1f70f8..faed7e8a9e 100644--- a/packages/css-engine/src/core/to-value.ts+++ b/packages/css-engine/src/core/to-value.ts@@ -89,7 +89,8 @@ export const toValue = (if (value.type === "color") {let [c1, c2, c3] = value.components;- const alpha = value.alpha;+ const alpha =+ typeof value.alpha === "number" ? value.alpha : toValue(value.alpha);// Use specific CSS functions when availableswitch (value.colorSpace) {diff --git a/packages/css-engine/src/schema.ts b/packages/css-engine/src/schema.tsindex fbca75503a..de7e81e46c 100644--- a/packages/css-engine/src/schema.ts+++ b/packages/css-engine/src/schema.ts@@ -64,7 +64,31 @@ const RgbValue = z.object({});export type RgbValue = z.infer<typeof RgbValue>;-export const ColorValue = z.object({+// Explicit type declaration needed to break the ColorValue ↔ VarValue ↔ VarFallback cycle.+// VarValue (defined later) may appear as the alpha channel value.+export type ColorValue = {+ type: "color";+ colorSpace:+ | "srgb"+ | "p3"+ | "srgb-linear"+ | "hsl"+ | "hwb"+ | "lab"+ | "lch"+ | "oklab"+ | "oklch"+ | "a98rgb"+ | "prophoto"+ | "rec2020"+ | "xyz-d65"+ | "xyz-d50";+ components: [number, number, number];+ alpha: number | VarValue;+ hidden?: boolean;+};++export const ColorValue: z.ZodType<ColorValue> = z.object({type: z.literal("color"),// all these color spaces are defined by design tokens specificationcolorSpace: z.union([@@ -84,10 +108,9 @@ export const ColorValue = z.object({z.literal("xyz-d50"),]),components: z.tuple([z.number(), z.number(), z.number()]),- alpha: z.number(),+ alpha: z.union([z.number(), z.lazy(() => VarValue) as z.ZodType<VarValue>]),hidden: z.boolean().optional(),});-export type ColorValue = z.infer<typeof ColorValue>;export type FunctionValue = z.infer<typeof FunctionValue>;