From b91f1fa9891c69f07172e15f99604724331b0127 Mon Sep 17 00:00:00 2001 From: Andrea Moretti Date: Tue, 24 Nov 2026 13:46:36 +0100 Subject: [PATCH] fix: mediaquery matching on defineVars --- .../src/native/css/customProperties.js | 55 ++++++-- .../react-strict-dom/src/native/css/index.js | 19 +-- .../src/native/css/mediaQueryMatches.js | 43 ++++-- .../src/native/modules/mediaQuery.js | 1 + .../src/native/modules/mediaQuery.js.flow | 1 + .../react-strict-dom/tests/babel-test.node.js | 39 ++++++ .../tests/css/css-themes-test.native.js | 126 ++++++++++++++++++ 7 files changed, 250 insertions(+), 34 deletions(-) diff --git a/packages/react-strict-dom/src/native/css/customProperties.js b/packages/react-strict-dom/src/native/css/customProperties.js index 7389215f..5beef61f 100644 --- a/packages/react-strict-dom/src/native/css/customProperties.js +++ b/packages/react-strict-dom/src/native/css/customProperties.js @@ -8,9 +8,11 @@ */ import type { CustomProperties } from '../../types/styles'; +import type { MediaQueryContext } from './mediaQueryMatches'; import { CSSUnparsedValue } from './typed-om/CSSUnparsedValue'; import { CSSVariableReferenceValue } from './typed-om/CSSVariableReferenceValue'; +import { mediaQueryMatches } from './mediaQueryMatches'; import { warnMsg } from '../../shared/logUtils'; const memoizedValues = new Map(); @@ -40,16 +42,52 @@ export function stringContainsVariables(input: string): boolean { return input.includes('var('); } +function selectVariableValue( + value: unknown, + context: MediaQueryContext, + depth: number = 0 +): ?{ value: string | number, depth: number } { + if (typeof value === 'string' || typeof value === 'number') { + return { value, depth }; + } + if ( + value == null || + typeof value !== 'object' || + !Object.hasOwn(value, 'default') + ) { + return null; + } + + let selected = selectVariableValue(value.default, context, depth); + // StyleX emits nested conditions after shallower ones. At equal depth, + // keep the native convention of taking the last matching declaration. + for (const query in value) { + if (query.startsWith('@media') && mediaQueryMatches(query, context)) { + const match = selectVariableValue(value[query], context, depth + 1); + if ( + match != null && + (selected == null || match.depth >= selected.depth) + ) { + selected = match; + } + } + } + return selected; +} + function resolveVariableReferenceValue( propName: string, variable: CSSVariableReferenceValue, propertyRegistry: CustomProperties, - colorScheme: 'light' | 'dark' + context: MediaQueryContext ) { const variableName = normalizeVariableName(variable.variable); const fallbackValue = variable.fallback; let variableValue: unknown = propertyRegistry[variableName]; + if (variableValue != null && typeof variableValue === 'object') { + variableValue = selectVariableValue(variableValue, context)?.value; + } // Perform variable resolution on the variable's resolved value if it itself // contains variables @@ -61,25 +99,18 @@ function resolveVariableReferenceValue( propName, CSSUnparsedValue.parse(propName, variableValue), propertyRegistry, - colorScheme + context ); } if (variableValue != null) { - if (typeof variableValue === 'object' && variableValue.default != null) { - let defaultValue = variableValue.default; - if (colorScheme === 'dark') { - defaultValue = variableValue['@media (prefers-color-scheme: dark)']; - } - return defaultValue; - } return variableValue; } else if (fallbackValue != null) { const resolvedFallback = resolveVariableReferences( propName, fallbackValue, propertyRegistry, - colorScheme + context ); if (resolvedFallback != null) { return resolvedFallback; @@ -98,7 +129,7 @@ export function resolveVariableReferences( propName: string, propValue: CSSUnparsedValue, propertyRegistry: CustomProperties, - colorScheme: 'light' | 'dark' = 'light' + context: MediaQueryContext ): string | number | null { const result: Array = []; for (const value of propValue.values()) { @@ -107,7 +138,7 @@ export function resolveVariableReferences( propName, value, propertyRegistry, - colorScheme + context ); if (resolvedValue == null) { // Failure to resolve a CSS variable in a value means the entire value diff --git a/packages/react-strict-dom/src/native/css/index.js b/packages/react-strict-dom/src/native/css/index.js index bc90fe09..4415a33a 100644 --- a/packages/react-strict-dom/src/native/css/index.js +++ b/packages/react-strict-dom/src/native/css/index.js @@ -146,7 +146,6 @@ function resolveStyle( fontSize: _fontSize, hover, inheritedFontSize, - prefersReducedMotion, viewportHeight, viewportScale = 1, viewportWidth @@ -167,7 +166,7 @@ function resolveStyle( propName, styleValue, customProperties, - colorScheme + options ); if (resolvedValue != null) { stylesToReprocess[propName] = resolvedValue; @@ -244,16 +243,12 @@ function resolveStyle( // Just picks the last MQ in order that matches. // TODO: decide how StyleX should handle multiple MQs. for (const variant in styleValue) { - if (variant.startsWith('@media') && variant !== mqDark) { - const matches = mediaQueryMatches( - variant, - viewportWidth, - viewportHeight, - prefersReducedMotion - ); - if (matches) { - activeVariant = variant; - } + if ( + variant.startsWith('@media') && + variant !== mqDark && + mediaQueryMatches(variant, options) + ) { + activeVariant = variant; } } stylesToReprocess[propName] = styleValue[activeVariant]; diff --git a/packages/react-strict-dom/src/native/css/mediaQueryMatches.js b/packages/react-strict-dom/src/native/css/mediaQueryMatches.js index 6fc59889..f12ed997 100644 --- a/packages/react-strict-dom/src/native/css/mediaQueryMatches.js +++ b/packages/react-strict-dom/src/native/css/mediaQueryMatches.js @@ -11,18 +11,41 @@ import { mediaQuery } from '../modules/mediaQuery'; const MEDIA = '@media'; +export type MediaQueryContext = Readonly<{ + colorScheme: ?('light' | 'dark'), + prefersReducedMotion: boolean, + viewportHeight: number, + viewportWidth: number, + ... +}>; + export function mediaQueryMatches( query: string, - width: number, - height: number, - prefersReducedMotion: boolean + context: MediaQueryContext ): boolean { + const { + colorScheme, + prefersReducedMotion, + viewportHeight: height, + viewportWidth: width + } = context; const q = query.split(MEDIA)[1]; - return mediaQuery.match(q, { - width: width, - height: height, - orientation: width > height ? 'landscape' : 'portrait', - 'aspect-ratio': width / height, - 'prefers-reduced-motion': prefersReducedMotion ? 'reduce' : 'no-preference' - }); + try { + return mediaQuery.match(q, { + width, + height, + orientation: width > height ? 'landscape' : 'portrait', + 'aspect-ratio': width / height, + 'prefers-color-scheme': colorScheme ?? 'light', + 'prefers-reduced-motion': prefersReducedMotion + ? 'reduce' + : 'no-preference' + }); + } catch (error) { + // A valid web query may use syntax the native parser does not support. + if (error instanceof SyntaxError || error instanceof TypeError) { + return false; + } + throw error; + } } diff --git a/packages/react-strict-dom/src/native/modules/mediaQuery.js b/packages/react-strict-dom/src/native/modules/mediaQuery.js index 144569d0..c65048b9 100644 --- a/packages/react-strict-dom/src/native/modules/mediaQuery.js +++ b/packages/react-strict-dom/src/native/modules/mediaQuery.js @@ -89,6 +89,7 @@ function matchQuery(mediaQuery, values) { } switch (feature) { + case 'prefers-color-scheme': case 'prefers-reduced-motion': case 'orientation': case 'scan': diff --git a/packages/react-strict-dom/src/native/modules/mediaQuery.js.flow b/packages/react-strict-dom/src/native/modules/mediaQuery.js.flow index 9b2f81d4..0e9b8cc9 100644 --- a/packages/react-strict-dom/src/native/modules/mediaQuery.js.flow +++ b/packages/react-strict-dom/src/native/modules/mediaQuery.js.flow @@ -14,6 +14,7 @@ type MediaQueryValues = Readonly<{ orientation?: 'landscape' | 'portrait', 'aspect-ratio'?: number, direction?: 'ltr' | 'rtl', + 'prefers-color-scheme'?: 'light' | 'dark', 'prefers-reduced-motion'?: 'reduce' | 'no-preference', }>; diff --git a/packages/react-strict-dom/tests/babel-test.node.js b/packages/react-strict-dom/tests/babel-test.node.js index cd78f938..d3c3f053 100644 --- a/packages/react-strict-dom/tests/babel-test.node.js +++ b/packages/react-strict-dom/tests/babel-test.node.js @@ -27,6 +27,45 @@ function transform(source, pluginOptions = {}) { } describe('react-strict-dom/babel-preset', () => { + test('emits base and nested media declarations for variables', () => { + const { metadata } = transformSync( + ` + import { css } from 'react-strict-dom'; + export const tokens = css.defineVars({ + '--rsd-size': { + default: '1rem', + '@media (min-width: 400px)': { + default: '2rem', + '@media (prefers-color-scheme: dark)': '3rem' + }, + '@media (prefers-color-scheme: dark)': '1.5rem' + }, + '--rsd-opacity': { + default: null, + '@media (min-width: 400px)': 0 + } + }); + `, + { + filename: 'tokens.css.js', + presets: [[reactStrictPreset, { debug: false }]] + } + ); + const css = reactStrictPreset.generateStyles(metadata.stylex); + expect(css.split('\n')).toEqual([ + expect.stringMatching(/^:root.*\{--rsd-size:1rem;\}$/), + expect.stringMatching( + /^@media \(prefers-color-scheme: dark\).*--rsd-size:1\.5rem;/ + ), + expect.stringMatching( + /^@media \(min-width: 400px\).*--rsd-size:2rem;--rsd-opacity:0;/ + ), + expect.stringMatching( + /^@media \(prefers-color-scheme: dark\).*@media \(min-width: 400px\).*--rsd-size:3rem;/ + ) + ]); + }); + describe('[transform] ignore unrelated elements', () => { test('noop
', () => { expect( diff --git a/packages/react-strict-dom/tests/css/css-themes-test.native.js b/packages/react-strict-dom/tests/css/css-themes-test.native.js index 9186d0d7..93addeb9 100644 --- a/packages/react-strict-dom/tests/css/css-themes-test.native.js +++ b/packages/react-strict-dom/tests/css/css-themes-test.native.js @@ -210,4 +210,130 @@ describe('css.* themes', () => { }); expect(root.toJSON()).toMatchSnapshot(); }); + + test.each(['light', 'dark'])( + 'updates a width-dependent variable in %s mode', + (colorScheme) => { + const tokens = css.defineVars({ + fontSize: { + default: '1rem', + '@media (min-width: 400px)': '2rem' + } + }); + const styles = css.create({ text: { fontSize: tokens.fontSize } }); + ReactNative.useColorScheme.mockReturnValue(colorScheme); + ReactNative.useWindowDimensions.mockReturnValue({ + fontScale: 1, + height: 1000, + width: 200 + }); + let root; + act(() => { + root = create(); + }); + expect(root.toJSON().props.style.fontSize).toBe(16); + + ReactNative.useWindowDimensions.mockReturnValue({ + fontScale: 1, + height: 1000, + width: 400 + }); + act(() => { + root.update(); + }); + expect(root.toJSON().props.style.fontSize).toBe(32); + } + ); + + test('resolves nested media, aliases and omitted variable declarations', () => { + const wide = '@media (min-width: 400px)'; + const dark = '@media (prefers-color-scheme: dark)'; + const tokens = css.defineVars({ + size: { + default: '1rem', + [wide]: { default: '2rem', [dark]: '3rem' }, + [dark]: '1.5rem' + }, + opacity: { default: null, [wide]: 0 }, + color: { default: 'red', [dark]: null }, + width: { default: '10px', '@media (width >= 400px)': '20px' } + }); + const aliases = css.defineVars({ + fontSize: { default: '1rem', [wide]: tokens.size } + }); + const styles = css.create({ + text: { + color: tokens.color, + fontSize: aliases.fontSize, + minWidth: tokens.width, + opacity: tokens.opacity.replace(')', ', 1)') + } + }); + ReactNative.useColorScheme.mockReturnValue('dark'); + ReactNative.useWindowDimensions.mockReturnValue({ + fontScale: 1, + height: 1000, + width: 200 + }); + let root; + act(() => { + root = create(); + }); + expect(root.toJSON().props.style).toMatchObject({ + color: 'red', + fontSize: 16, + minWidth: 10, + opacity: 1 + }); + + ReactNative.useWindowDimensions.mockReturnValue({ + fontScale: 1, + height: 1000, + width: 400 + }); + act(() => { + root.update(); + }); + expect(root.toJSON().props.style).toMatchObject({ + color: 'red', + fontSize: 48, + minWidth: 10, + opacity: 0 + }); + }); + + test('matches compound media in scoped theme overrides', () => { + const tokens = css.defineVars({ color: 'red' }); + const theme = css.createTheme(tokens, { + color: { + default: 'blue', + '@media (min-width: 400px) and (prefers-color-scheme: dark)': 'green' + } + }); + const styles = css.create({ text: { color: tokens.color } }); + ReactNative.useWindowDimensions.mockReturnValue({ + height: 1000, + width: 400 + }); + const render = () => ( + <> + + + + + + ); + let root; + act(() => { + root = create(render()); + }); + expect(root.toJSON()[1].children[0].props.style.color).toBe('blue'); + + ReactNative.useColorScheme.mockReturnValue('dark'); + act(() => { + root.update(render()); + }); + expect(root.toJSON()[0].props.style.color).toBe('red'); + expect(root.toJSON()[1].children[0].props.style.color).toBe('green'); + }); });