diff --git a/src/__tests__/compiler/inline-variables.test.ts b/src/__tests__/compiler/inline-variables.test.ts new file mode 100644 index 00000000..c00dcbe7 --- /dev/null +++ b/src/__tests__/compiler/inline-variables.test.ts @@ -0,0 +1,377 @@ +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); + }); +}); + +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("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/variable-fold-parity.test.tsx b/src/__tests__/native/variable-fold-parity.test.tsx new file mode 100644 index 00000000..1bdd3863 --- /dev/null +++ b/src/__tests__/native/variable-fold-parity.test.tsx @@ -0,0 +1,305 @@ +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 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" }, + { 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", + knownDivergence: ratioText("16 / 9"), + }, + // The property parser writes a square ratio as 1 + { + 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. + "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 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", + 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[] = [ + ...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 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..e81f14e9 --- /dev/null +++ b/src/__tests__/native/variable-inlining.test.tsx @@ -0,0 +1,151 @@ +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; } + .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..7d27da78 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,7 +38,6 @@ 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"; @@ -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); }; @@ -530,40 +491,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..6ab6720f 100644 --- a/src/compiler/declarations.ts +++ b/src/compiler/declarations.ts @@ -1269,7 +1269,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 ( diff --git a/src/compiler/inline-variables.ts b/src/compiler/inline-variables.ts index 9158c5db..978baf42 100644 --- a/src/compiler/inline-variables.ts +++ b/src/compiler/inline-variables.ts @@ -1,6 +1,8 @@ import type { Declaration, DeclarationBlock, + Rule, + Selector, StyleSheet, TokenOrValue, UnresolvedColor, @@ -8,30 +10,54 @@ import type { import type { UniqueVarInfo } from "./compiler.types"; +// 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); - } - } + const scope = collectVariableScope(stylesheet, exclude, nonInheriting); - for (const [name, info] of [...vars]) { - if (info.count !== 1) { - vars.delete(name); - } else { - flattenVar(name, vars); - } + 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 +78,162 @@ 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; +function declarationsOf(block: DeclarationBlock): Declaration[] { + return [ + ...(block.declarations ?? []), + ...(block.importantDeclarations ?? []), + ]; } -function replaceDeclarationBlock( - block: DeclarationBlock | undefined, - vars: Map, -) { - if (!block) return; +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.declarations = block.declarations - ?.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[] = []; - block.importantDeclarations = block.importantDeclarations - ?.map((decl) => { - return replaceDeclaration(decl, vars); - }) - .filter((d) => !!d); + const read = (name: string) => { + if (!reads.has(name)) { + reads.add(name); + pending.push(name); + } + }; - return block; -} + 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); + } + } + }); -function replaceDeclaration( - declaration: Declaration, - vars: Map, -) { - if ( - declaration.property !== "unparsed" && - declaration.property !== "custom" - ) { - return declaration; + 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 +242,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 +251,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 +298,194 @@ 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 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; + case "supports": + case "layer-block": + for (const child of rule.value.rules) { + annotateRule(child, ruleScope); + } + 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); + } + } + + // 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 === undefined || + declarations.some(({ reach }) => reach !== "every-element") + ); + }), + ); + + // 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(