From 392e1e026c07ef8c178e65ccba8294b73e31c40c Mon Sep 17 00:00:00 2001 From: Mathieu Acthernoene Date: Thu, 12 Nov 2026 12:27:02 +0000 Subject: [PATCH 1/6] WIP --- .../Animated/components/AnimatedScrollView.js | 7 +- .../Components/TextInput/TextInput.js | 3 +- .../Libraries/Image/Image.android.js | 8 +- .../react-native/Libraries/Image/Image.ios.js | 12 +- .../ReactNativeAttributePayload.js | 204 +++++++++--- .../Libraries/StyleSheet/StyleSheetTypes.js | 49 ++- .../__tests__/MediaQueries-itest.js | 295 ++++++++++++++++++ .../Libraries/StyleSheet/splitLayoutProps.js | 14 +- packages/react-native/Libraries/Text/Text.js | 5 +- .../react-native/React/Fabric/RCTScheduler.h | 6 + .../react-native/React/Fabric/RCTScheduler.mm | 5 + .../React/Fabric/RCTSurfacePresenter.mm | 28 ++ .../react/fabric/FabricUIManager.java | 16 + .../react/fabric/FabricUIManagerBinding.kt | 2 + .../react/fabric/MediaFeaturesObserver.kt | 161 ++++++++++ .../facebook/react/runtime/ReactHostImpl.kt | 3 + .../react/fabric/FabricUIManagerBinding.cpp | 21 ++ .../jni/react/fabric/FabricUIManagerBinding.h | 2 + .../core/ConcreteComponentDescriptor.h | 19 +- .../react/renderer/core/ConditionalProps.cpp | 131 ++++++++ .../react/renderer/core/ConditionalProps.h | 73 +++++ .../react/renderer/core/MediaFeatures.cpp | 170 ++++++++++ .../react/renderer/core/MediaFeatures.h | 72 +++++ .../ReactCommon/react/renderer/core/Props.cpp | 4 +- .../ReactCommon/react/renderer/core/Props.h | 16 +- .../react/renderer/core/RawProps.cpp | 13 + .../react/renderer/core/RawProps.h | 6 + .../react/renderer/core/React/RendererCore.h | 2 + .../core/tests/ConditionalPropsTest.cpp | 158 ++++++++++ .../renderer/core/tests/MediaFeaturesTest.cpp | 116 +++++++ .../react/renderer/scheduler/Scheduler.cpp | 18 ++ .../react/renderer/scheduler/Scheduler.h | 14 + .../react/renderer/uimanager/UIManager.h | 8 + .../UIManagerUpdateConditionalProps.cpp | 89 ++++++ packages/react-native/ReactNativeApi.d.ts | 163 +++++----- .../stylesheet-media-queries.tsx | 40 +++ packages/react-native/package.json | 4 +- .../testing/fantom/specs/NativeFantom.js | 1 + .../examples/Playground/RNTesterPlayground.js | 226 +++++++++++++- private/react-native-fantom/src/index.js | 24 ++ .../tester/src/NativeFantom.cpp | 17 + .../tester/src/NativeFantom.h | 2 + .../api-snapshots/ReactAppleDebugCxx.api | 39 +++ .../api-snapshots/ReactAppleFrameworksCxx.api | 41 +++ .../api-snapshots/ReactAppleNewarchCxx.api | 39 +++ .../api-snapshots/ReactAppleReleaseCxx.api | 39 +++ .../api-snapshots/ReactCommonDebugCxx.api | 38 +++ .../ReactCommonFrameworksCxx.api | 40 +++ .../api-snapshots/ReactCommonNewarchCxx.api | 38 +++ .../api-snapshots/ReactCommonReleaseCxx.api | 38 +++ yarn.lock | 8 +- 51 files changed, 2401 insertions(+), 146 deletions(-) create mode 100644 packages/react-native/Libraries/StyleSheet/__tests__/MediaQueries-itest.js create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt create mode 100644 packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.cpp create mode 100644 packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.h create mode 100644 packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp create mode 100644 packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h create mode 100644 packages/react-native/ReactCommon/react/renderer/core/tests/ConditionalPropsTest.cpp create mode 100644 packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp create mode 100644 packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerUpdateConditionalProps.cpp create mode 100644 packages/react-native/__typetests__/stylesheet-media-queries.tsx diff --git a/packages/react-native/Libraries/Animated/components/AnimatedScrollView.js b/packages/react-native/Libraries/Animated/components/AnimatedScrollView.js index 1607ebf96b34..67807aa80504 100644 --- a/packages/react-native/Libraries/Animated/components/AnimatedScrollView.js +++ b/packages/react-native/Libraries/Animated/components/AnimatedScrollView.js @@ -8,7 +8,10 @@ * @format */ -import type {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; +import type { + ViewStyle, + WithConditionalStyleValues, +} from '../../StyleSheet/StyleSheetTypes'; import type { AnimatedComponentType, AnimatedProps, @@ -99,7 +102,7 @@ const AnimatedScrollViewWithInvertedRefreshControl = // Handle animated props on `refreshControl`. const [refreshControlAnimatedProps, refreshControlRef] = useAnimatedProps< - {style: ?ViewStyle}, + {style: ?WithConditionalStyleValues}, $FlowFixMe, >(intermediatePropsForRefreshControl); // NOTE: Assumes that refreshControl.ref` and `refreshControl.style` can be diff --git a/packages/react-native/Libraries/Components/TextInput/TextInput.js b/packages/react-native/Libraries/Components/TextInput/TextInput.js index 77dcb9829ec6..c249474073e9 100644 --- a/packages/react-native/Libraries/Components/TextInput/TextInput.js +++ b/packages/react-native/Libraries/Components/TextInput/TextInput.js @@ -543,7 +543,8 @@ function InternalTextInput(props: TextInputProps): React.Node { flattenedStyle.fontWeight.toString() as TextStyle['fontWeight']; } - if (flattenedStyle.verticalAlign != null) { + // A conditional value (with media queries) is not converted. + if (typeof flattenedStyle.verticalAlign === 'string') { overrides = overrides || ({} as {...TextStyle}); overrides.textAlignVertical = verticalAlignToTextAlignVerticalMap[flattenedStyle.verticalAlign]; diff --git a/packages/react-native/Libraries/Image/Image.android.js b/packages/react-native/Libraries/Image/Image.android.js index 025ee03cac37..165508c5afe2 100644 --- a/packages/react-native/Libraries/Image/Image.android.js +++ b/packages/react-native/Libraries/Image/Image.android.js @@ -300,9 +300,15 @@ let BaseImage: AbstractImageAndroid = ({ } const flattenedStyle_ = flattenStyle(style); - const objectFit_ = convertObjectFitToResizeMode(flattenedStyle_?.objectFit); + const styleObjectFit_ = flattenedStyle_?.objectFit; + // A conditional value (with media queries) is not converted. + const objectFit_ = + typeof styleObjectFit_ === 'string' + ? convertObjectFitToResizeMode(styleObjectFit_) + : undefined; const resizeMode_ = objectFit_ || resizeMode || flattenedStyle_?.resizeMode || 'cover'; + // $FlowFixMe[incompatible-type] A conditional value is resolved natively. nativeProps.resizeMode = resizeMode_; const actualRef = useWrapRefWithImageAttachedCallbacks(forwardedRef); diff --git a/packages/react-native/Libraries/Image/Image.ios.js b/packages/react-native/Libraries/Image/Image.ios.js index f0a7ae8c58c3..c405859597cb 100644 --- a/packages/react-native/Libraries/Image/Image.ios.js +++ b/packages/react-native/Libraries/Image/Image.ios.js @@ -190,9 +190,17 @@ let BaseImage: AbstractImageIOS = ({ nativeProps.source = sources; const flattenedStyle = flattenStyle(resolvedStyle); - const objectFit = convertObjectFitToResizeMode(flattenedStyle?.objectFit); - nativeProps.resizeMode = + const styleObjectFit = flattenedStyle?.objectFit; + // A conditional value (with media queries) is not converted. + const objectFit = + typeof styleObjectFit === 'string' + ? convertObjectFitToResizeMode(styleObjectFit) + : undefined; + const resolvedResizeMode = objectFit || resizeMode || flattenedStyle?.resizeMode || 'cover'; + // $FlowFixMe[incompatible-type] A conditional value is resolved natively. + nativeProps.resizeMode = resolvedResizeMode; + // $FlowFixMe[incompatible-type] A conditional value is resolved natively. nativeProps.tintColor = tintColor ?? flattenedStyle?.tintColor; // Maintain pre-existing order, accessibilityLabel takes priority over alt diff --git a/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js b/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js index 3144295c2d5a..9202cd651029 100644 --- a/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js +++ b/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js @@ -15,6 +15,127 @@ import deepDiffer from '../../Utilities/differ/deepDiffer'; const emptyObject = {}; +// Conditional values (for example `{default: 'white', '@media +// (prefers-color-scheme: dark)': 'black'}`) are sent to native under this prop, +// and native resolves them. See `ConditionalProps.h` for the format. +const CONDITIONAL_PROPS_KEY = '__conditionalProps'; + +type ConditionalPropCondition = { + queries: Array, + value: unknown, +}; + +class ConditionalProp { + definition: { + default: unknown, + conditions: Array, + }; + + constructor( + defaultValue: unknown, + conditions: Array, + ) { + this.definition = {default: defaultValue, conditions}; + } +} + +// Set when a `ConditionalProp` is added to the payload, so that `create` and +// `diff` only move them to `CONDITIONAL_PROPS_KEY` when needed. +let hasConditionalProps = false; + +function isConditionalValue(value: unknown): boolean { + return ( + typeof value === 'object' && + value !== null && + !Array.isArray(value) && + 'default' in value + ); +} + +function addConditions( + value: unknown, + queries: Array, + conditions: Array, + process: ?(value: unknown) => unknown, +): void { + if (!isConditionalValue(value)) { + conditions.push({ + queries, + value: value == null ? null : process != null ? process(value) : value, + }); + return; + } + // $FlowFixMe[incompatible-type] refined by `isConditionalValue` + const conditionalValue: {readonly [key: string]: unknown} = value; + // The default value applies first, whatever its position in the object. + addConditions(conditionalValue.default, queries, conditions, process); + for (const key in conditionalValue) { + if (key !== 'default') { + addConditions( + conditionalValue[key], + [...queries, key], + conditions, + process, + ); + } + } +} + +function createConditionalProp( + value: unknown, + process: ?(value: unknown) => unknown, +): ConditionalProp { + const conditions: Array = []; + // Nested conditions are flattened: each condition has all the queries that + // lead to its value. + addConditions(value, [], conditions, process); + hasConditionalProps = true; + // The first condition has no query: it is the default value. + return new ConditionalProp(conditions[0].value, conditions.slice(1)); +} + +function processAttributeValue( + attributeConfig: unknown, + value: unknown, +): unknown { + const process: ?(value: unknown) => unknown = + typeof attributeConfig === 'object' && + attributeConfig !== null && + typeof attributeConfig.process === 'function' + ? // $FlowFixMe[unclear-type] AnyAttributeType is defined upstream with $FlowFixMe + (attributeConfig.process as any) + : null; + if (isConditionalValue(value)) { + return createConditionalProp(value, process); + } + return process != null ? process(value) : value; +} + +function moveConditionalProps( + payload: null | {[key: string]: unknown}, +): null | {[key: string]: unknown} { + if (!hasConditionalProps) { + return payload; + } + hasConditionalProps = false; + if (payload == null) { + return payload; + } + let conditionalProps: ?{[key: string]: unknown} = null; + for (const key in payload) { + const value = payload[key]; + if (value instanceof ConditionalProp) { + conditionalProps = conditionalProps ?? ({} as {[key: string]: unknown}); + conditionalProps[key] = value.definition; + delete payload[key]; + } + } + if (conditionalProps != null) { + payload[CONDITIONAL_PROPS_KEY] = conditionalProps; + } + return payload; +} + /** * Create a payload that contains all the updates between two sets of props. * @@ -82,19 +203,16 @@ function restoreDeletedValuesInNestedArray( nextProp = null; } - if (typeof attributeConfig !== 'object') { - // case: !Object is the default case - updatePayload[propKey] = nextProp; - } else if ( + if ( + typeof attributeConfig !== 'object' || typeof attributeConfig.diff === 'function' || typeof attributeConfig.process === 'function' ) { - // case: CustomAttributeConfiguration - const nextValue = - typeof attributeConfig.process === 'function' - ? attributeConfig.process(nextProp) - : nextProp; - updatePayload[propKey] = nextValue; + // case: !Object | CustomAttributeConfiguration + updatePayload[propKey] = processAttributeValue( + attributeConfig, + nextProp, + ); } // $FlowFixMe[incompatible-use] found when upgrading Flow removedKeys[propKey] = false; @@ -291,19 +409,16 @@ function diffProperties( // value. It doesn't matter if nothing changed, we'll set it anyway. // Pattern match on: attributeConfig - if (typeof attributeConfig !== 'object') { - // case: !Object is the default case - updatePayload[propKey] = nextProp; - } else if ( + if ( + typeof attributeConfig !== 'object' || typeof attributeConfig.diff === 'function' || typeof attributeConfig.process === 'function' ) { - // case: CustomAttributeConfiguration - const nextValue = - typeof attributeConfig.process === 'function' - ? attributeConfig.process(nextProp) - : nextProp; - updatePayload[propKey] = nextValue; + // case: !Object | CustomAttributeConfiguration + updatePayload[propKey] = processAttributeValue( + attributeConfig, + nextProp, + ); } continue; } @@ -319,27 +434,29 @@ function diffProperties( // a normal leaf has changed (updatePayload || (updatePayload = {} as {[key: string]: unknown}))[ propKey - ] = nextProp; + ] = processAttributeValue(attributeConfig, nextProp); } } else if ( typeof attributeConfig.diff === 'function' || typeof attributeConfig.process === 'function' ) { // case: CustomAttributeConfiguration + // A custom differ does not know conditional values. + const customDiffer = + typeof attributeConfig.diff === 'function' && + !isConditionalValue(prevProp) && + !isConditionalValue(nextProp) + ? attributeConfig.diff + : null; const shouldUpdate = prevProp === undefined || - (typeof attributeConfig.diff === 'function' - ? attributeConfig.diff(prevProp, nextProp) + (customDiffer != null + ? customDiffer(prevProp, nextProp) : defaultDiffer(prevProp, nextProp)); if (shouldUpdate) { - const nextValue = - typeof attributeConfig.process === 'function' - ? // $FlowFixMe[incompatible-use] found when upgrading Flow - attributeConfig.process(nextProp) - : nextProp; (updatePayload || (updatePayload = {} as {[key: string]: unknown}))[ propKey - ] = nextValue; + ] = processAttributeValue(attributeConfig, nextProp); } } else { // default: fallthrough case when nested properties are defined @@ -460,12 +577,13 @@ function addNestedProperty( continue; } } else if (typeof attributeConfig === 'object') { - if (typeof attributeConfig.process === 'function') { - // An atomic prop with custom processing. - newValue = attributeConfig.process(prop); - } else if (typeof attributeConfig.diff === 'function') { - // An atomic prop with custom diffing. We don't need to do diffing when adding props. - newValue = prop; + if ( + typeof attributeConfig.process === 'function' || + typeof attributeConfig.diff === 'function' + ) { + // An atomic prop with custom processing or diffing. We don't need to + // do diffing when adding props. + newValue = processAttributeValue(attributeConfig, prop); } } else { if (typeof prop === 'function') { @@ -473,7 +591,7 @@ function addNestedProperty( newValue = true; } else { // An atomic prop. Doesn't need to be flattened. - newValue = prop; + newValue = processAttributeValue(attributeConfig, prop); } } @@ -512,7 +630,7 @@ export function create( props: NestedNode, validAttributes: AttributeConfiguration, ): null | {[key: string]: unknown} { - return addNestedProperty(null, props, validAttributes); + return moveConditionalProps(addNestedProperty(null, props, validAttributes)); } export function diff( @@ -520,10 +638,12 @@ export function diff( nextProps: {[key: string]: unknown}, validAttributes: AttributeConfiguration, ): null | {[key: string]: unknown} { - return diffProperties( - null, // updatePayload - prevProps, - nextProps, - validAttributes, + return moveConditionalProps( + diffProperties( + null, // updatePayload + prevProps, + nextProps, + validAttributes, + ), ); } diff --git a/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js b/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js index 0e926394122a..5dfc618a38fd 100644 --- a/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js +++ b/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js @@ -42,6 +42,43 @@ export type DimensionValue = number | string | 'auto' | null; export type CursorValue = 'auto' | 'pointer'; +/** + * A style value that depends on media queries. The value of the last matching + * query is used, or the `default` value. Supported media features: + * - `(prefers-color-scheme: light | dark)` + * - `(prefers-contrast: no-preference | less | more)` + * + * Features can be combined with `and`, for example + * `'@media (prefers-color-scheme: dark) and (prefers-contrast: more)'`. + * + * ``` + * backgroundColor: { + * default: 'white', + * '@media (prefers-color-scheme: dark)': 'black', + * } + * ``` + */ +export type ConditionalStyleValue = Readonly<{ + default: ConditionalStyleValueBranch, + [mediaQuery: string]: ConditionalStyleValueBranch, +}>; + +// One level of nested conditions is typed. A recursive type makes Flow +// overflow its stack. +type ConditionalStyleValueBranch = + | T + | Readonly<{ + default: T, + [mediaQuery: string]: T, + }>; + +/** + * A style object where each value can be a `ConditionalStyleValue`. + */ +export type WithConditionalStyleValues = T extends {...} + ? {readonly [K in keyof T]: T[K] | ConditionalStyleValue} + : T; + /** * React Native's layout system is based on Flexbox and is powered both * on iOS and Android by an open source project called `Yoga`: @@ -1096,7 +1133,13 @@ export type ____DangerouslyImpreciseStyle_Internal = Readonly<{ }>; export type StyleProp = - null | void | T | false | '' | ReadonlyArray>; + | null + | void + | T + | WithConditionalStyleValues + | false + | '' + | ReadonlyArray>; export type ____DangerouslyImpreciseStyleProp_Internal = StyleProp< Partial<____DangerouslyImpreciseStyle_Internal>, @@ -1118,7 +1161,9 @@ export type ____ImageStyleProp_Internal = StyleProp< export type ____Styles_Internal = { // $FlowFixMe[incompatible-exact] // $FlowFixMe[incompatible-type] - readonly [key: string]: Partial<____DangerouslyImpreciseStyle_Internal>, + readonly [key: string]: Partial< + WithConditionalStyleValues<____DangerouslyImpreciseStyle_Internal>, + >, ... }; diff --git a/packages/react-native/Libraries/StyleSheet/__tests__/MediaQueries-itest.js b/packages/react-native/Libraries/StyleSheet/__tests__/MediaQueries-itest.js new file mode 100644 index 000000000000..2f4ac0c063ca --- /dev/null +++ b/packages/react-native/Libraries/StyleSheet/__tests__/MediaQueries-itest.js @@ -0,0 +1,295 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; + +import type {HostInstance} from 'react-native'; + +import * as Fantom from '@react-native/fantom'; +import * as React from 'react'; +import {createRef, memo} from 'react'; +import {StyleSheet, Text, View} from 'react-native'; + +const DARK = '@media (prefers-color-scheme: dark)'; +const MORE_CONTRAST = '@media (prefers-contrast: more)'; +const DARK_AND_MORE_CONTRAST = + '@media (prefers-color-scheme: dark) and (prefers-contrast: more)'; + +const styles = StyleSheet.create({ + box: { + backgroundColor: {default: 'white', [DARK]: 'black'}, + }, + contrast: { + backgroundColor: { + default: 'white', + [DARK]: 'black', + [MORE_CONTRAST]: 'red', + }, + }, + nested: { + backgroundColor: { + default: 'white', + [DARK]: {default: 'black', [MORE_CONTRAST]: 'blue'}, + }, + }, + combined: { + backgroundColor: { + default: 'white', + [DARK_AND_MORE_CONTRAST]: 'blue', + }, + }, + width: { + width: {default: 10, [DARK]: 20}, + height: 10, + }, + text: { + color: {default: 'black', [DARK]: 'white'}, + }, +}); + +function setMediaFeatures( + mediaFeatures: Parameters[0], +) { + Fantom.runTask(() => { + Fantom.setMediaFeatures(mediaFeatures); + }); +} + +function renderedBackgroundColor(root: Fantom.Root): React.Node { + return root.getRenderedOutput({props: ['backgroundColor']}).toJSX(); +} + +describe('media queries in styles', () => { + afterEach(() => { + setMediaFeatures({}); + }); + + it('uses the default value when no condition matches', () => { + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + + expect(renderedBackgroundColor(root)).toEqual( + , + ); + }); + + it('uses the value of a matching condition on the first render', () => { + setMediaFeatures({colorScheme: 'dark'}); + + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + + expect(renderedBackgroundColor(root)).toEqual( + , + ); + }); + + it('updates mounted views when the media features change, without a React render', () => { + let renderCount = 0; + const Box = memo(function Box() { + renderCount++; + return ; + }); + + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + expect(renderCount).toBe(1); + + setMediaFeatures({colorScheme: 'dark'}); + expect(renderedBackgroundColor(root)).toEqual( + , + ); + + setMediaFeatures({colorScheme: 'light'}); + expect(renderedBackgroundColor(root)).toEqual( + , + ); + expect(renderCount).toBe(1); + }); + + it('keeps the resolved value when React renders the view again after a change', () => { + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + + setMediaFeatures({colorScheme: 'dark'}); + + Fantom.runTask(() => { + root.render(); + }); + expect( + root.getRenderedOutput({props: ['backgroundColor', 'nativeID']}).toJSX(), + ).toEqual(); + }); + + it('keeps the resolved value of views that React does not render again after a change', () => { + const Box = memo(function Box() { + return ; + }); + + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render( + + + , + ); + }); + + setMediaFeatures({colorScheme: 'dark'}); + + Fantom.runTask(() => { + root.render( + + + , + ); + }); + expect( + root.getRenderedOutput({props: ['backgroundColor', 'nativeID']}).toJSX(), + ).toEqual( + + + , + ); + }); + + it('matches prefers-contrast, and the last matching condition wins', () => { + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + + setMediaFeatures({colorScheme: 'dark', contrast: 'more'}); + expect(renderedBackgroundColor(root)).toEqual( + , + ); + + setMediaFeatures({colorScheme: 'dark', contrast: 'no-preference'}); + expect(renderedBackgroundColor(root)).toEqual( + , + ); + }); + + it('supports nested conditions', () => { + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + + setMediaFeatures({colorScheme: 'light', contrast: 'more'}); + expect(renderedBackgroundColor(root)).toEqual( + , + ); + + setMediaFeatures({colorScheme: 'dark', contrast: 'more'}); + expect(renderedBackgroundColor(root)).toEqual( + , + ); + }); + + it('supports media features combined with and', () => { + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + + setMediaFeatures({colorScheme: 'dark'}); + expect(renderedBackgroundColor(root)).toEqual( + , + ); + + setMediaFeatures({colorScheme: 'dark', contrast: 'more'}); + expect(renderedBackgroundColor(root)).toEqual( + , + ); + + setMediaFeatures({colorScheme: 'light', contrast: 'more'}); + expect(renderedBackgroundColor(root)).toEqual( + , + ); + }); + + it('updates the layout of conditional layout props', () => { + const ref = createRef(); + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + expect(ref.current?.getBoundingClientRect().width).toBe(10); + + setMediaFeatures({colorScheme: 'dark'}); + expect(ref.current?.getBoundingClientRect().width).toBe(20); + }); + + it('stops updating a prop when React replaces its conditional value with a plain value', () => { + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + Fantom.runTask(() => { + root.render(); + }); + + setMediaFeatures({colorScheme: 'dark'}); + expect(renderedBackgroundColor(root)).toEqual( + , + ); + }); + + it('resolves conditional values of inline styles and Text', () => { + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render( + + Hello + , + ); + }); + + setMediaFeatures({colorScheme: 'dark'}); + expect( + root.getRenderedOutput({props: ['opacity', 'foregroundColor']}).toJSX(), + ).toEqual( + + + Hello + + , + ); + }); + + it('never matches an unsupported media query', () => { + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render( + , + ); + }); + + expect(renderedBackgroundColor(root)).toEqual( + , + ); + }); +}); diff --git a/packages/react-native/Libraries/StyleSheet/splitLayoutProps.js b/packages/react-native/Libraries/StyleSheet/splitLayoutProps.js index e37b9b749d0b..78ecd4cdcc61 100644 --- a/packages/react-native/Libraries/StyleSheet/splitLayoutProps.js +++ b/packages/react-native/Libraries/StyleSheet/splitLayoutProps.js @@ -8,14 +8,16 @@ * @format */ -import type {ViewStyle} from './StyleSheetTypes'; +import type {ViewStyle, WithConditionalStyleValues} from './StyleSheetTypes'; -export default function splitLayoutProps(props: ?ViewStyle): { - outer: ?ViewStyle, - inner: ?ViewStyle, +type Style = WithConditionalStyleValues; + +export default function splitLayoutProps(props: ?Style): { + outer: ?Style, + inner: ?Style, } { - let outer: ?ViewStyle = null; - let inner: ?ViewStyle = null; + let outer: ?Style = null; + let inner: ?Style = null; if (props != null) { // $FlowFixMe[incompatible-exact] Will contain a subset of keys from `props`. diff --git a/packages/react-native/Libraries/Text/Text.js b/packages/react-native/Libraries/Text/Text.js index 6c4b28d0caf0..a90ed0122767 100644 --- a/packages/react-native/Libraries/Text/Text.js +++ b/packages/react-native/Libraries/Text/Text.js @@ -195,13 +195,14 @@ const TextImpl: component( String(processedStyle.fontWeight) as TextStyle['fontWeight']; } - if (processedStyle.userSelect != null) { + // A conditional value (with media queries) is not converted. + if (typeof processedStyle.userSelect === 'string') { _selectable = userSelectToSelectableMap[processedStyle.userSelect]; overrides = overrides || ({} as {...TextStyle}); overrides.userSelect = undefined; } - if (processedStyle.verticalAlign != null) { + if (typeof processedStyle.verticalAlign === 'string') { overrides = overrides || ({} as {...TextStyle}); overrides.textAlignVertical = verticalAlignToTextAlignVerticalMap[processedStyle.verticalAlign]; diff --git a/packages/react-native/React/Fabric/RCTScheduler.h b/packages/react-native/React/Fabric/RCTScheduler.h index 214e43b30103..50884248934f 100644 --- a/packages/react-native/React/Fabric/RCTScheduler.h +++ b/packages/react-native/React/Fabric/RCTScheduler.h @@ -70,6 +70,12 @@ NS_ASSUME_NONNULL_BEGIN - (void)reportMount:(facebook::react::SurfaceId)surfaceId; +/* + * Sets the media features that conditional props (for example with + * `@media (prefers-color-scheme: dark)`) are matched against. + */ +- (void)updateMediaFeatures:(const facebook::react::MediaFeatures &)mediaFeatures; + - (void)addEventListener:(const std::shared_ptr &)listener; - (void)removeEventListener:(const std::shared_ptr &)listener; diff --git a/packages/react-native/React/Fabric/RCTScheduler.mm b/packages/react-native/React/Fabric/RCTScheduler.mm index 9519f18428e4..deef1eb5fdf2 100644 --- a/packages/react-native/React/Fabric/RCTScheduler.mm +++ b/packages/react-native/React/Fabric/RCTScheduler.mm @@ -229,6 +229,11 @@ - (void)reportMount:(facebook::react::SurfaceId)surfaceId _scheduler->reportMount(surfaceId); } +- (void)updateMediaFeatures:(const facebook::react::MediaFeatures &)mediaFeatures +{ + _scheduler->updateMediaFeatures(mediaFeatures); +} + - (void)dealloc { if (_animationDriver) { diff --git a/packages/react-native/React/Fabric/RCTSurfacePresenter.mm b/packages/react-native/React/Fabric/RCTSurfacePresenter.mm index e5b19bd47658..923568484aa5 100644 --- a/packages/react-native/React/Fabric/RCTSurfacePresenter.mm +++ b/packages/react-native/React/Fabric/RCTSurfacePresenter.mm @@ -115,6 +115,19 @@ - (instancetype)initWithContextContainer:(std::shared_ptr { + FabricUIManagerBinding binding = mBinding; + if (binding != null) { + binding.updateMediaFeatures(colorScheme, contrast); + } + }); + mMediaFeaturesObserver.start(); if (ReactNativeFeatureFlags.enableFabricLogs()) { mDevToolsReactPerfLogger = new DevToolsReactPerfLogger(); mDevToolsReactPerfLogger.addDevToolsReactPerfLoggerListener(FABRIC_PERF_LOGGER); @@ -502,6 +513,11 @@ public void invalidate() { mReactApplicationContext.unregisterComponentCallbacks(mViewManagerRegistry); mViewManagerRegistry.invalidate(); + if (mMediaFeaturesObserver != null) { + mMediaFeaturesObserver.stop(); + mMediaFeaturesObserver = null; + } + // Remove lifecycle listeners (onHostResume, onHostPause) since the FabricUIManager is going // away. Then stop the mDispatchUIFrameCallback false will cause the choreographer // callbacks to stop firing. diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManagerBinding.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManagerBinding.kt index b1b3f12f50c2..0d585667c0c1 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManagerBinding.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManagerBinding.kt @@ -85,6 +85,8 @@ internal class FabricUIManagerBinding : HybridClassBase() { external fun reportMount(surfaceId: Int) + external fun updateMediaFeatures(colorScheme: Int, contrast: Int) + external fun pullAndExecuteTransaction(surfaceId: Int) external fun mergeReactRevision(surfaceId: Int) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt new file mode 100644 index 000000000000..a25085f95641 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt @@ -0,0 +1,161 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.fabric + +import android.app.UiModeManager +import android.content.ComponentCallbacks +import android.content.Context +import android.content.res.Configuration +import android.database.ContentObserver +import android.net.Uri +import android.os.Build +import android.provider.Settings +import androidx.annotation.RequiresApi +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.bridge.UiThreadUtil +import com.facebook.react.views.common.UiModeUtils +import java.util.Collections +import java.util.WeakHashMap + +/** + * Reads the media features that conditional props are matched against (for example with `@media + * (prefers-color-scheme: dark)`), and reports them when they change. + */ +internal class MediaFeaturesObserver( + private val reactContext: ReactApplicationContext, + private val listener: Listener, +) { + + fun interface Listener { + /** + * @param colorScheme one of [COLOR_SCHEME_LIGHT] or [COLOR_SCHEME_DARK] + * @param contrast one of [CONTRAST_NO_PREFERENCE], [CONTRAST_LESS] or [CONTRAST_MORE] + */ + fun onMediaFeaturesChanged(colorScheme: Int, contrast: Int) + } + + private var lastColorScheme: Int? = null + private var lastContrast: Int? = null + + private val componentCallbacks = + object : ComponentCallbacks { + override fun onConfigurationChanged(newConfig: Configuration) { + update() + } + + @Deprecated("Deprecated in Java") override fun onLowMemory() = Unit + } + + private val highTextContrastObserver = + object : ContentObserver(UiThreadUtil.getUiThreadHandler()) { + override fun onChange(selfChange: Boolean) { + update() + } + + override fun onChange(selfChange: Boolean, uri: Uri?) { + update() + } + } + + private var contrastChangeListener: Any? = null + + fun start() { + activeObservers.add(this) + reactContext.registerComponentCallbacks(componentCallbacks) + reactContext.contentResolver.registerContentObserver( + Settings.Secure.getUriFor(HIGH_TEXT_CONTRAST_ENABLED), + false, + highTextContrastObserver, + ) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + addContrastChangeListener() + } + update() + } + + fun stop() { + activeObservers.remove(this) + reactContext.unregisterComponentCallbacks(componentCallbacks) + reactContext.contentResolver.unregisterContentObserver(highTextContrastObserver) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + removeContrastChangeListener() + } + } + + @Synchronized + fun update(context: Context? = null) { + // The activity context reflects `AppCompatDelegate.setDefaultNightMode()`, which + // `Appearance.setColorScheme()` uses. + val currentContext = context ?: reactContext.currentActivity ?: reactContext + val colorScheme = + if (UiModeUtils.isDarkMode(currentContext)) COLOR_SCHEME_DARK else COLOR_SCHEME_LIGHT + val contrast = readContrast() + + if (colorScheme != lastColorScheme || contrast != lastContrast) { + lastColorScheme = colorScheme + lastContrast = contrast + listener.onMediaFeaturesChanged(colorScheme, contrast) + } + } + + private fun readContrast(): Int { + val isHighTextContrastEnabled = + Settings.Secure.getInt(reactContext.contentResolver, HIGH_TEXT_CONTRAST_ENABLED, 0) != 0 + val contrastLevel = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) readContrastLevel() + else 0f + return when { + isHighTextContrastEnabled || contrastLevel > 0f -> CONTRAST_MORE + contrastLevel < 0f -> CONTRAST_LESS + else -> CONTRAST_NO_PREFERENCE + } + } + + @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) + private fun readContrastLevel(): Float = + reactContext.getSystemService(UiModeManager::class.java)?.contrast ?: 0f + + @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) + private fun addContrastChangeListener() { + val uiModeManager = reactContext.getSystemService(UiModeManager::class.java) ?: return + val contrastListener = UiModeManager.ContrastChangeListener { update() } + uiModeManager.addContrastChangeListener(reactContext.mainExecutor, contrastListener) + contrastChangeListener = contrastListener + } + + @RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) + private fun removeContrastChangeListener() { + val contrastListener = contrastChangeListener as? UiModeManager.ContrastChangeListener ?: return + reactContext + .getSystemService(UiModeManager::class.java) + ?.removeContrastChangeListener(contrastListener) + contrastChangeListener = null + } + + companion object { + // These values match `FabricUIManagerBinding::updateMediaFeatures`. + const val COLOR_SCHEME_LIGHT: Int = 0 + const val COLOR_SCHEME_DARK: Int = 1 + const val CONTRAST_NO_PREFERENCE: Int = 0 + const val CONTRAST_LESS: Int = 1 + const val CONTRAST_MORE: Int = 2 + + private const val HIGH_TEXT_CONTRAST_ENABLED = "high_text_contrast_enabled" + + private val activeObservers: MutableSet = + Collections.synchronizedSet(Collections.newSetFromMap(WeakHashMap())) + + /** + * Call this when the configuration of an activity changes: changes made with + * `AppCompatDelegate.setDefaultNightMode()` only reach the activity. + */ + fun onConfigurationChanged(context: Context) { + synchronized(activeObservers) { activeObservers.toList() }.forEach { it.update(context) } + } + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt index f54557bf6906..19eec8da7b5c 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt @@ -55,6 +55,7 @@ import com.facebook.react.devsupport.interfaces.DevSupportManager import com.facebook.react.devsupport.interfaces.DevSupportManager.PausedInDebuggerOverlayCommandListener import com.facebook.react.fabric.ComponentFactory import com.facebook.react.fabric.FabricUIManager +import com.facebook.react.fabric.MediaFeaturesObserver import com.facebook.react.interfaces.TaskInterface import com.facebook.react.interfaces.fabric.ReactSurface import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags @@ -745,6 +746,8 @@ public class ReactHostImpl( val appearanceModule = currentReactContext.getNativeModule(AppearanceModule::class.java) appearanceModule?.onConfigurationChanged(context) + + MediaFeaturesObserver.onConfigurationChanged(context) } } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp index 8cff9f825b58..641a32153e2a 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp @@ -120,6 +120,25 @@ void FabricUIManagerBinding::reportMount(SurfaceId surfaceId) { scheduler->reportMount(surfaceId); } +void FabricUIManagerBinding::updateMediaFeatures( + jint colorScheme, + jint contrast) { + auto scheduler = getScheduler(); + if (!scheduler) { + LOG(ERROR) + << "FabricUIManagerBinding::updateMediaFeatures: scheduler disappeared"; + return; + } + // The values match `FabricUIManager.MEDIA_*` constants. + scheduler->updateMediaFeatures({ + .colorScheme = + colorScheme == 1 ? MediaColorScheme::Dark : MediaColorScheme::Light, + .contrast = contrast == 2 ? MediaContrast::More + : contrast == 1 ? MediaContrast::Less + : MediaContrast::NoPreference, + }); +} + void FabricUIManagerBinding::pullAndExecuteTransaction(SurfaceId surfaceId) { TraceSection section("FabricUIManagerBinding::pullAndExecuteTransaction"); @@ -937,6 +956,8 @@ void FabricUIManagerBinding::registerNatives() { "drainPreallocateViewsQueue", FabricUIManagerBinding::drainPreallocateViewsQueue), makeNativeMethod("reportMount", FabricUIManagerBinding::reportMount), + makeNativeMethod( + "updateMediaFeatures", FabricUIManagerBinding::updateMediaFeatures), makeNativeMethod( "pullAndExecuteTransaction", FabricUIManagerBinding::pullAndExecuteTransaction), diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h index 68c47706ba7b..ecd9d66002d4 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h @@ -135,6 +135,8 @@ class FabricUIManagerBinding : public jni::HybridClass, void reportMount(SurfaceId surfaceId); + void updateMediaFeatures(jint colorScheme, jint contrast); + void pullAndExecuteTransaction(SurfaceId surfaceId); jint findNextFocusableElement(jint parentTag, jint focusedTag, jint direction); diff --git a/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h index e11bf20fb3a1..2b1c6f5e0ffe 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -125,6 +126,11 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { ShadowNodeT::filterRawProps(rawProps); } + // Replaces conditional values (for example with media queries) by the + // values that match the current media features. + auto conditionalPropsResolution = resolveConditionalProps(props.get(), rawProps); + auto &resolvedRawProps = conditionalPropsResolution ? conditionalPropsResolution->rawProps : rawProps; + // Two construction paths: // - Iterator-setter (only available when `ConcreteProps` satisfies // `HasIteratorSetterCtor` AND the runtime flag is on): copy-construct @@ -146,8 +152,13 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { } } if (!useIteratorSetter) { - rawProps.parse(rawPropsParser_); - shadowNodeProps = ShadowNodeT::Props(context, rawProps, props); + resolvedRawProps.parse(rawPropsParser_); + shadowNodeProps = ShadowNodeT::Props(context, resolvedRawProps, props); + } + + if (conditionalPropsResolution) { + shadowNodeProps->conditionalProps = std::move(conditionalPropsResolution->conditionalProps); + shadowNodeProps->conditionalPropsGeneration = conditionalPropsResolution->generation; } #ifdef RN_SERIALIZABLE_STATE @@ -166,13 +177,13 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { } } if (fallbackToDynamicRawPropsAccumulation) { - ShadowNodeT::initializeDynamicProps(shadowNodeProps, rawProps, props); + ShadowNodeT::initializeDynamicProps(shadowNodeProps, resolvedRawProps, props); } #endif if constexpr (kSupportsIteratorSetter) { if (useIteratorSetter) { - rawProps.forEachItem([&](std::string_view name, const RawValue &value) { + resolvedRawProps.forEachItem([&](std::string_view name, const RawValue &value) { shadowNodeProps->setProp(context, RAW_PROPS_KEY_HASH(name), name.data(), value); }); } diff --git a/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.cpp b/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.cpp new file mode 100644 index 000000000000..b0ebbdd58bf6 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.cpp @@ -0,0 +1,131 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "ConditionalProps.h" + +namespace facebook::react { + +namespace { + +bool matchesAllQueries( + const folly::dynamic& queries, + const MediaFeatures& features) { + if (!queries.isArray()) { + return false; + } + for (const auto& query : queries) { + if (!query.isString() || !matchMediaQuery(query.getString(), features)) { + return false; + } + } + return true; +} + +} // namespace + +folly::dynamic resolveConditionalValue( + const folly::dynamic& conditionalValue, + const MediaFeatures& features) { + if (!conditionalValue.isObject()) { + return nullptr; + } + + const auto* resolvedValue = conditionalValue.get_ptr("default"); + + const auto* conditions = conditionalValue.get_ptr("conditions"); + if (conditions != nullptr && conditions->isArray()) { + for (const auto& condition : *conditions) { + if (!condition.isObject()) { + continue; + } + const auto* queries = condition.get_ptr("queries"); + const auto* value = condition.get_ptr("value"); + if (queries != nullptr && value != nullptr && + matchesAllQueries(*queries, features)) { + resolvedValue = value; + } + } + } + + return resolvedValue != nullptr ? *resolvedValue : nullptr; +} + +std::optional resolveConditionalProps( + const Props* sourceProps, + const RawProps& rawProps) { + const auto* sourceConditionalProps = + sourceProps != nullptr ? sourceProps->conditionalProps.get() : nullptr; + auto hasNewConditionalProps = rawProps.hasProperty(kConditionalPropsName); + + if (sourceConditionalProps == nullptr && !hasNewConditionalProps) { + return std::nullopt; + } + + auto snapshot = getMediaFeaturesSnapshot(); + auto isStale = sourceConditionalProps != nullptr && + sourceProps->conditionalPropsGeneration != snapshot.generation; + + if (!hasNewConditionalProps && !isStale) { + // The source conditional values are up to date. They only change if + // `rawProps` gives a plain value to one of their props. + auto isAnyReplaced = false; + for (const auto& item : sourceConditionalProps->items()) { + if (rawProps.hasProperty(item.first.c_str())) { + isAnyReplaced = true; + break; + } + } + if (!isAnyReplaced) { + return std::nullopt; + } + } + + auto values = rawProps.toDynamic(); + + folly::dynamic newConditionalProps = folly::dynamic::object(); + if (auto it = values.find(kConditionalPropsName); + it != values.items().end()) { + if (it->second.isObject()) { + newConditionalProps = std::move(it->second); + } + values.erase(kConditionalPropsName); + } + + folly::dynamic conditionalProps = sourceConditionalProps != nullptr + ? *sourceConditionalProps + : folly::dynamic(folly::dynamic::object()); + + // A plain value replaces the conditional value of the same prop. + for (const auto& item : values.items()) { + conditionalProps.erase(item.first); + } + + for (const auto& item : newConditionalProps.items()) { + values[item.first] = + resolveConditionalValue(item.second, snapshot.features); + conditionalProps[item.first] = item.second; + } + + if (isStale) { + for (const auto& item : conditionalProps.items()) { + if (newConditionalProps.count(item.first) == 0) { + values[item.first] = + resolveConditionalValue(item.second, snapshot.features); + } + } + } + + return ConditionalPropsResolution{ + .rawProps = RawProps(std::move(values)), + .conditionalProps = conditionalProps.empty() + ? nullptr + : std::make_shared(std::move(conditionalProps)), + .generation = snapshot.generation, + }; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.h b/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.h new file mode 100644 index 000000000000..3bb5e7d48335 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include +#include + +#include +#include +#include +#include + +namespace facebook::react { + +/* + * The prop that holds the conditional values of a props payload, by prop name. + * Each conditional value has this format: + * + * { + * "default": , + * "conditions": [ + * {"queries": ["@media (prefers-color-scheme: dark)", ...], "value": }, + * ... + * ] + * } + * + * A condition matches when all its queries match. The value of the last + * matching condition is used, or the default value if no condition matches. + * The values are already processed by JavaScript (for example with + * `processColor`). + */ +inline constexpr const char *kConditionalPropsName = "__conditionalProps"; + +/* + * Returns the value that a conditional value resolves to for `features`. + */ +folly::dynamic resolveConditionalValue(const folly::dynamic &conditionalValue, const MediaFeatures &features); + +struct ConditionalPropsResolution { + /* + * The raw props to parse instead of the given ones: plain values only, with + * the conditional values resolved for the current media features. + */ + RawProps rawProps; + + /* + * The conditional values of the new props. `nullptr` when there are none. + */ + std::shared_ptr conditionalProps; + + /* + * The generation of the media features that the values were resolved with. + */ + MediaFeaturesGeneration generation; +}; + +/* + * Merges the conditional values of `sourceProps` and `rawProps`, and resolves + * the ones that are new or that were resolved with older media features. + * + * Returns `std::nullopt` when the new props can use `rawProps` as they are, + * and keep the conditional values of `sourceProps` (the common case). + */ +std::optional resolveConditionalProps(const Props *sourceProps, const RawProps &rawProps); + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp new file mode 100644 index 000000000000..8b674ef5d1cb --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "MediaFeatures.h" + +#include + +namespace facebook::react { + +namespace { + +// The generation and the media features are packed in one value, so that a +// single atomic read gives a consistent snapshot. +std::atomic packedMediaFeatures{0}; + +uint64_t pack( + const MediaFeatures& features, + MediaFeaturesGeneration generation) noexcept { + return (static_cast(generation) << 16) | + (static_cast(features.colorScheme) << 8) | + static_cast(features.contrast); +} + +MediaFeaturesSnapshot unpack(uint64_t packed) noexcept { + return { + .features = + { + .colorScheme = + static_cast((packed >> 8) & 0xff), + .contrast = static_cast(packed & 0xff), + }, + .generation = static_cast(packed >> 16), + }; +} + +char toLowerAscii(char c) noexcept { + return (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; +} + +bool equalsIgnoringAsciiCase(std::string_view a, std::string_view b) noexcept { + if (a.size() != b.size()) { + return false; + } + for (size_t i = 0; i < a.size(); i++) { + if (toLowerAscii(a[i]) != b[i]) { + return false; + } + } + return true; +} + +bool isWhitespace(char c) noexcept { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f'; +} + +std::string_view trim(std::string_view value) noexcept { + while (!value.empty() && isWhitespace(value.front())) { + value.remove_prefix(1); + } + while (!value.empty() && isWhitespace(value.back())) { + value.remove_suffix(1); + } + return value; +} + +// Matches the inside of `(feature: value)`. A feature or value that is not +// supported never matches. +bool matchMediaFeature( + std::string_view feature, + const MediaFeatures& features) noexcept { + auto colon = feature.find(':'); + if (colon == std::string_view::npos) { + return false; + } + auto name = trim(feature.substr(0, colon)); + auto value = trim(feature.substr(colon + 1)); + + if (equalsIgnoringAsciiCase(name, "prefers-color-scheme")) { + if (equalsIgnoringAsciiCase(value, "light")) { + return features.colorScheme == MediaColorScheme::Light; + } + if (equalsIgnoringAsciiCase(value, "dark")) { + return features.colorScheme == MediaColorScheme::Dark; + } + return false; + } + + if (equalsIgnoringAsciiCase(name, "prefers-contrast")) { + if (equalsIgnoringAsciiCase(value, "no-preference")) { + return features.contrast == MediaContrast::NoPreference; + } + if (equalsIgnoringAsciiCase(value, "less")) { + return features.contrast == MediaContrast::Less; + } + if (equalsIgnoringAsciiCase(value, "more")) { + return features.contrast == MediaContrast::More; + } + return false; + } + + return false; +} + +} // namespace + +MediaFeaturesSnapshot getMediaFeaturesSnapshot() noexcept { + return unpack(packedMediaFeatures.load(std::memory_order_acquire)); +} + +bool setMediaFeatures(const MediaFeatures& features) noexcept { + auto packed = packedMediaFeatures.load(std::memory_order_acquire); + while (true) { + auto snapshot = unpack(packed); + if (snapshot.features == features) { + return false; + } + if (packedMediaFeatures.compare_exchange_weak( + packed, + pack(features, snapshot.generation + 1), + std::memory_order_acq_rel, + std::memory_order_acquire)) { + return true; + } + } +} + +bool matchMediaQuery( + std::string_view query, + const MediaFeatures& features) noexcept { + constexpr std::string_view kMedia = "@media"; + constexpr std::string_view kAnd = "and"; + + auto rest = trim(query); + if (rest.size() < kMedia.size() || + !equalsIgnoringAsciiCase(rest.substr(0, kMedia.size()), kMedia)) { + return false; + } + rest = trim(rest.substr(kMedia.size())); + + // `(feature: value)`, optionally followed by `and (feature: value)` parts. + // All the parts must match. + while (true) { + if (rest.empty() || rest.front() != '(') { + return false; + } + auto close = rest.find(')'); + if (close == std::string_view::npos || + !matchMediaFeature(rest.substr(1, close - 1), features)) { + return false; + } + rest = trim(rest.substr(close + 1)); + + if (rest.empty()) { + return true; + } + + if (rest.size() <= kAnd.size() || + !equalsIgnoringAsciiCase(rest.substr(0, kAnd.size()), kAnd) || + !isWhitespace(rest[kAnd.size()])) { + return false; + } + rest = trim(rest.substr(kAnd.size())); + } +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h new file mode 100644 index 000000000000..3abb9c292503 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#pragma once + +#include + +#include +#include + +namespace facebook::react { + +enum class MediaColorScheme : uint8_t { Light, Dark }; + +enum class MediaContrast : uint8_t { NoPreference, Less, More }; + +/* + * The values that media queries in props are matched against, for example + * `@media (prefers-color-scheme: dark)`. + */ +struct MediaFeatures { + MediaColorScheme colorScheme{MediaColorScheme::Light}; + MediaContrast contrast{MediaContrast::NoPreference}; + + bool operator==(const MediaFeatures &other) const = default; +}; + +/* + * Each change of the media features increments the generation. Props keep the + * generation of the media features that their conditional values were resolved + * with, so that the renderer can find the props to resolve again. + */ +using MediaFeaturesGeneration = uint32_t; + +struct MediaFeaturesSnapshot { + MediaFeatures features; + MediaFeaturesGeneration generation; +}; + +/* + * Returns the current media features of the process, and their generation. + * Thread-safe. + */ +MediaFeaturesSnapshot getMediaFeaturesSnapshot() noexcept; + +/* + * Sets the current media features of the process. Returns `true` if they + * changed. Thread-safe. + * + * This does not update existing shadow nodes. To do it, use + * `Scheduler::updateMediaFeatures` or `UIManager::updateConditionalProps`. + */ +bool setMediaFeatures(const MediaFeatures &features) noexcept; + +/* + * Returns whether `query` (for example `@media (prefers-color-scheme: dark)`) + * matches `features`. A query that is not supported never matches. + * + * Supported media features: + * - `(prefers-color-scheme: light | dark)` + * - `(prefers-contrast: no-preference | less | more)` + * + * Features can be combined with `and`, for example + * `@media (prefers-color-scheme: dark) and (prefers-contrast: more)`. + */ +bool matchMediaQuery(std::string_view query, const MediaFeatures &features) noexcept; + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/Props.cpp b/packages/react-native/ReactCommon/react/renderer/core/Props.cpp index 3e8845e9c31d..59a523c40ffe 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Props.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/Props.cpp @@ -26,7 +26,9 @@ Props::Props( rawProps, "nativeID", sourceProps.nativeId, - {})) {} + {})), + conditionalProps(sourceProps.conditionalProps), + conditionalPropsGeneration(sourceProps.conditionalPropsGeneration) {} void Props::setProp( const PropsParserContext& context, diff --git a/packages/react-native/ReactCommon/react/renderer/core/Props.h b/packages/react-native/ReactCommon/react/renderer/core/Props.h index c717e3182a05..b4836053efee 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Props.h +++ b/packages/react-native/ReactCommon/react/renderer/core/Props.h @@ -10,6 +10,8 @@ #include #include +#include +#include #include #include #include @@ -18,7 +20,6 @@ #ifdef ANDROID #include -#include #endif namespace facebook::react { @@ -61,6 +62,19 @@ class Props : public virtual Sealable, public virtual DebugStringConvertible { std::string nativeId; + /* + * The conditional values of these props (for example, values that depend on + * `@media (prefers-color-scheme: dark)`), by prop name, in the format of + * `ConditionalProps.h`. `nullptr` when there are none. + */ + std::shared_ptr conditionalProps; + + /* + * The generation of the media features that `conditionalProps` were resolved + * with. + */ + MediaFeaturesGeneration conditionalPropsGeneration{0}; + #ifdef RN_SERIALIZABLE_STATE folly::dynamic rawProps = folly::dynamic::object(); diff --git a/packages/react-native/ReactCommon/react/renderer/core/RawProps.cpp b/packages/react-native/ReactCommon/react/renderer/core/RawProps.cpp index bf1849ffa10c..ae1f8b932b5b 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/RawProps.cpp @@ -105,6 +105,19 @@ bool RawProps::isEmpty() const noexcept { return mode_ == Mode::Empty; } +bool RawProps::hasProperty(const char* name) const { + switch (mode_) { + case Mode::Empty: + return false; + case Mode::JSI: + return value_.isObject() && + value_.getObject(*runtime_).hasProperty(*runtime_, name); + case Mode::Dynamic: + return dynamic_.isObject() && dynamic_.count(name) > 0; + } + return false; +} + /* * Returns a const unowning pointer to `RawValue` of a prop with a given name. * Returns `nullptr` if a prop with the given name does not exist. diff --git a/packages/react-native/ReactCommon/react/renderer/core/RawProps.h b/packages/react-native/ReactCommon/react/renderer/core/RawProps.h index 8685ec6f575d..ba57934a264d 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/RawProps.h +++ b/packages/react-native/ReactCommon/react/renderer/core/RawProps.h @@ -95,6 +95,12 @@ class RawProps final { */ bool isEmpty() const noexcept; + /* + * Returns `true` if the source object has a prop with the given name. + * Does not require a prior `parse(parser)` call. + */ + bool hasProperty(const char *name) const; + /* * Returns a const unowning pointer to `RawValue` of a prop with a given name. * Returns `nullptr` if a prop with the given name does not exist. diff --git a/packages/react-native/ReactCommon/react/renderer/core/React/RendererCore.h b/packages/react-native/ReactCommon/react/renderer/core/React/RendererCore.h index 670b7acd78b7..412d9b29f0fe 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/React/RendererCore.h +++ b/packages/react-native/ReactCommon/react/renderer/core/React/RendererCore.h @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -55,6 +56,7 @@ #include #include #include +#include #include #include #include diff --git a/packages/react-native/ReactCommon/react/renderer/core/tests/ConditionalPropsTest.cpp b/packages/react-native/ReactCommon/react/renderer/core/tests/ConditionalPropsTest.cpp new file mode 100644 index 000000000000..ccdb2c5d8f18 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/ConditionalPropsTest.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include + +#include +#include +#include +#include +#include + +using namespace facebook::react; + +namespace { + +constexpr const char* kDarkQuery = "@media (prefers-color-scheme: dark)"; +constexpr const char* kMoreContrastQuery = "@media (prefers-contrast: more)"; + +const MediaFeatures kLight{ + .colorScheme = MediaColorScheme::Light, + .contrast = MediaContrast::NoPreference}; +const MediaFeatures kDark{ + .colorScheme = MediaColorScheme::Dark, + .contrast = MediaContrast::NoPreference}; +const MediaFeatures kDarkMoreContrast{ + .colorScheme = MediaColorScheme::Dark, + .contrast = MediaContrast::More}; + +folly::dynamic condition(folly::dynamic queries, folly::dynamic value) { + return folly::dynamic::object("queries", std::move(queries))( + "value", std::move(value)); +} + +// `{default: 1, [DARK]: 2, [MORE_CONTRAST]: 3}` +folly::dynamic opacityValue() { + return folly::dynamic::object("default", 1)( + "conditions", + folly::dynamic::array( + condition(folly::dynamic::array(kDarkQuery), 2), + condition(folly::dynamic::array(kMoreContrastQuery), 3))); +} + +class ConditionalPropsTest : public ::testing::Test { + protected: + void SetUp() override { + setMediaFeatures(kLight); + } + + void TearDown() override { + setMediaFeatures(kLight); + } +}; + +} // namespace + +TEST_F(ConditionalPropsTest, resolvesTheLastMatchingCondition) { + EXPECT_EQ(resolveConditionalValue(opacityValue(), kLight), 1); + EXPECT_EQ(resolveConditionalValue(opacityValue(), kDark), 2); + EXPECT_EQ(resolveConditionalValue(opacityValue(), kDarkMoreContrast), 3); +} + +TEST_F(ConditionalPropsTest, matchesAConditionOnlyIfAllItsQueriesMatch) { + folly::dynamic value = folly::dynamic::object("default", 1)( + "conditions", + folly::dynamic::array( + condition(folly::dynamic::array(kDarkQuery, kMoreContrastQuery), 2), + condition(folly::dynamic::array(), 3))); + // A condition without queries always matches. + EXPECT_EQ(resolveConditionalValue(value, kDarkMoreContrast), 3); + + value["conditions"].erase(value["conditions"].begin() + 1); + EXPECT_EQ(resolveConditionalValue(value, kDark), 1); + EXPECT_EQ(resolveConditionalValue(value, kDarkMoreContrast), 2); +} + +TEST_F(ConditionalPropsTest, resolvesToNullWithoutDefaultValue) { + EXPECT_EQ( + resolveConditionalValue(folly::dynamic(folly::dynamic::object()), kLight), + nullptr); + EXPECT_EQ(resolveConditionalValue(42, kLight), nullptr); +} + +TEST_F(ConditionalPropsTest, doesNothingWithoutConditionalValues) { + Props sourceProps; + auto rawProps = RawProps(folly::dynamic::object("opacity", 0.5)); + EXPECT_FALSE(resolveConditionalProps(&sourceProps, rawProps).has_value()); + EXPECT_FALSE(resolveConditionalProps(nullptr, rawProps).has_value()); +} + +TEST_F(ConditionalPropsTest, resolvesNewConditionalValues) { + setMediaFeatures(kDark); + auto rawProps = RawProps( + folly::dynamic::object("nativeID", "box")( + kConditionalPropsName, + folly::dynamic::object("opacity", opacityValue()))); + + auto resolution = resolveConditionalProps(nullptr, rawProps); + ASSERT_TRUE(resolution.has_value()); + EXPECT_EQ( + resolution->rawProps.toDynamic(), + folly::dynamic(folly::dynamic::object("nativeID", "box")("opacity", 2))); + ASSERT_NE(resolution->conditionalProps, nullptr); + EXPECT_EQ( + *resolution->conditionalProps, + folly::dynamic(folly::dynamic::object("opacity", opacityValue()))); + EXPECT_EQ(resolution->generation, getMediaFeaturesSnapshot().generation); +} + +TEST_F(ConditionalPropsTest, keepsUpToDateConditionalValuesOfTheSource) { + Props sourceProps; + sourceProps.conditionalProps = std::make_shared( + folly::dynamic::object("opacity", opacityValue())); + sourceProps.conditionalPropsGeneration = + getMediaFeaturesSnapshot().generation; + + auto rawProps = RawProps(folly::dynamic::object("nativeID", "box")); + EXPECT_FALSE(resolveConditionalProps(&sourceProps, rawProps).has_value()); +} + +TEST_F(ConditionalPropsTest, dropsConditionalValuesReplacedByPlainValues) { + Props sourceProps; + sourceProps.conditionalProps = std::make_shared( + folly::dynamic::object("opacity", opacityValue())); + sourceProps.conditionalPropsGeneration = + getMediaFeaturesSnapshot().generation; + + auto rawProps = RawProps(folly::dynamic::object("opacity", 0.5)); + auto resolution = resolveConditionalProps(&sourceProps, rawProps); + ASSERT_TRUE(resolution.has_value()); + EXPECT_EQ( + resolution->rawProps.toDynamic(), + folly::dynamic(folly::dynamic::object("opacity", 0.5))); + EXPECT_EQ(resolution->conditionalProps, nullptr); +} + +TEST_F(ConditionalPropsTest, resolvesOutdatedConditionalValuesOfTheSource) { + Props sourceProps; + sourceProps.conditionalProps = std::make_shared( + folly::dynamic::object("opacity", opacityValue())); + sourceProps.conditionalPropsGeneration = + getMediaFeaturesSnapshot().generation; + + setMediaFeatures(kDarkMoreContrast); + + auto rawProps = RawProps(folly::dynamic::object()); + auto resolution = resolveConditionalProps(&sourceProps, rawProps); + ASSERT_TRUE(resolution.has_value()); + EXPECT_EQ( + resolution->rawProps.toDynamic(), + folly::dynamic(folly::dynamic::object("opacity", 3))); + ASSERT_NE(resolution->conditionalProps, nullptr); + EXPECT_EQ(*resolution->conditionalProps, *sourceProps.conditionalProps); + EXPECT_EQ(resolution->generation, getMediaFeaturesSnapshot().generation); +} diff --git a/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp b/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp new file mode 100644 index 000000000000..ba69d9b9b3ef --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include +#include + +using namespace facebook::react; + +namespace { + +const MediaFeatures kLight{ + .colorScheme = MediaColorScheme::Light, + .contrast = MediaContrast::NoPreference}; +const MediaFeatures kDarkMoreContrast{ + .colorScheme = MediaColorScheme::Dark, + .contrast = MediaContrast::More}; +const MediaFeatures kLessContrast{ + .colorScheme = MediaColorScheme::Light, + .contrast = MediaContrast::Less}; + +} // namespace + +TEST(MediaFeaturesTest, matchesPrefersColorScheme) { + EXPECT_TRUE(matchMediaQuery("@media (prefers-color-scheme: light)", kLight)); + EXPECT_FALSE(matchMediaQuery("@media (prefers-color-scheme: dark)", kLight)); + EXPECT_TRUE(matchMediaQuery( + "@media (prefers-color-scheme: dark)", kDarkMoreContrast)); + EXPECT_FALSE(matchMediaQuery( + "@media (prefers-color-scheme: light)", kDarkMoreContrast)); +} + +TEST(MediaFeaturesTest, matchesPrefersContrast) { + EXPECT_TRUE( + matchMediaQuery("@media (prefers-contrast: no-preference)", kLight)); + EXPECT_FALSE(matchMediaQuery("@media (prefers-contrast: more)", kLight)); + EXPECT_TRUE( + matchMediaQuery("@media (prefers-contrast: more)", kDarkMoreContrast)); + EXPECT_TRUE( + matchMediaQuery("@media (prefers-contrast: less)", kLessContrast)); + EXPECT_FALSE( + matchMediaQuery("@media (prefers-contrast: less)", kDarkMoreContrast)); +} + +TEST(MediaFeaturesTest, ignoresWhitespaceAndCase) { + EXPECT_TRUE(matchMediaQuery( + " @MEDIA( Prefers-Color-Scheme :DARK ) ", kDarkMoreContrast)); +} + +TEST(MediaFeaturesTest, matchesFeaturesCombinedWithAnd) { + constexpr auto query = + "@media (prefers-color-scheme: dark) and (prefers-contrast: more)"; + EXPECT_TRUE(matchMediaQuery(query, kDarkMoreContrast)); + EXPECT_FALSE(matchMediaQuery(query, kLight)); + EXPECT_FALSE(matchMediaQuery( + query, + {.colorScheme = MediaColorScheme::Dark, + .contrast = MediaContrast::NoPreference})); + EXPECT_FALSE(matchMediaQuery( + query, + {.colorScheme = MediaColorScheme::Light, + .contrast = MediaContrast::More})); + + EXPECT_TRUE(matchMediaQuery( + "@media (prefers-color-scheme: dark)AND (prefers-contrast: more) and " + "(prefers-color-scheme: dark)", + kDarkMoreContrast)); +} + +TEST(MediaFeaturesTest, neverMatchesInvalidCombinations) { + // An unsupported feature makes the whole query fail. + EXPECT_FALSE(matchMediaQuery( + "@media (prefers-color-scheme: dark) and (max-width: 800px)", + kDarkMoreContrast)); + EXPECT_FALSE(matchMediaQuery( + "@media (prefers-color-scheme: dark) or (prefers-contrast: more)", + kDarkMoreContrast)); + EXPECT_FALSE(matchMediaQuery( + "@media (prefers-color-scheme: dark) and", kDarkMoreContrast)); + EXPECT_FALSE(matchMediaQuery( + "@media (prefers-color-scheme: dark) and(prefers-contrast: more)", + kDarkMoreContrast)); + EXPECT_FALSE(matchMediaQuery( + "@media (prefers-color-scheme: dark) (prefers-contrast: more)", + kDarkMoreContrast)); + EXPECT_FALSE(matchMediaQuery( + "@media (prefers-color-scheme: dark) and and (prefers-contrast: more)", + kDarkMoreContrast)); +} + +TEST(MediaFeaturesTest, neverMatchesUnsupportedQueries) { + EXPECT_FALSE(matchMediaQuery("@media (max-width: 800px)", kLight)); + EXPECT_FALSE(matchMediaQuery("@media (prefers-color-scheme)", kLight)); + EXPECT_FALSE(matchMediaQuery("@media (prefers-color-scheme: blue)", kLight)); + EXPECT_FALSE(matchMediaQuery("(prefers-color-scheme: light)", kLight)); + EXPECT_FALSE(matchMediaQuery("@media prefers-color-scheme: light", kLight)); + EXPECT_FALSE(matchMediaQuery("", kLight)); +} + +TEST(MediaFeaturesTest, incrementsTheGenerationOnlyOnChange) { + setMediaFeatures(kLight); + auto generation = getMediaFeaturesSnapshot().generation; + + EXPECT_FALSE(setMediaFeatures(kLight)); + EXPECT_EQ(getMediaFeaturesSnapshot().generation, generation); + + EXPECT_TRUE(setMediaFeatures(kDarkMoreContrast)); + auto snapshot = getMediaFeaturesSnapshot(); + EXPECT_EQ(snapshot.generation, generation + 1); + EXPECT_EQ(snapshot.features, kDarkMoreContrast); + + setMediaFeatures(kLight); +} diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp index a278fb2b3400..0abc1a405fd2 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp @@ -459,6 +459,24 @@ void Scheduler::reportMount(SurfaceId surfaceId) const { uiManager_->reportMount(surfaceId); } +void Scheduler::updateMediaFeatures(const MediaFeatures& mediaFeatures) { + // The media features are global to the process: another scheduler may + // already have set them. Comparing generations tells whether the shadow + // trees of this scheduler still need an update. + setMediaFeatures(mediaFeatures); + auto generation = getMediaFeaturesSnapshot().generation; + if (mediaFeaturesGeneration_.exchange(generation) == generation) { + return; + } + + runtimeExecutor_([weakUIManager = std::weak_ptr(uiManager_)]( + jsi::Runtime& /*runtime*/) { + if (auto uiManager = weakUIManager.lock()) { + uiManager->updateConditionalProps(); + } + }); +} + std::shared_ptr Scheduler::getContextContainer() const { return contextContainer_; } diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h index 139df24d68d3..139a9b4b6401 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h @@ -114,6 +114,16 @@ class Scheduler final : public UIManagerDelegate { void reportMount(SurfaceId surfaceId) const; +#pragma mark - Media features + + /* + * Sets the media features that conditional props (for example with + * `@media (prefers-color-scheme: dark)`) are matched against. If they + * changed, the shadow trees of this scheduler are updated on the JavaScript + * thread. Thread-safe. + */ + void updateMediaFeatures(const MediaFeatures &mediaFeatures); + #pragma mark - Event listeners void addEventListener(std::shared_ptr listener); void removeEventListener(const std::shared_ptr &listener); @@ -129,6 +139,10 @@ class Scheduler final : public UIManagerDelegate { RuntimeExecutor runtimeExecutor_; std::shared_ptr uiManager_; + // The generation of the media features that this scheduler last updated its + // shadow trees for. + std::atomic mediaFeaturesGeneration_{0}; + std::vector> commitHooks_; /* diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h index 541d57a0b258..1a32f410352e 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h @@ -220,6 +220,14 @@ class UIManager final : public ShadowTreeDelegate { void updateShadowTree(std::unordered_map &&tagToProps); + /* + * Resolves again, in all shadow trees, the conditional props (for example + * with media queries) that were resolved with older media features, and + * commits the result. Call it on the JavaScript thread, so that React keeps + * references to the new shadow nodes. + */ + void updateConditionalProps() const; + #pragma mark - ContextContainer std::shared_ptr getContextContainer() const; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerUpdateConditionalProps.cpp b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerUpdateConditionalProps.cpp new file mode 100644 index 000000000000..eef8522e3fa5 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerUpdateConditionalProps.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "UIManager.h" + +#include +#include +#include +#include +#include + +namespace facebook::react { + +namespace { + +/* + * Returns a clone of `shadowNode` where the props with conditional values that + * were resolved with an older generation of the media features are resolved + * again. Returns `nullptr` if nothing changed in the subtree. + */ +std::shared_ptr cloneWithUpdatedConditionalProps( + const ShadowNode& shadowNode, + const PropsParserContext& context, + MediaFeaturesGeneration generation) { + const auto& children = shadowNode.getChildren(); + std::shared_ptr>> newChildren; + for (size_t index = 0; index < children.size(); index++) { + auto newChild = + cloneWithUpdatedConditionalProps(*children[index], context, generation); + if (newChild) { + if (!newChildren) { + newChildren = + std::make_shared>>( + children); + } + (*newChildren)[index] = std::move(newChild); + } + } + + Props::Shared newProps; + const auto& props = shadowNode.getProps(); + if (props->conditionalProps != nullptr && + props->conditionalPropsGeneration != generation) { + // Empty raw props: `cloneProps` resolves the outdated conditional values + // of `props` again. + newProps = shadowNode.getComponentDescriptor().cloneProps( + context, props, RawProps(folly::dynamic::object())); + } + + if (!newChildren && !newProps) { + return nullptr; + } + + std::shared_ptr>> + fragmentChildren = + newChildren ? newChildren : ShadowNodeFragment::childrenPlaceholder(); + + return shadowNode.clone({ + .props = newProps ? newProps : ShadowNodeFragment::propsPlaceholder(), + .children = fragmentChildren, + }); +} + +} // namespace + +void UIManager::updateConditionalProps() const { + TraceSection s("UIManager::updateConditionalProps"); + + auto generation = getMediaFeaturesSnapshot().generation; + + shadowTreeRegistry_.enumerate([&](const ShadowTree& shadowTree, + bool& /*stop*/) { + PropsParserContext context{shadowTree.getSurfaceId(), *contextContainer_}; + shadowTree.commit( + [&](const RootShadowNode& oldRootShadowNode) + -> RootShadowNode::Unshared { + return std::static_pointer_cast( + cloneWithUpdatedConditionalProps( + oldRootShadowNode, context, generation)); + }, + {.enableStateReconciliation = true}); + }); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index b352f656de23..e3feaddefabd 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<57f47f589dc7eb46102f17c4570f55c3>> + * @generated SignedSource<> * * This file was generated by scripts/js-api/build-types/index.js. */ @@ -732,7 +732,9 @@ declare type ____ShadowStyle_InternalCore = { } declare type ____ShadowStyle_InternalOverrides = {} declare type ____Styles_Internal = { - readonly [key: string]: Partial<____DangerouslyImpreciseStyle_Internal> + readonly [key: string]: Partial< + WithConditionalStyleValues<____DangerouslyImpreciseStyle_Internal> + > } declare type ____TextStyle_InternalBase = { readonly color?: ____ColorValue_Internal @@ -1784,6 +1786,16 @@ declare type CompositeAnimation = { start: (callback?: EndCallback | undefined, isLooping?: boolean) => void stop: () => void } +declare type ConditionalStyleValue = { + readonly [mediaQuery: string]: ConditionalStyleValueBranch + readonly default: ConditionalStyleValueBranch +} +declare type ConditionalStyleValueBranch = + | T + | { + readonly [mediaQuery: string]: T + readonly default: T + } declare function configureNext( config: LayoutAnimationConfig, onAnimationDidEnd?: OnAnimationDidEndCallback, @@ -4863,7 +4875,13 @@ declare type StickyHeaderComponentType = ( }, ) => React.ReactNode declare type StyleProp = - "" | false | null | ReadonlyArray> | T | void + | "" + | false + | null + | ReadonlyArray> + | T + | void + | WithConditionalStyleValues declare namespace StyleSheet { export { AbsoluteFillStyle, @@ -5835,6 +5853,9 @@ declare type WithAnimatedValue = T extends Builtin | Nullable : T extends {} ? { readonly [K in keyof T]: WithAnimatedValue } : T +declare type WithConditionalStyleValues = T extends {} + ? { readonly [K in keyof T]: ConditionalStyleValue | T[K] } + : T declare type WithDefault< Type extends DefaultTypes, Value extends (null | Type | undefined) | string, @@ -5856,24 +5877,24 @@ export { AccessibilityValue, // cf8bcb74 ActionSheetIOS, // b558559e ActionSheetIOSOptions, // 1756eb5a - ActivityIndicator, // b9f6c361 + ActivityIndicator, // db93587e ActivityIndicatorInstance, // 203a7308 - ActivityIndicatorProps, // 45a4dd7e + ActivityIndicatorProps, // 5b1688b9 Alert, // a398a509 AlertButton, // bf1a3b60 AlertButtonStyle, // ec9fb242 AlertOptions, // 8a116d2a AlertType, // 5ab91217 AndroidKeyboardEvent, // e03becc8 - Animated, // eabf9148 - AnimatedFlatList, // 7dd37b2f - AnimatedImage, // 70a521de - AnimatedScrollView, // 6e7d4228 - AnimatedSectionList, // ae393fe9 - AnimatedText, // 55bc68a2 - AnimatedView, // ed267c3c + Animated, // 828f966e + AnimatedFlatList, // 07b39f12 + AnimatedImage, // a3bd201a + AnimatedScrollView, // b8f36597 + AnimatedSectionList, // 98a492bd + AnimatedText, // 14c75629 + AnimatedView, // c0d8ef98 AppConfig, // 80afc5fa - AppRegistry, // b906537d + AppRegistry, // 68b6aa73 AppState, // db34d225 AppStateEvent, // 80f034c3 AppStateStatus, // 447e5ef2 @@ -5885,8 +5906,8 @@ export { BackPressEventName, // 4620fb76 BlurEvent, // 81e2d52d BoxShadowValue, // b679703f - Button, // a8154deb - ButtonInstance, // 2171b004 + Button, // 272f1127 + ButtonInstance, // 6ec92866 ButtonProps, // 39ba1271 CodegenTypes, // 8225fbd1 ColorSchemeName, // 6615edd6 @@ -5904,9 +5925,9 @@ export { DimensionsPayload, // 653bc26c DisplayMetrics, // 1dc35cef DisplayMetricsAndroid, // 872e62eb - DrawerLayoutAndroid, // e17f5c7f + DrawerLayoutAndroid, // dc4e455c DrawerLayoutAndroidInstance, // aa243cbf - DrawerLayoutAndroidProps, // 888a0cd8 + DrawerLayoutAndroidProps, // acecd68e DrawerSlideEvent, // 4fa8f7ff DropShadowValue, // e9df2606 DynamicColorIOS, // d96c228c @@ -5922,9 +5943,9 @@ export { EventSubscription, // b8d084aa ExtendedExceptionData, // 5a6ccf5a FilterFunction, // bf24c0e3 - FlatList, // 93582d36 - FlatListInstance, // 44658d70 - FlatListProps, // 9bd2f266 + FlatList, // 55faa351 + FlatListInstance, // 6f9e8a67 + FlatListProps, // 73a2acd4 FocusEvent, // eaa2af9d FontVariant, // 7c7558bb GestureResponderEvent, // 8a8611e2 @@ -5935,17 +5956,17 @@ export { IEventEmitter, // fbef6131 IOSKeyboardEvent, // e67bfe3a IgnorePattern, // ec6f6ece - Image, // 525435c5 - ImageBackground, // d15d8abb - ImageBackgroundInstance, // 87cb3a96 - ImageBackgroundProps, // 3c909664 + Image, // bfe9f3e9 + ImageBackground, // aa859ee5 + ImageBackgroundInstance, // a324870e + ImageBackgroundProps, // 64375e6e ImageErrorEvent, // 91b7bd15 ImageInstance, // f5ca8548 ImageLoadEvent, // 26c72f36 ImageProgressEventIOS, // 78694e24 - ImageProps, // d0584850 + ImageProps, // d1e0379d ImagePropsAndroid, // 283349a4 - ImagePropsBase, // 6203d7f7 + ImagePropsBase, // 08566c9b ImagePropsIOS, // ebd30376 ImageRequireSource, // 681d683b ImageResizeMode, // d51106e2 @@ -5955,17 +5976,17 @@ export { ImageSourcePropType, // ff97c174 ImageStyle, // 85dc694a ImageURISource, // 9bf63692 - InputAccessoryView, // ab6e2a66 - InputAccessoryViewProps, // 73685b83 + InputAccessoryView, // 9d61f4c2 + InputAccessoryViewProps, // e29f4eae InputModeOptions, // 4e8581b9 Insets, // e7fe432a KeyDownEvent, // cc4773b1 KeyEvent, // 20fa4267 KeyUpEvent, // c4e5a70b Keyboard, // a26f7bd4 - KeyboardAvoidingView, // 668b6171 - KeyboardAvoidingViewInstance, // ce03459c - KeyboardAvoidingViewProps, // 53cc84d8 + KeyboardAvoidingView, // 909db07b + KeyboardAvoidingViewInstance, // ac7700ad + KeyboardAvoidingViewProps, // 41c36318 KeyboardEvent, // c3f895d4 KeyboardEventEasing, // af4091c8 KeyboardEventName, // 59299ad6 @@ -5990,10 +6011,10 @@ export { MeasureInWindowOnSuccessCallback, // a285f598 MeasureLayoutOnSuccessCallback, // 3592502a MeasureOnSuccessCallback, // 82824e59 - Modal, // d422cbdb + Modal, // 4a71f045 ModalBaseProps, // fe84ee7f ModalInstance, // e66062fb - ModalProps, // ee71f2ac + ModalProps, // 79361e93 ModalPropsAndroid, // 515fb173 ModalPropsIOS, // 2b335b15 ModeChangeEvent, // 9ccef558 @@ -6029,15 +6050,15 @@ export { PointerEvent, // 06310bdb PressabilityConfig, // ed721435 PressabilityEventHandlers, // 314a0b05 - Pressable, // b430b931 + Pressable, // eee2d67c PressableAndroidRippleConfig, // ee32eaca PressableInstance, // a13c73cb - PressableProps, // 5f06b483 + PressableProps, // 6f4e2baa PressableStateCallbackType, // f83728cd ProcessedColorValue, // 33f74304 - ProgressBarAndroid, // 7d199258 + ProgressBarAndroid, // d4dee391 ProgressBarAndroidInstance, // e25bcc95 - ProgressBarAndroidProps, // 07593242 + ProgressBarAndroidProps, // 0156e7ea PublicRootInstance, // 8040afd7 PublicTextInstance, // 42c897b3 PushNotificationEventName, // 84e7e150 @@ -6045,9 +6066,9 @@ export { PushNotificationPermissions, // c2e7ae4f Rationale, // 5df1b1c1 ReactNativeVersion, // abd76827 - RefreshControl, // db42b24c - RefreshControlInstance, // fd5c0365 - RefreshControlProps, // e839b56d + RefreshControl, // 4a318b5a + RefreshControlInstance, // 54eb5d31 + RefreshControlProps, // 3893c5d3 RefreshControlPropsAndroid, // 8ac931ca RefreshControlPropsIOS, // 72a36381 Registry, // e7beb42e @@ -6056,29 +6077,29 @@ export { Role, // af7b889d RootTag, // 3cd10504 RootTagContext, // 38bfc8f6 - RootViewStyleProvider, // 716d0b7f + RootViewStyleProvider, // 724a7e93 Runnable, // 557d13d9 Runnables, // 75114853 SafeAreaInsets, // 64d7a605 SafeAreaInsetsChangeEvent, // e63da69b - SafeAreaView, // c3188b34 + SafeAreaView, // 4993cc80 SafeAreaViewInstance, // 620923d2 ScaledSize, // 07e417c7 ScrollEvent, // 5b300f75 - ScrollResponderType, // d454c555 + ScrollResponderType, // c206c3e2 ScrollToLocationParamsType, // d7ecdad1 - ScrollView, // ded391d4 - ScrollViewImperativeMethods, // bbff2b8c - ScrollViewInstance, // a59c167a - ScrollViewProps, // 0f5f149e + ScrollView, // 73d101f9 + ScrollViewImperativeMethods, // 62befec8 + ScrollViewInstance, // 998c1f98 + ScrollViewProps, // be0024eb ScrollViewPropsAndroid, // 02f3df2e ScrollViewPropsIOS, // b2cf82e0 ScrollViewScrollToOptions, // 3313411e SectionBase, // 9f13db00 - SectionList, // 0c0b716d + SectionList, // 5906451b SectionListData, // 1a4de01a - SectionListInstance, // 2ce6ff23 - SectionListProps, // 270e3f29 + SectionListInstance, // 06864429 + SectionListProps, // ebc47474 SectionListRenderItem, // 715b2086 SectionListRenderItemInfo, // 4a48a922 Separators, // 6a45f7e3 @@ -6094,20 +6115,20 @@ export { StatusBarInstance, // de13e4a1 StatusBarProps, // c2a44d88 StatusBarStyle, // 78f53eea - StyleProp, // fa0e9b4a - StyleSheet, // cf156a8b + StyleProp, // 2b847ce6 + StyleSheet, // 7a662751 SubmitBehavior, // c4ddf490 - Switch, // b810ece4 + Switch, // c47f1fa6 SwitchChangeEvent, // 4d12c11f SwitchInstance, // 389a240b - SwitchProps, // c86198ca + SwitchProps, // 69d2b43a Systrace, // 2a0a0871 TVViewPropsIOS, // 1c612e4e TargetedEvent, // 16e98910 TaskProvider, // 266dedf2 - Text, // 841fd00c + Text, // dd2520dd TextContentType, // 239b3ecc - TextInput, // f4502971 + TextInput, // 7e4d6c31 TextInputAndroidProps, // 9ebbc103 TextInputBlurEvent, // c04c4bf0 TextInputChangeEvent, // ed7f8b04 @@ -6117,34 +6138,34 @@ export { TextInputIOSProps, // fb3c9327 TextInputInstance, // d442c53f TextInputKeyPressEvent, // 07548cd0 - TextInputProps, // 0166e0c9 + TextInputProps, // 8d8c36b2 TextInputSelectionChangeEvent, // 131f3be5 TextInputSubmitEditingEvent, // f2ad5e3b TextInstance, // 5d4340ff TextLayoutEvent, // bcd28f9a - TextProps, // 78881b55 + TextProps, // b95d4e9e TextStyle, // 898adfd1 ToastAndroid, // 88a8969a - TouchableHighlight, // c355bdc0 + TouchableHighlight, // d5d44e9e TouchableHighlightInstance, // 86235e9b - TouchableHighlightProps, // 9d69cf73 - TouchableNativeFeedback, // aa19af38 - TouchableNativeFeedbackInstance, // 063cefb1 - TouchableNativeFeedbackProps, // 8c37965a - TouchableOpacity, // f7c31bda + TouchableHighlightProps, // 0a68da65 + TouchableNativeFeedback, // d63a57bf + TouchableNativeFeedbackInstance, // 5d507633 + TouchableNativeFeedbackProps, // 6fe85f4e + TouchableOpacity, // e1cab824 TouchableOpacityInstance, // 174a3ad9 - TouchableOpacityProps, // 839b5f73 - TouchableWithoutFeedback, // 3371c1e0 - TouchableWithoutFeedbackProps, // 86d9d4ef + TouchableOpacityProps, // 98fce3b3 + TouchableWithoutFeedback, // 8e13c7df + TouchableWithoutFeedbackProps, // ec0ae881 TransformsStyle, // 65e70f18 TurboModule, // dfe29706 TurboModuleRegistry, // 4ace6db2 UIManager, // 6a18fc05 UTFSequence, // ad625158 Vibration, // 31e4bbf8 - View, // 37dd3f10 + View, // d1f6b4ee ViewInstance, // da166ce1 - ViewProps, // 0a38b735 + ViewProps, // 07a15b58 ViewPropsAndroid, // 66397d7f ViewPropsIOS, // 58ee19bf ViewStyle, // 4e2746d6 @@ -6153,10 +6174,10 @@ export { VirtualViewMode, // 6be59722 VirtualizedList, // 68c7345e VirtualizedListInstance, // 423ee7c0 - VirtualizedListProps, // 7eb90be3 + VirtualizedListProps, // bc41a1e9 VirtualizedSectionList, // 9fd9cd61 VirtualizedSectionListInstance, // 12b706d5 - VirtualizedSectionListProps, // 645dfd17 + VirtualizedSectionListProps, // f892536c WrapperComponentProvider, // 6ce47ba4 codegenNativeCommands, // 322f3f4e codegenNativeComponent, // c9cccb03 diff --git a/packages/react-native/__typetests__/stylesheet-media-queries.tsx b/packages/react-native/__typetests__/stylesheet-media-queries.tsx new file mode 100644 index 000000000000..089591ace557 --- /dev/null +++ b/packages/react-native/__typetests__/stylesheet-media-queries.tsx @@ -0,0 +1,40 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import * as React from 'react'; +import {StyleSheet, Text, View} from 'react-native'; + +const DARK = '@media (prefers-color-scheme: dark)'; +const MORE_CONTRAST = '@media (prefers-contrast: more)'; + +const styles = StyleSheet.create({ + container: { + width: {default: 800, [DARK]: '100%'}, + backgroundColor: { + default: 'white', + [DARK]: {default: 'black', [MORE_CONTRAST]: 'blue'}, + }, + }, + text: { + color: {default: 'black', [DARK]: 'white'}, + }, + invalid: { + // Should error: the values must have the type of the style prop + // @ts-expect-error + width: {default: 800, [DARK]: true}, + }, +}); + +export function App() { + return ( + + Hello + + ); +} diff --git a/packages/react-native/package.json b/packages/react-native/package.json index 0a5e87ee89d1..36e4764325a5 100644 --- a/packages/react-native/package.json +++ b/packages/react-native/package.json @@ -158,10 +158,10 @@ "@react-native/virtualized-lists": "0.87.0-main", "anser": "^1.4.9", "ansi-regex": "^5.0.0", - "flow-parser": "0.336.0", "base64-js": "^1.5.1", "flow-enums-runtime": "^0.0.6", - "hermes-compiler": "0.0.0", + "flow-parser": "0.336.0", + "hermes-compiler": "260318099.0.7", "invariant": "^2.2.4", "memoize-one": "^6.0.0", "metro-runtime": "^0.88.0", diff --git a/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js b/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js index d4ef3a3e39ca..2b1d9e8b4d8b 100644 --- a/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js +++ b/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js @@ -138,6 +138,7 @@ interface Spec extends TurboModule { setImageResponse(uri: string, imageResponse: ImageResponse): void; clearImage(uri: string): void; clearAllImages(): void; + setMediaFeatures: (colorScheme: string, contrast: string) => void; } export default TurboModuleRegistry.getEnforcing( diff --git a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js index 8e6b10479de7..c745cce0bbfd 100644 --- a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js +++ b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js @@ -9,24 +9,240 @@ */ import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; +import type {ColorSchemeOverride} from 'react-native/Libraries/Utilities/Appearance'; import RNTesterText from '../../components/RNTesterText'; +import RNTOption from '../../components/RNTOption'; import * as React from 'react'; -import {StyleSheet, View} from 'react-native'; +import {memo, useEffect, useRef, useState} from 'react'; +import { + Appearance, + Platform, + ScrollView, + StyleSheet, + Text, + View, + useColorScheme, +} from 'react-native'; + +const DARK = '@media (prefers-color-scheme: dark)'; +const LESS_CONTRAST = '@media (prefers-contrast: less)'; +const MORE_CONTRAST = '@media (prefers-contrast: more)'; +const DARK_AND_MORE_CONTRAST = + '@media (prefers-color-scheme: dark) and (prefers-contrast: more)'; + +const CONTRAST_SETTING = + Platform.OS === 'ios' + ? 'Settings > Accessibility > Display & Text Size > Increase Contrast' + : 'Settings > Accessibility > Contrast (Android 14+), or High contrast text'; + +const COLOR_SCHEME_OPTIONS: ReadonlyArray<{ + label: string, + value: ColorSchemeOverride, +}> = [ + {label: 'System', value: 'unspecified'}, + {label: 'Light', value: 'light'}, + {label: 'Dark', value: 'dark'}, +]; + +function ColorSchemeSelector() { + const colorScheme = useColorScheme(); + const [override, setOverride] = useState('unspecified'); + const hasChangedOverride = useRef(false); + + useEffect(() => { + return () => { + // Do not keep the override after leaving the playground. + if (hasChangedOverride.current) { + Appearance.setColorScheme('unspecified'); + } + }; + }, []); -function Playground() { return ( - - - Edit "RNTesterPlayground.js" to change this file + + Color scheme + + {COLOR_SCHEME_OPTIONS.map(option => ( + { + hasChangedOverride.current = true; + setOverride(option.value); + Appearance.setColorScheme(option.value); + }} + /> + ))} + + + useColorScheme(): {colorScheme ?? 'null'} + + To change the contrast: {CONTRAST_SETTING}. + + + ); +} + +function Example({ + title, + description, + children, +}: { + title: string, + description: string, + children: React.Node, +}) { + return ( + + {title} + {description} + {children} ); } +// This component renders once. Its colors still change with the media +// features, because native resolves the media queries. +const MemoizedBox = memo(function MemoizedBox() { + const renderCount = useRef(0); + renderCount.current++; + + return ( + + + React renders: {renderCount.current} + + + ); +}); + +function Playground() { + return ( + + + + + + Hello + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +} + const styles = StyleSheet.create({ container: { padding: 10, + gap: 20, + }, + section: { + gap: 8, + }, + title: { + fontSize: 16, + fontWeight: 'bold', + }, + note: { + fontSize: 12, + }, + options: { + flexDirection: 'row', + gap: 8, + }, +}); + +const examples = StyleSheet.create({ + box: { + height: 50, + borderRadius: 8, + }, + colorScheme: { + padding: 12, + borderRadius: 8, + borderWidth: 1, + borderColor: 'gray', + backgroundColor: {default: 'white', [DARK]: 'black'}, + }, + colorSchemeText: { + color: {default: 'black', [DARK]: 'white'}, + }, + contrast: { + height: 50, + borderRadius: 8, + borderWidth: {default: 2, [LESS_CONTRAST]: 1, [MORE_CONTRAST]: 6}, + borderColor: { + default: 'gray', + [LESS_CONTRAST]: 'lightgray', + [MORE_CONTRAST]: 'black', + }, + }, + combined: { + height: 50, + borderRadius: 8, + backgroundColor: {default: 'gray', [DARK_AND_MORE_CONTRAST]: 'red'}, + }, + nested: { + height: 50, + borderRadius: 8, + backgroundColor: { + default: 'lightblue', + [DARK]: {default: 'darkblue', [MORE_CONTRAST]: 'yellow'}, + }, + }, + layout: { + height: 50, + borderRadius: 8, + backgroundColor: 'green', + width: {default: '50%', [DARK]: '100%'}, }, }); diff --git a/private/react-native-fantom/src/index.js b/private/react-native-fantom/src/index.js index 2d5ee2504383..9275fd8718f9 100644 --- a/private/react-native-fantom/src/index.js +++ b/private/react-native-fantom/src/index.js @@ -722,6 +722,30 @@ export function enqueueModalSizeUpdate( NativeFantom.enqueueModalSizeUpdate(shadowNode, size.width, size.height); } +/** + * Sets the media features that conditional style values are matched against, + * for example `{default: 'white', '@media (prefers-color-scheme: dark)': + * 'black'}`, and updates the mounted shadow trees. + * + * @example + * ``` + * Fantom.runTask(() => { + * Fantom.setMediaFeatures({colorScheme: 'dark'}); + * }); + * ``` + */ +export function setMediaFeatures( + mediaFeatures: Readonly<{ + colorScheme?: 'light' | 'dark', + contrast?: 'no-preference' | 'less' | 'more', + }>, +) { + NativeFantom.setMediaFeatures( + mediaFeatures.colorScheme ?? 'light', + mediaFeatures.contrast ?? 'no-preference', + ); +} + export const unstable_benchmark = Benchmark; export type { diff --git a/private/react-native-fantom/tester/src/NativeFantom.cpp b/private/react-native-fantom/tester/src/NativeFantom.cpp index 0567b1746af1..93d5ed4e7190 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.cpp +++ b/private/react-native-fantom/tester/src/NativeFantom.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -235,6 +236,22 @@ void NativeFantom::enqueueScrollEvent( }); } +void NativeFantom::setMediaFeatures( + jsi::Runtime& runtime, + const std::string& colorScheme, + const std::string& contrast) { + facebook::react::setMediaFeatures({ + .colorScheme = colorScheme == "dark" ? MediaColorScheme::Dark + : MediaColorScheme::Light, + .contrast = contrast == "more" ? MediaContrast::More + : contrast == "less" ? MediaContrast::Less + : MediaContrast::NoPreference, + }); + UIManagerBinding::getBinding(runtime) + ->getUIManager() + .updateConditionalProps(); +} + void NativeFantom::enqueueModalSizeUpdate( jsi::Runtime& /*runtime*/, std::shared_ptr shadowNode, diff --git a/private/react-native-fantom/tester/src/NativeFantom.h b/private/react-native-fantom/tester/src/NativeFantom.h index b26aa851c17e..c3016f9a47a3 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.h +++ b/private/react-native-fantom/tester/src/NativeFantom.h @@ -152,6 +152,8 @@ class NativeFantom : public NativeFantomCxxSpec { void clearImage(jsi::Runtime &rt, const std::string &uri); void clearAllImages(jsi::Runtime &rt); + void setMediaFeatures(jsi::Runtime &runtime, const std::string &colorScheme, const std::string &contrast); + private: TesterAppDelegate &appDelegate_; std::unordered_map assetPaths_; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index 1a3a9cf6d207..44ca8eaabdac 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -1594,6 +1594,7 @@ interface RCTScheduler : public NSObject { public virtual void reportMount:(facebook::react::SurfaceId surfaceId); public virtual void setupAnimationDriver:(const facebook::react::SurfaceHandler& surfaceHandler); public virtual void unregisterSurface:(const facebook::react::SurfaceHandler& surfaceHandler); + public virtual void updateMediaFeatures:(const facebook::react::MediaFeatures& mediaFeatures); } interface RCTScrollEvent : public NSObject { @@ -3084,6 +3085,7 @@ struct facebook::hermes::ISetEventLoopControl : public facebook::jsi::ICast { const char facebook::react::ViewComponentName[]; const facebook::react::EventTag facebook::react::EMPTY_EVENT_TAG; +constexpr char* facebook::react::kConditionalPropsName; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -3130,6 +3132,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -3190,6 +3193,8 @@ bool facebook::react::areBorderRadiiCircular(const facebook::react::BorderRadii& bool facebook::react::hostPlatformColorIsColorMeaningful(facebook::react::Color color) noexcept; bool facebook::react::isColorMeaningful(const facebook::react::SharedColor& color) noexcept; bool facebook::react::isZero(facebook::react::Float n); +bool facebook::react::matchMediaQuery(std::string_view query, const facebook::react::MediaFeatures& features) noexcept; +bool facebook::react::setMediaFeatures(const facebook::react::MediaFeatures& features) noexcept; constexpr auto facebook::react::to_underlying(auto e) noexcept; constexpr char facebook::react::toLower(char c); constexpr uint32_t facebook::react::fnv1aLowercase(std::string_view string); @@ -3203,6 +3208,7 @@ facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay facebook::react::Float facebook::react::floatFromYogaFloat(float value); facebook::react::Float facebook::react::floatFromYogaOptionalFloat(facebook::yoga::FloatOptional value); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); +facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; facebook::react::SharedColor facebook::react::blackColor(); @@ -3221,9 +3227,11 @@ float facebook::react::blueFromHostPlatformColor(facebook::react::Color color); float facebook::react::greenFromHostPlatformColor(facebook::react::Color color); float facebook::react::redFromHostPlatformColor(facebook::react::Color color); float facebook::react::yogaFloatFromFloat(facebook::react::Float value); +folly::dynamic facebook::react::resolveConditionalValue(const folly::dynamic& conditionalValue, const facebook::react::MediaFeatures& features); int facebook::react::toInt(const facebook::react::DisplayType& displayType); int facebook::react::toInt(const facebook::react::LayoutDirection& layoutDirection); std::optional facebook::react::blendModeFromString(std::string_view blendModeName); +std::optional facebook::react::resolveConditionalProps(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps); std::optional facebook::react::filterTypeFromString(std::string_view filterName); std::optional facebook::react::optionalFloatFromYogaValue(const facebook::yoga::Style::Length& length, std::optional base = {}); std::optional facebook::react::isolationFromString(std::string_view isolationSetting); @@ -4297,7 +4305,9 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); + public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalProps; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -4349,6 +4359,7 @@ class facebook::react::RawProps { public RawProps(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& value) noexcept; public RawProps(facebook::react::RawProps&& other) noexcept = default; public RawProps(folly::dynamic dynamic) noexcept; + public bool hasProperty(const char* name) const; public bool isEmpty() const noexcept; public const facebook::react::RawValue* at(const char* name) const noexcept; public const facebook::react::RawValue* at(const char* name, const char* prefix, const char* suffix) const noexcept; @@ -4966,6 +4977,17 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaColorScheme : uint8_t { + Dark, + Light, +} + +enum facebook::react::MediaContrast : uint8_t { + Less, + More, + NoPreference, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -5282,6 +5304,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalProps; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -5370,6 +5398,17 @@ struct facebook::react::LinearGradient { public std::vector colorStops; } +struct facebook::react::MediaFeatures { + public bool operator==(const facebook::react::MediaFeatures& other) const = default; + public facebook::react::MediaColorScheme colorScheme; + public facebook::react::MediaContrast contrast; +} + +struct facebook::react::MediaFeaturesSnapshot { + public facebook::react::MediaFeatures features; + public facebook::react::MediaFeaturesGeneration generation; +} + struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { public facebook::react::ModalHostViewSupportedOrientationsMask value; } diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index 9566f14830b4..fb56b44c73f6 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -1637,6 +1637,7 @@ interface RCTScheduler : public NSObject { public virtual void reportMount:(facebook::react::SurfaceId surfaceId); public virtual void setupAnimationDriver:(const facebook::react::SurfaceHandler& surfaceHandler); public virtual void unregisterSurface:(const facebook::react::SurfaceHandler& surfaceHandler); + public virtual void updateMediaFeatures:(const facebook::react::MediaFeatures& mediaFeatures); } interface RCTScrollEvent : public NSObject { @@ -3196,6 +3197,7 @@ const char facebook::react::ViewComponentName[]; const facebook::react::EventTag facebook::react::EMPTY_EVENT_TAG; constexpr auto facebook::react::kSimpleThreadSafeCacheSizeCap; constexpr char* const facebook::react::TextLayoutManagerKey; +constexpr char* facebook::react::kConditionalPropsName; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr float facebook::react::kDefaultEpsilon; @@ -3284,6 +3286,7 @@ using facebook::react::LayoutConformanceComponentDescriptor = facebook::react::C using facebook::react::LineMeasureCache = facebook::react::SimpleThreadSafeCache; using facebook::react::LinesMeasurements = std::vector; using facebook::react::Logger = std::function; +using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::MountingTransactionCallback = std::function; using facebook::react::NativeMethodCallFunc = std::function; @@ -3445,6 +3448,8 @@ bool facebook::react::hostPlatformColorIsColorMeaningful(facebook::react::Color bool facebook::react::isColorMeaningful(const facebook::react::SharedColor& color) noexcept; bool facebook::react::isHermesBytecodeBundle(const facebook::react::BundleHeader& header); bool facebook::react::isZero(facebook::react::Float n); +bool facebook::react::matchMediaQuery(std::string_view query, const facebook::react::MediaFeatures& features) noexcept; +bool facebook::react::setMediaFeatures(const facebook::react::MediaFeatures& features) noexcept; const char* facebook::react::stringForScriptTag(const facebook::react::ScriptTag& tag); constexpr auto facebook::react::to_underlying(auto e) noexcept; constexpr bool facebook::react::iequals(std::string_view a, std::string_view b); @@ -3464,6 +3469,7 @@ facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay facebook::react::Float facebook::react::floatFromYogaFloat(float value); facebook::react::Float facebook::react::floatFromYogaOptionalFloat(facebook::yoga::FloatOptional value); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); +facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; facebook::react::ParagraphAttributes facebook::react::convertRawProp(const facebook::react::PropsParserContext& context, const facebook::react::RawProps& rawProps, const facebook::react::ParagraphAttributes& sourceParagraphAttributes, const facebook::react::ParagraphAttributes& defaultParagraphAttributes); facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; @@ -3490,6 +3496,7 @@ float facebook::react::yogaFloatFromFloat(facebook::react::Float value); folly::dynamic facebook::react::convertIdToFollyDynamic(id json); folly::dynamic facebook::react::diffDynamicProps(const folly::dynamic& oldProps, const folly::dynamic& newProps); folly::dynamic facebook::react::mergeDynamicProps(const folly::dynamic& source, const folly::dynamic& patch, facebook::react::NullValueStrategy nullValueStrategy); +folly::dynamic facebook::react::resolveConditionalValue(const folly::dynamic& conditionalValue, const facebook::react::MediaFeatures& features); id facebook::react::convertFollyDynamicToId(const folly::dynamic& dyn); int facebook::react::toInt(const facebook::react::DisplayType& displayType); int facebook::react::toInt(const facebook::react::LayoutDirection& layoutDirection); @@ -3499,6 +3506,7 @@ size_t facebook::react::attributedStringHashDisplayWise(const facebook::react::A size_t facebook::react::attributedStringHashLayoutWise(const facebook::react::AttributedString& attributedString); size_t facebook::react::textAttributesHashLayoutWise(const facebook::react::TextAttributes& textAttributes); std::optional facebook::react::blendModeFromString(std::string_view blendModeName); +std::optional facebook::react::resolveConditionalProps(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps); std::optional facebook::react::filterTypeFromString(std::string_view filterName); std::optional facebook::react::optionalFloatFromYogaValue(const facebook::yoga::Style::Length& length, std::optional base = {}); std::optional facebook::react::fontVariantFromCSSFontVariant(facebook::react::CSSFontVariant cssVariant); @@ -5376,7 +5384,9 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); + public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalProps; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -5442,6 +5452,7 @@ class facebook::react::RawProps { public RawProps(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& value) noexcept; public RawProps(facebook::react::RawProps&& other) noexcept = default; public RawProps(folly::dynamic dynamic) noexcept; + public bool hasProperty(const char* name) const; public bool isEmpty() const noexcept; public const facebook::react::RawValue* at(const char* name) const noexcept; public const facebook::react::RawValue* at(const char* name, const char* prefix, const char* suffix) const noexcept; @@ -5692,6 +5703,7 @@ class facebook::react::Scheduler : public facebook::react::UIManagerDelegate { public void reportMount(facebook::react::SurfaceId surfaceId) const; public void setDelegate(facebook::react::SchedulerDelegate* delegate); public void unregisterSurface(const facebook::react::SurfaceHandler& surfaceHandler) const noexcept; + public void updateMediaFeatures(const facebook::react::MediaFeatures& mediaFeatures); public ~Scheduler() override; } @@ -6333,6 +6345,7 @@ class facebook::react::UIManager : public facebook::react::ShadowTreeDelegate { public void synchronouslyUpdateViewOnUIThread(facebook::react::Tag tag, const folly::dynamic& props); public void unregisterCommitHook(facebook::react::UIManagerCommitHook& commitHook); public void unregisterMountHook(facebook::react::UIManagerMountHook& mountHook); + public void updateConditionalProps() const; public void updateShadowTree(std::unordered_map&& tagToProps); public void updateState(const facebook::react::StateUpdate& stateUpdate) const; public void visitBinding(const std::function& callback, facebook::jsi::Runtime& runtime) const; @@ -7252,6 +7265,17 @@ enum facebook::react::LineBreakStrategy : uint8_t { Standard, } +enum facebook::react::MediaColorScheme : uint8_t { + Dark, + Light, +} + +enum facebook::react::MediaContrast : uint8_t { + Less, + More, + NoPreference, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -8135,6 +8159,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalProps; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -8300,6 +8330,17 @@ struct facebook::react::MeasuredPreparedTextLayout { public facebook::react::detail::TextLayoutManagerExtended::PreparedTextLayout preparedTextLayout; } +struct facebook::react::MediaFeatures { + public bool operator==(const facebook::react::MediaFeatures& other) const = default; + public facebook::react::MediaColorScheme colorScheme; + public facebook::react::MediaContrast contrast; +} + +struct facebook::react::MediaFeaturesSnapshot { + public facebook::react::MediaFeatures features; + public facebook::react::MediaFeaturesGeneration generation; +} + struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { public facebook::react::ModalHostViewSupportedOrientationsMask value; } diff --git a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api index c2c16f8c1470..53c79a798985 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -1593,6 +1593,7 @@ interface RCTScheduler : public NSObject { public virtual void reportMount:(facebook::react::SurfaceId surfaceId); public virtual void setupAnimationDriver:(const facebook::react::SurfaceHandler& surfaceHandler); public virtual void unregisterSurface:(const facebook::react::SurfaceHandler& surfaceHandler); + public virtual void updateMediaFeatures:(const facebook::react::MediaFeatures& mediaFeatures); } interface RCTScrollEvent : public NSObject { @@ -3077,6 +3078,7 @@ struct facebook::hermes::ISetEventLoopControl : public facebook::jsi::ICast { const char facebook::react::ViewComponentName[]; const facebook::react::EventTag facebook::react::EMPTY_EVENT_TAG; +constexpr char* facebook::react::kConditionalPropsName; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -3123,6 +3125,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -3183,6 +3186,8 @@ bool facebook::react::areBorderRadiiCircular(const facebook::react::BorderRadii& bool facebook::react::hostPlatformColorIsColorMeaningful(facebook::react::Color color) noexcept; bool facebook::react::isColorMeaningful(const facebook::react::SharedColor& color) noexcept; bool facebook::react::isZero(facebook::react::Float n); +bool facebook::react::matchMediaQuery(std::string_view query, const facebook::react::MediaFeatures& features) noexcept; +bool facebook::react::setMediaFeatures(const facebook::react::MediaFeatures& features) noexcept; constexpr auto facebook::react::to_underlying(auto e) noexcept; constexpr char facebook::react::toLower(char c); constexpr uint32_t facebook::react::fnv1aLowercase(std::string_view string); @@ -3196,6 +3201,7 @@ facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay facebook::react::Float facebook::react::floatFromYogaFloat(float value); facebook::react::Float facebook::react::floatFromYogaOptionalFloat(facebook::yoga::FloatOptional value); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); +facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; facebook::react::SharedColor facebook::react::blackColor(); @@ -3214,9 +3220,11 @@ float facebook::react::blueFromHostPlatformColor(facebook::react::Color color); float facebook::react::greenFromHostPlatformColor(facebook::react::Color color); float facebook::react::redFromHostPlatformColor(facebook::react::Color color); float facebook::react::yogaFloatFromFloat(facebook::react::Float value); +folly::dynamic facebook::react::resolveConditionalValue(const folly::dynamic& conditionalValue, const facebook::react::MediaFeatures& features); int facebook::react::toInt(const facebook::react::DisplayType& displayType); int facebook::react::toInt(const facebook::react::LayoutDirection& layoutDirection); std::optional facebook::react::blendModeFromString(std::string_view blendModeName); +std::optional facebook::react::resolveConditionalProps(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps); std::optional facebook::react::filterTypeFromString(std::string_view filterName); std::optional facebook::react::optionalFloatFromYogaValue(const facebook::yoga::Style::Length& length, std::optional base = {}); std::optional facebook::react::isolationFromString(std::string_view isolationSetting); @@ -4289,7 +4297,9 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); + public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalProps; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -4341,6 +4351,7 @@ class facebook::react::RawProps { public RawProps(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& value) noexcept; public RawProps(facebook::react::RawProps&& other) noexcept = default; public RawProps(folly::dynamic dynamic) noexcept; + public bool hasProperty(const char* name) const; public bool isEmpty() const noexcept; public const facebook::react::RawValue* at(const char* name) const noexcept; public const facebook::react::RawValue* at(const char* name, const char* prefix, const char* suffix) const noexcept; @@ -4952,6 +4963,17 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaColorScheme : uint8_t { + Dark, + Light, +} + +enum facebook::react::MediaContrast : uint8_t { + Less, + More, + NoPreference, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -5268,6 +5290,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalProps; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -5356,6 +5384,17 @@ struct facebook::react::LinearGradient { public std::vector colorStops; } +struct facebook::react::MediaFeatures { + public bool operator==(const facebook::react::MediaFeatures& other) const = default; + public facebook::react::MediaColorScheme colorScheme; + public facebook::react::MediaContrast contrast; +} + +struct facebook::react::MediaFeaturesSnapshot { + public facebook::react::MediaFeatures features; + public facebook::react::MediaFeaturesGeneration generation; +} + struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { public facebook::react::ModalHostViewSupportedOrientationsMask value; } diff --git a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api index 97659b7a892c..32f846398326 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -1594,6 +1594,7 @@ interface RCTScheduler : public NSObject { public virtual void reportMount:(facebook::react::SurfaceId surfaceId); public virtual void setupAnimationDriver:(const facebook::react::SurfaceHandler& surfaceHandler); public virtual void unregisterSurface:(const facebook::react::SurfaceHandler& surfaceHandler); + public virtual void updateMediaFeatures:(const facebook::react::MediaFeatures& mediaFeatures); } interface RCTScrollEvent : public NSObject { @@ -3084,6 +3085,7 @@ struct facebook::hermes::ISetEventLoopControl : public facebook::jsi::ICast { const char facebook::react::ViewComponentName[]; const facebook::react::EventTag facebook::react::EMPTY_EVENT_TAG; +constexpr char* facebook::react::kConditionalPropsName; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -3130,6 +3132,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -3190,6 +3193,8 @@ bool facebook::react::areBorderRadiiCircular(const facebook::react::BorderRadii& bool facebook::react::hostPlatformColorIsColorMeaningful(facebook::react::Color color) noexcept; bool facebook::react::isColorMeaningful(const facebook::react::SharedColor& color) noexcept; bool facebook::react::isZero(facebook::react::Float n); +bool facebook::react::matchMediaQuery(std::string_view query, const facebook::react::MediaFeatures& features) noexcept; +bool facebook::react::setMediaFeatures(const facebook::react::MediaFeatures& features) noexcept; constexpr auto facebook::react::to_underlying(auto e) noexcept; constexpr char facebook::react::toLower(char c); constexpr uint32_t facebook::react::fnv1aLowercase(std::string_view string); @@ -3203,6 +3208,7 @@ facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay facebook::react::Float facebook::react::floatFromYogaFloat(float value); facebook::react::Float facebook::react::floatFromYogaOptionalFloat(facebook::yoga::FloatOptional value); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); +facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; facebook::react::SharedColor facebook::react::blackColor(); @@ -3221,9 +3227,11 @@ float facebook::react::blueFromHostPlatformColor(facebook::react::Color color); float facebook::react::greenFromHostPlatformColor(facebook::react::Color color); float facebook::react::redFromHostPlatformColor(facebook::react::Color color); float facebook::react::yogaFloatFromFloat(facebook::react::Float value); +folly::dynamic facebook::react::resolveConditionalValue(const folly::dynamic& conditionalValue, const facebook::react::MediaFeatures& features); int facebook::react::toInt(const facebook::react::DisplayType& displayType); int facebook::react::toInt(const facebook::react::LayoutDirection& layoutDirection); std::optional facebook::react::blendModeFromString(std::string_view blendModeName); +std::optional facebook::react::resolveConditionalProps(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps); std::optional facebook::react::filterTypeFromString(std::string_view filterName); std::optional facebook::react::optionalFloatFromYogaValue(const facebook::yoga::Style::Length& length, std::optional base = {}); std::optional facebook::react::isolationFromString(std::string_view isolationSetting); @@ -4296,7 +4304,9 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); + public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalProps; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -4348,6 +4358,7 @@ class facebook::react::RawProps { public RawProps(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& value) noexcept; public RawProps(facebook::react::RawProps&& other) noexcept = default; public RawProps(folly::dynamic dynamic) noexcept; + public bool hasProperty(const char* name) const; public bool isEmpty() const noexcept; public const facebook::react::RawValue* at(const char* name) const noexcept; public const facebook::react::RawValue* at(const char* name, const char* prefix, const char* suffix) const noexcept; @@ -4959,6 +4970,17 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaColorScheme : uint8_t { + Dark, + Light, +} + +enum facebook::react::MediaContrast : uint8_t { + Less, + More, + NoPreference, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -5275,6 +5297,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalProps; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -5363,6 +5391,17 @@ struct facebook::react::LinearGradient { public std::vector colorStops; } +struct facebook::react::MediaFeatures { + public bool operator==(const facebook::react::MediaFeatures& other) const = default; + public facebook::react::MediaColorScheme colorScheme; + public facebook::react::MediaContrast contrast; +} + +struct facebook::react::MediaFeaturesSnapshot { + public facebook::react::MediaFeatures features; + public facebook::react::MediaFeaturesGeneration generation; +} + struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { public facebook::react::ModalHostViewSupportedOrientationsMask value; } diff --git a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api index a1d44bf9c7c9..d6e500185c8a 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api @@ -73,6 +73,7 @@ struct facebook::hermes::ISetEventLoopControl : public facebook::jsi::ICast { const char facebook::react::ViewComponentName[]; const facebook::react::EventTag facebook::react::EMPTY_EVENT_TAG; +constexpr char* facebook::react::kConditionalPropsName; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -107,6 +108,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; using facebook::react::RawPropsPropNameHash = uint32_t; @@ -159,6 +161,8 @@ YGDirection facebook::react::yogaDirectionFromLayoutDirection(facebook::react::L bool facebook::react::areBorderRadiiCircular(const facebook::react::BorderRadii& borderRadii); bool facebook::react::isColorMeaningful(const facebook::react::SharedColor& color) noexcept; bool facebook::react::isZero(Float n); +bool facebook::react::matchMediaQuery(std::string_view query, const facebook::react::MediaFeatures& features) noexcept; +bool facebook::react::setMediaFeatures(const facebook::react::MediaFeatures& features) noexcept; constexpr auto facebook::react::to_underlying(auto e) noexcept; constexpr char facebook::react::toLower(char c); constexpr uint32_t facebook::react::fnv1aLowercase(std::string_view string); @@ -167,6 +171,7 @@ facebook::react::ColorComponents facebook::react::colorComponentsFromColor(faceb facebook::react::ColorSpace facebook::react::getDefaultColorSpace(); facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay display); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); +facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; facebook::react::SharedColor facebook::react::blackColor(); @@ -180,10 +185,12 @@ facebook::react::ValueUnit facebook::react::toValueUnit(const facebook::react::R facebook::yoga::FloatOptional facebook::react::convertAspectRatio(const facebook::react::PropsParserContext&, const facebook::react::RawValue& value); facebook::yoga::FloatOptional facebook::react::yogaOptionalFloatFromFloat(Float value); float facebook::react::yogaFloatFromFloat(Float value); +folly::dynamic facebook::react::resolveConditionalValue(const folly::dynamic& conditionalValue, const facebook::react::MediaFeatures& features); int facebook::react::toInt(const facebook::react::DisplayType& displayType); int facebook::react::toInt(const facebook::react::LayoutDirection& layoutDirection); std::optional facebook::react::optionalFloatFromYogaValue(const facebook::yoga::Style::Length& length, std::optional base = {}); std::optional facebook::react::blendModeFromString(std::string_view blendModeName); +std::optional facebook::react::resolveConditionalProps(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps); std::optional facebook::react::filterTypeFromString(std::string_view filterName); std::optional facebook::react::isolationFromString(std::string_view isolationSetting); std::string facebook::react::toString(const double& value); @@ -948,7 +955,9 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); + public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalProps; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -961,6 +970,7 @@ class facebook::react::RawProps { public RawProps(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& value) noexcept; public RawProps(facebook::react::RawProps&& other) noexcept = default; public RawProps(folly::dynamic dynamic) noexcept; + public bool hasProperty(const char* name) const; public bool isEmpty() const noexcept; public const facebook::react::RawValue* at(const char* name) const noexcept; public const facebook::react::RawValue* at(const char* name, const char* prefix, const char* suffix) const noexcept; @@ -1502,6 +1512,17 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaColorScheme : uint8_t { + Dark, + Light, +} + +enum facebook::react::MediaContrast : uint8_t { + Less, + More, + NoPreference, +} + enum facebook::react::OutlineStyle : uint8_t { Dashed, Dotted, @@ -1777,6 +1798,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalProps; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -1851,6 +1878,17 @@ struct facebook::react::LinearGradient { public std::vector colorStops; } +struct facebook::react::MediaFeatures { + public bool operator==(const facebook::react::MediaFeatures& other) const = default; + public facebook::react::MediaColorScheme colorScheme; + public facebook::react::MediaContrast contrast; +} + +struct facebook::react::MediaFeaturesSnapshot { + public facebook::react::MediaFeatures features; + public facebook::react::MediaFeaturesGeneration generation; +} + struct facebook::react::Point { public Float x; public Float y; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api index b545beed0c09..9bb00328d2c5 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api @@ -85,6 +85,7 @@ const char facebook::react::ViewComponentName[]; const facebook::react::EventTag facebook::react::EMPTY_EVENT_TAG; constexpr auto facebook::react::kSimpleThreadSafeCacheSizeCap; constexpr char* const facebook::react::TextLayoutManagerKey; +constexpr char* facebook::react::kConditionalPropsName; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr float facebook::react::kDefaultEpsilon; @@ -160,6 +161,7 @@ using facebook::react::LayoutConformanceComponentDescriptor = facebook::react::C using facebook::react::LineMeasureCache = facebook::react::SimpleThreadSafeCache; using facebook::react::LinesMeasurements = std::vector; using facebook::react::Logger = std::function; +using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::MountingTransactionCallback = std::function; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::ParagraphProps = HostPlatformParagraphProps; @@ -312,6 +314,8 @@ bool facebook::react::areTextAttributesEquivalentLayoutWise(const facebook::reac bool facebook::react::isColorMeaningful(const facebook::react::SharedColor& color) noexcept; bool facebook::react::isHermesBytecodeBundle(const facebook::react::BundleHeader& header); bool facebook::react::isZero(Float n); +bool facebook::react::matchMediaQuery(std::string_view query, const facebook::react::MediaFeatures& features) noexcept; +bool facebook::react::setMediaFeatures(const facebook::react::MediaFeatures& features) noexcept; const char* facebook::react::stringForScriptTag(const facebook::react::ScriptTag& tag); constexpr auto facebook::react::to_underlying(auto e) noexcept; constexpr bool facebook::react::iequals(std::string_view a, std::string_view b); @@ -326,6 +330,7 @@ facebook::react::ColorSpace facebook::react::getDefaultColorSpace(); facebook::react::ComponentRegistryFactory facebook::react::getDefaultComponentRegistryFactory(); facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay display); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); +facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; facebook::react::ParagraphAttributes facebook::react::convertRawProp(const facebook::react::PropsParserContext& context, const facebook::react::RawProps& rawProps, const facebook::react::ParagraphAttributes& sourceParagraphAttributes, const facebook::react::ParagraphAttributes& defaultParagraphAttributes); facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; @@ -346,6 +351,7 @@ facebook::yoga::FloatOptional facebook::react::yogaOptionalFloatFromFloat(Float float facebook::react::yogaFloatFromFloat(Float value); folly::dynamic facebook::react::diffDynamicProps(const folly::dynamic& oldProps, const folly::dynamic& newProps); folly::dynamic facebook::react::mergeDynamicProps(const folly::dynamic& source, const folly::dynamic& patch, facebook::react::NullValueStrategy nullValueStrategy); +folly::dynamic facebook::react::resolveConditionalValue(const folly::dynamic& conditionalValue, const facebook::react::MediaFeatures& features); int facebook::react::toInt(const facebook::react::DisplayType& displayType); int facebook::react::toInt(const facebook::react::LayoutDirection& layoutDirection); size_t facebook::react::attributedStringFragmentHashDisplayWise(const facebook::react::AttributedString::Fragment& fragment); @@ -355,6 +361,7 @@ size_t facebook::react::attributedStringHashLayoutWise(const facebook::react::At size_t facebook::react::textAttributesHashLayoutWise(const facebook::react::TextAttributes& textAttributes); std::optional facebook::react::optionalFloatFromYogaValue(const facebook::yoga::Style::Length& length, std::optional base = {}); std::optional facebook::react::blendModeFromString(std::string_view blendModeName); +std::optional facebook::react::resolveConditionalProps(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps); std::optional facebook::react::filterTypeFromString(std::string_view filterName); std::optional facebook::react::fontVariantFromCSSFontVariant(facebook::react::CSSFontVariant cssVariant); std::optional facebook::react::isolationFromString(std::string_view isolationSetting); @@ -1886,7 +1893,9 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); + public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalProps; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -1899,6 +1908,7 @@ class facebook::react::RawProps { public RawProps(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& value) noexcept; public RawProps(facebook::react::RawProps&& other) noexcept = default; public RawProps(folly::dynamic dynamic) noexcept; + public bool hasProperty(const char* name) const; public bool isEmpty() const noexcept; public const facebook::react::RawValue* at(const char* name) const noexcept; public const facebook::react::RawValue* at(const char* name, const char* prefix, const char* suffix) const noexcept; @@ -2141,6 +2151,7 @@ class facebook::react::Scheduler : public facebook::react::UIManagerDelegate { public void reportMount(facebook::react::SurfaceId surfaceId) const; public void setDelegate(facebook::react::SchedulerDelegate* delegate); public void unregisterSurface(const facebook::react::SurfaceHandler& surfaceHandler) const noexcept; + public void updateMediaFeatures(const facebook::react::MediaFeatures& mediaFeatures); public ~Scheduler() override; } @@ -2703,6 +2714,7 @@ class facebook::react::UIManager : public facebook::react::ShadowTreeDelegate { public void synchronouslyUpdateViewOnUIThread(facebook::react::Tag tag, const folly::dynamic& props); public void unregisterCommitHook(facebook::react::UIManagerCommitHook& commitHook); public void unregisterMountHook(facebook::react::UIManagerMountHook& mountHook); + public void updateConditionalProps() const; public void updateShadowTree(std::unordered_map&& tagToProps); public void updateState(const facebook::react::StateUpdate& stateUpdate) const; public void visitBinding(const std::function& callback, facebook::jsi::Runtime& runtime) const; @@ -3546,6 +3558,17 @@ enum facebook::react::LineBreakStrategy : uint8_t { Standard, } +enum facebook::react::MediaColorScheme : uint8_t { + Dark, + Light, +} + +enum facebook::react::MediaContrast : uint8_t { + Less, + More, + NoPreference, +} + enum facebook::react::NullValueStrategy { Ignore, Override, @@ -4364,6 +4387,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalProps; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -4515,6 +4544,17 @@ struct facebook::react::MeasuredPreparedTextLayout { public facebook::react::detail::TextLayoutManagerExtended::PreparedTextLayout preparedTextLayout; } +struct facebook::react::MediaFeatures { + public bool operator==(const facebook::react::MediaFeatures& other) const = default; + public facebook::react::MediaColorScheme colorScheme; + public facebook::react::MediaContrast contrast; +} + +struct facebook::react::MediaFeaturesSnapshot { + public facebook::react::MediaFeatures features; + public facebook::react::MediaFeaturesGeneration generation; +} + struct facebook::react::Point { public Float x; public Float y; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api index e3211613043f..6a17c3cf2315 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api @@ -73,6 +73,7 @@ struct facebook::hermes::ISetEventLoopControl : public facebook::jsi::ICast { const char facebook::react::ViewComponentName[]; const facebook::react::EventTag facebook::react::EMPTY_EVENT_TAG; +constexpr char* facebook::react::kConditionalPropsName; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -107,6 +108,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; using facebook::react::RawPropsPropNameHash = uint32_t; @@ -159,6 +161,8 @@ YGDirection facebook::react::yogaDirectionFromLayoutDirection(facebook::react::L bool facebook::react::areBorderRadiiCircular(const facebook::react::BorderRadii& borderRadii); bool facebook::react::isColorMeaningful(const facebook::react::SharedColor& color) noexcept; bool facebook::react::isZero(Float n); +bool facebook::react::matchMediaQuery(std::string_view query, const facebook::react::MediaFeatures& features) noexcept; +bool facebook::react::setMediaFeatures(const facebook::react::MediaFeatures& features) noexcept; constexpr auto facebook::react::to_underlying(auto e) noexcept; constexpr char facebook::react::toLower(char c); constexpr uint32_t facebook::react::fnv1aLowercase(std::string_view string); @@ -167,6 +171,7 @@ facebook::react::ColorComponents facebook::react::colorComponentsFromColor(faceb facebook::react::ColorSpace facebook::react::getDefaultColorSpace(); facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay display); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); +facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; facebook::react::SharedColor facebook::react::blackColor(); @@ -180,10 +185,12 @@ facebook::react::ValueUnit facebook::react::toValueUnit(const facebook::react::R facebook::yoga::FloatOptional facebook::react::convertAspectRatio(const facebook::react::PropsParserContext&, const facebook::react::RawValue& value); facebook::yoga::FloatOptional facebook::react::yogaOptionalFloatFromFloat(Float value); float facebook::react::yogaFloatFromFloat(Float value); +folly::dynamic facebook::react::resolveConditionalValue(const folly::dynamic& conditionalValue, const facebook::react::MediaFeatures& features); int facebook::react::toInt(const facebook::react::DisplayType& displayType); int facebook::react::toInt(const facebook::react::LayoutDirection& layoutDirection); std::optional facebook::react::optionalFloatFromYogaValue(const facebook::yoga::Style::Length& length, std::optional base = {}); std::optional facebook::react::blendModeFromString(std::string_view blendModeName); +std::optional facebook::react::resolveConditionalProps(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps); std::optional facebook::react::filterTypeFromString(std::string_view filterName); std::optional facebook::react::isolationFromString(std::string_view isolationSetting); std::string facebook::react::toString(const double& value); @@ -947,7 +954,9 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); + public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalProps; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -960,6 +969,7 @@ class facebook::react::RawProps { public RawProps(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& value) noexcept; public RawProps(facebook::react::RawProps&& other) noexcept = default; public RawProps(folly::dynamic dynamic) noexcept; + public bool hasProperty(const char* name) const; public bool isEmpty() const noexcept; public const facebook::react::RawValue* at(const char* name) const noexcept; public const facebook::react::RawValue* at(const char* name, const char* prefix, const char* suffix) const noexcept; @@ -1495,6 +1505,17 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaColorScheme : uint8_t { + Dark, + Light, +} + +enum facebook::react::MediaContrast : uint8_t { + Less, + More, + NoPreference, +} + enum facebook::react::OutlineStyle : uint8_t { Dashed, Dotted, @@ -1770,6 +1791,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalProps; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -1844,6 +1871,17 @@ struct facebook::react::LinearGradient { public std::vector colorStops; } +struct facebook::react::MediaFeatures { + public bool operator==(const facebook::react::MediaFeatures& other) const = default; + public facebook::react::MediaColorScheme colorScheme; + public facebook::react::MediaContrast contrast; +} + +struct facebook::react::MediaFeaturesSnapshot { + public facebook::react::MediaFeatures features; + public facebook::react::MediaFeaturesGeneration generation; +} + struct facebook::react::Point { public Float x; public Float y; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api index e3211613043f..6a17c3cf2315 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api @@ -73,6 +73,7 @@ struct facebook::hermes::ISetEventLoopControl : public facebook::jsi::ICast { const char facebook::react::ViewComponentName[]; const facebook::react::EventTag facebook::react::EMPTY_EVENT_TAG; +constexpr char* facebook::react::kConditionalPropsName; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -107,6 +108,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; using facebook::react::RawPropsPropNameHash = uint32_t; @@ -159,6 +161,8 @@ YGDirection facebook::react::yogaDirectionFromLayoutDirection(facebook::react::L bool facebook::react::areBorderRadiiCircular(const facebook::react::BorderRadii& borderRadii); bool facebook::react::isColorMeaningful(const facebook::react::SharedColor& color) noexcept; bool facebook::react::isZero(Float n); +bool facebook::react::matchMediaQuery(std::string_view query, const facebook::react::MediaFeatures& features) noexcept; +bool facebook::react::setMediaFeatures(const facebook::react::MediaFeatures& features) noexcept; constexpr auto facebook::react::to_underlying(auto e) noexcept; constexpr char facebook::react::toLower(char c); constexpr uint32_t facebook::react::fnv1aLowercase(std::string_view string); @@ -167,6 +171,7 @@ facebook::react::ColorComponents facebook::react::colorComponentsFromColor(faceb facebook::react::ColorSpace facebook::react::getDefaultColorSpace(); facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay display); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); +facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; facebook::react::SharedColor facebook::react::blackColor(); @@ -180,10 +185,12 @@ facebook::react::ValueUnit facebook::react::toValueUnit(const facebook::react::R facebook::yoga::FloatOptional facebook::react::convertAspectRatio(const facebook::react::PropsParserContext&, const facebook::react::RawValue& value); facebook::yoga::FloatOptional facebook::react::yogaOptionalFloatFromFloat(Float value); float facebook::react::yogaFloatFromFloat(Float value); +folly::dynamic facebook::react::resolveConditionalValue(const folly::dynamic& conditionalValue, const facebook::react::MediaFeatures& features); int facebook::react::toInt(const facebook::react::DisplayType& displayType); int facebook::react::toInt(const facebook::react::LayoutDirection& layoutDirection); std::optional facebook::react::optionalFloatFromYogaValue(const facebook::yoga::Style::Length& length, std::optional base = {}); std::optional facebook::react::blendModeFromString(std::string_view blendModeName); +std::optional facebook::react::resolveConditionalProps(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps); std::optional facebook::react::filterTypeFromString(std::string_view filterName); std::optional facebook::react::isolationFromString(std::string_view isolationSetting); std::string facebook::react::toString(const double& value); @@ -947,7 +954,9 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); + public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalProps; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -960,6 +969,7 @@ class facebook::react::RawProps { public RawProps(facebook::jsi::Runtime& runtime, const facebook::jsi::Value& value) noexcept; public RawProps(facebook::react::RawProps&& other) noexcept = default; public RawProps(folly::dynamic dynamic) noexcept; + public bool hasProperty(const char* name) const; public bool isEmpty() const noexcept; public const facebook::react::RawValue* at(const char* name) const noexcept; public const facebook::react::RawValue* at(const char* name, const char* prefix, const char* suffix) const noexcept; @@ -1495,6 +1505,17 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaColorScheme : uint8_t { + Dark, + Light, +} + +enum facebook::react::MediaContrast : uint8_t { + Less, + More, + NoPreference, +} + enum facebook::react::OutlineStyle : uint8_t { Dashed, Dotted, @@ -1770,6 +1791,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalProps; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -1844,6 +1871,17 @@ struct facebook::react::LinearGradient { public std::vector colorStops; } +struct facebook::react::MediaFeatures { + public bool operator==(const facebook::react::MediaFeatures& other) const = default; + public facebook::react::MediaColorScheme colorScheme; + public facebook::react::MediaContrast contrast; +} + +struct facebook::react::MediaFeaturesSnapshot { + public facebook::react::MediaFeatures features; + public facebook::react::MediaFeaturesGeneration generation; +} + struct facebook::react::Point { public Float x; public Float y; diff --git a/yarn.lock b/yarn.lock index 7cdbbb8e06ba..8b00e0bc1468 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5305,10 +5305,10 @@ hasown@^2.0.3: dependencies: function-bind "^1.1.2" -hermes-compiler@0.0.0: - version "0.0.0" - resolved "https://registry.yarnpkg.com/hermes-compiler/-/hermes-compiler-0.0.0.tgz#8d9f6a0b2740ce34d71258fec684e7b6bfd97efa" - integrity sha512-boVFutx6ME/Km2mB6vvsQcdnazEYYI/jV1pomx1wcFUG/EVqTkr5CU0CW9bKipOA/8Hyu3NYwW3THg2Q1kNCfA== +hermes-compiler@260318099.0.7: + version "260318099.0.7" + resolved "https://registry.yarnpkg.com/hermes-compiler/-/hermes-compiler-260318099.0.7.tgz#e253054d854e89f0c22c92edc8230068a03925c9" + integrity sha512-rhygMID0xtxNEuEdACZDheG3pZOxrKc9fiaF4U/Nr1jADLNmgaW7WD3P9dDRFMTJ9gKgq8sEdttcJ4+u8kwlCA== hermes-estree@0.25.1: version "0.25.1" From 174509f6a92c0c30ed71b3321ecded1c600bd113 Mon Sep 17 00:00:00 2001 From: Mathieu Acthernoene Date: Thu, 12 Nov 2026 12:43:06 +0000 Subject: [PATCH 2/6] WIP (simplify) --- .../react/fabric/FabricUIManager.java | 13 ++++++ .../react/fabric/MediaFeaturesObserver.kt | 15 ------- .../facebook/react/runtime/ReactHostImpl.kt | 3 +- .../react/fabric/FabricUIManagerBinding.cpp | 2 +- .../core/ConcreteComponentDescriptor.h | 2 +- .../react/renderer/core/ConditionalProps.cpp | 11 +++-- .../react/renderer/core/ConditionalProps.h | 6 +-- .../react/renderer/core/MediaFeatures.cpp | 44 +++---------------- .../react/renderer/core/MediaFeatures.h | 17 +------ .../ReactCommon/react/renderer/core/Props.cpp | 2 +- .../ReactCommon/react/renderer/core/Props.h | 5 +-- .../core/tests/ConditionalPropsTest.cpp | 13 +++--- .../renderer/core/tests/MediaFeaturesTest.cpp | 9 ++-- .../react/renderer/scheduler/Scheduler.cpp | 7 ++- .../react/renderer/scheduler/Scheduler.h | 5 +-- .../UIManagerUpdateConditionalProps.cpp | 16 +++---- .../api-snapshots/ReactAppleDebugCxx.api | 12 ++--- .../api-snapshots/ReactAppleFrameworksCxx.api | 12 ++--- .../api-snapshots/ReactAppleNewarchCxx.api | 12 ++--- .../api-snapshots/ReactAppleReleaseCxx.api | 12 ++--- .../api-snapshots/ReactCommonDebugCxx.api | 12 ++--- .../ReactCommonFrameworksCxx.api | 12 ++--- .../api-snapshots/ReactCommonNewarchCxx.api | 12 ++--- .../api-snapshots/ReactCommonReleaseCxx.api | 12 ++--- 24 files changed, 79 insertions(+), 187 deletions(-) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java index 56f48f6effe2..f4f90ce7f301 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java @@ -461,6 +461,19 @@ public void stopSurface(final int surfaceID) { mBinding.stopSurface(surfaceID); } + /** + * Call this when the configuration of an activity changes: changes made with {@code + * AppCompatDelegate.setDefaultNightMode()} only reach the activity. + */ + @UiThread + @UnstableReactNativeAPI + public void onConfigurationChanged(Context context) { + MediaFeaturesObserver mediaFeaturesObserver = mMediaFeaturesObserver; + if (mediaFeaturesObserver != null) { + mediaFeaturesObserver.update(context); + } + } + @Override public void initialize() { mEventDispatcher.addBatchEventDispatchedListener(mBatchEventDispatchedListener); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt index a25085f95641..51738ae44a74 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt @@ -19,8 +19,6 @@ import androidx.annotation.RequiresApi import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.UiThreadUtil import com.facebook.react.views.common.UiModeUtils -import java.util.Collections -import java.util.WeakHashMap /** * Reads the media features that conditional props are matched against (for example with `@media @@ -65,7 +63,6 @@ internal class MediaFeaturesObserver( private var contrastChangeListener: Any? = null fun start() { - activeObservers.add(this) reactContext.registerComponentCallbacks(componentCallbacks) reactContext.contentResolver.registerContentObserver( Settings.Secure.getUriFor(HIGH_TEXT_CONTRAST_ENABLED), @@ -79,7 +76,6 @@ internal class MediaFeaturesObserver( } fun stop() { - activeObservers.remove(this) reactContext.unregisterComponentCallbacks(componentCallbacks) reactContext.contentResolver.unregisterContentObserver(highTextContrastObserver) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { @@ -146,16 +142,5 @@ internal class MediaFeaturesObserver( const val CONTRAST_MORE: Int = 2 private const val HIGH_TEXT_CONTRAST_ENABLED = "high_text_contrast_enabled" - - private val activeObservers: MutableSet = - Collections.synchronizedSet(Collections.newSetFromMap(WeakHashMap())) - - /** - * Call this when the configuration of an activity changes: changes made with - * `AppCompatDelegate.setDefaultNightMode()` only reach the activity. - */ - fun onConfigurationChanged(context: Context) { - synchronized(activeObservers) { activeObservers.toList() }.forEach { it.update(context) } - } } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt index 19eec8da7b5c..c01d633bc416 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt @@ -55,7 +55,6 @@ import com.facebook.react.devsupport.interfaces.DevSupportManager import com.facebook.react.devsupport.interfaces.DevSupportManager.PausedInDebuggerOverlayCommandListener import com.facebook.react.fabric.ComponentFactory import com.facebook.react.fabric.FabricUIManager -import com.facebook.react.fabric.MediaFeaturesObserver import com.facebook.react.interfaces.TaskInterface import com.facebook.react.interfaces.fabric.ReactSurface import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags @@ -747,7 +746,7 @@ public class ReactHostImpl( val appearanceModule = currentReactContext.getNativeModule(AppearanceModule::class.java) appearanceModule?.onConfigurationChanged(context) - MediaFeaturesObserver.onConfigurationChanged(context) + uiManager?.onConfigurationChanged(context) } } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp index 641a32153e2a..a4e250f2003c 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp @@ -129,7 +129,7 @@ void FabricUIManagerBinding::updateMediaFeatures( << "FabricUIManagerBinding::updateMediaFeatures: scheduler disappeared"; return; } - // The values match `FabricUIManager.MEDIA_*` constants. + // The values match the `MediaFeaturesObserver` constants. scheduler->updateMediaFeatures({ .colorScheme = colorScheme == 1 ? MediaColorScheme::Dark : MediaColorScheme::Light, diff --git a/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h index 2b1c6f5e0ffe..c37b33fd619a 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h @@ -158,7 +158,7 @@ class ConcreteComponentDescriptor : public ComponentDescriptor { if (conditionalPropsResolution) { shadowNodeProps->conditionalProps = std::move(conditionalPropsResolution->conditionalProps); - shadowNodeProps->conditionalPropsGeneration = conditionalPropsResolution->generation; + shadowNodeProps->conditionalPropsMediaFeatures = conditionalPropsResolution->mediaFeatures; } #ifdef RN_SERIALIZABLE_STATE diff --git a/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.cpp b/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.cpp index b0ebbdd58bf6..a351b1d48977 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.cpp @@ -65,9 +65,9 @@ std::optional resolveConditionalProps( return std::nullopt; } - auto snapshot = getMediaFeaturesSnapshot(); + auto mediaFeatures = getMediaFeatures(); auto isStale = sourceConditionalProps != nullptr && - sourceProps->conditionalPropsGeneration != snapshot.generation; + sourceProps->conditionalPropsMediaFeatures != mediaFeatures; if (!hasNewConditionalProps && !isStale) { // The source conditional values are up to date. They only change if @@ -105,8 +105,7 @@ std::optional resolveConditionalProps( } for (const auto& item : newConditionalProps.items()) { - values[item.first] = - resolveConditionalValue(item.second, snapshot.features); + values[item.first] = resolveConditionalValue(item.second, mediaFeatures); conditionalProps[item.first] = item.second; } @@ -114,7 +113,7 @@ std::optional resolveConditionalProps( for (const auto& item : conditionalProps.items()) { if (newConditionalProps.count(item.first) == 0) { values[item.first] = - resolveConditionalValue(item.second, snapshot.features); + resolveConditionalValue(item.second, mediaFeatures); } } } @@ -124,7 +123,7 @@ std::optional resolveConditionalProps( .conditionalProps = conditionalProps.empty() ? nullptr : std::make_shared(std::move(conditionalProps)), - .generation = snapshot.generation, + .mediaFeatures = mediaFeatures, }; } diff --git a/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.h b/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.h index 3bb5e7d48335..448891c3c06c 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.h @@ -56,14 +56,14 @@ struct ConditionalPropsResolution { std::shared_ptr conditionalProps; /* - * The generation of the media features that the values were resolved with. + * The media features that the values were resolved with. */ - MediaFeaturesGeneration generation; + MediaFeatures mediaFeatures; }; /* * Merges the conditional values of `sourceProps` and `rawProps`, and resolves - * the ones that are new or that were resolved with older media features. + * the ones that are new or that were resolved with other media features. * * Returns `std::nullopt` when the new props can use `rawProps` as they are, * and keep the conditional values of `sourceProps` (the common case). diff --git a/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp index 8b674ef5d1cb..651988ac889b 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp @@ -13,29 +13,7 @@ namespace facebook::react { namespace { -// The generation and the media features are packed in one value, so that a -// single atomic read gives a consistent snapshot. -std::atomic packedMediaFeatures{0}; - -uint64_t pack( - const MediaFeatures& features, - MediaFeaturesGeneration generation) noexcept { - return (static_cast(generation) << 16) | - (static_cast(features.colorScheme) << 8) | - static_cast(features.contrast); -} - -MediaFeaturesSnapshot unpack(uint64_t packed) noexcept { - return { - .features = - { - .colorScheme = - static_cast((packed >> 8) & 0xff), - .contrast = static_cast(packed & 0xff), - }, - .generation = static_cast(packed >> 16), - }; -} +std::atomic currentMediaFeatures{MediaFeatures{}}; char toLowerAscii(char c) noexcept { return (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; @@ -107,25 +85,13 @@ bool matchMediaFeature( } // namespace -MediaFeaturesSnapshot getMediaFeaturesSnapshot() noexcept { - return unpack(packedMediaFeatures.load(std::memory_order_acquire)); +MediaFeatures getMediaFeatures() noexcept { + return currentMediaFeatures.load(std::memory_order_acquire); } bool setMediaFeatures(const MediaFeatures& features) noexcept { - auto packed = packedMediaFeatures.load(std::memory_order_acquire); - while (true) { - auto snapshot = unpack(packed); - if (snapshot.features == features) { - return false; - } - if (packedMediaFeatures.compare_exchange_weak( - packed, - pack(features, snapshot.generation + 1), - std::memory_order_acq_rel, - std::memory_order_acquire)) { - return true; - } - } + return currentMediaFeatures.exchange(features, std::memory_order_acq_rel) != + features; } bool matchMediaQuery( diff --git a/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h index 3abb9c292503..c0937b92f400 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h +++ b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h @@ -30,22 +30,9 @@ struct MediaFeatures { }; /* - * Each change of the media features increments the generation. Props keep the - * generation of the media features that their conditional values were resolved - * with, so that the renderer can find the props to resolve again. + * Returns the current media features of the process. Thread-safe. */ -using MediaFeaturesGeneration = uint32_t; - -struct MediaFeaturesSnapshot { - MediaFeatures features; - MediaFeaturesGeneration generation; -}; - -/* - * Returns the current media features of the process, and their generation. - * Thread-safe. - */ -MediaFeaturesSnapshot getMediaFeaturesSnapshot() noexcept; +MediaFeatures getMediaFeatures() noexcept; /* * Sets the current media features of the process. Returns `true` if they diff --git a/packages/react-native/ReactCommon/react/renderer/core/Props.cpp b/packages/react-native/ReactCommon/react/renderer/core/Props.cpp index 59a523c40ffe..c2d5afb206f7 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Props.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/Props.cpp @@ -28,7 +28,7 @@ Props::Props( sourceProps.nativeId, {})), conditionalProps(sourceProps.conditionalProps), - conditionalPropsGeneration(sourceProps.conditionalPropsGeneration) {} + conditionalPropsMediaFeatures(sourceProps.conditionalPropsMediaFeatures) {} void Props::setProp( const PropsParserContext& context, diff --git a/packages/react-native/ReactCommon/react/renderer/core/Props.h b/packages/react-native/ReactCommon/react/renderer/core/Props.h index b4836053efee..45997666b3bc 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Props.h +++ b/packages/react-native/ReactCommon/react/renderer/core/Props.h @@ -70,10 +70,9 @@ class Props : public virtual Sealable, public virtual DebugStringConvertible { std::shared_ptr conditionalProps; /* - * The generation of the media features that `conditionalProps` were resolved - * with. + * The media features that `conditionalProps` were resolved with. */ - MediaFeaturesGeneration conditionalPropsGeneration{0}; + MediaFeatures conditionalPropsMediaFeatures{}; #ifdef RN_SERIALIZABLE_STATE folly::dynamic rawProps = folly::dynamic::object(); diff --git a/packages/react-native/ReactCommon/react/renderer/core/tests/ConditionalPropsTest.cpp b/packages/react-native/ReactCommon/react/renderer/core/tests/ConditionalPropsTest.cpp index ccdb2c5d8f18..b48436fb6f60 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/tests/ConditionalPropsTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/ConditionalPropsTest.cpp @@ -107,15 +107,14 @@ TEST_F(ConditionalPropsTest, resolvesNewConditionalValues) { EXPECT_EQ( *resolution->conditionalProps, folly::dynamic(folly::dynamic::object("opacity", opacityValue()))); - EXPECT_EQ(resolution->generation, getMediaFeaturesSnapshot().generation); + EXPECT_EQ(resolution->mediaFeatures, kDark); } TEST_F(ConditionalPropsTest, keepsUpToDateConditionalValuesOfTheSource) { Props sourceProps; sourceProps.conditionalProps = std::make_shared( folly::dynamic::object("opacity", opacityValue())); - sourceProps.conditionalPropsGeneration = - getMediaFeaturesSnapshot().generation; + sourceProps.conditionalPropsMediaFeatures = kLight; auto rawProps = RawProps(folly::dynamic::object("nativeID", "box")); EXPECT_FALSE(resolveConditionalProps(&sourceProps, rawProps).has_value()); @@ -125,8 +124,7 @@ TEST_F(ConditionalPropsTest, dropsConditionalValuesReplacedByPlainValues) { Props sourceProps; sourceProps.conditionalProps = std::make_shared( folly::dynamic::object("opacity", opacityValue())); - sourceProps.conditionalPropsGeneration = - getMediaFeaturesSnapshot().generation; + sourceProps.conditionalPropsMediaFeatures = kLight; auto rawProps = RawProps(folly::dynamic::object("opacity", 0.5)); auto resolution = resolveConditionalProps(&sourceProps, rawProps); @@ -141,8 +139,7 @@ TEST_F(ConditionalPropsTest, resolvesOutdatedConditionalValuesOfTheSource) { Props sourceProps; sourceProps.conditionalProps = std::make_shared( folly::dynamic::object("opacity", opacityValue())); - sourceProps.conditionalPropsGeneration = - getMediaFeaturesSnapshot().generation; + sourceProps.conditionalPropsMediaFeatures = kLight; setMediaFeatures(kDarkMoreContrast); @@ -154,5 +151,5 @@ TEST_F(ConditionalPropsTest, resolvesOutdatedConditionalValuesOfTheSource) { folly::dynamic(folly::dynamic::object("opacity", 3))); ASSERT_NE(resolution->conditionalProps, nullptr); EXPECT_EQ(*resolution->conditionalProps, *sourceProps.conditionalProps); - EXPECT_EQ(resolution->generation, getMediaFeaturesSnapshot().generation); + EXPECT_EQ(resolution->mediaFeatures, kDarkMoreContrast); } diff --git a/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp b/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp index ba69d9b9b3ef..18301f112692 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp @@ -100,17 +100,14 @@ TEST(MediaFeaturesTest, neverMatchesUnsupportedQueries) { EXPECT_FALSE(matchMediaQuery("", kLight)); } -TEST(MediaFeaturesTest, incrementsTheGenerationOnlyOnChange) { +TEST(MediaFeaturesTest, reportsOnlyChanges) { setMediaFeatures(kLight); - auto generation = getMediaFeaturesSnapshot().generation; EXPECT_FALSE(setMediaFeatures(kLight)); - EXPECT_EQ(getMediaFeaturesSnapshot().generation, generation); + EXPECT_EQ(getMediaFeatures(), kLight); EXPECT_TRUE(setMediaFeatures(kDarkMoreContrast)); - auto snapshot = getMediaFeaturesSnapshot(); - EXPECT_EQ(snapshot.generation, generation + 1); - EXPECT_EQ(snapshot.features, kDarkMoreContrast); + EXPECT_EQ(getMediaFeatures(), kDarkMoreContrast); setMediaFeatures(kLight); } diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp index 0abc1a405fd2..296067924c94 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp @@ -461,11 +461,10 @@ void Scheduler::reportMount(SurfaceId surfaceId) const { void Scheduler::updateMediaFeatures(const MediaFeatures& mediaFeatures) { // The media features are global to the process: another scheduler may - // already have set them. Comparing generations tells whether the shadow - // trees of this scheduler still need an update. + // already have set them. `mediaFeatures_` tells whether the shadow trees of + // this scheduler still need an update. setMediaFeatures(mediaFeatures); - auto generation = getMediaFeaturesSnapshot().generation; - if (mediaFeaturesGeneration_.exchange(generation) == generation) { + if (mediaFeatures_.exchange(mediaFeatures) == mediaFeatures) { return; } diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h index 139a9b4b6401..183f9bb48b4f 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h @@ -139,9 +139,8 @@ class Scheduler final : public UIManagerDelegate { RuntimeExecutor runtimeExecutor_; std::shared_ptr uiManager_; - // The generation of the media features that this scheduler last updated its - // shadow trees for. - std::atomic mediaFeaturesGeneration_{0}; + // The media features that this scheduler last updated its shadow trees for. + std::atomic mediaFeatures_{MediaFeatures{}}; std::vector> commitHooks_; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerUpdateConditionalProps.cpp b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerUpdateConditionalProps.cpp index eef8522e3fa5..d56678e3faeb 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerUpdateConditionalProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManagerUpdateConditionalProps.cpp @@ -19,18 +19,18 @@ namespace { /* * Returns a clone of `shadowNode` where the props with conditional values that - * were resolved with an older generation of the media features are resolved - * again. Returns `nullptr` if nothing changed in the subtree. + * were resolved with other media features are resolved again. Returns + * `nullptr` if nothing changed in the subtree. */ std::shared_ptr cloneWithUpdatedConditionalProps( const ShadowNode& shadowNode, const PropsParserContext& context, - MediaFeaturesGeneration generation) { + const MediaFeatures& mediaFeatures) { const auto& children = shadowNode.getChildren(); std::shared_ptr>> newChildren; for (size_t index = 0; index < children.size(); index++) { - auto newChild = - cloneWithUpdatedConditionalProps(*children[index], context, generation); + auto newChild = cloneWithUpdatedConditionalProps( + *children[index], context, mediaFeatures); if (newChild) { if (!newChildren) { newChildren = @@ -44,7 +44,7 @@ std::shared_ptr cloneWithUpdatedConditionalProps( Props::Shared newProps; const auto& props = shadowNode.getProps(); if (props->conditionalProps != nullptr && - props->conditionalPropsGeneration != generation) { + props->conditionalPropsMediaFeatures != mediaFeatures) { // Empty raw props: `cloneProps` resolves the outdated conditional values // of `props` again. newProps = shadowNode.getComponentDescriptor().cloneProps( @@ -70,7 +70,7 @@ std::shared_ptr cloneWithUpdatedConditionalProps( void UIManager::updateConditionalProps() const { TraceSection s("UIManager::updateConditionalProps"); - auto generation = getMediaFeaturesSnapshot().generation; + auto mediaFeatures = getMediaFeatures(); shadowTreeRegistry_.enumerate([&](const ShadowTree& shadowTree, bool& /*stop*/) { @@ -80,7 +80,7 @@ void UIManager::updateConditionalProps() const { -> RootShadowNode::Unshared { return std::static_pointer_cast( cloneWithUpdatedConditionalProps( - oldRootShadowNode, context, generation)); + oldRootShadowNode, context, mediaFeatures)); }, {.enableStateReconciliation = true}); }); diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index 44ca8eaabdac..df1e5d93a21c 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -3132,7 +3132,6 @@ using facebook::react::GradientDirection = std::variant; -using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -3208,7 +3207,7 @@ facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay facebook::react::Float facebook::react::floatFromYogaFloat(float value); facebook::react::Float facebook::react::floatFromYogaOptionalFloat(facebook::yoga::FloatOptional value); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); -facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; +facebook::react::MediaFeatures facebook::react::getMediaFeatures() noexcept; facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; facebook::react::SharedColor facebook::react::blackColor(); @@ -4305,7 +4304,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); - public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; + public facebook::react::MediaFeatures conditionalPropsMediaFeatures; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; public std::shared_ptr conditionalProps; public std::string nativeId; @@ -5305,7 +5304,7 @@ struct facebook::react::ColorStop { } struct facebook::react::ConditionalPropsResolution { - public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::MediaFeatures mediaFeatures; public facebook::react::RawProps rawProps; public std::shared_ptr conditionalProps; } @@ -5404,11 +5403,6 @@ struct facebook::react::MediaFeatures { public facebook::react::MediaContrast contrast; } -struct facebook::react::MediaFeaturesSnapshot { - public facebook::react::MediaFeatures features; - public facebook::react::MediaFeaturesGeneration generation; -} - struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { public facebook::react::ModalHostViewSupportedOrientationsMask value; } diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index fb56b44c73f6..eb67ff272f42 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -3286,7 +3286,6 @@ using facebook::react::LayoutConformanceComponentDescriptor = facebook::react::C using facebook::react::LineMeasureCache = facebook::react::SimpleThreadSafeCache; using facebook::react::LinesMeasurements = std::vector; using facebook::react::Logger = std::function; -using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::MountingTransactionCallback = std::function; using facebook::react::NativeMethodCallFunc = std::function; @@ -3469,7 +3468,7 @@ facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay facebook::react::Float facebook::react::floatFromYogaFloat(float value); facebook::react::Float facebook::react::floatFromYogaOptionalFloat(facebook::yoga::FloatOptional value); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); -facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; +facebook::react::MediaFeatures facebook::react::getMediaFeatures() noexcept; facebook::react::ParagraphAttributes facebook::react::convertRawProp(const facebook::react::PropsParserContext& context, const facebook::react::RawProps& rawProps, const facebook::react::ParagraphAttributes& sourceParagraphAttributes, const facebook::react::ParagraphAttributes& defaultParagraphAttributes); facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; @@ -5384,7 +5383,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); - public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; + public facebook::react::MediaFeatures conditionalPropsMediaFeatures; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; public std::shared_ptr conditionalProps; public std::string nativeId; @@ -8160,7 +8159,7 @@ struct facebook::react::ColorStop { } struct facebook::react::ConditionalPropsResolution { - public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::MediaFeatures mediaFeatures; public facebook::react::RawProps rawProps; public std::shared_ptr conditionalProps; } @@ -8336,11 +8335,6 @@ struct facebook::react::MediaFeatures { public facebook::react::MediaContrast contrast; } -struct facebook::react::MediaFeaturesSnapshot { - public facebook::react::MediaFeatures features; - public facebook::react::MediaFeaturesGeneration generation; -} - struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { public facebook::react::ModalHostViewSupportedOrientationsMask value; } diff --git a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api index 53c79a798985..21baab761e94 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -3125,7 +3125,6 @@ using facebook::react::GradientDirection = std::variant; -using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -3201,7 +3200,7 @@ facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay facebook::react::Float facebook::react::floatFromYogaFloat(float value); facebook::react::Float facebook::react::floatFromYogaOptionalFloat(facebook::yoga::FloatOptional value); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); -facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; +facebook::react::MediaFeatures facebook::react::getMediaFeatures() noexcept; facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; facebook::react::SharedColor facebook::react::blackColor(); @@ -4297,7 +4296,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); - public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; + public facebook::react::MediaFeatures conditionalPropsMediaFeatures; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; public std::shared_ptr conditionalProps; public std::string nativeId; @@ -5291,7 +5290,7 @@ struct facebook::react::ColorStop { } struct facebook::react::ConditionalPropsResolution { - public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::MediaFeatures mediaFeatures; public facebook::react::RawProps rawProps; public std::shared_ptr conditionalProps; } @@ -5390,11 +5389,6 @@ struct facebook::react::MediaFeatures { public facebook::react::MediaContrast contrast; } -struct facebook::react::MediaFeaturesSnapshot { - public facebook::react::MediaFeatures features; - public facebook::react::MediaFeaturesGeneration generation; -} - struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { public facebook::react::ModalHostViewSupportedOrientationsMask value; } diff --git a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api index 32f846398326..29bf7cce6682 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -3132,7 +3132,6 @@ using facebook::react::GradientDirection = std::variant; -using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -3208,7 +3207,7 @@ facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay facebook::react::Float facebook::react::floatFromYogaFloat(float value); facebook::react::Float facebook::react::floatFromYogaOptionalFloat(facebook::yoga::FloatOptional value); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); -facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; +facebook::react::MediaFeatures facebook::react::getMediaFeatures() noexcept; facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; facebook::react::SharedColor facebook::react::blackColor(); @@ -4304,7 +4303,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); - public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; + public facebook::react::MediaFeatures conditionalPropsMediaFeatures; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; public std::shared_ptr conditionalProps; public std::string nativeId; @@ -5298,7 +5297,7 @@ struct facebook::react::ColorStop { } struct facebook::react::ConditionalPropsResolution { - public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::MediaFeatures mediaFeatures; public facebook::react::RawProps rawProps; public std::shared_ptr conditionalProps; } @@ -5397,11 +5396,6 @@ struct facebook::react::MediaFeatures { public facebook::react::MediaContrast contrast; } -struct facebook::react::MediaFeaturesSnapshot { - public facebook::react::MediaFeatures features; - public facebook::react::MediaFeaturesGeneration generation; -} - struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { public facebook::react::ModalHostViewSupportedOrientationsMask value; } diff --git a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api index d6e500185c8a..494aad7ce01e 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api @@ -108,7 +108,6 @@ using facebook::react::GradientDirection = std::variant; -using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; using facebook::react::RawPropsPropNameHash = uint32_t; @@ -171,7 +170,7 @@ facebook::react::ColorComponents facebook::react::colorComponentsFromColor(faceb facebook::react::ColorSpace facebook::react::getDefaultColorSpace(); facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay display); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); -facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; +facebook::react::MediaFeatures facebook::react::getMediaFeatures() noexcept; facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; facebook::react::SharedColor facebook::react::blackColor(); @@ -955,7 +954,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); - public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; + public facebook::react::MediaFeatures conditionalPropsMediaFeatures; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; public std::shared_ptr conditionalProps; public std::string nativeId; @@ -1799,7 +1798,7 @@ struct facebook::react::ColorStop { } struct facebook::react::ConditionalPropsResolution { - public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::MediaFeatures mediaFeatures; public facebook::react::RawProps rawProps; public std::shared_ptr conditionalProps; } @@ -1884,11 +1883,6 @@ struct facebook::react::MediaFeatures { public facebook::react::MediaContrast contrast; } -struct facebook::react::MediaFeaturesSnapshot { - public facebook::react::MediaFeatures features; - public facebook::react::MediaFeaturesGeneration generation; -} - struct facebook::react::Point { public Float x; public Float y; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api index 9bb00328d2c5..33c418bd6bf0 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api @@ -161,7 +161,6 @@ using facebook::react::LayoutConformanceComponentDescriptor = facebook::react::C using facebook::react::LineMeasureCache = facebook::react::SimpleThreadSafeCache; using facebook::react::LinesMeasurements = std::vector; using facebook::react::Logger = std::function; -using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::MountingTransactionCallback = std::function; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::ParagraphProps = HostPlatformParagraphProps; @@ -330,7 +329,7 @@ facebook::react::ColorSpace facebook::react::getDefaultColorSpace(); facebook::react::ComponentRegistryFactory facebook::react::getDefaultComponentRegistryFactory(); facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay display); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); -facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; +facebook::react::MediaFeatures facebook::react::getMediaFeatures() noexcept; facebook::react::ParagraphAttributes facebook::react::convertRawProp(const facebook::react::PropsParserContext& context, const facebook::react::RawProps& rawProps, const facebook::react::ParagraphAttributes& sourceParagraphAttributes, const facebook::react::ParagraphAttributes& defaultParagraphAttributes); facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; @@ -1893,7 +1892,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); - public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; + public facebook::react::MediaFeatures conditionalPropsMediaFeatures; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; public std::shared_ptr conditionalProps; public std::string nativeId; @@ -4388,7 +4387,7 @@ struct facebook::react::ColorStop { } struct facebook::react::ConditionalPropsResolution { - public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::MediaFeatures mediaFeatures; public facebook::react::RawProps rawProps; public std::shared_ptr conditionalProps; } @@ -4550,11 +4549,6 @@ struct facebook::react::MediaFeatures { public facebook::react::MediaContrast contrast; } -struct facebook::react::MediaFeaturesSnapshot { - public facebook::react::MediaFeatures features; - public facebook::react::MediaFeaturesGeneration generation; -} - struct facebook::react::Point { public Float x; public Float y; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api index 6a17c3cf2315..6fba7a6ac1bb 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api @@ -108,7 +108,6 @@ using facebook::react::GradientDirection = std::variant; -using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; using facebook::react::RawPropsPropNameHash = uint32_t; @@ -171,7 +170,7 @@ facebook::react::ColorComponents facebook::react::colorComponentsFromColor(faceb facebook::react::ColorSpace facebook::react::getDefaultColorSpace(); facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay display); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); -facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; +facebook::react::MediaFeatures facebook::react::getMediaFeatures() noexcept; facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; facebook::react::SharedColor facebook::react::blackColor(); @@ -954,7 +953,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); - public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; + public facebook::react::MediaFeatures conditionalPropsMediaFeatures; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; public std::shared_ptr conditionalProps; public std::string nativeId; @@ -1792,7 +1791,7 @@ struct facebook::react::ColorStop { } struct facebook::react::ConditionalPropsResolution { - public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::MediaFeatures mediaFeatures; public facebook::react::RawProps rawProps; public std::shared_ptr conditionalProps; } @@ -1877,11 +1876,6 @@ struct facebook::react::MediaFeatures { public facebook::react::MediaContrast contrast; } -struct facebook::react::MediaFeaturesSnapshot { - public facebook::react::MediaFeatures features; - public facebook::react::MediaFeaturesGeneration generation; -} - struct facebook::react::Point { public Float x; public Float y; diff --git a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api index 6a17c3cf2315..6fba7a6ac1bb 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api @@ -108,7 +108,6 @@ using facebook::react::GradientDirection = std::variant; -using facebook::react::MediaFeaturesGeneration = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; using facebook::react::RawPropsPropNameHash = uint32_t; @@ -171,7 +170,7 @@ facebook::react::ColorComponents facebook::react::colorComponentsFromColor(faceb facebook::react::ColorSpace facebook::react::getDefaultColorSpace(); facebook::react::DisplayType facebook::react::displayTypeFromYGDisplay(YGDisplay display); facebook::react::LayoutMetrics facebook::react::layoutMetricsFromYogaNode(facebook::yoga::Node& yogaNode); -facebook::react::MediaFeaturesSnapshot facebook::react::getMediaFeaturesSnapshot() noexcept; +facebook::react::MediaFeatures facebook::react::getMediaFeatures() noexcept; facebook::react::Rect facebook::react::insetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& insets) noexcept; facebook::react::Rect facebook::react::outsetBy(const facebook::react::Rect& rect, const facebook::react::EdgeInsets& outsets) noexcept; facebook::react::SharedColor facebook::react::blackColor(); @@ -954,7 +953,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public public Props() = default; public Props(const facebook::react::Props& other) = default; public Props(const facebook::react::PropsParserContext& context, const facebook::react::Props& sourceProps, const facebook::react::RawProps& rawProps, const std::function& filterObjectKeys = nullptr); - public facebook::react::MediaFeaturesGeneration conditionalPropsGeneration; + public facebook::react::MediaFeatures conditionalPropsMediaFeatures; public facebook::react::Props& operator=(const facebook::react::Props& other) = delete; public std::shared_ptr conditionalProps; public std::string nativeId; @@ -1792,7 +1791,7 @@ struct facebook::react::ColorStop { } struct facebook::react::ConditionalPropsResolution { - public facebook::react::MediaFeaturesGeneration generation; + public facebook::react::MediaFeatures mediaFeatures; public facebook::react::RawProps rawProps; public std::shared_ptr conditionalProps; } @@ -1877,11 +1876,6 @@ struct facebook::react::MediaFeatures { public facebook::react::MediaContrast contrast; } -struct facebook::react::MediaFeaturesSnapshot { - public facebook::react::MediaFeatures features; - public facebook::react::MediaFeaturesGeneration generation; -} - struct facebook::react::Point { public Float x; public Float y; From e0b5ccec3b4da7cc4d22d339952a7c525b702aff Mon Sep 17 00:00:00 2001 From: Mathieu Acthernoene Date: Thu, 12 Nov 2026 12:48:00 +0000 Subject: [PATCH 3/6] WIP (perfs) --- .../ReactNativeAttributePayload.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js b/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js index 9202cd651029..e024069628fe 100644 --- a/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js +++ b/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js @@ -121,19 +121,22 @@ function moveConditionalProps( if (payload == null) { return payload; } + const plainProps: {[key: string]: unknown} = {}; let conditionalProps: ?{[key: string]: unknown} = null; for (const key in payload) { const value = payload[key]; if (value instanceof ConditionalProp) { conditionalProps = conditionalProps ?? ({} as {[key: string]: unknown}); conditionalProps[key] = value.definition; - delete payload[key]; + } else { + plainProps[key] = value; } } - if (conditionalProps != null) { - payload[CONDITIONAL_PROPS_KEY] = conditionalProps; + if (conditionalProps == null) { + return payload; } - return payload; + plainProps[CONDITIONAL_PROPS_KEY] = conditionalProps; + return plainProps; } /** From 01838ee80e35604fce064727a247349d5c9d4e4d Mon Sep 17 00:00:00 2001 From: Mathieu Acthernoene Date: Thu, 12 Nov 2026 12:48:27 +0000 Subject: [PATCH 4/6] format --- .../react-native/ReactCommon/react/renderer/core/Props.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/react-native/ReactCommon/react/renderer/core/Props.cpp b/packages/react-native/ReactCommon/react/renderer/core/Props.cpp index c2d5afb206f7..f1fb85b7a73d 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Props.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/Props.cpp @@ -28,7 +28,8 @@ Props::Props( sourceProps.nativeId, {})), conditionalProps(sourceProps.conditionalProps), - conditionalPropsMediaFeatures(sourceProps.conditionalPropsMediaFeatures) {} + conditionalPropsMediaFeatures(sourceProps.conditionalPropsMediaFeatures) { +} void Props::setProp( const PropsParserContext& context, From be581e63bbf2e40c372d8fbde87337e9d099d8cd Mon Sep 17 00:00:00 2001 From: Mathieu Acthernoene Date: Thu, 12 Nov 2026 12:58:25 +0000 Subject: [PATCH 5/6] revert --- packages/react-native/package.json | 4 +- .../examples/Playground/RNTesterPlayground.js | 226 +----------------- yarn.lock | 8 +- 3 files changed, 11 insertions(+), 227 deletions(-) diff --git a/packages/react-native/package.json b/packages/react-native/package.json index 36e4764325a5..0a5e87ee89d1 100644 --- a/packages/react-native/package.json +++ b/packages/react-native/package.json @@ -158,10 +158,10 @@ "@react-native/virtualized-lists": "0.87.0-main", "anser": "^1.4.9", "ansi-regex": "^5.0.0", + "flow-parser": "0.336.0", "base64-js": "^1.5.1", "flow-enums-runtime": "^0.0.6", - "flow-parser": "0.336.0", - "hermes-compiler": "260318099.0.7", + "hermes-compiler": "0.0.0", "invariant": "^2.2.4", "memoize-one": "^6.0.0", "metro-runtime": "^0.88.0", diff --git a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js index c745cce0bbfd..8e6b10479de7 100644 --- a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js +++ b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js @@ -9,240 +9,24 @@ */ import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; -import type {ColorSchemeOverride} from 'react-native/Libraries/Utilities/Appearance'; import RNTesterText from '../../components/RNTesterText'; -import RNTOption from '../../components/RNTOption'; import * as React from 'react'; -import {memo, useEffect, useRef, useState} from 'react'; -import { - Appearance, - Platform, - ScrollView, - StyleSheet, - Text, - View, - useColorScheme, -} from 'react-native'; - -const DARK = '@media (prefers-color-scheme: dark)'; -const LESS_CONTRAST = '@media (prefers-contrast: less)'; -const MORE_CONTRAST = '@media (prefers-contrast: more)'; -const DARK_AND_MORE_CONTRAST = - '@media (prefers-color-scheme: dark) and (prefers-contrast: more)'; - -const CONTRAST_SETTING = - Platform.OS === 'ios' - ? 'Settings > Accessibility > Display & Text Size > Increase Contrast' - : 'Settings > Accessibility > Contrast (Android 14+), or High contrast text'; - -const COLOR_SCHEME_OPTIONS: ReadonlyArray<{ - label: string, - value: ColorSchemeOverride, -}> = [ - {label: 'System', value: 'unspecified'}, - {label: 'Light', value: 'light'}, - {label: 'Dark', value: 'dark'}, -]; - -function ColorSchemeSelector() { - const colorScheme = useColorScheme(); - const [override, setOverride] = useState('unspecified'); - const hasChangedOverride = useRef(false); - - useEffect(() => { - return () => { - // Do not keep the override after leaving the playground. - if (hasChangedOverride.current) { - Appearance.setColorScheme('unspecified'); - } - }; - }, []); +import {StyleSheet, View} from 'react-native'; +function Playground() { return ( - - Color scheme - - {COLOR_SCHEME_OPTIONS.map(option => ( - { - hasChangedOverride.current = true; - setOverride(option.value); - Appearance.setColorScheme(option.value); - }} - /> - ))} - - - useColorScheme(): {colorScheme ?? 'null'} + + + Edit "RNTesterPlayground.js" to change this file - - To change the contrast: {CONTRAST_SETTING}. - - - ); -} - -function Example({ - title, - description, - children, -}: { - title: string, - description: string, - children: React.Node, -}) { - return ( - - {title} - {description} - {children} ); } -// This component renders once. Its colors still change with the media -// features, because native resolves the media queries. -const MemoizedBox = memo(function MemoizedBox() { - const renderCount = useRef(0); - renderCount.current++; - - return ( - - - React renders: {renderCount.current} - - - ); -}); - -function Playground() { - return ( - - - - - - Hello - - - - - - - - - - - - - - - - - - - - - - - - - - - - ); -} - const styles = StyleSheet.create({ container: { padding: 10, - gap: 20, - }, - section: { - gap: 8, - }, - title: { - fontSize: 16, - fontWeight: 'bold', - }, - note: { - fontSize: 12, - }, - options: { - flexDirection: 'row', - gap: 8, - }, -}); - -const examples = StyleSheet.create({ - box: { - height: 50, - borderRadius: 8, - }, - colorScheme: { - padding: 12, - borderRadius: 8, - borderWidth: 1, - borderColor: 'gray', - backgroundColor: {default: 'white', [DARK]: 'black'}, - }, - colorSchemeText: { - color: {default: 'black', [DARK]: 'white'}, - }, - contrast: { - height: 50, - borderRadius: 8, - borderWidth: {default: 2, [LESS_CONTRAST]: 1, [MORE_CONTRAST]: 6}, - borderColor: { - default: 'gray', - [LESS_CONTRAST]: 'lightgray', - [MORE_CONTRAST]: 'black', - }, - }, - combined: { - height: 50, - borderRadius: 8, - backgroundColor: {default: 'gray', [DARK_AND_MORE_CONTRAST]: 'red'}, - }, - nested: { - height: 50, - borderRadius: 8, - backgroundColor: { - default: 'lightblue', - [DARK]: {default: 'darkblue', [MORE_CONTRAST]: 'yellow'}, - }, - }, - layout: { - height: 50, - borderRadius: 8, - backgroundColor: 'green', - width: {default: '50%', [DARK]: '100%'}, }, }); diff --git a/yarn.lock b/yarn.lock index 8b00e0bc1468..7cdbbb8e06ba 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5305,10 +5305,10 @@ hasown@^2.0.3: dependencies: function-bind "^1.1.2" -hermes-compiler@260318099.0.7: - version "260318099.0.7" - resolved "https://registry.yarnpkg.com/hermes-compiler/-/hermes-compiler-260318099.0.7.tgz#e253054d854e89f0c22c92edc8230068a03925c9" - integrity sha512-rhygMID0xtxNEuEdACZDheG3pZOxrKc9fiaF4U/Nr1jADLNmgaW7WD3P9dDRFMTJ9gKgq8sEdttcJ4+u8kwlCA== +hermes-compiler@0.0.0: + version "0.0.0" + resolved "https://registry.yarnpkg.com/hermes-compiler/-/hermes-compiler-0.0.0.tgz#8d9f6a0b2740ce34d71258fec684e7b6bfd97efa" + integrity sha512-boVFutx6ME/Km2mB6vvsQcdnazEYYI/jV1pomx1wcFUG/EVqTkr5CU0CW9bKipOA/8Hyu3NYwW3THg2Q1kNCfA== hermes-estree@0.25.1: version "0.25.1" From 04b4ff9d9870c7b496e2a1f34fc747305a433de3 Mon Sep 17 00:00:00 2001 From: Mathieu Acthernoene Date: Thu, 12 Nov 2026 13:42:07 +0000 Subject: [PATCH 6/6] Add orientation --- .../Libraries/StyleSheet/StyleSheetTypes.js | 1 + .../__tests__/MediaQueries-itest.js | 30 +++++++++++++++++++ .../React/Fabric/RCTSurfacePresenter.mm | 9 +++++- .../react/fabric/FabricUIManager.java | 4 +-- .../react/fabric/FabricUIManagerBinding.kt | 2 +- .../react/fabric/MediaFeaturesObserver.kt | 22 +++++++++++--- .../react/fabric/FabricUIManagerBinding.cpp | 5 +++- .../jni/react/fabric/FabricUIManagerBinding.h | 2 +- .../react/renderer/core/MediaFeatures.cpp | 11 +++++++ .../react/renderer/core/MediaFeatures.h | 8 ++++- .../renderer/core/tests/MediaFeaturesTest.cpp | 9 ++++++ .../testing/fantom/specs/NativeFantom.js | 6 +++- private/react-native-fantom/src/index.js | 2 ++ .../tester/src/NativeFantom.cpp | 5 +++- .../tester/src/NativeFantom.h | 6 +++- .../api-snapshots/ReactAppleDebugCxx.api | 6 ++++ .../api-snapshots/ReactAppleFrameworksCxx.api | 6 ++++ .../api-snapshots/ReactAppleNewarchCxx.api | 6 ++++ .../api-snapshots/ReactAppleReleaseCxx.api | 6 ++++ .../api-snapshots/ReactCommonDebugCxx.api | 6 ++++ .../ReactCommonFrameworksCxx.api | 6 ++++ .../api-snapshots/ReactCommonNewarchCxx.api | 6 ++++ .../api-snapshots/ReactCommonReleaseCxx.api | 6 ++++ 23 files changed, 156 insertions(+), 14 deletions(-) diff --git a/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js b/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js index 5dfc618a38fd..16337eaaa1c8 100644 --- a/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js +++ b/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js @@ -47,6 +47,7 @@ export type CursorValue = 'auto' | 'pointer'; * query is used, or the `default` value. Supported media features: * - `(prefers-color-scheme: light | dark)` * - `(prefers-contrast: no-preference | less | more)` + * - `(orientation: portrait | landscape)` * * Features can be combined with `and`, for example * `'@media (prefers-color-scheme: dark) and (prefers-contrast: more)'`. diff --git a/packages/react-native/Libraries/StyleSheet/__tests__/MediaQueries-itest.js b/packages/react-native/Libraries/StyleSheet/__tests__/MediaQueries-itest.js index 2f4ac0c063ca..42a09016fef6 100644 --- a/packages/react-native/Libraries/StyleSheet/__tests__/MediaQueries-itest.js +++ b/packages/react-native/Libraries/StyleSheet/__tests__/MediaQueries-itest.js @@ -21,6 +21,7 @@ const DARK = '@media (prefers-color-scheme: dark)'; const MORE_CONTRAST = '@media (prefers-contrast: more)'; const DARK_AND_MORE_CONTRAST = '@media (prefers-color-scheme: dark) and (prefers-contrast: more)'; +const LANDSCAPE = '@media (orientation: landscape)'; const styles = StyleSheet.create({ box: { @@ -49,6 +50,10 @@ const styles = StyleSheet.create({ width: {default: 10, [DARK]: 20}, height: 10, }, + orientation: { + flexDirection: {default: 'column', [LANDSCAPE]: 'row'}, + backgroundColor: {default: 'white', [LANDSCAPE]: 'black'}, + }, text: { color: {default: 'black', [DARK]: 'white'}, }, @@ -185,6 +190,31 @@ describe('media queries in styles', () => { ); }); + it('matches orientation', () => { + const root = Fantom.createRoot(); + Fantom.runTask(() => { + root.render(); + }); + + expect(renderedBackgroundColor(root)).toEqual( + , + ); + + setMediaFeatures({orientation: 'landscape'}); + expect( + root + .getRenderedOutput({props: ['backgroundColor', 'flexDirection']}) + .toJSX(), + ).toEqual( + , + ); + + setMediaFeatures({orientation: 'portrait'}); + expect(renderedBackgroundColor(root)).toEqual( + , + ); + }); + it('supports nested conditions', () => { const root = Fantom.createRoot(); Fantom.runTask(() => { diff --git a/packages/react-native/React/Fabric/RCTSurfacePresenter.mm b/packages/react-native/React/Fabric/RCTSurfacePresenter.mm index 923568484aa5..40e18118adb5 100644 --- a/packages/react-native/React/Fabric/RCTSurfacePresenter.mm +++ b/packages/react-native/React/Fabric/RCTSurfacePresenter.mm @@ -124,6 +124,10 @@ - (instancetype)initWithContextContainer:(std::shared_ptr windowSize.height ? MediaOrientation::Landscape : MediaOrientation::Portrait, }; [self.scheduler updateMediaFeatures:mediaFeatures]; } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java index f4f90ce7f301..9d4e36d1cea6 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java @@ -480,10 +480,10 @@ public void initialize() { mMediaFeaturesObserver = new MediaFeaturesObserver( mReactApplicationContext, - (colorScheme, contrast) -> { + (colorScheme, contrast, orientation) -> { FabricUIManagerBinding binding = mBinding; if (binding != null) { - binding.updateMediaFeatures(colorScheme, contrast); + binding.updateMediaFeatures(colorScheme, contrast, orientation); } }); mMediaFeaturesObserver.start(); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManagerBinding.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManagerBinding.kt index 0d585667c0c1..0dc6b3db5a84 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManagerBinding.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManagerBinding.kt @@ -85,7 +85,7 @@ internal class FabricUIManagerBinding : HybridClassBase() { external fun reportMount(surfaceId: Int) - external fun updateMediaFeatures(colorScheme: Int, contrast: Int) + external fun updateMediaFeatures(colorScheme: Int, contrast: Int, orientation: Int) external fun pullAndExecuteTransaction(surfaceId: Int) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt index 51738ae44a74..1baecf9bb55d 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt @@ -33,12 +33,14 @@ internal class MediaFeaturesObserver( /** * @param colorScheme one of [COLOR_SCHEME_LIGHT] or [COLOR_SCHEME_DARK] * @param contrast one of [CONTRAST_NO_PREFERENCE], [CONTRAST_LESS] or [CONTRAST_MORE] + * @param orientation one of [ORIENTATION_PORTRAIT] or [ORIENTATION_LANDSCAPE] */ - fun onMediaFeaturesChanged(colorScheme: Int, contrast: Int) + fun onMediaFeaturesChanged(colorScheme: Int, contrast: Int, orientation: Int) } private var lastColorScheme: Int? = null private var lastContrast: Int? = null + private var lastOrientation: Int? = null private val componentCallbacks = object : ComponentCallbacks { @@ -91,11 +93,21 @@ internal class MediaFeaturesObserver( val colorScheme = if (UiModeUtils.isDarkMode(currentContext)) COLOR_SCHEME_DARK else COLOR_SCHEME_LIGHT val contrast = readContrast() - - if (colorScheme != lastColorScheme || contrast != lastContrast) { + val orientation = + if ( + currentContext.resources.configuration.orientation == + Configuration.ORIENTATION_LANDSCAPE + ) + ORIENTATION_LANDSCAPE + else ORIENTATION_PORTRAIT + + if ( + colorScheme != lastColorScheme || contrast != lastContrast || orientation != lastOrientation + ) { lastColorScheme = colorScheme lastContrast = contrast - listener.onMediaFeaturesChanged(colorScheme, contrast) + lastOrientation = orientation + listener.onMediaFeaturesChanged(colorScheme, contrast, orientation) } } @@ -140,6 +152,8 @@ internal class MediaFeaturesObserver( const val CONTRAST_NO_PREFERENCE: Int = 0 const val CONTRAST_LESS: Int = 1 const val CONTRAST_MORE: Int = 2 + const val ORIENTATION_PORTRAIT: Int = 0 + const val ORIENTATION_LANDSCAPE: Int = 1 private const val HIGH_TEXT_CONTRAST_ENABLED = "high_text_contrast_enabled" } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp index a4e250f2003c..8b8e49774eee 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.cpp @@ -122,7 +122,8 @@ void FabricUIManagerBinding::reportMount(SurfaceId surfaceId) { void FabricUIManagerBinding::updateMediaFeatures( jint colorScheme, - jint contrast) { + jint contrast, + jint orientation) { auto scheduler = getScheduler(); if (!scheduler) { LOG(ERROR) @@ -136,6 +137,8 @@ void FabricUIManagerBinding::updateMediaFeatures( .contrast = contrast == 2 ? MediaContrast::More : contrast == 1 ? MediaContrast::Less : MediaContrast::NoPreference, + .orientation = orientation == 1 ? MediaOrientation::Landscape + : MediaOrientation::Portrait, }); } diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h index ecd9d66002d4..8e64964aab67 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/fabric/FabricUIManagerBinding.h @@ -135,7 +135,7 @@ class FabricUIManagerBinding : public jni::HybridClass, void reportMount(SurfaceId surfaceId); - void updateMediaFeatures(jint colorScheme, jint contrast); + void updateMediaFeatures(jint colorScheme, jint contrast, jint orientation); void pullAndExecuteTransaction(SurfaceId surfaceId); diff --git a/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp index 651988ac889b..c86a64d1e1ed 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp @@ -14,6 +14,7 @@ namespace facebook::react { namespace { std::atomic currentMediaFeatures{MediaFeatures{}}; +static_assert(std::atomic::is_always_lock_free); char toLowerAscii(char c) noexcept { return (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; @@ -80,6 +81,16 @@ bool matchMediaFeature( return false; } + if (equalsIgnoringAsciiCase(name, "orientation")) { + if (equalsIgnoringAsciiCase(value, "portrait")) { + return features.orientation == MediaOrientation::Portrait; + } + if (equalsIgnoringAsciiCase(value, "landscape")) { + return features.orientation == MediaOrientation::Landscape; + } + return false; + } + return false; } diff --git a/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h index c0937b92f400..7d392178a1c3 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h +++ b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h @@ -18,13 +18,18 @@ enum class MediaColorScheme : uint8_t { Light, Dark }; enum class MediaContrast : uint8_t { NoPreference, Less, More }; +enum class MediaOrientation : uint8_t { Portrait, Landscape }; + /* * The values that media queries in props are matched against, for example * `@media (prefers-color-scheme: dark)`. + * + * Aligned on 4 bytes, so that `std::atomic` is lock-free. */ -struct MediaFeatures { +struct alignas(4) MediaFeatures { MediaColorScheme colorScheme{MediaColorScheme::Light}; MediaContrast contrast{MediaContrast::NoPreference}; + MediaOrientation orientation{MediaOrientation::Portrait}; bool operator==(const MediaFeatures &other) const = default; }; @@ -50,6 +55,7 @@ bool setMediaFeatures(const MediaFeatures &features) noexcept; * Supported media features: * - `(prefers-color-scheme: light | dark)` * - `(prefers-contrast: no-preference | less | more)` + * - `(orientation: portrait | landscape)` * * Features can be combined with `and`, for example * `@media (prefers-color-scheme: dark) and (prefers-contrast: more)`. diff --git a/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp b/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp index 18301f112692..a7cd0abfe60e 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp @@ -45,6 +45,15 @@ TEST(MediaFeaturesTest, matchesPrefersContrast) { matchMediaQuery("@media (prefers-contrast: less)", kDarkMoreContrast)); } +TEST(MediaFeaturesTest, matchesOrientation) { + const MediaFeatures landscape{.orientation = MediaOrientation::Landscape}; + EXPECT_TRUE(matchMediaQuery("@media (orientation: portrait)", kLight)); + EXPECT_FALSE(matchMediaQuery("@media (orientation: landscape)", kLight)); + EXPECT_TRUE(matchMediaQuery("@media (orientation: landscape)", landscape)); + EXPECT_FALSE(matchMediaQuery("@media (orientation: portrait)", landscape)); + EXPECT_FALSE(matchMediaQuery("@media (orientation: square)", landscape)); +} + TEST(MediaFeaturesTest, ignoresWhitespaceAndCase) { EXPECT_TRUE(matchMediaQuery( " @MEDIA( Prefers-Color-Scheme :DARK ) ", kDarkMoreContrast)); diff --git a/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js b/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js index 2b1d9e8b4d8b..d14e787fdab5 100644 --- a/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js +++ b/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js @@ -138,7 +138,11 @@ interface Spec extends TurboModule { setImageResponse(uri: string, imageResponse: ImageResponse): void; clearImage(uri: string): void; clearAllImages(): void; - setMediaFeatures: (colorScheme: string, contrast: string) => void; + setMediaFeatures: ( + colorScheme: string, + contrast: string, + orientation: string, + ) => void; } export default TurboModuleRegistry.getEnforcing( diff --git a/private/react-native-fantom/src/index.js b/private/react-native-fantom/src/index.js index 9275fd8718f9..735c2e4e74ba 100644 --- a/private/react-native-fantom/src/index.js +++ b/private/react-native-fantom/src/index.js @@ -738,11 +738,13 @@ export function setMediaFeatures( mediaFeatures: Readonly<{ colorScheme?: 'light' | 'dark', contrast?: 'no-preference' | 'less' | 'more', + orientation?: 'portrait' | 'landscape', }>, ) { NativeFantom.setMediaFeatures( mediaFeatures.colorScheme ?? 'light', mediaFeatures.contrast ?? 'no-preference', + mediaFeatures.orientation ?? 'portrait', ); } diff --git a/private/react-native-fantom/tester/src/NativeFantom.cpp b/private/react-native-fantom/tester/src/NativeFantom.cpp index 93d5ed4e7190..d2b460a69dd1 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.cpp +++ b/private/react-native-fantom/tester/src/NativeFantom.cpp @@ -239,13 +239,16 @@ void NativeFantom::enqueueScrollEvent( void NativeFantom::setMediaFeatures( jsi::Runtime& runtime, const std::string& colorScheme, - const std::string& contrast) { + const std::string& contrast, + const std::string& orientation) { facebook::react::setMediaFeatures({ .colorScheme = colorScheme == "dark" ? MediaColorScheme::Dark : MediaColorScheme::Light, .contrast = contrast == "more" ? MediaContrast::More : contrast == "less" ? MediaContrast::Less : MediaContrast::NoPreference, + .orientation = orientation == "landscape" ? MediaOrientation::Landscape + : MediaOrientation::Portrait, }); UIManagerBinding::getBinding(runtime) ->getUIManager() diff --git a/private/react-native-fantom/tester/src/NativeFantom.h b/private/react-native-fantom/tester/src/NativeFantom.h index c3016f9a47a3..bb2c701dcdda 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.h +++ b/private/react-native-fantom/tester/src/NativeFantom.h @@ -152,7 +152,11 @@ class NativeFantom : public NativeFantomCxxSpec { void clearImage(jsi::Runtime &rt, const std::string &uri); void clearAllImages(jsi::Runtime &rt); - void setMediaFeatures(jsi::Runtime &runtime, const std::string &colorScheme, const std::string &contrast); + void setMediaFeatures( + jsi::Runtime &runtime, + const std::string &colorScheme, + const std::string &contrast, + const std::string &orientation); private: TesterAppDelegate &appDelegate_; diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index df1e5d93a21c..bcc1adaad4ed 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -4987,6 +4987,11 @@ enum facebook::react::MediaContrast : uint8_t { NoPreference, } +enum facebook::react::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -5401,6 +5406,7 @@ struct facebook::react::MediaFeatures { public bool operator==(const facebook::react::MediaFeatures& other) const = default; public facebook::react::MediaColorScheme colorScheme; public facebook::react::MediaContrast contrast; + public facebook::react::MediaOrientation orientation; } struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { diff --git a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api index eb67ff272f42..a9474a60be27 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -7275,6 +7275,11 @@ enum facebook::react::MediaContrast : uint8_t { NoPreference, } +enum facebook::react::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -8333,6 +8338,7 @@ struct facebook::react::MediaFeatures { public bool operator==(const facebook::react::MediaFeatures& other) const = default; public facebook::react::MediaColorScheme colorScheme; public facebook::react::MediaContrast contrast; + public facebook::react::MediaOrientation orientation; } struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { diff --git a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api index 21baab761e94..24cea806e0bc 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -4973,6 +4973,11 @@ enum facebook::react::MediaContrast : uint8_t { NoPreference, } +enum facebook::react::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -5387,6 +5392,7 @@ struct facebook::react::MediaFeatures { public bool operator==(const facebook::react::MediaFeatures& other) const = default; public facebook::react::MediaColorScheme colorScheme; public facebook::react::MediaContrast contrast; + public facebook::react::MediaOrientation orientation; } struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { diff --git a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api index 29bf7cce6682..054035741ec8 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -4980,6 +4980,11 @@ enum facebook::react::MediaContrast : uint8_t { NoPreference, } +enum facebook::react::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -5394,6 +5399,7 @@ struct facebook::react::MediaFeatures { public bool operator==(const facebook::react::MediaFeatures& other) const = default; public facebook::react::MediaColorScheme colorScheme; public facebook::react::MediaContrast contrast; + public facebook::react::MediaOrientation orientation; } struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { diff --git a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api index 494aad7ce01e..42a5dbbf7658 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api @@ -1522,6 +1522,11 @@ enum facebook::react::MediaContrast : uint8_t { NoPreference, } +enum facebook::react::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::OutlineStyle : uint8_t { Dashed, Dotted, @@ -1881,6 +1886,7 @@ struct facebook::react::MediaFeatures { public bool operator==(const facebook::react::MediaFeatures& other) const = default; public facebook::react::MediaColorScheme colorScheme; public facebook::react::MediaContrast contrast; + public facebook::react::MediaOrientation orientation; } struct facebook::react::Point { diff --git a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api index 33c418bd6bf0..de1a3eac64ae 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api @@ -3568,6 +3568,11 @@ enum facebook::react::MediaContrast : uint8_t { NoPreference, } +enum facebook::react::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::NullValueStrategy { Ignore, Override, @@ -4547,6 +4552,7 @@ struct facebook::react::MediaFeatures { public bool operator==(const facebook::react::MediaFeatures& other) const = default; public facebook::react::MediaColorScheme colorScheme; public facebook::react::MediaContrast contrast; + public facebook::react::MediaOrientation orientation; } struct facebook::react::Point { diff --git a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api index 6fba7a6ac1bb..f5fbe5983a9b 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api @@ -1515,6 +1515,11 @@ enum facebook::react::MediaContrast : uint8_t { NoPreference, } +enum facebook::react::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::OutlineStyle : uint8_t { Dashed, Dotted, @@ -1874,6 +1879,7 @@ struct facebook::react::MediaFeatures { public bool operator==(const facebook::react::MediaFeatures& other) const = default; public facebook::react::MediaColorScheme colorScheme; public facebook::react::MediaContrast contrast; + public facebook::react::MediaOrientation orientation; } struct facebook::react::Point { diff --git a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api index 6fba7a6ac1bb..f5fbe5983a9b 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api @@ -1515,6 +1515,11 @@ enum facebook::react::MediaContrast : uint8_t { NoPreference, } +enum facebook::react::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::OutlineStyle : uint8_t { Dashed, Dotted, @@ -1874,6 +1879,7 @@ struct facebook::react::MediaFeatures { public bool operator==(const facebook::react::MediaFeatures& other) const = default; public facebook::react::MediaColorScheme colorScheme; public facebook::react::MediaContrast contrast; + public facebook::react::MediaOrientation orientation; } struct facebook::react::Point {