Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(build): preserve @media wrappers in per-component CSS extraction (#957)

Cindy Zhangd92510b999fa
diff --git a/scripts/build-css.mjs b/scripts/build-css.mjs
index aaa757cbb3..0efb32198e 100644
--- a/scripts/build-css.mjs
+++ b/scripts/build-css.mjs
@@ -123,23 +123,95 @@ async function collectStyleXCSS() {
/**
* Given a list of StyleX rules, produce CSS via the official processor
* and parse it into individual rule entries: { className, rule (full text) }
+ *
+ * Handles @media and other at-rule wrappers by preserving them around the
+ * inner rule. For example:
+ * @media (prefers-reduced-motion: reduce){.x1{transition-duration:0s}}
+ * is parsed as a single entry with the full @media wrapper intact.
*/
function parseRulesFromCSS(css) {
const entries = [];
- // Match each rule: .className...{ ... }
- // StyleX rules can have :not(#\#) and pseudo-selectors
- const ruleRegex = /(\.[a-z][a-z0-9_-]+[^{}]*)\{([^}]+)\}/g;
- let match;
- while ((match = ruleRegex.exec(css)) !== null) {
- const selector = match[1].trim();
- const className = selector.match(/^(\.[a-z][a-z0-9_-]+)/)?.[1];
- if (className) {
- entries.push({className, fullRule: match[0]});
+ let i = 0;
+
+ while (i < css.length) {
+ // Skip whitespace and newlines
+ while (i < css.length && /\s/.test(css[i])) i++;
+ if (i >= css.length) break;
+
+ // Detect at-rules (@media, @keyframes, etc.)
+ if (css[i] === '@') {
+ // Find the opening brace of the at-rule
+ const atStart = i;
+ const braceIdx = css.indexOf('{', i);
+ if (braceIdx === -1) break;
+
+ const atPrelude = css.slice(atStart, braceIdx).trim();
+
+ // Skip @keyframes entirely — they aren't component-splittable rules
+ if (atPrelude.startsWith('@keyframes')) {
+ // Jump past the balanced braces
+ i = findClosingBrace(css, braceIdx);
+ continue;
+ }
+
+ // For @media and other conditional at-rules, extract inner rules
+ // and wrap each one with the at-rule prelude
+ const closeIdx = findClosingBrace(css, braceIdx);
+ const innerCSS = css.slice(braceIdx + 1, closeIdx - 1);
+ const innerEntries = parseRulesFromCSS(innerCSS);
+
+ for (const entry of innerEntries) {
+ entries.push({
+ className: entry.className,
+ fullRule: `${atPrelude}{${entry.fullRule}}`,
+ });
+ }
+
+ i = closeIdx;
+ continue;
+ }
+
+ // Regular rule: .className...{ declarations }
+ if (css[i] === '.') {
+ const ruleStart = i;
+ const braceIdx = css.indexOf('{', i);
+ if (braceIdx === -1) break;
+
+ const closeIdx = findClosingBrace(css, braceIdx);
+ const fullRule = css.slice(ruleStart, closeIdx).trim();
+ const selector = css.slice(ruleStart, braceIdx).trim();
+ const className = selector.match(/^(\.[a-z][a-z0-9_-]+)/)?.[1];
+
+ if (className) {
+ entries.push({className, fullRule});
+ }
+
+ i = closeIdx;
+ continue;
}
+
+ // Skip anything else (comments, etc.)
+ i++;
}
+
return entries;
}
+/**
+ * Find the index just past the closing brace that matches the opening brace
+ * at `openIdx`. Handles nested braces.
+ */
+function findClosingBrace(css, openIdx) {
+ let depth = 1;
+ let i = openIdx + 1;
+ while (i < css.length && depth > 0) {
+ if (css[i] === '{') depth++;
+ else if (css[i] === '}') depth--;
+ i++;
+ }
+ return i;
+}
+
function wrapInLayer(css, comment) {
if (!css.trim()) return '';
return `/* ${comment} */
diff --git a/scripts/build-css.test.mjs b/scripts/build-css.test.mjs
new file mode 100644
index 0000000000..9a2ed362ac
--- /dev/null
+++ b/scripts/build-css.test.mjs
@@ -0,0 +1,184 @@
+/**
+ * @file build-css.test.mjs
+ * Integration test for build-css.mjs
+ *
+ * Validates that the CSS splitting pipeline (common.css + per-component styles.css)
+ * preserves all @media wrappers from the combined xds.css output.
+ *
+ * The combined xds.css writes directly from processStylexRules and is always correct.
+ * common.css and per-component styles.css go through parseRulesFromCSS, which is the
+ * code under test — a regression in that parser silently stripped @media wrappers,
+ * causing conditional rules (prefers-reduced-motion, hover, prefers-contrast) to apply
+ * unconditionally. See #952, #957.
+ */
+
+import {describe, it, expect, beforeAll} from 'vitest';
+import fs from 'fs/promises';
+import path from 'path';
+import {fileURLToPath} from 'url';
+import {execSync} from 'child_process';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.resolve(__dirname, '..');
+const CORE_DIST = path.resolve(ROOT, 'packages/core/dist');
+
+/**
+ * Extract all @media blocks from a CSS string.
+ * Returns an array of the full @media rule strings.
+ */
+function extractMediaRules(css) {
+ const rules = [];
+ let i = 0;
+ while (i < css.length) {
+ // Find @media
+ const idx = css.indexOf('@media', i);
+ if (idx === -1) break;
+
+ // Find the opening brace
+ const braceStart = css.indexOf('{', idx);
+ if (braceStart === -1) break;
+
+ // Balance braces to find the end
+ let depth = 1;
+ let j = braceStart + 1;
+ while (j < css.length && depth > 0) {
+ if (css[j] === '{') depth++;
+ else if (css[j] === '}') depth--;
+ j++;
+ }
+
+ rules.push(css.slice(idx, j).trim());
+ i = j;
+ }
+ return rules;
+}
+
+describe('build-css @media preservation', () => {
+ let xdsCss;
+ let commonCss;
+ let componentCssFiles;
+
+ beforeAll(async () => {
+ // Build core first (build-css needs compiled source)
+ console.log('Running yarn build...');
+ execSync('yarn build', {cwd: ROOT, stdio: 'pipe', timeout: 120_000});
+
+ // Read the outputs
+ xdsCss = await fs.readFile(path.join(CORE_DIST, 'xds.css'), 'utf8');
+ commonCss = await fs.readFile(path.join(CORE_DIST, 'common.css'), 'utf8');
+
+ // Collect all per-component styles.css files
+ componentCssFiles = {};
+ const entries = await fs.readdir(CORE_DIST, {withFileTypes: true});
+ for (const entry of entries) {
+ if (entry.isDirectory()) {
+ const stylesPath = path.join(CORE_DIST, entry.name, 'styles.css');
+ try {
+ componentCssFiles[entry.name] = await fs.readFile(stylesPath, 'utf8');
+ } catch {
+ // No styles.css for this component — that's fine
+ }
+ }
+ }
+ }, 180_000);
+
+ it('xds.css contains @media rules', () => {
+ const mediaRules = extractMediaRules(xdsCss);
+ expect(mediaRules.length).toBeGreaterThan(0);
+ console.log(`xds.css has ${mediaRules.length} @media rules`);
+ });
+
+ it('combined split CSS has the same @media count as xds.css', () => {
+ const xdsMedia = extractMediaRules(xdsCss);
+
+ // Collect @media rules from common.css + all per-component files
+ let splitMedia = extractMediaRules(commonCss);
+ for (const [name, css] of Object.entries(componentCssFiles)) {
+ splitMedia = splitMedia.concat(extractMediaRules(css));
+ }
+
+ console.log(`xds.css @media rules: ${xdsMedia.length}`);
+ console.log(
+ `Split CSS @media rules: ${splitMedia.length} (common: ${extractMediaRules(commonCss).length})`,
+ );
+
+ expect(splitMedia.length).toBe(xdsMedia.length);
+ });
+
+ it('common.css contains prefers-reduced-motion rules', () => {
+ const mediaRules = extractMediaRules(commonCss);
+ const motionRules = mediaRules.filter(r =>
+ r.includes('prefers-reduced-motion'),
+ );
+ expect(motionRules.length).toBeGreaterThan(0);
+ console.log(
+ `common.css has ${motionRules.length} prefers-reduced-motion rules`,
+ );
+ });
+
+ it('no transition-duration:0s rules appear outside @media blocks', () => {
+ // The bug caused rules like .x12w9bfk.x12w9bfk{transition-duration:0s}
+ // to appear WITHOUT their @media wrapper. Check that any rule with
+ // transition-duration:0s is inside an @media block.
+ const allSplitCss =
+ commonCss + '\n' + Object.values(componentCssFiles).join('\n');
+
+ // Find all transition-duration:0s rules
+ const zeroTransitionRegex =
+ /\.[a-z][a-z0-9_-]+[^{}]*\{[^}]*transition-duration:\s*0s[^}]*\}/g;
+ const matches = [...allSplitCss.matchAll(zeroTransitionRegex)];
+
+ for (const match of matches) {
+ const position = match.index;
+
+ // Check if this rule is inside an @media block by looking backwards
+ const before = allSplitCss.slice(0, position);
+ const mediaStarts = [...before.matchAll(/@media[^{]*\{/g)];
+ const isWrapped = mediaStarts.some(m => {
+ const mediaStart = m.index;
+ const afterMedia = allSplitCss.slice(mediaStart);
+ let depth = 0;
+ for (let i = 0; i < afterMedia.length; i++) {
+ if (afterMedia[i] === '{') depth++;
+ else if (afterMedia[i] === '}') {
+ depth--;
+ if (depth === 0) {
+ return mediaStart + i > position;
+ }
+ }
+ }
+ return false;
+ });
+
+ expect(isWrapped).toBe(true);
+ }
+
+ if (matches.length > 0) {
+ console.log(
+ `Verified ${matches.length} transition-duration:0s rules are all inside @media blocks`,
+ );
+ }
+ });
+
+ it('every @media variant from xds.css exists in split CSS', () => {
+ const preludeRegex = /@media\s*\([^)]+\)/g;
+
+ const xdsVariants = new Set(
+ [...xdsCss.matchAll(preludeRegex)].map(m => m[0]),
+ );
+ const splitCss =
+ commonCss + '\n' + Object.values(componentCssFiles).join('\n');
+ const splitVariants = new Set(
+ [...splitCss.matchAll(preludeRegex)].map(m => m[0]),
+ );
+
+ console.log(`xds.css @media variants: ${[...xdsVariants].join(', ')}`);
+ console.log(
+ `Split CSS @media variants: ${[...splitVariants].join(', ')}`,
+ );
+
+ for (const variant of xdsVariants) {
+ expect(splitVariants.has(variant)).toBe(true);
+ }
+ });
+});
diff --git a/vitest.config.ts b/vitest.config.ts
index 310a119459..f375a17103 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -54,6 +54,7 @@ export default defineConfig({
include: [
'packages/**/src/**/*.test.{ts,tsx,mjs}',
'internal/**/*.test.{ts,tsx,mjs}',
+ 'scripts/**/*.test.{ts,tsx,mjs}',
],
coverage: {
provider: 'v8',