From 6bc12b3f327833ed42f43c0abce1d5eace311b28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nishan=20=28o=5E=E2=96=BD=5Eo=29?= Date: Wed, 18 Nov 2026 19:50:05 +0530 Subject: [PATCH] Add types and an RNTester example for conditional style values --- .../Animated/components/AnimatedScrollView.js | 7 +- .../Libraries/StyleSheet/StyleSheetTypes.js | 48 ++++- .../Libraries/StyleSheet/splitLayoutProps.js | 15 +- packages/react-native/ReactNativeApi.d.ts | 166 ++++++++++-------- packages/react-native/__typetests__/index.tsx | 4 +- .../stylesheet-conditional-values.tsx | 65 +++++++ .../__typetests__/tsconfig.legacy.json | 4 +- .../MediaQueries/MediaQueriesExample.js | 161 +++++++++++++++++ .../js/utils/RNTesterList.android.js | 5 + .../rn-tester/js/utils/RNTesterList.ios.js | 4 + 10 files changed, 394 insertions(+), 85 deletions(-) create mode 100644 packages/react-native/__typetests__/stylesheet-conditional-values.tsx create mode 100644 packages/rn-tester/js/examples/MediaQueries/MediaQueriesExample.js diff --git a/packages/react-native/Libraries/Animated/components/AnimatedScrollView.js b/packages/react-native/Libraries/Animated/components/AnimatedScrollView.js index 4e0f09a3d3bb..80a7502169cd 100644 --- a/packages/react-native/Libraries/Animated/components/AnimatedScrollView.js +++ b/packages/react-native/Libraries/Animated/components/AnimatedScrollView.js @@ -8,7 +8,10 @@ * @format */ -import type {ViewStyle} from '../../StyleSheet/StyleSheetTypes'; +import type { + ViewStyle, + WithConditionalStyleValues, +} from '../../StyleSheet/StyleSheetTypes'; import type { AnimatedComponentType, AnimatedProps, @@ -96,7 +99,7 @@ const AnimatedScrollViewWithInvertedRefreshControl = // Handle animated props on `refreshControl`. const [refreshControlAnimatedProps, refreshControlRef] = useAnimatedProps< - {style: ?ViewStyle}, + {style: ?WithConditionalStyleValues}, $FlowFixMe, >(intermediatePropsForRefreshControl); // NOTE: Assumes that refreshControl.ref` and `refreshControl.style` can be diff --git a/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js b/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js index 1c23024fec6e..28a221cb9d1c 100644 --- a/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js +++ b/packages/react-native/Libraries/StyleSheet/StyleSheetTypes.js @@ -42,6 +42,42 @@ export type DimensionValue = number | string | 'auto' | null; export type CursorValue = 'auto' | 'pointer'; +/** + * A style value that depends on media queries. The value of the last matching + * query is used, or the `default` value if no query matches. Supported media + * query: `@media (prefers-color-scheme: light | dark)`. + * + * ``` + * backgroundColor: { + * default: 'white', + * '@media (prefers-color-scheme: dark)': 'black', + * } + * ``` + */ +export type ConditionalStyleValue = Readonly<{ + default: T, + '@media (prefers-color-scheme: light)'?: T, + '@media (prefers-color-scheme: dark)'?: T, +}>; + +// Components convert these style props in JavaScript, so they do not support +// conditional values yet. +type ____StylePropsWithoutConditionalValues_Internal = + 'objectFit' | 'resizeMode' | 'tintColor' | 'userSelect' | 'verticalAlign'; + +/** + * A style object in which each value can be a `ConditionalStyleValue`. + */ +export type WithConditionalStyleValues = T extends {...} + ? { + readonly [ + K in keyof T + ]: K extends ____StylePropsWithoutConditionalValues_Internal + ? T[K] + : T[K] | ConditionalStyleValue, + } + : T; + /** * React Native's layout system is based on Flexbox and is powered both * on iOS and Android by an open source project called `Yoga`: @@ -1141,7 +1177,13 @@ export type ____DangerouslyImpreciseStyle_Internal = Readonly<{ }>; export type StyleProp = - null | void | T | false | '' | ReadonlyArray>; + | null + | void + | T + | WithConditionalStyleValues + | false + | '' + | ReadonlyArray>; export type ____DangerouslyImpreciseStyleProp_Internal = StyleProp< Partial<____DangerouslyImpreciseStyle_Internal>, @@ -1161,7 +1203,9 @@ export type ____ImageStyleProp_Internal = StyleProp< >; export type ____Styles_Internal = { - readonly [key: string]: Partial<____DangerouslyImpreciseStyle_Internal>, + readonly [key: string]: Partial< + WithConditionalStyleValues<____DangerouslyImpreciseStyle_Internal>, + >, ... }; diff --git a/packages/react-native/Libraries/StyleSheet/splitLayoutProps.js b/packages/react-native/Libraries/StyleSheet/splitLayoutProps.js index 16dc8d04643a..501fcd7b4a9d 100644 --- a/packages/react-native/Libraries/StyleSheet/splitLayoutProps.js +++ b/packages/react-native/Libraries/StyleSheet/splitLayoutProps.js @@ -8,16 +8,17 @@ * @format */ -import type {ViewStyle} from './StyleSheetTypes'; +import type {ViewStyle, WithConditionalStyleValues} from './StyleSheetTypes'; -type MutableViewStyle = {-readonly [K in keyof ViewStyle]: ViewStyle[K]}; +type Style = WithConditionalStyleValues; +type MutableStyle = {-readonly [K in keyof Style]: Style[K]}; -export default function splitLayoutProps(props: ?ViewStyle): { - outer: ?ViewStyle, - inner: ?ViewStyle, +export default function splitLayoutProps(props: ?Style): { + outer: ?Style, + inner: ?Style, } { - let outer: ?MutableViewStyle = null; - let inner: ?MutableViewStyle = null; + let outer: ?MutableStyle = null; + let inner: ?MutableStyle = null; if (props != null) { outer = {}; diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index 55e761e65927..80330a9dd009 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -4,7 +4,7 @@ * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * - * @generated SignedSource<> + * @generated SignedSource<<077513a92d14b8bcd0000dedd7c1cc52>> * * This file was generated by scripts/js-api/build-types/index.js. */ @@ -737,8 +737,12 @@ declare type ____ShadowStyle_InternalCore = { readonly shadowRadius?: number } declare type ____ShadowStyle_InternalOverrides = {} +declare type ____StylePropsWithoutConditionalValues_Internal = + "objectFit" | "resizeMode" | "tintColor" | "userSelect" | "verticalAlign" declare type ____Styles_Internal = { - readonly [key: string]: Partial<____DangerouslyImpreciseStyle_Internal> + readonly [key: string]: Partial< + WithConditionalStyleValues<____DangerouslyImpreciseStyle_Internal> + > } declare type ____TextStyle_InternalBase = { readonly color?: ____ColorValue_Internal @@ -1799,6 +1803,11 @@ declare type CompositeAnimation = { start: (callback?: EndCallback | undefined, isLooping?: boolean) => void stop: () => void } +declare type ConditionalStyleValue = { + readonly "@media (prefers-color-scheme: dark)"?: T + readonly "@media (prefers-color-scheme: light)"?: T + readonly default: T +} declare function configureNext( config: LayoutAnimationConfig, onAnimationDidEnd?: OnAnimationDidEndCallback, @@ -4882,7 +4891,13 @@ declare type StickyHeaderComponentType = ( }, ) => React.ReactNode declare type StyleProp = - "" | false | null | ReadonlyArray> | T | void + | "" + | false + | null + | ReadonlyArray> + | T + | void + | WithConditionalStyleValues declare namespace StyleSheet { export { AbsoluteFillStyle, @@ -5856,6 +5871,15 @@ declare type WithAnimatedValue = T extends Builtin | Nullable : T extends {} ? { readonly [K in keyof T]: WithAnimatedValue } : T +declare type WithConditionalStyleValues = T extends {} + ? { + readonly [ + K in keyof T + ]: K extends ____StylePropsWithoutConditionalValues_Internal + ? T[K] + : ConditionalStyleValue | T[K] + } + : T declare type WithDefault< Type extends DefaultTypes, Value extends (null | Type | undefined) | string, @@ -5877,24 +5901,24 @@ export { AccessibilityValue, // cf8bcb74 ActionSheetIOS, // b558559e ActionSheetIOSOptions, // 1756eb5a - ActivityIndicator, // 81cc132f + ActivityIndicator, // ce714e1a ActivityIndicatorInstance, // 69299e35 - ActivityIndicatorProps, // 2b51f177 + ActivityIndicatorProps, // 7b655304 Alert, // a398a509 AlertButton, // bf1a3b60 AlertButtonStyle, // ec9fb242 AlertOptions, // 8a116d2a AlertType, // 5ab91217 AndroidKeyboardEvent, // e03becc8 - Animated, // 4dd69575 - AnimatedFlatList, // 2605f07c - AnimatedImage, // f63d372c - AnimatedScrollView, // f109a9f5 - AnimatedSectionList, // cc26f27d - AnimatedText, // 7deca110 - AnimatedView, // 0e3634b9 + Animated, // d1866f70 + AnimatedFlatList, // e2d9584e + AnimatedImage, // f880cfc7 + AnimatedScrollView, // 19a2a905 + AnimatedSectionList, // f04774e3 + AnimatedText, // 3a7f7124 + AnimatedView, // 3d28204f AppConfig, // 80afc5fa - AppRegistry, // a9925121 + AppRegistry, // 64ec476d AppState, // db34d225 AppStateEvent, // 80f034c3 AppStateStatus, // 447e5ef2 @@ -5906,8 +5930,8 @@ export { BackPressEventName, // 4620fb76 BlurEvent, // 00c596e2 BoxShadowValue, // b679703f - Button, // 8a7997de - ButtonInstance, // 6c48e56a + Button, // d28d5c38 + ButtonInstance, // f16af139 ButtonProps, // 2fe658e4 CodegenTypes, // d0052fd4 ColorSchemeName, // 6615edd6 @@ -5925,9 +5949,9 @@ export { DimensionsPayload, // 653bc26c DisplayMetrics, // 1dc35cef DisplayMetricsAndroid, // 872e62eb - DrawerLayoutAndroid, // abc2dddb + DrawerLayoutAndroid, // ef828c83 DrawerLayoutAndroidInstance, // aa243cbf - DrawerLayoutAndroidProps, // c8e55522 + DrawerLayoutAndroidProps, // ffd27d18 DrawerSlideEvent, // aa703fa0 DropShadowValue, // e9df2606 DynamicColorIOS, // d96c228c @@ -5943,9 +5967,9 @@ export { EventSubscription, // b8d084aa ExtendedExceptionData, // 5a6ccf5a FilterFunction, // bf24c0e3 - FlatList, // aa91c262 - FlatListInstance, // 6af65728 - FlatListProps, // 79ea1720 + FlatList, // 0a6e978b + FlatListInstance, // a5f5af52 + FlatListProps, // 421ed36d FocusEvent, // f7d67f9b FontVariant, // 7c7558bb GestureResponderEvent, // cbf6abac @@ -5956,17 +5980,17 @@ export { IEventEmitter, // fbef6131 IOSKeyboardEvent, // e67bfe3a IgnorePattern, // ec6f6ece - Image, // e360cc3c - ImageBackground, // 326ef608 - ImageBackgroundInstance, // 9d0784f1 - ImageBackgroundProps, // aaeb56b7 + Image, // 38474883 + ImageBackground, // a0dfaf4b + ImageBackgroundInstance, // a63a6787 + ImageBackgroundProps, // fd2dcf72 ImageErrorEvent, // e2926c20 ImageInstance, // 46f8deb7 ImageLoadEvent, // 9b52ad36 ImageProgressEventIOS, // a97c3831 - ImageProps, // 5c47ecaa + ImageProps, // 28bfe74a ImagePropsAndroid, // 283349a4 - ImagePropsBase, // cd629db8 + ImagePropsBase, // 8f083f98 ImagePropsIOS, // 4f29f905 ImageRequireSource, // 681d683b ImageResizeMode, // d51106e2 @@ -5976,17 +6000,17 @@ export { ImageSourcePropType, // ff97c174 ImageStyle, // 2112f35d ImageURISource, // 9bf63692 - InputAccessoryView, // 0416dc2b - InputAccessoryViewProps, // 9ade9e08 + InputAccessoryView, // 17d4c7b9 + InputAccessoryViewProps, // 6d8e16af InputModeOptions, // 4e8581b9 Insets, // e7fe432a KeyDownEvent, // ccd5ec9d KeyEvent, // 20fa4267 KeyUpEvent, // e45aac1c Keyboard, // a26f7bd4 - KeyboardAvoidingView, // 9c54a914 - KeyboardAvoidingViewInstance, // bd0b2937 - KeyboardAvoidingViewProps, // a1a3a411 + KeyboardAvoidingView, // b1528565 + KeyboardAvoidingViewInstance, // 34d06100 + KeyboardAvoidingViewProps, // 5f134336 KeyboardEvent, // c3f895d4 KeyboardEventEasing, // af4091c8 KeyboardEventName, // 59299ad6 @@ -6011,10 +6035,10 @@ export { MeasureInWindowOnSuccessCallback, // a285f598 MeasureLayoutOnSuccessCallback, // 3592502a MeasureOnSuccessCallback, // 82824e59 - Modal, // b7648910 + Modal, // 7352893b ModalBaseProps, // 18ba4525 ModalInstance, // c47ff608 - ModalProps, // be55116f + ModalProps, // 81a1d6dc ModalPropsAndroid, // 515fb173 ModalPropsIOS, // 7943cbd7 ModeChangeEvent, // 9e9a28c4 @@ -6050,15 +6074,15 @@ export { PointerEvent, // a3d953b4 PressabilityConfig, // 5a09717f PressabilityEventHandlers, // 4ffc75dd - Pressable, // f6c4d92e + Pressable, // 8bbf7913 PressableAndroidRippleConfig, // ee32eaca PressableInstance, // 4f7bc23d - PressableProps, // ea4c9958 + PressableProps, // ed7c1bcb PressableStateCallbackType, // f83728cd ProcessedColorValue, // 33f74304 - ProgressBarAndroid, // c12b1742 + ProgressBarAndroid, // 6e65d71c ProgressBarAndroidInstance, // e049fddf - ProgressBarAndroidProps, // 8a020f5a + ProgressBarAndroidProps, // 02f95959 PublicRootInstance, // 8040afd7 PublicTextInstance, // ab85b323 PushNotificationEventName, // 84e7e150 @@ -6066,9 +6090,9 @@ export { PushNotificationPermissions, // c2e7ae4f Rationale, // 5df1b1c1 ReactNativeVersion, // abd76827 - RefreshControl, // 55f62de8 - RefreshControlInstance, // 55db681a - RefreshControlProps, // 9c641fc3 + RefreshControl, // 708cf86d + RefreshControlInstance, // f116ea0d + RefreshControlProps, // 2823fb53 RefreshControlPropsAndroid, // 8ac931ca RefreshControlPropsIOS, // 72a36381 Registry, // e7beb42e @@ -6077,29 +6101,29 @@ export { Role, // af7b889d RootTag, // 3cd10504 RootTagContext, // 38bfc8f6 - RootViewStyleProvider, // 8aa32d1d + RootViewStyleProvider, // fdabc65b Runnable, // 557d13d9 Runnables, // 75114853 SafeAreaInsets, // 64d7a605 SafeAreaInsetsChangeEvent, // ecf5a1e0 - SafeAreaView, // a8dabc19 + SafeAreaView, // c0b672ea SafeAreaViewInstance, // a873bd17 ScaledSize, // 07e417c7 ScrollEvent, // 8dfaa310 - ScrollResponderType, // 13abef1e + ScrollResponderType, // 5b37502d ScrollToLocationParamsType, // d7ecdad1 - ScrollView, // d79523d5 - ScrollViewImperativeMethods, // 01ed395a - ScrollViewInstance, // 265c5675 - ScrollViewProps, // edd205bf + ScrollView, // 423f57f9 + ScrollViewImperativeMethods, // 8f6dcb29 + ScrollViewInstance, // acd43af4 + ScrollViewProps, // 1e99b56a ScrollViewPropsAndroid, // 02f3df2e ScrollViewPropsIOS, // e93686bd ScrollViewScrollToOptions, // 3313411e SectionBase, // 9f13db00 - SectionList, // 4de421b9 + SectionList, // 9ab5bef2 SectionListData, // 1a4de01a - SectionListInstance, // aec01410 - SectionListProps, // 8014499f + SectionListInstance, // 96675fed + SectionListProps, // a16b03c0 SectionListRenderItem, // 715b2086 SectionListRenderItemInfo, // 4a48a922 Separators, // 6a45f7e3 @@ -6116,20 +6140,20 @@ export { StatusBarProps, // c2a44d88 StatusBarStyle, // 78f53eea StatusBarVerticalBarEdgeIOS, // f0ffbe54 - StyleProp, // fa0e9b4a - StyleSheet, // 72b902eb + StyleProp, // 1d254554 + StyleSheet, // 1f4e419a SubmitBehavior, // c4ddf490 - Switch, // 7abe9e91 + Switch, // 1cd2e1f1 SwitchChangeEvent, // 459b3e36 SwitchInstance, // f17ba6e8 - SwitchProps, // ca5b3312 + SwitchProps, // 663f47ac Systrace, // 2a0a0871 TVViewPropsIOS, // 1c612e4e TargetedEvent, // 16e98910 TaskProvider, // 266dedf2 - Text, // 9bbb7bc0 + Text, // 8bbf6590 TextContentType, // 239b3ecc - TextInput, // 153a9b12 + TextInput, // b68bd5ae TextInputAndroidProps, // 9ebbc103 TextInputBlurEvent, // ac0d8a35 TextInputChangeEvent, // 4123dc4d @@ -6139,34 +6163,34 @@ export { TextInputIOSProps, // fb3c9327 TextInputInstance, // e5cb59ab TextInputKeyPressEvent, // 5b603a00 - TextInputProps, // 75ee72bb + TextInputProps, // 122856bf TextInputSelectionChangeEvent, // 817bea8a TextInputSubmitEditingEvent, // 260f6e41 TextInstance, // c927e793 TextLayoutEvent, // e9765128 - TextProps, // 325e93b5 + TextProps, // 85e9bf01 TextStyle, // 55ea5e42 ToastAndroid, // 88a8969a - TouchableHighlight, // 0a900542 + TouchableHighlight, // 23a6a0c3 TouchableHighlightInstance, // 7fb6781a - TouchableHighlightProps, // d0b13d30 - TouchableNativeFeedback, // 06d2a186 - TouchableNativeFeedbackInstance, // bb702365 - TouchableNativeFeedbackProps, // 9e5a4301 - TouchableOpacity, // 4dac793e + TouchableHighlightProps, // 56faca35 + TouchableNativeFeedback, // 51ab15f3 + TouchableNativeFeedbackInstance, // 986b5ba9 + TouchableNativeFeedbackProps, // da8c17e6 + TouchableOpacity, // 8f90e6ba TouchableOpacityInstance, // dca89710 - TouchableOpacityProps, // 3f196747 - TouchableWithoutFeedback, // a3d824c8 - TouchableWithoutFeedbackProps, // d8cd87af + TouchableOpacityProps, // b59a22ca + TouchableWithoutFeedback, // ae2bd744 + TouchableWithoutFeedbackProps, // 8ecae654 TransformsStyle, // 65e70f18 TurboModule, // dfe29706 TurboModuleRegistry, // 4ace6db2 UIManager, // 6a18fc05 UTFSequence, // ad625158 Vibration, // 31e4bbf8 - View, // 6f621139 + View, // 029e896c ViewInstance, // 9caf25c4 - ViewProps, // e658159c + ViewProps, // b9a80920 ViewPropsAndroid, // dada44cc ViewPropsIOS, // 58ee19bf ViewStyle, // ab163328 @@ -6175,10 +6199,10 @@ export { VirtualViewMode, // 6be59722 VirtualizedList, // 68c7345e VirtualizedListInstance, // 423ee7c0 - VirtualizedListProps, // 99dbfb7b + VirtualizedListProps, // f1743c55 VirtualizedSectionList, // 9fd9cd61 VirtualizedSectionListInstance, // 12b706d5 - VirtualizedSectionListProps, // 33ba4135 + VirtualizedSectionListProps, // 77ebe873 WrapperComponentProvider, // 6ce47ba4 codegenNativeCommands, // 322f3f4e codegenNativeComponent, // 162426af diff --git a/packages/react-native/__typetests__/index.tsx b/packages/react-native/__typetests__/index.tsx index 75e5dce1634c..955a24d2c186 100644 --- a/packages/react-native/__typetests__/index.tsx +++ b/packages/react-native/__typetests__/index.tsx @@ -1896,9 +1896,9 @@ DynamicColorIOS({ // Test you cannot set internals of ColorValue directly const OpaqueTest1 = () => ( ( const OpaqueTest2 = () => ( + + + + ); +} + +StyleSheet.create({ + wrongType: { + // @ts-expect-error The values must have the type of the style prop. + opacity: {default: 1, '@media (prefers-color-scheme: dark)': 'half'}, + }, + unsupportedQuery: { + // @ts-expect-error Only the supported media queries are allowed. + opacity: {default: 1, '@media (prefers-color-scheme: drak)': 0.5}, + }, + noDefault: { + // @ts-expect-error A conditional value needs a `default` value. + opacity: {'@media (prefers-color-scheme: dark)': 0.5}, + }, + convertedInJavaScript: { + // @ts-expect-error Components convert this prop in JavaScript. + resizeMode: { + default: 'cover', + '@media (prefers-color-scheme: dark)': 'contain', + }, + }, +}); diff --git a/packages/react-native/__typetests__/tsconfig.legacy.json b/packages/react-native/__typetests__/tsconfig.legacy.json index 6f5e91b9e551..72cdec8b8625 100644 --- a/packages/react-native/__typetests__/tsconfig.legacy.json +++ b/packages/react-native/__typetests__/tsconfig.legacy.json @@ -6,5 +6,7 @@ "extends": "./tsconfig.json", "compilerOptions": { "customConditions": ["react-native-legacy-deep-imports"] - } + }, + // Conditional style values exist only in the generated types. + "exclude": ["stylesheet-conditional-values.tsx"] } diff --git a/packages/rn-tester/js/examples/MediaQueries/MediaQueriesExample.js b/packages/rn-tester/js/examples/MediaQueries/MediaQueriesExample.js new file mode 100644 index 000000000000..76f0de35e44e --- /dev/null +++ b/packages/rn-tester/js/examples/MediaQueries/MediaQueriesExample.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 type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + +import RNTesterText from '../../components/RNTesterText'; +import * as React from 'react'; +import { + Appearance, + Button, + StyleSheet, + Text, + View, + useColorScheme, +} from 'react-native'; + +function ColorSchemeControls(): React.Node { + const colorScheme = useColorScheme(); + return ( + + Color scheme: {colorScheme ?? 'unknown'} + +