From 7fe4012cff1f16612bcb65e68232db93ffa68cb8 Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Fri, 23 Oct 2026 19:37:40 +0300 Subject: [PATCH 1/5] fix(compiler): scope single-definition variable inlining to the declaring block The inliner folded a custom property declared once into every var() in the stylesheet, whether or not the reference's element can hold the declaration. It now folds a value only into the block that declares it, or from a declaration outside @media and @container that reaches every element: `*`, or `:root`, `:host` and `html` for an inheriting property. An @supports block counts as extractRule decides it, through one rulesTheCompilerKeeps, so a dropped block is emptied before the census; a registered `*` property that nothing declares folds to its initial value; and a declaration is removed once no rule reads it. Values the fold no longer normalises reach the token path, which now reads `0` and `false` as values and gives a the descriptor parseAspectRatio gives it. A compiled box-shadow drops a transparent shadow, as the runtime does. --- .../compiler/inline-variables.test.ts | 436 +++++++++++++++ src/__tests__/compiler/property.test.ts | 6 +- src/__tests__/native/box-shadow.test.tsx | 42 +- .../native/variable-fold-parity.test.tsx | 276 ++++++++++ .../native/variable-inlining.test.tsx | 152 ++++++ src/__tests__/native/variables.test.tsx | 9 +- src/compiler/compiler.ts | 93 +--- src/compiler/compiler.types.ts | 1 - src/compiler/declarations.ts | 57 +- src/compiler/inline-variables.ts | 508 ++++++++++++++---- src/compiler/supports.ts | 7 +- src/native/styles/shorthands/box-shadow.ts | 3 +- src/utilities/index.ts | 1 + src/utilities/transparent-color.ts | 4 + 14 files changed, 1364 insertions(+), 231 deletions(-) create mode 100644 src/__tests__/compiler/inline-variables.test.ts create mode 100644 src/__tests__/native/variable-fold-parity.test.tsx create mode 100644 src/__tests__/native/variable-inlining.test.tsx create mode 100644 src/utilities/transparent-color.ts diff --git a/src/__tests__/compiler/inline-variables.test.ts b/src/__tests__/compiler/inline-variables.test.ts new file mode 100644 index 00000000..981879e5 --- /dev/null +++ b/src/__tests__/compiler/inline-variables.test.ts @@ -0,0 +1,436 @@ +import type { + ReactNativeCssStyleSheet, + StyleDescriptor, + StyleRule, +} from "react-native-css/compiler"; +import { compile } from "react-native-css/compiler"; + +function rulesFor( + sheet: ReactNativeCssStyleSheet, + className: string, +): StyleRule[] { + return sheet.s?.find(([name]) => name === className)?.[1] ?? []; +} + +function foldedValue( + sheet: ReactNativeCssStyleSheet, + className: string, + property: string, +) { + for (const rule of rulesFor(sheet, className)) { + for (const declaration of rule.d ?? []) { + if (!Array.isArray(declaration) && property in declaration) { + return declaration[property]; + } + } + } + return undefined; +} + +function runtimeValue( + sheet: ReactNativeCssStyleSheet, + className: string, + property: string, +): StyleDescriptor { + for (const rule of rulesFor(sheet, className)) { + for (const declaration of rule.d ?? []) { + if (Array.isArray(declaration) && declaration[1] === property) { + return declaration[0]; + } + } + } + return undefined; +} + +function readsAtRuntime(sheet: ReactNativeCssStyleSheet, className: string) { + return rulesFor(sheet, className).some((rule) => rule.dv === 1); +} + +function declaredValue( + sheet: ReactNativeCssStyleSheet, + className: string, + name: string, +) { + for (const rule of rulesFor(sheet, className)) { + for (const [declared, value] of rule.v ?? []) { + if (declared === name) return value; + } + } + return undefined; +} + +describe("a variable is folded only where its value is provable", () => { + test("a class-scoped variable does not reach another rule", () => { + const sheet = compile( + `.parent { --x: 10px; } .child { width: var(--x); }`, + ).stylesheet(); + + // An element carrying only `.child` never matched `.parent`, so it has no `--x` + expect(foldedValue(sheet, "child", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "child")).toBe(true); + expect(declaredValue(sheet, "parent", "x")).toBe(10); + }); + + test("the same block is provable, and still folds", () => { + const sheet = compile(`.a { --x: 10px; width: var(--x); }`).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + expect(readsAtRuntime(sheet, "a")).toBe(false); + }); + + test.each([":root", ":host", "*", "html"])( + "%s is universal, so its variables fold anywhere", + (selector) => { + const sheet = compile( + `${selector} { --x: 10px; } .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBe(10); + expect(readsAtRuntime(sheet, "child")).toBe(false); + }, + ); + + test.each([ + ["div", "every element descends from html, from no other element name"], + [":hover", "a state is not a scope"], + [".theme", "a class is the case this whole rule exists for"], + ])("%s is not universal: %s", (selector) => { + const sheet = compile( + `${selector} { --x: 10px; } .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "child")).toBe(true); + }); + + test.each([ + [":root", 10], + [".theme", undefined], + ])("a nested `&` under %s takes its parent's answer", (parent, expected) => { + const sheet = compile( + `${parent} { & { --x: 10px; } } .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBe(expected); + }); + + test("a nested selector under :root names its descendants, not every element", () => { + const sheet = compile( + `:root { * { --x: 10px; } } .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBeUndefined(); + }); + + test("@layer does not narrow a universal scope", () => { + const sheet = compile( + `@layer theme { :root, :host { --x: 10px; } } .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBe(10); + }); + + test("a keyframe's declaration is a second definition", () => { + const sheet = compile( + `.a { --x: 10px; width: var(--x); animation: grow 1s; } @keyframes grow { to { --x: 20px; } }`, + ).stylesheet(); + + // While the animation runs, `.a`'s `--x` is the keyframe's + expect(foldedValue(sheet, "a", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "a")).toBe(true); + }); + + test("a keyframe's reference folds a universal variable", () => { + const sheet = compile( + `:root { --x: 10px; } @keyframes grow { to { width: var(--x); } }`, + ).stylesheet(); + + expect(sheet.k).toStrictEqual([["grow", [["to", [{ width: 10 }]]]]]); + }); +}); + +describe("a folded declaration is removed once nothing reads it", () => { + test("a declaration whose every reference folded is removed", () => { + const sheet = compile(`.a { --x: 10px; width: var(--x); }`).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + expect(declaredValue(sheet, "a", "x")).toBeUndefined(); + }); + + test("a declaration another rule reads at runtime is kept", () => { + const sheet = compile( + `.a { --x: 10px; width: var(--x); } .b { height: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + expect(readsAtRuntime(sheet, "b")).toBe(true); + expect(declaredValue(sheet, "a", "x")).toBe(10); + }); + + test("an !important declaration and an !important read count as any other", () => { + const sheet = compile( + `.a { --x: 10px !important; width: var(--x); } .b { height: var(--x) !important; }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + expect(readsAtRuntime(sheet, "b")).toBe(true); + expect(declaredValue(sheet, "a", "x")).toBe(10); + }); + + test.each([ + ["an rgb() alpha", `.a { --c: 0.5; color: rgb(255 0 0 / var(--c)); }`], + [ + "a light-dark() branch", + `.a { --c: 0.5; color: light-dark(rgb(255 0 0 / var(--c)), #00f); }`, + ], + ])("a reference inside %s keeps its declaration", (_name, css) => { + const sheet = compile(css).stylesheet(); + + expect(declaredValue(sheet, "a", "c")).toBe(0.5); + }); + + test("a variable declared initial folds to the reference's fallback", () => { + const sheet = compile( + `.a { --x: initial; width: var(--x, 10px); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + }); + + test("every declaration of a fully folded chain is removed", () => { + const sheet = compile( + `.a { --y: 10px; --x: var(--y); width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + expect(declaredValue(sheet, "a", "x")).toBeUndefined(); + expect(declaredValue(sheet, "a", "y")).toBeUndefined(); + }); + + test("a declaration read only by a removed declaration is removed", () => { + const sheet = compile( + `.a { --x: var(--y); height: 1px; } .b { --y: 10px; height: 2px; }`, + ).stylesheet(); + + expect(declaredValue(sheet, "a", "x")).toBeUndefined(); + expect(declaredValue(sheet, "b", "y")).toBeUndefined(); + }); + + test("a declaration read by a kept declaration is kept", () => { + const sheet = compile( + `.a { --x: var(--y); height: 1px; } .b { --y: 10px; height: 2px; } .c { width: var(--x); }`, + ).stylesheet(); + + expect(declaredValue(sheet, "a", "x")).toStrictEqual([{}, "var", "y", 1]); + expect(declaredValue(sheet, "b", "y")).toBe(10); + }); +}); + +describe("a conditional scope is not a universal one", () => { + test.each([ + ["@media (min-width: 1px)", "media"], + ["@container (min-width: 1px)", "container"], + ])("%s wrapping :root", (atRule) => { + const sheet = compile( + `${atRule} { :root { --x: 10px; } } .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "child")).toBe(true); + }); + + test("a conditional block still folds into itself", () => { + // A query that switches the declaration off switches the reference off with it + const sheet = compile( + `@media (min-width: 1px) { .a { --x: 10px; width: var(--x); } }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + }); +}); + +describe("@supports is decided when the stylesheet compiles", () => { + test("a kept block's declarations apply unconditionally", () => { + const sheet = compile( + `@supports (color: color-mix(in lab, red, red)) { :root { --x: 10px; } } + .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBe(10); + }); + + test("a dropped block's declarations do not apply", () => { + const sheet = compile( + `@supports (display: grid) { :root { --x: 10px; } } + .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBeUndefined(); + }); + + test("a dropped block's read keeps no declaration", () => { + const sheet = compile( + `.a { --x: 10px; height: 1px; } + @supports (display: grid) { .b { width: var(--x); } }`, + ).stylesheet(); + + expect(declaredValue(sheet, "a", "x")).toBeUndefined(); + }); + + test("a dropped block nested in a rule keeps no declaration", () => { + const sheet = compile( + `.a { --x: 10px; height: 1px; } + .b { height: 2px; @supports (display: grid) { width: var(--x); } }`, + ).stylesheet(); + + expect(declaredValue(sheet, "a", "x")).toBeUndefined(); + }); + + test("a dropped block's declaration is not a second definition", () => { + const sheet = compile( + `@supports (display: grid) { :root { --x: 20px; } } + :root { --x: 10px; } + .child { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "child", "width")).toBe(10); + }); +}); + +describe("a registered property", () => { + test("inherits: false keeps a :root declaration from reaching other elements", () => { + // An element other than the root holds the registered initial value, not the one `:root` declares + const sheet = compile( + `@property --x { syntax: ""; inherits: false; initial-value: 10px; } + :root { --x: 20px; } + .b { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "b", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "b")).toBe(true); + }); + + test("inherits: true leaves the universal fold alone", () => { + const sheet = compile( + `@property --x { syntax: ""; inherits: true; initial-value: 10px; } + :root { --x: 20px; } + .b { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "b", "width")).toBe(20); + }); + + test("inherits: false does not narrow a declaration on every element", () => { + const sheet = compile( + `@property --x { syntax: ""; inherits: false; initial-value: 10px; } + * { --x: 20px; } + .b { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "b", "width")).toBe(20); + }); + + test("an undeclared property folds to its initial value", () => { + const sheet = compile( + `@property --x { syntax: "*"; inherits: false; initial-value: 10px; } + .b { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "b", "width")).toBe(10); + }); + + test("the initial value wins over a fallback block the compiler drops", () => { + // Tailwind's shape: the fallback serves browsers without @property, and the compiler drops it + const sheet = compile( + `@property --x { syntax: "*"; inherits: false; initial-value: 10px; } + @supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) { + *, ::before, ::after, ::backdrop { --x: 20px; } + } + .b { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "b", "width")).toBe(10); + }); + + test("a typed initial value is left to the runtime", () => { + const sheet = compile( + `@property --x { syntax: ""; inherits: false; initial-value: 10px; } + .b { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "b", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "b")).toBe(true); + }); + + test("a declared property does not fold its initial value across rules", () => { + const sheet = compile( + `@property --x { syntax: "*"; inherits: false; initial-value: 10px; } + .a { --x: 20px; } + .b { width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "b", "width")).toBeUndefined(); + expect(readsAtRuntime(sheet, "b")).toBe(true); + }); +}); + +describe("a variable's own value is held to the same terms", () => { + test("a nested reference does not cross a block boundary", () => { + const sheet = compile( + `.a { --x: var(--y); width: var(--x); } .b { --y: 10px; }`, + ).stylesheet(); + + // `--y` belongs to `.b`, and folding it into `.a` would carry it to elements that never matched `.b` + expect(foldedValue(sheet, "a", "width")).toBeUndefined(); + expect(runtimeValue(sheet, "a", "width")).toStrictEqual([ + {}, + "var", + "y", + 1, + ]); + expect(declaredValue(sheet, "b", "y")).toBe(10); + }); + + test("a nested reference in the same block folds", () => { + const sheet = compile( + `.a { --y: 10px; --x: var(--y); width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + }); + + test("a nested reference to a variable declared initial folds to its fallback", () => { + const sheet = compile( + `.a { --y: initial; --x: var(--y, 10px); width: var(--x); }`, + ).stylesheet(); + + expect(foldedValue(sheet, "a", "width")).toBe(10); + }); + + test("a universal nested reference folds into a kept declaration", () => { + const sheet = compile( + `:root { --y: 10px; } .a { --x: var(--y); } .b { width: var(--x); }`, + ).stylesheet(); + + expect(declaredValue(sheet, "a", "x")).toBe(10); + }); +}); + +test("the fold does not depend on the order the rules are written in", () => { + // `--y` is declared twice, so it is not a candidate, and the winning `2px` is left to the runtime + const declarations = `:root { --y: 1px; } :root { --y: 2px; }`; + const reference = `.a { --x: var(--y); width: var(--x); }`; + + const varFirst = compile(`${reference} ${declarations}`).stylesheet(); + const varLast = compile(`${declarations} ${reference}`).stylesheet(); + + for (const sheet of [varFirst, varLast]) { + expect(foldedValue(sheet, "a", "width")).toBeUndefined(); + expect(runtimeValue(sheet, "a", "width")).toStrictEqual([ + {}, + "var", + "y", + 1, + ]); + } +}); diff --git a/src/__tests__/compiler/property.test.ts b/src/__tests__/compiler/property.test.ts index 20ae04db..11d7b564 100644 --- a/src/__tests__/compiler/property.test.ts +++ b/src/__tests__/compiler/property.test.ts @@ -316,7 +316,7 @@ test("an inheriting property with one declaration is still inlined", () => { inherits: true; initial-value: 0px; } -.parent { --folded: 10px; } +:root { --folded: 10px; } .child { width: var(--folded); } `); @@ -404,7 +404,7 @@ test.each([ test("a property left unregistered is inlined like any other declared once", () => { const result = compile(` @property --t { syntax: ""; inherits: false; initial-value: rotate(45deg); } -.parent { --t: rotate(10deg); } +:root { --t: rotate(10deg); } .child { transform: var(--t); } `).stylesheet(); @@ -433,7 +433,7 @@ test("an @property nested in @media is not registered", () => { test("the last @property declaration of a name decides what the inliner folds", () => { const consumers = ` -.parent { --flip: 10px; } +:root { --flip: 10px; } .child { width: var(--flip); } `; const child = (css: string) => diff --git a/src/__tests__/native/box-shadow.test.tsx b/src/__tests__/native/box-shadow.test.tsx index 85a809a5..b0479b58 100644 --- a/src/__tests__/native/box-shadow.test.tsx +++ b/src/__tests__/native/box-shadow.test.tsx @@ -383,10 +383,7 @@ describe("shadow values from CSS variables", () => { }); }); - // Compile-time path: lightningcss inlines the variable and processes the - // value through its CSS parser. The shorthand handler converts to native - // format without filtering — transparent shadows pass through as-is. - test("transparent shadow is preserved", () => { + test("a transparent shadow is dropped when its variable folds, as when it does not", () => { registerCSS(` :root { --my-shadow: 0 0 0 0 #0000; @@ -397,18 +394,38 @@ describe("shadow values from CSS variables", () => { render(); const component = screen.getByTestId(testID); - expect(component.props.style).toStrictEqual({ + expect(component.props.style).toStrictEqual({ boxShadow: [] }); + }); + + test("only the transparent shadows of a list are dropped", () => { + registerCSS(`.test { box-shadow: 0 0 #0000, 0 4px 6px -1px #0000001a; }`); + + render(); + + expect(screen.getByTestId(testID).props.style).toStrictEqual({ boxShadow: [ { offsetX: 0, - offsetY: 0, - blurRadius: 0, - spreadDistance: 0, - color: "#0000", + offsetY: 4, + blurRadius: 6, + spreadDistance: -1, + color: "#0000001a", }, ], }); }); + + test("a list of transparent shadows still replaces an earlier one", () => { + registerCSS( + `.shadow { box-shadow: 1px 1px #f00; } .test { box-shadow: 0 0 transparent; }`, + ); + + render(); + + expect(screen.getByTestId(testID).props.style).toStrictEqual({ + boxShadow: [], + }); + }); }); describe("shadow values from runtime variables", () => { @@ -526,12 +543,7 @@ describe("shadow values from runtime variables", () => { ]); }); - // Runtime path: variables resolve at runtime, so the shorthand handler - // processes the raw values. Transparent shadows (e.g., Tailwind v4's - // @property --tw-inset-shadow { initial-value: 0 0 0 0 #0000 }) are - // filtered out to avoid creating invisible native shadow objects that - // the renderer would still process. This is intentionally different - // from the compile-time path which preserves them. + // A transparent shadow paints nothing, so neither path hands React Native one to process test("transparent shadow is filtered", () => { registerCSS( `.test { diff --git a/src/__tests__/native/variable-fold-parity.test.tsx b/src/__tests__/native/variable-fold-parity.test.tsx new file mode 100644 index 00000000..0df6b400 --- /dev/null +++ b/src/__tests__/native/variable-fold-parity.test.tsx @@ -0,0 +1,276 @@ +import { StyleSheet } from "react-native"; + +import { render } from "@testing-library/react-native"; +import type { TokenOrValue } from "lightningcss"; +import { View } from "react-native-css/components/View"; +import { registerCSS, testID } from "react-native-css/jest"; +import { StyleCollection } from "react-native-css/native"; + +// Keyed by lightningcss's own unions, so a value kind it adds fails to compile until it is listed here +type ValueKind = TokenOrValue["type"]; +type RawTokenKind = Extract["value"]["type"]; + +interface Shape { + readonly property: string; + readonly value: string; + readonly knownDivergence?: { + readonly kept: Readonly>; + readonly openDefect: string; + }; +} + +// Normalising the variable store instead would turn `font-family: var(--v)` over `--v: red` into "#f00" +const namedColour = (kept: string) => ({ + kept: { color: kept }, + openDefect: + "the runtime hands React Native a colour read through a variable as the name it holds, where the compiler writes it as hex; processColor paints both alike", +}); + +const TOKEN_CENSUS: Record = { + "ident": [ + { property: "position", value: "absolute" }, + { property: "color", value: "red", knownDivergence: namedColour("red") }, + { + property: "color", + value: "transparent", + knownDivergence: namedColour("transparent"), + }, + { + property: "color", + value: "rebeccapurple", + knownDivergence: namedColour("rebeccapurple"), + }, + ], + "string": [{ property: "font-family", value: '"Inter"' }], + "number": [ + { property: "flex-grow", value: "2" }, + { property: "width", value: "0" }, + { property: "opacity", value: "0" }, + { property: "z-index", value: "3" }, + ], + "percentage": [ + { property: "width", value: "50%" }, + { property: "scale", value: "50%" }, + ], + "dimension": [ + { + property: "transition-duration", + value: "3s", + knownDivergence: { + kept: { transitionDuration: 3000 }, + openDefect: + "a transition longhand read through a variable leaves its element unanimated and lands in the style, where the written one reaches the animation system", + }, + }, + ], + "delim": [ + { property: "aspect-ratio", value: "16 / 9" }, + // The property parser writes a square ratio as 1 + { property: "aspect-ratio", value: "3 / 3" }, + ], + "hash": [{ property: "color", value: "#123456" }], + // Not reachable as the whole value of a custom property a style consumes. + "at-keyword": [], + "id-hash": [], + "unquoted-url": [], + "white-space": [], + "comment": [], + "colon": [], + "semicolon": [], + "comma": [], + "include-match": [], + "dash-match": [], + "prefix-match": [], + "suffix-match": [], + "substring-match": [], + "cdo": [], + "cdc": [], + "function": [], + "parenthesis-block": [], + "square-bracket-block": [], + "curly-bracket-block": [], + "bad-url": [], + "bad-string": [], + "close-parenthesis": [], + "close-square-bracket": [], + "close-curly-bracket": [], +}; + +const VALUE_CENSUS: Record = { + "token": Object.values(TOKEN_CENSUS).flat(), + "color": [ + { property: "color", value: "#12345678" }, + { property: "color", value: "rgba(255, 0, 0, 0.5)" }, + { property: "color", value: "oklch(63.7% 0.237 25.331)" }, + ], + "length": [ + { property: "width", value: "10px" }, + { property: "width", value: "0px" }, + { property: "margin-top", value: "-4px" }, + { property: "width", value: "1rem" }, + ], + "angle": [ + { + property: "rotate", + value: "45deg", + knownDivergence: { + kept: { transform: [{ rotate: "45deg" }] }, + openDefect: + "the runtime keeps `rotate`, where the compiler writes rotateZ; #389 writes rotateZ on both", + }, + }, + ], + "function": [ + { property: "width", value: "calc(10px + 2px)" }, + { property: "transform", value: "translateX(10px)" }, + ], + "var": [ + { + property: "color", + value: "var(--inner)", + knownDivergence: namedColour("teal"), + }, + ], + // Both paths share parseUnresolvedColor's channel scale, so only their agreement is claimed here + "unresolved-color": [ + { property: "color", value: "rgb(255 0 0 / var(--alpha))" }, + ], + // Not reachable, or not a style value React Native consumes. + "url": [], + "env": [], + "time": [], + "resolution": [], + "dashed-ident": [], + "animation-name": [], +}; + +const SHORTHANDS: readonly Shape[] = ( + [ + ["margin", "margin"], + ["padding", "padding"], + ["border-width", "borderWidth"], + ] as const +).map(([property, key]) => ({ + property, + value: "1px 2px", + knownDivergence: { + kept: { [key]: [1, 2] }, + openDefect: + "the runtime hands React Native a shorthand read through a variable as one list, which it does not read, where the compiler expands the written one into its sides", + }, +})); + +const SHADOW_LISTS: readonly Shape[] = [ + { property: "box-shadow", value: "1px 2px 3px 4px #123456" }, + { property: "box-shadow", value: "0 0 #0000, 1px 2px 3px 4px #123456" }, + { property: "box-shadow", value: "0 0 transparent" }, +]; + +const SHAPES: readonly Shape[] = [ + ...Object.values(VALUE_CENSUS).flat(), + ...SHORTHANDS, + ...SHADOW_LISTS, +]; + +function renderStylesheet( + css: string, + className: string, + inlineVariables: boolean, +): Record { + StyleCollection.styles.clear(); + registerCSS(css, inlineVariables ? {} : { inlineVariables: false }); + const { style } = render( + , + ).getByTestId(testID).props as { + style?: Record | Record[]; + }; + + return StyleSheet.flatten>(style ?? {}); +} + +type Path = "written" | "folded" | "kept"; + +function renderShape(shape: Shape, path: Path): Record { + const declarations = + path === "written" + ? `${shape.property}: ${shape.value};` + : `--v: ${shape.value}; ${shape.property}: var(--v);`; + + // `--inner` and `--alpha` back the shapes whose value is itself a reference + return renderStylesheet( + `.a { --inner: teal; --alpha: 0.5; ${declarations} }`, + "a", + path !== "kept", + ); +} + +test("the census covers something", () => { + expect(SHAPES.length).toBeGreaterThan(20); +}); + +describe.each(SHAPES)("$property: var(--v) over $value", (shape) => { + test("folding renders the written value", () => { + expect(renderShape(shape, "folded")).toStrictEqual( + renderShape(shape, "written"), + ); + }); + + test("a kept variable renders the written value, but for a named open defect", () => { + const written = renderShape(shape, "written"); + const kept = renderShape(shape, "kept"); + + if (shape.knownDivergence) { + expect(kept).toStrictEqual(shape.knownDivergence.kept); + return; + } + + // A shape that renders nothing would agree vacuously + expect(written).not.toStrictEqual({}); + expect(kept).toStrictEqual(written); + }); +}); + +// Each case names its own properties, because root and universal variables outlive a test +test.each([ + [ + "a declaration in a rule the element does not match", + `.p { --scope-a: 10px; } .a { width: var(--scope-a); height: 5px; }`, + "a", + ], + [ + "a declaration another rule on the element also reads", + `.a { --scope-b: 10px; width: var(--scope-b); } .b { height: var(--scope-b); }`, + "a b", + ], + [ + "a registered initial value beside a fallback block the compiler drops", + `@property --scope-c { syntax: "*"; inherits: false; initial-value: 10px; } + @supports (display: grid) { *, ::before { --scope-c: 20px; } } + .a { width: var(--scope-c); }`, + "a", + ], + [ + "a declaration inside an @supports block the compiler keeps", + `@supports (color: color-mix(in lab, red, red)) { :root { --scope-d: 10px; } } + .a { width: var(--scope-d); }`, + "a", + ], + [ + "a declaration on every element, registered inherits: false", + `@property --scope-e { syntax: ""; inherits: false; initial-value: 0px; } + * { --scope-e: 10px; } + .a { width: var(--scope-e); }`, + "a", + ], + [ + "a nested reference to a variable declared initial", + `.a { --scope-f: initial; --scope-g: var(--scope-f, 10px); width: var(--scope-g); }`, + "a", + ], +])("%s renders the same whether or not it folds", (_name, css, className) => { + const folded = renderStylesheet(css, className, true); + const kept = renderStylesheet(css, className, false); + + expect(folded).not.toStrictEqual({}); + expect(kept).toStrictEqual(folded); +}); diff --git a/src/__tests__/native/variable-inlining.test.tsx b/src/__tests__/native/variable-inlining.test.tsx new file mode 100644 index 00000000..8b9e492b --- /dev/null +++ b/src/__tests__/native/variable-inlining.test.tsx @@ -0,0 +1,152 @@ +import { act, render, screen } from "@testing-library/react-native"; +import { vars } from "react-native-css"; +import type { CompilerOptions } from "react-native-css/compiler"; +import { View } from "react-native-css/components/View"; +import { registerCSS, testID } from "react-native-css/jest"; + +import { dimensions } from "../../native/reactivity"; + +// Each test names its own properties, because root variables outlive a test + +test("a class-scoped variable does not leak into an unrelated rule", () => { + registerCSS(`.parent { --leak-a: 10px; } .child { width: var(--leak-a); }`); + + render(); + + // No `.parent` anywhere above it, so there is no `--leak-a` to read. + expect(screen.getByTestId(testID).props.style).toStrictEqual({}); +}); + +test("a class-scoped variable still reaches a descendant", () => { + registerCSS(`.parent { --leak-b: 10px; } .child { width: var(--leak-b); }`); + + render( + + + , + ); + + // The declaration has to survive the fold for this to resolve at all. + expect(screen.getByTestId(testID).props.style).toStrictEqual({ width: 10 }); +}); + +test("a variable's own value does not leak across blocks", () => { + registerCSS( + `.a { --nest-a: var(--nest-b); width: var(--nest-a); } .b { --nest-b: 10px; }`, + ); + + render(); + + // `--nest-b` belongs to `.b`. An element carrying only `.a` never had it. + expect(screen.getByTestId(testID).props.style).toStrictEqual({}); +}); + +test("a conditional :root does not fold into an unconditional rule", () => { + registerCSS(` + @media (min-width: 1000px) { :root { --cond-off: 10px; } } + .child { width: var(--cond-off); } + `); + + act(() => { + dimensions.set({ width: 500, height: 500, scale: 1, fontScale: 1 }); + }); + render(); + + // The declaration does not apply at this width, so neither does the value. + expect(screen.getByTestId(testID).props.style).toStrictEqual({}); +}); + +test("a conditional :root still applies when its query matches", () => { + registerCSS(` + @media (min-width: 1000px) { :root { --cond-on: 10px; } } + .child { width: var(--cond-on); } + `); + + act(() => { + dimensions.set({ width: 1200, height: 500, scale: 1, fontScale: 1 }); + }); + render(); + + expect(screen.getByTestId(testID).props.style).toStrictEqual({ width: 10 }); +}); + +test("a property registered with inherits: false resolves at runtime", () => { + registerCSS(` + @property --registered { syntax: ""; inherits: false; initial-value: 10px; } + :root { --registered: 20px; } + .b { width: var(--registered); } + `); + + render(); + + // CSS gives `.b` the initial 10, since :root's 20 does not inherit + expect(screen.getByTestId(testID).props.style).toStrictEqual({ width: 10 }); +}); + +test("a registered initial value applies where nothing declares the property", () => { + registerCSS(` + @property --initial-a { syntax: "*"; inherits: false; initial-value: 10px; } + @supports (display: grid) { *, ::before { --initial-a: 20px; } } + .a { width: var(--initial-a); } + `); + + render(); + + expect(screen.getByTestId(testID).props.style).toStrictEqual({ width: 10 }); +}); + +test("a declaration another rule reads survives its own fold", () => { + registerCSS( + `.a { --kept-a: 10px; width: var(--kept-a); } .b { height: var(--kept-a); }`, + ); + + render( + + + , + ); + + expect(screen.getByTestId(testID).props.style).toStrictEqual({ height: 10 }); +}); + +test("a runtime write reaches a rule that reads the variable", () => { + registerCSS(`.parent { --write-a: red; } .child { color: var(--write-a); }`); + + render( + + + , + ); + + // An inline write outranks a class declaration, which a value folded into `.child` could not express + expect(screen.getByTestId(testID).props.style).toStrictEqual({ + color: "blue", + }); +}); + +// Known limit: CSS lets the inline write win, but a fold leaves no read for it +test.each<[string, string, CompilerOptions]>([ + ["folded", "#f00", {}], + ["kept by inlineVariables: false", "blue", { inlineVariables: false }], + ["kept by exclude", "blue", { inlineVariables: { exclude: ["--write-b"] } }], +])( + "a runtime write to a reference in its declaring block, %s, renders %s", + (_path, color, options) => { + registerCSS(`.a { --write-b: red; color: var(--write-b); }`, options); + + render( + , + ); + + expect(screen.getByTestId(testID).props.style).toStrictEqual({ color }); + }, +); diff --git a/src/__tests__/native/variables.test.tsx b/src/__tests__/native/variables.test.tsx index 2f37f0d8..f382d32a 100644 --- a/src/__tests__/native/variables.test.tsx +++ b/src/__tests__/native/variables.test.tsx @@ -174,8 +174,9 @@ test("can apply and set new variables", () => { expect(screen.getByTestId(testIDs.two).props.style).toStrictEqual({ color: "#f00", }); + // `.another-class` inherits `--another-var` from `.my-class` at runtime, which carries the name as written expect(screen.getByTestId(testIDs.three).props.style).toStrictEqual({ - color: "#008000", + color: "green", }); }); @@ -201,8 +202,9 @@ test("variables will be inherited", () => { , ); + // Inherited from `.green` at runtime, which carries the name as written expect(screen.getByTestId(testIDs.three).props.style).toStrictEqual({ - color: "#008000", + color: "green", }); }); @@ -349,7 +351,8 @@ test("variable overriding with classes", () => { ); const component = screen.getByTestId(testID); - expect(component.props.style).toStrictEqual({ color: "#f00" }); + // `.test` inherits `--tier-500` from `.tier-red`, whose value the `:root` tier folded into + expect(component.props.style).toStrictEqual({ color: "red" }); }); // css-variables-1 §2.2: a custom property set to `initial` is a declaration of the guaranteed-invalid value, or of a registered initial value, so it hides an earlier rule's value and its parent's diff --git a/src/compiler/compiler.ts b/src/compiler/compiler.ts index 9082f589..82699a82 100644 --- a/src/compiler/compiler.ts +++ b/src/compiler/compiler.ts @@ -5,7 +5,6 @@ import { debug } from "debug"; import { type ContainerRule, type CustomAtRules, - type Declaration, type MediaRule, type ParsedComponent, type PropertyRule, @@ -24,7 +23,6 @@ import type { ContainerQuery, StyleDescriptor, StyleRuleMapping, - UniqueVarInfo, } from "./compiler.types"; import { parseContainerCondition } from "./container-query"; import { @@ -40,9 +38,8 @@ import { inlineVariables } from "./inline-variables"; import { extractKeyFrames } from "./keyframes"; import { lightningcssLoader } from "./lightningcss-loader"; import { parseMediaQuery } from "./media-query"; -import { isUniversalSelector } from "./selector-builder"; import { StylesheetBuilder } from "./stylesheet"; -import { supportsConditionValid } from "./supports"; +import { rulesTheCompilerKeeps, supportsConditionValid } from "./supports"; const defaultLogger = debug("react-native-css:compiler"); @@ -104,8 +101,6 @@ export function compile(code: Buffer | string, options: CompilerOptions = {}) { * Due to the above issue, we run lightningcss twice */ - const vars = new Map(); - // Determine the effective rem multiplier for compile-time inlining. // If inlineRem is explicitly set, use that. Otherwise, scan for // :root { font-size: Npx } in the CSS to allow CSS-based configuration. @@ -117,7 +112,7 @@ export function compile(code: Buffer | string, options: CompilerOptions = {}) { options.inlineRem = effectiveRem; } - const inlining = options.inlineVariables !== false; + const inlining = options.inlineVariables; const firstPassVisitor: Visitor = { // Registered from the first pass, since lightningcss prints only the last @property of a name, valid or not @@ -127,24 +122,15 @@ export function compile(code: Buffer | string, options: CompilerOptions = {}) { builder, ); - if (!inlining) { + if (inlining === false) { return sheet; } - const universalDeclarations = countUniversalDeclarations(sheet.rules); - - // A non-inheriting property has one value on every element only when universal rules are all that declare it - const runtimeVariables = new Set( - Array.from(nonInheriting).filter((name) => { - const declarations = vars.get(name)?.count; - return ( - declarations === undefined || - universalDeclarations.get(name) !== declarations - ); - }), + return inlineVariables( + sheet, + inlining?.exclude ?? [], + nonInheriting, ); - - return inlineVariables(sheet, vars, runtimeVariables); }, Rule(rule) { if ( @@ -192,32 +178,7 @@ export function compile(code: Buffer | string, options: CompilerOptions = {}) { }; } - let countVariable: ((decl: Declaration) => void) | undefined; - - if (options.inlineVariables !== false) { - const exclusionList: string[] = options.inlineVariables?.exclude ?? []; - - countVariable = (decl) => { - if ( - decl.property === "custom" && - decl.value.name.startsWith("--") && - !exclusionList.includes(decl.value.name) - ) { - const entry = vars.get(decl.value.name) ?? { - count: 0, - value: [ - ...decl.value.value, - { type: "token", value: { type: "white-space", value: " " } }, - ], - }; - entry.count++; - vars.set(decl.value.name, entry); - } - }; - } - firstPassVisitor.Declaration = (decl) => { - countVariable?.(decl); return unparseIndividualTransform(decl); }; @@ -382,10 +343,8 @@ function extractRule( } break; case "supports": - if (supportsConditionValid(rule.value.condition)) { - for (const layerRule of rule.value.rules) { - extractRule(layerRule, builder, mapping); - } + for (const supportedRule of rulesTheCompilerKeeps(rule.value)) { + extractRule(supportedRule, builder, mapping); } break; case "property": @@ -530,40 +489,6 @@ function registerProperties( return nonInheriting; } -// Counts each custom property's declarations in universal rules every element shares: at the top level, in a layer or under an @supports, whose declarations the inliner reads too, and not under @media or @container -function countUniversalDeclarations( - rules: readonly Rule[], - counts = new Map(), -) { - for (const rule of rules) { - switch (rule.type) { - case "style": - if (rule.value.selectors.some(isUniversalSelector)) { - const { declarations = [], importantDeclarations = [] } = - rule.value.declarations ?? {}; - for (const declaration of [ - ...declarations, - ...importantDeclarations, - ]) { - if (declaration.property === "custom") { - const { name } = declaration.value; - counts.set(name, (counts.get(name) ?? 0) + 1); - } - } - } - break; - case "layer-block": - countUniversalDeclarations(rule.value.rules, counts); - break; - case "supports": - countUniversalDeclarations(rule.value.rules, counts); - break; - } - } - - return counts; -} - function parsePropertyInitialValue( component: ParsedComponent, builder: StylesheetBuilder, diff --git a/src/compiler/compiler.types.ts b/src/compiler/compiler.types.ts index 7c37c775..9029dd68 100644 --- a/src/compiler/compiler.types.ts +++ b/src/compiler/compiler.types.ts @@ -177,7 +177,6 @@ export type InlineVariable = { }; export type UniqueVarInfo = { - count: number; value: TokenOrValue[] | undefined; flat?: true; }; diff --git a/src/compiler/declarations.ts b/src/compiler/declarations.ts index e7e4528a..9dc9fd59 100644 --- a/src/compiler/declarations.ts +++ b/src/compiler/declarations.ts @@ -36,7 +36,7 @@ import type { UnresolvedColor, } from "lightningcss"; -import { isStyleFunction } from "../utilities"; +import { isStyleFunction, isTransparentColor } from "../utilities"; import { isMappingProperty } from "./atRules"; import type { StyleDescriptor, @@ -1142,6 +1142,21 @@ function isSoleInitial(tokens: TokenOrValue[]) { ); } +function isRatioGroup( + group: readonly unknown[], +): group is [number, "/", number] { + return ( + group.length === 3 && + typeof group[0] === "number" && + group[1] === "/" && + typeof group[2] === "number" + ); +} + +function ratioDescriptor(width: number, height: number): StyleDescriptor { + return width === height ? 1 : `${width}/${height}`; +} + export function reduceParseUnparsed( tokenOrValues: TokenOrValue[], builder: StylesheetBuilder, @@ -1188,17 +1203,8 @@ export function reduceParseUnparsed( } else { return [[first]]; } - } else if ( - // This is a special case for values - group.includes("/") && - group.every((item) => - typeof item === "string" && item === "/" - ? item - : typeof item === "number", - ) - ) { - // eslint-disable-next-line @typescript-eslint/no-base-to-string - return [[group.join(" ")]]; + } else if (isRatioGroup(group)) { + return [[ratioDescriptor(group[0], group[2])]]; } else { return [group]; } @@ -1269,7 +1275,8 @@ export function parseUnparsed( property, allowAuto, ); - if (!args) return; + // `0` and `false` are values, not absences + if (args === undefined) return; if (Array.isArray(args) && args.length === 1) { return args[0]; } else if ( @@ -2530,11 +2537,18 @@ export function parseBoxShadow( { value }: DeclarationType<"box-shadow">, builder: StylesheetBuilder, ) { - for (const [index, shadow] of value.entries()) { - builder.addDescriptor( - `&.boxShadow.[${index}].color`, - parseColor(shadow.color, builder), - ); + const shadows = value + .map((shadow) => ({ shadow, color: parseColor(shadow.color, builder) })) + .filter(({ color }) => !isTransparentColor(color)); + + // A transparent shadow paints nothing, so it is dropped as the runtime drops one it reads from a variable + if (shadows.length === 0 && value.length > 0) { + builder.addDescriptor("box-shadow", [{}, "boxShadow", [], 1]); + return; + } + + for (const [index, { shadow, color }] of shadows.entries()) { + builder.addDescriptor(`&.boxShadow.[${index}].color`, color); builder.addDescriptor( `&.boxShadow.[${index}].offsetX`, parseLength(shadow.xOffset, builder), @@ -2648,12 +2662,7 @@ export function parseAspectRatio({ } else if (value.auto) { return "auto"; } else { - const [width, height] = value.ratio; - if (width === height) { - return 1; - } else { - return `${width}/${height}`; - } + return ratioDescriptor(...value.ratio); } } diff --git a/src/compiler/inline-variables.ts b/src/compiler/inline-variables.ts index 9158c5db..540d584c 100644 --- a/src/compiler/inline-variables.ts +++ b/src/compiler/inline-variables.ts @@ -1,37 +1,66 @@ import type { Declaration, DeclarationBlock, + Rule, + Selector, StyleSheet, TokenOrValue, UnresolvedColor, } from "lightningcss"; import type { UniqueVarInfo } from "./compiler.types"; +import { rulesTheCompilerKeeps } from "./supports"; +// A custom property is scoped to the elements its rule matches (css-variables-1 §2), so a value folds only where every matching element provably holds it export function inlineVariables( stylesheet: StyleSheet, - vars: Map, - runtimeVariables: ReadonlySet, + exclude: readonly string[], + nonInheriting: ReadonlySet, ) { - // Removed before any value flattens, since a value that refers to one is computed where it is declared - for (const [name, info] of [...vars]) { - if ( - runtimeVariables.has(name) || - refersToAny(info.value, runtimeVariables) - ) { - vars.delete(name); - } - } + emptyDroppedSupportsBlocks(stylesheet.rules); - for (const [name, info] of [...vars]) { - if (info.count !== 1) { - vars.delete(name); - } else { - flattenVar(name, vars); - } + const scope = collectVariableScope(stylesheet, exclude, nonInheriting); + + for (const name of [...scope.vars.keys()]) { + flattenVar(name, scope); } - stylesheet.rules = stylesheet.rules.map(function checkRule(rule) { + forEachDeclarationBlock(stylesheet.rules, (block) => { + foldDeclarationBlock(block, scope); + }); + + const reads = collectRuntimeReads(stylesheet.rules, scope); + + forEachDeclarationBlock(stylesheet.rules, (block) => { + removeUnreadDeclarations(block, scope, reads); + }); + + return stylesheet; +} + +interface VariableScope { + readonly vars: Map; + readonly declaringBlocks: Map; + readonly universalNames: Set; +} + +// Every matching element holds the property when its declaration is universal and unconditional, or when the reference shares its block +function canFold( + name: string, + block: DeclarationBlock | undefined, + scope: VariableScope, +) { + return ( + scope.universalNames.has(name) || + (block !== undefined && scope.declaringBlocks.get(name) === block) + ); +} + +function forEachDeclarationBlock( + rules: Rule[], + visit: (block: DeclarationBlock) => void, +): void { + for (const rule of rules) { switch (rule.type) { case "custom": case "font-face": @@ -52,107 +81,184 @@ export function inlineVariables( case "custom-media": case "scope": case "starting-style": - return rule; - - case "media": - rule.value.rules = rule.value.rules.map((rule) => checkRule(rule)); - return rule; + break; case "keyframes": - rule.value.keyframes = rule.value.keyframes.map((keyframe) => { - keyframe.declarations = - replaceDeclarationBlock(keyframe.declarations, vars) ?? - keyframe.declarations; - - return keyframe; - }); - return rule; + for (const keyframe of rule.value.keyframes) { + visit(keyframe.declarations); + } + break; case "style": - rule.value.declarations = replaceDeclarationBlock( - rule.value.declarations, - vars, - ); - - rule.value.rules = rule.value.rules?.flatMap((rule) => checkRule(rule)); - - return rule; + if (rule.value.declarations) { + visit(rule.value.declarations); + } + forEachDeclarationBlock(rule.value.rules ?? [], visit); + break; case "nested-declarations": - rule.value.declarations = - replaceDeclarationBlock(rule.value.declarations, vars) ?? {}; - return rule; + visit(rule.value.declarations); + break; + case "media": case "supports": - rule.value.rules = rule.value.rules.flatMap((rule) => checkRule(rule)); - return rule; case "layer-block": - rule.value.rules = rule.value.rules.flatMap((rule) => checkRule(rule)); - return rule; case "container": - rule.value.rules = rule.value.rules.flatMap((rule) => checkRule(rule)); - return rule; + forEachDeclarationBlock(rule.value.rules, visit); + break; } - }); + } +} - return stylesheet; +// A block the compiler drops never applies, so it is emptied before anything counts what it declares or reads +function emptyDroppedSupportsBlocks(rules: Rule[]): void { + for (const rule of rules) { + switch (rule.type) { + case "supports": + rule.value.rules = rulesTheCompilerKeeps(rule.value); + emptyDroppedSupportsBlocks(rule.value.rules); + break; + case "style": + emptyDroppedSupportsBlocks(rule.value.rules ?? []); + break; + case "media": + case "layer-block": + case "container": + emptyDroppedSupportsBlocks(rule.value.rules); + break; + default: + break; + } + } } -function replaceDeclarationBlock( - block: DeclarationBlock | undefined, - vars: Map, -) { - if (!block) return; +function declarationsOf(block: DeclarationBlock): Declaration[] { + return [ + ...(block.declarations ?? []), + ...(block.importantDeclarations ?? []), + ]; +} - block.declarations = block.declarations - ?.map((decl) => { - return replaceDeclaration(decl, vars); - }) - .filter((d) => !!d); +function foldDeclarationBlock(block: DeclarationBlock, scope: VariableScope) { + for (const declaration of declarationsOf(block)) { + if ( + declaration.property === "unparsed" || + declaration.property === "custom" + ) { + declaration.value.value = declaration.value.value.flatMap((part) => { + return flattenPart(part, scope, block); + }); + } + } +} - block.importantDeclarations = block.importantDeclarations - ?.map((decl) => { - return replaceDeclaration(decl, vars); - }) - .filter((d) => !!d); +function collectRuntimeReads(rules: Rule[], scope: VariableScope) { + const reads = new Set(); + const readsOfCandidates = new Map(); + const pending: string[] = []; - return block; -} + const read = (name: string) => { + if (!reads.has(name)) { + reads.add(name); + pending.push(name); + } + }; -function replaceDeclaration( - declaration: Declaration, - vars: Map, -) { - if ( - declaration.property !== "unparsed" && - declaration.property !== "custom" - ) { - return declaration; + forEachDeclarationBlock(rules, (block) => { + for (const declaration of declarationsOf(block)) { + if (declaration.property === "custom") { + const { name, value } = declaration.value; + + // A candidate's own value is read only while something reads the candidate + if (scope.vars.has(name)) { + const names = readsOfCandidates.get(name) ?? []; + forEachReadName(value, (readName) => names.push(readName)); + readsOfCandidates.set(name, names); + } else { + forEachReadName(value, read); + } + } else if (declaration.property === "unparsed") { + forEachReadName(declaration.value.value, read); + } + } + }); + + for (let name = pending.pop(); name !== undefined; name = pending.pop()) { + for (const readName of readsOfCandidates.get(name) ?? []) { + read(readName); + } } - if (declaration.property === "custom" && vars.has(declaration.value.name)) { - return; + return reads; +} + +function forEachReadName( + parts: TokenOrValue[], + visit: (name: string) => void, +): void { + for (const part of parts) { + switch (part.type) { + case "var": + visit(part.value.name.ident); + forEachReadName(part.value.fallback ?? [], visit); + break; + case "env": + forEachReadName(part.value.fallback ?? [], visit); + break; + case "function": + forEachReadName(part.value.arguments, visit); + break; + case "unresolved-color": + switch (part.value.type) { + case "rgb": + case "hsl": + forEachReadName(part.value.alpha, visit); + break; + case "light-dark": + forEachReadName(part.value.light, visit); + forEachReadName(part.value.dark, visit); + break; + default: + part.value satisfies never; + } + break; + default: + break; + } } +} - declaration.value.value = declaration.value.value.flatMap((part) => { - return flattenPart(part, vars); - }); +function removeUnreadDeclarations( + block: DeclarationBlock, + scope: VariableScope, + reads: Set, +) { + const isKept = (declaration: Declaration) => { + return ( + declaration.property !== "custom" || + !scope.vars.has(declaration.value.name) || + reads.has(declaration.value.name) + ); + }; - return declaration; + block.declarations = block.declarations?.filter(isKept); + block.importantDeclarations = block.importantDeclarations?.filter(isKept); } function flattenPart( part: TokenOrValue, - vars: Map, + scope: VariableScope, + block: DeclarationBlock | undefined, ): TokenOrValue | TokenOrValue[] { if (part.type === "var") { - const varInfo = vars.get(part.value.name.ident); + const name = part.value.name.ident; + const varInfo = scope.vars.get(name); - if (!varInfo) { + if (!varInfo || !canFold(name, block, scope)) { part.value.fallback = part.value.fallback?.flatMap((arg) => { - return flattenPart(arg, vars); + return flattenPart(arg, scope, block); }); return part; } else if (varInfo.value === undefined) { const fallback = part.value.fallback?.flatMap((arg) => { - return flattenPart(arg, vars); + return flattenPart(arg, scope, block); }); return fallback ?? []; @@ -161,7 +267,7 @@ function flattenPart( return varInfo.value; } else if (part.type === "function") { part.value.arguments = part.value.arguments.flatMap((arg) => { - return flattenPart(arg, vars); + return flattenPart(arg, scope, block); }); } @@ -170,33 +276,38 @@ function flattenPart( function flattenVar( name: string, - vars: Map, + scope: VariableScope, seen = new Set(), ) { if (seen.has(name)) { - vars.delete(name); + scope.vars.delete(name); } seen.add(name); - let varInfo = vars.get(name); + let varInfo = scope.vars.get(name); if (!varInfo || varInfo.flat) { return; } + // A value is substituted only into its declaring block, so a var() inside it folds on that block's terms + const declaringBlock = scope.declaringBlocks.get(name); + let varInfoValue = varInfo.value?.flatMap((part) => { if (part.type === "var") { - const name = part.value.name.ident; + const nestedName = part.value.name.ident; - flattenVar(name, vars, seen); + flattenVar(nestedName, scope, seen); - const nestedVarInfo = vars.get(part.value.name.ident); - if (nestedVarInfo?.value) { - return nestedVarInfo.value; + if (canFold(nestedName, declaringBlock, scope)) { + const nestedVarInfo = scope.vars.get(nestedName); + if (nestedVarInfo?.value) { + return nestedVarInfo.value; + } } } - return flattenPart(part, vars); + return flattenPart(part, scope, declaringBlock); }); // If the variable is shorthand for "initial", substitute it for undefined @@ -212,12 +323,211 @@ function flattenVar( } varInfo = { - count: 1, flat: true, value: varInfoValue, }; - vars.set(name, varInfo); + scope.vars.set(name, varInfo); +} + +type Reach = "every-element" | "inherited-from-root" | "matched-elements"; + +interface RuleScope { + readonly reach: Reach; + readonly conditional: boolean; +} + +interface CustomDeclaration { + readonly block: DeclarationBlock; + readonly reach: Reach; + readonly value: TokenOrValue[]; +} + +const DOCUMENT_SCOPE: RuleScope = { + reach: "matched-elements", + conditional: false, +}; + +// Separates a value spliced between tokens, as the source's own whitespace did +const VALUE_SEPARATOR: TokenOrValue = { + type: "token", + value: { type: "white-space", value: " " }, +}; + +function collectVariableScope( + stylesheet: StyleSheet, + exclude: readonly string[], + nonInheriting: ReadonlySet, +): VariableScope { + const declared = new Map(); + const initialValues = new Map(); + + const annotateBlock = (block: DeclarationBlock, ruleScope: RuleScope) => { + for (const declaration of declarationsOf(block)) { + if (declaration.property !== "custom") continue; + + const { name, value } = declaration.value; + if (!name.startsWith("--") || exclude.includes(name)) continue; + + const declarations = declared.get(name) ?? []; + declarations.push({ + block, + reach: ruleScope.conditional ? "matched-elements" : ruleScope.reach, + value, + }); + declared.set(name, declarations); + } + }; + + const annotateRule = (rule: Rule, ruleScope: RuleScope): void => { + switch (rule.type) { + case "style": { + const nested: RuleScope = { + ...ruleScope, + reach: selectorReach(rule.value.selectors, ruleScope), + }; + if (rule.value.declarations) { + annotateBlock(rule.value.declarations, nested); + } + for (const child of rule.value.rules ?? []) { + annotateRule(child, nested); + } + return; + } + case "nested-declarations": + annotateBlock(rule.value.declarations, ruleScope); + return; + case "keyframes": + for (const keyframe of rule.value.keyframes) { + annotateBlock(keyframe.declarations, { + ...ruleScope, + reach: "matched-elements", + }); + } + return; + case "media": + case "container": + for (const child of rule.value.rules) { + annotateRule(child, { + reach: "matched-elements", + conditional: true, + }); + } + return; + // Every @supports block the compiler drops is empty by now, so the ones left apply unconditionally + case "supports": + case "layer-block": + for (const child of rule.value.rules) { + annotateRule(child, ruleScope); + } + return; + case "property": + if ( + rule.value.initialValue?.type === "token-list" && + !ruleScope.conditional + ) { + initialValues.set(rule.value.name, rule.value.initialValue.value); + } + return; + default: + return; + } + }; + + for (const rule of stylesheet.rules) annotateRule(rule, DOCUMENT_SCOPE); + + const scope: VariableScope = { + vars: new Map(), + declaringBlocks: new Map(), + universalNames: new Set(), + }; + + for (const [name, declarations] of declared) { + // Which of two declarations wins depends on the element + const [declaration, ...others] = declarations; + if (!declaration || others.length > 0) continue; + + scope.vars.set(name, { value: [...declaration.value, VALUE_SEPARATOR] }); + scope.declaringBlocks.set(name, declaration.block); + + if ( + declaration.reach === "every-element" || + (declaration.reach === "inherited-from-root" && !nonInheriting.has(name)) + ) { + scope.universalNames.add(name); + } + } + + // Where nothing declares a registered property, every element holds its initial value (css-properties-values-api-1 §3.3) + for (const [name, initialValue] of initialValues) { + if (declared.has(name) || exclude.includes(name)) continue; + + scope.vars.set(name, { value: [...initialValue, VALUE_SEPARATOR] }); + scope.universalNames.add(name); + } + + // A non-inheriting property has one value on every element only when universal rules are all that declare it + const runtimeVariables = new Set( + Array.from(nonInheriting).filter((name) => { + const declarations = declared.get(name); + return declarations + ? declarations.some(({ reach }) => reach !== "every-element") + : !scope.vars.has(name); + }), + ); + + // Left to the runtime, since a value that refers to one is computed where it is declared + for (const [name, info] of [...scope.vars]) { + if ( + runtimeVariables.has(name) || + refersToAny(info.value, runtimeVariables) + ) { + scope.vars.delete(name); + scope.universalNames.delete(name); + } + } + + return scope; +} + +// A `*` in the list declares on every element, and a nested rule reaches only as far as its parent +function selectorReach(selectors: Selector[], ruleScope: RuleScope): Reach { + const reaches = selectors.map((selector): Reach => { + const meaningful = selector.filter( + (component) => component.type !== "nesting", + ); + + if (meaningful.length === 0) { + return ruleScope.reach; + } + + if (meaningful.length !== 1) { + // A compound or combined selector, such as `:root .theme`, matches less than the whole document + return "matched-elements"; + } + + const [component] = meaningful; + + switch (component?.type) { + case "universal": + return "every-element"; + case "type": + // Every element descends from html, and no other element name can be relied on + return component.name === "html" + ? "inherited-from-root" + : "matched-elements"; + case "pseudo-class": + return component.kind === "root" || component.kind === "host" + ? "inherited-from-root" + : "matched-elements"; + default: + return "matched-elements"; + } + }); + + if (reaches.includes("every-element")) return "every-element"; + if (reaches.includes("inherited-from-root")) return "inherited-from-root"; + return "matched-elements"; } function refersToAny( diff --git a/src/compiler/supports.ts b/src/compiler/supports.ts index bbd74fa7..fabd18f4 100644 --- a/src/compiler/supports.ts +++ b/src/compiler/supports.ts @@ -1,4 +1,9 @@ -import type { SupportsCondition } from "lightningcss"; +import type { Rule, SupportsCondition, SupportsRule } from "lightningcss"; + +// The compiler keeps or drops an @supports block at build time, so its rules apply unconditionally or not at all +export function rulesTheCompilerKeeps(rule: SupportsRule): Rule[] { + return supportsConditionValid(rule.condition) ? rule.rules : []; +} export function supportsConditionValid(condition: SupportsCondition): boolean { if (condition.type === "and") { diff --git a/src/native/styles/shorthands/box-shadow.ts b/src/native/styles/shorthands/box-shadow.ts index b3066f01..dec9d66a 100644 --- a/src/native/styles/shorthands/box-shadow.ts +++ b/src/native/styles/shorthands/box-shadow.ts @@ -1,6 +1,7 @@ import { isCommaList, isStyleDescriptorArray, + isTransparentColor, } from "react-native-css/utilities"; import type { StyleFunctionResolver } from "../resolve"; @@ -69,7 +70,7 @@ export const boxShadow: StyleFunctionResolver = ( function omitTransparentShadows(style: unknown) { if (typeof style === "object" && style && "color" in style) { - if (style.color === "#0000" || style.color === "transparent") { + if (isTransparentColor(style.color)) { return; } } diff --git a/src/utilities/index.ts b/src/utilities/index.ts index a421c7b6..0f96f00a 100644 --- a/src/utilities/index.ts +++ b/src/utilities/index.ts @@ -1,4 +1,5 @@ export * from "./equality"; export * from "./specificity"; export * from "./style-descriptor"; +export * from "./transparent-color"; export * from "./dot-notation.types"; diff --git a/src/utilities/transparent-color.ts b/src/utilities/transparent-color.ts new file mode 100644 index 00000000..f8dbe4d8 --- /dev/null +++ b/src/utilities/transparent-color.ts @@ -0,0 +1,4 @@ +// lightningcss writes every fully transparent colour as #0000, and a variable can still carry the keyword +export function isTransparentColor(color: unknown): boolean { + return color === "#0000" || color === "transparent"; +} From 361459cad620ec3f29f93d2871a0e0dcd18f1670 Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Sat, 21 Nov 2026 16:08:09 -0500 Subject: [PATCH 2/5] refactor(compiler): leave dropped @supports blocks to extractRule Removes the inliner's emptying of @supports blocks the compiler drops, and rulesTheCompilerKeeps with it, so extractRule decides them through supportsConditionValid as on main. It is a second bug (a dropped block's declaration still counts as one) and not the scope bug this PR fixes. Tailwind is the only producer of such a block, its @layer properties fallback, and it repeats each @property initial value there, so folding the fallback gives the same values as the registration. With the block emptied, --tw-text-shadow-color lost its only declaration, `initial`, its var() reached the runtime, and text-shadow-md rendered no shadow there (a text-shadow list read through a var() renders nothing on main too). Without it, the Tailwind scan matches main in every utility but the two arbitrary properties this PR scopes, which render the same. --- .../compiler/inline-variables.test.ts | 50 ------------------- .../native/variable-fold-parity.test.tsx | 7 --- .../native/variable-inlining.test.tsx | 1 - src/compiler/compiler.ts | 8 +-- src/compiler/inline-variables.ts | 26 ---------- src/compiler/supports.ts | 7 +-- 6 files changed, 6 insertions(+), 93 deletions(-) diff --git a/src/__tests__/compiler/inline-variables.test.ts b/src/__tests__/compiler/inline-variables.test.ts index 981879e5..f53b4fbe 100644 --- a/src/__tests__/compiler/inline-variables.test.ts +++ b/src/__tests__/compiler/inline-variables.test.ts @@ -258,43 +258,6 @@ describe("@supports is decided when the stylesheet compiles", () => { expect(foldedValue(sheet, "child", "width")).toBe(10); }); - - test("a dropped block's declarations do not apply", () => { - const sheet = compile( - `@supports (display: grid) { :root { --x: 10px; } } - .child { width: var(--x); }`, - ).stylesheet(); - - expect(foldedValue(sheet, "child", "width")).toBeUndefined(); - }); - - test("a dropped block's read keeps no declaration", () => { - const sheet = compile( - `.a { --x: 10px; height: 1px; } - @supports (display: grid) { .b { width: var(--x); } }`, - ).stylesheet(); - - expect(declaredValue(sheet, "a", "x")).toBeUndefined(); - }); - - test("a dropped block nested in a rule keeps no declaration", () => { - const sheet = compile( - `.a { --x: 10px; height: 1px; } - .b { height: 2px; @supports (display: grid) { width: var(--x); } }`, - ).stylesheet(); - - expect(declaredValue(sheet, "a", "x")).toBeUndefined(); - }); - - test("a dropped block's declaration is not a second definition", () => { - const sheet = compile( - `@supports (display: grid) { :root { --x: 20px; } } - :root { --x: 10px; } - .child { width: var(--x); }`, - ).stylesheet(); - - expect(foldedValue(sheet, "child", "width")).toBe(10); - }); }); describe("a registered property", () => { @@ -339,19 +302,6 @@ describe("a registered property", () => { expect(foldedValue(sheet, "b", "width")).toBe(10); }); - test("the initial value wins over a fallback block the compiler drops", () => { - // Tailwind's shape: the fallback serves browsers without @property, and the compiler drops it - const sheet = compile( - `@property --x { syntax: "*"; inherits: false; initial-value: 10px; } - @supports ((-webkit-hyphens: none) and (not (margin-trim: inline))) { - *, ::before, ::after, ::backdrop { --x: 20px; } - } - .b { width: var(--x); }`, - ).stylesheet(); - - expect(foldedValue(sheet, "b", "width")).toBe(10); - }); - test("a typed initial value is left to the runtime", () => { const sheet = compile( `@property --x { syntax: ""; inherits: false; initial-value: 10px; } diff --git a/src/__tests__/native/variable-fold-parity.test.tsx b/src/__tests__/native/variable-fold-parity.test.tsx index 0df6b400..26b82550 100644 --- a/src/__tests__/native/variable-fold-parity.test.tsx +++ b/src/__tests__/native/variable-fold-parity.test.tsx @@ -242,13 +242,6 @@ test.each([ `.a { --scope-b: 10px; width: var(--scope-b); } .b { height: var(--scope-b); }`, "a b", ], - [ - "a registered initial value beside a fallback block the compiler drops", - `@property --scope-c { syntax: "*"; inherits: false; initial-value: 10px; } - @supports (display: grid) { *, ::before { --scope-c: 20px; } } - .a { width: var(--scope-c); }`, - "a", - ], [ "a declaration inside an @supports block the compiler keeps", `@supports (color: color-mix(in lab, red, red)) { :root { --scope-d: 10px; } } diff --git a/src/__tests__/native/variable-inlining.test.tsx b/src/__tests__/native/variable-inlining.test.tsx index 8b9e492b..e81f14e9 100644 --- a/src/__tests__/native/variable-inlining.test.tsx +++ b/src/__tests__/native/variable-inlining.test.tsx @@ -86,7 +86,6 @@ test("a property registered with inherits: false resolves at runtime", () => { test("a registered initial value applies where nothing declares the property", () => { registerCSS(` @property --initial-a { syntax: "*"; inherits: false; initial-value: 10px; } - @supports (display: grid) { *, ::before { --initial-a: 20px; } } .a { width: var(--initial-a); } `); diff --git a/src/compiler/compiler.ts b/src/compiler/compiler.ts index 82699a82..7d27da78 100644 --- a/src/compiler/compiler.ts +++ b/src/compiler/compiler.ts @@ -39,7 +39,7 @@ import { extractKeyFrames } from "./keyframes"; import { lightningcssLoader } from "./lightningcss-loader"; import { parseMediaQuery } from "./media-query"; import { StylesheetBuilder } from "./stylesheet"; -import { rulesTheCompilerKeeps, supportsConditionValid } from "./supports"; +import { supportsConditionValid } from "./supports"; const defaultLogger = debug("react-native-css:compiler"); @@ -343,8 +343,10 @@ function extractRule( } break; case "supports": - for (const supportedRule of rulesTheCompilerKeeps(rule.value)) { - extractRule(supportedRule, builder, mapping); + if (supportsConditionValid(rule.value.condition)) { + for (const layerRule of rule.value.rules) { + extractRule(layerRule, builder, mapping); + } } break; case "property": diff --git a/src/compiler/inline-variables.ts b/src/compiler/inline-variables.ts index 540d584c..ada1f025 100644 --- a/src/compiler/inline-variables.ts +++ b/src/compiler/inline-variables.ts @@ -9,7 +9,6 @@ import type { } from "lightningcss"; import type { UniqueVarInfo } from "./compiler.types"; -import { rulesTheCompilerKeeps } from "./supports"; // A custom property is scoped to the elements its rule matches (css-variables-1 §2), so a value folds only where every matching element provably holds it export function inlineVariables( @@ -17,8 +16,6 @@ export function inlineVariables( exclude: readonly string[], nonInheriting: ReadonlySet, ) { - emptyDroppedSupportsBlocks(stylesheet.rules); - const scope = collectVariableScope(stylesheet, exclude, nonInheriting); for (const name of [...scope.vars.keys()]) { @@ -106,28 +103,6 @@ function forEachDeclarationBlock( } } -// A block the compiler drops never applies, so it is emptied before anything counts what it declares or reads -function emptyDroppedSupportsBlocks(rules: Rule[]): void { - for (const rule of rules) { - switch (rule.type) { - case "supports": - rule.value.rules = rulesTheCompilerKeeps(rule.value); - emptyDroppedSupportsBlocks(rule.value.rules); - break; - case "style": - emptyDroppedSupportsBlocks(rule.value.rules ?? []); - break; - case "media": - case "layer-block": - case "container": - emptyDroppedSupportsBlocks(rule.value.rules); - break; - default: - break; - } - } -} - function declarationsOf(block: DeclarationBlock): Declaration[] { return [ ...(block.declarations ?? []), @@ -414,7 +389,6 @@ function collectVariableScope( }); } return; - // Every @supports block the compiler drops is empty by now, so the ones left apply unconditionally case "supports": case "layer-block": for (const child of rule.value.rules) { diff --git a/src/compiler/supports.ts b/src/compiler/supports.ts index fabd18f4..bbd74fa7 100644 --- a/src/compiler/supports.ts +++ b/src/compiler/supports.ts @@ -1,9 +1,4 @@ -import type { Rule, SupportsCondition, SupportsRule } from "lightningcss"; - -// The compiler keeps or drops an @supports block at build time, so its rules apply unconditionally or not at all -export function rulesTheCompilerKeeps(rule: SupportsRule): Rule[] { - return supportsConditionValid(rule.condition) ? rule.rules : []; -} +import type { SupportsCondition } from "lightningcss"; export function supportsConditionValid(condition: SupportsCondition): boolean { if (condition.type === "and") { From bc3d926654e1975d3d50c6a9a839f8fb34d3d618 Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Sat, 21 Nov 2026 16:09:20 -0500 Subject: [PATCH 3/5] refactor(compiler): leave an undeclared registered property to the runtime Removes the inliner's fold of a `syntax: "*"` property's initial value where nothing declares it. Since #567 the stylesheet carries every registration and the runtime resolves an undeclared property to its initial value, so the fold only moved the same value to compile time; the runtime test for it, `a registered initial value applies where nothing declares the property`, passes without it. The Tailwind scan is unchanged. --- .../compiler/inline-variables.test.ts | 9 ------- src/compiler/inline-variables.ts | 24 ++++--------------- 2 files changed, 4 insertions(+), 29 deletions(-) diff --git a/src/__tests__/compiler/inline-variables.test.ts b/src/__tests__/compiler/inline-variables.test.ts index f53b4fbe..c00dcbe7 100644 --- a/src/__tests__/compiler/inline-variables.test.ts +++ b/src/__tests__/compiler/inline-variables.test.ts @@ -293,15 +293,6 @@ describe("a registered property", () => { expect(foldedValue(sheet, "b", "width")).toBe(20); }); - test("an undeclared property folds to its initial value", () => { - const sheet = compile( - `@property --x { syntax: "*"; inherits: false; initial-value: 10px; } - .b { width: var(--x); }`, - ).stylesheet(); - - expect(foldedValue(sheet, "b", "width")).toBe(10); - }); - test("a typed initial value is left to the runtime", () => { const sheet = compile( `@property --x { syntax: ""; inherits: false; initial-value: 10px; } diff --git a/src/compiler/inline-variables.ts b/src/compiler/inline-variables.ts index ada1f025..978baf42 100644 --- a/src/compiler/inline-variables.ts +++ b/src/compiler/inline-variables.ts @@ -335,7 +335,6 @@ function collectVariableScope( nonInheriting: ReadonlySet, ): VariableScope { const declared = new Map(); - const initialValues = new Map(); const annotateBlock = (block: DeclarationBlock, ruleScope: RuleScope) => { for (const declaration of declarationsOf(block)) { @@ -395,14 +394,6 @@ function collectVariableScope( annotateRule(child, ruleScope); } return; - case "property": - if ( - rule.value.initialValue?.type === "token-list" && - !ruleScope.conditional - ) { - initialValues.set(rule.value.name, rule.value.initialValue.value); - } - return; default: return; } @@ -432,21 +423,14 @@ function collectVariableScope( } } - // Where nothing declares a registered property, every element holds its initial value (css-properties-values-api-1 §3.3) - for (const [name, initialValue] of initialValues) { - if (declared.has(name) || exclude.includes(name)) continue; - - scope.vars.set(name, { value: [...initialValue, VALUE_SEPARATOR] }); - scope.universalNames.add(name); - } - // A non-inheriting property has one value on every element only when universal rules are all that declare it const runtimeVariables = new Set( Array.from(nonInheriting).filter((name) => { const declarations = declared.get(name); - return declarations - ? declarations.some(({ reach }) => reach !== "every-element") - : !scope.vars.has(name); + return ( + declarations === undefined || + declarations.some(({ reach }) => reach !== "every-element") + ); }), ); From cb13a9cee6a51217680261aa9af200d751bc8d6b Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Sat, 21 Nov 2026 16:10:40 -0500 Subject: [PATCH 4/5] refactor(compiler): leave a read through a variable as main writes it Removes the token path's ratioDescriptor, so a kept `var()` over `16 / 9` reaches the runtime as the text "16 / 9" again, not "16/9". React Native's processAspectRatio splits on "/" and trims each side, so both render the same ratio; the change only made the parity test's kept and written values equal. The parity rows now name the difference as a known one. Tailwind's aspect-* utilities read a :root theme variable, which folds, so the scan is unchanged. --- .../native/variable-fold-parity.test.tsx | 18 ++++++++-- src/compiler/declarations.ts | 35 +++++++++---------- 2 files changed, 33 insertions(+), 20 deletions(-) diff --git a/src/__tests__/native/variable-fold-parity.test.tsx b/src/__tests__/native/variable-fold-parity.test.tsx index 26b82550..a32b82b1 100644 --- a/src/__tests__/native/variable-fold-parity.test.tsx +++ b/src/__tests__/native/variable-fold-parity.test.tsx @@ -26,6 +26,12 @@ const namedColour = (kept: string) => ({ "the runtime hands React Native a colour read through a variable as the name it holds, where the compiler writes it as hex; processColor paints both alike", }); +const ratioText = (kept: string) => ({ + kept: { aspectRatio: kept }, + openDefect: + "the runtime keeps a ratio read through a variable as its text, where the compiler writes width/height; processAspectRatio reads both alike", +}); + const TOKEN_CENSUS: Record = { "ident": [ { property: "position", value: "absolute" }, @@ -64,9 +70,17 @@ const TOKEN_CENSUS: Record = { }, ], "delim": [ - { property: "aspect-ratio", value: "16 / 9" }, + { + property: "aspect-ratio", + value: "16 / 9", + knownDivergence: ratioText("16 / 9"), + }, // The property parser writes a square ratio as 1 - { property: "aspect-ratio", value: "3 / 3" }, + { + property: "aspect-ratio", + value: "3 / 3", + knownDivergence: ratioText("3 / 3"), + }, ], "hash": [{ property: "color", value: "#123456" }], // Not reachable as the whole value of a custom property a style consumes. diff --git a/src/compiler/declarations.ts b/src/compiler/declarations.ts index 9dc9fd59..aa118494 100644 --- a/src/compiler/declarations.ts +++ b/src/compiler/declarations.ts @@ -1142,21 +1142,6 @@ function isSoleInitial(tokens: TokenOrValue[]) { ); } -function isRatioGroup( - group: readonly unknown[], -): group is [number, "/", number] { - return ( - group.length === 3 && - typeof group[0] === "number" && - group[1] === "/" && - typeof group[2] === "number" - ); -} - -function ratioDescriptor(width: number, height: number): StyleDescriptor { - return width === height ? 1 : `${width}/${height}`; -} - export function reduceParseUnparsed( tokenOrValues: TokenOrValue[], builder: StylesheetBuilder, @@ -1203,8 +1188,17 @@ export function reduceParseUnparsed( } else { return [[first]]; } - } else if (isRatioGroup(group)) { - return [[ratioDescriptor(group[0], group[2])]]; + } else if ( + // This is a special case for values + group.includes("/") && + group.every((item) => + typeof item === "string" && item === "/" + ? item + : typeof item === "number", + ) + ) { + // eslint-disable-next-line @typescript-eslint/no-base-to-string + return [[group.join(" ")]]; } else { return [group]; } @@ -2662,7 +2656,12 @@ export function parseAspectRatio({ } else if (value.auto) { return "auto"; } else { - return ratioDescriptor(...value.ratio); + const [width, height] = value.ratio; + if (width === height) { + return 1; + } else { + return `${width}/${height}`; + } } } From f6b73de912ccca2cb3003f44d016e75f6f7f6fe7 Mon Sep 17 00:00:00 2001 From: Sam Moore Date: Sat, 21 Nov 2026 16:22:00 -0500 Subject: [PATCH 5/5] refactor(compiler): keep a compiled transparent box-shadow as main does Removes parseBoxShadow's filter and the shared isTransparentColor, so a box-shadow the compiler parses keeps its transparent shadows again, and restores box-shadow.test.tsx to main. A transparent shadow paints nothing, so this changes no rendering; main's own tests already pin the compile path keeping it and the runtime dropping it. The parity rows for the two transparent lists now name that difference. Tailwind's shadow utilities read their shadows through variables and take the runtime path either way, so the scan is unchanged. --- src/__tests__/native/box-shadow.test.tsx | 42 +++++++------------ .../native/variable-fold-parity.test.tsx | 26 +++++++++++- src/compiler/declarations.ts | 19 +++------ src/native/styles/shorthands/box-shadow.ts | 3 +- src/utilities/index.ts | 1 - src/utilities/transparent-color.ts | 4 -- 6 files changed, 46 insertions(+), 49 deletions(-) delete mode 100644 src/utilities/transparent-color.ts diff --git a/src/__tests__/native/box-shadow.test.tsx b/src/__tests__/native/box-shadow.test.tsx index b0479b58..85a809a5 100644 --- a/src/__tests__/native/box-shadow.test.tsx +++ b/src/__tests__/native/box-shadow.test.tsx @@ -383,7 +383,10 @@ describe("shadow values from CSS variables", () => { }); }); - test("a transparent shadow is dropped when its variable folds, as when it does not", () => { + // Compile-time path: lightningcss inlines the variable and processes the + // value through its CSS parser. The shorthand handler converts to native + // format without filtering — transparent shadows pass through as-is. + test("transparent shadow is preserved", () => { registerCSS(` :root { --my-shadow: 0 0 0 0 #0000; @@ -394,38 +397,18 @@ describe("shadow values from CSS variables", () => { render(); const component = screen.getByTestId(testID); - expect(component.props.style).toStrictEqual({ boxShadow: [] }); - }); - - test("only the transparent shadows of a list are dropped", () => { - registerCSS(`.test { box-shadow: 0 0 #0000, 0 4px 6px -1px #0000001a; }`); - - render(); - - expect(screen.getByTestId(testID).props.style).toStrictEqual({ + expect(component.props.style).toStrictEqual({ boxShadow: [ { offsetX: 0, - offsetY: 4, - blurRadius: 6, - spreadDistance: -1, - color: "#0000001a", + offsetY: 0, + blurRadius: 0, + spreadDistance: 0, + color: "#0000", }, ], }); }); - - test("a list of transparent shadows still replaces an earlier one", () => { - registerCSS( - `.shadow { box-shadow: 1px 1px #f00; } .test { box-shadow: 0 0 transparent; }`, - ); - - render(); - - expect(screen.getByTestId(testID).props.style).toStrictEqual({ - boxShadow: [], - }); - }); }); describe("shadow values from runtime variables", () => { @@ -543,7 +526,12 @@ describe("shadow values from runtime variables", () => { ]); }); - // A transparent shadow paints nothing, so neither path hands React Native one to process + // Runtime path: variables resolve at runtime, so the shorthand handler + // processes the raw values. Transparent shadows (e.g., Tailwind v4's + // @property --tw-inset-shadow { initial-value: 0 0 0 0 #0000 }) are + // filtered out to avoid creating invisible native shadow objects that + // the renderer would still process. This is intentionally different + // from the compile-time path which preserves them. test("transparent shadow is filtered", () => { registerCSS( `.test { diff --git a/src/__tests__/native/variable-fold-parity.test.tsx b/src/__tests__/native/variable-fold-parity.test.tsx index a32b82b1..1bdd3863 100644 --- a/src/__tests__/native/variable-fold-parity.test.tsx +++ b/src/__tests__/native/variable-fold-parity.test.tsx @@ -174,10 +174,32 @@ const SHORTHANDS: readonly Shape[] = ( }, })); +const transparentShadow = (kept: readonly unknown[]) => ({ + kept: { boxShadow: kept }, + openDefect: + "the runtime drops a transparent shadow read through a variable, where the compiler keeps it; neither paints anything", +}); + const SHADOW_LISTS: readonly Shape[] = [ { property: "box-shadow", value: "1px 2px 3px 4px #123456" }, - { property: "box-shadow", value: "0 0 #0000, 1px 2px 3px 4px #123456" }, - { property: "box-shadow", value: "0 0 transparent" }, + { + property: "box-shadow", + value: "0 0 #0000, 1px 2px 3px 4px #123456", + knownDivergence: transparentShadow([ + { + offsetX: 1, + offsetY: 2, + blurRadius: 3, + spreadDistance: 4, + color: "#123456", + }, + ]), + }, + { + property: "box-shadow", + value: "0 0 transparent", + knownDivergence: transparentShadow([]), + }, ]; const SHAPES: readonly Shape[] = [ diff --git a/src/compiler/declarations.ts b/src/compiler/declarations.ts index aa118494..6ab6720f 100644 --- a/src/compiler/declarations.ts +++ b/src/compiler/declarations.ts @@ -36,7 +36,7 @@ import type { UnresolvedColor, } from "lightningcss"; -import { isStyleFunction, isTransparentColor } from "../utilities"; +import { isStyleFunction } from "../utilities"; import { isMappingProperty } from "./atRules"; import type { StyleDescriptor, @@ -2531,18 +2531,11 @@ export function parseBoxShadow( { value }: DeclarationType<"box-shadow">, builder: StylesheetBuilder, ) { - const shadows = value - .map((shadow) => ({ shadow, color: parseColor(shadow.color, builder) })) - .filter(({ color }) => !isTransparentColor(color)); - - // A transparent shadow paints nothing, so it is dropped as the runtime drops one it reads from a variable - if (shadows.length === 0 && value.length > 0) { - builder.addDescriptor("box-shadow", [{}, "boxShadow", [], 1]); - return; - } - - for (const [index, { shadow, color }] of shadows.entries()) { - builder.addDescriptor(`&.boxShadow.[${index}].color`, color); + for (const [index, shadow] of value.entries()) { + builder.addDescriptor( + `&.boxShadow.[${index}].color`, + parseColor(shadow.color, builder), + ); builder.addDescriptor( `&.boxShadow.[${index}].offsetX`, parseLength(shadow.xOffset, builder), diff --git a/src/native/styles/shorthands/box-shadow.ts b/src/native/styles/shorthands/box-shadow.ts index dec9d66a..b3066f01 100644 --- a/src/native/styles/shorthands/box-shadow.ts +++ b/src/native/styles/shorthands/box-shadow.ts @@ -1,7 +1,6 @@ import { isCommaList, isStyleDescriptorArray, - isTransparentColor, } from "react-native-css/utilities"; import type { StyleFunctionResolver } from "../resolve"; @@ -70,7 +69,7 @@ export const boxShadow: StyleFunctionResolver = ( function omitTransparentShadows(style: unknown) { if (typeof style === "object" && style && "color" in style) { - if (isTransparentColor(style.color)) { + if (style.color === "#0000" || style.color === "transparent") { return; } } diff --git a/src/utilities/index.ts b/src/utilities/index.ts index 0f96f00a..a421c7b6 100644 --- a/src/utilities/index.ts +++ b/src/utilities/index.ts @@ -1,5 +1,4 @@ export * from "./equality"; export * from "./specificity"; export * from "./style-descriptor"; -export * from "./transparent-color"; export * from "./dot-notation.types"; diff --git a/src/utilities/transparent-color.ts b/src/utilities/transparent-color.ts deleted file mode 100644 index f8dbe4d8..00000000 --- a/src/utilities/transparent-color.ts +++ /dev/null @@ -1,4 +0,0 @@ -// lightningcss writes every fully transparent colour as #0000, and a variable can still carry the keyword -export function isTransparentColor(color: unknown): boolean { - return color === "#0000" || color === "transparent"; -}