From 622a46e97867d6e03781fd89aad19e7221fdbc95 Mon Sep 17 00:00:00 2001 From: Yevhenii Date: Sat, 10 Oct 2026 14:51:54 +0300 Subject: [PATCH] fix(compiler): list a stylesheet's variables in the same order on every read getNativeStyleSheet reversed each root and universal variable list in place to put the most specific value first. Reading the stylesheet again reversed the lists back, so a second read listed the unconditioned value first, and the first sheet's lists changed under it. The lists are now reversed into a copy. --- src/__tests__/compiler/compiler.test.tsx | 23 +++++++++++++++++++++++ src/compiler/stylesheet.ts | 8 ++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/__tests__/compiler/compiler.test.tsx b/src/__tests__/compiler/compiler.test.tsx index b08e24c3..3dfabb32 100644 --- a/src/__tests__/compiler/compiler.test.tsx +++ b/src/__tests__/compiler/compiler.test.tsx @@ -77,6 +77,29 @@ test(":root CSS variables with media queries", () => { }); }); +test("every read of a stylesheet lists each variable's most specific value first", () => { + const compiled = compile( + `:root { --tone: red; } + @media (prefers-color-scheme: dark) { :root { --tone: blue; } } + * { --gap: 1px; } + @media (min-width: 100px) { * { --gap: 2px; } }`, + { inlineVariables: false }, + ); + const expected = { + vr: [ + ["tone", [["blue", [["=", "prefers-color-scheme", "dark"]]], ["red"]]], + ], + vu: [["gap", [[2, [[">=", "width", 100]]], [1]]]], + }; + + const first = compiled.stylesheet(); + expect({ vr: first.vr, vu: first.vu }).toStrictEqual(expected); + + const second = compiled.stylesheet(); + expect({ vr: second.vr, vu: second.vu }).toStrictEqual(expected); + expect({ vr: first.vr, vu: first.vu }).toStrictEqual(expected); +}); + test("removes unused CSS variables while preserving the resolved value", () => { const result = compile( `.test { --blue: blue; --green: green; --red: red; color: var(--red, var(--blue)); }`, diff --git a/src/compiler/stylesheet.ts b/src/compiler/stylesheet.ts index a77fdf89..23108523 100644 --- a/src/compiler/stylesheet.ts +++ b/src/compiler/stylesheet.ts @@ -161,15 +161,15 @@ export class StylesheetBuilder { if (this.shared.rootVariables) { stylesheetOptions.vr = Object.entries(this.shared.rootVariables).map( - // Reverse these so the most specific variables are first - ([key, value]) => [key, value.reverse()] as const, + // Most specific first, on a copy: the builder can be read again + ([key, value]) => [key, value.toReversed()] as const, ); } if (this.shared.universalVariables) { stylesheetOptions.vu = Object.entries(this.shared.universalVariables).map( - // Reverse these so the most specific variables are first - ([key, value]) => [key, value.reverse()] as const, + // Most specific first, on a copy: the builder can be read again + ([key, value]) => [key, value.toReversed()] as const, ); }