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..e024069628fe 100644 --- a/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js +++ b/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js @@ -15,6 +15,130 @@ 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; + } + 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; + } else { + plainProps[key] = value; + } + } + if (conditionalProps == null) { + return payload; + } + plainProps[CONDITIONAL_PROPS_KEY] = conditionalProps; + return plainProps; +} + /** * Create a payload that contains all the updates between two sets of props. * @@ -82,19 +206,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 +412,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 +437,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 +580,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 +594,7 @@ function addNestedProperty( newValue = true; } else { // An atomic prop. Doesn't need to be flattened. - newValue = prop; + newValue = processAttributeValue(attributeConfig, prop); } } @@ -512,7 +633,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 +641,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..16337eaaa1c8 100644 --- a/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js +++ b/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js @@ -42,6 +42,44 @@ 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)` + * - `(orientation: portrait | landscape)` + * + * 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 +1134,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 +1162,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..42a09016fef6 --- /dev/null +++ b/packages/react-native/Libraries/StyleSheet/__tests__/MediaQueries-itest.js @@ -0,0 +1,325 @@ +/** + * 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 LANDSCAPE = '@media (orientation: landscape)'; + +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, + }, + orientation: { + flexDirection: {default: 'column', [LANDSCAPE]: 'row'}, + backgroundColor: {default: 'white', [LANDSCAPE]: 'black'}, + }, + 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('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(() => { + 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..40e18118adb5 100644 --- a/packages/react-native/React/Fabric/RCTSurfacePresenter.mm +++ b/packages/react-native/React/Fabric/RCTSurfacePresenter.mm @@ -115,6 +115,23 @@ - (instancetype)initWithContextContainer:(std::shared_ptr windowSize.height ? MediaOrientation::Landscape : MediaOrientation::Portrait, + }; + [self.scheduler updateMediaFeatures:mediaFeatures]; +} + - (RCTScheduler *)_createScheduler { auto componentRegistryFactory = [factory = 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 2727e880d083..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 @@ -178,6 +178,7 @@ public class FabricUIManager } @Nullable private FabricUIManagerBinding mBinding; + @Nullable private MediaFeaturesObserver mMediaFeaturesObserver; private final ReactApplicationContext mReactApplicationContext; private final MountingManager mMountingManager; private final FabricEventDispatcher mEventDispatcher; @@ -460,9 +461,32 @@ 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); + mMediaFeaturesObserver = + new MediaFeaturesObserver( + mReactApplicationContext, + (colorScheme, contrast, orientation) -> { + FabricUIManagerBinding binding = mBinding; + if (binding != null) { + binding.updateMediaFeatures(colorScheme, contrast, orientation); + } + }); + mMediaFeaturesObserver.start(); if (ReactNativeFeatureFlags.enableFabricLogs()) { mDevToolsReactPerfLogger = new DevToolsReactPerfLogger(); mDevToolsReactPerfLogger.addDevToolsReactPerfLoggerListener(FABRIC_PERF_LOGGER); @@ -502,6 +526,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..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,6 +85,8 @@ internal class FabricUIManagerBinding : HybridClassBase() { external fun reportMount(surfaceId: Int) + external fun updateMediaFeatures(colorScheme: Int, contrast: Int, orientation: 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..1baecf9bb55d --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/fabric/MediaFeaturesObserver.kt @@ -0,0 +1,160 @@ +/* + * 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 + +/** + * 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] + * @param orientation one of [ORIENTATION_PORTRAIT] or [ORIENTATION_LANDSCAPE] + */ + 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 { + 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() { + 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() { + 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() + 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 + lastOrientation = orientation + listener.onMediaFeaturesChanged(colorScheme, contrast, orientation) + } + } + + 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 + 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/java/com/facebook/react/runtime/ReactHostImpl.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/runtime/ReactHostImpl.kt index f54557bf6906..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 @@ -745,6 +745,8 @@ public class ReactHostImpl( val appearanceModule = currentReactContext.getNativeModule(AppearanceModule::class.java) appearanceModule?.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 8cff9f825b58..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 @@ -120,6 +120,28 @@ void FabricUIManagerBinding::reportMount(SurfaceId surfaceId) { scheduler->reportMount(surfaceId); } +void FabricUIManagerBinding::updateMediaFeatures( + jint colorScheme, + jint contrast, + jint orientation) { + auto scheduler = getScheduler(); + if (!scheduler) { + LOG(ERROR) + << "FabricUIManagerBinding::updateMediaFeatures: scheduler disappeared"; + return; + } + // The values match the `MediaFeaturesObserver` constants. + scheduler->updateMediaFeatures({ + .colorScheme = + colorScheme == 1 ? MediaColorScheme::Dark : MediaColorScheme::Light, + .contrast = contrast == 2 ? MediaContrast::More + : contrast == 1 ? MediaContrast::Less + : MediaContrast::NoPreference, + .orientation = orientation == 1 ? MediaOrientation::Landscape + : MediaOrientation::Portrait, + }); +} + void FabricUIManagerBinding::pullAndExecuteTransaction(SurfaceId surfaceId) { TraceSection section("FabricUIManagerBinding::pullAndExecuteTransaction"); @@ -937,6 +959,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..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,6 +135,8 @@ class FabricUIManagerBinding : public jni::HybridClass, void reportMount(SurfaceId surfaceId); + void updateMediaFeatures(jint colorScheme, jint contrast, jint orientation); + 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..c37b33fd619a 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->conditionalPropsMediaFeatures = conditionalPropsResolution->mediaFeatures; } #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..a351b1d48977 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/ConditionalProps.cpp @@ -0,0 +1,130 @@ +/* + * 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 mediaFeatures = getMediaFeatures(); + auto isStale = sourceConditionalProps != nullptr && + sourceProps->conditionalPropsMediaFeatures != mediaFeatures; + + 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, mediaFeatures); + 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, mediaFeatures); + } + } + } + + return ConditionalPropsResolution{ + .rawProps = RawProps(std::move(values)), + .conditionalProps = conditionalProps.empty() + ? nullptr + : std::make_shared(std::move(conditionalProps)), + .mediaFeatures = mediaFeatures, + }; +} + +} // 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..448891c3c06c --- /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 media features that the values were resolved with. + */ + MediaFeatures mediaFeatures; +}; + +/* + * Merges the conditional values of `sourceProps` and `rawProps`, and resolves + * 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). + */ +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..c86a64d1e1ed --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.cpp @@ -0,0 +1,147 @@ +/* + * 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 { + +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; +} + +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; + } + + 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; +} + +} // namespace + +MediaFeatures getMediaFeatures() noexcept { + return currentMediaFeatures.load(std::memory_order_acquire); +} + +bool setMediaFeatures(const MediaFeatures& features) noexcept { + return currentMediaFeatures.exchange(features, std::memory_order_acq_rel) != + features; +} + +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..7d392178a1c3 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h @@ -0,0 +1,65 @@ +/* + * 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 }; + +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 alignas(4) MediaFeatures { + MediaColorScheme colorScheme{MediaColorScheme::Light}; + MediaContrast contrast{MediaContrast::NoPreference}; + MediaOrientation orientation{MediaOrientation::Portrait}; + + bool operator==(const MediaFeatures &other) const = default; +}; + +/* + * Returns the current media features of the process. Thread-safe. + */ +MediaFeatures getMediaFeatures() 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)` + * - `(orientation: portrait | landscape)` + * + * 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..f1fb85b7a73d 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Props.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/Props.cpp @@ -26,7 +26,10 @@ Props::Props( rawProps, "nativeID", sourceProps.nativeId, - {})) {} + {})), + conditionalProps(sourceProps.conditionalProps), + 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 c717e3182a05..45997666b3bc 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,18 @@ 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 media features that `conditionalProps` were resolved with. + */ + MediaFeatures conditionalPropsMediaFeatures{}; + #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..b48436fb6f60 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/ConditionalPropsTest.cpp @@ -0,0 +1,155 @@ +/* + * 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->mediaFeatures, kDark); +} + +TEST_F(ConditionalPropsTest, keepsUpToDateConditionalValuesOfTheSource) { + Props sourceProps; + sourceProps.conditionalProps = std::make_shared( + folly::dynamic::object("opacity", opacityValue())); + sourceProps.conditionalPropsMediaFeatures = kLight; + + 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.conditionalPropsMediaFeatures = kLight; + + 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.conditionalPropsMediaFeatures = kLight; + + 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->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 new file mode 100644 index 000000000000..a7cd0abfe60e --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp @@ -0,0 +1,122 @@ +/* + * 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, 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)); +} + +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, reportsOnlyChanges) { + setMediaFeatures(kLight); + + EXPECT_FALSE(setMediaFeatures(kLight)); + EXPECT_EQ(getMediaFeatures(), kLight); + + EXPECT_TRUE(setMediaFeatures(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 a278fb2b3400..296067924c94 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp @@ -459,6 +459,23 @@ 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. `mediaFeatures_` tells whether the shadow trees of + // this scheduler still need an update. + setMediaFeatures(mediaFeatures); + if (mediaFeatures_.exchange(mediaFeatures) == mediaFeatures) { + 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..183f9bb48b4f 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,9 @@ class Scheduler final : public UIManagerDelegate { RuntimeExecutor runtimeExecutor_; std::shared_ptr uiManager_; + // 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/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..d56678e3faeb --- /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 other media features are resolved again. Returns + * `nullptr` if nothing changed in the subtree. + */ +std::shared_ptr cloneWithUpdatedConditionalProps( + const ShadowNode& shadowNode, + const PropsParserContext& context, + 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, mediaFeatures); + 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->conditionalPropsMediaFeatures != mediaFeatures) { + // 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 mediaFeatures = getMediaFeatures(); + + 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, mediaFeatures)); + }, + {.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/src/private/testing/fantom/specs/NativeFantom.js b/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js index d4ef3a3e39ca..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,6 +138,11 @@ interface Spec extends TurboModule { setImageResponse(uri: string, imageResponse: ImageResponse): void; clearImage(uri: string): void; clearAllImages(): 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 2d5ee2504383..735c2e4e74ba 100644 --- a/private/react-native-fantom/src/index.js +++ b/private/react-native-fantom/src/index.js @@ -722,6 +722,32 @@ 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', + orientation?: 'portrait' | 'landscape', + }>, +) { + NativeFantom.setMediaFeatures( + mediaFeatures.colorScheme ?? 'light', + mediaFeatures.contrast ?? 'no-preference', + mediaFeatures.orientation ?? 'portrait', + ); +} + 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..d2b460a69dd1 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,25 @@ void NativeFantom::enqueueScrollEvent( }); } +void NativeFantom::setMediaFeatures( + jsi::Runtime& runtime, + const std::string& colorScheme, + 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() + .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..bb2c701dcdda 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.h +++ b/private/react-native-fantom/tester/src/NativeFantom.h @@ -152,6 +152,12 @@ 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, + const std::string &orientation); + 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..bcc1adaad4ed 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; @@ -3190,6 +3192,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 +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::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(); @@ -3221,9 +3226,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 +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::MediaFeatures conditionalPropsMediaFeatures; 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 +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; @@ -4966,6 +4976,22 @@ 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::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -5282,6 +5308,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeatures mediaFeatures; + 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 +5402,13 @@ 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; + public facebook::react::MediaOrientation orientation; +} + 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..a9474a60be27 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; @@ -3445,6 +3447,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 +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::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; @@ -3490,6 +3495,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 +3505,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 +5383,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::MediaFeatures conditionalPropsMediaFeatures; 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 +5451,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 +5702,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 +6344,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 +7264,22 @@ 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::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -8135,6 +8163,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeatures mediaFeatures; + 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 +8334,13 @@ 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; + public facebook::react::MediaOrientation orientation; +} + 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..24cea806e0bc 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; @@ -3183,6 +3185,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 +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::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(); @@ -3214,9 +3219,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 +4296,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::MediaFeatures conditionalPropsMediaFeatures; 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 +4350,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 +4962,22 @@ 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::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -5268,6 +5294,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeatures mediaFeatures; + 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 +5388,13 @@ 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; + public facebook::react::MediaOrientation orientation; +} + 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..054035741ec8 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; @@ -3190,6 +3192,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 +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::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(); @@ -3221,9 +3226,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 +4303,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::MediaFeatures conditionalPropsMediaFeatures; 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 +4357,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 +4969,22 @@ 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::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -5275,6 +5301,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeatures mediaFeatures; + 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 +5395,13 @@ 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; + public facebook::react::MediaOrientation orientation; +} + 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..42a5dbbf7658 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; @@ -159,6 +160,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 +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::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(); @@ -180,10 +184,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 +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::MediaFeatures conditionalPropsMediaFeatures; 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 +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; @@ -1502,6 +1511,22 @@ 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::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::OutlineStyle : uint8_t { Dashed, Dotted, @@ -1777,6 +1802,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeatures mediaFeatures; + 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 +1882,13 @@ 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; + public facebook::react::MediaOrientation orientation; +} + 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..de1a3eac64ae 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; @@ -312,6 +313,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 +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::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; @@ -346,6 +350,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 +360,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 +1892,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::MediaFeatures conditionalPropsMediaFeatures; 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 +1907,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 +2150,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 +2713,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 +3557,22 @@ 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::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::NullValueStrategy { Ignore, Override, @@ -4364,6 +4391,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeatures mediaFeatures; + 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 +4548,13 @@ 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; + public facebook::react::MediaOrientation orientation; +} + 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..f5fbe5983a9b 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; @@ -159,6 +160,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 +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::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(); @@ -180,10 +184,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 +953,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::MediaFeatures conditionalPropsMediaFeatures; 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 +968,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 +1504,22 @@ 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::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::OutlineStyle : uint8_t { Dashed, Dotted, @@ -1770,6 +1795,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeatures mediaFeatures; + 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 +1875,13 @@ 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; + public facebook::react::MediaOrientation orientation; +} + 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..f5fbe5983a9b 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; @@ -159,6 +160,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 +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::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(); @@ -180,10 +184,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 +953,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::MediaFeatures conditionalPropsMediaFeatures; 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 +968,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 +1504,22 @@ 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::MediaOrientation : uint8_t { + Landscape, + Portrait, +} + enum facebook::react::OutlineStyle : uint8_t { Dashed, Dotted, @@ -1770,6 +1795,12 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalPropsResolution { + public facebook::react::MediaFeatures mediaFeatures; + 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 +1875,13 @@ 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; + public facebook::react::MediaOrientation orientation; +} + struct facebook::react::Point { public Float x; public Float y;