From f047c9b42bded6e17b6187726b37d04aa31d12c2 Mon Sep 17 00:00:00 2001 From: Ruslan Shestopalyuk Date: Mon, 4 Aug 2025 05:29:19 -0700 Subject: [PATCH] Remove props that set by default for Text component on JS side (#52905) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/52905 Similarly to [this PR](https://github.com/facebook/react-native/pull/51225), we do it for the Text component now: we don't set any non-default value props (most prominently, the accessibility ones) before passing this to native. This saves bandwidth and potentially improves the prop parsing time, which existing Fantom benchmarks do confirm. This is implemented behind a feature flag, which is false by default (will use it to run an experiment before rolling out). **NOTE:** This implementation forks the whole text component, as suggested by rubennorte, in order to isolate the changes and with the ultimate goal of removing the old version once the experiment is concluded. ## Changelog: [Internal] - Text no longer sets any default accessibility props, which should not result in visible changes in behaviour but may affect snapshot tests. Reviewed By: rubennorte Differential Revision: D79177652 fbshipit-source-id: a39430464fd5edec953b4c91be7ef9620ebd75ac --- packages/react-native/Libraries/Text/Text.js | 760 ++++++++++++------ .../Text/__tests__/Text-benchmark-itest.js | 1 + .../Libraries/Text/__tests__/Text-itest.js | 1 + .../ReactNativeFeatureFlags.config.js | 11 + .../featureflags/ReactNativeFeatureFlags.js | 8 +- 5 files changed, 537 insertions(+), 244 deletions(-) diff --git a/packages/react-native/Libraries/Text/Text.js b/packages/react-native/Libraries/Text/Text.js index b08b8f38506..6c4764e1585 100644 --- a/packages/react-native/Libraries/Text/Text.js +++ b/packages/react-native/Libraries/Text/Text.js @@ -14,6 +14,7 @@ import type {GestureResponderEvent} from '../Types/CoreEventTypes'; import type {NativeTextProps} from './TextNativeComponent'; import type {PressRetentionOffset, TextProps} from './TextProps'; +import * as ReactNativeFeatureFlags from '../../src/private/featureflags/ReactNativeFeatureFlags'; import * as PressabilityDebug from '../Pressability/PressabilityDebug'; import usePressability from '../Pressability/usePressability'; import flattenStyle from '../StyleSheet/flattenStyle'; @@ -35,156 +36,495 @@ type TextForwardRef = React.ElementRef< * * @see https://reactnative.dev/docs/text */ -const TextImpl: component( - ref?: React.RefSetter, - ...props: TextProps -) = ({ - ref: forwardedRef, - accessible, - accessibilityLabel, - accessibilityState, - allowFontScaling, - 'aria-busy': ariaBusy, - 'aria-checked': ariaChecked, - 'aria-disabled': ariaDisabled, - 'aria-expanded': ariaExpanded, - 'aria-label': ariaLabel, - 'aria-selected': ariaSelected, - children, - ellipsizeMode, - disabled, - id, - nativeID, - numberOfLines, - onLongPress, - onPress, - onPressIn, - onPressOut, - onResponderGrant, - onResponderMove, - onResponderRelease, - onResponderTerminate, - onResponderTerminationRequest, - onStartShouldSetResponder, - pressRetentionOffset, - selectable, - selectionColor, - suppressHighlighting, - style, - ...restProps -}: { - ref?: React.RefSetter, - ...TextProps, -}) => { - const _accessibilityLabel = ariaLabel ?? accessibilityLabel; - - let _accessibilityState: ?TextProps['accessibilityState'] = - accessibilityState; - if ( - ariaBusy != null || - ariaChecked != null || - ariaDisabled != null || - ariaExpanded != null || - ariaSelected != null - ) { - if (_accessibilityState != null) { - _accessibilityState = { - busy: ariaBusy ?? _accessibilityState.busy, - checked: ariaChecked ?? _accessibilityState.checked, - disabled: ariaDisabled ?? _accessibilityState.disabled, - expanded: ariaExpanded ?? _accessibilityState.expanded, - selected: ariaSelected ?? _accessibilityState.selected, - }; - } else { - _accessibilityState = { - busy: ariaBusy, - checked: ariaChecked, - disabled: ariaDisabled, - expanded: ariaExpanded, - selected: ariaSelected, - }; +let _TextImpl; +if (ReactNativeFeatureFlags.reduceDefaultPropsInText()) { + const TextImplNoDefaultProps: component( + ref?: React.RefSetter, + ...props: TextProps + ) = ({ + ref: forwardedRef, + accessible, + accessibilityLabel, + accessibilityState, + allowFontScaling, + 'aria-busy': ariaBusy, + 'aria-checked': ariaChecked, + 'aria-disabled': ariaDisabled, + 'aria-expanded': ariaExpanded, + 'aria-label': ariaLabel, + 'aria-selected': ariaSelected, + children, + ellipsizeMode, + disabled, + id, + nativeID, + numberOfLines, + onLongPress, + onPress, + onPressIn, + onPressOut, + onResponderGrant, + onResponderMove, + onResponderRelease, + onResponderTerminate, + onResponderTerminationRequest, + onStartShouldSetResponder, + pressRetentionOffset, + selectable, + selectionColor, + suppressHighlighting, + style, + ...restProps + }: { + ref?: React.RefSetter, + ...TextProps, + }) => { + const processedProps = restProps as { + ...NativeTextProps, + }; + const _accessibilityLabel = ariaLabel ?? accessibilityLabel; + let _accessibilityState: ?TextProps['accessibilityState'] = + accessibilityState; + if ( + ariaBusy != null || + ariaChecked != null || + ariaDisabled != null || + ariaExpanded != null || + ariaSelected != null + ) { + if (_accessibilityState != null) { + _accessibilityState = { + busy: ariaBusy ?? _accessibilityState.busy, + checked: ariaChecked ?? _accessibilityState.checked, + disabled: ariaDisabled ?? _accessibilityState.disabled, + expanded: ariaExpanded ?? _accessibilityState.expanded, + selected: ariaSelected ?? _accessibilityState.selected, + }; + } else { + _accessibilityState = { + busy: ariaBusy, + checked: ariaChecked, + disabled: ariaDisabled, + expanded: ariaExpanded, + selected: ariaSelected, + }; + } } - } - const _accessibilityStateDisabled = _accessibilityState?.disabled; - const _disabled = disabled ?? _accessibilityStateDisabled; + const _accessibilityStateDisabled = _accessibilityState?.disabled; + const _disabled = disabled ?? _accessibilityStateDisabled; - const isPressable = - (onPress != null || - onLongPress != null || - onStartShouldSetResponder != null) && - _disabled !== true; - - // TODO: Move this processing to the view configuration. - const _selectionColor = - selectionColor != null ? processColor(selectionColor) : undefined; - - let _style = style; - if (__DEV__) { - if (PressabilityDebug.isEnabled() && onPress != null) { - _style = [style, {color: 'magenta'}]; + // If the disabled prop and accessibilityState.disabled are out of sync but not both in + // falsy states we need to update the accessibilityState object to use the disabled prop. + if ( + _accessibilityState != null && + _disabled !== _accessibilityStateDisabled && + ((_disabled != null && _disabled !== false) || + (_accessibilityStateDisabled != null && + _accessibilityStateDisabled !== false)) + ) { + _accessibilityState.disabled = _disabled; } - } - let _numberOfLines = numberOfLines; - if (_numberOfLines != null && !(_numberOfLines >= 0)) { + const _accessible = Platform.select({ + ios: accessible !== false, + android: + accessible == null + ? onPress != null || onLongPress != null + : accessible, + default: accessible, + }); + + const isPressable = + (onPress != null || + onLongPress != null || + onStartShouldSetResponder != null) && + _disabled !== true; + + // TODO: Move this processing to the view configuration. + const _selectionColor = + selectionColor != null ? processColor(selectionColor) : undefined; + + let _style = style; if (__DEV__) { - console.error( - `'numberOfLines' in must be a non-negative number, received: ${_numberOfLines}. The value will be set to 0.`, + if (PressabilityDebug.isEnabled() && onPress != null) { + _style = [style, {color: 'magenta'}]; + } + } + + let _numberOfLines = numberOfLines; + if (_numberOfLines != null && !(_numberOfLines >= 0)) { + if (__DEV__) { + console.error( + `'numberOfLines' in must be a non-negative number, received: ${_numberOfLines}. The value will be set to 0.`, + ); + } + _numberOfLines = 0; + } + + let _selectable = selectable; + + let processedStyle = flattenStyle(_style); + if (processedStyle != null) { + let overrides: ?{...TextStyleInternal} = null; + if (typeof processedStyle.fontWeight === 'number') { + overrides = overrides || ({}: {...TextStyleInternal}); + overrides.fontWeight = + // $FlowFixMe[incompatible-cast] + (String(processedStyle.fontWeight): TextStyleInternal['fontWeight']); + } + + if (processedStyle.userSelect != null) { + _selectable = userSelectToSelectableMap[processedStyle.userSelect]; + overrides = overrides || ({}: {...TextStyleInternal}); + overrides.userSelect = undefined; + } + + if (processedStyle.verticalAlign != null) { + overrides = overrides || ({}: {...TextStyleInternal}); + overrides.textAlignVertical = + verticalAlignToTextAlignVerticalMap[processedStyle.verticalAlign]; + overrides.verticalAlign = undefined; + } + + if (overrides != null) { + // $FlowFixMe[incompatible-type] + _style = [_style, overrides]; + } + } + + const _nativeID = id ?? nativeID; + + if (_accessibilityLabel !== undefined) { + processedProps.accessibilityLabel = _accessibilityLabel; + } + if (_accessibilityState !== undefined) { + processedProps.accessibilityState = _accessibilityState; + } + if (_nativeID !== undefined) { + processedProps.nativeID = _nativeID; + } + if (_numberOfLines !== undefined) { + processedProps.numberOfLines = _numberOfLines; + } + if (_selectable !== undefined) { + processedProps.selectable = _selectable; + } + if (_style !== undefined) { + processedProps.style = _style; + } + if (_selectionColor !== undefined) { + processedProps.selectionColor = _selectionColor; + } + + let textPressabilityProps: ?TextPressabilityProps; + if (isPressable) { + textPressabilityProps = { + onLongPress, + onPress, + onPressIn, + onPressOut, + onResponderGrant, + onResponderMove, + onResponderRelease, + onResponderTerminate, + onResponderTerminationRequest, + onStartShouldSetResponder, + pressRetentionOffset, + suppressHighlighting, + }; + } + + const hasTextAncestor = useContext(TextAncestorContext); + if (hasTextAncestor) { + processedProps.disabled = disabled; + processedProps.children = children; + if (isPressable) { + return ( + + ); + } + return ; + } + + let nativeText = null; + + processedProps.accessible = _accessible; + processedProps.allowFontScaling = allowFontScaling !== false; + processedProps.disabled = _disabled; + processedProps.ellipsizeMode = ellipsizeMode ?? 'tail'; + processedProps.children = children; + + if (isPressable) { + nativeText = ( + + ); + } else { + nativeText = ; + } + + if (children == null) { + return nativeText; + } + + // If the children do not contain a JSX element it would not be possible to have a + // nested `Text` component so we can skip adding the `TextAncestorContext` context wrapper + // which has a performance overhead. Since we do this for performance reasons we need + // to keep the check simple to avoid regressing overall perf. For this reason the + // `children.length` constant is set to `3`, this should be a reasonable tradeoff + // to capture the majority of `Text` uses but also not make this check too expensive. + if (Array.isArray(children) && children.length <= 3) { + let hasNonTextChild = false; + for (let child of children) { + if (child != null && typeof child === 'object') { + hasNonTextChild = true; + break; + } + } + if (!hasNonTextChild) { + return nativeText; + } + } else if (typeof children !== 'object') { + return nativeText; + } + + return {nativeText}; + }; + _TextImpl = TextImplNoDefaultProps; +} else { + const TextImplLegacy: component( + ref?: React.RefSetter, + ...props: TextProps + ) = ({ + ref: forwardedRef, + accessible, + accessibilityLabel, + accessibilityState, + allowFontScaling, + 'aria-busy': ariaBusy, + 'aria-checked': ariaChecked, + 'aria-disabled': ariaDisabled, + 'aria-expanded': ariaExpanded, + 'aria-label': ariaLabel, + 'aria-selected': ariaSelected, + children, + ellipsizeMode, + disabled, + id, + nativeID, + numberOfLines, + onLongPress, + onPress, + onPressIn, + onPressOut, + onResponderGrant, + onResponderMove, + onResponderRelease, + onResponderTerminate, + onResponderTerminationRequest, + onStartShouldSetResponder, + pressRetentionOffset, + selectable, + selectionColor, + suppressHighlighting, + style, + ...restProps + }: { + ref?: React.RefSetter, + ...TextProps, + }) => { + const _accessibilityLabel = ariaLabel ?? accessibilityLabel; + + let _accessibilityState: ?TextProps['accessibilityState'] = + accessibilityState; + if ( + ariaBusy != null || + ariaChecked != null || + ariaDisabled != null || + ariaExpanded != null || + ariaSelected != null + ) { + if (_accessibilityState != null) { + _accessibilityState = { + busy: ariaBusy ?? _accessibilityState.busy, + checked: ariaChecked ?? _accessibilityState.checked, + disabled: ariaDisabled ?? _accessibilityState.disabled, + expanded: ariaExpanded ?? _accessibilityState.expanded, + selected: ariaSelected ?? _accessibilityState.selected, + }; + } else { + _accessibilityState = { + busy: ariaBusy, + checked: ariaChecked, + disabled: ariaDisabled, + expanded: ariaExpanded, + selected: ariaSelected, + }; + } + } + + const _accessibilityStateDisabled = _accessibilityState?.disabled; + const _disabled = disabled ?? _accessibilityStateDisabled; + + const isPressable = + (onPress != null || + onLongPress != null || + onStartShouldSetResponder != null) && + _disabled !== true; + + // TODO: Move this processing to the view configuration. + const _selectionColor = + selectionColor != null ? processColor(selectionColor) : undefined; + + let _style = style; + if (__DEV__) { + if (PressabilityDebug.isEnabled() && onPress != null) { + _style = [style, {color: 'magenta'}]; + } + } + + let _numberOfLines = numberOfLines; + if (_numberOfLines != null && !(_numberOfLines >= 0)) { + if (__DEV__) { + console.error( + `'numberOfLines' in must be a non-negative number, received: ${_numberOfLines}. The value will be set to 0.`, + ); + } + _numberOfLines = 0; + } + + let _selectable = selectable; + + let processedStyle = flattenStyle(_style); + if (processedStyle != null) { + let overrides: ?{...TextStyleInternal} = null; + if (typeof processedStyle.fontWeight === 'number') { + overrides = overrides || ({}: {...TextStyleInternal}); + overrides.fontWeight = + // $FlowFixMe[incompatible-cast] + (processedStyle.fontWeight.toString(): TextStyleInternal['fontWeight']); + } + + if (processedStyle.userSelect != null) { + _selectable = userSelectToSelectableMap[processedStyle.userSelect]; + overrides = overrides || ({}: {...TextStyleInternal}); + overrides.userSelect = undefined; + } + + if (processedStyle.verticalAlign != null) { + overrides = overrides || ({}: {...TextStyleInternal}); + overrides.textAlignVertical = + verticalAlignToTextAlignVerticalMap[processedStyle.verticalAlign]; + overrides.verticalAlign = undefined; + } + + if (overrides != null) { + // $FlowFixMe[incompatible-type] + _style = [_style, overrides]; + } + } + + const _nativeID = id ?? nativeID; + + const hasTextAncestor = useContext(TextAncestorContext); + if (hasTextAncestor) { + if (isPressable) { + return ( + + ); + } + + return ( + + {children} + ); } - _numberOfLines = 0; - } - let _selectable = selectable; - - let processedStyle = flattenStyle(_style); - if (processedStyle != null) { - let overrides: ?{...TextStyleInternal} = null; - if (typeof processedStyle.fontWeight === 'number') { - overrides = overrides || ({}: {...TextStyleInternal}); - overrides.fontWeight = - // $FlowFixMe[incompatible-cast] - (processedStyle.fontWeight.toString(): TextStyleInternal['fontWeight']); + // If the disabled prop and accessibilityState.disabled are out of sync but not both in + // falsy states we need to update the accessibilityState object to use the disabled prop. + if ( + _disabled !== _accessibilityStateDisabled && + ((_disabled != null && _disabled !== false) || + (_accessibilityStateDisabled != null && + _accessibilityStateDisabled !== false)) + ) { + _accessibilityState = {..._accessibilityState, disabled: _disabled}; } - if (processedStyle.userSelect != null) { - _selectable = userSelectToSelectableMap[processedStyle.userSelect]; - overrides = overrides || ({}: {...TextStyleInternal}); - overrides.userSelect = undefined; - } + const _accessible = Platform.select({ + ios: accessible !== false, + android: + accessible == null + ? onPress != null || onLongPress != null + : accessible, + default: accessible, + }); - if (processedStyle.verticalAlign != null) { - overrides = overrides || ({}: {...TextStyleInternal}); - overrides.textAlignVertical = - verticalAlignToTextAlignVerticalMap[processedStyle.verticalAlign]; - overrides.verticalAlign = undefined; - } - - if (overrides != null) { - // $FlowFixMe[incompatible-type] - _style = [_style, overrides]; - } - } - - const _nativeID = id ?? nativeID; - - const hasTextAncestor = useContext(TextAncestorContext); - if (hasTextAncestor) { + let nativeText = null; if (isPressable) { - return ( - ); + } else { + nativeText = ( + + {children} + + ); } - return ( - - {children} - - ); - } - - // If the disabled prop and accessibilityState.disabled are out of sync but not both in - // falsy states we need to update the accessibilityState object to use the disabled prop. - if ( - _disabled !== _accessibilityStateDisabled && - ((_disabled != null && _disabled !== false) || - (_accessibilityStateDisabled != null && - _accessibilityStateDisabled !== false)) - ) { - _accessibilityState = {..._accessibilityState, disabled: _disabled}; - } - - const _accessible = Platform.select({ - ios: accessible !== false, - android: - accessible == null ? onPress != null || onLongPress != null : accessible, - default: accessible, - }); - - let nativeText = null; - if (isPressable) { - nativeText = ( - - ); - } else { - nativeText = ( - - {children} - - ); - } - - if (children == null) { - return nativeText; - } - - // If the children do not contain a JSX element it would not be possible to have a - // nested `Text` component so we can skip adding the `TextAncestorContext` context wrapper - // which has a performance overhead. Since we do this for performance reasons we need - // to keep the check simple to avoid regressing overall perf. For this reason the - // `children.length` constant is set to `3`, this should be a reasonable tradeoff - // to capture the majority of `Text` uses but also not make this check too expensive. - if (Array.isArray(children) && children.length <= 3) { - let hasNonTextChild = false; - for (let child of children) { - if (child != null && typeof child === 'object') { - hasNonTextChild = true; - break; - } - } - if (!hasNonTextChild) { + if (children == null) { return nativeText; } - } else if (typeof children !== 'object') { - return nativeText; - } - return {nativeText}; -}; + // If the children do not contain a JSX element it would not be possible to have a + // nested `Text` component so we can skip adding the `TextAncestorContext` context wrapper + // which has a performance overhead. Since we do this for performance reasons we need + // to keep the check simple to avoid regressing overall perf. For this reason the + // `children.length` constant is set to `3`, this should be a reasonable tradeoff + // to capture the majority of `Text` uses but also not make this check too expensive. + if (Array.isArray(children) && children.length <= 3) { + let hasNonTextChild = false; + for (let child of children) { + if (child != null && typeof child === 'object') { + hasNonTextChild = true; + break; + } + } + if (!hasNonTextChild) { + return nativeText; + } + } else if (typeof children !== 'object') { + return nativeText; + } + + return {nativeText}; + }; + _TextImpl = TextImplLegacy; +} + +const TextImpl: component( + ref?: React.RefSetter, + ...props: TextProps +) = _TextImpl; TextImpl.displayName = 'Text'; diff --git a/packages/react-native/Libraries/Text/__tests__/Text-benchmark-itest.js b/packages/react-native/Libraries/Text/__tests__/Text-benchmark-itest.js index 58d21271417..69e48c66524 100644 --- a/packages/react-native/Libraries/Text/__tests__/Text-benchmark-itest.js +++ b/packages/react-native/Libraries/Text/__tests__/Text-benchmark-itest.js @@ -6,6 +6,7 @@ * * @flow strict-local * @format + * @fantom_flags reduceDefaultPropsInText:* */ import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; diff --git a/packages/react-native/Libraries/Text/__tests__/Text-itest.js b/packages/react-native/Libraries/Text/__tests__/Text-itest.js index c6f94ea3e0d..c16ff81ade1 100644 --- a/packages/react-native/Libraries/Text/__tests__/Text-itest.js +++ b/packages/react-native/Libraries/Text/__tests__/Text-itest.js @@ -6,6 +6,7 @@ * * @flow strict-local * @format + * @fantom_flags reduceDefaultPropsInText:* */ import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment'; diff --git a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js index bfb8ad04bef..bfac428c842 100644 --- a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js +++ b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js @@ -839,6 +839,17 @@ const definitions: FeatureFlagDefinitions = { }, ossReleaseStage: 'none', }, + reduceDefaultPropsInText: { + defaultValue: false, + metadata: { + dateAdded: '2025-07-25', + description: + 'Optimize how default props are processed in Text to avoid unnecessary keys.', + expectedReleaseValue: true, + purpose: 'experimentation', + }, + ossReleaseStage: 'none', + }, shouldUseAnimatedObjectForTransform: { defaultValue: false, metadata: { diff --git a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js index 6cba117a58e..c8d9bb946ab 100644 --- a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js +++ b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<<1c1248c26a59331017b9cd56763557cc>> + * @generated SignedSource<<24a5d3213cbc7cd101d34e059ba5c8c4>> * @flow strict * @noformat */ @@ -35,6 +35,7 @@ export type ReactNativeFeatureFlagsJsOnly = $ReadOnly<{ enableAccessToHostTreeInFabric: Getter, fixVirtualizeListCollapseWindowSize: Getter, isLayoutAnimationEnabled: Getter, + reduceDefaultPropsInText: Getter, shouldUseAnimatedObjectForTransform: Getter, shouldUseRemoveClippedSubviewsAsDefaultOnIOS: Getter, shouldUseSetNativePropsInFabric: Getter, @@ -150,6 +151,11 @@ export const fixVirtualizeListCollapseWindowSize: Getter = createJavaSc */ export const isLayoutAnimationEnabled: Getter = createJavaScriptFlagGetter('isLayoutAnimationEnabled', true); +/** + * Optimize how default props are processed in Text to avoid unnecessary keys. + */ +export const reduceDefaultPropsInText: Getter = createJavaScriptFlagGetter('reduceDefaultPropsInText', false); + /** * Enables use of AnimatedObject for animating transform values. */