diff --git a/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js b/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js index fa5583c74119..5aab9372c53f 100644 --- a/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js +++ b/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/ReactNativeAttributePayload.js @@ -8,9 +8,21 @@ * @format */ -import type {AttributeConfiguration} from '../../Renderer/shims/ReactNativeTypes'; - +import type { + AnyAttributeType, + AttributeConfiguration, +} from '../../Renderer/shims/ReactNativeTypes'; +import type { + CompiledConditionalValue, + StyleObject, +} from '../../StyleSheet/processStyleConditions'; + +import ReactNativeStyleAttributes from '../../Components/View/ReactNativeStyleAttributes'; import flattenStyle from '../../StyleSheet/flattenStyle'; +import { + compileConditionalValue, + isConditionalValue, +} from '../../StyleSheet/processStyleConditions'; import deepDiffer from '../../Utilities/differ/deepDiffer'; const emptyObject = {}; @@ -34,6 +46,75 @@ const deepDifferOptions = { unsafelyIgnoreFunctions: true, }; +// Native reads a conditional value under its own prop as +// `{$conditionalValue: {default, conditions}}`. +const CONDITIONAL_VALUE_KEY = '$conditionalValue'; + +// Tells native that the payload has a conditional value, so that other +// payloads skip the search. +const HAS_CONDITIONAL_VALUES_KEY = '$hasConditionalValues'; + +let hasConditionalValues = false; + +function isStyleConditionValue( + value: unknown, + validAttributes: AttributeConfiguration, +): implies value is StyleObject { + return ( + typeof value === 'object' && + value !== null && + (validAttributes as unknown) === ReactNativeStyleAttributes && + isConditionalValue(value) + ); +} + +function processStyleConditionValue( + value: StyleObject, + attributeConfig: ?AnyAttributeType, + propKey: string, +): unknown { + const compiled = compileConditionalValue(value, propKey); + if (compiled == null) { + return null; + } + const process = + attributeConfig != null && attributeConfig !== true + ? attributeConfig.process + : null; + // `process` returns undefined for an invalid value. + const processValue = (item: unknown) => + item == null || process == null ? (item ?? null) : (process(item) ?? null); + const defaultValue = processValue(compiled.default); + if (compiled.conditions.length === 0) { + return defaultValue; + } + hasConditionalValues = true; + const conditionalValue: CompiledConditionalValue = { + default: defaultValue, + conditions: compiled.conditions.map(condition => ({ + query: condition.query, + value: processValue(condition.value), + })), + }; + return {[CONDITIONAL_VALUE_KEY]: conditionalValue}; +} + +function processAttributeValue( + value: unknown, + attributeConfig: ?AnyAttributeType, + propKey: string, + validAttributes: AttributeConfiguration, +): unknown { + if (isStyleConditionValue(value, validAttributes)) { + return processStyleConditionValue(value, attributeConfig, propKey); + } + return attributeConfig != null && + attributeConfig !== true && + attributeConfig.process != null + ? attributeConfig.process(value) + : value; +} + function defaultDiffer(prevProp: unknown, nextProp: unknown): boolean { if (typeof nextProp !== 'object' || nextProp === null) { // Scalars have already been checked for equality @@ -82,19 +163,18 @@ 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( + nextProp, + attributeConfig, + propKey, + validAttributes, + ); } // $FlowFixMe[incompatible-use] found when upgrading Flow removedKeys[propKey] = false; @@ -291,19 +371,18 @@ 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( + nextProp, + attributeConfig, + propKey, + validAttributes, + ); } continue; } @@ -319,26 +398,35 @@ function diffProperties( // a normal leaf has changed (updatePayload || (updatePayload = {} as {[key: string]: unknown}))[ propKey - ] = nextProp; + ] = processAttributeValue( + nextProp, + attributeConfig, + propKey, + validAttributes, + ); } } else if ( typeof attributeConfig.diff === 'function' || typeof attributeConfig.process === 'function' ) { // case: CustomAttributeConfiguration + // A custom `diff` does not know conditional values. const shouldUpdate = prevProp === undefined || - (typeof attributeConfig.diff === 'function' + (!isStyleConditionValue(prevProp, validAttributes) && + !isStyleConditionValue(nextProp, validAttributes) && + typeof attributeConfig.diff === 'function' ? attributeConfig.diff(prevProp, nextProp) : defaultDiffer(prevProp, nextProp)); if (shouldUpdate) { - const nextValue = - typeof attributeConfig.process === 'function' - ? attributeConfig.process(nextProp) - : nextProp; (updatePayload || (updatePayload = {} as {[key: string]: unknown}))[ propKey - ] = nextValue; + ] = processAttributeValue( + nextProp, + attributeConfig, + propKey, + validAttributes, + ); } } else { // default: fallthrough case when nested properties are defined @@ -440,10 +528,10 @@ function addNestedProperty( for (const propKey in props) { const prop = props[propKey]; - const attributeConfig = validAttributes[ - propKey + const attributeType = validAttributes[propKey]; + const attributeConfig = // $FlowFixMe[unclear-type] AttributeConfiguration/AnyAttributeType are defined upstream with $FlowFixMe - ] as any as AttributeConfiguration; + attributeType as any as AttributeConfiguration; if (attributeConfig == null) { continue; @@ -459,12 +547,18 @@ 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( + prop, + attributeType, + propKey, + validAttributes, + ); } } else { if (typeof prop === 'function') { @@ -472,7 +566,12 @@ function addNestedProperty( newValue = true; } else { // An atomic prop. Doesn't need to be flattened. - newValue = prop; + newValue = processAttributeValue( + prop, + attributeType, + propKey, + validAttributes, + ); } } @@ -507,11 +606,23 @@ function clearProperties( return diffProperties(updatePayload, prevProps, emptyObject, validAttributes); } +// A later plain value can replace the conditional value, so the flag can be +// set without one. Native handles that. +function markConditionalValues( + payload: null | {[key: string]: unknown}, +): null | {[key: string]: unknown} { + if (hasConditionalValues && payload != null) { + payload[HAS_CONDITIONAL_VALUES_KEY] = true; + } + return payload; +} + export function create( props: NestedNode, validAttributes: AttributeConfiguration, ): null | {[key: string]: unknown} { - return addNestedProperty(null, props, validAttributes); + hasConditionalValues = false; + return markConditionalValues(addNestedProperty(null, props, validAttributes)); } export function diff( @@ -519,10 +630,13 @@ export function diff( nextProps: {[key: string]: unknown}, validAttributes: AttributeConfiguration, ): null | {[key: string]: unknown} { - return diffProperties( - null, // updatePayload - prevProps, - nextProps, - validAttributes, + hasConditionalValues = false; + return markConditionalValues( + diffProperties( + null, // updatePayload + prevProps, + nextProps, + validAttributes, + ), ); } diff --git a/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/__tests__/ReactNativeAttributePayload-itest.js b/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/__tests__/ReactNativeAttributePayload-itest.js index 7bfa795d77a4..c16686df5715 100644 --- a/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/__tests__/ReactNativeAttributePayload-itest.js +++ b/packages/react-native/Libraries/ReactNative/ReactFabricPublicInstance/__tests__/ReactNativeAttributePayload-itest.js @@ -12,6 +12,9 @@ import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; import type {AttributeConfiguration} from '../../../Renderer/shims/ReactNativeTypes'; +import ReactNativeStyleAttributes from '../../../Components/View/ReactNativeStyleAttributes'; +import processColor from '../../../StyleSheet/processColor'; + const {create, diff} = require('../ReactNativeAttributePayload'); describe('ReactNativeAttributePayload.create', () => { @@ -493,3 +496,338 @@ describe('ReactNativeAttributePayload.diff', () => { expect(process).toBeCalled(); }); }); + +describe('ReactNativeAttributePayload with conditional style values', () => { + const DARK = '@media (prefers-color-scheme: dark)'; + const validAttributes: AttributeConfiguration = { + style: ReactNativeStyleAttributes, + }; + const white = processColor('white'); + const black = processColor('black'); + const red = processColor('red'); + const conditional = {default: 'white', [DARK]: 'black'}; + // A conditional value, as native gets it. + const sent = (defaultValue: unknown, value: unknown) => ({ + $conditionalValue: { + default: defaultValue, + conditions: [{query: {colorScheme: 'dark'}, value}], + }, + }); + const whiteOrBlack = sent(white, black); + const flag = {$hasConditionalValues: true}; + + it('create: sends the default and the processed conditions', () => { + expect( + create( + {style: {width: 100, backgroundColor: conditional}}, + validAttributes, + ), + ).toEqual({width: 100, backgroundColor: whiteOrBlack, ...flag}); + }); + + it('create: a later plain value replaces the conditions', () => { + // A later plain value wins. The flag stays, and native handles that. + expect( + create( + {style: [{backgroundColor: conditional}, {backgroundColor: 'red'}]}, + validAttributes, + ), + ).toEqual({backgroundColor: red, ...flag}); + }); + + it('create: leaves the value as it is if the style does not allow conditions', () => { + const value = {default: 1, [DARK]: 0.5}; + expect(create({style: {opacity: value}}, {style: {opacity: true}})).toEqual( + {opacity: value}, + ); + }); + + it('diff: sends nothing when the value is the same', () => { + expect( + diff( + {style: [{backgroundColor: {default: 'white', [DARK]: 'black'}}]}, + {style: [{backgroundColor: {default: 'white', [DARK]: 'black'}}]}, + validAttributes, + ), + ).toEqual(null); + }); + + it('diff: sends the default and the conditions when a condition changes', () => { + expect( + diff( + {style: {width: 100, backgroundColor: conditional}}, + { + style: { + width: 100, + backgroundColor: {default: 'white', [DARK]: 'red'}, + }, + }, + validAttributes, + ), + ).toEqual({backgroundColor: sent(white, red), ...flag}); + }); + + it('diff: sends the plain value when the value stops being conditional', () => { + expect( + diff( + {style: {backgroundColor: conditional}}, + {style: {backgroundColor: 'white'}}, + validAttributes, + ), + ).toEqual({backgroundColor: white}); + }); + + it('diff: sends the default and the conditions when a value becomes conditional', () => { + expect( + diff( + {style: [{width: 100}, {backgroundColor: 'white'}]}, + {style: [{width: 100}, {backgroundColor: conditional}]}, + validAttributes, + ), + ).toEqual({backgroundColor: whiteOrBlack, ...flag}); + }); + + it('diff: clears the value when the style is removed', () => { + expect( + diff({style: {backgroundColor: conditional}}, {}, validAttributes), + ).toEqual({backgroundColor: null}); + }); + + it('diff: a plain value added later in the array replaces the conditions', () => { + const base = {backgroundColor: conditional}; + expect( + diff( + {style: [base]}, + {style: [base, {backgroundColor: 'red'}]}, + validAttributes, + ), + ).toEqual({backgroundColor: red}); + }); + + it('diff: removing a later plain value restores the earlier conditions', () => { + const base = {backgroundColor: conditional}; + expect( + diff( + {style: [base, {backgroundColor: 'red'}]}, + {style: [base]}, + validAttributes, + ), + ).toEqual({backgroundColor: whiteOrBlack, ...flag}); + }); + + it('diff: an earlier change does not hide a later conditional value', () => { + const base = {backgroundColor: conditional}; + expect( + diff( + {style: [{backgroundColor: 'red'}, base]}, + {style: [{backgroundColor: 'blue'}, base]}, + validAttributes, + ), + ).toEqual({backgroundColor: whiteOrBlack, ...flag}); + }); + + it('diff: compares conditional values deeply for attributes with a custom diff', () => { + expect( + diff( + { + style: { + shadowOffset: { + default: {width: 1, height: 1}, + [DARK]: {width: 2, height: 2}, + }, + }, + }, + { + style: { + shadowOffset: { + default: {width: 1, height: 1}, + [DARK]: {width: 3, height: 3}, + }, + }, + }, + validAttributes, + ), + ).toEqual({ + shadowOffset: sent({width: 1, height: 1}, {width: 3, height: 3}), + ...flag, + }); + }); + + it('never sends undefined for a conditional value', () => { + const plain = {backgroundColor: 'red'}; + // A later plain value wins. The flag stays, and native handles that. + expect( + diff( + {style: [{backgroundColor: 'blue'}, plain]}, + { + style: [ + {backgroundColor: {default: 'notacolor', [DARK]: 'white'}}, + plain, + ], + }, + validAttributes, + ), + ).toEqual({backgroundColor: red, ...flag}); + }); + + it('diff: a changed later plain value replaces earlier conditions', () => { + // A later plain value wins. The flag stays, and native handles that. + expect( + diff( + {style: [{backgroundColor: 'blue'}, {backgroundColor: 'red'}]}, + {style: [{backgroundColor: conditional}, {backgroundColor: 'green'}]}, + validAttributes, + ), + ).toEqual({backgroundColor: processColor('green'), ...flag}); + }); + + it('create: a user style key cannot set the native keys', () => { + expect( + create( + { + style: { + backgroundColor: 'red', + $hasConditionalValues: true, + $conditionalValue: {default: 1}, + }, + }, + validAttributes, + ), + ).toEqual({backgroundColor: red}); + }); + + it('create: leaves a non-style prop with a default key as it is', () => { + const value = {default: 1}; + expect( + create( + {config: value, style: {opacity: 1}}, + {config: true, style: ReactNativeStyleAttributes}, + ), + ).toEqual({config: value, opacity: 1}); + }); + + it('create: sends null for an invalid default', () => { + expect( + create( + {style: {backgroundColor: {default: 'notacolor', [DARK]: 'black'}}}, + validAttributes, + ), + ).toEqual({backgroundColor: sent(null, black), ...flag}); + }); + + it('create: sends null for a value without a default', () => { + const errors: Array = []; + const originalError = console.error; + // $FlowExpectedError[cannot-write] + console.error = (message: unknown) => { + errors.push(message); + }; + try { + expect( + create( + {style: {width: 100, backgroundColor: {[DARK]: 'black'}}}, + validAttributes, + ), + ).toEqual({width: 100, backgroundColor: null}); + } finally { + // $FlowExpectedError[cannot-write] + console.error = originalError; + } + expect(errors.length).toBe(1); + }); + + it('create: sends a default without conditions as a plain value', () => { + expect( + create({style: {backgroundColor: {default: 'white'}}}, validAttributes), + ).toEqual({backgroundColor: white}); + }); + + it('create: keeps null values as null', () => { + expect( + create( + {style: {backgroundColor: {default: null, [DARK]: null}}}, + validAttributes, + ), + ).toEqual({backgroundColor: sent(null, null), ...flag}); + }); + + it('create: sends raw values for a prop without a processor, and each key', () => { + expect( + create( + { + style: { + opacity: {default: 1, [DARK]: 0.5}, + backgroundColor: conditional, + }, + }, + validAttributes, + ), + ).toEqual({ + opacity: sent(1, 0.5), + backgroundColor: whiteOrBlack, + ...flag, + }); + }); + + it('create: finds conditional values in nested arrays', () => { + expect( + create( + {style: [{width: 1}, [null, [{backgroundColor: conditional}]]]}, + validAttributes, + ), + ).toEqual({width: 1, backgroundColor: whiteOrBlack, ...flag}); + }); + + it('create: a later explicit undefined clears the value and its conditions', () => { + // A later plain value wins. The flag stays, and native handles that. + expect( + create( + {style: [{backgroundColor: conditional}, {backgroundColor: undefined}]}, + validAttributes, + ), + ).toEqual({backgroundColor: null, ...flag}); + }); + + it('diff: handles a style that changes between an array and an object', () => { + expect( + diff( + {style: [{backgroundColor: conditional}]}, + {style: {backgroundColor: {default: 'white', [DARK]: 'black'}}}, + validAttributes, + ), + ).toEqual(null); + expect( + diff( + {style: {backgroundColor: conditional}}, + {style: [{backgroundColor: conditional}, {backgroundColor: 'red'}]}, + validAttributes, + ), + ).toEqual({backgroundColor: red}); + expect( + diff( + {style: [{width: 1}, {backgroundColor: 'red'}]}, + {style: {width: 1, backgroundColor: conditional}}, + validAttributes, + ), + ).toEqual({backgroundColor: whiteOrBlack, ...flag}); + }); + + it('does not carry the flag over to the next payload', () => { + create({style: {backgroundColor: conditional}}, validAttributes); + expect(create({style: {backgroundColor: 'red'}}, validAttributes)).toEqual({ + backgroundColor: red, + }); + diff( + {style: {backgroundColor: 'red'}}, + {style: {backgroundColor: conditional}}, + validAttributes, + ); + expect( + diff( + {style: {backgroundColor: 'red'}}, + {style: {backgroundColor: 'blue'}}, + validAttributes, + ), + ).toEqual({backgroundColor: processColor('blue')}); + }); +}); diff --git a/packages/react-native/Libraries/StyleSheet/__tests__/ConditionalValues-itest.js b/packages/react-native/Libraries/StyleSheet/__tests__/ConditionalValues-itest.js new file mode 100644 index 000000000000..33fb7dc383b4 --- /dev/null +++ b/packages/react-native/Libraries/StyleSheet/__tests__/ConditionalValues-itest.js @@ -0,0 +1,575 @@ +/** + * 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 + * @fantom_flags enableCppPropsIteratorSetter:* useSharedAnimatedBackend:* + * @format + */ + +import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; + +import type {ViewStyleProp} from '../StyleSheet'; +import type {HostInstance} from 'react-native'; + +import * as Fantom from '@react-native/fantom'; +import nullthrows from 'nullthrows'; +import * as React from 'react'; +import {createRef} from 'react'; +import {Animated, Text, View, useAnimatedValue} from 'react-native'; + +const DARK = '@media (prefers-color-scheme: dark)'; +const LIGHT = '@media (prefers-color-scheme: light)'; + +const WHITE = 'rgba(255, 255, 255, 1)'; +const BLACK = 'rgba(0, 0, 0, 1)'; +const NAVY = 'rgba(0, 0, 128, 1)'; +const RED = 'rgba(255, 0, 0, 1)'; + +// Conditional values are not in the style types yet. +function conditional( + defaultValue: unknown, + query: string, + value: unknown, +): $FlowFixMe { + const result: {[key: string]: unknown} = {default: defaultValue}; + result[query] = value; + return result; +} + +const whiteOrBlack = conditional('white', DARK, 'black'); + +function render(root: Fantom.Root, element: React.MixedElement) { + Fantom.runTask(() => { + root.render(element); + }); +} + +function output(root: Fantom.Root): React.Node { + return root + .getRenderedOutput({props: ['backgroundColor', 'opacity']}) + .toJSX(); +} + +describe('conditional values', () => { + afterEach(() => { + Fantom.setColorScheme('light'); + }); + + it('renders the default in light mode', () => { + const root = Fantom.createRoot(); + render(root, ); + expect(output(root)).toEqual(); + }); + + it('renders the matching value in dark mode', () => { + Fantom.setColorScheme('dark'); + const root = Fantom.createRoot(); + render(root, ); + expect(output(root)).toEqual(); + }); + + it('renders the default when no condition matches', () => { + Fantom.setColorScheme('dark'); + const root = Fantom.createRoot(); + render( + root, + , + ); + expect(output(root)).toEqual(); + }); + + it('a later plain value in the style array wins', () => { + Fantom.setColorScheme('dark'); + const root = Fantom.createRoot(); + // The payload keeps the flag without a conditional value. + render( + root, + , + ); + expect(output(root)).toEqual(); + }); + + it('keeps the matching value when another prop changes', () => { + Fantom.setColorScheme('dark'); + const root = Fantom.createRoot(); + render(root, ); + render( + root, + , + ); + expect(output(root)).toEqual( + , + ); + }); + + it('updates the value when a condition changes', () => { + Fantom.setColorScheme('dark'); + const root = Fantom.createRoot(); + render(root, ); + render( + root, + , + ); + expect(output(root)).toEqual(); + }); + + it('keeps a condition when another prop becomes conditional', () => { + Fantom.setColorScheme('dark'); + const root = Fantom.createRoot(); + render(root, ); + render( + root, + , + ); + // A later update keeps both conditions. + render( + root, + , + ); + expect(output(root)).toEqual( + , + ); + }); + + it('removes the condition when the value becomes plain', () => { + Fantom.setColorScheme('dark'); + const root = Fantom.createRoot(); + render(root, ); + render(root, ); + expect(output(root)).toEqual(); + + // The removed condition does not come back on a later update. + render(root, ); + expect(output(root)).toEqual( + , + ); + }); + + it('resets the value when the style is removed', () => { + Fantom.setColorScheme('dark'); + const root = Fantom.createRoot(); + render(root, ); + render(root, ); + expect(output(root)).toEqual(); + }); + + it('updates rendered views when the color scheme changes', () => { + const root = Fantom.createRoot(); + render(root, ); + expect(output(root)).toEqual(); + + Fantom.setColorScheme('dark'); + expect(output(root)).toEqual(); + + Fantom.setColorScheme('light'); + expect(output(root)).toEqual(); + }); + + it('updates the layout when the color scheme changes', () => { + const root = Fantom.createRoot(); + const ref = createRef(); + render( + root, + , + ); + const width = () => nullthrows(ref.current).getBoundingClientRect().width; + expect(width()).toBe(100); + + Fantom.setColorScheme('dark'); + expect(width()).toBe(200); + }); + + it('keeps the conditional value after a native animation', () => { + const root = Fantom.createRoot(); + let opacity; + function App({testID}: {testID: string}) { + opacity = useAnimatedValue(1); + return ( + + ); + } + render(root, ); + + Fantom.runTask(() => { + Animated.timing(nullthrows(opacity), { + toValue: 0.5, + duration: 100, + useNativeDriver: true, + }).start(); + }); + Fantom.unstable_produceFramesForDuration(200); + Fantom.runWorkLoop(); + expect(output(root)).toEqual( + , + ); + + Fantom.setColorScheme('dark'); + expect(output(root)).toEqual( + , + ); + + render(root, ); + expect(output(root)).toEqual( + , + ); + }); + + it('keeps the updated value when React updates another view', () => { + const root = Fantom.createRoot(); + const renderWithOpacity = (opacity: number) => + render( + root, + + + + , + ); + renderWithOpacity(1); + + // React still has the views from before this change. + Fantom.setColorScheme('dark'); + renderWithOpacity(0.5); + expect(output(root)).toEqual( + + + + , + ); + }); + + it('keeps the updated value after two React updates of another view', () => { + const root = Fantom.createRoot(); + const renderWithOpacity = (opacity: number) => + render( + root, + + + + , + ); + renderWithOpacity(1); + + Fantom.setColorScheme('dark'); + // Only the first React commit after the change resolves the values again. + renderWithOpacity(0.5); + renderWithOpacity(0.25); + expect(output(root)).toEqual( + + + + , + ); + }); + + it('updates only the views with conditional values, on each surface', () => { + const first = Fantom.createRoot(); + render( + first, + + + + , + ); + const second = Fantom.createRoot(); + render( + second, + , + ); + first.takeMountingManagerLogs(); + second.takeMountingManagerLogs(); + + Fantom.setColorScheme('dark'); + expect(first.takeMountingManagerLogs()).toEqual([ + 'Update {type: "View", nativeID: "A"}', + ]); + expect(second.takeMountingManagerLogs()).toEqual([ + 'Update {type: "View", nativeID: "C"}', + ]); + expect(output(first)).toEqual( + + + + , + ); + expect(output(second)).toEqual(); + }); + + it('makes no native updates without conditional values', () => { + const root = Fantom.createRoot(); + render(root, ); + root.takeMountingManagerLogs(); + + Fantom.setColorScheme('dark'); + expect(root.takeMountingManagerLogs()).toEqual([]); + + render(root, ); + root.takeMountingManagerLogs(); + // The same color scheme again. + Fantom.setColorScheme('dark'); + expect(root.takeMountingManagerLogs()).toEqual([]); + }); + + // Black is not in the output of text: it is the default text color. + it('updates the color of a text when the color scheme changes', () => { + const root = Fantom.createRoot(); + render( + root, + hello, + ); + const textOutput = () => + root.getRenderedOutput({props: ['foregroundColor']}).toJSX(); + expect(textOutput()).toEqual( + hello, + ); + + Fantom.setColorScheme('dark'); + expect(textOutput()).toEqual( + hello, + ); + }); + + it('updates the color of a nested text when the color scheme changes', () => { + const root = Fantom.createRoot(); + render( + root, + + hello{' '} + world + , + ); + const expected = (innerColor: string) => ({ + type: 'Paragraph', + props: {foregroundColor: 'rgba(0, 0, 0, 0)'}, + children: [ + 'hello ', + {type: 'Text', props: {foregroundColor: innerColor}, children: 'world'}, + ], + }); + const nestedOutput = () => + root.getRenderedOutput({props: ['foregroundColor']}).toJSON(); + expect(nestedOutput()).toEqual(expected(WHITE)); + + Fantom.setColorScheme('dark'); + expect(nestedOutput()).toEqual(expected(NAVY)); + }); + + it('keeps the updated value after a React update', () => { + const root = Fantom.createRoot(); + render(root, ); + + Fantom.setColorScheme('dark'); + render( + root, + , + ); + expect(output(root)).toEqual( + , + ); + }); + + it('a changed conditional value uses the current color scheme', () => { + const root = Fantom.createRoot(); + render(root, ); + expect(output(root)).toEqual(); + + Fantom.setColorScheme('dark'); + render( + root, + , + ); + expect(output(root)).toEqual(); + }); + + it('resolves conditions set with setNativeProps', () => { + Fantom.setColorScheme('dark'); + const root = Fantom.createRoot(); + const ref = createRef(); + const childRef = createRef(); + const renderWithChild = (opacity: number) => + render( + root, + + + , + ); + renderWithChild(1); + + Fantom.runTask(() => { + nullthrows(ref.current).setNativeProps({ + style: {backgroundColor: whiteOrBlack}, + }); + }); + expect(output(root)).toEqual( + + + , + ); + + // A React update of the view merges the `setNativeProps` props into it. + renderWithChild(0.5); + expect(output(root)).toEqual( + + + , + ); + + // A change of the child clones the view without new props. That clone + // applies the `setNativeProps` props again, with an empty + // `ContextContainer`. + Fantom.runTask(() => { + nullthrows(childRef.current).setNativeProps({style: {opacity: 0.25}}); + }); + expect(output(root)).toEqual( + + + , + ); + }); + + describe('with setNativeProps', () => { + let root: Fantom.Root; + const ref = createRef(); + const childRef = createRef(); + + function renderView(style: ViewStyleProp) { + render( + root, + + + , + ); + } + + function setNativeStyle(style: {...}) { + Fantom.runTask(() => { + nullthrows(ref.current).setNativeProps({style}); + }); + } + + // Clones the view without new props, which applies the `setNativeProps` + // props again. + function changeChild() { + Fantom.runTask(() => { + nullthrows(childRef.current).setNativeProps({style: {opacity: 0.25}}); + }); + } + + function parentOutput(): React.Node { + return root + .getRenderedOutput({props: ['backgroundColor', 'opacity']}) + .toJSX(); + } + + beforeEach(() => { + Fantom.setColorScheme('dark'); + root = Fantom.createRoot(); + renderView({opacity: 1}); + }); + + it('keeps the conditions of earlier calls', () => { + setNativeStyle({backgroundColor: whiteOrBlack}); + setNativeStyle({opacity: conditional(1, DARK, 0.5)}); + changeChild(); + expect(parentOutput()).toEqual( + + + , + ); + }); + + it('a later plain value removes the condition', () => { + setNativeStyle({backgroundColor: whiteOrBlack}); + setNativeStyle({backgroundColor: 'red'}); + changeChild(); + expect(parentOutput()).toEqual( + + + , + ); + }); + + it('keeps the condition when React adds another condition', () => { + setNativeStyle({backgroundColor: whiteOrBlack}); + renderView({opacity: conditional(1, DARK, 0.5)}); + expect(parentOutput()).toEqual( + + + , + ); + changeChild(); + expect(parentOutput()).toEqual( + + + , + ); + }); + + it('keeps a condition from React over a plain native value', () => { + // Like a JS-driven animation, which uses `setNativeProps`. + setNativeStyle({backgroundColor: 'red'}); + renderView({opacity: 1, backgroundColor: whiteOrBlack}); + changeChild(); + expect(parentOutput()).toEqual( + + + , + ); + }); + + it('a plain value from React replaces the condition', () => { + setNativeStyle({backgroundColor: whiteOrBlack}); + renderView({opacity: 1, backgroundColor: 'red'}); + changeChild(); + expect(parentOutput()).toEqual( + + + , + ); + }); + + it('updates a native condition when the color scheme changes', () => { + setNativeStyle({backgroundColor: whiteOrBlack}); + Fantom.setColorScheme('light'); + expect(parentOutput()).toEqual( + + + , + ); + // React and the clone apply the `setNativeProps` props again. + renderView({opacity: 0.5}); + expect(parentOutput()).toEqual( + + + , + ); + changeChild(); + expect(parentOutput()).toEqual( + + + , + ); + }); + }); +}); diff --git a/packages/react-native/Libraries/StyleSheet/__tests__/ConditionalValuesReferences-itest.js b/packages/react-native/Libraries/StyleSheet/__tests__/ConditionalValuesReferences-itest.js new file mode 100644 index 000000000000..35d0bece1cb0 --- /dev/null +++ b/packages/react-native/Libraries/StyleSheet/__tests__/ConditionalValuesReferences-itest.js @@ -0,0 +1,61 @@ +/** + * 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 + * @fantom_flags updateRuntimeShadowNodeReferencesOnCommit:* updateRuntimeShadowNodeReferencesOnCommitThread:* + * @format + */ + +import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; + +import * as Fantom from '@react-native/fantom'; +import * as React from 'react'; +import {View} from 'react-native'; + +// Conditional values are not in the style types yet. +const whiteOrBlack: $FlowFixMe = { + default: 'white', + '@media (prefers-color-scheme: dark)': 'black', +}; + +describe('conditional values and the shadow node references of React', () => { + afterEach(() => { + Fantom.setColorScheme('light'); + }); + + it('updates a conditional view only in the first React update after a change', () => { + const root = Fantom.createRoot(); + const renderWithOpacity = (opacity: number) => + Fantom.runTask(() => { + root.render( + + + + , + ); + }); + renderWithOpacity(1); + root.takeMountingManagerLogs(); + + Fantom.setColorScheme('dark'); + expect(root.takeMountingManagerLogs()).toEqual([ + 'Update {type: "View", nativeID: "A"}', + ]); + + // React still holds the view from before the change, so this update + // resolves it again. + renderWithOpacity(0.5); + expect(root.takeMountingManagerLogs()).toEqual([ + 'Update {type: "View", nativeID: "A"}', + 'Update {type: "View", nativeID: "B"}', + ]); + + renderWithOpacity(0.25); + expect(root.takeMountingManagerLogs()).toEqual([ + 'Update {type: "View", nativeID: "B"}', + ]); + }); +}); diff --git a/packages/react-native/Libraries/StyleSheet/__tests__/processStyleConditions-test.js b/packages/react-native/Libraries/StyleSheet/__tests__/processStyleConditions-test.js new file mode 100644 index 000000000000..9cfd778a4a8c --- /dev/null +++ b/packages/react-native/Libraries/StyleSheet/__tests__/processStyleConditions-test.js @@ -0,0 +1,161 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import { + compileConditionalValue, + isConditionalValue, + parseMediaQuery, +} from '../processStyleConditions'; + +const DARK = '@media (prefers-color-scheme: dark)'; +const LIGHT = '@media (prefers-color-scheme: light)'; + +describe('parseMediaQuery', () => { + it('parses both color schemes', () => { + expect(parseMediaQuery(DARK)).toEqual({colorScheme: 'dark'}); + expect(parseMediaQuery(LIGHT)).toEqual({colorScheme: 'light'}); + }); + + it('ignores case and extra whitespace', () => { + expect(parseMediaQuery('@MEDIA (Prefers-Color-Scheme: DARK)')).toEqual({ + colorScheme: 'dark', + }); + expect( + parseMediaQuery(' @media( prefers-color-scheme : dark ) '), + ).toEqual({colorScheme: 'dark'}); + }); + + it('requires @media', () => { + expect(parseMediaQuery('(prefers-color-scheme: dark)')).toBe(null); + expect(parseMediaQuery('@mediax (prefers-color-scheme: dark)')).toBe(null); + }); + + it('rejects other values and features', () => { + expect(parseMediaQuery('@media (prefers-color-scheme: blue)')).toBe(null); + expect(parseMediaQuery('@media (prefers-color-scheme: )')).toBe(null); + expect(parseMediaQuery('@media (orientation: landscape)')).toBe(null); + expect(parseMediaQuery('@media (min-width: 600px)')).toBe(null); + }); + + it('rejects media types, not, and and', () => { + expect( + parseMediaQuery('@media screen and (prefers-color-scheme: dark)'), + ).toBe(null); + expect(parseMediaQuery('@media not (prefers-color-scheme: dark)')).toBe( + null, + ); + expect(parseMediaQuery(`${DARK} and (prefers-color-scheme: dark)`)).toBe( + null, + ); + }); + + it('rejects invalid syntax', () => { + expect(parseMediaQuery('')).toBe(null); + expect(parseMediaQuery('@media')).toBe(null); + expect(parseMediaQuery('@media prefers-color-scheme: dark')).toBe(null); + }); +}); + +describe('compileConditionalValue', () => { + let consoleError; + beforeEach(() => { + consoleError = jest.spyOn(console, 'error').mockImplementation(() => {}); + }); + afterEach(() => { + consoleError.mockRestore(); + }); + + it('splits the default from the conditions', () => { + expect( + compileConditionalValue( + {default: 'white', [DARK]: 'black'}, + 'backgroundColor', + ), + ).toEqual({ + default: 'white', + conditions: [{query: {colorScheme: 'dark'}, value: 'black'}], + }); + expect(consoleError).not.toHaveBeenCalled(); + }); + + it('keeps the written order', () => { + expect( + compileConditionalValue( + {default: 1, [LIGHT]: 0.8, [DARK]: 0.5}, + 'opacity', + ), + ).toEqual({ + default: 1, + conditions: [ + {query: {colorScheme: 'light'}, value: 0.8}, + {query: {colorScheme: 'dark'}, value: 0.5}, + ], + }); + }); + + it('allows a null default', () => { + expect( + compileConditionalValue({default: null, [DARK]: 'black'}, 'color'), + ).toEqual({ + default: null, + conditions: [{query: {colorScheme: 'dark'}, value: 'black'}], + }); + }); + + it('allows a default without conditions', () => { + expect(compileConditionalValue({default: 1}, 'opacity')).toEqual({ + default: 1, + conditions: [], + }); + expect(consoleError).not.toHaveBeenCalled(); + }); + + it('skips unsupported keys and keeps the rest', () => { + expect( + compileConditionalValue( + {default: 1, '@media (orientation: landscape)': 0.2, [DARK]: 0.5}, + 'opacity', + ), + ).toEqual({ + default: 1, + conditions: [{query: {colorScheme: 'dark'}, value: 0.5}], + }); + expect(consoleError).toHaveBeenCalledTimes(1); + expect(consoleError).toHaveBeenCalledWith( + expect.stringContaining('"@media (orientation: landscape)"'), + ); + }); + + it('rejects a value without a default', () => { + expect(compileConditionalValue({[DARK]: 'black'}, 'color')).toBe(null); + expect( + compileConditionalValue({default: undefined, [DARK]: 'black'}, 'color'), + ).toBe(null); + expect(consoleError).toHaveBeenCalledWith( + expect.stringContaining("needs a 'default' key"), + ); + }); +}); + +describe('isConditionalValue', () => { + it('detects objects with a default or an @media key', () => { + expect(isConditionalValue({default: 'white', [DARK]: 'black'})).toBe(true); + expect(isConditionalValue({default: 'white'})).toBe(true); + expect(isConditionalValue({[DARK]: 'black'})).toBe(true); + }); + + it('ignores other values', () => { + expect(isConditionalValue(100)).toBe(false); + expect(isConditionalValue('red')).toBe(false); + expect(isConditionalValue(null)).toBe(false); + expect(isConditionalValue([{translateX: 10}])).toBe(false); + expect(isConditionalValue({width: 1, height: 2})).toBe(false); + }); +}); diff --git a/packages/react-native/Libraries/StyleSheet/processStyleConditions.js b/packages/react-native/Libraries/StyleSheet/processStyleConditions.js new file mode 100644 index 000000000000..69b066775a2d --- /dev/null +++ b/packages/react-native/Libraries/StyleSheet/processStyleConditions.js @@ -0,0 +1,91 @@ +/** + * 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 + */ + +export type MediaQuery = Readonly<{ + colorScheme: 'light' | 'dark', +}>; + +export type StyleCondition = Readonly<{ + query: MediaQuery, + value: unknown, +}>; + +export type CompiledConditionalValue = Readonly<{ + default: unknown, + conditions: ReadonlyArray, +}>; + +export type StyleObject = {readonly [key: string]: unknown}; + +const MEDIA_QUERY_REGEX = + /^@media\s*\(\s*prefers-color-scheme\s*:\s*([a-z]+)\s*\)$/i; +const MEDIA_KEY_REGEX = /^@media\b/i; + +export function parseMediaQuery(key: string): MediaQuery | null { + const match = MEDIA_QUERY_REGEX.exec(key.trim()); + if (match == null) { + return null; + } + const colorScheme = match[1].toLowerCase(); + if (colorScheme !== 'light' && colorScheme !== 'dark') { + return null; + } + return {colorScheme}; +} + +export function compileConditionalValue( + value: StyleObject, + property: string, +): CompiledConditionalValue | null { + if (value.default === undefined) { + if (__DEV__) { + console.error( + `StyleSheet: the conditional value of "${property}" needs a ` + + "'default' key. Use `default: null` for no value.", + ); + } + return null; + } + + const conditions: Array = []; + for (const key in value) { + if (key === 'default') { + continue; + } + const query = parseMediaQuery(key); + if (query == null) { + if (__DEV__) { + console.error( + `StyleSheet: "${key}" in the conditional value of "${property}" ` + + 'is not a supported media query. It is ignored.', + ); + } + continue; + } + conditions.push({query, value: value[key]}); + } + + return {default: value.default, conditions}; +} + +// Looks like a conditional value. `compileConditionalValue` checks the rules. +export function isConditionalValue( + value: unknown, +): implies value is StyleObject { + if (typeof value !== 'object' || value == null || Array.isArray(value)) { + return false; + } + for (const key in value as StyleObject) { + if (key === 'default' || MEDIA_KEY_REGEX.test(key)) { + return true; + } + } + return false; +} diff --git a/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h b/packages/react-native/ReactCommon/react/renderer/core/ConcreteComponentDescriptor.h index e11bf20fb3a1..22885896d3a6 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); } + // Use the descriptor's container: when `ShadowNode::clone` applies the + // `setNativeProps` props again, `context` has an empty one. + auto conditionalValues = resolveConditionalValues(props.get(), rawProps, contextContainer_.get()); + auto &resolvedRawProps = conditionalValues ? conditionalValues->rawProps : rawProps; + // Two construction paths: // - Iterator-setter (only available when `ConcreteProps` satisfies // `HasIteratorSetterCtor` AND the runtime flag is on): copy-construct @@ -146,8 +152,11 @@ 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 (conditionalValues) { + shadowNodeProps->conditionalValues = std::move(conditionalValues->conditionalValues); } #ifdef RN_SERIALIZABLE_STATE @@ -166,13 +175,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/ConditionalValues.cpp b/packages/react-native/ReactCommon/react/renderer/core/ConditionalValues.cpp new file mode 100644 index 000000000000..a0fe8ec2b882 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/ConditionalValues.cpp @@ -0,0 +1,185 @@ +/* + * 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 "ConditionalValues.h" + +namespace facebook::react { + +namespace { + +std::optional getMediaFeature(const folly::dynamic& name) { + if (name == "colorScheme") { + return MediaFeature::ColorScheme; + } + return std::nullopt; +} + +bool matchesColorScheme(const folly::dynamic& value, ColorScheme colorScheme) { + if (!value.isString()) { + return false; + } + const auto& name = value.getString(); + return (name == "light" && colorScheme == ColorScheme::Light) || + (name == "dark" && colorScheme == ColorScheme::Dark); +} + +bool matchesQuery(const folly::dynamic& query, const MediaFeatures& features) { + if (!query.isObject() || query.empty()) { + return false; + } + for (const auto& [name, value] : query.items()) { + auto feature = getMediaFeature(name); + if (!feature) { + return false; + } + switch (*feature) { + case MediaFeature::ColorScheme: + if (!matchesColorScheme(value, features.colorScheme)) { + return false; + } + break; + } + } + return true; +} + +} // namespace + +folly::dynamic resolveConditionalValue( + const folly::dynamic& conditionalValue, + const MediaFeatures& features) { + if (!conditionalValue.isObject()) { + return nullptr; + } + + const auto* result = 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* query = condition.get_ptr("query"); + const auto* value = condition.get_ptr("value"); + if (query != nullptr && value != nullptr && + matchesQuery(*query, features)) { + result = value; + } + } + } + + return result != nullptr ? *result : nullptr; +} + +MediaFeatureSet getMediaFeatureDependencies( + const folly::dynamic& conditionalValue) { + const auto* conditions = conditionalValue.isObject() + ? conditionalValue.get_ptr("conditions") + : nullptr; + if (conditions == nullptr || !conditions->isArray()) { + return 0; + } + + MediaFeatureSet dependencies = 0; + for (const auto& condition : *conditions) { + const auto* query = + condition.isObject() ? condition.get_ptr("query") : nullptr; + if (query == nullptr || !query->isObject()) { + continue; + } + for (const auto& name : query->keys()) { + if (auto feature = getMediaFeature(name)) { + dependencies |= static_cast(*feature); + } + } + } + return dependencies; +} + +std::optional resolveConditionalValues( + const Props* sourceProps, + const RawProps& rawProps, + const ContextContainer* contextContainer) { + const auto* sourceConditionalValues = + sourceProps != nullptr ? sourceProps->conditionalValues.get() : nullptr; + + // JavaScript adds the flag to each payload with a conditional value. + if (!rawProps.hasProperty(kHasConditionalValuesPropName)) { + if (sourceConditionalValues == nullptr) { + return std::nullopt; + } + // Only a new value for a prop with a conditional value changes something. + auto isAnyReplaced = false; + for (const auto& item : sourceConditionalValues->values.items()) { + if (rawProps.hasProperty(item.first.c_str())) { + isAnyReplaced = true; + break; + } + } + if (!isAnyReplaced) { + return std::nullopt; + } + } + + auto values = rawProps.toDynamic(); + if (!values.isObject()) { + return std::nullopt; + } + values.erase(kHasConditionalValuesPropName); + + auto conditionalValues = sourceConditionalValues != nullptr + ? sourceConditionalValues->values + : folly::dynamic(folly::dynamic::object()); + std::optional features; + for (auto& item : values.items()) { + const auto* conditionalValue = item.second.isObject() + ? item.second.get_ptr(kConditionalValueKey) + : nullptr; + if (conditionalValue == nullptr) { + conditionalValues.erase(item.first); + continue; + } + if (!features) { + features = getMediaFeatures(contextContainer); + } + conditionalValues[item.first] = *conditionalValue; + item.second = resolveConditionalValue(*conditionalValue, *features); + } + + if (conditionalValues.empty()) { + return ConditionalValuesResolution{ + .rawProps = RawProps(std::move(values)), .conditionalValues = nullptr}; + } + + auto result = std::make_shared(); + if (features) { + // All values of the props must be resolved for the same media features. + if (sourceConditionalValues != nullptr && + sourceConditionalValues->isOutdatedFor(*features)) { + for (const auto& item : conditionalValues.items()) { + if (values.count(item.first) == 0) { + values[item.first] = resolveConditionalValue(item.second, *features); + } + } + } + result->resolvedFor = *features; + } else { + // Only stored values are left, so `sourceConditionalValues` is not null. + result->resolvedFor = sourceConditionalValues->resolvedFor; + } + for (const auto& item : conditionalValues.items()) { + result->dependencies |= getMediaFeatureDependencies(item.second); + } + result->values = std::move(conditionalValues); + + return ConditionalValuesResolution{ + .rawProps = RawProps(std::move(values)), + .conditionalValues = std::move(result)}; +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/ConditionalValues.h b/packages/react-native/ReactCommon/react/renderer/core/ConditionalValues.h new file mode 100644 index 000000000000..8b9e69338c12 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/ConditionalValues.h @@ -0,0 +1,91 @@ +/* + * 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 { + +/* + * Returns the value of the last condition in `conditionalValue` that matches + * `features`, or its default if none matches. Returns null for an invalid + * value. The format, with processed values: + * + * { + * "default": , + * "conditions": [{"query": {"colorScheme": "dark"}, "value": }] + * } + */ +folly::dynamic resolveConditionalValue(const folly::dynamic &conditionalValue, const MediaFeatures &features); + +MediaFeatureSet getMediaFeatureDependencies(const folly::dynamic &conditionalValue); + +struct ConditionalValues { + /* + * The conditional values by prop name, in the format of + * `resolveConditionalValue`. + */ + folly::dynamic values; + + /* + * The media features that the queries of `values` read. + */ + MediaFeatureSet dependencies{0}; + + MediaFeatures resolvedFor; + + bool isOutdatedFor(const MediaFeatures &features) const + { + return (resolvedFor.differences(features) & dependencies) != 0; + } +}; + +/* + * JavaScript sends a conditional value under its own prop, wrapped in this key: + * `{"opacity": {"$conditionalValue": {"default": 1, "conditions": [...]}}}`. + */ +inline constexpr const char *kConditionalValueKey = "$conditionalValue"; + +/* + * JavaScript adds this prop to a payload that has a conditional value, so that + * other payloads skip the search. + */ +inline constexpr const char *kHasConditionalValuesPropName = "$hasConditionalValues"; + +struct ConditionalValuesResolution { + /* + * The raw props to use instead of the given ones: each conditional value + * resolved, and no `$hasConditionalValues` prop. + */ + RawProps rawProps; + + /* + * The conditional values of the new props. Null if there are none. + */ + std::shared_ptr conditionalValues; +}; + +/* + * Resolves the conditional values in `rawProps` for the media features in + * `contextContainer`, and merges them with the ones of `sourceProps`. A plain + * value removes the conditional value of the same prop. Stored values that are + * outdated for these media features are resolved again. Returns nullopt if + * nothing changes. Does not need `parse`. + */ +std::optional +resolveConditionalValues(const Props *sourceProps, const RawProps &rawProps, const ContextContainer *contextContainer); + +} // 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..1269ca8d11d7 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/MediaFeatures.h @@ -0,0 +1,79 @@ +/* + * 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 + +namespace facebook::react { + +enum class ColorScheme : uint8_t { Light, Dark }; + +enum class MediaFeature : uint8_t { + ColorScheme = 1 << 0, +}; + +/* + * A set of `MediaFeature` bits. + */ +using MediaFeatureSet = uint8_t; + +struct MediaFeatures { + ColorScheme colorScheme{ColorScheme::Light}; + + bool operator==(const MediaFeatures &other) const = default; + + MediaFeatureSet differences(const MediaFeatures &other) const + { + MediaFeatureSet result = 0; + if (colorScheme != other.colorScheme) { + result |= static_cast(MediaFeature::ColorScheme); + } + return result; + } +}; + +/* + * The media features of one React Native instance, which are the same for all + * its surfaces. Thread-safe. + */ +class MediaFeaturesStore final { + public: + MediaFeatures get() const noexcept + { + return features_.load(); + } + + void set(MediaFeatures features) noexcept + { + features_.store(features); + } + + private: + std::atomic features_{MediaFeatures{}}; + static_assert(std::atomic::is_always_lock_free); +}; + +inline constexpr const char *kMediaFeaturesStoreKey = "MediaFeaturesStore"; + +inline MediaFeatures getMediaFeatures(const ContextContainer *contextContainer) +{ + if (contextContainer != nullptr) { + if (auto store = contextContainer->find>(kMediaFeaturesStoreKey)) { + return (*store)->get(); + } + } + return {}; +} + +} // 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..e79281bc4d2c 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Props.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/Props.cpp @@ -26,7 +26,8 @@ Props::Props( rawProps, "nativeID", sourceProps.nativeId, - {})) {} + {})), + conditionalValues(sourceProps.conditionalValues) {} 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..19f64de816d2 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/Props.h +++ b/packages/react-native/ReactCommon/react/renderer/core/Props.h @@ -23,6 +23,8 @@ namespace facebook::react { +struct ConditionalValues; + /* * Represents the most generic props object. */ @@ -61,6 +63,12 @@ class Props : public virtual Sealable, public virtual DebugStringConvertible { std::string nativeId; + /* + * The conditional values that these props were resolved from. Null if there + * are none. See `ConditionalValues.h`. + */ + std::shared_ptr conditionalValues; + #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..1752dfb00cd2 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 object has a prop with the given name. Does not need + * `parse`. + */ + 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..36983de5284f 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/ShadowNode.cpp b/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.cpp index 7c7c8ded57d3..d0395610ce45 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.cpp @@ -97,8 +97,13 @@ ShadowNode::ShadowNode( traits_.set(ShadowNodeTraits::Trait::ChildrenAreShared); + auto childrenHaveConditionalValues = false; for (const auto& child : *children_) { child->family_->setParent(family_); + childrenHaveConditionalValues |= child->subtreeHasConditionalValues(); + } + if (childrenHaveConditionalValues) { + traits_.set(ShadowNodeTraits::Trait::ChildrenHaveConditionalValues); } propagateUncullableTraitsFromChildren(); @@ -127,8 +132,15 @@ ShadowNode::ShadowNode( traits_.set(ShadowNodeTraits::Trait::ChildrenAreShared); if (fragment.children) { + auto childrenHaveConditionalValues = false; for (const auto& child : *children_) { child->family_->setParent(family_); + childrenHaveConditionalValues |= child->subtreeHasConditionalValues(); + } + if (childrenHaveConditionalValues) { + traits_.set(ShadowNodeTraits::Trait::ChildrenHaveConditionalValues); + } else { + traits_.unset(ShadowNodeTraits::Trait::ChildrenHaveConditionalValues); } propagateUncullableTraitsFromChildren(); } @@ -260,6 +272,9 @@ void ShadowNode::appendChild(const std::shared_ptr& child) { child->family_->setParent(family_); propagateUncullableTraitsFromChildren(); + if (child->subtreeHasConditionalValues()) { + traits_.set(ShadowNodeTraits::Trait::ChildrenHaveConditionalValues); + } } void ShadowNode::replaceChild( @@ -270,6 +285,9 @@ void ShadowNode::replaceChild( cloneChildrenIfShared(); newChild->family_->setParent(family_); + if (newChild->subtreeHasConditionalValues()) { + traits_.set(ShadowNodeTraits::Trait::ChildrenHaveConditionalValues); + } auto& children = const_cast>&>(*children_); @@ -325,6 +343,11 @@ void ShadowNode::propagateUncullableTraitsFromChildren() { } } +bool ShadowNode::subtreeHasConditionalValues() const { + return props_->conditionalValues != nullptr || + traits_.check(ShadowNodeTraits::Trait::ChildrenHaveConditionalValues); +} + void ShadowNode::setMounted(bool mounted) const { if (mounted) { family_->setMostRecentState(getState()); diff --git a/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h b/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h index 05c3f203ad2c..a62241c0ffd0 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNode.h @@ -142,6 +142,12 @@ class ShadowNode : public Sealable, public DebugStringConvertible, public jsi::N */ ShadowNodeTraits getTraits() const; + /* + * Whether this node or a descendant can have conditional values. False means + * that none has them. + */ + bool subtreeHasConditionalValues() const; + const Props::Shared &getProps() const; const std::vector> &getChildren() const; const SharedEventEmitter &getEventEmitter() const; diff --git a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeTraits.h b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeTraits.h index e944a35b9f2d..25770878445f 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeTraits.h +++ b/packages/react-native/ReactCommon/react/renderer/core/ShadowNodeTraits.h @@ -93,6 +93,10 @@ class ShadowNodeTraits { // **Deprecated**: This trait is deprecated and will be removed in a future // version of React Native. DirtyYogaNode = 1 << 14, + + // A descendant has conditional values. `replaceChild` can leave it set + // after the last one is removed, which only costs a walk. + ChildrenHaveConditionalValues = 1 << 15, }; /* diff --git a/packages/react-native/ReactCommon/react/renderer/core/tests/ConditionalValuesTest.cpp b/packages/react-native/ReactCommon/react/renderer/core/tests/ConditionalValuesTest.cpp new file mode 100644 index 000000000000..a3b0f8c8f1fe --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/ConditionalValuesTest.cpp @@ -0,0 +1,466 @@ +/* + * 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 +#include +#include + +#include "TestComponent.h" + +namespace facebook::react { + +namespace { + +const MediaFeatures kLight{.colorScheme = ColorScheme::Light}; +const MediaFeatures kDark{.colorScheme = ColorScheme::Dark}; + +folly::dynamic resolve(const char* json, const MediaFeatures& features) { + return resolveConditionalValue(folly::parseJson(json), features); +} + +} // namespace + +TEST(ConditionalValuesTest, resolvesTheMatchingCondition) { + auto entry = R"({ + "default": 1, + "conditions": [{"query": {"colorScheme": "dark"}, "value": 2}] + })"; + EXPECT_EQ(resolve(entry, kLight), 1); + EXPECT_EQ(resolve(entry, kDark), 2); +} + +TEST(ConditionalValuesTest, theLastMatchingConditionWins) { + auto entry = R"({ + "default": 1, + "conditions": [ + {"query": {"colorScheme": "dark"}, "value": 2}, + {"query": {"colorScheme": "light"}, "value": 3}, + {"query": {"colorScheme": "dark"}, "value": 4} + ] + })"; + EXPECT_EQ(resolve(entry, kLight), 3); + EXPECT_EQ(resolve(entry, kDark), 4); +} + +TEST(ConditionalValuesTest, keepsNullAndObjectValues) { + auto entry = R"({ + "default": null, + "conditions": [ + {"query": {"colorScheme": "dark"}, "value": {"width": 2, "height": 2}} + ] + })"; + EXPECT_EQ(resolve(entry, kLight), nullptr); + EXPECT_EQ( + resolve(entry, kDark), folly::parseJson(R"({"width": 2, "height": 2})")); + + auto nullCondition = R"({ + "default": 1, + "conditions": [{"query": {"colorScheme": "dark"}, "value": null}] + })"; + EXPECT_EQ(resolve(nullCondition, kDark), nullptr); +} + +TEST(ConditionalValuesTest, resolvesTheDefaultWithoutConditions) { + EXPECT_EQ(resolve(R"({"default": 1})", kDark), 1); + EXPECT_EQ(resolve(R"({"default": 1, "conditions": []})", kDark), 1); + EXPECT_EQ(resolve(R"({"default": 1, "conditions": null})", kDark), 1); +} + +TEST(ConditionalValuesTest, aQueryWithAnUnknownFeatureNeverMatches) { + auto entry = R"({ + "default": 1, + "conditions": [ + {"query": {"colorScheme": "dark", "orientation": "landscape"}, "value": 2}, + {"query": {"orientation": "landscape"}, "value": 3}, + {"query": {}, "value": 4} + ] + })"; + EXPECT_EQ(resolve(entry, kLight), 1); + EXPECT_EQ(resolve(entry, kDark), 1); +} + +TEST(ConditionalValuesTest, skipsInvalidConditions) { + auto entry = R"({ + "default": 1, + "conditions": [ + null, + "dark", + {"query": {"colorScheme": "dark"}}, + {"value": 2}, + {"query": "dark", "value": 3}, + {"query": {"colorScheme": "DARK"}, "value": 4}, + {"query": {"colorScheme": 1}, "value": 5}, + {"query": {"colorScheme": "dark"}, "value": 6} + ] + })"; + EXPECT_EQ(resolve(entry, kDark), 6); + EXPECT_EQ(resolve(entry, kLight), 1); +} + +TEST(ConditionalValuesTest, returnsNullForAnInvalidEntry) { + EXPECT_EQ(resolve("null", kDark), nullptr); + EXPECT_EQ(resolve("1", kDark), nullptr); + EXPECT_EQ(resolve("[]", kDark), nullptr); + EXPECT_EQ(resolve("{}", kDark), nullptr); +} + +TEST(ConditionalValuesTest, aMatchWorksWithoutADefault) { + auto entry = R"({ + "conditions": [{"query": {"colorScheme": "dark"}, "value": 2}] + })"; + EXPECT_EQ(resolve(entry, kDark), 2); + EXPECT_EQ(resolve(entry, kLight), nullptr); +} + +TEST(ConditionalValuesTest, propsKeepTheConditionalValuesOfTheSource) { + Props source; + source.conditionalValues = std::make_shared( + ConditionalValues{.values = folly::dynamic::object("opacity", 1)}); + + // The iterator-setter path copies the source. + EXPECT_EQ(Props(source).conditionalValues, source.conditionalValues); + + // The classic path constructs from the source and the raw props. + RawPropsParser parser; + parser.prepare(); + RawProps rawProps(folly::dynamic::object("nativeID", "a")); + rawProps.parse(parser); + ContextContainer contextContainer; + PropsParserContext context{-1, contextContainer}; + Props props(context, source, rawProps); + EXPECT_EQ(props.conditionalValues, source.conditionalValues); + EXPECT_EQ(props.nativeId, "a"); +} + +namespace { + +// Resolves to 1 in light mode and 2 in dark mode. +folly::dynamic oneOrTwo() { + return folly::parseJson(R"({ + "default": 1, + "conditions": [{"query": {"colorScheme": "dark"}, "value": 2}] + })"); +} + +// Resolves to 0.5 in light mode and 0.25 in dark mode. +folly::dynamic halfOrQuarter() { + return folly::parseJson(R"({ + "default": 0.5, + "conditions": [{"query": {"colorScheme": "dark"}, "value": 0.25}] + })"); +} + +// A conditional value, as JavaScript sends it. +folly::dynamic sent(folly::dynamic conditionalValue) { + return folly::dynamic::object( + kConditionalValueKey, std::move(conditionalValue)); +} + +// A payload with a conditional value, as JavaScript sends it. +folly::dynamic withFlag(folly::dynamic values) { + values[kHasConditionalValuesPropName] = true; + return values; +} + +// By default, resolved for the same features as `resolveValues`. +Props propsWith(folly::dynamic values, const MediaFeatures& features = kDark) { + ConditionalValues conditionalValues{.resolvedFor = features}; + for (const auto& item : values.items()) { + conditionalValues.dependencies |= getMediaFeatureDependencies(item.second); + } + conditionalValues.values = std::move(values); + Props props; + props.conditionalValues = + std::make_shared(std::move(conditionalValues)); + return props; +} + +std::shared_ptr containerWith( + const MediaFeatures& features) { + auto store = std::make_shared(); + store->set(features); + auto contextContainer = std::make_shared(); + contextContainer->insert(kMediaFeaturesStoreKey, store); + return contextContainer; +} + +std::optional resolveValues( + const Props* sourceProps, + folly::dynamic values, + const MediaFeatures& features = kDark) { + return resolveConditionalValues( + sourceProps, RawProps(std::move(values)), containerWith(features).get()); +} + +} // namespace + +TEST(ConditionalValuesTest, changesNothingWithoutConditionalValues) { + EXPECT_FALSE(resolveValues(nullptr, folly::dynamic::object("opacity", 1))); +} + +TEST(ConditionalValuesTest, resolvesNewConditionalValues) { + auto values = withFlag( + folly::dynamic::object("opacity", sent(oneOrTwo()))("nativeID", "a")); + + auto dark = resolveValues(nullptr, values, kDark); + ASSERT_TRUE(dark); + EXPECT_EQ( + dark->rawProps.toDynamic(), + folly::dynamic(folly::dynamic::object("opacity", 2)("nativeID", "a"))); + ASSERT_NE(dark->conditionalValues, nullptr); + EXPECT_EQ( + dark->conditionalValues->values, + folly::dynamic(folly::dynamic::object("opacity", oneOrTwo()))); + + auto light = resolveValues(nullptr, values, kLight); + ASSERT_TRUE(light); + EXPECT_EQ(light->rawProps.toDynamic()["opacity"], 1); +} + +TEST(ConditionalValuesTest, resolvesTheDefaultWithoutAStore) { + auto result = resolveConditionalValues( + nullptr, + RawProps(withFlag(folly::dynamic::object("opacity", sent(oneOrTwo())))), + nullptr); + ASSERT_TRUE(result); + EXPECT_EQ(result->rawProps.toDynamic()["opacity"], 1); +} + +TEST(ConditionalValuesTest, keepsStoredValuesOfOtherProps) { + auto source = propsWith(folly::dynamic::object("opacity", oneOrTwo())); + EXPECT_FALSE(resolveValues(&source, folly::dynamic::object("nativeID", "a"))); +} + +TEST(ConditionalValuesTest, aPlainValueRemovesTheStoredValue) { + auto source = propsWith( + folly::dynamic::object("opacity", oneOrTwo())( + "borderWidth", halfOrQuarter())); + auto result = resolveValues(&source, folly::dynamic::object("opacity", 3)); + ASSERT_TRUE(result); + EXPECT_EQ( + result->rawProps.toDynamic(), + folly::dynamic(folly::dynamic::object("opacity", 3))); + EXPECT_EQ( + result->conditionalValues->values, + folly::dynamic(folly::dynamic::object("borderWidth", halfOrQuarter()))); +} + +TEST(ConditionalValuesTest, aNullValueRemovesTheStoredValue) { + auto source = propsWith(folly::dynamic::object("opacity", oneOrTwo())); + auto result = + resolveValues(&source, folly::dynamic::object("opacity", nullptr)); + ASSERT_TRUE(result); + EXPECT_EQ(result->conditionalValues, nullptr); +} + +TEST(ConditionalValuesTest, findsTheMediaFeaturesThatQueriesRead) { + auto colorScheme = static_cast(MediaFeature::ColorScheme); + EXPECT_EQ(getMediaFeatureDependencies(oneOrTwo()), colorScheme); + EXPECT_EQ( + getMediaFeatureDependencies(folly::parseJson(R"({ + "default": 1, + "conditions": [{"query": {"unknown": 1}, "value": 2}] + })")), + 0); + EXPECT_EQ( + getMediaFeatureDependencies(folly::parseJson(R"({"default": 1})")), 0); +} + +TEST(ConditionalValuesTest, isOutdatedOnlyForTheMediaFeaturesItReads) { + auto readsColorScheme = + propsWith(folly::dynamic::object("opacity", oneOrTwo()), kLight); + EXPECT_FALSE(readsColorScheme.conditionalValues->isOutdatedFor(kLight)); + EXPECT_TRUE(readsColorScheme.conditionalValues->isOutdatedFor(kDark)); + + auto readsNothing = propsWith( + folly::dynamic::object("opacity", folly::parseJson(R"({"default": 1})")), + kLight); + EXPECT_FALSE(readsNothing.conditionalValues->isOutdatedFor(kDark)); +} + +TEST(ConditionalValuesTest, storesTheMediaFeaturesOfTheResolution) { + auto result = resolveValues( + nullptr, withFlag(folly::dynamic::object("opacity", sent(oneOrTwo())))); + ASSERT_TRUE(result); + EXPECT_EQ( + result->conditionalValues->dependencies, + static_cast(MediaFeature::ColorScheme)); + EXPECT_EQ(result->conditionalValues->resolvedFor, kDark); +} + +TEST(ConditionalValuesTest, resolvesOutdatedStoredValuesAgain) { + auto source = + propsWith(folly::dynamic::object("opacity", oneOrTwo()), kLight); + auto result = resolveValues( + &source, + withFlag(folly::dynamic::object("borderWidth", sent(halfOrQuarter())))); + ASSERT_TRUE(result); + EXPECT_EQ( + result->rawProps.toDynamic(), + folly::dynamic( + folly::dynamic::object("borderWidth", 0.25)("opacity", 2))); + EXPECT_EQ(result->conditionalValues->resolvedFor, kDark); +} + +TEST(ConditionalValuesTest, mergesNewValuesWithStoredValues) { + auto source = propsWith(folly::dynamic::object("opacity", oneOrTwo())); + auto result = resolveValues( + &source, + withFlag(folly::dynamic::object("borderWidth", sent(halfOrQuarter())))); + ASSERT_TRUE(result); + EXPECT_EQ( + result->rawProps.toDynamic(), + folly::dynamic(folly::dynamic::object("borderWidth", 0.25))); + EXPECT_EQ( + result->conditionalValues->values, + folly::dynamic( + folly::dynamic::object("opacity", oneOrTwo())( + "borderWidth", halfOrQuarter()))); +} + +TEST(ConditionalValuesTest, anEmptyUpdateChangesNothing) { + auto source = propsWith(folly::dynamic::object("opacity", oneOrTwo())); + EXPECT_FALSE(resolveConditionalValues( + &source, RawProps(), containerWith(kLight).get())); +} + +TEST(ConditionalValuesTest, aNewValueReplacesTheStoredValue) { + auto source = propsWith(folly::dynamic::object("opacity", oneOrTwo())); + auto result = resolveValues( + &source, + withFlag(folly::dynamic::object("opacity", sent(halfOrQuarter())))); + ASSERT_TRUE(result); + EXPECT_EQ( + result->rawProps.toDynamic(), + folly::dynamic(folly::dynamic::object("opacity", 0.25))); + EXPECT_EQ( + result->conditionalValues->values, + folly::dynamic(folly::dynamic::object("opacity", halfOrQuarter()))); +} + +// For example, the `setNativeProps` props that `ShadowNode::clone` applies +// again. +TEST(ConditionalValuesTest, resolvesAReplacingValueWithoutTheFlag) { + auto source = propsWith(folly::dynamic::object("opacity", oneOrTwo())); + auto result = resolveValues( + &source, folly::dynamic::object("opacity", sent(halfOrQuarter()))); + ASSERT_TRUE(result); + EXPECT_EQ( + result->rawProps.toDynamic(), + folly::dynamic(folly::dynamic::object("opacity", 0.25))); +} + +TEST(ConditionalValuesTest, doesNotResolveANewViewWithoutTheFlag) { + EXPECT_FALSE(resolveValues( + nullptr, folly::dynamic::object("opacity", sent(oneOrTwo())))); +} + +TEST(ConditionalValuesTest, removesTheFlag) { + auto result = + resolveValues(nullptr, withFlag(folly::dynamic::object("opacity", 1))); + ASSERT_TRUE(result); + EXPECT_EQ( + result->rawProps.toDynamic(), + folly::dynamic(folly::dynamic::object("opacity", 1))); + EXPECT_EQ(result->conditionalValues, nullptr); +} + +namespace { + +// Clones props 3 times with `descriptor`, like React updates do. +template +void expectClonePropsResolvesConditionalValues() { + auto store = std::make_shared(); + store->set(kDark); + auto descriptorContainer = std::make_shared(); + descriptorContainer->insert(kMediaFeaturesStoreKey, store); + auto descriptor = std::make_shared(ComponentDescriptorParameters{ + .eventDispatcher = {}, + .contextContainer = descriptorContainer, + .flavor = nullptr}); + // An empty container, like `ShadowNode::clone` passes for `setNativeProps`. + ContextContainer contextContainer; + PropsParserContext context{-1, contextContainer}; + auto opacity = [](const Props::Shared& props) { + return std::static_pointer_cast(props)->opacity; + }; + + auto created = descriptor->cloneProps( + context, + nullptr, + RawProps( + withFlag(folly::dynamic::object("opacity", sent(halfOrQuarter()))))); + EXPECT_EQ(opacity(created), 0.25); + ASSERT_NE(created->conditionalValues, nullptr); + + auto updated = descriptor->cloneProps( + context, created, RawProps(folly::dynamic::object("nativeID", "a"))); + EXPECT_EQ(opacity(updated), 0.25); + EXPECT_EQ(updated->nativeId, "a"); + EXPECT_EQ(updated->conditionalValues, created->conditionalValues); + + // After a media features change, React sends the conditional value again. + store->set(kLight); + auto refreshed = descriptor->cloneProps( + context, + updated, + RawProps( + withFlag(folly::dynamic::object("opacity", sent(halfOrQuarter()))))); + EXPECT_EQ(opacity(refreshed), 0.5); + EXPECT_EQ(refreshed->nativeId, "a"); + EXPECT_EQ( + refreshed->conditionalValues->values, updated->conditionalValues->values); + + auto replaced = descriptor->cloneProps( + context, refreshed, RawProps(folly::dynamic::object("opacity", 0.75))); + EXPECT_EQ(opacity(replaced), 0.75); + EXPECT_EQ(replaced->conditionalValues, nullptr); +} + +class EnableCppPropsIteratorSetter : public ReactNativeFeatureFlagsDefaults { + public: + bool enableCppPropsIteratorSetter() override { + return true; + } +}; + +} // namespace + +TEST(ConditionalValuesTest, clonePropsResolvesOnTheClassicPath) { + // `TestProps` does not declare its own `setProp`, so it always uses the + // classic path. + static_assert(!HasIteratorSetterCtor); + expectClonePropsResolvesConditionalValues< + TestComponentDescriptor, + TestProps>(); +} + +TEST(ConditionalValuesTest, clonePropsResolvesOnTheIteratorSetterPath) { + static_assert(HasIteratorSetterCtor); + ReactNativeFeatureFlags::dangerouslyReset(); + ReactNativeFeatureFlags::override( + std::make_unique()); + expectClonePropsResolvesConditionalValues< + ViewComponentDescriptor, + ViewProps>(); + ReactNativeFeatureFlags::dangerouslyReset(); +} + +TEST(ConditionalValuesTest, anInvalidConditionalValueResolvesToNull) { + auto result = resolveValues( + nullptr, withFlag(folly::dynamic::object("opacity", sent(1)))); + ASSERT_TRUE(result); + EXPECT_EQ(result->rawProps.toDynamic()["opacity"], nullptr); +} + +} // namespace facebook::react 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..37bb98d322b6 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/MediaFeaturesTest.cpp @@ -0,0 +1,44 @@ +/* + * 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 + +namespace facebook::react { + +namespace { +const MediaFeatures kDark{.colorScheme = ColorScheme::Dark}; +} // namespace + +TEST(MediaFeaturesTest, storeDefaultsToLight) { + EXPECT_EQ(MediaFeaturesStore{}.get().colorScheme, ColorScheme::Light); +} + +TEST(MediaFeaturesTest, storeReturnsTheLastSetValue) { + MediaFeaturesStore store; + store.set(kDark); + EXPECT_EQ(store.get(), kDark); + store.set({}); + EXPECT_EQ(store.get(), MediaFeatures{}); +} + +TEST(MediaFeaturesTest, getMediaFeaturesReadsTheStore) { + auto store = std::make_shared(); + ContextContainer contextContainer; + contextContainer.insert(kMediaFeaturesStoreKey, store); + store->set(kDark); + EXPECT_EQ(getMediaFeatures(&contextContainer), kDark); +} + +TEST(MediaFeaturesTest, getMediaFeaturesReturnsTheDefaultsWithoutAStore) { + ContextContainer contextContainer; + EXPECT_EQ(getMediaFeatures(&contextContainer), MediaFeatures{}); + EXPECT_EQ(getMediaFeatures(nullptr), MediaFeatures{}); +} + +} // namespace facebook::react diff --git a/packages/react-native/ReactCommon/react/renderer/core/tests/RawPropsTest.cpp b/packages/react-native/ReactCommon/react/renderer/core/tests/RawPropsTest.cpp index 46774b3d1401..c066d3c54cb6 100644 --- a/packages/react-native/ReactCommon/react/renderer/core/tests/RawPropsTest.cpp +++ b/packages/react-native/ReactCommon/react/renderer/core/tests/RawPropsTest.cpp @@ -33,6 +33,23 @@ TEST(RawPropsTest, emptyPropsHaveNoDynamicSource) { EXPECT_EQ(RawProps(nullptr).getDynamic(), nullptr); } +TEST(RawPropsTest, hasPropertyWithoutParse) { + EXPECT_FALSE(RawProps().hasProperty("opacity")); + EXPECT_FALSE(RawProps(nullptr).hasProperty("opacity")); + + const auto dynamicProps = RawProps(folly::dynamic::object("opacity", 0.5)); + EXPECT_TRUE(dynamicProps.hasProperty("opacity")); + EXPECT_FALSE(dynamicProps.hasProperty("width")); + + auto runtime = facebook::hermes::makeHermesRuntime(); + auto object = jsi::Object(*runtime); + object.setProperty(*runtime, "opacity", 0.5); + const auto jsiProps = RawProps(*runtime, jsi::Value(*runtime, object)); + EXPECT_TRUE(jsiProps.hasProperty("opacity")); + EXPECT_FALSE(jsiProps.hasProperty("width")); + EXPECT_FALSE(RawProps(*runtime, jsi::Value::null()).hasProperty("opacity")); +} + TEST(RawPropsTest, jsiPropsHaveNoDynamicSource) { auto runtime = facebook::hermes::makeHermesRuntime(); auto object = jsi::Object(*runtime); diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.cpp b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.cpp index 8f08f6480679..902f4e17b234 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.cpp +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.cpp @@ -12,8 +12,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -223,13 +225,78 @@ static std::shared_ptr progressRootLayoutInfo( return shadowNode; } +/* + * The stored conditional values as JavaScript sends them, so that `cloneProps` + * resolves them again. + */ +static RawProps conditionalValuesAsRawProps(const folly::dynamic& values) { + folly::dynamic rawProps = + folly::dynamic::object(kHasConditionalValuesPropName, true); + for (const auto& item : values.items()) { + rawProps[item.first] = + folly::dynamic::object(kConditionalValueKey, item.second); + } + return RawProps(std::move(rawProps)); +} + +/* + * Returns null if no view in the subtree has outdated conditional values. + */ +static std::shared_ptr resolveOutdatedConditionalValues( + const ShadowNode& shadowNode, + const MediaFeatures& mediaFeatures) { + if (!shadowNode.subtreeHasConditionalValues()) { + return nullptr; + } + + const auto& children = shadowNode.getChildren(); + std::shared_ptr>> newChildren; + for (size_t index = 0; index < children.size(); index++) { + if (auto newChild = + resolveOutdatedConditionalValues(*children[index], mediaFeatures)) { + if (!newChildren) { + newChildren = + std::make_shared>>( + children); + } + (*newChildren)[index] = std::move(newChild); + } + } + + Props::Shared newProps; + const auto& props = shadowNode.getProps(); + if (props->conditionalValues != nullptr && + props->conditionalValues->isOutdatedFor(mediaFeatures)) { + PropsParserContext context{ + shadowNode.getSurfaceId(), *shadowNode.getContextContainer()}; + newProps = shadowNode.getComponentDescriptor().cloneProps( + context, + props, + conditionalValuesAsRawProps(props->conditionalValues->values)); + } + + if (!newChildren && !newProps) { + return nullptr; + } + return shadowNode.clone({ + .props = newProps ? newProps : ShadowNodeFragment::propsPlaceholder(), + .children = + newChildren ? newChildren : ShadowNodeFragment::childrenPlaceholder(), + }); +} + ShadowTree::ShadowTree( SurfaceId surfaceId, const LayoutConstraints& layoutConstraints, const LayoutContext& layoutContext, const ShadowTreeDelegate& delegate, const ContextContainer& contextContainer) - : surfaceId_(surfaceId), delegate_(delegate) { + : surfaceId_(surfaceId), + delegate_(delegate), + mediaFeaturesStore_( + contextContainer + .find>(kMediaFeaturesStoreKey) + .value_or(nullptr)) { static RootComponentDescriptor globalRootComponentDescriptor( ComponentDescriptorParameters{ .eventDispatcher = EventDispatcher::Shared{}, @@ -398,6 +465,16 @@ CommitStatus ShadowTree::tryCommit( commitOptions); } + // Resolve outdated conditional values, for example in the nodes that React + // holds, before the commit hooks see the tree. + if (mediaFeaturesStore_) { + if (auto resolvedRootShadowNode = resolveOutdatedConditionalValues( + *newRootShadowNode, mediaFeaturesStore_->get())) { + newRootShadowNode = + std::static_pointer_cast(resolvedRootShadowNode); + } + } + // Run commit hooks. newRootShadowNode = delegate_.shadowTreeWillCommit( *this, oldRootShadowNode, newRootShadowNode, commitOptions); diff --git a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h index 457f9a56e3a2..70d51c23e635 100644 --- a/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h +++ b/packages/react-native/ReactCommon/react/renderer/mounting/ShadowTree.h @@ -23,6 +23,8 @@ namespace facebook::react { +class MediaFeaturesStore; + using ShadowTreeCommitTransaction = std::function; /* @@ -165,6 +167,7 @@ class ShadowTree final { const SurfaceId surfaceId_; const ShadowTreeDelegate &delegate_; + const std::shared_ptr mediaFeaturesStore_; mutable std::shared_mutex revisionMutex_; mutable std::recursive_mutex revisionMutexRecursive_; mutable CommitMode commitMode_{CommitMode::Normal}; // Protected by `revisionMutex_`. diff --git a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp index a278fb2b3400..f3cd373398ec 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -38,6 +39,11 @@ Scheduler::Scheduler( SchedulerDelegate* delegate) : runtimeExecutor_(schedulerToolbox.runtimeExecutor), contextContainer_(schedulerToolbox.contextContainer) { + // A platform can insert a store with its initial media features first; + // `insert` keeps it. + contextContainer_->insert( + kMediaFeaturesStoreKey, std::make_shared()); + // Creating a container for future `EventDispatcher` instance. eventDispatcher_ = std::make_shared>(); @@ -459,6 +465,10 @@ void Scheduler::reportMount(SurfaceId surfaceId) const { uiManager_->reportMount(surfaceId); } +void Scheduler::setMediaFeatures(MediaFeatures mediaFeatures) const { + uiManager_->setMediaFeatures(mediaFeatures); +} + 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..34cc99de4cd3 100644 --- a/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h +++ b/packages/react-native/ReactCommon/react/renderer/scheduler/Scheduler.h @@ -114,6 +114,9 @@ class Scheduler final : public UIManagerDelegate { void reportMount(SurfaceId surfaceId) const; +#pragma mark - Media features + void setMediaFeatures(MediaFeatures mediaFeatures) const; + #pragma mark - Event listeners void addEventListener(std::shared_ptr listener); void removeEventListener(const std::shared_ptr &listener); diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp index 6a18881fd844..a105dc7f79d2 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.cpp @@ -514,6 +514,27 @@ void UIManager::setNativeProps_DEPRECATED( }); } +void UIManager::setMediaFeatures(MediaFeatures mediaFeatures) const { + auto store = contextContainer_->find>( + kMediaFeaturesStoreKey); + if (!store || (*store)->get() == mediaFeatures) { + return; + } + (*store)->set(mediaFeatures); + + // `ShadowTree::tryCommit` resolves the outdated values, so an empty commit is + // enough. Commit every tree: a React commit in progress can add new ones. + shadowTreeRegistry_.enumerate( + [&](const ShadowTree& shadowTree, bool& /*stop*/) { + shadowTree.commit( + [](const RootShadowNode& oldRootShadowNode) { + return std::make_shared( + oldRootShadowNode, ShadowNodeFragment{}); + }, + {}); + }); +} + void UIManager::sendAccessibilityEvent( const std::shared_ptr& shadowNode, const std::string& eventType) { diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h index 541d57a0b258..005261b05881 100644 --- a/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/UIManager.h @@ -220,6 +220,13 @@ class UIManager final : public ShadowTreeDelegate { void updateShadowTree(std::unordered_map &&tagToProps); + /* + * Sets the media features that conditional style values match, and resolves + * the values of rendered views that depend on a changed feature. Can be + * called on any thread; concurrent calls end with the last set value. + */ + void setMediaFeatures(MediaFeatures mediaFeatures) const; + #pragma mark - ContextContainer std::shared_ptr getContextContainer() const; diff --git a/packages/react-native/ReactCommon/react/renderer/uimanager/tests/UIManagerMediaFeaturesTest.cpp b/packages/react-native/ReactCommon/react/renderer/uimanager/tests/UIManagerMediaFeaturesTest.cpp new file mode 100644 index 000000000000..f53994485c27 --- /dev/null +++ b/packages/react-native/ReactCommon/react/renderer/uimanager/tests/UIManagerMediaFeaturesTest.cpp @@ -0,0 +1,356 @@ +/* + * 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 +#include +#include +#include +#include +#include +#include + +namespace facebook::react { + +namespace { + +// Changes the media features on another thread, like the UI thread does, +// while a commit runs. +class SetMediaFeaturesDuringCommitHook : public UIManagerCommitHook { + public: + void commitHookWasRegistered(const UIManager& uiManager) noexcept override { + uiManager_ = &uiManager; + } + + void commitHookWasUnregistered( + const UIManager& /*uiManager*/) noexcept override { + uiManager_ = nullptr; + } + + RootShadowNode::Unshared shadowTreeWillCommit( + const ShadowTree& /*shadowTree*/, + const std::shared_ptr& /*oldRootShadowNode*/, + const RootShadowNode::Unshared& newRootShadowNode) noexcept override { + if (mediaFeatures && uiManager_ != nullptr) { + auto newMediaFeatures = *mediaFeatures; + mediaFeatures.reset(); + std::thread([&] { + uiManager_->setMediaFeatures(newMediaFeatures); + }).join(); + } + return newRootShadowNode; + } + + std::optional mediaFeatures; + + private: + const UIManager* uiManager_{nullptr}; +}; + +class CancelCommitHook : public UIManagerCommitHook { + public: + void commitHookWasRegistered( + const UIManager& /*uiManager*/) noexcept override {} + + void commitHookWasUnregistered( + const UIManager& /*uiManager*/) noexcept override {} + + RootShadowNode::Unshared shadowTreeWillCommit( + const ShadowTree& /*shadowTree*/, + const std::shared_ptr& /*oldRootShadowNode*/, + const RootShadowNode::Unshared& newRootShadowNode) noexcept override { + if (cancelNextCommit) { + cancelNextCommit = false; + return nullptr; + } + return newRootShadowNode; + } + + bool cancelNextCommit{false}; +}; + +} // namespace + +class UIManagerMediaFeaturesTest : public ::testing::Test { + public: + UIManagerMediaFeaturesTest() { + contextContainer_ = std::make_shared(); + contextContainer_->insert( + kMediaFeaturesStoreKey, std::make_shared()); + + ComponentDescriptorProviderRegistry componentDescriptorProviderRegistry{}; + auto componentDescriptorRegistry = + componentDescriptorProviderRegistry.createComponentDescriptorRegistry( + ComponentDescriptorParameters{ + .eventDispatcher = EventDispatcher::Shared{}, + .contextContainer = contextContainer_, + .flavor = nullptr}); + componentDescriptorProviderRegistry.add( + concreteComponentDescriptorProvider()); + componentDescriptorProviderRegistry.add( + concreteComponentDescriptorProvider()); + + RuntimeExecutor runtimeExecutor = + [](std::function&& /*callback*/) {}; + uiManager_ = + std::make_unique(runtimeExecutor, contextContainer_); + uiManager_->setComponentDescriptorRegistry(componentDescriptorRegistry); + + auto shadowTree = std::make_unique( + surfaceId_, + LayoutConstraints{}, + LayoutContext{}, + *uiManager_, + *contextContainer_); + shadowTree_ = shadowTree.get(); + uiManager_->startSurface( + std::move(shadowTree), + "test", + folly::dynamic::object, + DisplayMode::Visible); + } + + void TearDown() override { + uiManager_->stopSurface(surfaceId_); + } + + protected: + // A view with opacity 1 in light mode and 0.5 in dark mode. + std::shared_ptr createView() { + auto props = folly::parseJson(R"({ + "$hasConditionalValues": true, + "opacity": {"$conditionalValue": { + "default": 1, + "conditions": [{"query": {"colorScheme": "dark"}, "value": 0.5}] + }} + })"); + return uiManager_->createNode( + viewTag_, "View", surfaceId_, RawProps(std::move(props)), nullptr); + } + + void reactCommit(const std::shared_ptr& view) { + uiManager_->completeSurface( + surfaceId_, + std::make_shared>>( + std::vector>{view}), + // The options of `completeRoot` in `UIManagerBinding`. + {.enableStateReconciliation = true, + .mountSynchronously = false, + .source = ShadowTree::CommitSource::React}); + } + + Float committedOpacity() const { + auto root = shadowTree_->getCurrentRevision().rootShadowNode; + return static_cast( + *root->getChildren().front()->getProps()) + .opacity; + } + + SurfaceId surfaceId_{1}; + Tag viewTag_{42}; + std::shared_ptr contextContainer_; + std::unique_ptr uiManager_; + ShadowTree* shadowTree_{nullptr}; +}; + +TEST_F(UIManagerMediaFeaturesTest, reactCommitResolvesAChangeDuringIt) { + auto view = createView(); + reactCommit(view); + EXPECT_FLOAT_EQ(committedOpacity(), 1); + + // React commits its light view again. During that commit, the color scheme + // changes and its update commits first, so the React commit runs again. + SetMediaFeaturesDuringCommitHook commitHook; + commitHook.mediaFeatures = MediaFeatures{.colorScheme = ColorScheme::Dark}; + uiManager_->registerCommitHook(commitHook); + reactCommit(view); + uiManager_->unregisterCommitHook(commitHook); + + EXPECT_FALSE(commitHook.mediaFeatures.has_value()); + EXPECT_FLOAT_EQ(committedOpacity(), 0.5); +} + +TEST_F( + UIManagerMediaFeaturesTest, + firstConditionalViewResolvesAChangeDuringItsCommit) { + // The committed tree has no conditional values yet, only the React commit. + SetMediaFeaturesDuringCommitHook commitHook; + commitHook.mediaFeatures = MediaFeatures{.colorScheme = ColorScheme::Dark}; + uiManager_->registerCommitHook(commitHook); + reactCommit(createView()); + uiManager_->unregisterCommitHook(commitHook); + + EXPECT_FALSE(commitHook.mediaFeatures.has_value()); + EXPECT_FLOAT_EQ(committedOpacity(), 0.5); +} + +TEST_F(UIManagerMediaFeaturesTest, cancelledReactCommitDoesNotSaveTheChange) { + auto view = createView(); + reactCommit(view); + uiManager_->setMediaFeatures({.colorScheme = ColorScheme::Dark}); + EXPECT_FLOAT_EQ(committedOpacity(), 0.5); + + // The next React commit is cancelled, so the next one must resolve again. + CancelCommitHook commitHook; + commitHook.cancelNextCommit = true; + uiManager_->registerCommitHook(commitHook); + reactCommit(view); + uiManager_->unregisterCommitHook(commitHook); + EXPECT_FALSE(commitHook.cancelNextCommit); + + reactCommit(view); + EXPECT_FLOAT_EQ(committedOpacity(), 0.5); +} + +TEST_F(UIManagerMediaFeaturesTest, reactCommitResolvesAChangeBeforeIt) { + auto view = createView(); + reactCommit(view); + EXPECT_FLOAT_EQ(committedOpacity(), 1); + + uiManager_->setMediaFeatures({.colorScheme = ColorScheme::Dark}); + reactCommit(view); + EXPECT_FLOAT_EQ(committedOpacity(), 0.5); + + uiManager_->setMediaFeatures({.colorScheme = ColorScheme::Light}); + reactCommit(view); + EXPECT_FLOAT_EQ(committedOpacity(), 1); +} + +TEST_F(UIManagerMediaFeaturesTest, reactCommitsWithoutAChangeKeepTheValue) { + auto view = createView(); + reactCommit(view); + EXPECT_FLOAT_EQ(committedOpacity(), 1); + + reactCommit(view); + EXPECT_FLOAT_EQ(committedOpacity(), 1); +} + +TEST_F(UIManagerMediaFeaturesTest, rootKnowsIfTheTreeHasConditionalValues) { + auto view = createView(); + reactCommit(view); + EXPECT_TRUE(shadowTree_->getCurrentRevision() + .rootShadowNode->subtreeHasConditionalValues()); + + // A plain value replaces the only conditional value. + reactCommit(uiManager_->cloneNode( + *view, nullptr, RawProps(folly::dynamic::object("opacity", 1)))); + EXPECT_FALSE(shadowTree_->getCurrentRevision() + .rootShadowNode->subtreeHasConditionalValues()); +} + +TEST_F(UIManagerMediaFeaturesTest, aCommitOfAnOlderTreeResolvesAChange) { + auto view = createView(); + reactCommit(view); + auto olderRootShadowNode = shadowTree_->getCurrentRevision().rootShadowNode; + + uiManager_->setMediaFeatures({.colorScheme = ColorScheme::Dark}); + EXPECT_FLOAT_EQ(committedOpacity(), 0.5); + + // Like `updateShadowTree`, which commits a tree that it made earlier. + shadowTree_->commit( + [&](const RootShadowNode& /*oldRootShadowNode*/) { + return std::make_shared( + *olderRootShadowNode, ShadowNodeFragment{}); + }, + {}); + EXPECT_FLOAT_EQ(committedOpacity(), 0.5); +} + +TEST_F(UIManagerMediaFeaturesTest, aChangeDoesNotCloneViewsOfATreeWithoutThem) { + reactCommit(uiManager_->createNode( + viewTag_, + "View", + surfaceId_, + RawProps(folly::dynamic::object("opacity", 1)), + nullptr)); + auto revisionBeforeChange = shadowTree_->getCurrentRevision(); + + // The change commits only a new root. + uiManager_->setMediaFeatures({.colorScheme = ColorScheme::Dark}); + auto revision = shadowTree_->getCurrentRevision(); + EXPECT_EQ(revision.number, revisionBeforeChange.number + 1); + EXPECT_EQ( + revision.rootShadowNode->getChildren().front(), + revisionBeforeChange.rootShadowNode->getChildren().front()); +} + +TEST_F(UIManagerMediaFeaturesTest, aChangeDoesNotCloneViewsThatDoNotReadIt) { + // The query reads a feature that the color scheme change does not change. + auto props = folly::parseJson(R"({ + "$hasConditionalValues": true, + "opacity": {"$conditionalValue": { + "default": 1, + "conditions": [{"query": {"unknown": "value"}, "value": 0.5}] + }} + })"); + reactCommit(uiManager_->createNode( + viewTag_, "View", surfaceId_, RawProps(std::move(props)), nullptr)); + auto committedView = [&] { + return shadowTree_->getCurrentRevision() + .rootShadowNode->getChildren() + .front(); + }; + auto viewBeforeChange = committedView(); + + uiManager_->setMediaFeatures({.colorScheme = ColorScheme::Dark}); + EXPECT_EQ(committedView(), viewBeforeChange); + EXPECT_FLOAT_EQ(committedOpacity(), 1); +} + +namespace { + +class CommitBranchingFlags : public ReactNativeFeatureFlagsDefaults { + public: + bool enableFabricCommitBranching() override { + return true; + } +}; + +// A base class, so the flags are set before the fixture reads them. +class WithCommitBranching { + public: + WithCommitBranching() { + ReactNativeFeatureFlags::dangerouslyReset(); + ReactNativeFeatureFlags::override(std::make_unique()); + } + + ~WithCommitBranching() { + ReactNativeFeatureFlags::dangerouslyReset(); + } +}; + +} // namespace + +class UIManagerMediaFeaturesBranchingTest : public WithCommitBranching, + public UIManagerMediaFeaturesTest { +}; + +// With commit branching, a React commit is put on screen by a later merge. +TEST_F(UIManagerMediaFeaturesBranchingTest, mergeKeepsAChangeBeforeIt) { + auto view = createView(); + reactCommit(view); + shadowTree_->promoteReactRevision(); + shadowTree_->mergeReactRevision(); + EXPECT_FLOAT_EQ(committedOpacity(), 1); + + // React commits its light view again, and the change comes before the merge. + reactCommit(view); + shadowTree_->promoteReactRevision(); + uiManager_->setMediaFeatures({.colorScheme = ColorScheme::Dark}); + EXPECT_FLOAT_EQ(committedOpacity(), 0.5); + + shadowTree_->mergeReactRevision(); + EXPECT_FLOAT_EQ(committedOpacity(), 0.5); +} + +} // namespace facebook::react 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..77dc19d4c579 100644 --- a/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js +++ b/packages/react-native/src/private/testing/fantom/specs/NativeFantom.js @@ -138,6 +138,7 @@ interface Spec extends TurboModule { setImageResponse(uri: string, imageResponse: ImageResponse): void; clearImage(uri: string): void; clearAllImages(): void; + setColorScheme: (colorScheme: 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 310689624005..c1f379c294b8 100644 --- a/private/react-native-fantom/src/index.js +++ b/private/react-native-fantom/src/index.js @@ -721,6 +721,14 @@ export function enqueueModalSizeUpdate( NativeFantom.enqueueModalSizeUpdate(shadowNode, size.width, size.height); } +/** + * Sets the color scheme that `@media (prefers-color-scheme: ...)` conditional + * values match, and updates the rendered views. + */ +export function setColorScheme(colorScheme: 'light' | 'dark') { + NativeFantom.setColorScheme(colorScheme); +} + 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..abd657ed8b48 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 @@ -257,6 +258,20 @@ void NativeFantom::enqueueModalSizeUpdate( .height = static_cast(height)})); } +void NativeFantom::setColorScheme( + jsi::Runtime& runtime, + const std::string& colorScheme) { + // Platforms call it on the UI thread, where clones do not update the shadow + // node references of React. + auto wasEnabled = + ShadowNode::getUseRuntimeShadowNodeReferenceUpdateOnThread(); + ShadowNode::setUseRuntimeShadowNodeReferenceUpdateOnThread(false); + UIManagerBinding::getBinding(runtime)->getUIManager().setMediaFeatures( + {.colorScheme = + colorScheme == "dark" ? ColorScheme::Dark : ColorScheme::Light}); + ShadowNode::setUseRuntimeShadowNodeReferenceUpdateOnThread(wasEnabled); +} + jsi::Function NativeFantom::createShadowNodeReferenceCounter( 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..27e942b949c1 100644 --- a/private/react-native-fantom/tester/src/NativeFantom.h +++ b/private/react-native-fantom/tester/src/NativeFantom.h @@ -152,6 +152,8 @@ class NativeFantom : public NativeFantomCxxSpec { void clearImage(jsi::Runtime &rt, const std::string &uri); void clearAllImages(jsi::Runtime &rt); + void setColorScheme(jsi::Runtime &runtime, const std::string &colorScheme); + private: TesterAppDelegate &appDelegate_; std::unordered_map assetPaths_; diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api index f6d983a0272d..5a80ff622d96 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api @@ -375,6 +375,9 @@ 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::kConditionalValueKey; +constexpr char* facebook::react::kHasConditionalValuesPropName; +constexpr char* facebook::react::kMediaFeaturesStoreKey; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -422,6 +425,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeatureSet = uint8_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -505,6 +509,8 @@ 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::MediaFeatureSet facebook::react::getMediaFeatureDependencies(const folly::dynamic& conditionalValue); +facebook::react::MediaFeatures facebook::react::getMediaFeatures(const facebook::react::ContextContainer* contextContainer); 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(); @@ -524,6 +530,7 @@ 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); folly::dynamic facebook::react::toDynamic(const YGValue& dimension); folly::dynamic facebook::react::toDynamic(const facebook::react::BackgroundImage& backgroundImage); folly::dynamic facebook::react::toDynamic(const facebook::react::BoxShadow& boxShadow); @@ -543,6 +550,7 @@ int facebook::react::toAndroidRepr(const facebook::react::SharedColor& color); 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::resolveConditionalValues(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps, const facebook::react::ContextContainer* contextContainer); 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); @@ -1817,6 +1825,11 @@ class facebook::react::MapBufferBuilder { public void putString(facebook::react::MapBuffer::Key key, const std::string& value); } +class facebook::react::MediaFeaturesStore { + public facebook::react::MediaFeatures get() const noexcept; + public void set(facebook::react::MediaFeatures features) noexcept; +} + class facebook::react::ModalHostViewEventEmitter : public facebook::react::BaseViewEventEmitter { public static char const* toString(const facebook::react::ModalHostViewEventEmitter::OnOrientationChangeOrientation value); public void onDismiss(facebook::react::ModalHostViewEventEmitter::OnDismiss value) const; @@ -2100,6 +2113,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public 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::Props& operator=(const facebook::react::Props& other) = delete; public folly::dynamic rawProps; + public std::shared_ptr conditionalValues; public std::string nativeId; public using Shared = std::shared_ptr; public virtual facebook::react::ComponentName getDiffPropsImplementationTarget() const; @@ -2134,6 +2148,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; @@ -2233,6 +2248,7 @@ class facebook::react::ShadowNode : public facebook::react::Sealable, public fac public ShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ShadowNode(const facebook::react::ShadowNodeFragment& fragment, facebook::react::ShadowNodeFamily::Shared family, facebook::react::ShadowNodeTraits traits); public bool getHasBeenPromoted() const; + public bool subtreeHasConditionalValues() const; public const facebook::react::ComponentDescriptor& getComponentDescriptor() const; public const facebook::react::Props::Shared& getProps() const; public const facebook::react::ShadowNodeFamily& getFamily() const; @@ -2309,6 +2325,7 @@ enum facebook::react::ShadowNodeTraits::Trait : int32_t { BaselineYogaNode, ChildrenAreShared, ChildrenFormStackingContext, + ChildrenHaveConditionalValues, DirtyYogaNode, ForceFlattenView, FormsStackingContext, @@ -2758,6 +2775,11 @@ enum facebook::react::BorderStyle : uint8_t { Solid, } +enum facebook::react::ColorScheme : uint8_t { + Dark, + Light, +} + enum facebook::react::ColorSpace { DisplayP3, sRGB, @@ -2887,6 +2909,10 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaFeature : uint8_t { + ColorScheme, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -3209,6 +3235,18 @@ struct facebook::react::ColorStop { public folly::dynamic toDynamic() const; } +struct facebook::react::ConditionalValues { + public bool isOutdatedFor(const facebook::react::MediaFeatures& features) const; + public facebook::react::MediaFeatureSet dependencies; + public facebook::react::MediaFeatures resolvedFor; + public folly::dynamic values; +} + +struct facebook::react::ConditionalValuesResolution { + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalValues; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -3406,6 +3444,12 @@ 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::ColorScheme colorScheme; + public facebook::react::MediaFeatureSet differences(const facebook::react::MediaFeatures& other) const; +} + struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { public facebook::react::ModalHostViewSupportedOrientationsMask value; } diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api index 6a7f3f69bce1..fdb57f060455 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidFrameworksCxx.api @@ -388,6 +388,9 @@ 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::kConditionalValueKey; +constexpr char* facebook::react::kHasConditionalValuesPropName; +constexpr char* facebook::react::kMediaFeaturesStoreKey; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr float facebook::react::kDefaultEpsilon; @@ -536,6 +539,7 @@ using facebook::react::LayoutConformanceComponentDescriptor = facebook::react::C using facebook::react::LineMeasureCache = facebook::react::SimpleThreadSafeCache; using facebook::react::LinesMeasurements = std::vector; using facebook::react::Logger = std::function; +using facebook::react::MediaFeatureSet = uint8_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::MountingTransactionCallback = std::function; using facebook::react::NativeMethodCallFunc = std::function; @@ -730,6 +734,8 @@ facebook::react::MapBuffer facebook::react::toMapBuffer(const facebook::react::A facebook::react::MapBuffer facebook::react::toMapBuffer(const facebook::react::FontVariant& fontVariant); facebook::react::MapBuffer facebook::react::toMapBuffer(const facebook::react::ParagraphAttributes& paragraphAttributes); facebook::react::MapBuffer facebook::react::toMapBuffer(const facebook::react::TextAttributes& textAttributes); +facebook::react::MediaFeatureSet facebook::react::getMediaFeatureDependencies(const folly::dynamic& conditionalValue); +facebook::react::MediaFeatures facebook::react::getMediaFeatures(const facebook::react::ContextContainer* contextContainer); 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; @@ -756,6 +762,7 @@ float facebook::react::redFromHostPlatformColor(facebook::react::Color color); float facebook::react::yogaFloatFromFloat(facebook::react::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); folly::dynamic facebook::react::toDynamic(const YGValue& dimension); folly::dynamic facebook::react::toDynamic(const facebook::react::AndroidTextInputTextShadowOffsetStruct& value); folly::dynamic facebook::react::toDynamic(const facebook::react::BackgroundImage& backgroundImage); @@ -781,6 +788,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::resolveConditionalValues(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps, const facebook::react::ContextContainer* contextContainer); 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); @@ -2701,6 +2709,11 @@ class facebook::react::MapBufferBuilder { public void putString(facebook::react::MapBuffer::Key key, const std::string& value); } +class facebook::react::MediaFeaturesStore { + public facebook::react::MediaFeatures get() const noexcept; + public void set(facebook::react::MediaFeatures features) noexcept; +} + class facebook::react::MergedValueDispatcher { public MergedValueDispatcher(facebook::react::MergedValueDispatcher::DispatchFunction dispatchFunction, facebook::react::MergedValueDispatcher::MergedValueFunction mergedValueFunction); public using DispatchFunction = std::function&&)>; @@ -3247,6 +3260,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public 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::Props& operator=(const facebook::react::Props& other) = delete; public folly::dynamic rawProps; + public std::shared_ptr conditionalValues; public std::string nativeId; public using Shared = std::shared_ptr; public virtual facebook::react::ComponentName getDiffPropsImplementationTarget() const; @@ -3281,6 +3295,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; @@ -3549,6 +3564,7 @@ class facebook::react::Scheduler : public facebook::react::UIManagerDelegate { public void removeEventListener(const std::shared_ptr& listener); public void reportMount(facebook::react::SurfaceId surfaceId) const; public void setDelegate(facebook::react::SchedulerDelegate* delegate); + public void setMediaFeatures(facebook::react::MediaFeatures mediaFeatures) const; public void unregisterSurface(const facebook::react::SurfaceHandler& surfaceHandler) const noexcept; public ~Scheduler() override; } @@ -3629,6 +3645,7 @@ class facebook::react::ShadowNode : public facebook::react::Sealable, public fac public ShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ShadowNode(const facebook::react::ShadowNodeFragment& fragment, facebook::react::ShadowNodeFamily::Shared family, facebook::react::ShadowNodeTraits traits); public bool getHasBeenPromoted() const; + public bool subtreeHasConditionalValues() const; public const facebook::react::ComponentDescriptor& getComponentDescriptor() const; public const facebook::react::Props::Shared& getProps() const; public const facebook::react::ShadowNodeFamily& getFamily() const; @@ -3705,6 +3722,7 @@ enum facebook::react::ShadowNodeTraits::Trait : int32_t { BaselineYogaNode, ChildrenAreShared, ChildrenFormStackingContext, + ChildrenHaveConditionalValues, DirtyYogaNode, ForceFlattenView, FormsStackingContext, @@ -4231,6 +4249,7 @@ class facebook::react::UIManager : public facebook::react::ShadowTreeDelegate { public void setComponentDescriptorRegistry(const facebook::react::SharedComponentDescriptorRegistry& componentDescriptorRegistry); public void setDelegate(facebook::react::UIManagerDelegate* delegate); public void setIsJSResponder(const std::shared_ptr& shadowNode, bool isJSResponder, bool blockNativeResponder) const; + public void setMediaFeatures(facebook::react::MediaFeatures mediaFeatures) const; public void setNativeAnimatedDelegate(std::weak_ptr delegate); public void setSurfaceProps(facebook::react::SurfaceId surfaceId, std::string moduleName, folly::dynamic props, facebook::react::DisplayMode displayMode) const noexcept; public void setViewTransitionDelegate(facebook::react::UIManagerViewTransitionDelegate* delegate); @@ -4927,6 +4946,11 @@ enum facebook::react::CSSWideKeyword : std::underlying_type_t conditionalValues; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -6325,6 +6365,12 @@ 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::ColorScheme colorScheme; + public facebook::react::MediaFeatureSet differences(const facebook::react::MediaFeatures& other) const; +} + struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { public facebook::react::ModalHostViewSupportedOrientationsMask value; } diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api index 7d2118c15877..e540648e6ece 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidNewarchCxx.api @@ -375,6 +375,9 @@ 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::kConditionalValueKey; +constexpr char* facebook::react::kHasConditionalValuesPropName; +constexpr char* facebook::react::kMediaFeaturesStoreKey; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -422,6 +425,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeatureSet = uint8_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -505,6 +509,8 @@ 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::MediaFeatureSet facebook::react::getMediaFeatureDependencies(const folly::dynamic& conditionalValue); +facebook::react::MediaFeatures facebook::react::getMediaFeatures(const facebook::react::ContextContainer* contextContainer); 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(); @@ -524,6 +530,7 @@ 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); folly::dynamic facebook::react::toDynamic(const YGValue& dimension); folly::dynamic facebook::react::toDynamic(const facebook::react::BackgroundImage& backgroundImage); folly::dynamic facebook::react::toDynamic(const facebook::react::BoxShadow& boxShadow); @@ -543,6 +550,7 @@ int facebook::react::toAndroidRepr(const facebook::react::SharedColor& color); 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::resolveConditionalValues(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps, const facebook::react::ContextContainer* contextContainer); 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); @@ -1816,6 +1824,11 @@ class facebook::react::MapBufferBuilder { public void putString(facebook::react::MapBuffer::Key key, const std::string& value); } +class facebook::react::MediaFeaturesStore { + public facebook::react::MediaFeatures get() const noexcept; + public void set(facebook::react::MediaFeatures features) noexcept; +} + class facebook::react::ModalHostViewEventEmitter : public facebook::react::BaseViewEventEmitter { public static char const* toString(const facebook::react::ModalHostViewEventEmitter::OnOrientationChangeOrientation value); public void onDismiss(facebook::react::ModalHostViewEventEmitter::OnDismiss value) const; @@ -2099,6 +2112,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public 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::Props& operator=(const facebook::react::Props& other) = delete; public folly::dynamic rawProps; + public std::shared_ptr conditionalValues; public std::string nativeId; public using Shared = std::shared_ptr; public virtual facebook::react::ComponentName getDiffPropsImplementationTarget() const; @@ -2133,6 +2147,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; @@ -2226,6 +2241,7 @@ class facebook::react::ShadowNode : public facebook::react::Sealable, public fac public ShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ShadowNode(const facebook::react::ShadowNodeFragment& fragment, facebook::react::ShadowNodeFamily::Shared family, facebook::react::ShadowNodeTraits traits); public bool getHasBeenPromoted() const; + public bool subtreeHasConditionalValues() const; public const facebook::react::ComponentDescriptor& getComponentDescriptor() const; public const facebook::react::Props::Shared& getProps() const; public const facebook::react::ShadowNodeFamily& getFamily() const; @@ -2302,6 +2318,7 @@ enum facebook::react::ShadowNodeTraits::Trait : int32_t { BaselineYogaNode, ChildrenAreShared, ChildrenFormStackingContext, + ChildrenHaveConditionalValues, DirtyYogaNode, ForceFlattenView, FormsStackingContext, @@ -2751,6 +2768,11 @@ enum facebook::react::BorderStyle : uint8_t { Solid, } +enum facebook::react::ColorScheme : uint8_t { + Dark, + Light, +} + enum facebook::react::ColorSpace { DisplayP3, sRGB, @@ -2880,6 +2902,10 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaFeature : uint8_t { + ColorScheme, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -3202,6 +3228,18 @@ struct facebook::react::ColorStop { public folly::dynamic toDynamic() const; } +struct facebook::react::ConditionalValues { + public bool isOutdatedFor(const facebook::react::MediaFeatures& features) const; + public facebook::react::MediaFeatureSet dependencies; + public facebook::react::MediaFeatures resolvedFor; + public folly::dynamic values; +} + +struct facebook::react::ConditionalValuesResolution { + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalValues; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -3399,6 +3437,12 @@ 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::ColorScheme colorScheme; + public facebook::react::MediaFeatureSet differences(const facebook::react::MediaFeatures& other) const; +} + struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { public facebook::react::ModalHostViewSupportedOrientationsMask value; } diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api index 7d2118c15877..e540648e6ece 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api @@ -375,6 +375,9 @@ 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::kConditionalValueKey; +constexpr char* facebook::react::kHasConditionalValuesPropName; +constexpr char* facebook::react::kMediaFeaturesStoreKey; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -422,6 +425,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeatureSet = uint8_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -505,6 +509,8 @@ 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::MediaFeatureSet facebook::react::getMediaFeatureDependencies(const folly::dynamic& conditionalValue); +facebook::react::MediaFeatures facebook::react::getMediaFeatures(const facebook::react::ContextContainer* contextContainer); 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(); @@ -524,6 +530,7 @@ 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); folly::dynamic facebook::react::toDynamic(const YGValue& dimension); folly::dynamic facebook::react::toDynamic(const facebook::react::BackgroundImage& backgroundImage); folly::dynamic facebook::react::toDynamic(const facebook::react::BoxShadow& boxShadow); @@ -543,6 +550,7 @@ int facebook::react::toAndroidRepr(const facebook::react::SharedColor& color); 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::resolveConditionalValues(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps, const facebook::react::ContextContainer* contextContainer); 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); @@ -1816,6 +1824,11 @@ class facebook::react::MapBufferBuilder { public void putString(facebook::react::MapBuffer::Key key, const std::string& value); } +class facebook::react::MediaFeaturesStore { + public facebook::react::MediaFeatures get() const noexcept; + public void set(facebook::react::MediaFeatures features) noexcept; +} + class facebook::react::ModalHostViewEventEmitter : public facebook::react::BaseViewEventEmitter { public static char const* toString(const facebook::react::ModalHostViewEventEmitter::OnOrientationChangeOrientation value); public void onDismiss(facebook::react::ModalHostViewEventEmitter::OnDismiss value) const; @@ -2099,6 +2112,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public 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::Props& operator=(const facebook::react::Props& other) = delete; public folly::dynamic rawProps; + public std::shared_ptr conditionalValues; public std::string nativeId; public using Shared = std::shared_ptr; public virtual facebook::react::ComponentName getDiffPropsImplementationTarget() const; @@ -2133,6 +2147,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; @@ -2226,6 +2241,7 @@ class facebook::react::ShadowNode : public facebook::react::Sealable, public fac public ShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ShadowNode(const facebook::react::ShadowNodeFragment& fragment, facebook::react::ShadowNodeFamily::Shared family, facebook::react::ShadowNodeTraits traits); public bool getHasBeenPromoted() const; + public bool subtreeHasConditionalValues() const; public const facebook::react::ComponentDescriptor& getComponentDescriptor() const; public const facebook::react::Props::Shared& getProps() const; public const facebook::react::ShadowNodeFamily& getFamily() const; @@ -2302,6 +2318,7 @@ enum facebook::react::ShadowNodeTraits::Trait : int32_t { BaselineYogaNode, ChildrenAreShared, ChildrenFormStackingContext, + ChildrenHaveConditionalValues, DirtyYogaNode, ForceFlattenView, FormsStackingContext, @@ -2751,6 +2768,11 @@ enum facebook::react::BorderStyle : uint8_t { Solid, } +enum facebook::react::ColorScheme : uint8_t { + Dark, + Light, +} + enum facebook::react::ColorSpace { DisplayP3, sRGB, @@ -2880,6 +2902,10 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaFeature : uint8_t { + ColorScheme, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -3202,6 +3228,18 @@ struct facebook::react::ColorStop { public folly::dynamic toDynamic() const; } +struct facebook::react::ConditionalValues { + public bool isOutdatedFor(const facebook::react::MediaFeatures& features) const; + public facebook::react::MediaFeatureSet dependencies; + public facebook::react::MediaFeatures resolvedFor; + public folly::dynamic values; +} + +struct facebook::react::ConditionalValuesResolution { + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalValues; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -3399,6 +3437,12 @@ 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::ColorScheme colorScheme; + public facebook::react::MediaFeatureSet differences(const facebook::react::MediaFeatures& other) const; +} + struct facebook::react::ModalHostViewSupportedOrientationsMaskWrapped { public facebook::react::ModalHostViewSupportedOrientationsMask value; } diff --git a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api index d9b5033ad90c..0594edef3bfa 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleDebugCxx.api @@ -3113,6 +3113,9 @@ 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::kConditionalValueKey; +constexpr char* facebook::react::kHasConditionalValuesPropName; +constexpr char* facebook::react::kMediaFeaturesStoreKey; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -3159,6 +3162,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeatureSet = uint8_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -3232,6 +3236,8 @@ 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::MediaFeatureSet facebook::react::getMediaFeatureDependencies(const folly::dynamic& conditionalValue); +facebook::react::MediaFeatures facebook::react::getMediaFeatures(const facebook::react::ContextContainer* contextContainer); 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(); @@ -3250,9 +3256,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::resolveConditionalValues(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps, const facebook::react::ContextContainer* contextContainer); 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); @@ -4075,6 +4083,11 @@ class facebook::react::MapBufferBuilder { public void putString(facebook::react::MapBuffer::Key key, const std::string& value); } +class facebook::react::MediaFeaturesStore { + public facebook::react::MediaFeatures get() const noexcept; + public void set(facebook::react::MediaFeatures features) noexcept; +} + class facebook::react::ModalHostViewEventEmitter : public facebook::react::BaseViewEventEmitter { public static char const* toString(const facebook::react::ModalHostViewEventEmitter::OnOrientationChangeOrientation value); public void onDismiss(facebook::react::ModalHostViewEventEmitter::OnDismiss value) const; @@ -4328,6 +4341,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public 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::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalValues; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -4379,6 +4393,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; @@ -4459,6 +4474,7 @@ class facebook::react::ShadowNode : public facebook::react::Sealable, public fac public ShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ShadowNode(const facebook::react::ShadowNodeFragment& fragment, facebook::react::ShadowNodeFamily::Shared family, facebook::react::ShadowNodeTraits traits); public bool getHasBeenPromoted() const; + public bool subtreeHasConditionalValues() const; public const facebook::react::ComponentDescriptor& getComponentDescriptor() const; public const facebook::react::Props::Shared& getProps() const; public const facebook::react::ShadowNodeFamily& getFamily() const; @@ -4535,6 +4551,7 @@ enum facebook::react::ShadowNodeTraits::Trait : int32_t { BaselineYogaNode, ChildrenAreShared, ChildrenFormStackingContext, + ChildrenHaveConditionalValues, DirtyYogaNode, ForceFlattenView, FormsStackingContext, @@ -4883,6 +4900,11 @@ enum facebook::react::BorderStyle : uint8_t { Solid, } +enum facebook::react::ColorScheme : uint8_t { + Dark, + Light, +} + enum facebook::react::ColorSpace { DisplayP3, sRGB, @@ -5003,6 +5025,10 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaFeature : uint8_t { + ColorScheme, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -5326,6 +5352,18 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalValues { + public bool isOutdatedFor(const facebook::react::MediaFeatures& features) const; + public facebook::react::MediaFeatureSet dependencies; + public facebook::react::MediaFeatures resolvedFor; + public folly::dynamic values; +} + +struct facebook::react::ConditionalValuesResolution { + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalValues; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -5414,6 +5452,12 @@ 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::ColorScheme colorScheme; + public facebook::react::MediaFeatureSet differences(const facebook::react::MediaFeatures& other) const; +} + 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 3c64308d98f7..67a58bcecc1f 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleFrameworksCxx.api @@ -3225,6 +3225,9 @@ 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::kConditionalValueKey; +constexpr char* facebook::react::kHasConditionalValuesPropName; +constexpr char* facebook::react::kMediaFeaturesStoreKey; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr float facebook::react::kDefaultEpsilon; @@ -3313,6 +3316,7 @@ using facebook::react::LayoutConformanceComponentDescriptor = facebook::react::C using facebook::react::LineMeasureCache = facebook::react::SimpleThreadSafeCache; using facebook::react::LinesMeasurements = std::vector; using facebook::react::Logger = std::function; +using facebook::react::MediaFeatureSet = uint8_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::MountingTransactionCallback = std::function; using facebook::react::NativeMethodCallFunc = std::function; @@ -3493,6 +3497,8 @@ 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::MediaFeatureSet facebook::react::getMediaFeatureDependencies(const folly::dynamic& conditionalValue); +facebook::react::MediaFeatures facebook::react::getMediaFeatures(const facebook::react::ContextContainer* contextContainer); 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; @@ -3519,6 +3525,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); @@ -3528,6 +3535,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::resolveConditionalValues(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps, const facebook::react::ContextContainer* contextContainer); 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); @@ -4891,6 +4899,11 @@ class facebook::react::MapBufferBuilder { public void putString(facebook::react::MapBuffer::Key key, const std::string& value); } +class facebook::react::MediaFeaturesStore { + public facebook::react::MediaFeatures get() const noexcept; + public void set(facebook::react::MediaFeatures features) noexcept; +} + class facebook::react::MergedValueDispatcher { public MergedValueDispatcher(facebook::react::MergedValueDispatcher::DispatchFunction dispatchFunction, facebook::react::MergedValueDispatcher::MergedValueFunction mergedValueFunction); public using DispatchFunction = std::function&&)>; @@ -5406,6 +5419,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public 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::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalValues; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -5471,6 +5485,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; @@ -5723,6 +5738,7 @@ class facebook::react::Scheduler : public facebook::react::UIManagerDelegate { public void removeEventListener(const std::shared_ptr& listener); public void reportMount(facebook::react::SurfaceId surfaceId) const; public void setDelegate(facebook::react::SchedulerDelegate* delegate); + public void setMediaFeatures(facebook::react::MediaFeatures mediaFeatures) const; public void unregisterSurface(const facebook::react::SurfaceHandler& surfaceHandler) const noexcept; public ~Scheduler() override; } @@ -5801,6 +5817,7 @@ class facebook::react::ShadowNode : public facebook::react::Sealable, public fac public ShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ShadowNode(const facebook::react::ShadowNodeFragment& fragment, facebook::react::ShadowNodeFamily::Shared family, facebook::react::ShadowNodeTraits traits); public bool getHasBeenPromoted() const; + public bool subtreeHasConditionalValues() const; public const facebook::react::ComponentDescriptor& getComponentDescriptor() const; public const facebook::react::Props::Shared& getProps() const; public const facebook::react::ShadowNodeFamily& getFamily() const; @@ -5877,6 +5894,7 @@ enum facebook::react::ShadowNodeTraits::Trait : int32_t { BaselineYogaNode, ChildrenAreShared, ChildrenFormStackingContext, + ChildrenHaveConditionalValues, DirtyYogaNode, ForceFlattenView, FormsStackingContext, @@ -6355,6 +6373,7 @@ class facebook::react::UIManager : public facebook::react::ShadowTreeDelegate { public void setComponentDescriptorRegistry(const facebook::react::SharedComponentDescriptorRegistry& componentDescriptorRegistry); public void setDelegate(facebook::react::UIManagerDelegate* delegate); public void setIsJSResponder(const std::shared_ptr& shadowNode, bool isJSResponder, bool blockNativeResponder) const; + public void setMediaFeatures(facebook::react::MediaFeatures mediaFeatures) const; public void setNativeAnimatedDelegate(std::weak_ptr delegate); public void setSurfaceProps(facebook::react::SurfaceId surfaceId, std::string moduleName, folly::dynamic props, facebook::react::DisplayMode displayMode) const noexcept; public void setViewTransitionDelegate(facebook::react::UIManagerViewTransitionDelegate* delegate); @@ -7033,6 +7052,11 @@ enum facebook::react::CSSWideKeyword : std::underlying_type_t conditionalValues; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -8348,6 +8388,12 @@ 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::ColorScheme colorScheme; + public facebook::react::MediaFeatureSet differences(const facebook::react::MediaFeatures& other) const; +} + 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 280067df592a..42a136136821 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleNewarchCxx.api @@ -3106,6 +3106,9 @@ 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::kConditionalValueKey; +constexpr char* facebook::react::kHasConditionalValuesPropName; +constexpr char* facebook::react::kMediaFeaturesStoreKey; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -3152,6 +3155,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeatureSet = uint8_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -3225,6 +3229,8 @@ 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::MediaFeatureSet facebook::react::getMediaFeatureDependencies(const folly::dynamic& conditionalValue); +facebook::react::MediaFeatures facebook::react::getMediaFeatures(const facebook::react::ContextContainer* contextContainer); 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(); @@ -3243,9 +3249,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::resolveConditionalValues(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps, const facebook::react::ContextContainer* contextContainer); 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); @@ -4067,6 +4075,11 @@ class facebook::react::MapBufferBuilder { public void putString(facebook::react::MapBuffer::Key key, const std::string& value); } +class facebook::react::MediaFeaturesStore { + public facebook::react::MediaFeatures get() const noexcept; + public void set(facebook::react::MediaFeatures features) noexcept; +} + class facebook::react::ModalHostViewEventEmitter : public facebook::react::BaseViewEventEmitter { public static char const* toString(const facebook::react::ModalHostViewEventEmitter::OnOrientationChangeOrientation value); public void onDismiss(facebook::react::ModalHostViewEventEmitter::OnDismiss value) const; @@ -4320,6 +4333,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public 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::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalValues; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -4371,6 +4385,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; @@ -4445,6 +4460,7 @@ class facebook::react::ShadowNode : public facebook::react::Sealable, public fac public ShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ShadowNode(const facebook::react::ShadowNodeFragment& fragment, facebook::react::ShadowNodeFamily::Shared family, facebook::react::ShadowNodeTraits traits); public bool getHasBeenPromoted() const; + public bool subtreeHasConditionalValues() const; public const facebook::react::ComponentDescriptor& getComponentDescriptor() const; public const facebook::react::Props::Shared& getProps() const; public const facebook::react::ShadowNodeFamily& getFamily() const; @@ -4521,6 +4537,7 @@ enum facebook::react::ShadowNodeTraits::Trait : int32_t { BaselineYogaNode, ChildrenAreShared, ChildrenFormStackingContext, + ChildrenHaveConditionalValues, DirtyYogaNode, ForceFlattenView, FormsStackingContext, @@ -4869,6 +4886,11 @@ enum facebook::react::BorderStyle : uint8_t { Solid, } +enum facebook::react::ColorScheme : uint8_t { + Dark, + Light, +} + enum facebook::react::ColorSpace { DisplayP3, sRGB, @@ -4989,6 +5011,10 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaFeature : uint8_t { + ColorScheme, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -5312,6 +5338,18 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalValues { + public bool isOutdatedFor(const facebook::react::MediaFeatures& features) const; + public facebook::react::MediaFeatureSet dependencies; + public facebook::react::MediaFeatures resolvedFor; + public folly::dynamic values; +} + +struct facebook::react::ConditionalValuesResolution { + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalValues; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -5400,6 +5438,12 @@ 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::ColorScheme colorScheme; + public facebook::react::MediaFeatureSet differences(const facebook::react::MediaFeatures& other) const; +} + 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 4d607c7ed5e8..c22849b2b66d 100644 --- a/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAppleReleaseCxx.api @@ -3113,6 +3113,9 @@ 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::kConditionalValueKey; +constexpr char* facebook::react::kHasConditionalValuesPropName; +constexpr char* facebook::react::kMediaFeaturesStoreKey; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -3159,6 +3162,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeatureSet = uint8_t; using facebook::react::ModalHostViewSupportedOrientationsMask = uint32_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; @@ -3232,6 +3236,8 @@ 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::MediaFeatureSet facebook::react::getMediaFeatureDependencies(const folly::dynamic& conditionalValue); +facebook::react::MediaFeatures facebook::react::getMediaFeatures(const facebook::react::ContextContainer* contextContainer); 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(); @@ -3250,9 +3256,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::resolveConditionalValues(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps, const facebook::react::ContextContainer* contextContainer); 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); @@ -4074,6 +4082,11 @@ class facebook::react::MapBufferBuilder { public void putString(facebook::react::MapBuffer::Key key, const std::string& value); } +class facebook::react::MediaFeaturesStore { + public facebook::react::MediaFeatures get() const noexcept; + public void set(facebook::react::MediaFeatures features) noexcept; +} + class facebook::react::ModalHostViewEventEmitter : public facebook::react::BaseViewEventEmitter { public static char const* toString(const facebook::react::ModalHostViewEventEmitter::OnOrientationChangeOrientation value); public void onDismiss(facebook::react::ModalHostViewEventEmitter::OnDismiss value) const; @@ -4327,6 +4340,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public 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::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalValues; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -4378,6 +4392,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; @@ -4452,6 +4467,7 @@ class facebook::react::ShadowNode : public facebook::react::Sealable, public fac public ShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ShadowNode(const facebook::react::ShadowNodeFragment& fragment, facebook::react::ShadowNodeFamily::Shared family, facebook::react::ShadowNodeTraits traits); public bool getHasBeenPromoted() const; + public bool subtreeHasConditionalValues() const; public const facebook::react::ComponentDescriptor& getComponentDescriptor() const; public const facebook::react::Props::Shared& getProps() const; public const facebook::react::ShadowNodeFamily& getFamily() const; @@ -4528,6 +4544,7 @@ enum facebook::react::ShadowNodeTraits::Trait : int32_t { BaselineYogaNode, ChildrenAreShared, ChildrenFormStackingContext, + ChildrenHaveConditionalValues, DirtyYogaNode, ForceFlattenView, FormsStackingContext, @@ -4876,6 +4893,11 @@ enum facebook::react::BorderStyle : uint8_t { Solid, } +enum facebook::react::ColorScheme : uint8_t { + Dark, + Light, +} + enum facebook::react::ColorSpace { DisplayP3, sRGB, @@ -4996,6 +5018,10 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaFeature : uint8_t { + ColorScheme, +} + enum facebook::react::ModalHostViewAnimationType { Fade, None, @@ -5319,6 +5345,18 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalValues { + public bool isOutdatedFor(const facebook::react::MediaFeatures& features) const; + public facebook::react::MediaFeatureSet dependencies; + public facebook::react::MediaFeatures resolvedFor; + public folly::dynamic values; +} + +struct facebook::react::ConditionalValuesResolution { + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalValues; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -5407,6 +5445,12 @@ 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::ColorScheme colorScheme; + public facebook::react::MediaFeatureSet differences(const facebook::react::MediaFeatures& other) const; +} + 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 a86a7e149972..e9114e518faa 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonDebugCxx.api @@ -73,6 +73,9 @@ 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::kConditionalValueKey; +constexpr char* facebook::react::kHasConditionalValuesPropName; +constexpr char* facebook::react::kMediaFeaturesStoreKey; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -107,6 +110,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeatureSet = uint8_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; using facebook::react::RawPropsPropNameHash = uint32_t; @@ -167,6 +171,8 @@ 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::MediaFeatureSet facebook::react::getMediaFeatureDependencies(const folly::dynamic& conditionalValue); +facebook::react::MediaFeatures facebook::react::getMediaFeatures(const facebook::react::ContextContainer* contextContainer); 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 +186,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::resolveConditionalValues(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps, const facebook::react::ContextContainer* contextContainer); 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); @@ -939,6 +947,11 @@ class facebook::react::MapBufferBuilder { public void putString(facebook::react::MapBuffer::Key key, const std::string& value); } +class facebook::react::MediaFeaturesStore { + public facebook::react::MediaFeatures get() const noexcept; + public void set(facebook::react::MediaFeatures features) noexcept; +} + class facebook::react::NativeMethodCallInvoker { public virtual void invokeAsync(const std::string& methodName, facebook::react::NativeMethodCallFunc&& func) noexcept = 0; public virtual void invokeSync(const std::string& methodName, facebook::react::NativeMethodCallFunc&& func) = 0; @@ -950,6 +963,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public 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::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalValues; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -962,6 +976,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; @@ -1033,6 +1048,7 @@ class facebook::react::ShadowNode : public facebook::react::Sealable, public fac public ShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ShadowNode(const facebook::react::ShadowNodeFragment& fragment, facebook::react::ShadowNodeFamily::Shared family, facebook::react::ShadowNodeTraits traits); public bool getHasBeenPromoted() const; + public bool subtreeHasConditionalValues() const; public const facebook::react::ComponentDescriptor& getComponentDescriptor() const; public const facebook::react::Props::Shared& getProps() const; public const facebook::react::ShadowNodeFamily& getFamily() const; @@ -1109,6 +1125,7 @@ enum facebook::react::ShadowNodeTraits::Trait : int32_t { BaselineYogaNode, ChildrenAreShared, ChildrenFormStackingContext, + ChildrenHaveConditionalValues, DirtyYogaNode, ForceFlattenView, FormsStackingContext, @@ -1389,6 +1406,11 @@ enum facebook::react::BorderStyle : uint8_t { Solid, } +enum facebook::react::ColorScheme : uint8_t { + Dark, + Light, +} + enum facebook::react::ColorSpace { DisplayP3, sRGB, @@ -1509,6 +1531,10 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaFeature : uint8_t { + ColorScheme, +} + enum facebook::react::OutlineStyle : uint8_t { Dashed, Dotted, @@ -1784,6 +1810,18 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalValues { + public bool isOutdatedFor(const facebook::react::MediaFeatures& features) const; + public facebook::react::MediaFeatureSet dependencies; + public facebook::react::MediaFeatures resolvedFor; + public folly::dynamic values; +} + +struct facebook::react::ConditionalValuesResolution { + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalValues; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -1858,6 +1896,12 @@ 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::ColorScheme colorScheme; + public facebook::react::MediaFeatureSet differences(const facebook::react::MediaFeatures& other) const; +} + 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 4af89d8221d3..70bf49296355 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonFrameworksCxx.api @@ -85,6 +85,9 @@ 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::kConditionalValueKey; +constexpr char* facebook::react::kHasConditionalValuesPropName; +constexpr char* facebook::react::kMediaFeaturesStoreKey; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr float facebook::react::kDefaultEpsilon; @@ -160,6 +163,7 @@ using facebook::react::LayoutConformanceComponentDescriptor = facebook::react::C using facebook::react::LineMeasureCache = facebook::react::SimpleThreadSafeCache; using facebook::react::LinesMeasurements = std::vector; using facebook::react::Logger = std::function; +using facebook::react::MediaFeatureSet = uint8_t; using facebook::react::MountingTransactionCallback = std::function; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::ParagraphProps = HostPlatformParagraphProps; @@ -326,6 +330,8 @@ 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::MediaFeatureSet facebook::react::getMediaFeatureDependencies(const folly::dynamic& conditionalValue); +facebook::react::MediaFeatures facebook::react::getMediaFeatures(const facebook::react::ContextContainer* contextContainer); 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 +352,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 +362,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::resolveConditionalValues(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps, const facebook::react::ContextContainer* contextContainer); 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); @@ -1630,6 +1638,11 @@ class facebook::react::MapBufferBuilder { public void putString(facebook::react::MapBuffer::Key key, const std::string& value); } +class facebook::react::MediaFeaturesStore { + public facebook::react::MediaFeatures get() const noexcept; + public void set(facebook::react::MediaFeatures features) noexcept; +} + class facebook::react::MergedValueDispatcher { public MergedValueDispatcher(facebook::react::MergedValueDispatcher::DispatchFunction dispatchFunction, facebook::react::MergedValueDispatcher::MergedValueFunction mergedValueFunction); public using DispatchFunction = std::function&&)>; @@ -1887,6 +1900,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public 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::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalValues; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -1899,6 +1913,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; @@ -2142,6 +2157,7 @@ class facebook::react::Scheduler : public facebook::react::UIManagerDelegate { public void removeEventListener(const std::shared_ptr& listener); public void reportMount(facebook::react::SurfaceId surfaceId) const; public void setDelegate(facebook::react::SchedulerDelegate* delegate); + public void setMediaFeatures(facebook::react::MediaFeatures mediaFeatures) const; public void unregisterSurface(const facebook::react::SurfaceHandler& surfaceHandler) const noexcept; public ~Scheduler() override; } @@ -2215,6 +2231,7 @@ class facebook::react::ShadowNode : public facebook::react::Sealable, public fac public ShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ShadowNode(const facebook::react::ShadowNodeFragment& fragment, facebook::react::ShadowNodeFamily::Shared family, facebook::react::ShadowNodeTraits traits); public bool getHasBeenPromoted() const; + public bool subtreeHasConditionalValues() const; public const facebook::react::ComponentDescriptor& getComponentDescriptor() const; public const facebook::react::Props::Shared& getProps() const; public const facebook::react::ShadowNodeFamily& getFamily() const; @@ -2291,6 +2308,7 @@ enum facebook::react::ShadowNodeTraits::Trait : int32_t { BaselineYogaNode, ChildrenAreShared, ChildrenFormStackingContext, + ChildrenHaveConditionalValues, DirtyYogaNode, ForceFlattenView, FormsStackingContext, @@ -2695,6 +2713,7 @@ class facebook::react::UIManager : public facebook::react::ShadowTreeDelegate { public void setComponentDescriptorRegistry(const facebook::react::SharedComponentDescriptorRegistry& componentDescriptorRegistry); public void setDelegate(facebook::react::UIManagerDelegate* delegate); public void setIsJSResponder(const std::shared_ptr& shadowNode, bool isJSResponder, bool blockNativeResponder) const; + public void setMediaFeatures(facebook::react::MediaFeatures mediaFeatures) const; public void setNativeAnimatedDelegate(std::weak_ptr delegate); public void setSurfaceProps(facebook::react::SurfaceId surfaceId, std::string moduleName, folly::dynamic props, facebook::react::DisplayMode displayMode) const noexcept; public void setViewTransitionDelegate(facebook::react::UIManagerViewTransitionDelegate* delegate); @@ -3320,6 +3339,11 @@ enum facebook::react::CSSWideKeyword : std::underlying_type_t conditionalValues; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -4526,6 +4566,12 @@ 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::ColorScheme colorScheme; + public facebook::react::MediaFeatureSet differences(const facebook::react::MediaFeatures& other) const; +} + 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 e2ebd548ac3f..587b1145ad55 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonNewarchCxx.api @@ -73,6 +73,9 @@ 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::kConditionalValueKey; +constexpr char* facebook::react::kHasConditionalValuesPropName; +constexpr char* facebook::react::kMediaFeaturesStoreKey; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -107,6 +110,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeatureSet = uint8_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; using facebook::react::RawPropsPropNameHash = uint32_t; @@ -167,6 +171,8 @@ 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::MediaFeatureSet facebook::react::getMediaFeatureDependencies(const folly::dynamic& conditionalValue); +facebook::react::MediaFeatures facebook::react::getMediaFeatures(const facebook::react::ContextContainer* contextContainer); 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 +186,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::resolveConditionalValues(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps, const facebook::react::ContextContainer* contextContainer); 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); @@ -938,6 +946,11 @@ class facebook::react::MapBufferBuilder { public void putString(facebook::react::MapBuffer::Key key, const std::string& value); } +class facebook::react::MediaFeaturesStore { + public facebook::react::MediaFeatures get() const noexcept; + public void set(facebook::react::MediaFeatures features) noexcept; +} + class facebook::react::NativeMethodCallInvoker { public virtual void invokeAsync(const std::string& methodName, facebook::react::NativeMethodCallFunc&& func) noexcept = 0; public virtual void invokeSync(const std::string& methodName, facebook::react::NativeMethodCallFunc&& func) = 0; @@ -949,6 +962,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public 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::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalValues; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -961,6 +975,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; @@ -1026,6 +1041,7 @@ class facebook::react::ShadowNode : public facebook::react::Sealable, public fac public ShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ShadowNode(const facebook::react::ShadowNodeFragment& fragment, facebook::react::ShadowNodeFamily::Shared family, facebook::react::ShadowNodeTraits traits); public bool getHasBeenPromoted() const; + public bool subtreeHasConditionalValues() const; public const facebook::react::ComponentDescriptor& getComponentDescriptor() const; public const facebook::react::Props::Shared& getProps() const; public const facebook::react::ShadowNodeFamily& getFamily() const; @@ -1102,6 +1118,7 @@ enum facebook::react::ShadowNodeTraits::Trait : int32_t { BaselineYogaNode, ChildrenAreShared, ChildrenFormStackingContext, + ChildrenHaveConditionalValues, DirtyYogaNode, ForceFlattenView, FormsStackingContext, @@ -1382,6 +1399,11 @@ enum facebook::react::BorderStyle : uint8_t { Solid, } +enum facebook::react::ColorScheme : uint8_t { + Dark, + Light, +} + enum facebook::react::ColorSpace { DisplayP3, sRGB, @@ -1502,6 +1524,10 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaFeature : uint8_t { + ColorScheme, +} + enum facebook::react::OutlineStyle : uint8_t { Dashed, Dotted, @@ -1777,6 +1803,18 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalValues { + public bool isOutdatedFor(const facebook::react::MediaFeatures& features) const; + public facebook::react::MediaFeatureSet dependencies; + public facebook::react::MediaFeatures resolvedFor; + public folly::dynamic values; +} + +struct facebook::react::ConditionalValuesResolution { + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalValues; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -1851,6 +1889,12 @@ 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::ColorScheme colorScheme; + public facebook::react::MediaFeatureSet differences(const facebook::react::MediaFeatures& other) const; +} + 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 e2ebd548ac3f..587b1145ad55 100644 --- a/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactCommonReleaseCxx.api @@ -73,6 +73,9 @@ 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::kConditionalValueKey; +constexpr char* facebook::react::kHasConditionalValuesPropName; +constexpr char* facebook::react::kMediaFeaturesStoreKey; constexpr facebook::react::ReactNativeVersionType facebook::react::ReactNativeVersion; constexpr facebook::react::Tag facebook::react::kNoTag; constexpr uint32_t facebook::react::INITIAL_BUCKETS_SIZE; @@ -107,6 +110,7 @@ using facebook::react::GradientDirection = std::variant; +using facebook::react::MediaFeatureSet = uint8_t; using facebook::react::NativeMethodCallFunc = std::function; using facebook::react::PromiseSetupFunctionType = std::function)>; using facebook::react::RawPropsPropNameHash = uint32_t; @@ -167,6 +171,8 @@ 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::MediaFeatureSet facebook::react::getMediaFeatureDependencies(const folly::dynamic& conditionalValue); +facebook::react::MediaFeatures facebook::react::getMediaFeatures(const facebook::react::ContextContainer* contextContainer); 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 +186,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::resolveConditionalValues(const facebook::react::Props* sourceProps, const facebook::react::RawProps& rawProps, const facebook::react::ContextContainer* contextContainer); 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); @@ -938,6 +946,11 @@ class facebook::react::MapBufferBuilder { public void putString(facebook::react::MapBuffer::Key key, const std::string& value); } +class facebook::react::MediaFeaturesStore { + public facebook::react::MediaFeatures get() const noexcept; + public void set(facebook::react::MediaFeatures features) noexcept; +} + class facebook::react::NativeMethodCallInvoker { public virtual void invokeAsync(const std::string& methodName, facebook::react::NativeMethodCallFunc&& func) noexcept = 0; public virtual void invokeSync(const std::string& methodName, facebook::react::NativeMethodCallFunc&& func) = 0; @@ -949,6 +962,7 @@ class facebook::react::Props : public virtual facebook::react::Sealable, public 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::Props& operator=(const facebook::react::Props& other) = delete; + public std::shared_ptr conditionalValues; public std::string nativeId; public using Shared = std::shared_ptr; public virtual ~Props() = default; @@ -961,6 +975,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; @@ -1026,6 +1041,7 @@ class facebook::react::ShadowNode : public facebook::react::Sealable, public fac public ShadowNode(const facebook::react::ShadowNode& sourceShadowNode, const facebook::react::ShadowNodeFragment& fragment); public ShadowNode(const facebook::react::ShadowNodeFragment& fragment, facebook::react::ShadowNodeFamily::Shared family, facebook::react::ShadowNodeTraits traits); public bool getHasBeenPromoted() const; + public bool subtreeHasConditionalValues() const; public const facebook::react::ComponentDescriptor& getComponentDescriptor() const; public const facebook::react::Props::Shared& getProps() const; public const facebook::react::ShadowNodeFamily& getFamily() const; @@ -1102,6 +1118,7 @@ enum facebook::react::ShadowNodeTraits::Trait : int32_t { BaselineYogaNode, ChildrenAreShared, ChildrenFormStackingContext, + ChildrenHaveConditionalValues, DirtyYogaNode, ForceFlattenView, FormsStackingContext, @@ -1382,6 +1399,11 @@ enum facebook::react::BorderStyle : uint8_t { Solid, } +enum facebook::react::ColorScheme : uint8_t { + Dark, + Light, +} + enum facebook::react::ColorSpace { DisplayP3, sRGB, @@ -1502,6 +1524,10 @@ enum facebook::react::LayoutDirection { Undefined, } +enum facebook::react::MediaFeature : uint8_t { + ColorScheme, +} + enum facebook::react::OutlineStyle : uint8_t { Dashed, Dotted, @@ -1777,6 +1803,18 @@ struct facebook::react::ColorStop { public facebook::react::ValueUnit position; } +struct facebook::react::ConditionalValues { + public bool isOutdatedFor(const facebook::react::MediaFeatures& features) const; + public facebook::react::MediaFeatureSet dependencies; + public facebook::react::MediaFeatures resolvedFor; + public folly::dynamic values; +} + +struct facebook::react::ConditionalValuesResolution { + public facebook::react::RawProps rawProps; + public std::shared_ptr conditionalValues; +} + struct facebook::react::CornerRadii { public bool operator==(const facebook::react::CornerRadii& other) const = default; public float horizontal; @@ -1851,6 +1889,12 @@ 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::ColorScheme colorScheme; + public facebook::react::MediaFeatureSet differences(const facebook::react::MediaFeatures& other) const; +} + struct facebook::react::Point { public Float x; public Float y;