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
fix: CSS shorthand properties not saved when value contains var() (#5688)
Oleg Isonen8de2fd47f6e7
diff --git a/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.tsx b/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.tsxindex 308e903a42..17832752f7 100644--- a/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.tsx@@ -43,7 +43,7 @@ export const Section = () => {onAdd={() => {addRepeatedStyleItem([styleDecl],- parseCssFragment(initialBackdropFilter, ["backdrop-filter"])+ parseCssFragment(initialBackdropFilter, ["backdrop-filter"]).styles);}}>diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-code-editor.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-code-editor.tsxindex 6e0144508c..799fe48120 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-code-editor.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-code-editor.tsx@@ -14,7 +14,7 @@ import {setRepeatedStyleItem,} from "../../shared/repeated-style";import { useComputedStyleDecl } from "../../shared/model";-import { InputErrorsTooltip } from "@webstudio-is/design-system";+import { InputErrorsTooltip, toast } from "@webstudio-is/design-system";type IntermediateValue = {type: "intermediate";@@ -65,10 +65,13 @@ export const BackgroundCodeEditor = ({value,});- const parsed = parseCssFragment(value, [+ const { styles: parsed, errors } = parseCssFragment(value, ["background-image","background",]);+ for (const error of errors) {+ toast.error(error);+ }const newValue = parsed.get("background-image");if (newValue === undefined || newValue?.type === "invalid") {@@ -103,10 +106,13 @@ export const BackgroundCodeEditor = ({return;}- const parsed = parseCssFragment(intermediateValue.value, [- "background-image",- "background",- ]);+ const { styles: parsed, errors } = parseCssFragment(+ intermediateValue.value,+ ["background-image", "background"]+ );+ for (const error of errors) {+ toast.error(error);+ }const backgroundImage = parsed.get("background-image");const backgroundColor = parsed.get("background-color");diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.tsxindex 45deeb2b6d..845cd930ac 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.tsx@@ -36,7 +36,7 @@ export const Section = () => {onAdd={() => {addRepeatedStyleItem(styles,- parseCssFragment("none", ["background-image"])+ parseCssFragment("none", ["background-image"]).styles);}}collapsiblediff --git a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.tsx b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.tsxindex a9e826eb55..85c8e43ddb 100644--- a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.tsx@@ -60,7 +60,7 @@ export const Section = () => {onAdd={() => {addRepeatedStyleItem([styleDecl],- parseCssFragment(initialBoxShadow, ["box-shadow"])+ parseCssFragment(initialBoxShadow, ["box-shadow"]).styles);}}>diff --git a/apps/builder/app/builder/features/style-panel/sections/filter/filter.tsx b/apps/builder/app/builder/features/style-panel/sections/filter/filter.tsxindex cab5f95ece..22c7d56b8a 100644--- a/apps/builder/app/builder/features/style-panel/sections/filter/filter.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/filter/filter.tsx@@ -40,7 +40,7 @@ export const Section = () => {onAdd={() => {addRepeatedStyleItem([styleDecl],- parseCssFragment(initialFilter, ["filter"])+ parseCssFragment(initialFilter, ["filter"]).styles);}}>diff --git a/apps/builder/app/builder/features/style-panel/sections/text-shadows/text-shadows.tsx b/apps/builder/app/builder/features/style-panel/sections/text-shadows/text-shadows.tsxindex 7be1c784aa..880a877f93 100644--- a/apps/builder/app/builder/features/style-panel/sections/text-shadows/text-shadows.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/text-shadows/text-shadows.tsx@@ -54,7 +54,7 @@ export const Section = () => {onAdd={() => {addRepeatedStyleItem([styleDecl],- parseCssFragment(initialTextShadow, ["text-shadow"])+ parseCssFragment(initialTextShadow, ["text-shadow"]).styles);}}>diff --git a/apps/builder/app/builder/features/style-panel/sections/transitions/transition-content.tsx b/apps/builder/app/builder/features/style-panel/sections/transitions/transition-content.tsxindex 9471460c4d..5d9ea0617c 100644--- a/apps/builder/app/builder/features/style-panel/sections/transitions/transition-content.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/transitions/transition-content.tsx@@ -15,6 +15,7 @@ import {Tooltip,Text,Grid,+ toast,} from "@webstudio-is/design-system";import { InfoCircleIcon } from "@webstudio-is/icons";import { propertiesData, propertyDescriptions } from "@webstudio-is/css-data";@@ -84,11 +85,14 @@ export const TransitionContent = ({ index }: { index: number }) => {if (intermediateValue === undefined) {return;}- editRepeatedStyleItem(- styles,- index,- parseCssFragment(intermediateValue.value, ["transition"])+ const { styles: parsed, errors } = parseCssFragment(+ intermediateValue.value,+ ["transition"]);+ for (const error of errors) {+ toast.error(error);+ }+ editRepeatedStyleItem(styles, index, parsed);};const updateIntermediateValue = (params: {diff --git a/apps/builder/app/builder/features/style-panel/sections/transitions/transitions.tsx b/apps/builder/app/builder/features/style-panel/sections/transitions/transitions.tsxindex c4a8acbdeb..6b7f05d735 100644--- a/apps/builder/app/builder/features/style-panel/sections/transitions/transitions.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/transitions/transitions.tsx@@ -125,7 +125,7 @@ export const Section = () => {styles,parseCssFragment("all 200ms ease 0ms normal", ["transition",- ])+ ]).styles);}}/>diff --git a/apps/builder/app/builder/features/style-panel/shared/css-fragment.test.ts b/apps/builder/app/builder/features/style-panel/shared/css-fragment.test.tsindex 2b76a77a04..da4c93c5f1 100644--- a/apps/builder/app/builder/features/style-panel/shared/css-fragment.test.ts+++ b/apps/builder/app/builder/features/style-panel/shared/css-fragment.test.ts@@ -10,13 +10,13 @@ test("parse var()", () => {["background-image", parseCssValue("background-image", "var(--bg)")],]);expect(- parseCssFragment("var(--bg)", ["background-image", "background"])+ parseCssFragment("var(--bg)", ["background-image", "background"]).styles).toEqual(result);expect(parseCssFragment("background-image: var(--bg)", ["background-image","background",- ])+ ]).styles).toEqual(result);});@@ -32,9 +32,9 @@ test("fallback further to valid values", () => {["background-clip", parseCssValue("background-clip", "border-box")],["background-color", parseCssValue("background-color", "#fff")],]);- expect(parseCssFragment("#fff", ["background-image", "background"])).toEqual(- result- );+ expect(+ parseCssFragment("#fff", ["background-image", "background"]).styles+ ).toEqual(result);});test("parse shorthand property", () => {@@ -48,10 +48,10 @@ test("parse shorthand property", () => {["transition-delay", parseCssValue("transition-delay", "0s")],["transition-behavior", parseCssValue("transition-behavior", "normal")],]);- expect(parseCssFragment("opacity 1s", ["transition"])).toEqual(result);- expect(parseCssFragment("transition: opacity 1s", ["transition"])).toEqual(- result- );+ expect(parseCssFragment("opacity 1s", ["transition"]).styles).toEqual(result);+ expect(+ parseCssFragment("transition: opacity 1s", ["transition"]).styles+ ).toEqual(result);});test("parse longhand properties", () => {@@ -62,7 +62,7 @@ test("parse longhand properties", () => {transition-duration: 1s;`,["transition"]- )+ ).styles).toEqual(new Map([["transition-property", parseCssValue("transition-property", "opacity")],@@ -70,3 +70,17 @@ test("parse longhand properties", () => {]));});++test("error from first parse is preserved when fallback path produces no styles", () => {+ // background shorthand with an unresolvable var: the initial parse emits an+ // error and returns no styles. Fallback attempts (background-image: ...) also+ // produce no styles but emit no error of their own. Without the fix the error+ // would be silently discarded.+ const { errors } = parseCssFragment("background: var(--missing)", [+ "background-image",+ "background",+ ]);+ expect(errors).toEqual([+ '"background" was not applied because --missing could not be resolved',+ ]);+});diff --git a/apps/builder/app/builder/features/style-panel/shared/css-fragment.tsx b/apps/builder/app/builder/features/style-panel/shared/css-fragment.tsxindex 895226001a..5714a77d22 100644--- a/apps/builder/app/builder/features/style-panel/shared/css-fragment.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/css-fragment.tsx@@ -17,7 +17,7 @@ import {EditorDialogControl,getCodeEditorCssVars,} from "~/shared/code-editor-base";-import { $availableVariables } from "./model";+import { $availableVariables, $cssVarsMap } from "./model";type ShorthandProperty = (typeof shorthandProperties)[number];@@ -26,20 +26,40 @@ export { getCodeEditorCssVars };export const parseCssFragment = (css: string,fallbacks: (CssProperty | ShorthandProperty)[]-): Map<CssProperty, StyleValue> => {- let parsed = parseCss(`.styles{${css}}`);+): { styles: Map<CssProperty, StyleValue>; errors: string[] } => {+ const cssVars = $cssVarsMap.get();+ const { styles: firstStyles, errors: firstErrors } = parseCss(+ `.styles{${css}}`,+ cssVars+ );+ let parsed = firstStyles;+ let errors = firstErrors;if (parsed.length === 0) {for (const fallbackProperty of fallbacks) {- parsed = parseCss(`.styles{${fallbackProperty}: ${css}}`);- parsed = parsed.filter((styleDecl) => styleDecl.value.type !== "invalid");+ const result = parseCss(`.styles{${fallbackProperty}: ${css}}`, cssVars);+ parsed = result.styles.filter(+ (styleDecl) => styleDecl.value.type !== "invalid"+ );+ // Only use fallback errors when firstErrors is empty: the initial+ // full-declaration parse produces the most relevant diagnostic (e.g.+ // "background was not applied because --x could not be resolved").+ // Fallback attempts with a forced property prefix often produce silent+ // failures with no errors at all, which would otherwise discard the+ // original diagnostic.+ if (errors.length === 0 && result.errors.length > 0) {+ errors = result.errors;+ }if (parsed.length > 0) {break;}}}- return new Map(- parsed.map((styleDecl) => [styleDecl.property, styleDecl.value])- );+ return {+ styles: new Map(+ parsed.map((styleDecl) => [styleDecl.property, styleDecl.value])+ ),+ errors,+ };};const compareVariables = (left: RankingInfo, right: RankingInfo) => {diff --git a/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx b/apps/builder/app/builder/features/style-panel/shared/filter-content.tsxindex 25b1f5eea7..dd7cbb06a4 100644--- a/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx@@ -13,6 +13,7 @@ import {Separator,Select,Grid,+ toast,} from "@webstudio-is/design-system";import { useEffect, useState, type JSX } from "react";import {@@ -152,7 +153,10 @@ export const FilterSectionContent = ({value: string,options: StyleUpdateOptions = { isEphemeral: false }) => {- const parsed = parseCssFragment(value, [property]);+ const { styles: parsed, errors } = parseCssFragment(value, [property]);+ for (const error of errors) {+ toast.error(error);+ }const parsedValue = parsed.get(property);const invalid = parsedValue === undefined || parsedValue.type === "invalid";setIntermediateValue({diff --git a/apps/builder/app/builder/features/style-panel/shared/model.tsx b/apps/builder/app/builder/features/style-panel/shared/model.tsxindex 68e2605ccd..8a7261223c 100644--- a/apps/builder/app/builder/features/style-panel/shared/model.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/model.tsx@@ -6,6 +6,7 @@ import { propertiesData } from "@webstudio-is/css-data";import {compareMedia,hyphenateProperty,+ toValue,toVarFallback,type CssProperty,type StyleValue,@@ -317,6 +318,24 @@ export const $availableVariables = computed(});+/**+ * Resolved CSS custom properties for the currently selected element,+ * keyed by full property name (e.g. "--clr-red" → "#f00").+ * Used to substitute var() references when parsing shorthand CSS input.+ */+export const $cssVarsMap = computed(+ $computedStyleDeclarations,+ (computedStyles): Map<string, string> => {+ const map = new Map<string, string>();+ for (const styleDecl of computedStyles) {+ if (styleDecl.property.startsWith("--")) {+ map.set(styleDecl.property, toValue(styleDecl.computedValue));+ }+ }+ return map;+ }+);+export const $availableUnitVariables = computed($availableVariables,(availableVariables) =>diff --git a/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts b/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.tsindex a6aea87377..95a92e335b 100644--- a/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts+++ b/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts@@ -109,7 +109,7 @@ describe("add repeated item", () => {expect($transitionProperty.get().cascadedValue.type).toEqual("var");addRepeatedStyleItem([$transitionProperty.get()],- parseCssFragment("opacity", ["transition-property"])+ parseCssFragment("opacity", ["transition-property"]).styles);expect(toValue($transitionProperty.get().cascadedValue)).toEqual("var(--my-property), opacity"@@ -122,11 +122,11 @@ describe("add repeated item", () => {);addRepeatedStyleItem([$transitionProperty.get()],- parseCssFragment("opacity", ["transition-property"])+ parseCssFragment("opacity", ["transition-property"]).styles);addRepeatedStyleItem([$transitionProperty.get()],- parseCssFragment("transform", ["transition-property"])+ parseCssFragment("transform", ["transition-property"]).styles);expect(toValue($transitionProperty.get().cascadedValue)).toEqual("opacity, transform"@@ -137,11 +137,11 @@ describe("add repeated item", () => {const $filter = createComputedStyleDeclStore("filter");addRepeatedStyleItem([$filter.get()],- parseCssFragment("blur(5px)", ["filter"])+ parseCssFragment("blur(5px)", ["filter"]).styles);addRepeatedStyleItem([$filter.get()],- parseCssFragment("brightness(0.5)", ["filter"])+ parseCssFragment("brightness(0.5)", ["filter"]).styles);expect(toValue($filter.get().cascadedValue)).toEqual("blur(5px) brightness(0.5)"@@ -152,7 +152,7 @@ describe("add repeated item", () => {const $backgroundColor = createComputedStyleDeclStore("background-color");addRepeatedStyleItem([$backgroundColor.get()],- parseCssFragment("none", ["background"])+ parseCssFragment("none", ["background"]).styles);expect($backgroundColor.get().source.name).toEqual("default");expect(toValue($backgroundColor.get().cascadedValue)).toEqual(@@ -176,7 +176,7 @@ describe("add repeated item", () => {$transitionDuration.get(),$transitionDelay.get(),],- parseCssFragment("width 2s", ["transition"])+ parseCssFragment("width 2s", ["transition"]).styles);expect(toValue($transitionProperty.get().cascadedValue)).toEqual("opacity, transform, width"@@ -195,7 +195,7 @@ describe("edit item in repeated style", () => {editRepeatedStyleItem([$backgroundImage.get()],0,- parseCssFragment("var(--gradient1)", ["background-image"])+ parseCssFragment("var(--gradient1)", ["background-image"]).styles);expect(toValue($backgroundImage.get().cascadedValue)).toEqual("var(--gradient1)"@@ -205,7 +205,7 @@ describe("edit item in repeated style", () => {[$backgroundImage.get()],// use greater index when access computed items2,- parseCssFragment("var(--gradient2)", ["background-image"])+ parseCssFragment("var(--gradient2)", ["background-image"]).styles);expect(toValue($backgroundImage.get().cascadedValue)).toEqual("var(--gradient2)"@@ -219,7 +219,7 @@ describe("edit item in repeated style", () => {editRepeatedStyleItem([$backgroundImage.get()],1,- parseCssFragment("var(--gradient1)", ["background-image"])+ parseCssFragment("var(--gradient1)", ["background-image"]).styles);expect(toValue($backgroundImage.get().cascadedValue)).toEqual("none, var(--gradient1)"@@ -228,7 +228,7 @@ describe("edit item in repeated style", () => {editRepeatedStyleItem([$backgroundImage.get()],1,- parseCssFragment("var(--gradient2)", ["background-image"])+ parseCssFragment("var(--gradient2)", ["background-image"]).styles);expect(toValue($backgroundImage.get().cascadedValue)).toEqual("none, var(--gradient2)"@@ -244,7 +244,7 @@ describe("edit item in repeated style", () => {editRepeatedStyleItem([$transitionProperty.get()],1,- parseCssFragment("width", ["transition-property"])+ parseCssFragment("width", ["transition-property"]).styles);expect(toValue($transitionProperty.get().cascadedValue)).toEqual("opacity, width"@@ -257,7 +257,7 @@ describe("edit item in repeated style", () => {editRepeatedStyleItem([$filter.get()],1,- parseCssFragment("contrast(200%)", ["filter"])+ parseCssFragment("contrast(200%)", ["filter"]).styles);expect(toValue($filter.get().cascadedValue)).toEqual("blur(5px) contrast(200%)"diff --git a/apps/builder/app/builder/features/style-panel/shared/shadow-content.tsx b/apps/builder/app/builder/features/style-panel/shared/shadow-content.tsxindex 9cfbcac5f2..26c71b5ef8 100644--- a/apps/builder/app/builder/features/style-panel/shared/shadow-content.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/shadow-content.tsx@@ -24,6 +24,7 @@ import {ToggleGroup,ToggleGroupButton,Tooltip,+ toast,} from "@webstudio-is/design-system";import {InfoCircleIcon,@@ -179,9 +180,13 @@ export const ShadowContent = ({// https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/drop-shadow#formal_syntax// https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow#formal_syntax// Both share a similar syntax but the property name is different.- const parsed = parseCssFragment(intermediateValue.value, [- parsedShadowProperty,- ]);+ const { styles: parsed, errors } = parseCssFragment(+ intermediateValue.value,+ [parsedShadowProperty]+ );+ for (const error of errors) {+ toast.error(error);+ }const parsedValue = parsed.get(parsedShadowProperty);if (parsedValue?.type === "layers" || parsedValue?.type === "var") {onEditLayer(index, parsedValue, { isEphemeral: false });diff --git a/apps/builder/app/builder/shared/css-editor/add-style-input.tsx b/apps/builder/app/builder/shared/css-editor/add-style-input.tsxindex ce14a9a64c..6d64ad422e 100644--- a/apps/builder/app/builder/shared/css-editor/add-style-input.tsx+++ b/apps/builder/app/builder/shared/css-editor/add-style-input.tsx@@ -34,7 +34,10 @@ import {deleteProperty,setProperty,} from "~/builder/features/style-panel/shared/use-style-data";-import { $availableVariables } from "~/builder/features/style-panel/shared/model";+import {+ $availableVariables,+ $cssVarsMap,+} from "~/builder/features/style-panel/shared/model";import { parseStyleInput } from "./parse-style-input";import { validateCssVariableName } from "~/builder/shared/css-variable-utils";import { toast } from "@webstudio-is/design-system";@@ -122,7 +125,10 @@ const matchOrSuggestToCreate = (search: string, items: Array<SearchItem>) => {matched.length = Math.min(matched.length, 100);if (matched.length === 0) {- const parsedStyleMap = parseStyleInput(search);+ const { styleMap: parsedStyleMap } = parseStyleInput(+ search,+ $cssVarsMap.get()+ );const styleMap = mergeStyles(parsedStyleMap);// When parsedStyles is more than one, user entered a shorthand.diff --git a/apps/builder/app/builder/shared/css-editor/css-editor.tsx b/apps/builder/app/builder/shared/css-editor/css-editor.tsxindex 61d4a6cf8d..1328b3f77a 100644--- a/apps/builder/app/builder/shared/css-editor/css-editor.tsx+++ b/apps/builder/app/builder/shared/css-editor/css-editor.tsx@@ -18,6 +18,7 @@ import {Separator,Text,theme,+ toast,Tooltip,} from "@webstudio-is/design-system";import {@@ -33,7 +34,10 @@ import {} from "@webstudio-is/css-engine";// @todo all style panel stuff needs to be moved to shared and/or decoupled from style panelimport { CssValueInputContainer } from "../../features/style-panel/shared/css-value-input";-import { $availableVariables } from "../../features/style-panel/shared/model";+import {+ $availableVariables,+ $cssVarsMap,+} from "../../features/style-panel/shared/model";import { PropertyInfo } from "../../features/style-panel/property-label";import { ColorPicker } from "@webstudio-is/design-system";import { useClientSupports } from "~/shared/client-supports";@@ -366,7 +370,10 @@ export const CssEditor = ({recentProperties.length > 0 && searchProperties === undefined;const handleInsertStyles = (cssText: string) => {- const styleMap = parseStyleInput(cssText);+ const { styleMap, errors } = parseStyleInput(cssText, $cssVarsMap.get());+ for (const error of errors) {+ toast.error(error);+ }if (styleMap.size === 0) {return new Map();}diff --git a/apps/builder/app/builder/shared/css-editor/parse-style-input.test.ts b/apps/builder/app/builder/shared/css-editor/parse-style-input.test.tsindex abbf4245f7..552d97b734 100644--- a/apps/builder/app/builder/shared/css-editor/parse-style-input.test.ts+++ b/apps/builder/app/builder/shared/css-editor/parse-style-input.test.ts@@ -3,21 +3,21 @@ import { parseStyleInput } from "./parse-style-input";describe("parseStyleInput", () => {test("parses custom property", () => {- const result = parseStyleInput("--custom-color");+ const { styleMap: result } = parseStyleInput("--custom-color", new Map());expect(result).toEqual(new Map([["--custom-color", { type: "unparsed", value: "" }]]));});test("parses longhand property", () => {- const result = parseStyleInput("color");+ const { styleMap: result } = parseStyleInput("color", new Map());expect(result).toEqual(new Map([["color", { type: "keyword", value: "unset" }]]));});test("parses shorthand property", () => {- const result = parseStyleInput("margin");+ const { styleMap: result } = parseStyleInput("margin", new Map());expect(result).toEqual(new Map([["margin-top", { type: "keyword", value: "unset" }],@@ -29,33 +29,36 @@ describe("parseStyleInput", () => {});test("trims whitespace", () => {- const result = parseStyleInput(" color ");+ const { styleMap: result } = parseStyleInput(" color ", new Map());expect(result).toEqual(new Map([["color", { type: "keyword", value: "unset" }]]));});test("handles unparsable regular property", () => {- const result = parseStyleInput("notapro perty");+ const { styleMap: result } = parseStyleInput("notapro perty", new Map());expect(result).toEqual(new Map());});test("converts unknown property to custom property assuming user forgot to add --", () => {- const result = parseStyleInput("notaproperty");+ const { styleMap: result } = parseStyleInput("notaproperty", new Map());expect(result).toEqual(new Map([["--notaproperty", { type: "unparsed", value: "" }]]));});test("parses single property-value pair", () => {- const result = parseStyleInput("color: red");+ const { styleMap: result } = parseStyleInput("color: red", new Map());expect(result).toEqual(new Map([["color", { type: "keyword", value: "red" }]]));});test("parses multiple property-value pairs", () => {- const result = parseStyleInput("color: red; display: block");+ const { styleMap: result } = parseStyleInput(+ "color: red; display: block",+ new Map()+ );expect(result).toEqual(new Map([["color", { type: "keyword", value: "red" }],@@ -65,7 +68,10 @@ describe("parseStyleInput", () => {});test("parses multiple property-value pairs, one is invalid", () => {- const result = parseStyleInput("color: red; somethinginvalid: block");+ const { styleMap: result } = parseStyleInput(+ "color: red; somethinginvalid: block",+ new Map()+ );expect(result).toEqual(new Map([["color", { type: "keyword", value: "red" }],@@ -75,28 +81,37 @@ describe("parseStyleInput", () => {});test("parses custom property with value", () => {- const result = parseStyleInput("--custom-color: red");+ const { styleMap: result } = parseStyleInput(+ "--custom-color: red",+ new Map()+ );expect(result).toEqual(new Map([["--custom-color", { type: "unparsed", value: "red" }]]));});test("handles malformed style block", () => {- const result = parseStyleInput("color: red; invalid;");+ const { styleMap: result } = parseStyleInput(+ "color: red; invalid;",+ new Map()+ );expect(result).toEqual(new Map([["color", { type: "keyword", value: "red" }]]));});test("output property with invalid value", () => {- const result = parseStyleInput("rotate: z 0;");+ const { styleMap: result } = parseStyleInput("rotate: z 0;", new Map());expect(result).toEqual(new Map([["rotate", { type: "invalid", value: "z 0" }]]));});test("preserves -webkit-text-stroke as shorthand property, not as CSS variable", () => {- const result = parseStyleInput("-webkit-text-stroke: 1px red");+ const { styleMap: result } = parseStyleInput(+ "-webkit-text-stroke: 1px red",+ new Map()+ );expect(result).toEqual(new Map([[diff --git a/apps/builder/app/builder/shared/css-editor/parse-style-input.ts b/apps/builder/app/builder/shared/css-editor/parse-style-input.tsindex 816dd681c6..3bd5f0779e 100644--- a/apps/builder/app/builder/shared/css-editor/parse-style-input.ts+++ b/apps/builder/app/builder/shared/css-editor/parse-style-input.ts@@ -41,9 +41,17 @@ const ensureValue = (css: string) => {* - Property and value: color: red* - Multiple properties: color: red; background: blue*/-export const parseStyleInput = (css: string): CssStyleMap => {+export type ParseStyleInputResult = {+ styleMap: CssStyleMap;+ errors: string[];+};++export const parseStyleInput = (+ css: string,+ cssVars: Map<string, string>+): ParseStyleInputResult => {css = ensureValue(css);- const styles = parseCss(`selector{${css}}`);+ const { styles, errors } = parseCss(`selector{${css}}`, cssVars);const styleMap: CssStyleMap = new Map();for (const { property, value } of styles) {if (property.startsWith("--")) {@@ -64,5 +72,5 @@ export const parseStyleInput = (css: string): CssStyleMap => {// @todo This should be returning { type: "guaranteedInvalid" }styleMap.set(property, value);}- return styleMap;+ return { styleMap, errors };};diff --git a/apps/builder/app/shared/copy-paste/plugin-webflow/styles.ts b/apps/builder/app/shared/copy-paste/plugin-webflow/styles.tsindex 798be6d546..dcc82e3996 100644--- a/apps/builder/app/shared/copy-paste/plugin-webflow/styles.ts+++ b/apps/builder/app/shared/copy-paste/plugin-webflow/styles.ts@@ -139,7 +139,8 @@ const toParsedVariants = (variants: UnparsedVariants) => {try {const sanitizedStyles = styles.replaceAll(/@raw<\|([^@]+)\|>/g, "$1");const parsed = processStyles(- parseCss(`.styles${state} {${sanitizedStyles}}`) ?? []+ parseCss(`.styles${state} {${sanitizedStyles}}`, new Map()).styles ??+ []);const allBreakpointStyles = parsedVariants.get(breakpointName) ?? [];allBreakpointStyles.push(...parsed);diff --git a/apps/builder/app/shared/html.ts b/apps/builder/app/shared/html.tsindex 4a1ad11f30..931dcc0678 100644--- a/apps/builder/app/shared/html.ts+++ b/apps/builder/app/shared/html.ts@@ -509,7 +509,8 @@ export const generateFragmentFromHtml = (};styleSources.push(localStyleSource);styleSourceSelections.push({ instanceId, values: [localStyleSource.id] });- for (const { property, value } of parseCss(`.styles{${css}}`)) {+ for (const { property, value } of parseCss(`.styles{${css}}`, new Map())+ .styles) {styles.push({styleSourceId: localStyleSource.id,breakpointId: getBaseBreakpointId(),@@ -530,7 +531,7 @@ export const generateFragmentFromHtml = (const allCssText = styleTexts.join("\n");// Parse all CSS and classify rules- const allDecls = parseCss(allCssText);+ const { styles: allDecls } = parseCss(allCssText, new Map());const { classRules, nestedClassRules } = classifyRules(allDecls);// Track which class names are used by elements — IDs will be assigned later@@ -551,7 +552,7 @@ export const generateFragmentFromHtml = (styleTagActions.push({ type: "skip" });continue;}- const parsedDecls = parseCss(text);+ const { styles: parsedDecls } = parseCss(text, new Map());const {classRules: tagClassRules,nestedClassRules: tagNestedRules,diff --git a/apps/builder/app/shared/style-object-model.test.tsx b/apps/builder/app/shared/style-object-model.test.tsxindex 90e51040ce..f3f2f92e92 100644--- a/apps/builder/app/shared/style-object-model.test.tsx+++ b/apps/builder/app/shared/style-object-model.test.tsx@@ -53,7 +53,7 @@ const createModel = ({matchingStates?: Set<string>;}): StyleObjectModel => {const instanceTags = new Map<Instance["id"], HtmlTags>();- const parsedStyles = parseCss(css);+ const { styles: parsedStyles } = parseCss(css, new Map());const styles: Styles = new Map();for (const { breakpoint, selector, state, property, value } of parsedStyles) {const styleDecl: StyleDecl = {@@ -82,7 +82,7 @@ const createModel = ({}const presetStyles = new Map<string, StyleValue>();for (const [componentName, css] of Object.entries(presets ?? {})) {- const parsedStyles = parseCss(css);+ const { styles: parsedStyles } = parseCss(css, new Map());for (const styleDecl of parsedStyles) {const key = getPresetStyleDeclKey({component: componentName,diff --git a/apps/builder/app/shared/tailwind/preflight-bin.ts b/apps/builder/app/shared/tailwind/preflight-bin.tsindex 94a57bc74b..3a820b508c 100644--- a/apps/builder/app/shared/tailwind/preflight-bin.ts+++ b/apps/builder/app/shared/tailwind/preflight-bin.ts@@ -5,7 +5,7 @@ import { tags } from "@webstudio-is/sdk";const cssFile = new URL("./preflight.css", import.meta.url);const css = await readFile(cssFile, "utf8");-const parsed = parseCss(css);+const { styles: parsed } = parseCss(css, new Map());const result: Record<string, { property: CssProperty; value: StyleValue }[]> ={};for (const { selector, breakpoint, ...styleDecl } of parsed) {diff --git a/apps/builder/app/shared/tailwind/tailwind.ts b/apps/builder/app/shared/tailwind/tailwind.tsindex f2652b92fc..b464e38286 100644--- a/apps/builder/app/shared/tailwind/tailwind.ts+++ b/apps/builder/app/shared/tailwind/tailwind.ts@@ -3,6 +3,7 @@ import { presetLegacyCompat } from "@unocss/preset-legacy-compat";import { presetWind3 } from "@unocss/preset-wind3";import {camelCaseProperty,+ extractCssCustomProperties,parseCss,parseMediaQuery,type ParsedStyleDecl,@@ -239,9 +240,24 @@ const parseTailwindClasses = async (const generated = await generator.generate(classes);// use tailwind prefix instead of unocss oneconst css = generated.css.replaceAll("--un-", "--tw-");+ // Normalize CSS custom property values: when the same var is declared in+ // multiple utility-class rules, replace every occurrence with the value from+ // the LAST declaration (the final cascaded value). This allows per-rule+ // two-pass pre-collection to see the correct final value regardless of which+ // rule a shorthand (e.g. border-color) lives in.+ const finalVars = extractCssCustomProperties(css);+ let normalizedCss = css;+ if (finalVars.size > 0) {+ normalizedCss = css.replace(/--[\w-]+\s*:[^;{}\n]*/g, (match) => {+ const colonIdx = match.indexOf(":");+ const propName = match.slice(0, colonIdx).trim();+ const finalValue = finalVars.get(propName);+ return finalValue !== undefined ? `${propName}: ${finalValue}` : match;+ });+ }let parsedStyles: StyleDecl[] = [];// @todo probably builtin in v4- if (css.includes("border")) {+ if (normalizedCss.includes("border")) {// Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)// [UnoCSS]: allow to override the default border color with css var `--un-default-border-color`const reset = `.styles {@@ -249,9 +265,9 @@ const parseTailwindClasses = async (border-color: var(--tw-default-border-color, #e5e7eb);border-width: 0;}`;- parsedStyles.push(...parseCss(reset));+ parsedStyles.push(...parseCss(reset, new Map()).styles);}- parsedStyles.push(...parseCss(css));+ parsedStyles.push(...parseCss(normalizedCss, new Map()).styles);// skip preflights with ::before, ::after and ::backdropparsedStyles = parsedStyles.filter((styleDecl) => !styleDecl.state?.startsWith("::")diff --git a/packages/css-data/bin/css-to-ws.ts b/packages/css-data/bin/css-to-ws.tsindex 27c4d6a48b..0749247a3a 100755--- a/packages/css-data/bin/css-to-ws.ts+++ b/packages/css-data/bin/css-to-ws.ts@@ -34,13 +34,15 @@ const objectGroupBy = <Item>(list: Item[], by: (item: Item) => string) => {};const css = readFileSync(sourcePath, "utf8");-const parsed = parseCss(css).map(({ property, ...styleDecl }) => ({- selector: styleDecl.selector,- breakpoint: styleDecl.breakpoint,- state: styleDecl.state,- property: camelCaseProperty(property),- value: styleDecl.value,-}));+const parsed = parseCss(css, new Map()).styles.map(+ ({ property, ...styleDecl }) => ({+ selector: styleDecl.selector,+ breakpoint: styleDecl.breakpoint,+ state: styleDecl.state,+ property: camelCaseProperty(property),+ value: styleDecl.value,+ })+);const records = objectGroupBy(parsed, (item) => item.selector);mkdirSync(path.dirname(destinationPath), { recursive: true });const code = `/* eslint-disable */diff --git a/packages/css-data/bin/html.css.ts b/packages/css-data/bin/html.css.tsindex 04b823c45b..47232eff64 100644--- a/packages/css-data/bin/html.css.ts+++ b/packages/css-data/bin/html.css.ts@@ -3,7 +3,7 @@ import type { StyleValue } from "@webstudio-is/css-engine";import { parseCss } from "../src/parse-css";const css = readFileSync("./src/html.css", "utf8");-const parsed = parseCss(css);+const { styles: parsed } = parseCss(css, new Map());const result: [string, StyleValue][] = [];for (const styleDecl of parsed) {result.push([`${styleDecl.selector}:${styleDecl.property}`, styleDecl.value]);diff --git a/packages/css-data/src/parse-css.test.ts b/packages/css-data/src/parse-css.test.tsindex da708e99c2..3fb5aacf69 100644--- a/packages/css-data/src/parse-css.test.ts+++ b/packages/css-data/src/parse-css.test.ts@@ -8,7 +8,9 @@ import {describe("Parse CSS", () => {test("longhand property name with keyword value", () => {- expect(parseCss(`.test { background-color: red }`)).toEqual([+ expect(+ parseCss(`.test { background-color: red }`, new Map()).styles+ ).toEqual([{selector: ".test",property: "background-color",@@ -18,7 +20,7 @@ describe("Parse CSS", () => {});test("one class selector rules", () => {- expect(parseCss(`.test { color: #ff0000 }`)).toEqual([+ expect(parseCss(`.test { color: #ff0000 }`, new Map()).styles).toEqual([{selector: ".test",property: "color",@@ -34,7 +36,7 @@ describe("Parse CSS", () => {// @todo this is wrongtest.skip("parse declaration with missing value", () => {- expect(parseCss(`.test { color:;}`)).toEqual([+ expect(parseCss(`.test { color:;}`, new Map()).styles).toEqual([{selector: ".test",property: "color",@@ -49,7 +51,7 @@ describe("Parse CSS", () => {background: #ff0000 linear-gradient(180deg, #11181C 0%, rgba(17, 24, 28, 0) 36.09%), #EBFFFC;}`;- expect(parseCss(css)).toEqual([+ expect(parseCss(css, new Map()).styles).toEqual([{selector: ".test",property: "background-image",@@ -173,7 +175,7 @@ describe("Parse CSS", () => {background-image: none; background-position: 0px 0px; background-size: auto;}`;- expect(parseCss(css)).toEqual([+ expect(parseCss(css, new Map()).styles).toEqual([{selector: ".test",property: "background-image",@@ -210,7 +212,7 @@ describe("Parse CSS", () => {});test("parse state", () => {- expect(parseCss(`a:hover { color: #ff0000 }`)).toEqual([+ expect(parseCss(`a:hover { color: #ff0000 }`, new Map()).styles).toEqual([{selector: "a",state: ":hover",@@ -226,7 +228,9 @@ describe("Parse CSS", () => {});test("attribute selector", () => {- expect(parseCss(`[class^="a"] { color: #ff0000 }`)).toEqual([+ expect(+ parseCss(`[class^="a"] { color: #ff0000 }`, new Map()).styles+ ).toEqual([{selector: '[class^="a"]',property: "color",@@ -242,7 +246,9 @@ describe("Parse CSS", () => {test("parse first pseudo class as selector", () => {// E.g. :root- expect(parseCss(`:first-pseudo:my-state { color: #ff0000 }`)).toEqual([+ expect(+ parseCss(`:first-pseudo:my-state { color: #ff0000 }`, new Map()).styles+ ).toEqual([{selector: ":first-pseudo",state: ":my-state",@@ -258,7 +264,9 @@ describe("Parse CSS", () => {});test("parse pseudo element", () => {- expect(parseCss(`input::placeholder { color: #ff0000 }`)).toEqual([+ expect(+ parseCss(`input::placeholder { color: #ff0000 }`, new Map()).styles+ ).toEqual([{selector: "input",state: "::placeholder",@@ -274,33 +282,37 @@ describe("Parse CSS", () => {});test("parse multiple selectors, one with state", () => {- expect(parseCss(`a, a:hover { color: #ff0000 }`)).toEqual([- {- selector: "a",- property: "color",- value: {- type: "color",- colorSpace: "hex",- alpha: 1,- components: [1, 0, 0],+ expect(parseCss(`a, a:hover { color: #ff0000 }`, new Map()).styles).toEqual(+ [+ {+ selector: "a",+ property: "color",+ value: {+ type: "color",+ colorSpace: "hex",+ alpha: 1,+ components: [1, 0, 0],+ },},- },- {- selector: "a",- state: ":hover",- property: "color",- value: {- type: "color",- colorSpace: "hex",- alpha: 1,- components: [1, 0, 0],+ {+ selector: "a",+ state: ":hover",+ property: "color",+ value: {+ type: "color",+ colorSpace: "hex",+ alpha: 1,+ components: [1, 0, 0],+ },},- },- ]);+ ]+ );});test("parse multiple selectors, both with state", () => {- expect(parseCss(`a:active, a:hover { color: #ff0000 }`)).toEqual([+ expect(+ parseCss(`a:active, a:hover { color: #ff0000 }`, new Map()).styles+ ).toEqual([{selector: "a",state: ":active",@@ -327,7 +339,9 @@ describe("Parse CSS", () => {});test("parse multiple rules", () => {- expect(parseCss(`a { color: red} a:hover { color: #ff0000 }`)).toEqual([+ expect(+ parseCss(`a { color: red} a:hover { color: #ff0000 }`, new Map()).styles+ ).toEqual([{selector: "a",property: "color",@@ -367,7 +381,7 @@ describe("Parse CSS", () => {line-height: 44px;}`;- expect(parseCss(css)).toEqual([+ expect(parseCss(css, new Map()).styles).toEqual([{selector: "h1",property: "margin-bottom",@@ -397,7 +411,7 @@ describe("Parse CSS", () => {});test("parse shorthand", () => {- expect(parseCss(`a { border: 1px solid red }`)).toEqual([+ expect(parseCss(`a { border: 1px solid red }`, new Map()).styles).toEqual([{selector: "a",property: "border-top-width",@@ -462,7 +476,7 @@ describe("Parse CSS", () => {});test("parse custom property", () => {- expect(parseCss(`a { --my-property: red; }`)).toEqual([+ expect(parseCss(`a { --my-property: red; }`, new Map()).styles).toEqual([{selector: "a",property: "--my-property",@@ -472,7 +486,7 @@ describe("Parse CSS", () => {});test("parse empty custom property", () => {- expect(parseCss(`a { --my-property: ; }`)).toEqual([+ expect(parseCss(`a { --my-property: ; }`, new Map()).styles).toEqual([{selector: "a",property: "--my-property",@@ -489,8 +503,9 @@ describe("Parse CSS", () => {color: var(--color);background-color: var(--color, red);}- `- )+ `,+ new Map()+ ).styles).toEqual([{selector: "a",@@ -510,7 +525,9 @@ describe("Parse CSS", () => {});test("parse empty value as unset", () => {- expect(parseCss(`a { color: ; background-color: red }`)).toEqual([+ expect(+ parseCss(`a { color: ; background-color: red }`, new Map()).styles+ ).toEqual([{selector: "a",property: "color",@@ -525,7 +542,7 @@ describe("Parse CSS", () => {});test("unprefix property that doesn't need a prefix", () => {- expect(parseCss(`a { -webkit-color: red; }`)).toEqual([+ expect(parseCss(`a { -webkit-color: red; }`, new Map()).styles).toEqual([{selector: "a",property: "color",@@ -535,7 +552,9 @@ describe("Parse CSS", () => {});test("keep prefix for property that needs one", () => {- expect(parseCss(`a { -webkit-box-orient: horizontal; }`)).toEqual([+ expect(+ parseCss(`a { -webkit-box-orient: horizontal; }`, new Map()).styles+ ).toEqual([{selector: "a",property: "-webkit-box-orient",@@ -546,7 +565,9 @@ describe("Parse CSS", () => {test("keep prefix for -webkit-text-stroke", () => {// shorthand is kept as-is (not expanded) but prefix is preserved- expect(parseCss(`a { -webkit-text-stroke: 1px black; }`)).toEqual([+ expect(+ parseCss(`a { -webkit-text-stroke: 1px black; }`, new Map()).styles+ ).toEqual([{selector: "a",property: "-webkit-text-stroke",@@ -562,7 +583,7 @@ describe("Parse CSS", () => {});test("parse child combinator", () => {- expect(parseCss(`a > b { color: #ff0000 }`)).toEqual([+ expect(parseCss(`a > b { color: #ff0000 }`, new Map()).styles).toEqual([{selector: "a > b",property: "color",@@ -577,7 +598,7 @@ describe("Parse CSS", () => {});test("parse space combinator", () => {- expect(parseCss(`.a b { color: #ff0000 }`)).toEqual([+ expect(parseCss(`.a b { color: #ff0000 }`, new Map()).styles).toEqual([{selector: ".a b",property: "color",@@ -592,7 +613,7 @@ describe("Parse CSS", () => {});test("parse nested selectors as one token", () => {- expect(parseCss(`a b c.d { color: #ff0000 }`)).toEqual([+ expect(parseCss(`a b c.d { color: #ff0000 }`, new Map()).styles).toEqual([{selector: "a b c.d",property: "color",@@ -609,7 +630,8 @@ describe("Parse CSS", () => {test("parse font-smooth properties", () => {expect(- parseCss(`+ parseCss(+ `a {font-smoothing: auto;}@@ -619,7 +641,9 @@ test("parse font-smooth properties", () => {c {-moz-osx-font-smoothing: auto;}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "a",@@ -641,14 +665,17 @@ test("parse font-smooth properties", () => {test("parse incorrectly unprefixed tap-highlight-color", () => {expect(- parseCss(`+ parseCss(+ `a {-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}b {tap-highlight-color: transparent;}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "a",@@ -670,7 +697,8 @@ test("parse incorrectly unprefixed tap-highlight-color", () => {test("parse top level rules and media all as base query", () => {expect(- parseCss(`+ parseCss(+ `a {color: red;}@@ -679,7 +707,9 @@ test("parse top level rules and media all as base query", () => {width: auto;}}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "a",@@ -696,7 +726,8 @@ test("parse top level rules and media all as base query", () => {test("parse media queries", () => {expect(- parseCss(`+ parseCss(+ `@media ( max-width: 768px ) {a {color: red;@@ -707,7 +738,9 @@ test("parse media queries", () => {color: green;}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: `(max-width:768px)`,@@ -726,7 +759,8 @@ test("parse media queries", () => {test("support only screen media type", () => {expect(- parseCss(`+ parseCss(+ `@media all {a {color: yellow;@@ -747,7 +781,9 @@ test("support only screen media type", () => {color: blue;}}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "a",@@ -771,7 +807,8 @@ test("support only screen media type", () => {test("parse previously unsupported media queries", () => {expect(- parseCss(`+ parseCss(+ `a {color: red;}@@ -795,7 +832,9 @@ test("parse previously unsupported media queries", () => {color: orange;}}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "a",@@ -826,7 +865,8 @@ test("parse previously unsupported media queries", () => {test("parse nested media queries by flattening", () => {expect(- parseCss(`+ parseCss(+ `@media (min-width: 768px) {a {color: green;@@ -837,7 +877,9 @@ test("parse nested media queries by flattening", () => {}}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: "(min-width:768px)",@@ -856,7 +898,8 @@ test("parse nested media queries by flattening", () => {test("ignore unsupported at rules", () => {expect(- parseCss(`+ parseCss(+ `a {color: red;}@@ -865,7 +908,9 @@ test("ignore unsupported at rules", () => {color: green;}}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "a",@@ -877,13 +922,16 @@ test("ignore unsupported at rules", () => {test("parse condition-based media queries", () => {expect(- parseCss(`+ parseCss(+ `@media (prefers-color-scheme: dark) {a {color: white;}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: `(prefers-color-scheme:dark)`,@@ -896,13 +944,16 @@ test("parse condition-based media queries", () => {test("parse hover media feature", () => {expect(- parseCss(`+ parseCss(+ `@media (hover: hover) {a {color: blue;}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: `(hover:hover)`,@@ -915,13 +966,16 @@ test("parse hover media feature", () => {test("parse orientation media feature", () => {expect(- parseCss(`+ parseCss(+ `@media (orientation: portrait) {a {color: green;}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: `(orientation:portrait)`,@@ -934,13 +988,16 @@ test("parse orientation media feature", () => {test("parse prefers-reduced-motion media feature", () => {expect(- parseCss(`+ parseCss(+ `@media (prefers-reduced-motion: reduce) {a {color: red;}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: `(prefers-reduced-motion:reduce)`,@@ -953,13 +1010,16 @@ test("parse prefers-reduced-motion media feature", () => {test("parse combined min-width and max-width media query", () => {expect(- parseCss(`+ parseCss(+ `@media (min-width: 768px) and (max-width: 1024px) {a {color: green;}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: `(min-width:768px) and (max-width:1024px)`,@@ -972,13 +1032,16 @@ test("parse combined min-width and max-width media query", () => {test("parse min-width combined with condition feature", () => {expect(- parseCss(`+ parseCss(+ `@media (min-width: 768px) and (orientation: landscape) {a {color: green;}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: `(min-width:768px) and (orientation:landscape)`,@@ -991,13 +1054,16 @@ test("parse min-width combined with condition feature", () => {test("parse multiple condition features in media query", () => {expect(- parseCss(`+ parseCss(+ `@media (prefers-color-scheme: dark) and (prefers-contrast: more) {a {color: white;}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: `(prefers-color-scheme:dark) and (prefers-contrast:more)`,@@ -1010,7 +1076,8 @@ test("parse multiple condition features in media query", () => {test("parse nested media queries", () => {expect(- parseCss(`+ parseCss(+ `@media (min-width: 768px) {a {color: green;@@ -1021,7 +1088,9 @@ test("parse nested media queries", () => {}}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: "(min-width:768px)",@@ -1040,7 +1109,8 @@ test("parse nested media queries", () => {test("parse nested media with condition inside width", () => {expect(- parseCss(`+ parseCss(+ `@media (min-width: 768px) {a {color: green;@@ -1051,7 +1121,9 @@ test("parse nested media with condition inside width", () => {}}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: "(min-width:768px)",@@ -1070,7 +1142,8 @@ test("parse nested media with condition inside width", () => {test("parse deeply nested media queries", () => {expect(- parseCss(`+ parseCss(+ `@media (min-width: 768px) {@media (orientation: landscape) {@media (hover: hover) {@@ -1080,7 +1153,9 @@ test("parse deeply nested media queries", () => {}}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint:@@ -1094,7 +1169,8 @@ test("parse deeply nested media queries", () => {test("parse condition and base styles together", () => {expect(- parseCss(`+ parseCss(+ `a {color: black;}@@ -1103,7 +1179,9 @@ test("parse condition and base styles together", () => {color: white;}}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "a",@@ -1121,7 +1199,8 @@ test("parse condition and base styles together", () => {test("still ignore non-px units in media queries", () => {expect(- parseCss(`+ parseCss(+ `a {color: red;}@@ -1130,7 +1209,9 @@ test("still ignore non-px units in media queries", () => {color: green;}}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "a",@@ -1142,7 +1223,8 @@ test("still ignore non-px units in media queries", () => {test("still ignore @media print", () => {expect(- parseCss(`+ parseCss(+ `a {color: red;}@@ -1151,7 +1233,9 @@ test("still ignore @media print", () => {color: black;}}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "a",@@ -1163,7 +1247,8 @@ test("still ignore @media print", () => {test("still ignore @supports", () => {expect(- parseCss(`+ parseCss(+ `a {color: red;}@@ -1172,7 +1257,9 @@ test("still ignore @supports", () => {color: green;}}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "a",@@ -1184,11 +1271,14 @@ test("still ignore @supports", () => {test("parse &:pseudo-classes as state", () => {expect(- parseCss(`+ parseCss(+ `&:hover {color: red;}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "",@@ -1201,11 +1291,14 @@ test("parse &:pseudo-classes as state", () => {test("parse &[attribute=selector] as state", () => {expect(- parseCss(`+ parseCss(+ `&[data-state=active] {color: red;}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "",@@ -1219,7 +1312,7 @@ test("parse &[attribute=selector] as state", () => {// ---- Selector types ----test("parse class selector with pseudo-class", () => {- expect(parseCss(`.card:hover { color: red }`)).toEqual([+ expect(parseCss(`.card:hover { color: red }`, new Map()).styles).toEqual([{selector: ".card",state: ":hover",@@ -1230,18 +1323,20 @@ test("parse class selector with pseudo-class", () => {});test("parse class selector with pseudo-element", () => {- expect(parseCss(`.card::before { content: none }`)).toEqual([- {- selector: ".card",- state: "::before",- property: "content",- value: { type: "keyword", value: "none" },- },- ]);+ expect(parseCss(`.card::before { content: none }`, new Map()).styles).toEqual(+ [+ {+ selector: ".card",+ state: "::before",+ property: "content",+ value: { type: "keyword", value: "none" },+ },+ ]+ );});test("parse compound class selector", () => {- expect(parseCss(`.card.active { opacity: 1 }`)).toEqual([+ expect(parseCss(`.card.active { opacity: 1 }`, new Map()).styles).toEqual([{selector: ".card.active",property: "opacity",@@ -1251,7 +1346,9 @@ test("parse compound class selector", () => {});test("parse compound class selector with pseudo-class", () => {- expect(parseCss(`.card.active:hover { opacity: 0.5 }`)).toEqual([+ expect(+ parseCss(`.card.active:hover { opacity: 0.5 }`, new Map()).styles+ ).toEqual([{selector: ".card.active",state: ":hover",@@ -1262,17 +1359,21 @@ test("parse compound class selector with pseudo-class", () => {});test("parse class with attribute selector", () => {- expect(parseCss(`.btn[disabled] { opacity: 0.5 }`)).toEqual([- {- selector: ".btn[disabled]",- property: "opacity",- value: { type: "unit", unit: "number", value: 0.5 },- },- ]);+ expect(parseCss(`.btn[disabled] { opacity: 0.5 }`, new Map()).styles).toEqual(+ [+ {+ selector: ".btn[disabled]",+ property: "opacity",+ value: { type: "unit", unit: "number", value: 0.5 },+ },+ ]+ );});test("parse class + attribute + pseudo-class", () => {- expect(parseCss(`.btn[disabled]:focus { outline: none }`)).toEqual([+ expect(+ parseCss(`.btn[disabled]:focus { outline: none }`, new Map()).styles+ ).toEqual([{selector: ".btn[disabled]",state: ":focus",@@ -1295,7 +1396,7 @@ test("parse class + attribute + pseudo-class", () => {});test("parse ID selector", () => {- expect(parseCss(`#hero { display: flex }`)).toEqual([+ expect(parseCss(`#hero { display: flex }`, new Map()).styles).toEqual([{selector: "#hero",property: "display",@@ -1305,7 +1406,7 @@ test("parse ID selector", () => {});test("parse element + class compound selector", () => {- expect(parseCss(`div.card { display: flex }`)).toEqual([+ expect(parseCss(`div.card { display: flex }`, new Map()).styles).toEqual([{selector: "div.card",property: "display",@@ -1315,7 +1416,7 @@ test("parse element + class compound selector", () => {});test("parse sibling combinator +", () => {- expect(parseCss(`.a + .b { color: red }`)).toEqual([+ expect(parseCss(`.a + .b { color: red }`, new Map()).styles).toEqual([{selector: ".a + .b",property: "color",@@ -1325,7 +1426,7 @@ test("parse sibling combinator +", () => {});test("parse general sibling combinator ~", () => {- expect(parseCss(`.a ~ .b { color: red }`)).toEqual([+ expect(parseCss(`.a ~ .b { color: red }`, new Map()).styles).toEqual([{selector: ".a ~ .b",property: "color",@@ -1335,7 +1436,7 @@ test("parse general sibling combinator ~", () => {});test("parse :root as pseudo-class selector", () => {- expect(parseCss(`:root { --color: blue }`)).toEqual([+ expect(parseCss(`:root { --color: blue }`, new Map()).styles).toEqual([{selector: ":root",property: "--color",@@ -1345,7 +1446,7 @@ test("parse :root as pseudo-class selector", () => {});test("parse universal selector *", () => {- expect(parseCss(`* { box-sizing: border-box }`)).toEqual([+ expect(parseCss(`* { box-sizing: border-box }`, new Map()).styles).toEqual([{selector: "*",property: "box-sizing",@@ -1355,7 +1456,7 @@ test("parse universal selector *", () => {});test("parse &::pseudo-element as state", () => {- expect(parseCss(`&::after { content: none }`)).toEqual([+ expect(parseCss(`&::after { content: none }`, new Map()).styles).toEqual([{selector: "",state: "::after",@@ -1366,7 +1467,7 @@ test("parse &::pseudo-element as state", () => {});test("parse &:functional-pseudo as state", () => {- expect(parseCss(`&:nth-child(2) { color: red }`)).toEqual([+ expect(parseCss(`&:nth-child(2) { color: red }`, new Map()).styles).toEqual([{selector: "",state: ":nth-child",@@ -1379,19 +1480,22 @@ test("parse &:functional-pseudo as state", () => {// ---- Edge cases ----test("parse empty string returns empty array", () => {- expect(parseCss("")).toEqual([]);+ expect(parseCss("", new Map()).styles).toEqual([]);});test("parse malformed CSS returns empty array", () => {- expect(parseCss("{{{{")).toEqual([]);+ expect(parseCss("{{{{", new Map()).styles).toEqual([]);});test("parse CSS with no declarations returns empty array", () => {- expect(parseCss(".card {}")).toEqual([]);+ expect(parseCss(".card {}", new Map()).styles).toEqual([]);});test("parse multiple properties from one rule", () => {- const result = parseCss(`.card { display: flex; color: red; opacity: 1 }`);+ const result = parseCss(+ `.card { display: flex; color: red; opacity: 1 }`,+ new Map()+ ).styles;expect(result).toEqual([{selector: ".card",@@ -1412,7 +1516,7 @@ test("parse multiple properties from one rule", () => {});test("parse comma-separated class selectors", () => {- expect(parseCss(`.a, .b { color: red }`)).toEqual([+ expect(parseCss(`.a, .b { color: red }`, new Map()).styles).toEqual([{selector: ".a",property: "color",@@ -1427,7 +1531,7 @@ test("parse comma-separated class selectors", () => {});test("parse comma-separated mixed selectors (class + element)", () => {- expect(parseCss(`.card, div { display: flex }`)).toEqual([+ expect(parseCss(`.card, div { display: flex }`, new Map()).styles).toEqual([{selector: ".card",property: "display",@@ -1442,7 +1546,9 @@ test("parse comma-separated mixed selectors (class + element)", () => {});test("parse comma-separated selectors with different states", () => {- expect(parseCss(`.a:hover, .b:focus { color: blue }`)).toEqual([+ expect(+ parseCss(`.a:hover, .b:focus { color: blue }`, new Map()).styles+ ).toEqual([{selector: ".a",state: ":hover",@@ -1462,10 +1568,13 @@ test("parse comma-separated selectors with different states", () => {test("ignore @keyframes", () => {expect(- parseCss(`+ parseCss(+ `.card { color: red }@keyframes fade { from { opacity: 1 } to { opacity: 0 } }- `)+ `,+ new Map()+ ).styles).toEqual([{selector: ".card",@@ -1477,10 +1586,13 @@ test("ignore @keyframes", () => {test("ignore @font-face", () => {expect(- parseCss(`+ parseCss(+ `.card { color: red }@font-face { font-family: "Custom"; src: url(font.woff2); }- `)+ `,+ new Map()+ ).styles).toEqual([{selector: ".card",@@ -1492,14 +1604,17 @@ test("ignore @font-face", () => {test("ignore @supports nested inside @media", () => {expect(- parseCss(`+ parseCss(+ `@media (min-width: 768px) {.card { color: green }@supports (display: grid) {.card { display: grid }}}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: "(min-width:768px)",@@ -1514,11 +1629,14 @@ test("ignore @supports nested inside @media", () => {test("parse bare screen media type as base query", () => {expect(- parseCss(`+ parseCss(+ `@media screen {a { color: red }}- `)+ `,+ new Map()+ ).styles).toEqual([{selector: "a",@@ -1530,21 +1648,27 @@ test("parse bare screen media type as base query", () => {test("ignore @media print with min-width", () => {expect(- parseCss(`+ parseCss(+ `@media print and (min-width: 768px) {a { color: black }}- `)+ `,+ new Map()+ ).styles).toEqual([]);});test("parse non-px units in non-width features are allowed", () => {expect(- parseCss(`+ parseCss(+ `@media (min-resolution: 2dppx) {a { color: red }}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: "(min-resolution:2dppx)",@@ -1557,11 +1681,14 @@ test("parse non-px units in non-width features are allowed", () => {test("class selector inside media query preserves both breakpoint and selector", () => {expect(- parseCss(`+ parseCss(+ `@media (min-width: 640px) {.card:hover { color: blue }}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: "(min-width:640px)",@@ -1575,11 +1702,14 @@ test("class selector inside media query preserves both breakpoint and selector",test("compound class inside media query", () => {expect(- parseCss(`+ parseCss(+ `@media (max-width: 768px) {.card.featured { display: block }}- `)+ `,+ new Map()+ ).styles).toEqual([{breakpoint: "(max-width:768px)",@@ -1592,28 +1722,1138 @@ test("compound class inside media query", () => {test("nested media with non-px inner is rejected", () => {expect(- parseCss(`+ parseCss(+ `@media (min-width: 768px) {@media (min-width: 40em) {a { color: red }}}- `)+ `,+ new Map()+ ).styles).toEqual([]);});test("nested media with print inner is rejected", () => {expect(- parseCss(`+ parseCss(+ `@media (min-width: 768px) {@media print {a { color: red }}}- `)+ `,+ new Map()+ ).styles).toEqual([]);});+test("background: single var() resolving to a color in the same rule expands to background-color with the concrete color", () => {+ // --clr-red is in the same rule, so it's substituted before expansion.+ // background-color gets the concrete hex color (not a var ref).+ // The var declaration itself is also stored separately.+ const result = parseCss(+ `+ .my-parent {+ --clr-red: #f00;+ background: var(--clr-red);+ }+ `,+ new Map()+ ).styles;+ const bgColor = result.find(+ (d) => d.selector === ".my-parent" && d.property === "background-color"+ );+ expect(bgColor?.value).toEqual(+ expect.objectContaining({ type: "color", colorSpace: "hex" })+ );+});++test("background: single var() resolving to a non-color expands using resolved value", () => {+ const result = parseCss(+ `+ .my-parent {+ --bg: url("img.png") no-repeat center;+ background: var(--bg);+ }+ `,+ new Map()+ ).styles;+ // Expanded from the resolved value: background-image should be the url+ expect(result).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ property: "background-image" }),+ expect.objectContaining({ property: "background-repeat" }),+ ])+ );+ const image = result.find((d) => d.property === "background-image");+ expect(image?.value).toEqual(+ expect.objectContaining({+ type: "layers",+ value: expect.arrayContaining([+ expect.objectContaining({ type: "image" }),+ ]),+ })+ );+});++test("shorthand: var() in border is substituted and expanded", () => {+ // border expands: border → border-color/width/style → border-{side}-color/width/style+ const result = parseCss(+ `+ .box {+ --clr: blue;+ --w: 2px;+ border: var(--w) solid var(--clr);+ }+ `,+ new Map()+ ).styles;+ expect(result).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ property: "border-top-color",+ value: expect.objectContaining({ type: "keyword", value: "blue" }),+ }),+ expect.objectContaining({+ property: "border-top-width",+ value: expect.objectContaining({ type: "unit", value: 2, unit: "px" }),+ }),+ ])+ );+});++test("shorthand: var() in transition is substituted and expanded", () => {+ const result = parseCss(+ `+ .box {+ --dur: 300ms;+ transition: opacity var(--dur) ease;+ }+ `,+ new Map()+ ).styles;+ expect(result).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ property: "transition-duration" }),+ expect.objectContaining({ property: "transition-property" }),+ ])+ );+ // transition-duration is wrapped in a layers value (supports multiple transitions)+ const duration = result.find((d) => d.property === "transition-duration");+ expect(duration?.value).toEqual(+ expect.objectContaining({+ type: "layers",+ value: expect.arrayContaining([+ expect.objectContaining({ type: "unit", value: 300, unit: "ms" }),+ ]),+ })+ );+});++// ─── Comprehensive var() substitution in shorthands ───────────────────────────++const u = (value: number, unit: string) =>+ expect.objectContaining({ type: "unit", value, unit });+const num = (value: number) => u(value, "number");+const kw = (value: string) =>+ expect.objectContaining({ type: "keyword", value });+const layers = (...items: unknown[]) =>+ expect.objectContaining({+ type: "layers",+ value: expect.arrayContaining(items),+ });+const prop = (property: string, value: unknown) =>+ expect.objectContaining({ property, value });++const decls = (css: string) =>+ parseCss(`.x { ${css} }`, new Map()).styles.filter(+ (d) => d.selector === ".x"+ );++describe("var() substitution — background", () => {+ test("var() for color part alongside other background parts", () => {+ const result = decls(`+ --clr: green;+ background: no-repeat var(--clr);+ `);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("background-color", kw("green")),+ prop("background-repeat", layers(kw("no-repeat"))),+ ])+ );+ });++ test("multiple vars for image and repeat parts", () => {+ const result = decls(`+ --img: url("hero.png");+ --rpt: no-repeat;+ background: var(--img) var(--rpt) center;+ `);+ expect(result).toEqual(+ expect.arrayContaining([+ prop(+ "background-image",+ layers(expect.objectContaining({ type: "image" }))+ ),+ prop("background-repeat", layers(kw("no-repeat"))),+ ])+ );+ });++ test("var() for background-position part", () => {+ const result = decls(`+ --pos: center bottom;+ background: red var(--pos);+ `);+ expect(result).toEqual(+ expect.arrayContaining([+ prop(+ "background-color",+ expect.objectContaining({ type: "keyword", value: "red" })+ ),+ prop("background-position-x", layers(kw("center"))),+ prop("background-position-y", layers(kw("bottom"))),+ ])+ );+ });+});++describe("var() substitution — CSS var() inline fallback", () => {+ test("uses plain inline fallback when var is unresolvable", () => {+ // --w is not defined anywhere; inline fallback 2px should be used+ const result = decls(`border: var(--w, 2px) solid red;`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("border-top-width", u(2, "px")),+ prop("border-top-style", kw("solid")),+ prop("border-top-color", kw("red")),+ ])+ );+ });++ test("var value takes precedence over inline fallback", () => {+ // --w is defined as 4px; inline fallback 2px should be ignored+ const result = decls(`--w: 4px; border: var(--w, 2px) solid red;`);+ expect(result).toEqual(+ expect.arrayContaining([prop("border-top-width", u(4, "px"))])+ );+ });++ test("no error emitted when resolved via inline fallback", () => {+ const { errors } = parseCss(+ `.x { border: var(--w, 1px) solid black; }`,+ new Map()+ );+ expect(errors).toEqual([]);+ });++ test("nested var() in fallback is resolved — var(--a, var(--b))", () => {+ // --a unresolvable, fallback is var(--b) which resolves to 3px+ const result = decls(`--b: 3px; border: var(--a, var(--b)) solid red;`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("border-top-width", u(3, "px")),+ prop("border-top-style", kw("solid")),+ prop("border-top-color", kw("red")),+ ])+ );+ });++ test("nested var() in fallback from cssVars — var(--a, var(--b))", () => {+ // --a unresolvable in same-rule and cssVars, fallback var(--b) in cssVars+ const result = parseCss(+ `.x { border: var(--a, var(--b)) solid black; }`,+ new Map([["--b", "4px"]])+ ).styles.filter((d) => d.selector === ".x");+ expect(result).toEqual(+ expect.arrayContaining([prop("border-top-width", u(4, "px"))])+ );+ });++ test("deeply nested fallback var(--a, var(--b, var(--c)))", () => {+ // --a and --b unresolvable, --c resolves+ const result = decls(+ `--c: 5px; border: var(--a, var(--b, var(--c))) solid red;`+ );+ expect(result).toEqual(+ expect.arrayContaining([prop("border-top-width", u(5, "px"))])+ );+ });++ test("all nested fallback vars unresolvable — property dropped with error", () => {+ const { errors } = parseCss(+ `.x { border: var(--a, var(--b)) solid red; }`,+ new Map()+ );+ // --a is the top-level var reported in the error+ expect(errors).toEqual([+ `"border" was not applied because --a could not be resolved`,+ ]);+ });++ test("primary unresolvable, fallback resolves — background shorthand", () => {+ // --primary is not defined, fallback blue should be used for background-color+ const result = decls(`background: var(--primary, blue);`);+ expect(result).toEqual(+ expect.arrayContaining([prop("background-color", kw("blue"))])+ );+ });++ test("primary unresolvable, fallback resolves — no error emitted", () => {+ const { errors } = parseCss(+ `.x { background: var(--primary, blue); }`,+ new Map()+ );+ expect(errors).toEqual([]);+ });++ test("primary unresolvable, fallback resolves — mixed shorthand", () => {+ // --w is not defined, fallback 1px is used; other parts are literal+ const result = decls(`border: var(--w, 1px) solid var(--clr, navy);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("border-top-width", u(1, "px")),+ prop("border-top-style", kw("solid")),+ prop("border-top-color", kw("navy")),+ ])+ );+ });++ test("partial resolution — some vars resolve, some do not — error emitted", () => {+ // --w resolves, --clr does not; an error is emitted for --clr+ const { errors } = parseCss(+ `.x { --w: 1px; border: var(--w) solid var(--clr); }`,+ new Map()+ );+ expect(errors).toEqual([+ `"border" was not applied because --clr could not be resolved`,+ ]);+ });+});++describe("var() substitution — border", () => {+ test("var() for border width", () => {+ const result = decls(`--w: 3px; border: var(--w) solid red;`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("border-top-width", u(3, "px")),+ prop("border-right-width", u(3, "px")),+ prop("border-bottom-width", u(3, "px")),+ prop("border-left-width", u(3, "px")),+ ])+ );+ });++ test("var() for border color", () => {+ const result = decls(`--clr: red; border: 1px solid var(--clr);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("border-top-color", kw("red")),+ prop("border-bottom-color", kw("red")),+ ])+ );+ });++ test("var() for both border width and color", () => {+ const result = decls(+ `--w: 2px; --clr: blue; border: var(--w) dashed var(--clr);`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("border-top-width", u(2, "px")),+ prop("border-top-color", kw("blue")),+ ])+ );+ });++ test("var() for border-top color", () => {+ const result = decls(`--clr: orange; border-top: 1px solid var(--clr);`);+ expect(result).toEqual(+ expect.arrayContaining([prop("border-top-color", kw("orange"))])+ );+ });++ test("var() for border-bottom width", () => {+ const result = decls(`--w: 4px; border-bottom: var(--w) solid black;`);+ expect(result).toEqual(+ expect.arrayContaining([prop("border-bottom-width", u(4, "px"))])+ );+ });++ test("var() for border-left width and color", () => {+ const result = decls(+ `--w: 1px; --clr: purple; border-left: var(--w) solid var(--clr);`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("border-left-width", u(1, "px")),+ prop("border-left-color", kw("purple")),+ ])+ );+ });++ test("var() for border-block color", () => {+ const result = decls(`--clr: teal; border-block: 2px solid var(--clr);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("border-block-start-color", kw("teal")),+ prop("border-block-end-color", kw("teal")),+ ])+ );+ });++ test("var() for border-inline width", () => {+ const result = decls(`--w: 3px; border-inline: var(--w) solid black;`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("border-inline-start-width", u(3, "px")),+ prop("border-inline-end-width", u(3, "px")),+ ])+ );+ });+});++describe("var() substitution — outline", () => {+ test("var() for outline color", () => {+ const result = decls(`--clr: red; outline: 2px solid var(--clr);`);+ expect(result).toEqual(+ expect.arrayContaining([prop("outline-color", kw("red"))])+ );+ });++ test("var() for outline width", () => {+ const result = decls(`--w: 3px; outline: var(--w) dotted black;`);+ expect(result).toEqual(+ expect.arrayContaining([prop("outline-width", u(3, "px"))])+ );+ });++ test("var() for both outline width and color", () => {+ const result = decls(+ `--w: 1px; --clr: navy; outline: var(--w) solid var(--clr);`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("outline-width", u(1, "px")),+ prop("outline-color", kw("navy")),+ ])+ );+ });+});++describe("var() substitution — text-decoration", () => {+ test("var() for text-decoration color", () => {+ const result = decls(`--clr: red; text-decoration: underline var(--clr);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("text-decoration-line", kw("underline")),+ prop("text-decoration-color", kw("red")),+ ])+ );+ });++ test("var() for text-decoration style", () => {+ const result = decls(+ `--sty: dashed; text-decoration: underline var(--sty) red;`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("text-decoration-style", kw("dashed")),+ prop("text-decoration-color", kw("red")),+ ])+ );+ });+});++describe("var() substitution — text-emphasis", () => {+ test("var() for text-emphasis color", () => {+ const result = decls(`--clr: hotpink; text-emphasis: filled var(--clr);`);+ expect(result).toEqual(+ expect.arrayContaining([prop("text-emphasis-color", kw("hotpink"))])+ );+ });+});++describe("var() substitution — margin / padding", () => {+ test("var() for all sides of margin", () => {+ const result = decls(`--sp: 16px; margin: var(--sp);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("margin-top", u(16, "px")),+ prop("margin-right", u(16, "px")),+ prop("margin-bottom", u(16, "px")),+ prop("margin-left", u(16, "px")),+ ])+ );+ });++ test("var() for vertical/horizontal margin", () => {+ const result = decls(`--v: 8px; --h: 16px; margin: var(--v) var(--h);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("margin-top", u(8, "px")),+ prop("margin-right", u(16, "px")),+ prop("margin-bottom", u(8, "px")),+ prop("margin-left", u(16, "px")),+ ])+ );+ });++ test("var() for all sides of padding", () => {+ const result = decls(`--sp: 12px; padding: var(--sp);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("padding-top", u(12, "px")),+ prop("padding-right", u(12, "px")),+ prop("padding-bottom", u(12, "px")),+ prop("padding-left", u(12, "px")),+ ])+ );+ });++ test("var() for padding four-side notation", () => {+ const result = decls(+ `--a: 4px; --b: 8px; --c: 12px; --d: 16px; padding: var(--a) var(--b) var(--c) var(--d);`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("padding-top", u(4, "px")),+ prop("padding-right", u(8, "px")),+ prop("padding-bottom", u(12, "px")),+ prop("padding-left", u(16, "px")),+ ])+ );+ });++ test("var() for margin-inline", () => {+ const result = decls(`--sp: 10px; margin-inline: var(--sp);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("margin-inline-start", u(10, "px")),+ prop("margin-inline-end", u(10, "px")),+ ])+ );+ });++ test("var() for margin-block start and end", () => {+ const result = decls(+ `--s: 8px; --e: 16px; margin-block: var(--s) var(--e);`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("margin-block-start", u(8, "px")),+ prop("margin-block-end", u(16, "px")),+ ])+ );+ });++ test("var() for padding-inline", () => {+ const result = decls(`--sp: 20px; padding-inline: var(--sp);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("padding-inline-start", u(20, "px")),+ prop("padding-inline-end", u(20, "px")),+ ])+ );+ });++ test("var() for padding-block start and end", () => {+ const result = decls(+ `--s: 5px; --e: 10px; padding-block: var(--s) var(--e);`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("padding-block-start", u(5, "px")),+ prop("padding-block-end", u(10, "px")),+ ])+ );+ });+});++describe("var() substitution — inset", () => {+ test("var() for all inset sides", () => {+ const result = decls(`--sp: 0px; inset: var(--sp);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("top", u(0, "px")),+ prop("right", u(0, "px")),+ prop("bottom", u(0, "px")),+ prop("left", u(0, "px")),+ ])+ );+ });++ test("var() for inset two-value notation", () => {+ const result = decls(`--v: 10px; --h: 20px; inset: var(--v) var(--h);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("top", u(10, "px")),+ prop("right", u(20, "px")),+ prop("bottom", u(10, "px")),+ prop("left", u(20, "px")),+ ])+ );+ });++ test("var() for inset-inline", () => {+ const result = decls(+ `--s: 5px; --e: 15px; inset-inline: var(--s) var(--e);`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("inset-inline-start", u(5, "px")),+ prop("inset-inline-end", u(15, "px")),+ ])+ );+ });++ test("var() for inset-block", () => {+ const result = decls(`--sp: 8px; inset-block: var(--sp);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("inset-block-start", u(8, "px")),+ prop("inset-block-end", u(8, "px")),+ ])+ );+ });+});++describe("var() substitution — gap", () => {+ test("var() for both row and column gap", () => {+ const result = decls(`--sp: 24px; gap: var(--sp);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("row-gap", u(24, "px")),+ prop("column-gap", u(24, "px")),+ ])+ );+ });++ test("var() for row and column gap separately", () => {+ const result = decls(`--rg: 16px; --cg: 32px; gap: var(--rg) var(--cg);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("row-gap", u(16, "px")),+ prop("column-gap", u(32, "px")),+ ])+ );+ });+});++describe("var() substitution — flex", () => {+ test("var() for flex-basis", () => {+ const result = decls(`--basis: 200px; flex: 1 1 var(--basis);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("flex-grow", num(1)),+ prop("flex-shrink", num(1)),+ prop("flex-basis", u(200, "px")),+ ])+ );+ });++ test("var() for flex-grow and flex-shrink", () => {+ const result = decls(`--g: 2; --s: 0; flex: var(--g) var(--s) auto;`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("flex-grow", num(2)),+ prop("flex-shrink", num(0)),+ prop("flex-basis", kw("auto")),+ ])+ );+ });+});++describe("var() substitution — column-rule", () => {+ test("var() for column-rule color", () => {+ const result = decls(`--clr: silver; column-rule: 1px solid var(--clr);`);+ expect(result).toEqual(+ expect.arrayContaining([prop("column-rule-color", kw("silver"))])+ );+ });++ test("var() for column-rule width", () => {+ const result = decls(`--w: 2px; column-rule: var(--w) solid black;`);+ expect(result).toEqual(+ expect.arrayContaining([prop("column-rule-width", u(2, "px"))])+ );+ });+});++describe("var() substitution — animation", () => {+ test("var() for animation duration", () => {+ const result = decls(+ `--dur: 0.5s; animation: slide var(--dur) ease infinite;`+ );+ const duration = result.find((d) => d.property === "animation-duration");+ expect(duration?.value).toEqual(u(0.5, "s"));+ });++ test("var() for animation duration and delay", () => {+ const result = decls(+ `--dur: 1s; --del: 200ms; animation: bounce var(--dur) ease var(--del);`+ );+ const duration = result.find((d) => d.property === "animation-duration");+ const delay = result.find((d) => d.property === "animation-delay");+ expect(duration?.value).toEqual(u(1, "s"));+ expect(delay?.value).toEqual(u(200, "ms"));+ });+});++describe("var() substitution — transition", () => {+ test("var() for transition duration", () => {+ const result = decls(`--dur: 300ms; transition: opacity var(--dur) ease;`);+ const duration = result.find((d) => d.property === "transition-duration");+ expect(duration?.value).toEqual(+ layers(expect.objectContaining({ type: "unit", value: 300, unit: "ms" }))+ );+ });++ test("var() for transition duration and delay", () => {+ const result = decls(+ `--dur: 200ms; --del: 50ms; transition: color var(--dur) linear var(--del);`+ );+ const duration = result.find((d) => d.property === "transition-duration");+ const delay = result.find((d) => d.property === "transition-delay");+ expect(duration?.value).toEqual(+ layers(expect.objectContaining({ type: "unit", value: 200, unit: "ms" }))+ );+ expect(delay?.value).toEqual(+ layers(expect.objectContaining({ type: "unit", value: 50, unit: "ms" }))+ );+ });++ test("var() for transition-property name", () => {+ // transition-property stores property names as unparsed (not keyword)+ const result = decls(`--prop: opacity; transition: var(--prop) 300ms;`);+ const property = result.find((d) => d.property === "transition-property");+ expect(property?.value).toEqual(+ layers(expect.objectContaining({ type: "unparsed", value: "opacity" }))+ );+ });+});++describe("var() substitution — grid-row / grid-column / grid-area", () => {+ test("var() for grid-row start", () => {+ const result = decls(`--start: 2; grid-row: var(--start) / 4;`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("grid-row-start", num(2)),+ prop("grid-row-end", num(4)),+ ])+ );+ });++ test("var() for grid-column end", () => {+ const result = decls(`--end: 3; grid-column: 1 / var(--end);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("grid-column-start", num(1)),+ prop("grid-column-end", num(3)),+ ])+ );+ });+});++describe("var() substitution — columns", () => {+ test("var() for column-width", () => {+ const result = decls(`--w: 200px; columns: var(--w) auto;`);+ expect(result).toEqual(+ expect.arrayContaining([prop("column-width", u(200, "px"))])+ );+ });++ test("var() for column-count", () => {+ const result = decls(`--n: 3; columns: auto var(--n);`);+ expect(result).toEqual(+ expect.arrayContaining([prop("column-count", num(3))])+ );+ });+});++describe("var() substitution — list-style", () => {+ test("var() for list-style-type", () => {+ const result = decls(`--type: square; list-style: var(--type);`);+ expect(result).toEqual(+ expect.arrayContaining([prop("list-style-type", kw("square"))])+ );+ });+});++describe("var() substitution — place-content / place-items / place-self", () => {+ test("var() for place-content align and justify", () => {+ const result = decls(+ `--a: center; --j: start; place-content: var(--a) var(--j);`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("align-content", kw("center")),+ prop("justify-content", kw("start")),+ ])+ );+ });++ test("var() for place-items align", () => {+ const result = decls(`--a: end; place-items: var(--a) center;`);+ expect(result).toEqual(+ expect.arrayContaining([prop("align-items", kw("end"))])+ );+ });++ test("var() for place-self justify", () => {+ const result = decls(`--j: stretch; place-self: auto var(--j);`);+ expect(result).toEqual(+ expect.arrayContaining([prop("justify-self", kw("stretch"))])+ );+ });+});++describe("var() substitution — contain-intrinsic-size", () => {+ test("var() for both intrinsic dimensions", () => {+ const result = decls(+ `--w: 300px; --h: 200px; contain-intrinsic-size: var(--w) var(--h);`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("contain-intrinsic-width", u(300, "px")),+ prop("contain-intrinsic-height", u(200, "px")),+ ])+ );+ });+});++describe("var() substitution — scroll-margin / scroll-padding", () => {+ test("var() for all scroll-margin sides", () => {+ const result = decls(`--sp: 8px; scroll-margin: var(--sp);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("scroll-margin-top", u(8, "px")),+ prop("scroll-margin-right", u(8, "px")),+ prop("scroll-margin-bottom", u(8, "px")),+ prop("scroll-margin-left", u(8, "px")),+ ])+ );+ });++ test("var() for scroll-padding vertical/horizontal", () => {+ const result = decls(+ `--v: 4px; --h: 8px; scroll-padding: var(--v) var(--h);`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("scroll-padding-top", u(4, "px")),+ prop("scroll-padding-right", u(8, "px")),+ prop("scroll-padding-bottom", u(4, "px")),+ prop("scroll-padding-left", u(8, "px")),+ ])+ );+ });++ test("var() for scroll-padding-inline", () => {+ const result = decls(`--sp: 12px; scroll-padding-inline: var(--sp);`);+ expect(result).toEqual(+ expect.arrayContaining([+ prop("scroll-padding-inline-start", u(12, "px")),+ prop("scroll-padding-inline-end", u(12, "px")),+ ])+ );+ });++ test("var() for scroll-margin-block", () => {+ const result = decls(+ `--s: 6px; --e: 10px; scroll-margin-block: var(--s) var(--e);`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("scroll-margin-block-start", u(6, "px")),+ prop("scroll-margin-block-end", u(10, "px")),+ ])+ );+ });+});++describe("var() substitution — font", () => {+ test("var() for font-size", () => {+ const result = decls(`--sz: 18px; font: var(--sz) Arial;`);+ expect(result).toEqual(+ expect.arrayContaining([prop("font-size", u(18, "px"))])+ );+ });++ test("var() for font-weight and font-size", () => {+ const result = decls(+ `--w: 700; --sz: 16px; font: var(--w) var(--sz) sans-serif;`+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("font-weight", num(700)),+ prop("font-size", u(16, "px")),+ ])+ );+ });+});++describe("var() substitution — -webkit-text-stroke", () => {+ test("var() for stroke width and color — passes through as tuple (not expanded)", () => {+ // -webkit-text-stroke is in shorthand-properties so it gets var substitution,+ // but shorthands.ts has no expand case for it — it passes through as a tuple+ // value containing the resolved width and color tokens.+ const result = decls(+ `--w: 1px; --clr: black; -webkit-text-stroke: var(--w) var(--clr);`+ );+ const stroke = result.find(+ (d) => (d.property as string) === "-webkit-text-stroke"+ );+ expect(stroke?.value).toEqual(+ expect.objectContaining({+ type: "tuple",+ value: expect.arrayContaining([+ expect.objectContaining({ type: "unit", value: 1, unit: "px" }),+ expect.objectContaining({ type: "keyword", value: "black" }),+ ]),+ })+ );+ });+});++describe("parseCss — external cssVars parameter", () => {+ // Helper that passes an external var map+ const declsWithVars = (css: string, vars: Record<string, string>) =>+ parseCss(`.x { ${css} }`, new Map(Object.entries(vars))).styles.filter(+ (d) => d.selector === ".x"+ );++ // ── background ────────────────────────────────────────────────────────────++ test("background: cross-rule var resolves via cssVars", () => {+ // --clr defined only in cssVars (parent rule), not in same rule+ const result = declsWithVars(`background: var(--clr);`, {+ "--clr": "tomato",+ });+ expect(result).toEqual(+ expect.arrayContaining([prop("background-color", kw("tomato"))])+ );+ });++ test("background: same-rule var takes precedence over cssVars", () => {+ // same rule has --clr: blue, cssVars has --clr: red — blue wins+ const result = declsWithVars(`--clr: blue; background: var(--clr);`, {+ "--clr": "red",+ });+ expect(result).toEqual(+ expect.arrayContaining([prop("background-color", kw("blue"))])+ );+ });++ test("background: mixed — one var from same rule, one from cssVars", () => {+ // --img is in same rule, --pos is only in cssVars+ const result = declsWithVars(+ `--img: url(hero.png); background: var(--img) var(--pos);`,+ { "--pos": "center" }+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop(+ "background-image",+ layers(expect.objectContaining({ type: "image" }))+ ),+ prop("background-position-x", layers(kw("center"))),+ ])+ );+ });++ // ── border ────────────────────────────────────────────────────────────────++ test("border: cross-rule var for width via cssVars", () => {+ const result = declsWithVars(`border: var(--bw) solid black;`, {+ "--bw": "2px",+ });+ expect(result).toEqual(+ expect.arrayContaining([+ prop("border-top-width", u(2, "px")),+ prop("border-right-width", u(2, "px")),+ prop("border-bottom-width", u(2, "px")),+ prop("border-left-width", u(2, "px")),+ ])+ );+ });++ test("border: cross-rule var for color via cssVars", () => {+ const result = declsWithVars(`border: 1px solid var(--border-clr);`, {+ "--border-clr": "#333",+ });+ expect(result).toEqual(+ expect.arrayContaining([+ prop("border-top-color", expect.objectContaining({ type: "color" })),+ prop("border-right-color", expect.objectContaining({ type: "color" })),+ prop("border-bottom-color", expect.objectContaining({ type: "color" })),+ prop("border-left-color", expect.objectContaining({ type: "color" })),+ ])+ );+ });++ test("border: width from same rule, color from cssVars", () => {+ const result = declsWithVars(+ `--w: 3px; border: var(--w) dashed var(--clr);`,+ { "--clr": "navy" }+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("border-top-width", u(3, "px")),+ prop("border-top-style", kw("dashed")),+ prop("border-top-color", kw("navy")),+ ])+ );+ });++ // ── margin / padding ──────────────────────────────────────────────────────++ test("margin: cross-rule var for all sides via cssVars", () => {+ const result = declsWithVars(`margin: var(--space);`, {+ "--space": "16px",+ });+ expect(result).toEqual(+ expect.arrayContaining([+ prop("margin-top", u(16, "px")),+ prop("margin-right", u(16, "px")),+ prop("margin-bottom", u(16, "px")),+ prop("margin-left", u(16, "px")),+ ])+ );+ });++ test("padding: cross-rule var for horizontal via cssVars", () => {+ const result = declsWithVars(`padding: var(--v) var(--h);`, {+ "--v": "8px",+ "--h": "16px",+ });+ expect(result).toEqual(+ expect.arrayContaining([+ prop("padding-top", u(8, "px")),+ prop("padding-right", u(16, "px")),+ prop("padding-bottom", u(8, "px")),+ prop("padding-left", u(16, "px")),+ ])+ );+ });++ // ── transition ────────────────────────────────────────────────────────────++ test("transition: cross-rule var for duration via cssVars", () => {+ const result = declsWithVars(`transition: opacity var(--speed) ease;`, {+ "--speed": "400ms",+ });+ const duration = result.find((d) => d.property === "transition-duration");+ expect(duration?.value).toEqual(+ layers(expect.objectContaining({ type: "unit", value: 400, unit: "ms" }))+ );+ });++ test("transition: duration from same rule, delay from cssVars", () => {+ const result = declsWithVars(+ `--dur: 200ms; transition: color var(--dur) linear var(--del);`,+ { "--del": "100ms" }+ );+ const duration = result.find((d) => d.property === "transition-duration");+ const delay = result.find((d) => d.property === "transition-delay");+ expect(duration?.value).toEqual(+ layers(expect.objectContaining({ type: "unit", value: 200, unit: "ms" }))+ );+ expect(delay?.value).toEqual(+ layers(expect.objectContaining({ type: "unit", value: 100, unit: "ms" }))+ );+ });++ // ── font ──────────────────────────────────────────────────────────────────++ test("font: cross-rule var for size via cssVars", () => {+ const result = declsWithVars(`font: bold var(--fs) sans-serif;`, {+ "--fs": "18px",+ });+ expect(result).toEqual(+ expect.arrayContaining([prop("font-size", u(18, "px"))])+ );+ });++ test("font: weight from cssVars, size from same rule", () => {+ const result = declsWithVars(+ `--sz: 14px; font: var(--fw) var(--sz) Arial;`,+ {+ "--fw": "600",+ }+ );+ expect(result).toEqual(+ expect.arrayContaining([+ prop("font-weight", num(600)),+ prop("font-size", u(14, "px")),+ ])+ );+ });++ // ── flex ──────────────────────────────────────────────────────────────────++ test("flex: cross-rule var for basis via cssVars", () => {+ const result = declsWithVars(`flex: 1 1 var(--basis);`, {+ "--basis": "300px",+ });+ expect(result).toEqual(+ expect.arrayContaining([prop("flex-basis", u(300, "px"))])+ );+ });++ // ── gap ───────────────────────────────────────────────────────────────────++ test("gap: cross-rule vars for row and column via cssVars", () => {+ const result = declsWithVars(`gap: var(--row-gap) var(--col-gap);`, {+ "--row-gap": "8px",+ "--col-gap": "16px",+ });+ expect(result).toEqual(+ expect.arrayContaining([+ prop("row-gap", u(8, "px")),+ prop("column-gap", u(16, "px")),+ ])+ );+ });++ // ── multiple rules: cssVars doesn't bleed between rules ───────────────────++ test("cssVars are available in both rules when passed", () => {+ const styles = parseCss(+ `.a { border: var(--w) solid red; } .b { margin: var(--w); }`,+ new Map([["--w", "4px"]])+ ).styles;+ const aBorderTop = styles.find(+ (d) => d.selector === ".a" && d.property === "border-top-width"+ );+ const bMarginTop = styles.find(+ (d) => d.selector === ".b" && d.property === "margin-top"+ );+ expect(aBorderTop?.value).toEqual(u(4, "px"));+ expect(bMarginTop?.value).toEqual(u(4, "px"));+ });++ test("same-rule var overrides cssVars in first rule, not second", () => {+ // .a has --w: 10px in same rule, .b does not+ const styles = parseCss(+ `.a { --w: 10px; margin: var(--w); } .b { margin: var(--w); }`,+ new Map([["--w", "4px"]])+ ).styles;+ const aMarginTop = styles.find(+ (d) => d.selector === ".a" && d.property === "margin-top"+ );+ const bMarginTop = styles.find(+ (d) => d.selector === ".b" && d.property === "margin-top"+ );+ expect(aMarginTop?.value).toEqual(u(10, "px"));+ expect(bMarginTop?.value).toEqual(u(4, "px"));+ });+});+describe("parseMediaQuery", () => {test("simple min-width", () => {expect(parseMediaQuery(`(min-width: 768px)`)).toEqual({diff --git a/packages/css-data/src/parse-css.ts b/packages/css-data/src/parse-css.tsindex 17fa6b2c00..63c27dde26 100644--- a/packages/css-data/src/parse-css.ts+++ b/packages/css-data/src/parse-css.ts@@ -5,8 +5,18 @@ import type {CssProperty,StyleProperty,} from "@webstudio-is/css-engine";-import { parseCssValue as parseCssValueLonghand } from "./parse-css-value";+import {+ parseCssValue as parseCssValueLonghand,+ parseCssVar,+} from "./parse-css-value";import { expandShorthands } from "./shorthands";+import { shorthandProperties } from "./__generated__/shorthand-properties";++const shorthandSet = new Set<string>(shorthandProperties);++// css-tree exposes `skip` as a Symbol on the walk function itself.+// Returning it from an enter() callback prevents descent into child nodes.+const walkSkip = (csstree.walk as unknown as { skip: symbol }).skip;export type ParsedStyleDecl = {breakpoint?: string;@@ -83,6 +93,136 @@ const parseCssValue = (property: CssProperty, value: string) => {return final;};+/**+ * Recursively resolve all var() references in a CSS value string.+ * Handles nested var() in fallbacks (e.g. var(--a, var(--b))).+ * Returns `walkSkip` from enter() to prevent double-processing nested nodes.+ *+ * Resolution order per var(): direct custom property → cssVars → inline fallback+ * (fallback is itself recursively resolved if it contains var()).+ *+ * Returns undefined when the value contains no var() (fast path) or when the+ * recursion depth limit is exceeded.+ */+const resolveVars = (+ value: string,+ customProperties: Map<string, string>,+ cssVars: Map<string, string> | undefined,+ depth = 0+): { resolved: string; dropped: string[] } | undefined => {+ if (!value.includes("var(") || depth > 8) {+ return;+ }++ let ast: csstree.CssNode;+ try {+ ast = csstree.parse(value, { context: "value", positions: true });+ } catch {+ return;+ }++ const subs: Array<{ start: number; end: number; text: string }> = [];+ const dropped: string[] = [];++ csstree.walk(ast, {+ visit: "Function",+ enter(node) {+ const fnNode = node as csstree.FunctionNode;+ if (fnNode.name !== "var" || !fnNode.loc) {+ return;+ }+ const varRef = parseCssVar(fnNode);+ if (!varRef) {+ return walkSkip;+ }++ const direct =+ customProperties.get(`--${varRef.value}`) ??+ cssVars?.get(`--${varRef.value}`);++ if (direct !== undefined) {+ subs.push({+ start: fnNode.loc.start.offset,+ end: fnNode.loc.end.offset,+ text: direct,+ });+ return walkSkip;+ }++ // Try inline fallback — may itself contain var() references.+ if (varRef.fallback?.type === "unparsed") {+ const fbValue = varRef.fallback.value;+ // If the fallback itself has no var(), use it directly.+ // Otherwise recursively resolve any nested vars inside it.+ const fallbackResult = fbValue.includes("var(")+ ? resolveVars(fbValue, customProperties, cssVars, depth + 1)+ : { resolved: fbValue, dropped: [] };+ if (+ fallbackResult !== undefined &&+ fallbackResult.dropped.length === 0+ ) {+ subs.push({+ start: fnNode.loc.start.offset,+ end: fnNode.loc.end.offset,+ text: fallbackResult.resolved,+ });+ return walkSkip;+ }+ }++ dropped.push(`--${varRef.value}`);+ return walkSkip;+ },+ });++ let resolved = value;+ for (const s of [...subs].reverse()) {+ resolved = resolved.slice(0, s.start) + s.text + resolved.slice(s.end);+ }+ return { resolved, dropped };+};++/**+ * Substitute var() references in a shorthand value then expand the result.+ * Works for any shorthand (background, border, transition, font…).+ *+ * Returns undefined when the value contains no var() (fast path).+ * Returns { result: empty Map, droppedVars } when all vars are unresolvable.+ * Returns { result: parsed Map, droppedVars } when some vars resolved and+ * some did not — droppedVars is non-empty and an error should be reported,+ * but the partially-resolved value is still attempted (may produce invalid).+ */+const substituteVarsInShorthand = (+ property: string,+ value: string,+ customProperties: Map<string, string>,+ cssVars?: Map<string, string>+):+ | { result: Map<CssProperty, StyleValue>; droppedVars: string[] }+ | undefined => {+ const resolution = resolveVars(value, customProperties, cssVars);+ if (resolution === undefined) {+ return;+ }++ const { resolved, dropped } = resolution;++ if (resolved === value) {+ // No substitution happened.+ if (dropped.length === 0) {+ // No recognizable var() nodes — let caller fall through to default.+ return;+ }+ // All vars were unresolvable — signal that the property will be dropped.+ return { result: new Map(), droppedVars: dropped };+ }++ return {+ result: parseCssValue(property as CssProperty, resolved),+ droppedVars: dropped,+ };+};+const cssTreeTryParse = (input: string) => {try {const ast = csstree.parse(input);@@ -97,17 +237,72 @@ type Selector = {state?: string;};-export const parseCss = (css: string): ParsedStyleDecl[] => {+export type ParseCssResult = {+ styles: ParsedStyleDecl[];+ errors: string[];+};++/**+ * Extract all CSS custom property (--*) declarations from a CSS string,+ * regardless of which selector rule they appear in.+ * Useful when CSS from multiple rules (e.g. Tailwind utility classes) needs+ * to be resolved together as if they apply to the same element.+ */+export const extractCssCustomProperties = (+ css: string+): Map<string, string> => {+ const map = new Map<string, string>();const ast = cssTreeTryParse(css);- const styles = new Map<string, ParsedStyleDecl>();+ if (ast === undefined) {+ return map;+ }+ csstree.walk(ast, {+ visit: "Declaration",+ enter(node) {+ const decl = node as csstree.Declaration;+ const prop = normalizeProperty(decl.property);+ if (prop.startsWith("--")) {+ map.set(prop, csstree.generate(decl.value));+ }+ },+ });+ return map;+};++export const parseCss = (+ css: string,+ cssVars: Map<string, string>+): ParseCssResult => {+ const ast = cssTreeTryParse(css);+ const stylesMap = new Map<string, ParsedStyleDecl>();+ const errors: string[] = [];if (ast === undefined) {- return [];+ return { styles: [], errors };}// Track context as we traverse — use a stack to support nested @mediaconst atruleStack: csstree.Atrule[] = [];let currentRule: csstree.Rule | undefined;+ // Custom properties declared in the current rule, used to resolve var() in shorthand expansion.+ // Pre-populated for each rule (two-pass) so that forward references like+ // border-color: rgb(x y z / var(--op)); --op: 0.6;+ // resolve correctly regardless of declaration order.+ const customProperties = new Map<string, string>();++ const collectRuleCustomProperties = (rule: csstree.Rule) => {+ customProperties.clear();+ csstree.walk(rule, {+ visit: "Declaration",+ enter(node) {+ const decl = node as csstree.Declaration;+ const prop = normalizeProperty(decl.property);+ if (prop.startsWith("--")) {+ customProperties.set(prop, csstree.generate(decl.value));+ }+ },+ });+ };csstree.walk(ast, {enter(node) {@@ -115,6 +310,7 @@ export const parseCss = (css: string): ParsedStyleDecl[] => {atruleStack.push(node);} else if (node.type === "Rule") {currentRule = node;+ collectRuleCustomProperties(node);}},leave(node) {@@ -264,15 +460,33 @@ export const parseCss = (css: string): ParsedStyleDecl[] => {}const stringValue = csstree.generate(node.value);-- const parsedCss = parseCssValue(- normalizeProperty(node.property),- stringValue- );+ const property = normalizeProperty(node.property);++ let parsedCss: Map<CssProperty, StyleValue>;+ if (shorthandSet.has(property)) {+ const substituted = substituteVarsInShorthand(+ property,+ stringValue,+ customProperties,+ cssVars+ );+ if (substituted !== undefined) {+ parsedCss = substituted.result;+ for (const varName of substituted.droppedVars) {+ errors.push(+ `"${property}" was not applied because ${varName} could not be resolved`+ );+ }+ } else {+ parsedCss = parseCssValue(property, stringValue);+ }+ } else {+ parsedCss = parseCssValue(property, stringValue);+ }for (const { name: selector, state } of selectors) {- for (const [property, value] of parsedCss) {- const normalizedProperty = normalizeProperty(property);+ for (const [prop, value] of parsedCss) {+ const normalizedProperty = normalizeProperty(prop);const styleDecl: ParsedStyleDecl = {selector,property: normalizedProperty,@@ -286,7 +500,7 @@ export const parseCss = (css: string): ParsedStyleDecl[] => {}// deduplicate styles within selector and state by using map- styles.set(+ stylesMap.set(`${breakpoint}:${selector}:${state}:${normalizedProperty}`,styleDecl);@@ -295,7 +509,7 @@ export const parseCss = (css: string): ParsedStyleDecl[] => {},});- return Array.from(styles.values());+ return { styles: Array.from(stylesMap.values()), errors };};export type ParsedClassSelector = {diff --git a/packages/sdk/scripts/normalize.css.ts b/packages/sdk/scripts/normalize.css.tsindex 49f53a020f..c50d49ad57 100644--- a/packages/sdk/scripts/normalize.css.ts+++ b/packages/sdk/scripts/normalize.css.ts@@ -20,7 +20,7 @@ const mapGroupBy = <Item, Key>(};const css = await readFile("./src/normalize.css", "utf8");-const parsed = parseCss(css);+const { styles: parsed } = parseCss(css, new Map());const groups = mapGroupBy(parsed, (styleDecl) => styleDecl.selector);const validTags = [diff --git a/packages/template/src/css.ts b/packages/template/src/css.tsindex 0b02d36063..8405bffd2f 100644--- a/packages/template/src/css.ts+++ b/packages/template/src/css.ts@@ -14,7 +14,10 @@ export const css = (): TemplateStyleDecl[] => {const cssString = `.styles{ ${String.raw({ raw: strings }, ...values)} }`;const styles: TemplateStyleDecl[] = [];- for (const { breakpoint, state, property, value } of parseCss(cssString)) {+ for (const { breakpoint, state, property, value } of parseCss(+ cssString,+ new Map()+ ).styles) {styles.push({ breakpoint, state, property: property, value });}return styles;