Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 43 additions & 12 deletions packages/react-strict-dom/src/native/css/customProperties.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>();
Expand Down Expand Up @@ -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
Expand All @@ -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;
Expand All @@ -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<unknown> = [];
for (const value of propValue.values()) {
Expand All @@ -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
Expand Down
19 changes: 7 additions & 12 deletions packages/react-strict-dom/src/native/css/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,6 @@ function resolveStyle(
fontSize: _fontSize,
hover,
inheritedFontSize,
prefersReducedMotion,
viewportHeight,
viewportScale = 1,
viewportWidth
Expand All @@ -167,7 +166,7 @@ function resolveStyle(
propName,
styleValue,
customProperties,
colorScheme
options
);
if (resolvedValue != null) {
stylesToReprocess[propName] = resolvedValue;
Expand Down Expand Up @@ -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];
Expand Down
43 changes: 33 additions & 10 deletions packages/react-strict-dom/src/native/css/mediaQueryMatches.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
1 change: 1 addition & 0 deletions packages/react-strict-dom/src/native/modules/mediaQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ function matchQuery(mediaQuery, values) {
}

switch (feature) {
case 'prefers-color-scheme':
case 'prefers-reduced-motion':
case 'orientation':
case 'scan':
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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',
}>;

Expand Down
39 changes: 39 additions & 0 deletions packages/react-strict-dom/tests/babel-test.node.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 <div>', () => {
expect(
Expand Down
126 changes: 126 additions & 0 deletions packages/react-strict-dom/tests/css/css-themes-test.native.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(<html.span style={styles.text} />);
});
expect(root.toJSON().props.style.fontSize).toBe(16);

ReactNative.useWindowDimensions.mockReturnValue({
fontScale: 1,
height: 1000,
width: 400
});
act(() => {
root.update(<html.span style={styles.text} />);
});
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(<html.span style={styles.text} />);
});
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(<html.span style={styles.text} />);
});
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 = () => (
<>
<html.span style={styles.text} />
<html.div style={theme}>
<html.span style={styles.text} />
</html.div>
</>
);
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');
});
});
Loading