From 6c6511c6b35bab3075111d1c879a144b7b622030 Mon Sep 17 00:00:00 2001 From: Adrian Cotfas Date: Wed, 20 May 2026 08:25:33 -0700 Subject: [PATCH] feat(Pressable): add support for PlatformColor and alpha (#56395) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: `android_ripple` on `Pressable` (and `TouchableNativeFeedback.Ripple()`) only accepted numeric (pre-processed ARGB int) colors. Passing a `PlatformColor` would throw an invariant in JS, making theme-aware ripple colors impossible. This PR removes those guards and wires up the full color pipeline: 1. **JS** (`useAndroidRippleForView.js`, `TouchableNativeFeedback.js`): removed the `invariant` that rejected non-numeric processed colors. `TouchableNativeFeedback.Ripple()` now accepts `ColorValue` instead of `string`. 2. **C++** (`NativeDrawable.h`, `HostPlatformViewProps.cpp`): `color` changed from `int32_t` to `SharedColor` + a separate `colorResourcePaths` field for `PlatformColor` resource paths. The `fromRawValue` pipeline now resolves both plain colors and `PlatformColor` objects. 3. **Kotlin** (`ReactDrawableHelper.kt`): `getColor()` now handles both numeric and `PlatformColor` map values via `ColorPropConverter.getColor()`, catching `JSApplicationCausedNativeException` to fall back gracefully instead of crashing. 4. **Theme change support** (`ReactViewGroup.kt`): the raw drawable description maps are retained on the view, and `onConfigurationChanged` re-applies them so ripple colors update automatically on light/dark mode switch. A new `alpha: number` (0–1) field is also added so users can apply opacity to a `PlatformColor` whose value is fully opaque and can't have alpha embedded at the JS level. It is applied by multiplying into the resolved color's alpha channel. Unresolvable `PlatformColor` resources are handled gracefully: on New Arch, C++ omits the `color` key so Kotlin falls back to `colorControlHighlight`; on Old Arch, `ReactDrawableHelper` catches the `JSApplicationCausedNativeException` and falls back to `colorControlHighlight` instead of crashing. [ANDROID] [ADDED] - `android_ripple` now accepts `PlatformColor` for theme-aware ripple colors, and a new `alpha` (0–1) parameter for controlling ripple opacity independently of the color value. Pull Request resolved: https://github.com/facebook/react-native/pull/56395 Test Plan: **Automated:** - Existing Pressable snapshot tests pass unchanged. - Updated snapshot for `PlatformColor + alpha` to use `?attr/colorAccent` (matching the RNTester example). - Added snapshot test `should not crash with an unresolvable PlatformColor` verifying the component renders at the JS level without throwing. **Manual (RNTester → Pressable → "Pressable with PlatformColor ripple and alpha"):** 1. `PlatformColor('?attr/colorAccent'), no alpha` → full-opacity accent ripple 2. `PlatformColor('?attr/colorAccent'), alpha=0.3` → 30% opacity accent ripple 3. `#FF0000, no alpha` → full red ripple (regression check) 4. `#FF0000, alpha=0.5` → 50% opacity red ripple 5. Toggle system light/dark mode → ripple color updates automatically 6. Pass an intentionally invalid attribute (e.g. `?attr/doesNotExist`) → no crash, ripple falls back to default `colorControlHighlight` grey [Screen_recording_20260410_091000.webm](https://github.com/user-attachments/assets/5607d267-8cf1-4bbe-bad1-a80aac82d027) > [!NOTE] This is required in [React Native Paper](https://github.com/callstack/react-native-paper) to be able to fully support the Material Design specs but also useful as a general purpose feature for providing more flexibility when customizing ripple color. Reviewed By: javache Differential Revision: D105819708 Pulled By: fabriziocucci fbshipit-source-id: d27c43e0b4e619b6af1c8de0cdb2882db05ee33c --- .../Components/Pressable/Pressable.d.ts | 1 + .../Pressable/__tests__/Pressable-test.js | 67 ++++ .../__snapshots__/Pressable-test.js.snap | 286 ++++++++++++++++++ .../Pressable/useAndroidRippleForView.js | 15 +- .../Touchable/TouchableNativeFeedback.js | 16 +- .../Components/View/ViewPropTypes.js | 4 +- .../ReactAndroid/api/ReactAndroid.api | 1 + .../react/views/view/ReactDrawableHelper.kt | 79 +++-- .../react/views/view/ReactViewGroup.kt | 30 ++ .../react/views/view/ReactViewManager.kt | 9 +- .../components/view/HostPlatformViewProps.cpp | 21 +- .../renderer/components/view/NativeDrawable.h | 63 +++- packages/react-native/ReactNativeApi.d.ts | 104 +++---- .../js/examples/Pressable/PressableExample.js | 52 ++++ .../api-snapshots/ReactAndroidDebugCxx.api | 4 +- .../api-snapshots/ReactAndroidReleaseCxx.api | 4 +- 16 files changed, 639 insertions(+), 117 deletions(-) diff --git a/packages/react-native/Libraries/Components/Pressable/Pressable.d.ts b/packages/react-native/Libraries/Components/Pressable/Pressable.d.ts index e1f8bfefbd8..00d131f4aa1 100644 --- a/packages/react-native/Libraries/Components/Pressable/Pressable.d.ts +++ b/packages/react-native/Libraries/Components/Pressable/Pressable.d.ts @@ -30,6 +30,7 @@ export interface PressableAndroidRippleConfig { borderless?: null | boolean | undefined; radius?: null | number | undefined; foreground?: null | boolean | undefined; + alpha?: null | number | undefined; } export interface PressableProps diff --git a/packages/react-native/Libraries/Components/Pressable/__tests__/Pressable-test.js b/packages/react-native/Libraries/Components/Pressable/__tests__/Pressable-test.js index ca332e05ec2..8eb24e747bd 100644 --- a/packages/react-native/Libraries/Components/Pressable/__tests__/Pressable-test.js +++ b/packages/react-native/Libraries/Components/Pressable/__tests__/Pressable-test.js @@ -8,6 +8,8 @@ * @format */ +import {PlatformColor} from '../../../StyleSheet/PlatformColorValueTypes'; +import Platform from '../../../Utilities/Platform'; import {expectRendersMatchingSnapshot} from '../../../Utilities/ReactNativeTestTools'; import View from '../../View/View'; import Pressable from '../Pressable'; @@ -92,3 +94,68 @@ describe('', ); }); }); + +describe(' on Android', () => { + let originalOS: string; + + beforeEach(() => { + originalOS = Platform.OS; + /* $FlowFixMe[incompatible-type] */ + Platform.OS = 'android'; + }); + + afterEach(() => { + /* $FlowFixMe[incompatible-type] */ + Platform.OS = originalOS; + }); + + it('should set nativeBackgroundAndroid with numeric color and alpha', async () => { + await expectRendersMatchingSnapshot( + 'Pressable', + () => ( + + + + ), + () => { + jest.dontMock('../Pressable'); + }, + ); + }); + + it('should set nativeBackgroundAndroid with PlatformColor and alpha', async () => { + await expectRendersMatchingSnapshot( + 'Pressable', + () => ( + + + + ), + () => { + jest.dontMock('../Pressable'); + }, + ); + }); + + it('should not crash with an unresolvable PlatformColor', async () => { + await expectRendersMatchingSnapshot( + 'Pressable', + () => ( + + + + ), + () => { + jest.dontMock('../Pressable'); + }, + ); + }); +}); diff --git a/packages/react-native/Libraries/Components/Pressable/__tests__/__snapshots__/Pressable-test.js.snap b/packages/react-native/Libraries/Components/Pressable/__tests__/__snapshots__/Pressable-test.js.snap index 307aaba80c6..6f406d8766c 100644 --- a/packages/react-native/Libraries/Components/Pressable/__tests__/__snapshots__/Pressable-test.js.snap +++ b/packages/react-native/Libraries/Components/Pressable/__tests__/__snapshots__/Pressable-test.js.snap @@ -72,6 +72,292 @@ exports[` should render as expected: should deep render when not mo `; +exports[` on Android should not crash with an unresolvable PlatformColor: should deep render when mocked (please verify output manually) 1`] = ` + + + +`; + +exports[` on Android should not crash with an unresolvable PlatformColor: should deep render when not mocked (please verify output manually) 1`] = ` + + + +`; + +exports[` on Android should set nativeBackgroundAndroid with PlatformColor and alpha: should deep render when mocked (please verify output manually) 1`] = ` + + + +`; + +exports[` on Android should set nativeBackgroundAndroid with PlatformColor and alpha: should deep render when not mocked (please verify output manually) 1`] = ` + + + +`; + +exports[` on Android should set nativeBackgroundAndroid with numeric color and alpha: should deep render when mocked (please verify output manually) 1`] = ` + + + +`; + +exports[` on Android should set nativeBackgroundAndroid with numeric color and alpha: should deep render when not mocked (please verify output manually) 1`] = ` + + + +`; + exports[` should be disabled when disabled is true: should deep render when mocked (please verify output manually) 1`] = ` ; export type PressableAndroidRippleConfig = { @@ -31,6 +32,7 @@ export type PressableAndroidRippleConfig = { borderless?: boolean, radius?: number, foreground?: boolean, + alpha?: number, }; /** @@ -48,7 +50,7 @@ export default function useAndroidRippleForView( | Readonly<{nativeBackgroundAndroid: NativeBackgroundProp}> | Readonly<{nativeForegroundAndroid: NativeBackgroundProp}>, }> { - const {color, borderless, radius, foreground} = rippleConfig ?? {}; + const {color, borderless, radius, foreground, alpha} = rippleConfig ?? {}; return useMemo(() => { if ( @@ -56,16 +58,13 @@ export default function useAndroidRippleForView( (color != null || borderless != null || radius != null) ) { const processedColor = processColor(color); - invariant( - processedColor == null || typeof processedColor === 'number', - 'Unexpected color given for Ripple color', - ); const nativeRippleValue = { type: 'RippleAndroid', color: processedColor, borderless: borderless === true, rippleRadius: radius, + alpha: alpha ?? null, }; return { @@ -105,5 +104,5 @@ export default function useAndroidRippleForView( }; } return null; - }, [borderless, color, foreground, radius, viewRef]); + }, [alpha, borderless, color, foreground, radius, viewRef]); } diff --git a/packages/react-native/Libraries/Components/Touchable/TouchableNativeFeedback.js b/packages/react-native/Libraries/Components/Touchable/TouchableNativeFeedback.js index 6a0b5e12ee6..31943e6f678 100644 --- a/packages/react-native/Libraries/Components/Touchable/TouchableNativeFeedback.js +++ b/packages/react-native/Libraries/Components/Touchable/TouchableNativeFeedback.js @@ -8,6 +8,8 @@ * @format */ +import type {ProcessedColorValue} from '../../StyleSheet/processColor'; +import type {ColorValue} from '../../StyleSheet/StyleSheet'; import type {GestureResponderEvent} from '../../Types/CoreEventTypes'; import type {TouchableWithoutFeedbackProps} from './TouchableWithoutFeedback'; @@ -20,7 +22,6 @@ import {findHostInstance_DEPRECATED} from '../../ReactNative/RendererProxy'; import processColor from '../../StyleSheet/processColor'; import Platform from '../../Utilities/Platform'; import {Commands} from '../View/ViewNativeComponent'; -import invariant from 'invariant'; import * as React from 'react'; import {cloneElement} from 'react'; @@ -96,7 +97,7 @@ export type TouchableNativeFeedbackProps = Readonly<{ }> | Readonly<{ type: 'RippleAndroid', - color: ?number, + color: ?ProcessedColorValue, borderless: boolean, rippleRadius: ?number, }> @@ -177,23 +178,18 @@ class TouchableNativeFeedback extends React.Component< * @param rippleRadius The radius of ripple effect */ static Ripple: ( - color: string, + color: ColorValue, borderless: boolean, rippleRadius?: ?number, ) => Readonly<{ borderless: boolean, - color: ?number, + color: ?ProcessedColorValue, rippleRadius: ?number, type: 'RippleAndroid', - }> = (color: string, borderless: boolean, rippleRadius?: ?number) => { + }> = (color: ColorValue, borderless: boolean, rippleRadius?: ?number) => { const processedColor = processColor(color); - invariant( - processedColor == null || typeof processedColor === 'number', - 'Unexpected color given for Ripple color', - ); return { type: 'RippleAndroid', - // $FlowFixMe[incompatible-type] color: processedColor, borderless, rippleRadius, diff --git a/packages/react-native/Libraries/Components/View/ViewPropTypes.js b/packages/react-native/Libraries/Components/View/ViewPropTypes.js index a20d8f246ea..d232fd8ff8f 100644 --- a/packages/react-native/Libraries/Components/View/ViewPropTypes.js +++ b/packages/react-native/Libraries/Components/View/ViewPropTypes.js @@ -11,6 +11,7 @@ 'use strict'; import type {EdgeInsetsOrSizeProp} from '../../StyleSheet/EdgeInsetsPropType'; +import type {ProcessedColorValue} from '../../StyleSheet/processColor'; import type {ViewStyleProp} from '../../StyleSheet/StyleSheet'; import type { BlurEvent, @@ -264,9 +265,10 @@ type AndroidDrawableThemeAttr = Readonly<{ type AndroidDrawableRipple = Readonly<{ type: 'RippleAndroid', - color?: ?number, + color?: ?ProcessedColorValue, borderless?: ?boolean, rippleRadius?: ?number, + alpha?: ?number, }>; type AndroidDrawable = AndroidDrawableThemeAttr | AndroidDrawableRipple; diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index 024da3c221b..092adaa4197 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -6468,6 +6468,7 @@ public class com/facebook/react/views/view/ReactViewGroup : android/view/ViewGro public fun getZIndexMappedChildIndex (I)I public fun hasOverlappingRendering ()Z protected fun onAttachedToWindow ()V + protected fun onConfigurationChanged (Landroid/content/res/Configuration;)V public fun onHoverEvent (Landroid/view/MotionEvent;)Z public fun onInterceptTouchEvent (Landroid/view/MotionEvent;)Z protected fun onLayout (ZIIII)V diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactDrawableHelper.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactDrawableHelper.kt index 3b0cb0d8f82..5712b3b2bb8 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactDrawableHelper.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactDrawableHelper.kt @@ -15,10 +15,16 @@ import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.graphics.drawable.RippleDrawable import android.util.TypedValue +import com.facebook.common.logging.FLog +import com.facebook.react.bridge.ColorPropConverter +import com.facebook.react.bridge.JSApplicationCausedNativeException import com.facebook.react.bridge.JSApplicationIllegalArgumentException import com.facebook.react.bridge.ReadableMap +import com.facebook.react.bridge.ReadableType +import com.facebook.react.common.ReactConstants import com.facebook.react.uimanager.PixelUtil import com.facebook.react.uimanager.ViewProps +import kotlin.math.roundToInt /** * Utility class that helps with converting android drawable description used in JS to an actual @@ -73,11 +79,21 @@ public object ReactDrawableHelper { context: Context, drawableDescriptionDict: ReadableMap, ): RippleDrawable { - val color = getColor(context, drawableDescriptionDict) - val mask = getMask(drawableDescriptionDict) - val colorStateList = ColorStateList(arrayOf(intArrayOf()), intArrayOf(color)) + val resolvedColor = getColor(context, drawableDescriptionDict) + var color = resolvedColor ?: getFallbackColor(context) - return RippleDrawable(colorStateList, null, mask) + if ( + resolvedColor != null && + drawableDescriptionDict.hasKey("alpha") && + !drawableDescriptionDict.isNull("alpha") + ) { + val alphaFactor = drawableDescriptionDict.getDouble("alpha").coerceIn(0.0, 1.0) + val newAlpha = (Color.alpha(color) * alphaFactor).roundToInt() + color = Color.argb(newAlpha, Color.red(color), Color.green(color), Color.blue(color)) + } + + val mask = getMask(drawableDescriptionDict) + return RippleDrawable(ColorStateList(arrayOf(intArrayOf()), intArrayOf(color)), null, mask) } private fun setRadius(drawableDescriptionDict: ReadableMap, drawable: Drawable?): Drawable? { @@ -88,26 +104,49 @@ public object ReactDrawableHelper { return drawable } - private fun getColor(context: Context, drawableDescriptionDict: ReadableMap): Int = - if ( - drawableDescriptionDict.hasKey(ViewProps.COLOR) && - !drawableDescriptionDict.isNull(ViewProps.COLOR) - ) { - drawableDescriptionDict.getInt(ViewProps.COLOR) - } else { + /** + * Returns the resolved ripple color, or null if none was provided or the PlatformColor resource + * couldn't be found. + */ + private fun getColor(context: Context, drawableDescriptionDict: ReadableMap): Int? { + val rawColor: Any? = if ( - context.theme.resolveAttribute( - android.R.attr.colorControlHighlight, - resolveOutValue, - true, - ) + drawableDescriptionDict.hasKey(ViewProps.COLOR) && + !drawableDescriptionDict.isNull(ViewProps.COLOR) ) { - context.resources.getColor(resolveOutValue.resourceId, context.theme) + when (drawableDescriptionDict.getType(ViewProps.COLOR)) { + ReadableType.Number -> drawableDescriptionDict.getDouble(ViewProps.COLOR) + ReadableType.Map -> drawableDescriptionDict.getMap(ViewProps.COLOR) + else -> null + } } else { - throw JSApplicationIllegalArgumentException( - "Attribute colorControlHighlight couldn't be resolved into a drawable" - ) + null } + return try { + ColorPropConverter.getColor(rawColor, context) + } catch (e: JSApplicationCausedNativeException) { + FLog.w( + ReactConstants.TAG, + e, + "android_ripple: color resource not found, using colorControlHighlight", + ) + null + } + } + + private fun getFallbackColor(context: Context): Int = + if ( + context.theme.resolveAttribute( + android.R.attr.colorControlHighlight, + resolveOutValue, + true, + ) + ) { + context.resources.getColor(resolveOutValue.resourceId, context.theme) + } else { + throw JSApplicationIllegalArgumentException( + "Attribute colorControlHighlight couldn't be resolved into a drawable" + ) } private fun getMask(drawableDescriptionDict: ReadableMap): Drawable? { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.kt index 0d2f5faba3b..59775241c80 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewGroup.kt @@ -12,6 +12,7 @@ package com.facebook.react.views.view import android.annotation.SuppressLint import android.annotation.TargetApi import android.content.Context +import android.content.res.Configuration import android.graphics.BlendMode import android.graphics.Canvas import android.graphics.Paint @@ -28,6 +29,7 @@ import com.facebook.react.R import com.facebook.react.bridge.ReactNoCrashSoftException import com.facebook.react.bridge.ReactSoftExceptionLogger import com.facebook.react.bridge.ReactSoftExceptionLogger.logSoftException +import com.facebook.react.bridge.ReadableMap import com.facebook.react.bridge.UiThreadUtil.assertOnUiThread import com.facebook.react.bridge.UiThreadUtil.runOnUiThread import com.facebook.react.common.ReactConstants.TAG @@ -154,6 +156,9 @@ public open class ReactViewGroup public constructor(context: Context?) : null private var focusOnAttach = false + internal var nativeBackgroundMap: ReadableMap? = null + internal var nativeForegroundMap: ReadableMap? = null + init { initView() } @@ -181,6 +186,8 @@ public open class ReactViewGroup public constructor(context: Context?) : backfaceOpacity = 1f backfaceVisible = true childrenRemovedWhileTransitioning = null + nativeBackgroundMap = null + nativeForegroundMap = null } internal open fun recycleView() { @@ -587,6 +594,29 @@ public open class ReactViewGroup public constructor(context: Context?) : } } + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + if (nativeBackgroundMap != null) { + applyNativeBackground(nativeBackgroundMap) + } + if (nativeForegroundMap != null) { + applyNativeForeground(nativeForegroundMap) + } + } + + internal fun applyNativeBackground(map: ReadableMap?) { + nativeBackgroundMap = map + setFeedbackUnderlay( + this, + map?.let { ReactDrawableHelper.createDrawableFromJSDescription(context, it) }, + ) + } + + internal fun applyNativeForeground(map: ReadableMap?) { + nativeForegroundMap = map + foreground = map?.let { ReactDrawableHelper.createDrawableFromJSDescription(context, it) } + } + override fun onViewAdded(child: View) { assertOnUiThread() checkViewClippingTag(child, false) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt index 479eee756a7..0893e134f4e 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/view/ReactViewManager.kt @@ -305,17 +305,12 @@ public open class ReactViewManager : ReactClippingViewManager() @ReactProp(name = "nativeBackgroundAndroid") public open fun setNativeBackground(view: ReactViewGroup, background: ReadableMap?) { - val bg = background?.let { - ReactDrawableHelper.createDrawableFromJSDescription(view.context, it) - } - BackgroundStyleApplicator.setFeedbackUnderlay(view, bg) + view.applyNativeBackground(background) } @ReactProp(name = "nativeForegroundAndroid") public open fun setNativeForeground(view: ReactViewGroup, foreground: ReadableMap?) { - view.foreground = foreground?.let { - ReactDrawableHelper.createDrawableFromJSDescription(view.context, it) - } + view.applyNativeForeground(foreground) } @ReactProp(name = ViewProps.NEEDS_OFFSCREEN_ALPHA_COMPOSITING) diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.cpp b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.cpp index f430a957097..4897f22506e 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.cpp +++ b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/HostPlatformViewProps.cpp @@ -450,8 +450,25 @@ inline static void updateNativeDrawableProp( nativeDrawableResult["rippleRadius"] = nativeDrawableValue.ripple.rippleRadius.value(); } - if (nativeDrawableValue.ripple.color.has_value()) { - nativeDrawableResult["color"] = nativeDrawableValue.ripple.color.value(); + if (nativeDrawableValue.ripple.color.has_value() || + nativeDrawableValue.ripple.colorResourcePaths.has_value()) { + if (nativeDrawableValue.ripple.colorResourcePaths.has_value()) { + folly::dynamic resourcePaths = folly::dynamic::array(); + for (const auto& path : + nativeDrawableValue.ripple.colorResourcePaths.value()) { + resourcePaths.push_back(path); + } + folly::dynamic platformColorMap = folly::dynamic::object(); + platformColorMap["resource_paths"] = resourcePaths; + nativeDrawableResult["color"] = platformColorMap; + } else { + nativeDrawableResult["color"] = + toAndroidRepr(nativeDrawableValue.ripple.color.value()); + } + if (nativeDrawableValue.ripple.alpha.has_value()) { + nativeDrawableResult["alpha"] = + nativeDrawableValue.ripple.alpha.value(); + } } nativeDrawableResult["borderless"] = nativeDrawableValue.ripple.borderless; } else { diff --git a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/NativeDrawable.h b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/NativeDrawable.h index f02bb82205a..67c5a2bb27b 100644 --- a/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/NativeDrawable.h +++ b/packages/react-native/ReactCommon/react/renderer/components/view/platform/android/react/renderer/components/view/NativeDrawable.h @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -22,14 +23,16 @@ struct NativeDrawable { }; struct Ripple { - std::optional color{}; + std::optional color{}; + std::optional> colorResourcePaths{}; std::optional rippleRadius{}; bool borderless{false}; + std::optional alpha{}; bool operator==(const Ripple &rhs) const { - return std::tie(this->color, this->borderless, this->rippleRadius) == - std::tie(rhs.color, rhs.borderless, rhs.rippleRadius); + return std::tie(this->color, this->colorResourcePaths, this->borderless, this->rippleRadius, this->alpha) == + std::tie(rhs.color, rhs.colorResourcePaths, rhs.borderless, rhs.rippleRadius, rhs.alpha); } }; @@ -59,8 +62,7 @@ struct NativeDrawable { ~NativeDrawable() = default; }; -static inline void -fromRawValue(const PropsParserContext & /*context*/, const RawValue &rawValue, NativeDrawable &result) +static inline void fromRawValue(const PropsParserContext &context, const RawValue &rawValue, NativeDrawable &result) { auto map = (std::unordered_map)rawValue; @@ -73,24 +75,53 @@ fromRawValue(const PropsParserContext & /*context*/, const RawValue &rawValue, N react_native_expect(attrIterator != map.end() && attrIterator->second.hasType()); result = NativeDrawable{ - (std::string)attrIterator->second, - {}, - NativeDrawable::Kind::ThemeAttr, + .themeAttr = (std::string)attrIterator->second, + .ripple = {}, + .kind = NativeDrawable::Kind::ThemeAttr, }; } else if (type == "RippleAndroid") { auto color = map.find("color"); auto borderless = map.find("borderless"); auto rippleRadius = map.find("rippleRadius"); + auto alpha = map.find("alpha"); + + std::optional parsedColor{}; + std::optional> parsedColorResourcePaths{}; + if (color != map.end()) { + if (color->second.hasType>>()) { + auto colorMap = (std::unordered_map>)color->second; + auto pathsIt = colorMap.find("resource_paths"); + if (pathsIt != colorMap.end()) { + parsedColorResourcePaths = pathsIt->second; + } + } else { + SharedColor resolved; + fromRawValue(context, color->second, resolved); + if (resolved) { + parsedColor = resolved; + } + } + } + + std::optional parsedAlpha{}; + if (alpha != map.end() && alpha->second.hasType()) { + parsedAlpha = (Float)alpha->second; + } result = NativeDrawable{ - std::string{}, - NativeDrawable::Ripple{ - color != map.end() && color->second.hasType() ? (int32_t)color->second : std::optional{}, - rippleRadius != map.end() && rippleRadius->second.hasType() ? (Float)rippleRadius->second - : std::optional{}, - borderless != map.end() && borderless->second.hasType() ? (bool)borderless->second : false, - }, - NativeDrawable::Kind::Ripple, + .themeAttr = std::string{}, + .ripple = + NativeDrawable::Ripple{ + .color = parsedColor, + .colorResourcePaths = parsedColorResourcePaths, + .rippleRadius = rippleRadius != map.end() && rippleRadius->second.hasType() + ? (Float)rippleRadius->second + : std::optional{}, + .borderless = + borderless != map.end() && borderless->second.hasType() ? (bool)borderless->second : false, + .alpha = parsedAlpha, + }, + .kind = NativeDrawable::Kind::Ripple, }; } else { LOG(ERROR) << "Unknown native drawable type: " << type; diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index 13c53f3f59a..3df40c9fbf4 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<<1c8637ab03a5fec9d39704d1ae305595>> + * @generated SignedSource<<972e2e006306973351b2c19d46223b59>> * * This file was generated by scripts/js-api/build-types/index.js. */ @@ -1260,8 +1260,9 @@ declare type AlertType = | "secure-text" declare type AndroidDrawable = AndroidDrawableRipple | AndroidDrawableThemeAttr declare type AndroidDrawableRipple = { + readonly alpha?: number readonly borderless?: boolean - readonly color?: number + readonly color?: ProcessedColorValue readonly rippleRadius?: number readonly type: "RippleAndroid" } @@ -3806,6 +3807,7 @@ declare type PressabilityEventHandlers = { } declare type Pressable = typeof Pressable declare type PressableAndroidRippleConfig = { + alpha?: number borderless?: boolean color?: ColorValue foreground?: boolean @@ -5559,12 +5561,12 @@ declare class TouchableNativeFeedback extends React.Component< state: TouchableNativeFeedbackState static canUseNativeForeground: () => boolean static Ripple: ( - color: string, + color: ColorValue, borderless: boolean, rippleRadius?: null | number | undefined, ) => { readonly borderless: boolean - readonly color: number | undefined + readonly color: ProcessedColorValue | undefined readonly rippleRadius: number | undefined readonly type: "RippleAndroid" } @@ -5601,7 +5603,7 @@ declare type TouchableNativeFeedbackProps = Readonly< } | { readonly borderless: boolean - readonly color: number | undefined + readonly color: ProcessedColorValue | undefined readonly rippleRadius: number | undefined readonly type: "RippleAndroid" } @@ -6056,15 +6058,15 @@ export { AccessibilityValue, // cf8bcb74 ActionSheetIOS, // b558559e ActionSheetIOSOptions, // 1756eb5a - ActivityIndicator, // 9b127a18 - ActivityIndicatorProps, // 40142bf3 + ActivityIndicator, // 3cad29be + ActivityIndicatorProps, // d960bcd9 Alert, // 5bf12165 AlertButton, // bf1a3b60 AlertButtonStyle, // ec9fb242 AlertOptions, // a0cdac0f AlertType, // 5ab91217 AndroidKeyboardEvent, // e03becc8 - Animated, // 0652b5d1 + Animated, // 228f3189 AppConfig, // ce4209a7 AppRegistry, // 5edf0524 AppState, // 12012be5 @@ -6076,7 +6078,7 @@ export { BackPressEventName, // 4620fb76 BlurEvent, // e6151a1f BoxShadowValue, // b679703f - Button, // 53167a86 + Button, // 8a1b7d91 ButtonProps, // 0df9cb59 Clipboard, // 41addb89 CodegenTypes, // 0b8108a8 @@ -6095,8 +6097,8 @@ export { DimensionsPayload, // 653bc26c DisplayMetrics, // 1dc35cef DisplayMetricsAndroid, // 872e62eb - DrawerLayoutAndroid, // c0fe33a6 - DrawerLayoutAndroidProps, // 6ce7fb3d + DrawerLayoutAndroid, // b5c24b28 + DrawerLayoutAndroidProps, // 63da4182 DrawerSlideEvent, // 0256d35a DropShadowValue, // e9df2606 DynamicColorIOS, // d96c228c @@ -6111,8 +6113,8 @@ export { EventSubscription, // b8d084aa ExtendedExceptionData, // 5a6ccf5a FilterFunction, // bf24c0e3 - FlatList, // 8c50f04a - FlatListProps, // e170f2c9 + FlatList, // 32c61c26 + FlatListProps, // c5454227 FocusEvent, // 62fc1eb8 FontVariant, // 7c7558bb GestureResponderEvent, // f693e9a5 @@ -6124,15 +6126,15 @@ export { IEventEmitter, // fbef6131 IOSKeyboardEvent, // e67bfe3a IgnorePattern, // ec6f6ece - Image, // a2358f8c - ImageBackground, // 414c60ba - ImageBackgroundProps, // 65c127f9 + Image, // bf1a968c + ImageBackground, // a0c25687 + ImageBackgroundProps, // 83532322 ImageErrorEvent, // d3ee606e ImageLoadEvent, // 6b547ea5 ImageProgressEventIOS, // 4c866a82 - ImageProps, // d917cbd6 + ImageProps, // 82936b1a ImagePropsAndroid, // 9fd9bcbb - ImagePropsBase, // c9521ea0 + ImagePropsBase, // 158fb87f ImagePropsIOS, // c4ae0c06 ImageRequireSource, // 681d683b ImageResolvedAssetSource, // f3060931 @@ -6150,8 +6152,8 @@ export { KeyEvent, // 20fa4267 KeyUpEvent, // bc6bd87b Keyboard, // 49414c97 - KeyboardAvoidingView, // 79591758 - KeyboardAvoidingViewProps, // 7cd981a2 + KeyboardAvoidingView, // b8c4060e + KeyboardAvoidingViewProps, // 5d5b7295 KeyboardEvent, // c3f895d4 KeyboardEventEasing, // af4091c8 KeyboardEventName, // 59299ad6 @@ -6176,9 +6178,9 @@ export { MeasureInWindowOnSuccessCallback, // a285f598 MeasureLayoutOnSuccessCallback, // 3592502a MeasureOnSuccessCallback, // 82824e59 - Modal, // dad0b1ce + Modal, // 338838e9 ModalBaseProps, // cbd3c10d - ModalProps, // 8e1508c6 + ModalProps, // d9517626 ModalPropsAndroid, // 515fb173 ModalPropsIOS, // 144bbc95 ModeChangeEvent, // a5e9864f @@ -6216,13 +6218,13 @@ export { PointerEvent, // fe3989a1 PressabilityConfig, // 6dedcb61 PressabilityEventHandlers, // 3e6c0f56 - Pressable, // aef6bb57 - PressableAndroidRippleConfig, // 42bc9727 - PressableProps, // 3912691c + Pressable, // c52b5e3f + PressableAndroidRippleConfig, // ee32eaca + PressableProps, // 5d621e64 PressableStateCallbackType, // 9af36561 ProcessedColorValue, // 33f74304 - ProgressBarAndroid, // 36757db1 - ProgressBarAndroidProps, // 8bf4dfa6 + ProgressBarAndroid, // 782feeed + ProgressBarAndroidProps, // 02181314 PromiseTask, // 5102c862 PublicRootInstance, // 8040afd7 PublicTextInstance, // cd0d8f8d @@ -6231,8 +6233,8 @@ export { PushNotificationPermissions, // c2e7ae4f Rationale, // 5df1b1c1 ReactNativeVersion, // abd76827 - RefreshControl, // b8659b1f - RefreshControlProps, // e747ed5d + RefreshControl, // 5a0bb67f + RefreshControlProps, // 09286d5c RefreshControlPropsAndroid, // 99f64c97 RefreshControlPropsIOS, // 72a36381 Registry, // 6c39216d @@ -6244,21 +6246,21 @@ export { RootViewStyleProvider, // d4818465 Runnable, // 594dd93a Runnables, // 4367c557 - SafeAreaView, // 9589fa67 + SafeAreaView, // 44374f1c ScaledSize, // 07e417c7 ScrollEvent, // 5d529218 - ScrollResponderType, // c6860ec8 + ScrollResponderType, // f08ebcac ScrollToLocationParamsType, // d7ecdad1 - ScrollView, // a3918d1a - ScrollViewImperativeMethods, // 7cd8d8de - ScrollViewProps, // 429fdd65 + ScrollView, // d4f6cd67 + ScrollViewImperativeMethods, // 7949da33 + ScrollViewProps, // 8fe6beb4 ScrollViewPropsAndroid, // 44210553 ScrollViewPropsIOS, // b34b696c ScrollViewScrollToOptions, // 3313411e SectionBase, // b376bddc - SectionList, // 92031230 + SectionList, // 5d1f9b75 SectionListData, // 119baf83 - SectionListProps, // c0d0a46a + SectionListProps, // ffc7a846 SectionListRenderItem, // 1fad0435 SectionListRenderItemInfo, // 745e1992 Separators, // 6a45f7e3 @@ -6277,16 +6279,16 @@ export { StyleProp, // fa0e9b4a StyleSheet, // e77dd046 SubmitBehavior, // c4ddf490 - Switch, // 3434138b + Switch, // a3e3a6d7 SwitchChangeEvent, // 63e9c50b - SwitchProps, // 083b753d + SwitchProps, // ea50785b Systrace, // b5aa21fc TVViewPropsIOS, // 330ce7b5 TargetedEvent, // 16e98910 TaskProvider, // 266dedf2 Text, // 717d25fe TextContentType, // 239b3ecc - TextInput, // ed3a8375 + TextInput, // e39c95f8 TextInputAndroidProps, // 3f09ce49 TextInputChangeEvent, // 3ab11bb4 TextInputContentSizeChangeEvent, // f71f8571 @@ -6294,7 +6296,7 @@ export { TextInputFocusEvent, // 020507e6 TextInputIOSProps, // 0d05a855 TextInputKeyPressEvent, // 3924ad9b - TextInputProps, // 9b370db2 + TextInputProps, // 22be7373 TextInputSelectionChangeEvent, // d4d10630 TextInputSubmitEditingEvent, // 22885c31 TextLayoutEvent, // 73ab173e @@ -6302,12 +6304,12 @@ export { TextStyle, // bb9b7a58 ToastAndroid, // 88a8969a Touchable, // da3239ee - TouchableHighlight, // 9d67503a - TouchableHighlightProps, // b2aa6f4b - TouchableNativeFeedback, // 2ed83cf4 - TouchableNativeFeedbackProps, // 1209959b - TouchableOpacity, // fcbaef78 - TouchableOpacityProps, // 13fbd043 + TouchableHighlight, // c19c8aa2 + TouchableHighlightProps, // 2cc665bc + TouchableNativeFeedback, // fc866848 + TouchableNativeFeedbackProps, // cc2cd62f + TouchableOpacity, // 8bb5a256 + TouchableOpacityProps, // f65d15b1 TouchableWithoutFeedback, // 39070327 TouchableWithoutFeedbackProps, // b847de29 TransformsStyle, // 65e70f18 @@ -6316,16 +6318,16 @@ export { UIManager, // a1a7cc01 UTFSequence, // ad625158 Vibration, // 31e4bbf8 - View, // 02678ca8 - ViewProps, // 15e5f6b9 - ViewPropsAndroid, // bdfc84a1 + View, // d0020870 + ViewProps, // 05ae6eb9 + ViewPropsAndroid, // ac650c5c ViewPropsIOS, // 58ee19bf ViewStyle, // 00a0f8fb VirtualViewMode, // 6be59722 VirtualizedList, // 68c7345e - VirtualizedListProps, // c7e8e7d7 + VirtualizedListProps, // fa4c8673 VirtualizedSectionList, // 9fd9cd61 - VirtualizedSectionListProps, // 53a7e6a4 + VirtualizedSectionListProps, // 914d0bdc WrapperComponentProvider, // 9cf3844c codegenNativeCommands, // 628a7c0a codegenNativeComponent, // 2baac257 diff --git a/packages/rn-tester/js/examples/Pressable/PressableExample.js b/packages/rn-tester/js/examples/Pressable/PressableExample.js index 0e2f6c035a4..b52f9f9ba05 100644 --- a/packages/rn-tester/js/examples/Pressable/PressableExample.js +++ b/packages/rn-tester/js/examples/Pressable/PressableExample.js @@ -17,6 +17,7 @@ import { Animated, Image, Platform, + PlatformColor, Pressable, StyleSheet, Text, @@ -512,6 +513,57 @@ const examples = [ ); }, }, + { + title: 'Pressable with PlatformColor ripple and alpha', + description: + 'android_ripple accepts PlatformColor and a separate alpha (0–1) parameter' as string, + platform: 'android', + render: function (): React.Node { + const buttonStyle = {textAlign: 'center' as const, margin: 10}; + return ( + + + + PlatformColor('?attr/colorAccent'), no alpha + + + + + PlatformColor('?attr/colorAccent'), alpha=0.3 + + + + Red (#FF0000), no alpha + + + Red (#FF0000), alpha=0.5 + + + ); + }, + }, { title: ' with highlight', name: 'text-press', diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api index 8895f9a2255..46bf19be661 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidDebugCxx.api @@ -7455,8 +7455,10 @@ enum facebook::react::NativeDrawable::Kind : uint8_t { struct facebook::react::NativeDrawable::Ripple { public bool borderless; public bool operator==(const facebook::react::NativeDrawable::Ripple& rhs) const; + public std::optional alpha; public std::optional rippleRadius; - public std::optional color; + public std::optional color; + public std::optional> colorResourcePaths; } struct facebook::react::NativePerformanceEntry { diff --git a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api index e82d7dfbbee..2f0733cb396 100644 --- a/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api +++ b/scripts/cxx-api/api-snapshots/ReactAndroidReleaseCxx.api @@ -7446,8 +7446,10 @@ enum facebook::react::NativeDrawable::Kind : uint8_t { struct facebook::react::NativeDrawable::Ripple { public bool borderless; public bool operator==(const facebook::react::NativeDrawable::Ripple& rhs) const; + public std::optional alpha; public std::optional rippleRadius; - public std::optional color; + public std::optional color; + public std::optional> colorResourcePaths; } struct facebook::react::NativePerformanceEntry {