From 987751dcadef06d8a6be058bc9723dd441d47e38 Mon Sep 17 00:00:00 2001 From: Grzegorz Kruk Date: Wed, 19 Aug 2026 15:38:05 +0200 Subject: [PATCH 01/11] Update hermes-compiler version and enhance back navigation handling in ReactActivity Summary: - Added new methods to `ReactActivity` to improve back navigation handling on Android API 36 and above, including `getBackPressedCallback()` and `onSystemNavigationBackInvoked()`. - Introduced a `SystemNavigationBackObserver` to manage system back navigation events. - Added unit tests for the new back navigation functionality in `ReactActivityBackPressedCallbackTest.kt`. - Updated `RNTesterActivity` to allow system predictive-back animations while still notifying JS on app exit. Changelog: [GENERAL][CHANGED] - Enhanced back navigation handling and updated hermes-compiler version. Test Plan: - Verified back navigation functionality on Android API 36+. - Ensured that the updated hermes-compiler works without issues in the project. --- .../ReactAndroid/api/ReactAndroid.api | 1 + .../com/facebook/react/ReactActivity.java | 106 ++++++++++++++++-- .../ReactActivityBackPressedCallbackTest.kt | 78 +++++++++++++ .../facebook/react/uiapp/RNTesterActivity.kt | 5 + .../examples/Playground/RNTesterPlayground.js | 71 +++++++++++- 5 files changed, 252 insertions(+), 9 deletions(-) create mode 100644 packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index ba540f18c54d..a007e5548ddc 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -61,6 +61,7 @@ public final class com/facebook/react/NativeModuleRegistryBuilder { public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/AppCompatActivity, com/facebook/react/modules/core/DefaultHardwareBackBtnHandler, com/facebook/react/modules/core/PermissionAwareActivity { protected fun ()V protected fun createReactActivityDelegate ()Lcom/facebook/react/ReactActivityDelegate; + public fun getBackPressedCallback ()Landroidx/activity/OnBackPressedCallback; protected fun getMainComponentName ()Ljava/lang/String; public fun getReactActivityDelegate ()Lcom/facebook/react/ReactActivityDelegate; public fun getReactDelegate ()Lcom/facebook/react/ReactDelegate; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java index b375d1859dbc..b4adc6de6c56 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java @@ -7,12 +7,16 @@ package com.facebook.react; +import android.annotation.SuppressLint; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; +import android.util.Log; import android.view.KeyEvent; +import android.window.OnBackInvokedCallback; import androidx.activity.OnBackPressedCallback; import androidx.annotation.Nullable; +import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.modules.core.PermissionAwareActivity; @@ -24,10 +28,15 @@ public abstract class ReactActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler, PermissionAwareActivity { + private static final String PREDICTIVE_BACK_TAG = "PredictiveBack"; + private final ReactActivityDelegate mDelegate; - // Due to enforced predictive back on targetSdk 36, 'onBackPressed()' is disabled by default. - // Using a workaround to trigger it manually. + // On targetSdk 36, Activity.onBackPressed() is no longer invoked by the system. This callback + // keeps JS BackHandler working by consuming back and forwarding it to JS. + // An enabled callback suppresses the system predictive-back animation (back-to-home, + // cross-activity, cross-task) and FragmentManager predictive-back transitions. Navigation + // libraries that implement predictive back should disable it via getBackPressedCallback(). private final OnBackPressedCallback mBackPressedCallback = new OnBackPressedCallback(true) { @Override @@ -38,6 +47,10 @@ public void handleOnBackPressed() { } }; + // Registered only on API 36+. Typed as Object so ReactActivity can load on older devices + // that do not have android.window.OnBackInvokedCallback. + private @Nullable Object mSystemNavigationObserver; + @SuppressWarnings("this-escape") protected ReactActivity() { mDelegate = createReactActivityDelegate(); @@ -62,6 +75,7 @@ protected void onCreate(Bundle savedInstanceState) { mDelegate.onCreate(savedInstanceState); if (AndroidVersion.isAtLeastTargetSdk36(this)) { getOnBackPressedDispatcher().addCallback(this, mBackPressedCallback); + mSystemNavigationObserver = SystemNavigationBackObserver.register(this); } } @@ -79,6 +93,10 @@ protected void onResume() { @Override protected void onDestroy() { + if (mSystemNavigationObserver != null && AndroidVersion.isAtLeastTargetSdk36(this)) { + SystemNavigationBackObserver.unregister(this, mSystemNavigationObserver); + mSystemNavigationObserver = null; + } super.onDestroy(); mDelegate.onDestroy(); } @@ -91,6 +109,41 @@ public ReactActivityDelegate getReactActivityDelegate() { return mDelegate; } + /** + * Returns the {@link OnBackPressedCallback} React Native registers on Android 16+ (targetSdk 36) + * to keep JS {@code BackHandler} working after {@code Activity.onBackPressed()} stopped being + * called. + * + *

While this callback is enabled, Android will not play the system predictive-back animation, + * and FragmentManager will not receive the gesture. Navigation libraries that implement + * predictive back should disable it: + * + *

{@code
+   * getBackPressedCallback().setEnabled(false);
+   * }
+ * + *

Disabling the callback means JS {@code BackHandler} can no longer prevent back. The system + * or the next enabled callback (for example FragmentManager) handles the gesture instead. On + * Android 16+, a {@code PRIORITY_SYSTEM_NAVIGATION_OBSERVER} still delivers the committed + * app-exit event to {@code BackHandler} without suppressing the predictive-back animation. + * Returning {@code true} from a listener cannot cancel an exit that is already in progress. + */ + public OnBackPressedCallback getBackPressedCallback() { + return mBackPressedCallback; + } + + /** + * Called when the system is handling back (app exit) and this activity's consuming callback is + * disabled. Notifies JS without consuming the gesture, so the predictive-back animation can run. + */ + void onSystemNavigationBackInvoked() { + if (mBackPressedCallback.isEnabled()) { + return; + } + Log.i(PREDICTIVE_BACK_TAG, "observer: system back committed, notifying JS"); + mDelegate.onBackPressed(); + } + @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); @@ -121,13 +174,18 @@ public void onBackPressed() { @Override public void invokeDefaultOnBackPressed() { - // Disabling callback so the fallback logic (finish activity) can run - // as super.onBackPressed() will call all enabled callbacks in the dispatcher. + // System predictive back may already be finishing the activity. Calling super again would + // re-enter the dispatcher after JS BackHandler.exitApp(). + if (isFinishing()) { + return; + } + // Temporarily disable so super.onBackPressed() can run the fallback (finish the activity) + // instead of re-entering this callback. Restore the previous enabled state so that + // libraries which disabled the callback for predictive back stay disabled after resume. + boolean enabled = mBackPressedCallback.isEnabled(); mBackPressedCallback.setEnabled(false); super.onBackPressed(); - // Re-enable callback to ensure custom back handling works after activity resume - // Without this, the callback remains disabled when the app returns from background - mBackPressedCallback.setEnabled(true); + mBackPressedCallback.setEnabled(enabled); } @Override @@ -183,4 +241,38 @@ protected final ReactInstanceManager getReactInstanceManager() { protected final void loadApp(String appKey) { mDelegate.loadApp(appKey); } + + /** + * Isolated so that {@link OnBackInvokedCallback} (API 33) is only loaded when predictive back is + * active, and not from {@link ReactActivity} fields or method signatures. + */ + @RequiresApi(36) + private static final class SystemNavigationBackObserver { + + // android.window.OnBackInvokedDispatcher.PRIORITY_SYSTEM_NAVIGATION_OBSERVER (API 36). + // Inlined because this codebase is also compiled against older SDKs that lack the constant. + private static final int PRIORITY_SYSTEM_NAVIGATION_OBSERVER = -2; + + @SuppressLint("WrongConstant") + static @Nullable Object register(ReactActivity activity) { + OnBackInvokedCallback callback = activity::onSystemNavigationBackInvoked; + try { + activity + .getOnBackInvokedDispatcher() + .registerOnBackInvokedCallback(PRIORITY_SYSTEM_NAVIGATION_OBSERVER, callback); + return callback; + } catch (IllegalArgumentException e) { + // Observer priority is a flagged API and may be rejected on some devices. + return null; + } + } + + static void unregister(ReactActivity activity, Object observer) { + if (observer instanceof OnBackInvokedCallback) { + activity + .getOnBackInvokedDispatcher() + .unregisterOnBackInvokedCallback((OnBackInvokedCallback) observer); + } + } + } } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt new file mode 100644 index 000000000000..915cbb4df68b --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt @@ -0,0 +1,78 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react + +import org.assertj.core.api.Assertions.assertThat +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class ReactActivityBackPressedCallbackTest { + + @Test + fun getBackPressedCallback_isEnabledByDefault() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + + assertThat(activity.backPressedCallback.isEnabled).isTrue() + } + + @Test + fun invokeDefaultOnBackPressed_restoresDisabledState() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.backPressedCallback.isEnabled = false + + activity.invokeDefaultOnBackPressed() + + assertThat(activity.backPressedCallback.isEnabled).isFalse() + } + + @Test + fun invokeDefaultOnBackPressed_restoresEnabledState() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + + activity.invokeDefaultOnBackPressed() + + assertThat(activity.backPressedCallback.isEnabled).isTrue() + } + + @Test + fun systemNavigationObserver_notifiesJsWhenCallbackDisabled() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.backPressedCallback.isEnabled = false + + activity.onSystemNavigationBackInvoked() + + assertThat(activity.delegatedBackPressCount).isEqualTo(1) + } + + @Test + fun systemNavigationObserver_doesNotNotifyJsWhenCallbackEnabled() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + + activity.onSystemNavigationBackInvoked() + + assertThat(activity.delegatedBackPressCount).isEqualTo(0) + } + + class TestReactActivity : ReactActivity() { + var delegatedBackPressCount: Int = 0 + + override fun getMainComponentName(): String = "Test" + + override fun createReactActivityDelegate(): ReactActivityDelegate { + return object : ReactActivityDelegate(this, "Test") { + override fun onBackPressed(): Boolean { + delegatedBackPressCount++ + return true + } + } + } + } +} diff --git a/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.kt b/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.kt index 879c7f75bfe6..4c762618a7dc 100644 --- a/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.kt +++ b/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.kt @@ -63,6 +63,11 @@ internal open class RNTesterActivity : ReactActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) + // Lets the system predictive-back animation run. JS BackHandler still + // receives app-exit via PRIORITY_SYSTEM_NAVIGATION_OBSERVER; it cannot prevent it. + // Remove this line to restore RNTester's in-example back navigation. + backPressedCallback.isEnabled = false + fullyDrawnReporter.addReporter() maybeUpdateBackgroundColor() diff --git a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js index 8e6b10479de7..c337c29097f3 100644 --- a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js +++ b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js @@ -12,14 +12,69 @@ import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import RNTesterText from '../../components/RNTesterText'; import * as React from 'react'; -import {StyleSheet, View} from 'react-native'; +import {useEffect, useState} from 'react'; +import {BackHandler, Platform, StyleSheet, View} from 'react-native'; function Playground() { + const [events, setEvents] = useState<$ReadOnlyArray>([]); + + useEffect(() => { + if (Platform.OS !== 'android') { + return; + } + + const subscription = BackHandler.addEventListener( + 'hardwareBackPress', + () => { + const line = `${new Date().toISOString()} hardwareBackPress`; + console.log('[PredictiveBack]', line); + setEvents(current => [line, ...current].slice(0, 8)); + // Returning true cannot cancel a system-handled exit. If the observer + // is working, the app still closes after this log. + return true; + }, + ); + + return () => subscription.remove(); + }, []); + return ( + + Predictive back observer + - Edit "RNTesterPlayground.js" to change this file + RNTesterActivity disables React Native's consuming back callback so + Android can play the system predictive-back animation. A + PRIORITY_SYSTEM_NAVIGATION_OBSERVER still delivers hardwareBackPress + to JS on commit. + + + 1. API 36 device/AVD, gesture navigation, animations on. + + 2. Drag slowly inward from the left or right edge and hold. The + activity should shrink and home should peek through. + + + 3. Release to commit: Metro should log [PredictiveBack] and the app + should still close. Returning true cannot prevent that exit. + + + 4. Release early to cancel: no JS event, activity springs back. + + JS events + {events.length === 0 ? ( + + None yet. Watch Metro if the app closes too quickly to read this. + + ) : ( + events.map(event => ( + + {event} + + )) + )} ); } @@ -27,6 +82,18 @@ function Playground() { const styles = StyleSheet.create({ container: { padding: 10, + gap: 8, + }, + title: { + fontWeight: '700', + marginBottom: 4, + }, + step: { + marginTop: 4, + }, + logTitle: { + fontWeight: '700', + marginTop: 12, }, }); From ca5a3858ffe32022d4a1db7f5cb5c4084b98ba2d Mon Sep 17 00:00:00 2001 From: Grzegorz Kruk Date: Wed, 26 Aug 2026 12:44:01 +0200 Subject: [PATCH 02/11] Add setInterceptEnabled method to BackHandler for improved back navigation handling Summary: - Introduced `setInterceptEnabled(enabled: boolean)` method to `BackHandler` for Android, allowing React Native to manage back gesture interception. - Updated `ReactActivity` to handle predictive back animations on Android 16+. - Enhanced type definitions in TypeScript and Flow to include the new method. - Added unit tests to verify the functionality of the new back navigation feature. Changelog: [GENERAL][CHANGED] - Enhanced back navigation handling with new interception capabilities. --- .../Utilities/BackHandler.android.js | 16 + .../Libraries/Utilities/BackHandler.ios.js | 2 + .../Libraries/Utilities/BackHandler.js.flow | 1 + .../Utilities/__mocks__/BackHandler.js | 1 + .../ReactAndroid/api/ReactAndroid.api | 3 + .../com/facebook/react/ReactActivity.java | 373 +++++++++++++++++- .../modules/core/DeviceEventManagerModule.kt | 17 + .../ReactActivityBackPressedCallbackTest.kt | 19 + packages/react-native/ReactNativeApi.d.ts | 1 + .../modules/NativeDeviceEventManager.js | 1 + .../Libraries/Utilities/BackHandler.d.ts | 8 + .../facebook/react/uiapp/RNTesterActivity.kt | 6 +- packages/rn-tester/js/RNTesterAppShared.js | 191 +++++++-- .../examples/Playground/RNTesterPlayground.js | 33 +- 14 files changed, 608 insertions(+), 64 deletions(-) diff --git a/packages/react-native/Libraries/Utilities/BackHandler.android.js b/packages/react-native/Libraries/Utilities/BackHandler.android.js index 597f2eacc59a..5469cbaba457 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.android.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.android.js @@ -51,6 +51,14 @@ type TBackHandler = { eventName: BackPressEventName, handler: BackPressHandler, ) => {remove: () => void, ...}, + /** + * Android only. When true, React Native consumes the back gesture so + * BackHandler can pop an in-app screen. On Android 16+, a view tagged + * with nativeID "predictiveBackFrontPane" is scrubbed during the swipe. + * When false, the system predictive-back animation can run; BackHandler + * still observes app-exit commit. + */ + readonly setInterceptEnabled: (enabled: boolean) => void, }; const BackHandler: TBackHandler = { /** @@ -64,6 +72,14 @@ const BackHandler: TBackHandler = { NativeDeviceEventManager.invokeDefaultBackPressHandler(); }, + setInterceptEnabled: function (enabled: boolean): void { + if (!NativeDeviceEventManager) { + return; + } + + NativeDeviceEventManager.setInterceptEnabled(enabled); + }, + /** * Listen for the `hardwareBackPress` event. The handler should return `true` * to prevent the event from bubbling to earlier registered listeners. diff --git a/packages/react-native/Libraries/Utilities/BackHandler.ios.js b/packages/react-native/Libraries/Utilities/BackHandler.ios.js index e9bb65f193bb..6c3c19cd24f9 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.ios.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.ios.js @@ -21,6 +21,7 @@ type TBackHandler = { eventName: BackPressEventName, handler: BackPressHandler, ): {remove: () => void, ...}, + setInterceptEnabled(enabled: boolean): void, }; const BackHandler: TBackHandler = { @@ -30,6 +31,7 @@ const BackHandler: TBackHandler = { remove: emptyFunction, }; }, + setInterceptEnabled(_enabled: boolean): void {}, }; export default BackHandler; diff --git a/packages/react-native/Libraries/Utilities/BackHandler.js.flow b/packages/react-native/Libraries/Utilities/BackHandler.js.flow index 4c1debea88b0..3e8f68a16762 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.js.flow +++ b/packages/react-native/Libraries/Utilities/BackHandler.js.flow @@ -28,6 +28,7 @@ type TBackHandler = { eventName: BackPressEventName, handler: (event: HardwareBackPressEvent) => ?boolean, ): {remove: () => void, ...}, + setInterceptEnabled(enabled: boolean): void, }; /** diff --git a/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js b/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js index 9e964a069ba3..0523898fd782 100644 --- a/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js +++ b/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js @@ -19,6 +19,7 @@ const _backPressSubscriptions = new Set< const BackHandler = { exitApp: jest.fn() as () => void, + setInterceptEnabled: jest.fn() as (enabled: boolean) => void, addEventListener: function ( eventName: BackPressEventName, diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index a007e5548ddc..319bdc8b38c4 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -59,6 +59,7 @@ public final class com/facebook/react/NativeModuleRegistryBuilder { } public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/AppCompatActivity, com/facebook/react/modules/core/DefaultHardwareBackBtnHandler, com/facebook/react/modules/core/PermissionAwareActivity { + public static final field PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID Ljava/lang/String; protected fun ()V protected fun createReactActivityDelegate ()Lcom/facebook/react/ReactActivityDelegate; public fun getBackPressedCallback ()Landroidx/activity/OnBackPressedCallback; @@ -85,6 +86,7 @@ public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/ public fun onUserLeaveHint ()V public fun onWindowFocusChanged (Z)V public fun requestPermissions ([Ljava/lang/String;ILcom/facebook/react/modules/core/PermissionListener;)V + public fun setInterceptEnabled (Z)V } public class com/facebook/react/ReactActivityDelegate { @@ -2536,6 +2538,7 @@ public class com/facebook/react/modules/core/DeviceEventManagerModule : com/face public fun emitHardwareBackPressed ()V public fun emitNewIntentReceived (Landroid/net/Uri;)V public fun invokeDefaultBackPressHandler ()V + public fun setInterceptEnabled (Z)V } public final class com/facebook/react/modules/core/DeviceEventManagerModule$Companion { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java index b4adc6de6c56..794f6d9ce151 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java @@ -10,10 +10,21 @@ import android.annotation.SuppressLint; import android.content.Intent; import android.content.res.Configuration; +import android.graphics.Outline; import android.os.Bundle; +import android.os.SystemClock; import android.util.Log; import android.view.KeyEvent; +import android.view.View; +import android.view.ViewConfiguration; +import android.view.ViewGroup; +import android.view.ViewOutlineProvider; +import android.view.animation.DecelerateInterpolator; +import android.view.animation.PathInterpolator; +import android.window.BackEvent; +import android.window.OnBackAnimationCallback; import android.window.OnBackInvokedCallback; +import android.window.OnBackInvokedDispatcher; import androidx.activity.OnBackPressedCallback; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; @@ -28,6 +39,12 @@ public abstract class ReactActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler, PermissionAwareActivity { + /** + * {@code nativeID} of the view that in-app predictive back should scrub. Keep the previous + * screen mounted underneath this view so it can peek through during the gesture. + */ + public static final String PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID = "predictiveBackFrontPane"; + private static final String PREDICTIVE_BACK_TAG = "PredictiveBack"; private final ReactActivityDelegate mDelegate; @@ -51,6 +68,9 @@ public void handleOnBackPressed() { // that do not have android.window.OnBackInvokedCallback. private @Nullable Object mSystemNavigationObserver; + // In-app OnBackAnimationCallback. Typed as Object for the same older-device class loading. + private @Nullable Object mInAppPredictiveBack; + @SuppressWarnings("this-escape") protected ReactActivity() { mDelegate = createReactActivityDelegate(); @@ -93,9 +113,15 @@ protected void onResume() { @Override protected void onDestroy() { - if (mSystemNavigationObserver != null && AndroidVersion.isAtLeastTargetSdk36(this)) { - SystemNavigationBackObserver.unregister(this, mSystemNavigationObserver); - mSystemNavigationObserver = null; + if (AndroidVersion.isAtLeastTargetSdk36(this)) { + if (mSystemNavigationObserver != null) { + SystemNavigationBackObserver.unregister(this, mSystemNavigationObserver); + mSystemNavigationObserver = null; + } + if (mInAppPredictiveBack != null) { + InAppPredictiveBack.unregister(this, mInAppPredictiveBack); + mInAppPredictiveBack = null; + } } super.onDestroy(); mDelegate.onDestroy(); @@ -137,13 +163,41 @@ public OnBackPressedCallback getBackPressedCallback() { * disabled. Notifies JS without consuming the gesture, so the predictive-back animation can run. */ void onSystemNavigationBackInvoked() { - if (mBackPressedCallback.isEnabled()) { + if (mBackPressedCallback.isEnabled() || mInAppPredictiveBack != null) { return; } Log.i(PREDICTIVE_BACK_TAG, "observer: system back committed, notifying JS"); mDelegate.onBackPressed(); } + /** + * When {@code true}, React Native consumes the back gesture so JS {@code BackHandler} can pop an + * in-app screen. On Android 16+ (targetSdk 36) this registers a platform {@link + * OnBackAnimationCallback} that scrubs the view tagged with {@link + * #PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID} during the swipe, revealing whatever is drawn behind it. + * When {@code false}, the system predictive-back animation can run. + */ + public void setInterceptEnabled(boolean enabled) { + if (!AndroidVersion.isAtLeastTargetSdk36(this)) { + mBackPressedCallback.setEnabled(enabled); + return; + } + // Keep the commit-only callback off so it does not steal the gesture without progress. + mBackPressedCallback.setEnabled(false); + if (enabled) { + if (mInAppPredictiveBack == null) { + mInAppPredictiveBack = InAppPredictiveBack.register(this); + } + } else if (mInAppPredictiveBack != null) { + InAppPredictiveBack.unregister(this, mInAppPredictiveBack); + mInAppPredictiveBack = null; + } + } + + void notifyJsHardwareBackPressed() { + mDelegate.onBackPressed(); + } + @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); @@ -242,6 +296,317 @@ protected final void loadApp(String appKey) { mDelegate.loadApp(appKey); } + /** + * Isolated so that {@link OnBackAnimationCallback} (API 34) is only loaded when in-app predictive + * back is enabled, and not from {@link ReactActivity} fields or method signatures. + */ + @RequiresApi(34) + private static final class InAppPredictiveBack { + + static Object register(ReactActivity activity) { + Callback callback = new Callback(activity); + activity + .getOnBackInvokedDispatcher() + .registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT, callback); + return callback; + } + + static void unregister(ReactActivity activity, Object callback) { + if (callback instanceof OnBackInvokedCallback) { + activity + .getOnBackInvokedDispatcher() + .unregisterOnBackInvokedCallback((OnBackInvokedCallback) callback); + } + } + + private static final class Callback implements OnBackAnimationCallback { + private static final float MAX_SCALE_DELTA = 0.1f; + private static final float MAX_CORNER_RADIUS_DP = 32f; + private static final float MAX_SHADOW_Z_DP = 24f; + private static final long CANCEL_DURATION_MS = 250; + private static final long COMMIT_DURATION_MS = 220; + private static final float COMMIT_SCALE = 0.8f; + private static final float COMMIT_TRANSLATION_FRACTION = 0.12f; + // System progress hits 1.0 well before a full-screen swipe. Decide commit + // from actual travel so a short drag snaps back instead of popping. + private static final float COMMIT_DISTANCE_FRACTION = 0.25f; + private static final float COMMIT_VELOCITY_DP_PER_S = 900f; + + private final ReactActivity activity; + private @Nullable View frontPane; + private @Nullable ViewGroup paneParent; + private boolean parentClippedChildren; + private boolean parentClippedToPadding; + private float originalElevation; + private float cornerRadiusPx; + private boolean gestureCancelled; + private int swipeEdge; + private float startTouchX; + private float lastTouchX; + private long lastEventTimeMs; + private float velocityPxPerS; + private float lastProgress; + + Callback(ReactActivity activity) { + this.activity = activity; + } + + @Override + public void onBackStarted(BackEvent backEvent) { + gestureCancelled = false; + swipeEdge = backEvent.getSwipeEdge(); + startTouchX = backEvent.getTouchX(); + lastTouchX = startTouchX; + lastEventTimeMs = SystemClock.uptimeMillis(); + velocityPxPerS = 0f; + lastProgress = 0f; + frontPane = findFrontPane(); + if (frontPane == null) { + Log.i(PREDICTIVE_BACK_TAG, "in-app: back started, no front pane"); + return; + } + Log.i( + PREDICTIVE_BACK_TAG, + "in-app: back started pane=" + + frontPane.getClass().getSimpleName() + + " " + + frontPane.getWidth() + + "x" + + frontPane.getHeight()); + originalElevation = frontPane.getElevation(); + prepareParentForShadow(frontPane); + frontPane.setAlpha(1f); + frontPane.animate().cancel(); + frontPane.setClipToOutline(true); + frontPane.setOutlineProvider( + new ViewOutlineProvider() { + @Override + public void getOutline(View view, Outline outline) { + outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), cornerRadiusPx); + } + }); + applyProgress(backEvent); + } + + @Override + public void onBackProgressed(BackEvent backEvent) { + if (frontPane == null) { + frontPane = findFrontPane(); + if (frontPane == null) { + return; + } + } + applyProgress(backEvent); + } + + @Override + public void onBackCancelled() { + Log.i(PREDICTIVE_BACK_TAG, "in-app: back cancelled"); + cancelGesture(); + } + + @Override + public void onBackInvoked() { + if (gestureCancelled) { + return; + } + if (!shouldCommit()) { + Log.i( + PREDICTIVE_BACK_TAG, + "in-app: swipe too short, snapping back distance=" + + Math.abs(lastTouchX - startTouchX) + + " progress=" + + lastProgress); + cancelGesture(); + return; + } + commitGesture(); + } + + private void commitGesture() { + Log.i(PREDICTIVE_BACK_TAG, "in-app: back committed, finishing animation"); + if (frontPane == null) { + activity.notifyJsHardwareBackPressed(); + return; + } + final View pane = frontPane; + float width = pane.getWidth(); + float translationX = + swipeEdge == BackEvent.EDGE_LEFT + ? width * COMMIT_TRANSLATION_FRACTION + : -width * COMMIT_TRANSLATION_FRACTION; + cornerRadiusPx = + MAX_CORNER_RADIUS_DP * activity.getResources().getDisplayMetrics().density; + pane.invalidateOutline(); + float shadowZ = + MAX_SHADOW_Z_DP * activity.getResources().getDisplayMetrics().density; + pane.setElevation(originalElevation + shadowZ); + pane.animate().cancel(); + pane.animate() + .scaleX(COMMIT_SCALE) + .scaleY(COMMIT_SCALE) + .translationX(translationX) + .translationZ(shadowZ) + .alpha(0f) + .setDuration(COMMIT_DURATION_MS) + .setInterpolator(new PathInterpolator(0.4f, 0f, 1f, 1f)) + .withEndAction( + () -> { + restoreParentClip(); + if (activity.isFinishing() || activity.isDestroyed()) { + return; + } + if (frontPane == pane) { + frontPane = null; + } + activity.notifyJsHardwareBackPressed(); + }) + .start(); + } + + private boolean shouldCommit() { + float width = frontPane != null ? frontPane.getWidth() : 0f; + float distancePx = Math.abs(lastTouchX - startTouchX); + int touchSlop = ViewConfiguration.get(activity).getScaledTouchSlop(); + if (distancePx <= touchSlop) { + // No drag reported. Either a 3-button press, or touch coords were + // missing; fall back to progress so a short gesture can still cancel. + return lastProgress < 0.05f || lastProgress >= 0.5f; + } + boolean farEnough = width > 0 && distancePx >= width * COMMIT_DISTANCE_FRACTION; + float density = activity.getResources().getDisplayMetrics().density; + float commitVelocityPx = COMMIT_VELOCITY_DP_PER_S * density; + float commitVelocity = + swipeEdge == BackEvent.EDGE_LEFT ? velocityPxPerS : -velocityPxPerS; + boolean flung = commitVelocity >= commitVelocityPx; + return farEnough || flung; + } + + private void cancelGesture() { + gestureCancelled = true; + resetFrontPane(true); + } + + private @Nullable View findFrontPane() { + View root = activity.getWindow().getDecorView(); + View tagged = findLastViewWithNativeId(root, PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID); + if (tagged == null) { + return null; + } + // Never scrub the activity/root wrapper: that scales the whole tree, + // including the destination screen, which is what we want to reveal. + if (tagged == root || tagged == activity.findViewById(android.R.id.content)) { + return null; + } + return tagged; + } + + private static @Nullable View findLastViewWithNativeId(View root, String nativeId) { + View match = null; + if (nativeId.equals(root.getTag(com.facebook.react.R.id.view_tag_native_id))) { + match = root; + } + if (root instanceof ViewGroup) { + ViewGroup group = (ViewGroup) root; + for (int i = 0; i < group.getChildCount(); i++) { + View childMatch = findLastViewWithNativeId(group.getChildAt(i), nativeId); + if (childMatch != null) { + match = childMatch; + } + } + } + return match; + } + + private void applyProgress(BackEvent backEvent) { + if (frontPane == null) { + return; + } + long now = SystemClock.uptimeMillis(); + float touchX = backEvent.getTouchX(); + if (lastEventTimeMs > 0 && now > lastEventTimeMs) { + velocityPxPerS = (touchX - lastTouchX) * 1000f / (now - lastEventTimeMs); + } + lastTouchX = touchX; + lastEventTimeMs = now; + lastProgress = backEvent.getProgress(); + float progress = lastProgress; + float density = activity.getResources().getDisplayMetrics().density; + float scale = 1f - (MAX_SCALE_DELTA * progress); + frontPane.setScaleX(scale); + frontPane.setScaleY(scale); + float maxTranslation = frontPane.getWidth() / 20f; + float translationX = + backEvent.getSwipeEdge() == BackEvent.EDGE_LEFT + ? maxTranslation * progress + : -maxTranslation * progress; + frontPane.setTranslationX(translationX); + frontPane.setElevation(originalElevation + MAX_SHADOW_Z_DP * progress * density); + frontPane.setTranslationZ(MAX_SHADOW_Z_DP * progress * density); + cornerRadiusPx = MAX_CORNER_RADIUS_DP * progress * density; + frontPane.invalidateOutline(); + } + + private void prepareParentForShadow(View pane) { + if (!(pane.getParent() instanceof ViewGroup)) { + paneParent = null; + return; + } + paneParent = (ViewGroup) pane.getParent(); + parentClippedChildren = paneParent.getClipChildren(); + parentClippedToPadding = paneParent.getClipToPadding(); + paneParent.setClipChildren(false); + paneParent.setClipToPadding(false); + } + + private void restoreParentClip() { + if (paneParent == null) { + return; + } + paneParent.setClipChildren(parentClippedChildren); + paneParent.setClipToPadding(parentClippedToPadding); + paneParent = null; + } + + private void resetFrontPane(boolean animate) { + if (frontPane == null) { + return; + } + cornerRadiusPx = 0f; + if (animate) { + frontPane + .animate() + .scaleX(1f) + .scaleY(1f) + .translationX(0f) + .translationZ(0f) + .alpha(1f) + .setDuration(CANCEL_DURATION_MS) + .setInterpolator(new DecelerateInterpolator()) + .withEndAction( + () -> { + if (frontPane != null) { + frontPane.setElevation(originalElevation); + frontPane.invalidateOutline(); + } + restoreParentClip(); + }) + .start(); + } else { + frontPane.animate().cancel(); + frontPane.setScaleX(1f); + frontPane.setScaleY(1f); + frontPane.setTranslationX(0f); + frontPane.setTranslationZ(0f); + frontPane.setAlpha(1f); + frontPane.setElevation(originalElevation); + frontPane.invalidateOutline(); + restoreParentClip(); + } + } + } + } + /** * Isolated so that {@link OnBackInvokedCallback} (API 33) is only loaded when predictive back is * active, and not from {@link ReactActivity} fields or method signatures. diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt index 9ee720cf8bbc..491b0e8a50ec 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt @@ -10,6 +10,7 @@ package com.facebook.react.modules.core import android.net.Uri import com.facebook.fbreact.specs.NativeDeviceEventManagerSpec import com.facebook.proguard.annotations.DoNotStripAny +import com.facebook.react.ReactActivity import com.facebook.react.bridge.JavaScriptModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.UiThreadUtil @@ -59,6 +60,22 @@ public open class DeviceEventManagerModule( reactApplicationContext.runOnUiQueueThread(invokeDefaultBackPressRunnable) } + /** + * Enables or disables in-app back interception. + * + * When enabled on Android 16+, RN registers a predictive-back animation callback that scrubs + * the view tagged with [ReactActivity.PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID]. When disabled, the + * system handles the gesture and the navigation-observer still notifies JS on app-exit commit. + */ + override fun setInterceptEnabled(enabled: Boolean) { + reactApplicationContext.runOnUiQueueThread { + val activity = reactApplicationContext.currentActivity + if (activity is ReactActivity) { + activity.setInterceptEnabled(enabled) + } + } + } + public companion object { public const val NAME: String = NativeDeviceEventManagerSpec.NAME } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt index 915cbb4df68b..ced3fd4e6bd7 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt @@ -61,6 +61,25 @@ class ReactActivityBackPressedCallbackTest { assertThat(activity.delegatedBackPressCount).isEqualTo(0) } + @Test + fun setInterceptEnabled_true_enablesCallbackBelowApi36() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.backPressedCallback.isEnabled = false + + activity.setInterceptEnabled(true) + + assertThat(activity.backPressedCallback.isEnabled).isTrue() + } + + @Test + fun setInterceptEnabled_false_disablesCallbackBelowApi36() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + + activity.setInterceptEnabled(false) + + assertThat(activity.backPressedCallback.isEnabled).isFalse() + } + class TestReactActivity : ReactActivity() { var delegatedBackPressCount: Int = 0 diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index c0f8309f0ac5..c910eacf7d13 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -4861,6 +4861,7 @@ declare type TBackHandler = { remove: () => void } exitApp(): void + setInterceptEnabled(enabled: boolean): void } declare type Text = typeof Text declare type TextBaseProps = { diff --git a/packages/react-native/src/private/specs_DEPRECATED/modules/NativeDeviceEventManager.js b/packages/react-native/src/private/specs_DEPRECATED/modules/NativeDeviceEventManager.js index 4efff76e66a0..ba61662176ed 100644 --- a/packages/react-native/src/private/specs_DEPRECATED/modules/NativeDeviceEventManager.js +++ b/packages/react-native/src/private/specs_DEPRECATED/modules/NativeDeviceEventManager.js @@ -14,6 +14,7 @@ import * as TurboModuleRegistry from '../../../../Libraries/TurboModule/TurboMod export interface Spec extends TurboModule { readonly invokeDefaultBackPressHandler: () => void; + readonly setInterceptEnabled: (enabled: boolean) => void; } export default TurboModuleRegistry.get('DeviceEventManager') as ?Spec; diff --git a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts index ac2a530a9c05..f6f0347c0f32 100644 --- a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts +++ b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts @@ -38,6 +38,14 @@ export interface BackHandlerStatic { eventName: BackPressEventName, handler: (event: HardwareBackPressEvent) => boolean | null | undefined, ): NativeEventSubscription; + /** + * Android only. When true, React Native consumes the back gesture so + * BackHandler can pop an in-app screen. On Android 16+, a view tagged + * with nativeID "predictiveBackFrontPane" is scrubbed during the swipe. + * When false, the system predictive-back animation can run; BackHandler + * still observes app-exit commit. + */ + setInterceptEnabled(enabled: boolean): void; } export const BackHandler: BackHandlerStatic; diff --git a/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.kt b/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.kt index 4c762618a7dc..385eb132c357 100644 --- a/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.kt +++ b/packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterActivity.kt @@ -63,9 +63,9 @@ internal open class RNTesterActivity : ReactActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - // Lets the system predictive-back animation run. JS BackHandler still - // receives app-exit via PRIORITY_SYSTEM_NAVIGATION_OBSERVER; it cannot prevent it. - // Remove this line to restore RNTester's in-example back navigation. + // Lets the system predictive-back animation run on the root list. JS + // BackHandler.setInterceptEnabled(true) turns on in-app predictive back + // when an example is open. backPressedCallback.isEnabled = false fullyDrawnReporter.addReporter() diff --git a/packages/rn-tester/js/RNTesterAppShared.js b/packages/rn-tester/js/RNTesterAppShared.js index 3bfbde0edbd3..35a2b7e79855 100644 --- a/packages/rn-tester/js/RNTesterAppShared.js +++ b/packages/rn-tester/js/RNTesterAppShared.js @@ -128,6 +128,7 @@ const RNTesterApp = ({ handleBackPress(); return true; } + console.log('[PredictiveBack] hardwareBackPress at root (observer)'); return false; }; @@ -135,7 +136,19 @@ const RNTesterApp = ({ 'hardwareBackPress', handleHardwareBackPress, ); - return () => subscription.remove(); + if (Platform.OS === 'android') { + // Consume back only when an example is open so the list can peek + // through during in-app predictive back. On the root list, leave + // intercept off so the system back-to-home animation can run. + BackHandler.setInterceptEnabled(activeModuleKey != null); + BackHandler.setInterceptEnabled(activeModuleKey != null); + } + return () => { + subscription.remove(); + if (Platform.OS === 'android') { + BackHandler.setInterceptEnabled(false); + } + }; }, [activeModuleKey, handleBackPress]); const handleModuleCardPress = useCallback( @@ -280,12 +293,9 @@ const RNTesterApp = ({ activeModuleExampleKey != null ? activeModule?.examples.find(e => e.name === activeModuleExampleKey) : null; + const listTitle = screen === Screens.COMPONENTS ? 'Components' : 'APIs'; const title = - activeModuleTitle != null - ? activeModuleTitle - : screen === Screens.COMPONENTS - ? 'Components' - : 'APIs'; + activeModuleTitle != null ? activeModuleTitle : listTitle; const BackButtonComponent: ?BackButton = customBackButton ? customBackButton @@ -301,38 +311,38 @@ const RNTesterApp = ({ // Hide chrome if we don't have much screen space and are showing UI for tests const shouldHideChrome = isScreenTiny && hadDeepLink; - const titleBar = shouldHideChrome ? null : ( - - {activeModule && BackButtonComponent ? ( - - ) : undefined} - - ); + if (Platform.OS === 'ios') { + const titleBar = shouldHideChrome ? null : ( + + {activeModule && BackButtonComponent ? ( + + ) : undefined} + + ); - const content = ( - - {activeModule != null ? ( - - ) : ( - - )} - - ); + const content = ( + + {activeModule != null ? ( + + ) : ( + + )} + + ); - if (Platform.OS === 'ios') { return ( - {Platform.OS === 'android' ? : null} - {titleBar} - {content} + const listPane = ( + <> + {!shouldHideChrome && } + + + {!shouldHideChrome && ( )} + + ); + + const modulePane = + activeModule != null ? ( + <> + {!shouldHideChrome && ( + + {BackButtonComponent ? ( + + ) : undefined} + + )} + + + + {!shouldHideChrome && ( + + + + )} + + ) : null; + + return ( + + {Platform.OS === 'android' ? : null} + + + {listPane} + + {modulePane != null ? ( + // In-flow so it fills the screen and paints on top. nativeID must + // match ReactActivity.PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID. + + {modulePane} + + ) : null} + ); @@ -391,6 +481,23 @@ const RNTesterApp = ({ export default RNTesterApp; const styles = StyleSheet.create({ + stack: { + flex: 1, + }, + // Previous screen: taken out of flow so it stays mounted behind the example. + backPane: { + position: 'absolute', + top: 0, + left: 0, + right: 0, + bottom: 0, + zIndex: 0, + }, + // Current screen: in-flow, fills the parent, drawn last (on top). + frontPane: { + flex: 1, + zIndex: 1, + }, container: { flex: 1, }, diff --git a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js index c337c29097f3..9cdd59ed25d5 100644 --- a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js +++ b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js @@ -29,9 +29,9 @@ function Playground() { const line = `${new Date().toISOString()} hardwareBackPress`; console.log('[PredictiveBack]', line); setEvents(current => [line, ...current].slice(0, 8)); - // Returning true cannot cancel a system-handled exit. If the observer - // is working, the app still closes after this log. - return true; + // Let RNTester's root handler pop this example. Return true only + // if you want to consume and stay here. + return false; }, ); @@ -40,28 +40,31 @@ function Playground() { return ( - - Predictive back observer - + Predictive back - RNTesterActivity disables React Native's consuming back callback so - Android can play the system predictive-back animation. A - PRIORITY_SYSTEM_NAVIGATION_OBSERVER still delivers hardwareBackPress - to JS on commit. + Nested screens keep the list mounted underneath. Swipe from the edge + and hold: the example pane should shrink and the list should peek + through. The root list leaves intercept off so Android can play + back-to-home. 1. API 36 device/AVD, gesture navigation, animations on. - 2. Drag slowly inward from the left or right edge and hold. The - activity should shrink and home should peek through. + 2. From this Playground screen, swipe from the edge and hold: the + Components list should peek behind this pane. Swipe far (or flick) + and release: this pane should keep shrinking and fade out, then pop. + Release early to cancel: this pane should spring back to full screen. + The app must not close. - 3. Release to commit: Metro should log [PredictiveBack] and the app - should still close. Returning true cannot prevent that exit. + 3. From the root list, swipe from the edge and hold: the activity + should shrink and home should peek through. Release to exit; Metro + logs [PredictiveBack]. Returning true cannot prevent that exit. - 4. Release early to cancel: no JS event, activity springs back. + 4. From the root list, release early to cancel: no JS event, activity + springs back. JS events {events.length === 0 ? ( From bd86be5887b57fffbe16b988cb415d4a3b2eaa11 Mon Sep 17 00:00:00 2001 From: Grzegorz Kruk Date: Thu, 3 Sep 2026 10:36:06 +0200 Subject: [PATCH 03/11] Add predictive back navigation support to BackHandler and ReactActivity Summary: - Introduced `PredictiveBackAnimatedView` and related types for handling predictive back gestures in React Native. - Enhanced `BackHandler` to support predictive back events, allowing developers to listen for gesture phases and progress. - Updated `ReactActivity` to manage predictive back handlers and events, improving back navigation experience on Android. - Added unit tests to validate the new predictive back functionality and ensure proper event handling. Changelog: [GENERAL][ADDED] - Support for predictive back navigation in BackHandler and ReactActivity. --- .../Utilities/BackHandler.android.js | 66 ++++++- .../Libraries/Utilities/BackHandler.ios.js | 18 ++ .../Libraries/Utilities/BackHandler.js.flow | 18 ++ .../Utilities/__mocks__/BackHandler.js | 16 +- .../Utilities/__tests__/BackHandler-itest.js | 40 ++++ .../ReactAndroid/api/ReactAndroid.api | 20 ++ .../facebook/react/PredictiveBackEvent.java | 32 ++++ .../facebook/react/PredictiveBackHandler.java | 30 +++ .../com/facebook/react/ReactActivity.java | 172 ++++++++++++++++-- .../modules/core/DeviceEventManagerModule.kt | 5 +- .../ReactActivityBackPressedCallbackTest.kt | 91 +++++++++ packages/react-native/ReactNativeApi.d.ts | 15 +- packages/react-native/index.js.flow | 6 +- .../Libraries/Utilities/BackHandler.d.ts | 24 ++- packages/rn-tester/js/RNTesterAppShared.js | 4 +- .../examples/Playground/RNTesterPlayground.js | 31 ++-- 16 files changed, 544 insertions(+), 44 deletions(-) create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackEvent.java create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackHandler.java diff --git a/packages/react-native/Libraries/Utilities/BackHandler.android.js b/packages/react-native/Libraries/Utilities/BackHandler.android.js index 5469cbaba457..f90f1929d087 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.android.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.android.js @@ -14,11 +14,23 @@ import RCTDeviceEventEmitter from '../EventEmitter/RCTDeviceEventEmitter'; import {HardwareBackPressEvent} from './HardwareBackPressEvent'; const DEVICE_BACK_EVENT = 'hardwareBackPress'; +const PREDICTIVE_BACK_EVENT = 'predictiveBack'; type BackPressEventName = 'backPress' | 'hardwareBackPress'; type BackPressHandler = (event: HardwareBackPressEvent) => ?boolean; +export type PredictiveBackPhase = 'start' | 'progress' | 'cancel' | 'commit'; +export type PredictiveBackEvent = { + phase: PredictiveBackPhase, + progress: number, + swipeEdge: number, + touchX: number, + touchY: number, +}; +type PredictiveBackListener = (event: PredictiveBackEvent) => void; + const _backPressSubscriptions: Array = []; +const _predictiveBackSubscriptions: Array = []; RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function (nativeEvent) { const options = {}; @@ -36,6 +48,22 @@ RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function (nativeEvent) { BackHandler.exitApp(); }); +RCTDeviceEventEmitter.addListener( + PREDICTIVE_BACK_EVENT, + function (nativeEvent) { + const event: PredictiveBackEvent = { + phase: nativeEvent?.phase ?? 'progress', + progress: nativeEvent?.progress ?? 0, + swipeEdge: nativeEvent?.swipeEdge ?? 2, + touchX: nativeEvent?.touchX ?? 0, + touchY: nativeEvent?.touchY ?? 0, + }; + for (let i = _predictiveBackSubscriptions.length - 1; i >= 0; i--) { + _predictiveBackSubscriptions[i]?.(event); + } + }, +); + /** * Detects hardware button presses for back navigation and lets you register * event listeners for the system's back action. Event subscriptions are called @@ -54,11 +82,21 @@ type TBackHandler = { /** * Android only. When true, React Native consumes the back gesture so * BackHandler can pop an in-app screen. On Android 16+, a view tagged - * with nativeID "predictiveBackFrontPane" is scrubbed during the swipe. - * When false, the system predictive-back animation can run; BackHandler - * still observes app-exit commit. + * with nativeID "predictiveBackFrontPane" is scrubbed during the swipe + * unless a native PredictiveBackHandler is registered. When false, the + * system predictive-back animation can run; BackHandler still observes + * app-exit commit. */ readonly setInterceptEnabled: (enabled: boolean) => void, + /** + * Android only. Observes in-app predictive-back phases. Progress is + * throttled and is not suitable for 60fps animation; native libraries + * should use PredictiveBackHandler on ReactActivity instead. + */ + readonly addPredictiveBackListener: (handler: PredictiveBackListener) => { + remove: () => void, + ... + }, }; const BackHandler: TBackHandler = { /** @@ -100,6 +138,28 @@ const BackHandler: TBackHandler = { }, }; }, + + /** + * Listen for in-app predictive-back phases (`start`, `progress`, + * `cancel`, `commit`). Returning a value does not consume the gesture; + * use `setInterceptEnabled` or a native `PredictiveBackHandler` for that. + */ + addPredictiveBackListener: function (handler: PredictiveBackListener): { + remove: () => void, + ... + } { + if (_predictiveBackSubscriptions.indexOf(handler) === -1) { + _predictiveBackSubscriptions.push(handler); + } + return { + remove: (): void => { + const index = _predictiveBackSubscriptions.indexOf(handler); + if (index !== -1) { + _predictiveBackSubscriptions.splice(index, 1); + } + }, + }; + }, }; export default BackHandler; diff --git a/packages/react-native/Libraries/Utilities/BackHandler.ios.js b/packages/react-native/Libraries/Utilities/BackHandler.ios.js index 6c3c19cd24f9..61b1d412e5aa 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.ios.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.ios.js @@ -13,6 +13,15 @@ import type {HardwareBackPressEvent} from './HardwareBackPressEvent'; type BackPressEventName = 'backPress' | 'hardwareBackPress'; type BackPressHandler = (event: HardwareBackPressEvent) => ?boolean; +export type PredictiveBackPhase = 'start' | 'progress' | 'cancel' | 'commit'; +export type PredictiveBackEvent = { + phase: PredictiveBackPhase, + progress: number, + swipeEdge: number, + touchX: number, + touchY: number, +}; + function emptyFunction(): void {} type TBackHandler = { @@ -22,6 +31,10 @@ type TBackHandler = { handler: BackPressHandler, ): {remove: () => void, ...}, setInterceptEnabled(enabled: boolean): void, + addPredictiveBackListener(handler: (event: PredictiveBackEvent) => void): { + remove: () => void, + ... + }, }; const BackHandler: TBackHandler = { @@ -32,6 +45,11 @@ const BackHandler: TBackHandler = { }; }, setInterceptEnabled(_enabled: boolean): void {}, + addPredictiveBackListener(_handler: (event: PredictiveBackEvent) => void) { + return { + remove: emptyFunction, + }; + }, }; export default BackHandler; diff --git a/packages/react-native/Libraries/Utilities/BackHandler.js.flow b/packages/react-native/Libraries/Utilities/BackHandler.js.flow index 3e8f68a16762..0e66e08c8d25 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.js.flow +++ b/packages/react-native/Libraries/Utilities/BackHandler.js.flow @@ -22,6 +22,20 @@ export interface HardwareBackPressEvent { readonly timeStamp: number; } +export type PredictiveBackPhase = 'start' | 'progress' | 'cancel' | 'commit'; + +/** + * Observational copy of an in-app predictive-back gesture. Progress is + * throttled and is not suitable for 60fps animation. + */ +export type PredictiveBackEvent = { + phase: PredictiveBackPhase, + progress: number, + swipeEdge: number, + touchX: number, + touchY: number, +}; + type TBackHandler = { exitApp(): void, addEventListener( @@ -29,6 +43,10 @@ type TBackHandler = { handler: (event: HardwareBackPressEvent) => ?boolean, ): {remove: () => void, ...}, setInterceptEnabled(enabled: boolean): void, + addPredictiveBackListener(handler: (event: PredictiveBackEvent) => void): { + remove: () => void, + ... + }, }; /** diff --git a/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js b/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js index 0523898fd782..ea417f7c3d0b 100644 --- a/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js +++ b/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js @@ -8,7 +8,7 @@ * @format */ -import type {BackPressEventName} from '../BackHandler'; +import type {BackPressEventName, PredictiveBackEvent} from '../BackHandler'; import type {HardwareBackPressEvent} from '../HardwareBackPressEvent'; import {HardwareBackPressEvent as HardwareBackPressEventClass} from '../HardwareBackPressEvent'; @@ -16,11 +16,25 @@ import {HardwareBackPressEvent as HardwareBackPressEventClass} from '../Hardware const _backPressSubscriptions = new Set< (event: HardwareBackPressEvent) => ?boolean, >(); +const _predictiveBackSubscriptions = new Set< + (event: PredictiveBackEvent) => void, +>(); const BackHandler = { exitApp: jest.fn() as () => void, setInterceptEnabled: jest.fn() as (enabled: boolean) => void, + addPredictiveBackListener: function ( + handler: (event: PredictiveBackEvent) => void, + ): {remove: () => void, ...} { + _predictiveBackSubscriptions.add(handler); + return { + remove: () => { + _predictiveBackSubscriptions.delete(handler); + }, + }; + }, + addEventListener: function ( eventName: BackPressEventName, handler: (event: HardwareBackPressEvent) => ?boolean, diff --git a/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js b/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js index 2dfec3786236..f6499833a4e3 100644 --- a/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js +++ b/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js @@ -141,4 +141,44 @@ describe('BackHandler', () => { expect(called).toBe(false); }); + + it('notifies predictiveBack listeners in reverse order', () => { + const callOrder: Array = []; + subscriptions.push( + BackHandler.addPredictiveBackListener(event => { + callOrder.push(`first:${event.phase}`); + }), + ); + subscriptions.push( + BackHandler.addPredictiveBackListener(event => { + callOrder.push(`second:${event.phase}`); + }), + ); + + RCTDeviceEventEmitter.emit('predictiveBack', { + phase: 'start', + progress: 0, + swipeEdge: 0, + touchX: 1, + touchY: 2, + }); + + expect(callOrder).toEqual(['second:start', 'first:start']); + }); + + it('does not call exitApp for predictiveBack', () => { + const exitApp = jest.spyOn(BackHandler, 'exitApp'); + subscriptions.push(BackHandler.addPredictiveBackListener(() => {})); + + RCTDeviceEventEmitter.emit('predictiveBack', { + phase: 'commit', + progress: 1, + swipeEdge: 0, + touchX: 0, + touchY: 0, + }); + + expect(exitApp).not.toHaveBeenCalled(); + exitApp.mockRestore(); + }); }); diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index 319bdc8b38c4..9dd42742c65f 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -58,9 +58,28 @@ public final class com/facebook/react/NativeModuleRegistryBuilder { public final fun processPackage (Lcom/facebook/react/ReactPackage;)V } +public final class com/facebook/react/PredictiveBackEvent { + public static final field EDGE_LEFT I + public static final field EDGE_NONE I + public static final field EDGE_RIGHT I + public final field progress F + public final field swipeEdge I + public final field touchX F + public final field touchY F + public fun (FIFF)V +} + +public abstract interface class com/facebook/react/PredictiveBackHandler { + public abstract fun onPredictiveBackCancelled ()V + public abstract fun onPredictiveBackCommitted ()Z + public abstract fun onPredictiveBackProgressed (Lcom/facebook/react/PredictiveBackEvent;)V + public abstract fun onPredictiveBackStarted (Lcom/facebook/react/PredictiveBackEvent;)V +} + public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/AppCompatActivity, com/facebook/react/modules/core/DefaultHardwareBackBtnHandler, com/facebook/react/modules/core/PermissionAwareActivity { public static final field PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID Ljava/lang/String; protected fun ()V + public fun addPredictiveBackHandler (Lcom/facebook/react/PredictiveBackHandler;)V protected fun createReactActivityDelegate ()Lcom/facebook/react/ReactActivityDelegate; public fun getBackPressedCallback ()Landroidx/activity/OnBackPressedCallback; protected fun getMainComponentName ()Ljava/lang/String; @@ -85,6 +104,7 @@ public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/ protected fun onResume ()V public fun onUserLeaveHint ()V public fun onWindowFocusChanged (Z)V + public fun removePredictiveBackHandler (Lcom/facebook/react/PredictiveBackHandler;)V public fun requestPermissions ([Ljava/lang/String;ILcom/facebook/react/modules/core/PermissionListener;)V public fun setInterceptEnabled (Z)V } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackEvent.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackEvent.java new file mode 100644 index 000000000000..09eeaecc2729 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackEvent.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react; + +/** + * Progress of an in-app predictive-back gesture. Native libraries (for example + * react-native-screens) receive this on the UI thread. JavaScript receives a copy via {@code + * BackHandler.addPredictiveBackListener}; that path is not suitable for 60fps animation. + */ +public final class PredictiveBackEvent { + + public static final int EDGE_LEFT = 0; + public static final int EDGE_RIGHT = 1; + public static final int EDGE_NONE = 2; + + public final float progress; + public final int swipeEdge; + public final float touchX; + public final float touchY; + + public PredictiveBackEvent(float progress, int swipeEdge, float touchX, float touchY) { + this.progress = progress; + this.swipeEdge = swipeEdge; + this.touchX = touchX; + this.touchY = touchY; + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackHandler.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackHandler.java new file mode 100644 index 000000000000..a0c979f96f1d --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackHandler.java @@ -0,0 +1,30 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react; + +/** + * Native plugin for predictive back. Register on {@link ReactActivity} with {@link + * ReactActivity#addPredictiveBackHandler}. While at least one handler is registered, React Native + * consumes the Android back gesture and delivers progress here instead of (or in addition to) JS. + * + *

If {@link #onPredictiveBackCommitted()} returns {@code true}, JS {@code hardwareBackPress} is + * not emitted, so JS and this handler cannot both pop. + */ +public interface PredictiveBackHandler { + + void onPredictiveBackStarted(PredictiveBackEvent event); + + void onPredictiveBackProgressed(PredictiveBackEvent event); + + void onPredictiveBackCancelled(); + + /** + * @return {@code true} if this handler consumed the commit (for example popped a native screen). + */ + boolean onPredictiveBackCommitted(); +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java index 794f6d9ce151..ae07f302fb14 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java @@ -29,10 +29,15 @@ import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; +import com.facebook.react.bridge.Arguments; +import com.facebook.react.bridge.ReactContext; +import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.modules.core.PermissionAwareActivity; import com.facebook.react.modules.core.PermissionListener; import com.facebook.react.util.AndroidVersion; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; import org.jetbrains.annotations.NotNull; /** Base Activity for React Native applications. */ @@ -46,6 +51,10 @@ public abstract class ReactActivity extends AppCompatActivity public static final String PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID = "predictiveBackFrontPane"; private static final String PREDICTIVE_BACK_TAG = "PredictiveBack"; + private static final String PREDICTIVE_BACK_JS_EVENT = "predictiveBack"; + private static final long JS_PROGRESS_THROTTLE_MS = 32; + private static final PredictiveBackEvent EMPTY_PREDICTIVE_BACK_EVENT = + new PredictiveBackEvent(0f, PredictiveBackEvent.EDGE_NONE, 0f, 0f); private final ReactActivityDelegate mDelegate; @@ -59,7 +68,7 @@ public abstract class ReactActivity extends AppCompatActivity @Override public void handleOnBackPressed() { setEnabled(false); - onBackPressed(); + finishPredictiveBackCommit(); setEnabled(true); } }; @@ -71,6 +80,11 @@ public void handleOnBackPressed() { // In-app OnBackAnimationCallback. Typed as Object for the same older-device class loading. private @Nullable Object mInAppPredictiveBack; + private boolean mJsInterceptEnabled; + private final List mPredictiveBackHandlers = new CopyOnWriteArrayList<>(); + private PredictiveBackEvent mLastPredictiveBackEvent = EMPTY_PREDICTIVE_BACK_EVENT; + private long mLastJsProgressEmitMs; + @SuppressWarnings("this-escape") protected ReactActivity() { mDelegate = createReactActivityDelegate(); @@ -174,17 +188,43 @@ void onSystemNavigationBackInvoked() { * When {@code true}, React Native consumes the back gesture so JS {@code BackHandler} can pop an * in-app screen. On Android 16+ (targetSdk 36) this registers a platform {@link * OnBackAnimationCallback} that scrubs the view tagged with {@link - * #PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID} during the swipe, revealing whatever is drawn behind it. - * When {@code false}, the system predictive-back animation can run. + * #PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID} during the swipe, revealing whatever is drawn behind it + * — unless a {@link PredictiveBackHandler} is registered, in which case that handler owns the + * animation. When {@code false} and no native handler is registered, the system predictive-back + * animation can run. */ public void setInterceptEnabled(boolean enabled) { + mJsInterceptEnabled = enabled; + updateConsumeCallback(); + } + + /** + * Registers a native plugin (for example react-native-screens) as an owner of the back gesture. + * While any handler is registered, React Native consumes the gesture. If a handler returns {@code + * true} from {@link PredictiveBackHandler#onPredictiveBackCommitted()}, JS {@code + * hardwareBackPress} is not emitted. + */ + public void addPredictiveBackHandler(PredictiveBackHandler handler) { + if (!mPredictiveBackHandlers.contains(handler)) { + mPredictiveBackHandlers.add(handler); + } + updateConsumeCallback(); + } + + public void removePredictiveBackHandler(PredictiveBackHandler handler) { + mPredictiveBackHandlers.remove(handler); + updateConsumeCallback(); + } + + private void updateConsumeCallback() { + boolean consume = mJsInterceptEnabled || !mPredictiveBackHandlers.isEmpty(); if (!AndroidVersion.isAtLeastTargetSdk36(this)) { - mBackPressedCallback.setEnabled(enabled); + mBackPressedCallback.setEnabled(consume); return; } // Keep the commit-only callback off so it does not steal the gesture without progress. mBackPressedCallback.setEnabled(false); - if (enabled) { + if (consume) { if (mInAppPredictiveBack == null) { mInAppPredictiveBack = InAppPredictiveBack.register(this); } @@ -194,6 +234,74 @@ public void setInterceptEnabled(boolean enabled) { } } + boolean shouldScrubDefaultFrontPane() { + return mJsInterceptEnabled && mPredictiveBackHandlers.isEmpty(); + } + + void dispatchPredictiveBackStarted(PredictiveBackEvent event) { + mLastPredictiveBackEvent = event; + mLastJsProgressEmitMs = 0; + for (int i = mPredictiveBackHandlers.size() - 1; i >= 0; i--) { + mPredictiveBackHandlers.get(i).onPredictiveBackStarted(event); + } + emitPredictiveBackToJs("start", event, false); + } + + void dispatchPredictiveBackProgressed(PredictiveBackEvent event) { + mLastPredictiveBackEvent = event; + for (int i = mPredictiveBackHandlers.size() - 1; i >= 0; i--) { + mPredictiveBackHandlers.get(i).onPredictiveBackProgressed(event); + } + emitPredictiveBackToJs("progress", event, true); + } + + void dispatchPredictiveBackCancelled() { + for (int i = mPredictiveBackHandlers.size() - 1; i >= 0; i--) { + mPredictiveBackHandlers.get(i).onPredictiveBackCancelled(); + } + emitPredictiveBackToJs("cancel", mLastPredictiveBackEvent, false); + } + + void finishPredictiveBackCommit() { + boolean consumed = false; + for (int i = mPredictiveBackHandlers.size() - 1; i >= 0; i--) { + if (mPredictiveBackHandlers.get(i).onPredictiveBackCommitted()) { + consumed = true; + break; + } + } + emitPredictiveBackToJs("commit", mLastPredictiveBackEvent, false); + if (!consumed) { + notifyJsHardwareBackPressed(); + } + } + + private void emitPredictiveBackToJs( + String phase, PredictiveBackEvent event, boolean throttleProgress) { + if (throttleProgress) { + long now = SystemClock.uptimeMillis(); + if (mLastJsProgressEmitMs != 0 && now - mLastJsProgressEmitMs < JS_PROGRESS_THROTTLE_MS) { + return; + } + mLastJsProgressEmitMs = now; + } + ReactDelegate reactDelegate = getReactDelegate(); + if (reactDelegate == null) { + return; + } + ReactContext context = reactDelegate.getCurrentReactContext(); + if (context == null) { + return; + } + WritableMap map = Arguments.createMap(); + map.putString("phase", phase); + map.putDouble("progress", event.progress); + map.putInt("swipeEdge", event.swipeEdge); + map.putDouble("touchX", event.touchX); + map.putDouble("touchY", event.touchY); + context.emitDeviceEvent(PREDICTIVE_BACK_JS_EVENT, map); + } + void notifyJsHardwareBackPressed() { mDelegate.onBackPressed(); } @@ -360,6 +468,11 @@ public void onBackStarted(BackEvent backEvent) { lastEventTimeMs = SystemClock.uptimeMillis(); velocityPxPerS = 0f; lastProgress = 0f; + activity.dispatchPredictiveBackStarted(toPredictiveBackEvent(backEvent)); + if (!activity.shouldScrubDefaultFrontPane()) { + Log.i(PREDICTIVE_BACK_TAG, "in-app: back started, native handler owns animation"); + return; + } frontPane = findFrontPane(); if (frontPane == null) { Log.i(PREDICTIVE_BACK_TAG, "in-app: back started, no front pane"); @@ -390,9 +503,15 @@ public void getOutline(View view, Outline outline) { @Override public void onBackProgressed(BackEvent backEvent) { + activity.dispatchPredictiveBackProgressed(toPredictiveBackEvent(backEvent)); + if (!activity.shouldScrubDefaultFrontPane()) { + updateGestureMetrics(backEvent); + return; + } if (frontPane == null) { frontPane = findFrontPane(); if (frontPane == null) { + updateGestureMetrics(backEvent); return; } } @@ -402,6 +521,7 @@ public void onBackProgressed(BackEvent backEvent) { @Override public void onBackCancelled() { Log.i(PREDICTIVE_BACK_TAG, "in-app: back cancelled"); + activity.dispatchPredictiveBackCancelled(); cancelGesture(); } @@ -417,7 +537,7 @@ public void onBackInvoked() { + Math.abs(lastTouchX - startTouchX) + " progress=" + lastProgress); - cancelGesture(); + onBackCancelled(); return; } commitGesture(); @@ -425,8 +545,8 @@ public void onBackInvoked() { private void commitGesture() { Log.i(PREDICTIVE_BACK_TAG, "in-app: back committed, finishing animation"); - if (frontPane == null) { - activity.notifyJsHardwareBackPressed(); + if (!activity.shouldScrubDefaultFrontPane() || frontPane == null) { + activity.finishPredictiveBackCommit(); return; } final View pane = frontPane; @@ -459,13 +579,16 @@ private void commitGesture() { if (frontPane == pane) { frontPane = null; } - activity.notifyJsHardwareBackPressed(); + activity.finishPredictiveBackCommit(); }) .start(); } private boolean shouldCommit() { - float width = frontPane != null ? frontPane.getWidth() : 0f; + float width = + frontPane != null + ? frontPane.getWidth() + : activity.getWindow().getDecorView().getWidth(); float distancePx = Math.abs(lastTouchX - startTouchX); int touchSlop = ViewConfiguration.get(activity).getScaledTouchSlop(); if (distancePx <= touchSlop) { @@ -519,17 +642,10 @@ private void cancelGesture() { } private void applyProgress(BackEvent backEvent) { + updateGestureMetrics(backEvent); if (frontPane == null) { return; } - long now = SystemClock.uptimeMillis(); - float touchX = backEvent.getTouchX(); - if (lastEventTimeMs > 0 && now > lastEventTimeMs) { - velocityPxPerS = (touchX - lastTouchX) * 1000f / (now - lastEventTimeMs); - } - lastTouchX = touchX; - lastEventTimeMs = now; - lastProgress = backEvent.getProgress(); float progress = lastProgress; float density = activity.getResources().getDisplayMetrics().density; float scale = 1f - (MAX_SCALE_DELTA * progress); @@ -547,6 +663,26 @@ private void applyProgress(BackEvent backEvent) { frontPane.invalidateOutline(); } + private void updateGestureMetrics(BackEvent backEvent) { + long now = SystemClock.uptimeMillis(); + float touchX = backEvent.getTouchX(); + if (lastEventTimeMs > 0 && now > lastEventTimeMs) { + velocityPxPerS = (touchX - lastTouchX) * 1000f / (now - lastEventTimeMs); + } + lastTouchX = touchX; + lastEventTimeMs = now; + lastProgress = backEvent.getProgress(); + swipeEdge = backEvent.getSwipeEdge(); + } + + private static PredictiveBackEvent toPredictiveBackEvent(BackEvent backEvent) { + return new PredictiveBackEvent( + backEvent.getProgress(), + backEvent.getSwipeEdge(), + backEvent.getTouchX(), + backEvent.getTouchY()); + } + private void prepareParentForShadow(View pane) { if (!(pane.getParent() instanceof ViewGroup)) { paneParent = null; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt index 491b0e8a50ec..06b1c6aabe7b 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt @@ -64,8 +64,9 @@ public open class DeviceEventManagerModule( * Enables or disables in-app back interception. * * When enabled on Android 16+, RN registers a predictive-back animation callback that scrubs - * the view tagged with [ReactActivity.PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID]. When disabled, the - * system handles the gesture and the navigation-observer still notifies JS on app-exit commit. + * the view tagged with [ReactActivity.PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID], unless a native + * [com.facebook.react.PredictiveBackHandler] is registered. When disabled, the system handles + * the gesture and the navigation-observer still notifies JS on app-exit commit. */ override fun setInterceptEnabled(enabled: Boolean) { reactApplicationContext.runOnUiQueueThread { diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt index ced3fd4e6bd7..b64615bcc34f 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt @@ -80,6 +80,97 @@ class ReactActivityBackPressedCallbackTest { assertThat(activity.backPressedCallback.isEnabled).isFalse() } + @Test + fun addPredictiveBackHandler_enablesCallbackWhenInterceptDisabled() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.setInterceptEnabled(false) + + activity.addPredictiveBackHandler(NoOpPredictiveBackHandler()) + + assertThat(activity.backPressedCallback.isEnabled).isTrue() + } + + @Test + fun removePredictiveBackHandler_disablesCallbackWhenInterceptDisabled() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.setInterceptEnabled(false) + val handler = NoOpPredictiveBackHandler() + activity.addPredictiveBackHandler(handler) + + activity.removePredictiveBackHandler(handler) + + assertThat(activity.backPressedCallback.isEnabled).isFalse() + } + + @Test + fun nativeHandler_receivesStartAndProgress() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + val handler = RecordingPredictiveBackHandler() + activity.addPredictiveBackHandler(handler) + val event = PredictiveBackEvent(0.4f, PredictiveBackEvent.EDGE_LEFT, 12f, 40f) + + activity.dispatchPredictiveBackStarted(event) + activity.dispatchPredictiveBackProgressed(event) + + assertThat(handler.started).containsExactly(event) + assertThat(handler.progressed).containsExactly(event) + } + + @Test + fun finishPredictiveBackCommit_skipsJsWhenNativeHandlerConsumes() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.addPredictiveBackHandler(NoOpPredictiveBackHandler(consumeCommit = true)) + + activity.finishPredictiveBackCommit() + + assertThat(activity.delegatedBackPressCount).isEqualTo(0) + } + + @Test + fun finishPredictiveBackCommit_notifiesJsWhenNoHandlerConsumes() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + + activity.finishPredictiveBackCommit() + + assertThat(activity.delegatedBackPressCount).isEqualTo(1) + } + + @Test + fun shouldScrubDefaultFrontPane_falseWhenNativeHandlerRegistered() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.setInterceptEnabled(true) + assertThat(activity.shouldScrubDefaultFrontPane()).isTrue() + + activity.addPredictiveBackHandler(NoOpPredictiveBackHandler()) + + assertThat(activity.shouldScrubDefaultFrontPane()).isFalse() + } + + private open class NoOpPredictiveBackHandler( + private val consumeCommit: Boolean = false, + ) : PredictiveBackHandler { + override fun onPredictiveBackStarted(event: PredictiveBackEvent) = Unit + + override fun onPredictiveBackProgressed(event: PredictiveBackEvent) = Unit + + override fun onPredictiveBackCancelled() = Unit + + override fun onPredictiveBackCommitted(): Boolean = consumeCommit + } + + private class RecordingPredictiveBackHandler : NoOpPredictiveBackHandler() { + val started = mutableListOf() + val progressed = mutableListOf() + + override fun onPredictiveBackStarted(event: PredictiveBackEvent) { + started.add(event) + } + + override fun onPredictiveBackProgressed(event: PredictiveBackEvent) { + progressed.add(event) + } + } + class TestReactActivity : ReactActivity() { var delegatedBackPressCount: Int = 0 diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index c910eacf7d13..1075b77b69fc 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -3583,6 +3583,14 @@ declare type PointValue = { x: number y: number } +declare type PredictiveBackEvent = { + phase: PredictiveBackPhase + progress: number + swipeEdge: number + touchX: number + touchY: number +} +declare type PredictiveBackPhase = "cancel" | "commit" | "progress" | "start" declare type PresentLocalNotificationDetails = { alertAction?: string alertBody: string @@ -4860,6 +4868,9 @@ declare type TBackHandler = { ): { remove: () => void } + addPredictiveBackListener(handler: (event: PredictiveBackEvent) => void): { + remove: () => void + } exitApp(): void setInterceptEnabled(enabled: boolean): void } @@ -5802,7 +5813,7 @@ export { AssetDestPathResolver, // 59047424 AssetRegistry, // 6070bb45 AutoCapitalize, // c0e857a0 - BackHandler, // f139fc69 + BackHandler, // c0042375 BackPressEventName, // 4620fb76 BlurEvent, // d5e68e96 BoxShadowValue, // b679703f @@ -5949,6 +5960,8 @@ export { PlatformSelectSpec, // 09ed7758 PointValue, // 69db075f PointerEvent, // a506d9d7 + PredictiveBackEvent, // e2919d69 + PredictiveBackPhase, // dcc1122c PressabilityConfig, // 0fd655fe PressabilityEventHandlers, // be359ba3 Pressable, // 56235a5f diff --git a/packages/react-native/index.js.flow b/packages/react-native/index.js.flow index 113127b308b2..d97d72a96a75 100644 --- a/packages/react-native/index.js.flow +++ b/packages/react-native/index.js.flow @@ -288,7 +288,11 @@ export type { PackagerAsset, } from './src/private/assets/AssetRegistry'; -export type {BackPressEventName} from './Libraries/Utilities/BackHandler'; +export type { + BackPressEventName, + PredictiveBackEvent, + PredictiveBackPhase, +} from './Libraries/Utilities/BackHandler'; export {default as BackHandler} from './Libraries/Utilities/BackHandler'; export {default as Clipboard} from './Libraries/Components/Clipboard/Clipboard'; diff --git a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts index f6f0347c0f32..736a87e7d365 100644 --- a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts +++ b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts @@ -21,6 +21,16 @@ export interface HardwareBackPressEvent { readonly timeStamp: number; } +export type PredictiveBackPhase = 'start' | 'progress' | 'cancel' | 'commit'; + +export interface PredictiveBackEvent { + readonly phase: PredictiveBackPhase; + readonly progress: number; + readonly swipeEdge: number; + readonly touchX: number; + readonly touchY: number; +} + /** * Detect hardware back button presses, and programmatically invoke the * default back button functionality to exit the app if there are no @@ -41,11 +51,19 @@ export interface BackHandlerStatic { /** * Android only. When true, React Native consumes the back gesture so * BackHandler can pop an in-app screen. On Android 16+, a view tagged - * with nativeID "predictiveBackFrontPane" is scrubbed during the swipe. - * When false, the system predictive-back animation can run; BackHandler - * still observes app-exit commit. + * with nativeID "predictiveBackFrontPane" is scrubbed during the swipe + * unless a native PredictiveBackHandler is registered. When false, the + * system predictive-back animation can run; BackHandler still observes + * app-exit commit. */ setInterceptEnabled(enabled: boolean): void; + /** + * Android only. Observes in-app predictive-back phases. Progress is + * throttled and is not suitable for 60fps animation. + */ + addPredictiveBackListener( + handler: (event: PredictiveBackEvent) => void, + ): NativeEventSubscription; } export const BackHandler: BackHandlerStatic; diff --git a/packages/rn-tester/js/RNTesterAppShared.js b/packages/rn-tester/js/RNTesterAppShared.js index 35a2b7e79855..55f3d5b1955e 100644 --- a/packages/rn-tester/js/RNTesterAppShared.js +++ b/packages/rn-tester/js/RNTesterAppShared.js @@ -141,7 +141,6 @@ const RNTesterApp = ({ // through during in-app predictive back. On the root list, leave // intercept off so the system back-to-home animation can run. BackHandler.setInterceptEnabled(activeModuleKey != null); - BackHandler.setInterceptEnabled(activeModuleKey != null); } return () => { subscription.remove(); @@ -294,8 +293,7 @@ const RNTesterApp = ({ ? activeModule?.examples.find(e => e.name === activeModuleExampleKey) : null; const listTitle = screen === Screens.COMPONENTS ? 'Components' : 'APIs'; - const title = - activeModuleTitle != null ? activeModuleTitle : listTitle; + const title = activeModuleTitle != null ? activeModuleTitle : listTitle; const BackButtonComponent: ?BackButton = customBackButton ? customBackButton diff --git a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js index 9cdd59ed25d5..97d0de831613 100644 --- a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js +++ b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js @@ -34,33 +34,40 @@ function Playground() { return false; }, ); + const predictive = BackHandler.addPredictiveBackListener(event => { + const line = `${new Date().toISOString()} ${event.phase} progress=${event.progress.toFixed(2)}`; + console.log('[PredictiveBack]', line); + setEvents(current => [line, ...current].slice(0, 8)); + }); - return () => subscription.remove(); + return () => { + subscription.remove(); + predictive.remove(); + }; }, []); return ( Predictive back - Nested screens keep the list mounted underneath. Swipe from the edge - and hold: the example pane should shrink and the list should peek - through. The root list leaves intercept off so Android can play - back-to-home. + Nested screens keep the list mounted underneath. Swipe from the edge and + hold: the example pane should shrink and the list should peek through. + The root list leaves intercept off so Android can play back-to-home. 1. API 36 device/AVD, gesture navigation, animations on. 2. From this Playground screen, swipe from the edge and hold: the - Components list should peek behind this pane. Swipe far (or flick) - and release: this pane should keep shrinking and fade out, then pop. - Release early to cancel: this pane should spring back to full screen. - The app must not close. + Components list should peek behind this pane. Swipe far (or flick) and + release: this pane should keep shrinking and fade out, then pop. Release + early to cancel: this pane should spring back to full screen. The app + must not close. - 3. From the root list, swipe from the edge and hold: the activity - should shrink and home should peek through. Release to exit; Metro - logs [PredictiveBack]. Returning true cannot prevent that exit. + 3. From the root list, swipe from the edge and hold: the activity should + shrink and home should peek through. Release to exit; Metro logs + [PredictiveBack]. Returning true cannot prevent that exit. 4. From the root list, release early to cancel: no JS event, activity From eaf667e4e6d10dae2b30010f28f508e03aabe0b0 Mon Sep 17 00:00:00 2001 From: Grzegorz Kruk Date: Thu, 3 Sep 2026 18:19:59 +0200 Subject: [PATCH 04/11] Add PredictiveBackAnimatedView and related functionality Summary: - Introduced `PredictiveBackAnimatedView` for handling predictive back gestures on Android. - Added `usePredictiveBackAnimatedValue` hook to facilitate animated responses to back gesture progress. - Updated type definitions and flow types to include new predictive back event types and properties. - Enhanced `ReactActivity` to manage predictive back progress listeners without consuming the gesture. - Added unit tests to validate the new predictive back functionality. Changelog: [GENERAL][ADDED] - Support for predictive back navigation with new components and hooks. --- .../PredictiveBackAnimatedView.android.js | 70 ++++++++++++++ .../PredictiveBackAnimatedView.ios.js | 31 ++++++ .../PredictiveBackAnimatedView.js | 16 ++++ .../PredictiveBackAnimatedView.js.flow | 38 ++++++++ ...edictiveBackAnimatedViewNativeComponent.js | 12 +++ .../ReactAndroid/api/ReactAndroid.api | 10 ++ .../facebook/react/PredictiveBackEvent.java | 5 + .../facebook/react/PredictiveBackHandler.java | 3 + .../react/PredictiveBackProgressListener.java | 26 +++++ .../com/facebook/react/ReactActivity.java | 38 ++++++++ .../facebook/react/shell/MainReactPackage.kt | 4 + .../PredictiveBackProgressEvent.kt | 48 ++++++++++ .../ReactPredictiveBackAnimatedView.kt | 49 ++++++++++ .../ReactPredictiveBackAnimatedViewManager.kt | 42 +++++++++ .../ReactActivityBackPressedCallbackTest.kt | 35 +++++++ packages/react-native/ReactNativeApi.d.ts | 21 +++++ packages/react-native/index.js | 8 ++ packages/react-native/index.js.flow | 9 ++ ...edictiveBackAnimatedViewNativeComponent.js | 39 ++++++++ .../PredictiveBackAnimatedView.d.ts | 32 +++++++ .../react-native/types_DEPRECATED/index.d.ts | 1 + .../PredictiveBack/PredictiveBackExample.js | 94 +++++++++++++++++++ .../js/utils/RNTesterList.android.js | 5 + 23 files changed, 636 insertions(+) create mode 100644 packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.android.js create mode 100644 packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.ios.js create mode 100644 packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js create mode 100644 packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js.flow create mode 100644 packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedViewNativeComponent.js create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackProgressListener.java create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/predictiveback/PredictiveBackProgressEvent.kt create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/predictiveback/ReactPredictiveBackAnimatedView.kt create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/predictiveback/ReactPredictiveBackAnimatedViewManager.kt create mode 100644 packages/react-native/src/private/components/predictiveback/specs/PredictiveBackAnimatedViewNativeComponent.js create mode 100644 packages/react-native/types_DEPRECATED/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.d.ts create mode 100644 packages/rn-tester/js/examples/PredictiveBack/PredictiveBackExample.js diff --git a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.android.js b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.android.js new file mode 100644 index 000000000000..755fcb02b55c --- /dev/null +++ b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.android.js @@ -0,0 +1,70 @@ +/** + * 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 {PredictiveBackNativeEvent} from './PredictiveBackAnimatedViewNativeComponent'; + +import Animated from '../../Animated/Animated'; +import useAnimatedValue from '../../Animated/useAnimatedValue'; +import PredictiveBackAnimatedViewNativeComponent from './PredictiveBackAnimatedViewNativeComponent'; +import * as React from 'react'; +import {useMemo} from 'react'; + +/** + * Hidden host view that emits predictive-back progress as a native event. + * + * Drive RN Animated with the native driver: + * + * const progress = useAnimatedValue(0); + * + * + * Drive Reanimated with `useEvent` (no JS per frame): + * + * const progress = useSharedValue(0); + * const onProgress = useEvent((e) => { + * 'worklet'; + * progress.value = e.progress; + * }); + * + * + * @see https://github.com/satya164/react-native-animated-observer + * @platform android + */ +const NativeAnimatedView = Animated.createAnimatedComponent( + PredictiveBackAnimatedViewNativeComponent, +); + +export type {PredictiveBackNativeEvent}; + +export function usePredictiveBackAnimatedValue(): { + progress: Animated.Value, + onProgress: $FlowFixMe, +} { + const progress = useAnimatedValue(0); + const onProgress = useMemo( + () => Animated.event([{nativeEvent: {progress}}], {useNativeDriver: true}), + [progress], + ); + return {progress, onProgress}; +} + +function PredictiveBackAnimatedView( + props: React.ElementConfig, +): React.Node { + return ( + + ); +} + +export default PredictiveBackAnimatedView; diff --git a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.ios.js b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.ios.js new file mode 100644 index 000000000000..e7c1f6513fe1 --- /dev/null +++ b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.ios.js @@ -0,0 +1,31 @@ +/** + * 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 {PredictiveBackNativeEvent} from './PredictiveBackAnimatedViewNativeComponent'; + +import Animated from '../../Animated/Animated'; +import useAnimatedValue from '../../Animated/useAnimatedValue'; +import * as React from 'react'; + +export type {PredictiveBackNativeEvent}; + +function PredictiveBackAnimatedView(_props: {...}): React.Node { + return null; +} + +export function usePredictiveBackAnimatedValue(): { + progress: Animated.Value, + onProgress: $FlowFixMe, +} { + const progress = useAnimatedValue(0); + return {progress, onProgress: () => {}}; +} + +export default PredictiveBackAnimatedView; diff --git a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js new file mode 100644 index 000000000000..4e9118cfc4af --- /dev/null +++ b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js @@ -0,0 +1,16 @@ +/** + * 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 + */ + +// NOTE: This file supports backwards compatibility of subpath (deep) imports +// from 'react-native' with platform-specific extensions. It can be deleted +// once we remove the "./*" mapping from package.json "exports". + +export {usePredictiveBackAnimatedValue} from './PredictiveBackAnimatedView'; +export {default} from './PredictiveBackAnimatedView'; diff --git a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js.flow b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js.flow new file mode 100644 index 000000000000..cbed37be1ab5 --- /dev/null +++ b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js.flow @@ -0,0 +1,38 @@ +/** + * 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 + * @format + */ + +'use strict'; + +import type {ViewProps} from '../View/ViewPropTypes'; + +import Animated from '../../Animated/Animated'; +import * as React from 'react'; + +export type PredictiveBackNativeEvent = { + progress: number, + swipeEdge: number, + touchX: number, + touchY: number, + phase: number, +}; + +export type PredictiveBackAnimatedViewProps = { + ...ViewProps, + onProgress?: (event: {nativeEvent: PredictiveBackNativeEvent}) => mixed, +}; + +declare export function usePredictiveBackAnimatedValue(): { + progress: Animated.Value, + onProgress: $FlowFixMe, +}; + +declare const PredictiveBackAnimatedView: React.AbstractComponent; + +declare export default typeof PredictiveBackAnimatedView; diff --git a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedViewNativeComponent.js b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedViewNativeComponent.js new file mode 100644 index 000000000000..754266f9cdb2 --- /dev/null +++ b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedViewNativeComponent.js @@ -0,0 +1,12 @@ +/** + * 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 {PredictiveBackNativeEvent} from '../../../src/private/components/predictiveback/specs/PredictiveBackAnimatedViewNativeComponent'; +export {default} from '../../../src/private/components/predictiveback/specs/PredictiveBackAnimatedViewNativeComponent'; diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index 9dd42742c65f..aa9c1d4ab735 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -62,6 +62,10 @@ public final class com/facebook/react/PredictiveBackEvent { public static final field EDGE_LEFT I public static final field EDGE_NONE I public static final field EDGE_RIGHT I + public static final field PHASE_CANCEL I + public static final field PHASE_COMMIT I + public static final field PHASE_PROGRESS I + public static final field PHASE_START I public final field progress F public final field swipeEdge I public final field touchX F @@ -76,10 +80,15 @@ public abstract interface class com/facebook/react/PredictiveBackHandler { public abstract fun onPredictiveBackStarted (Lcom/facebook/react/PredictiveBackEvent;)V } +public abstract interface class com/facebook/react/PredictiveBackProgressListener { + public abstract fun onPredictiveBackProgress (Lcom/facebook/react/PredictiveBackEvent;I)V +} + public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/AppCompatActivity, com/facebook/react/modules/core/DefaultHardwareBackBtnHandler, com/facebook/react/modules/core/PermissionAwareActivity { public static final field PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID Ljava/lang/String; protected fun ()V public fun addPredictiveBackHandler (Lcom/facebook/react/PredictiveBackHandler;)V + public fun addPredictiveBackProgressListener (Lcom/facebook/react/PredictiveBackProgressListener;)V protected fun createReactActivityDelegate ()Lcom/facebook/react/ReactActivityDelegate; public fun getBackPressedCallback ()Landroidx/activity/OnBackPressedCallback; protected fun getMainComponentName ()Ljava/lang/String; @@ -105,6 +114,7 @@ public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/ public fun onUserLeaveHint ()V public fun onWindowFocusChanged (Z)V public fun removePredictiveBackHandler (Lcom/facebook/react/PredictiveBackHandler;)V + public fun removePredictiveBackProgressListener (Lcom/facebook/react/PredictiveBackProgressListener;)V public fun requestPermissions ([Ljava/lang/String;ILcom/facebook/react/modules/core/PermissionListener;)V public fun setInterceptEnabled (Z)V } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackEvent.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackEvent.java index 09eeaecc2729..2cbe7818ee4f 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackEvent.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackEvent.java @@ -18,6 +18,11 @@ public final class PredictiveBackEvent { public static final int EDGE_RIGHT = 1; public static final int EDGE_NONE = 2; + public static final int PHASE_START = 0; + public static final int PHASE_PROGRESS = 1; + public static final int PHASE_CANCEL = 2; + public static final int PHASE_COMMIT = 3; + public final float progress; public final int swipeEdge; public final float touchX; diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackHandler.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackHandler.java index a0c979f96f1d..99e4faf5b804 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackHandler.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackHandler.java @@ -12,6 +12,9 @@ * ReactActivity#addPredictiveBackHandler}. While at least one handler is registered, React Native * consumes the Android back gesture and delivers progress here instead of (or in addition to) JS. * + *

To observe progress without owning the gesture (for Animated / Reanimated), use {@link + * PredictiveBackProgressListener} or the JS {@code PredictiveBackAnimatedView} instead. + * *

If {@link #onPredictiveBackCommitted()} returns {@code true}, JS {@code hardwareBackPress} is * not emitted, so JS and this handler cannot both pop. */ diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackProgressListener.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackProgressListener.java new file mode 100644 index 000000000000..bb30aa8cfd56 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackProgressListener.java @@ -0,0 +1,26 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react; + +/** + * Observes in-app predictive-back progress without owning the gesture. Unlike {@link + * PredictiveBackHandler}, registering this does not consume the swipe or suppress the default + * front-pane animation. + * + *

Used by {@code PredictiveBackAnimatedView} to emit Fabric events that {@code Animated.event} + * (native driver) and Reanimated {@code useEvent} can consume on the UI thread. + */ +public interface PredictiveBackProgressListener { + + /** + * @param phase one of {@link PredictiveBackEvent#PHASE_START}, {@link + * PredictiveBackEvent#PHASE_PROGRESS}, {@link PredictiveBackEvent#PHASE_CANCEL}, {@link + * PredictiveBackEvent#PHASE_COMMIT} + */ + void onPredictiveBackProgress(PredictiveBackEvent event, int phase); +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java index ae07f302fb14..9fc44720d5d4 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java @@ -82,6 +82,8 @@ public void handleOnBackPressed() { private boolean mJsInterceptEnabled; private final List mPredictiveBackHandlers = new CopyOnWriteArrayList<>(); + private final List mPredictiveBackProgressListeners = + new CopyOnWriteArrayList<>(); private PredictiveBackEvent mLastPredictiveBackEvent = EMPTY_PREDICTIVE_BACK_EVENT; private long mLastJsProgressEmitMs; @@ -216,6 +218,20 @@ public void removePredictiveBackHandler(PredictiveBackHandler handler) { updateConsumeCallback(); } + /** + * Observes gesture progress without consuming the swipe. Used by {@code + * PredictiveBackAnimatedView} so Animated / Reanimated can drive UI-thread animations. + */ + public void addPredictiveBackProgressListener(PredictiveBackProgressListener listener) { + if (!mPredictiveBackProgressListeners.contains(listener)) { + mPredictiveBackProgressListeners.add(listener); + } + } + + public void removePredictiveBackProgressListener(PredictiveBackProgressListener listener) { + mPredictiveBackProgressListeners.remove(listener); + } + private void updateConsumeCallback() { boolean consume = mJsInterceptEnabled || !mPredictiveBackHandlers.isEmpty(); if (!AndroidVersion.isAtLeastTargetSdk36(this)) { @@ -244,6 +260,7 @@ void dispatchPredictiveBackStarted(PredictiveBackEvent event) { for (int i = mPredictiveBackHandlers.size() - 1; i >= 0; i--) { mPredictiveBackHandlers.get(i).onPredictiveBackStarted(event); } + notifyPredictiveBackProgressListeners(event, PredictiveBackEvent.PHASE_START); emitPredictiveBackToJs("start", event, false); } @@ -252,6 +269,7 @@ void dispatchPredictiveBackProgressed(PredictiveBackEvent event) { for (int i = mPredictiveBackHandlers.size() - 1; i >= 0; i--) { mPredictiveBackHandlers.get(i).onPredictiveBackProgressed(event); } + notifyPredictiveBackProgressListeners(event, PredictiveBackEvent.PHASE_PROGRESS); emitPredictiveBackToJs("progress", event, true); } @@ -259,6 +277,13 @@ void dispatchPredictiveBackCancelled() { for (int i = mPredictiveBackHandlers.size() - 1; i >= 0; i--) { mPredictiveBackHandlers.get(i).onPredictiveBackCancelled(); } + PredictiveBackEvent reset = + new PredictiveBackEvent( + 0f, + mLastPredictiveBackEvent.swipeEdge, + mLastPredictiveBackEvent.touchX, + mLastPredictiveBackEvent.touchY); + notifyPredictiveBackProgressListeners(reset, PredictiveBackEvent.PHASE_CANCEL); emitPredictiveBackToJs("cancel", mLastPredictiveBackEvent, false); } @@ -270,12 +295,25 @@ void finishPredictiveBackCommit() { break; } } + PredictiveBackEvent done = + new PredictiveBackEvent( + 1f, + mLastPredictiveBackEvent.swipeEdge, + mLastPredictiveBackEvent.touchX, + mLastPredictiveBackEvent.touchY); + notifyPredictiveBackProgressListeners(done, PredictiveBackEvent.PHASE_COMMIT); emitPredictiveBackToJs("commit", mLastPredictiveBackEvent, false); if (!consumed) { notifyJsHardwareBackPressed(); } } + private void notifyPredictiveBackProgressListeners(PredictiveBackEvent event, int phase) { + for (int i = mPredictiveBackProgressListeners.size() - 1; i >= 0; i--) { + mPredictiveBackProgressListeners.get(i).onPredictiveBackProgress(event, phase); + } + } + private void emitPredictiveBackToJs( String phase, PredictiveBackEvent event, boolean throttleProgress) { if (throttleProgress) { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.kt index 14b053b4196f..463a4651eee5 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/shell/MainReactPackage.kt @@ -49,6 +49,7 @@ import com.facebook.react.uimanager.ViewManager import com.facebook.react.views.drawer.ReactDrawerLayoutManager import com.facebook.react.views.image.ReactImageManager import com.facebook.react.views.modal.ReactModalHostManager +import com.facebook.react.views.predictiveback.ReactPredictiveBackAnimatedViewManager import com.facebook.react.views.progressbar.ReactProgressBarViewManager import com.facebook.react.views.safeareaview.ReactSafeAreaViewManager import com.facebook.react.views.scroll.ReactHorizontalScrollContainerViewManager @@ -145,6 +146,7 @@ constructor(private val config: MainPackageConfig? = null) : ReactHorizontalScrollViewManager(), ReactHorizontalScrollContainerViewManager(), ReactProgressBarViewManager(), + ReactPredictiveBackAnimatedViewManager(), if (ReactNativeFeatureFlags.useNestedScrollViewAndroid()) ReactNestedScrollViewManager() else ReactScrollViewManager(), ReactSwitchManager(), @@ -178,6 +180,8 @@ constructor(private val config: MainPackageConfig? = null) : ModuleSpec.viewManagerSpec { ReactHorizontalScrollContainerViewManager() }, ReactProgressBarViewManager.REACT_CLASS to ModuleSpec.viewManagerSpec { ReactProgressBarViewManager() }, + ReactPredictiveBackAnimatedViewManager.REACT_CLASS to + ModuleSpec.viewManagerSpec { ReactPredictiveBackAnimatedViewManager() }, ReactSafeAreaViewManager.REACT_CLASS to ModuleSpec.viewManagerSpec { ReactSafeAreaViewManager() }, ReactScrollViewManager.REACT_CLASS to diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/predictiveback/PredictiveBackProgressEvent.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/predictiveback/PredictiveBackProgressEvent.kt new file mode 100644 index 000000000000..57da62bc7c10 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/predictiveback/PredictiveBackProgressEvent.kt @@ -0,0 +1,48 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.views.predictiveback + +import com.facebook.react.PredictiveBackEvent +import com.facebook.react.bridge.Arguments +import com.facebook.react.bridge.WritableMap +import com.facebook.react.uimanager.events.Event + +internal class PredictiveBackProgressEvent( + surfaceId: Int, + viewId: Int, + private val progress: Float, + private val swipeEdge: Int, + private val touchX: Float, + private val touchY: Float, + private val phase: Int, +) : Event(surfaceId, viewId) { + + constructor( + surfaceId: Int, + viewId: Int, + event: PredictiveBackEvent, + phase: Int, + ) : this(surfaceId, viewId, event.progress, event.swipeEdge, event.touchX, event.touchY, phase) + + override fun getEventName(): String = EVENT_NAME + + override fun canCoalesce(): Boolean = phase == PredictiveBackEvent.PHASE_PROGRESS + + override fun getEventData(): WritableMap = + Arguments.createMap().apply { + putDouble("progress", progress.toDouble()) + putInt("swipeEdge", swipeEdge) + putDouble("touchX", touchX.toDouble()) + putDouble("touchY", touchY.toDouble()) + putInt("phase", phase) + } + + companion object { + const val EVENT_NAME: String = "topProgress" + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/predictiveback/ReactPredictiveBackAnimatedView.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/predictiveback/ReactPredictiveBackAnimatedView.kt new file mode 100644 index 000000000000..2149c58f2891 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/predictiveback/ReactPredictiveBackAnimatedView.kt @@ -0,0 +1,49 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.views.predictiveback + +import android.view.View +import com.facebook.react.PredictiveBackEvent +import com.facebook.react.PredictiveBackProgressListener +import com.facebook.react.ReactActivity +import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.react.uimanager.UIManagerHelper + +/** + * Zero-size host view that re-emits predictive-back progress as a Fabric direct event so {@code + * Animated.event} (native driver) and Reanimated {@code useEvent} can drive UI-thread animations. + */ +internal class ReactPredictiveBackAnimatedView(private val reactContext: ThemedReactContext) : + View(reactContext), PredictiveBackProgressListener { + + init { + importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO + isClickable = false + isFocusable = false + } + + override fun onAttachedToWindow() { + super.onAttachedToWindow() + (reactContext.currentActivity as? ReactActivity)?.addPredictiveBackProgressListener(this) + } + + override fun onDetachedFromWindow() { + (reactContext.currentActivity as? ReactActivity)?.removePredictiveBackProgressListener(this) + super.onDetachedFromWindow() + } + + override fun onPredictiveBackProgress(event: PredictiveBackEvent, phase: Int) { + if (id == NO_ID) { + return + } + val dispatcher = UIManagerHelper.getEventDispatcher(reactContext) ?: return + dispatcher.dispatchEvent( + PredictiveBackProgressEvent(UIManagerHelper.getSurfaceId(this), id, event, phase), + ) + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/predictiveback/ReactPredictiveBackAnimatedViewManager.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/predictiveback/ReactPredictiveBackAnimatedViewManager.kt new file mode 100644 index 000000000000..7c73d1e562b9 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/views/predictiveback/ReactPredictiveBackAnimatedViewManager.kt @@ -0,0 +1,42 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react.views.predictiveback + +import com.facebook.react.module.annotations.ReactModule +import com.facebook.react.uimanager.SimpleViewManager +import com.facebook.react.uimanager.ThemedReactContext +import com.facebook.react.uimanager.ViewManagerDelegate +import com.facebook.react.viewmanagers.PredictiveBackAnimatedViewManagerDelegate +import com.facebook.react.viewmanagers.PredictiveBackAnimatedViewManagerInterface + +@ReactModule(name = ReactPredictiveBackAnimatedViewManager.REACT_CLASS) +internal class ReactPredictiveBackAnimatedViewManager : + SimpleViewManager(), + PredictiveBackAnimatedViewManagerInterface { + + private val delegate: ViewManagerDelegate = + PredictiveBackAnimatedViewManagerDelegate(this) + + override fun getName(): String = REACT_CLASS + + override fun getDelegate(): ViewManagerDelegate = delegate + + override fun createViewInstance(context: ThemedReactContext): ReactPredictiveBackAnimatedView = + ReactPredictiveBackAnimatedView(context) + + override fun getExportedCustomDirectEventTypeConstants(): Map { + val eventTypeConstants = super.getExportedCustomDirectEventTypeConstants() ?: mutableMapOf() + return eventTypeConstants.apply { + put(PredictiveBackProgressEvent.EVENT_NAME, mapOf("registrationName" to "onProgress")) + } + } + + internal companion object { + const val REACT_CLASS: String = "PredictiveBackAnimatedView" + } +} diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt index b64615bcc34f..4b4448ee325e 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt @@ -135,6 +135,41 @@ class ReactActivityBackPressedCallbackTest { assertThat(activity.delegatedBackPressCount).isEqualTo(1) } + @Test + fun progressListener_doesNotEnableCallbackWhenInterceptDisabled() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.setInterceptEnabled(false) + + activity.addPredictiveBackProgressListener { _, _ -> } + + assertThat(activity.backPressedCallback.isEnabled).isFalse() + assertThat(activity.shouldScrubDefaultFrontPane()).isFalse() + } + + @Test + fun progressListener_doesNotStealFrontPaneOwnership() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.setInterceptEnabled(true) + + activity.addPredictiveBackProgressListener { _, _ -> } + + assertThat(activity.shouldScrubDefaultFrontPane()).isTrue() + } + + @Test + fun progressListener_receivesStartAndProgress() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + val phases = mutableListOf() + activity.addPredictiveBackProgressListener { _, phase -> phases.add(phase) } + val event = PredictiveBackEvent(0.4f, PredictiveBackEvent.EDGE_LEFT, 12f, 40f) + + activity.dispatchPredictiveBackStarted(event) + activity.dispatchPredictiveBackProgressed(event) + + assertThat(phases) + .containsExactly(PredictiveBackEvent.PHASE_START, PredictiveBackEvent.PHASE_PROGRESS) + } + @Test fun shouldScrubDefaultFrontPane_falseWhenNativeHandlerRegistered() { val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index 1075b77b69fc..852f861c84a3 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -309,6 +309,8 @@ declare const parallelImpl: ( declare const PermissionsAndroid: typeof PermissionsAndroidInstance_default declare const PermissionsAndroidInstance_default: PermissionsAndroidImpl declare const Platform: PlatformType +declare const PredictiveBackAnimatedView: typeof PredictiveBackAnimatedView_default +declare const PredictiveBackAnimatedView_default: React.ComponentType declare const Presets: { easeInEaseOut: LayoutAnimationConfig linear: LayoutAnimationConfig @@ -3583,6 +3585,10 @@ declare type PointValue = { x: number y: number } +declare type PredictiveBackAnimatedView = typeof PredictiveBackAnimatedView +declare type PredictiveBackAnimatedViewProps = ViewProps & { + onProgress?: (event: { nativeEvent: PredictiveBackNativeEvent }) => unknown +} declare type PredictiveBackEvent = { phase: PredictiveBackPhase progress: number @@ -3590,6 +3596,13 @@ declare type PredictiveBackEvent = { touchX: number touchY: number } +declare type PredictiveBackNativeEvent = { + phase: number + progress: number + swipeEdge: number + touchX: number + touchY: number +} declare type PredictiveBackPhase = "cancel" | "commit" | "progress" | "start" declare type PresentLocalNotificationDetails = { alertAction?: string @@ -5465,6 +5478,10 @@ declare function useAnimatedValueXY( ): Animated.ValueXY declare function useAppState(): AppStateStatus declare function useColorScheme(): ColorSchemeName | null +declare function usePredictiveBackAnimatedValue(): { + onProgress: any + progress: Animated.Value +} declare function usePressability( config: null | PressabilityConfig | undefined, ): null | PressabilityEventHandlers @@ -5960,7 +5977,10 @@ export { PlatformSelectSpec, // 09ed7758 PointValue, // 69db075f PointerEvent, // a506d9d7 + PredictiveBackAnimatedView, // b7897c30 + PredictiveBackAnimatedViewProps, // 9d8f7fe6 PredictiveBackEvent, // e2919d69 + PredictiveBackNativeEvent, // a7e9dafb PredictiveBackPhase, // dcc1122c PressabilityConfig, // 0fd655fe PressabilityEventHandlers, // be359ba3 @@ -6103,6 +6123,7 @@ export { useAnimatedValueXY, // dc9057ea useAppState, // 9338748a useColorScheme, // d585efdb + usePredictiveBackAnimatedValue, // 99a81437 usePressability, // af291ad3 useWindowDimensions, // bb4b683f } diff --git a/packages/react-native/index.js b/packages/react-native/index.js index a86064115ca6..f62f4257969e 100644 --- a/packages/react-native/index.js +++ b/packages/react-native/index.js @@ -104,6 +104,10 @@ module.exports = { get Pressable() { return require('./Libraries/Components/Pressable/Pressable').default; }, + get PredictiveBackAnimatedView() { + return require('./Libraries/Components/PredictiveBack/PredictiveBackAnimatedView') + .default; + }, get ProgressBarAndroid() { warnOnce( 'progress-bar-android-moved', @@ -377,6 +381,10 @@ module.exports = { get useAnimatedValue() { return require('./Libraries/Animated/useAnimatedValue').default; }, + get usePredictiveBackAnimatedValue() { + return require('./Libraries/Components/PredictiveBack/PredictiveBackAnimatedView') + .usePredictiveBackAnimatedValue; + }, get useAnimatedValueXY() { return require('./Libraries/Animated/useAnimatedValueXY').default; }, diff --git a/packages/react-native/index.js.flow b/packages/react-native/index.js.flow index d97d72a96a75..e7b67e72c236 100644 --- a/packages/react-native/index.js.flow +++ b/packages/react-native/index.js.flow @@ -94,6 +94,15 @@ export type { } from './Libraries/Components/Pressable/Pressable'; export {default as Pressable} from './Libraries/Components/Pressable/Pressable'; +export type { + PredictiveBackAnimatedViewProps, + PredictiveBackNativeEvent, +} from './Libraries/Components/PredictiveBack/PredictiveBackAnimatedView'; +export { + default as PredictiveBackAnimatedView, + usePredictiveBackAnimatedValue, +} from './Libraries/Components/PredictiveBack/PredictiveBackAnimatedView'; + export type { ProgressBarAndroidInstance, ProgressBarAndroidProps, diff --git a/packages/react-native/src/private/components/predictiveback/specs/PredictiveBackAnimatedViewNativeComponent.js b/packages/react-native/src/private/components/predictiveback/specs/PredictiveBackAnimatedViewNativeComponent.js new file mode 100644 index 000000000000..fabb18addb3d --- /dev/null +++ b/packages/react-native/src/private/components/predictiveback/specs/PredictiveBackAnimatedViewNativeComponent.js @@ -0,0 +1,39 @@ +/** + * 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 {ViewProps} from '../../../../../Libraries/Components/View/ViewPropTypes'; +import type { + DirectEventHandler, + Double, + Int32, +} from '../../../../../Libraries/Types/CodegenTypes'; +import type {HostComponent} from '../../../types/HostComponent'; + +import codegenNativeComponent from '../../../../../Libraries/Utilities/codegenNativeComponent'; + +export type PredictiveBackNativeEvent = Readonly<{ + progress: Double, + swipeEdge: Int32, + touchX: Double, + touchY: Double, + phase: Int32, +}>; + +type NativeProps = Readonly<{ + ...ViewProps, + onProgress?: ?DirectEventHandler, +}>; + +export default codegenNativeComponent( + 'PredictiveBackAnimatedView', + { + excludedPlatforms: ['iOS'], + }, +) as HostComponent; diff --git a/packages/react-native/types_DEPRECATED/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.d.ts b/packages/react-native/types_DEPRECATED/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.d.ts new file mode 100644 index 000000000000..bba4d03fb587 --- /dev/null +++ b/packages/react-native/types_DEPRECATED/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.d.ts @@ -0,0 +1,32 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import type * as React from 'react'; +import type {Animated} from '../../Animated/Animated'; +import {ViewProps} from '../View/ViewPropTypes'; + +export interface PredictiveBackNativeEvent { + readonly progress: number; + readonly swipeEdge: number; + readonly touchX: number; + readonly touchY: number; + readonly phase: number; +} + +export interface PredictiveBackAnimatedViewProps extends ViewProps { + onProgress?: (event: {nativeEvent: PredictiveBackNativeEvent}) => void; +} + +export function usePredictiveBackAnimatedValue(): { + progress: Animated.Value; + onProgress: (...args: any[]) => void; +}; + +export const PredictiveBackAnimatedView: React.ComponentType; +export default PredictiveBackAnimatedView; diff --git a/packages/react-native/types_DEPRECATED/index.d.ts b/packages/react-native/types_DEPRECATED/index.d.ts index a98e1f004510..47bf6fc116e0 100644 --- a/packages/react-native/types_DEPRECATED/index.d.ts +++ b/packages/react-native/types_DEPRECATED/index.d.ts @@ -87,6 +87,7 @@ export * from './Libraries/Components/Keyboard/Keyboard'; export * from './Libraries/Components/Keyboard/KeyboardAvoidingView'; export * from './Libraries/Components/LayoutConformance/LayoutConformance'; export * from './Libraries/Components/Pressable/Pressable'; +export * from './Libraries/Components/PredictiveBack/PredictiveBackAnimatedView'; export * from './Libraries/Components/ProgressBarAndroid/ProgressBarAndroid'; export * from './Libraries/Components/RefreshControl/RefreshControl'; export * from './Libraries/Components/SafeAreaView/SafeAreaView'; diff --git a/packages/rn-tester/js/examples/PredictiveBack/PredictiveBackExample.js b/packages/rn-tester/js/examples/PredictiveBack/PredictiveBackExample.js new file mode 100644 index 000000000000..7783ccaf16a1 --- /dev/null +++ b/packages/rn-tester/js/examples/PredictiveBack/PredictiveBackExample.js @@ -0,0 +1,94 @@ +/** + * 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 + */ + +'use strict'; + +import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; + +import RNTesterText from '../../components/RNTesterText'; +import * as React from 'react'; +import {useMemo} from 'react'; +import { + Animated, + Platform, + PredictiveBackAnimatedView, + StyleSheet, + View, + usePredictiveBackAnimatedValue, +} from 'react-native'; + +function UsePredictiveBackAnimatedValueExample(): React.Node { + const {progress, onProgress} = usePredictiveBackAnimatedValue(); + const boxStyle = useMemo( + () => [ + styles.box, + { + transform: [ + { + scale: progress.interpolate({ + inputRange: [0, 1], + outputRange: [1, 0.82], + }), + }, + { + translateX: progress.interpolate({ + inputRange: [0, 1], + outputRange: [0, 28], + }), + }, + ], + }, + ], + [progress], + ); + + return ( + + + Swipe from the edge and hold. The box is driven by + usePredictiveBackAnimatedValue through the native Animated driver. + + {Platform.OS === 'android' ? ( + + ) : null} + + + ); +} + +const styles = StyleSheet.create({ + container: { + gap: 8, + paddingVertical: 8, + }, + box: { + marginTop: 16, + width: 120, + height: 80, + borderRadius: 12, + backgroundColor: '#3b82f6', + }, +}); + +exports.title = 'PredictiveBack'; +exports.category = 'Android'; +exports.description = + 'Drive RN Animated from Android predictive-back progress with usePredictiveBackAnimatedValue.'; +exports.examples = [ + { + title: 'usePredictiveBackAnimatedValue', + description: + 'Native-driver progress from the system back gesture. Requires API 34+ gesture navigation.', + platform: 'android', + render(): React.Node { + return ; + }, + }, +] as Array; diff --git a/packages/rn-tester/js/utils/RNTesterList.android.js b/packages/rn-tester/js/utils/RNTesterList.android.js index 61844bb5f196..627d7e46cb1a 100644 --- a/packages/rn-tester/js/utils/RNTesterList.android.js +++ b/packages/rn-tester/js/utils/RNTesterList.android.js @@ -315,6 +315,11 @@ const APIs: Array = ( category: 'Basic', module: require('../examples/PointerEvents/PointerEventsExample'), }, + { + key: 'PredictiveBackExample', + category: 'Android', + module: require('../examples/PredictiveBack/PredictiveBackExample'), + }, { key: 'RTLExample', category: 'Basic', From 55ba48b590bfd244af476321c0050426757d0c9a Mon Sep 17 00:00:00 2001 From: Grzegorz Kruk Date: Mon, 7 Sep 2026 21:39:56 +0200 Subject: [PATCH 05/11] Enhance predictive back navigation handling in React Native Summary: - Updated `BackHandler` and `ReactActivity` to improve predictive back gesture handling on Android. - Removed deprecated `PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID` and adjusted related logic to streamline predictive back animations. - Enhanced type definitions to reflect changes in predictive back event handling. - Updated `RNTesterApp` and Playground example to demonstrate new predictive back functionality without the deprecated ID. - Cleaned up unit tests to align with the new implementation. Changelog: [GENERAL][CHANGED] - Improved predictive back navigation handling and removed deprecated identifiers. --- .../Utilities/BackHandler.android.js | 9 +- .../ReactAndroid/api/ReactAndroid.api | 1 - .../react/PredictiveBackProgressListener.java | 3 +- .../com/facebook/react/ReactActivity.java | 248 +----------------- .../modules/core/DeviceEventManagerModule.kt | 8 +- .../ReactActivityBackPressedCallbackTest.kt | 22 -- .../Libraries/Utilities/BackHandler.d.ts | 9 +- packages/rn-tester/js/RNTesterAppShared.js | 56 +--- .../examples/Playground/RNTesterPlayground.js | 78 ++++-- 9 files changed, 78 insertions(+), 356 deletions(-) diff --git a/packages/react-native/Libraries/Utilities/BackHandler.android.js b/packages/react-native/Libraries/Utilities/BackHandler.android.js index f90f1929d087..9e9743716316 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.android.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.android.js @@ -81,11 +81,10 @@ type TBackHandler = { ) => {remove: () => void, ...}, /** * Android only. When true, React Native consumes the back gesture so - * BackHandler can pop an in-app screen. On Android 16+, a view tagged - * with nativeID "predictiveBackFrontPane" is scrubbed during the swipe - * unless a native PredictiveBackHandler is registered. When false, the - * system predictive-back animation can run; BackHandler still observes - * app-exit commit. + * BackHandler can pop an in-app screen. On Android 16+, progress is + * delivered to PredictiveBackAnimatedView and native PredictiveBackHandler + * plugins. When false, the system predictive-back animation can run; + * BackHandler still observes app-exit commit. */ readonly setInterceptEnabled: (enabled: boolean) => void, /** diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index aa9c1d4ab735..62910552d8c6 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -85,7 +85,6 @@ public abstract interface class com/facebook/react/PredictiveBackProgressListene } public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/AppCompatActivity, com/facebook/react/modules/core/DefaultHardwareBackBtnHandler, com/facebook/react/modules/core/PermissionAwareActivity { - public static final field PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID Ljava/lang/String; protected fun ()V public fun addPredictiveBackHandler (Lcom/facebook/react/PredictiveBackHandler;)V public fun addPredictiveBackProgressListener (Lcom/facebook/react/PredictiveBackProgressListener;)V diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackProgressListener.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackProgressListener.java index bb30aa8cfd56..f1776fe33dc2 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackProgressListener.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackProgressListener.java @@ -9,8 +9,7 @@ /** * Observes in-app predictive-back progress without owning the gesture. Unlike {@link - * PredictiveBackHandler}, registering this does not consume the swipe or suppress the default - * front-pane animation. + * PredictiveBackHandler}, registering this does not consume the swipe. * *

Used by {@code PredictiveBackAnimatedView} to emit Fabric events that {@code Animated.event} * (native driver) and Reanimated {@code useEvent} can consume on the UI thread. diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java index 9fc44720d5d4..69ff883b1993 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java @@ -10,17 +10,11 @@ import android.annotation.SuppressLint; import android.content.Intent; import android.content.res.Configuration; -import android.graphics.Outline; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.KeyEvent; -import android.view.View; import android.view.ViewConfiguration; -import android.view.ViewGroup; -import android.view.ViewOutlineProvider; -import android.view.animation.DecelerateInterpolator; -import android.view.animation.PathInterpolator; import android.window.BackEvent; import android.window.OnBackAnimationCallback; import android.window.OnBackInvokedCallback; @@ -44,12 +38,6 @@ public abstract class ReactActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler, PermissionAwareActivity { - /** - * {@code nativeID} of the view that in-app predictive back should scrub. Keep the previous - * screen mounted underneath this view so it can peek through during the gesture. - */ - public static final String PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID = "predictiveBackFrontPane"; - private static final String PREDICTIVE_BACK_TAG = "PredictiveBack"; private static final String PREDICTIVE_BACK_JS_EVENT = "predictiveBack"; private static final long JS_PROGRESS_THROTTLE_MS = 32; @@ -189,11 +177,9 @@ void onSystemNavigationBackInvoked() { /** * When {@code true}, React Native consumes the back gesture so JS {@code BackHandler} can pop an * in-app screen. On Android 16+ (targetSdk 36) this registers a platform {@link - * OnBackAnimationCallback} that scrubs the view tagged with {@link - * #PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID} during the swipe, revealing whatever is drawn behind it - * — unless a {@link PredictiveBackHandler} is registered, in which case that handler owns the - * animation. When {@code false} and no native handler is registered, the system predictive-back - * animation can run. + * OnBackAnimationCallback} that delivers progress to {@link PredictiveBackHandler} and {@link + * PredictiveBackProgressListener} (used by {@code PredictiveBackAnimatedView}). When {@code + * false} and no native handler is registered, the system predictive-back animation can run. */ public void setInterceptEnabled(boolean enabled) { mJsInterceptEnabled = enabled; @@ -250,10 +236,6 @@ private void updateConsumeCallback() { } } - boolean shouldScrubDefaultFrontPane() { - return mJsInterceptEnabled && mPredictiveBackHandlers.isEmpty(); - } - void dispatchPredictiveBackStarted(PredictiveBackEvent event) { mLastPredictiveBackEvent = event; mLastJsProgressEmitMs = 0; @@ -466,25 +448,12 @@ static void unregister(ReactActivity activity, Object callback) { } private static final class Callback implements OnBackAnimationCallback { - private static final float MAX_SCALE_DELTA = 0.1f; - private static final float MAX_CORNER_RADIUS_DP = 32f; - private static final float MAX_SHADOW_Z_DP = 24f; - private static final long CANCEL_DURATION_MS = 250; - private static final long COMMIT_DURATION_MS = 220; - private static final float COMMIT_SCALE = 0.8f; - private static final float COMMIT_TRANSLATION_FRACTION = 0.12f; // System progress hits 1.0 well before a full-screen swipe. Decide commit // from actual travel so a short drag snaps back instead of popping. private static final float COMMIT_DISTANCE_FRACTION = 0.25f; private static final float COMMIT_VELOCITY_DP_PER_S = 900f; private final ReactActivity activity; - private @Nullable View frontPane; - private @Nullable ViewGroup paneParent; - private boolean parentClippedChildren; - private boolean parentClippedToPadding; - private float originalElevation; - private float cornerRadiusPx; private boolean gestureCancelled; private int swipeEdge; private float startTouchX; @@ -506,61 +475,21 @@ public void onBackStarted(BackEvent backEvent) { lastEventTimeMs = SystemClock.uptimeMillis(); velocityPxPerS = 0f; lastProgress = 0f; + Log.i(PREDICTIVE_BACK_TAG, "in-app: back started"); activity.dispatchPredictiveBackStarted(toPredictiveBackEvent(backEvent)); - if (!activity.shouldScrubDefaultFrontPane()) { - Log.i(PREDICTIVE_BACK_TAG, "in-app: back started, native handler owns animation"); - return; - } - frontPane = findFrontPane(); - if (frontPane == null) { - Log.i(PREDICTIVE_BACK_TAG, "in-app: back started, no front pane"); - return; - } - Log.i( - PREDICTIVE_BACK_TAG, - "in-app: back started pane=" - + frontPane.getClass().getSimpleName() - + " " - + frontPane.getWidth() - + "x" - + frontPane.getHeight()); - originalElevation = frontPane.getElevation(); - prepareParentForShadow(frontPane); - frontPane.setAlpha(1f); - frontPane.animate().cancel(); - frontPane.setClipToOutline(true); - frontPane.setOutlineProvider( - new ViewOutlineProvider() { - @Override - public void getOutline(View view, Outline outline) { - outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), cornerRadiusPx); - } - }); - applyProgress(backEvent); } @Override public void onBackProgressed(BackEvent backEvent) { + updateGestureMetrics(backEvent); activity.dispatchPredictiveBackProgressed(toPredictiveBackEvent(backEvent)); - if (!activity.shouldScrubDefaultFrontPane()) { - updateGestureMetrics(backEvent); - return; - } - if (frontPane == null) { - frontPane = findFrontPane(); - if (frontPane == null) { - updateGestureMetrics(backEvent); - return; - } - } - applyProgress(backEvent); } @Override public void onBackCancelled() { Log.i(PREDICTIVE_BACK_TAG, "in-app: back cancelled"); + gestureCancelled = true; activity.dispatchPredictiveBackCancelled(); - cancelGesture(); } @Override @@ -578,55 +507,12 @@ public void onBackInvoked() { onBackCancelled(); return; } - commitGesture(); - } - - private void commitGesture() { - Log.i(PREDICTIVE_BACK_TAG, "in-app: back committed, finishing animation"); - if (!activity.shouldScrubDefaultFrontPane() || frontPane == null) { - activity.finishPredictiveBackCommit(); - return; - } - final View pane = frontPane; - float width = pane.getWidth(); - float translationX = - swipeEdge == BackEvent.EDGE_LEFT - ? width * COMMIT_TRANSLATION_FRACTION - : -width * COMMIT_TRANSLATION_FRACTION; - cornerRadiusPx = - MAX_CORNER_RADIUS_DP * activity.getResources().getDisplayMetrics().density; - pane.invalidateOutline(); - float shadowZ = - MAX_SHADOW_Z_DP * activity.getResources().getDisplayMetrics().density; - pane.setElevation(originalElevation + shadowZ); - pane.animate().cancel(); - pane.animate() - .scaleX(COMMIT_SCALE) - .scaleY(COMMIT_SCALE) - .translationX(translationX) - .translationZ(shadowZ) - .alpha(0f) - .setDuration(COMMIT_DURATION_MS) - .setInterpolator(new PathInterpolator(0.4f, 0f, 1f, 1f)) - .withEndAction( - () -> { - restoreParentClip(); - if (activity.isFinishing() || activity.isDestroyed()) { - return; - } - if (frontPane == pane) { - frontPane = null; - } - activity.finishPredictiveBackCommit(); - }) - .start(); + Log.i(PREDICTIVE_BACK_TAG, "in-app: back committed"); + activity.finishPredictiveBackCommit(); } private boolean shouldCommit() { - float width = - frontPane != null - ? frontPane.getWidth() - : activity.getWindow().getDecorView().getWidth(); + float width = activity.getWindow().getDecorView().getWidth(); float distancePx = Math.abs(lastTouchX - startTouchX); int touchSlop = ViewConfiguration.get(activity).getScaledTouchSlop(); if (distancePx <= touchSlop) { @@ -643,64 +529,6 @@ private boolean shouldCommit() { return farEnough || flung; } - private void cancelGesture() { - gestureCancelled = true; - resetFrontPane(true); - } - - private @Nullable View findFrontPane() { - View root = activity.getWindow().getDecorView(); - View tagged = findLastViewWithNativeId(root, PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID); - if (tagged == null) { - return null; - } - // Never scrub the activity/root wrapper: that scales the whole tree, - // including the destination screen, which is what we want to reveal. - if (tagged == root || tagged == activity.findViewById(android.R.id.content)) { - return null; - } - return tagged; - } - - private static @Nullable View findLastViewWithNativeId(View root, String nativeId) { - View match = null; - if (nativeId.equals(root.getTag(com.facebook.react.R.id.view_tag_native_id))) { - match = root; - } - if (root instanceof ViewGroup) { - ViewGroup group = (ViewGroup) root; - for (int i = 0; i < group.getChildCount(); i++) { - View childMatch = findLastViewWithNativeId(group.getChildAt(i), nativeId); - if (childMatch != null) { - match = childMatch; - } - } - } - return match; - } - - private void applyProgress(BackEvent backEvent) { - updateGestureMetrics(backEvent); - if (frontPane == null) { - return; - } - float progress = lastProgress; - float density = activity.getResources().getDisplayMetrics().density; - float scale = 1f - (MAX_SCALE_DELTA * progress); - frontPane.setScaleX(scale); - frontPane.setScaleY(scale); - float maxTranslation = frontPane.getWidth() / 20f; - float translationX = - backEvent.getSwipeEdge() == BackEvent.EDGE_LEFT - ? maxTranslation * progress - : -maxTranslation * progress; - frontPane.setTranslationX(translationX); - frontPane.setElevation(originalElevation + MAX_SHADOW_Z_DP * progress * density); - frontPane.setTranslationZ(MAX_SHADOW_Z_DP * progress * density); - cornerRadiusPx = MAX_CORNER_RADIUS_DP * progress * density; - frontPane.invalidateOutline(); - } - private void updateGestureMetrics(BackEvent backEvent) { long now = SystemClock.uptimeMillis(); float touchX = backEvent.getTouchX(); @@ -720,64 +548,6 @@ private static PredictiveBackEvent toPredictiveBackEvent(BackEvent backEvent) { backEvent.getTouchX(), backEvent.getTouchY()); } - - private void prepareParentForShadow(View pane) { - if (!(pane.getParent() instanceof ViewGroup)) { - paneParent = null; - return; - } - paneParent = (ViewGroup) pane.getParent(); - parentClippedChildren = paneParent.getClipChildren(); - parentClippedToPadding = paneParent.getClipToPadding(); - paneParent.setClipChildren(false); - paneParent.setClipToPadding(false); - } - - private void restoreParentClip() { - if (paneParent == null) { - return; - } - paneParent.setClipChildren(parentClippedChildren); - paneParent.setClipToPadding(parentClippedToPadding); - paneParent = null; - } - - private void resetFrontPane(boolean animate) { - if (frontPane == null) { - return; - } - cornerRadiusPx = 0f; - if (animate) { - frontPane - .animate() - .scaleX(1f) - .scaleY(1f) - .translationX(0f) - .translationZ(0f) - .alpha(1f) - .setDuration(CANCEL_DURATION_MS) - .setInterpolator(new DecelerateInterpolator()) - .withEndAction( - () -> { - if (frontPane != null) { - frontPane.setElevation(originalElevation); - frontPane.invalidateOutline(); - } - restoreParentClip(); - }) - .start(); - } else { - frontPane.animate().cancel(); - frontPane.setScaleX(1f); - frontPane.setScaleY(1f); - frontPane.setTranslationX(0f); - frontPane.setTranslationZ(0f); - frontPane.setAlpha(1f); - frontPane.setElevation(originalElevation); - frontPane.invalidateOutline(); - restoreParentClip(); - } - } } } diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt index 06b1c6aabe7b..b29c15f2507c 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt @@ -63,10 +63,10 @@ public open class DeviceEventManagerModule( /** * Enables or disables in-app back interception. * - * When enabled on Android 16+, RN registers a predictive-back animation callback that scrubs - * the view tagged with [ReactActivity.PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID], unless a native - * [com.facebook.react.PredictiveBackHandler] is registered. When disabled, the system handles - * the gesture and the navigation-observer still notifies JS on app-exit commit. + * When enabled on Android 16+, RN registers a predictive-back animation callback that delivers + * progress to native handlers and [com.facebook.react.PredictiveBackProgressListener]. When + * disabled, the system handles the gesture and the navigation-observer still notifies JS on + * app-exit commit. */ override fun setInterceptEnabled(enabled: Boolean) { reactApplicationContext.runOnUiQueueThread { diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt index 4b4448ee325e..f70f8ca8676f 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt @@ -143,17 +143,6 @@ class ReactActivityBackPressedCallbackTest { activity.addPredictiveBackProgressListener { _, _ -> } assertThat(activity.backPressedCallback.isEnabled).isFalse() - assertThat(activity.shouldScrubDefaultFrontPane()).isFalse() - } - - @Test - fun progressListener_doesNotStealFrontPaneOwnership() { - val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() - activity.setInterceptEnabled(true) - - activity.addPredictiveBackProgressListener { _, _ -> } - - assertThat(activity.shouldScrubDefaultFrontPane()).isTrue() } @Test @@ -170,17 +159,6 @@ class ReactActivityBackPressedCallbackTest { .containsExactly(PredictiveBackEvent.PHASE_START, PredictiveBackEvent.PHASE_PROGRESS) } - @Test - fun shouldScrubDefaultFrontPane_falseWhenNativeHandlerRegistered() { - val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() - activity.setInterceptEnabled(true) - assertThat(activity.shouldScrubDefaultFrontPane()).isTrue() - - activity.addPredictiveBackHandler(NoOpPredictiveBackHandler()) - - assertThat(activity.shouldScrubDefaultFrontPane()).isFalse() - } - private open class NoOpPredictiveBackHandler( private val consumeCommit: Boolean = false, ) : PredictiveBackHandler { diff --git a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts index 736a87e7d365..7e269c765d68 100644 --- a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts +++ b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts @@ -50,11 +50,10 @@ export interface BackHandlerStatic { ): NativeEventSubscription; /** * Android only. When true, React Native consumes the back gesture so - * BackHandler can pop an in-app screen. On Android 16+, a view tagged - * with nativeID "predictiveBackFrontPane" is scrubbed during the swipe - * unless a native PredictiveBackHandler is registered. When false, the - * system predictive-back animation can run; BackHandler still observes - * app-exit commit. + * BackHandler can pop an in-app screen. On Android 16+, progress is + * delivered to PredictiveBackAnimatedView and native PredictiveBackHandler + * plugins. When false, the system predictive-back animation can run; + * BackHandler still observes app-exit commit. */ setInterceptEnabled(enabled: boolean): void; /** diff --git a/packages/rn-tester/js/RNTesterAppShared.js b/packages/rn-tester/js/RNTesterAppShared.js index 55f3d5b1955e..54f74b045cba 100644 --- a/packages/rn-tester/js/RNTesterAppShared.js +++ b/packages/rn-tester/js/RNTesterAppShared.js @@ -137,9 +137,9 @@ const RNTesterApp = ({ handleHardwareBackPress, ); if (Platform.OS === 'android') { - // Consume back only when an example is open so the list can peek - // through during in-app predictive back. On the root list, leave - // intercept off so the system back-to-home animation can run. + // Consume back only when an example is open so hardware back pops it. + // On the root list, leave intercept off so the system back-to-home + // animation can run. BackHandler.setInterceptEnabled(activeModuleKey != null); } return () => { @@ -439,37 +439,8 @@ const RNTesterApp = ({ return ( {Platform.OS === 'android' ? : null} - - - {listPane} - - {modulePane != null ? ( - // In-flow so it fills the screen and paints on top. nativeID must - // match ReactActivity.PREDICTIVE_BACK_FRONT_PANE_NATIVE_ID. - - {modulePane} - - ) : null} + + {modulePane != null ? modulePane : listPane} @@ -479,23 +450,6 @@ const RNTesterApp = ({ export default RNTesterApp; const styles = StyleSheet.create({ - stack: { - flex: 1, - }, - // Previous screen: taken out of flow so it stays mounted behind the example. - backPane: { - position: 'absolute', - top: 0, - left: 0, - right: 0, - bottom: 0, - zIndex: 0, - }, - // Current screen: in-flow, fills the parent, drawn last (on top). - frontPane: { - flex: 1, - zIndex: 1, - }, container: { flex: 1, }, diff --git a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js index 97d0de831613..147e5c22149b 100644 --- a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js +++ b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js @@ -12,11 +12,46 @@ import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; import RNTesterText from '../../components/RNTesterText'; import * as React from 'react'; -import {useEffect, useState} from 'react'; -import {BackHandler, Platform, StyleSheet, View} from 'react-native'; +import {useEffect, useMemo, useState} from 'react'; +import { + Animated, + BackHandler, + Platform, + PredictiveBackAnimatedView, + StyleSheet, + View, + useAnimatedValue, +} from 'react-native'; function Playground() { const [events, setEvents] = useState<$ReadOnlyArray>([]); + const progress = useAnimatedValue(0); + const onProgress = useMemo( + () => Animated.event([{nativeEvent: {progress}}], {useNativeDriver: true}), + [progress], + ); + const boxStyle = useMemo( + () => [ + styles.box, + { + transform: [ + { + scale: progress.interpolate({ + inputRange: [0, 1], + outputRange: [1, 0.82], + }), + }, + { + translateX: progress.interpolate({ + inputRange: [0, 1], + outputRange: [0, 28], + }), + }, + ], + }, + ], + [progress], + ); useEffect(() => { if (Platform.OS !== 'android') { @@ -50,29 +85,14 @@ function Playground() { Predictive back - Nested screens keep the list mounted underneath. Swipe from the edge and - hold: the example pane should shrink and the list should peek through. - The root list leaves intercept off so Android can play back-to-home. - - - 1. API 36 device/AVD, gesture navigation, animations on. - - - 2. From this Playground screen, swipe from the edge and hold: the - Components list should peek behind this pane. Swipe far (or flick) and - release: this pane should keep shrinking and fade out, then pop. Release - early to cancel: this pane should spring back to full screen. The app - must not close. - - - 3. From the root list, swipe from the edge and hold: the activity should - shrink and home should peek through. Release to exit; Metro logs - [PredictiveBack]. Returning true cannot prevent that exit. - - - 4. From the root list, release early to cancel: no JS event, activity - springs back. + The blue box is driven by PredictiveBackAnimatedView + Animated.event + (native driver). Swipe from the edge: the box should shrink. Prefer the + APIs → PredictiveBack example for the hook helper. + {Platform.OS === 'android' ? ( + + ) : null} + JS events {events.length === 0 ? ( @@ -98,13 +118,17 @@ const styles = StyleSheet.create({ fontWeight: '700', marginBottom: 4, }, - step: { - marginTop: 4, - }, logTitle: { fontWeight: '700', marginTop: 12, }, + box: { + marginTop: 16, + width: 120, + height: 80, + borderRadius: 12, + backgroundColor: '#3b82f6', + }, }); export default { From 9aced4d1c880b3b8f1c432caed868c015aab3124 Mon Sep 17 00:00:00 2001 From: Grzegorz Kruk Date: Thu, 10 Sep 2026 11:28:43 +0200 Subject: [PATCH 06/11] Refactor predictive back navigation components and remove deprecated functionality Summary: - Removed `usePredictiveBackAnimatedValue` hook and related predictive back event types from `BackHandler` and `ReactActivity`. - Updated `PredictiveBackAnimatedView` to streamline predictive back gesture handling. - Adjusted type definitions and flow types to reflect the removal of deprecated predictive back features. - Cleaned up related tests and examples to align with the new implementation. Changelog: [GENERAL][REMOVED] - Deprecated predictive back functionality and related types. --- .../PredictiveBackAnimatedView.android.js | 14 ----- .../PredictiveBackAnimatedView.ios.js | 10 ---- .../PredictiveBackAnimatedView.js | 1 - .../PredictiveBackAnimatedView.js.flow | 6 -- .../Utilities/BackHandler.android.js | 59 ------------------- .../Libraries/Utilities/BackHandler.ios.js | 18 ------ .../Libraries/Utilities/BackHandler.js.flow | 18 ------ .../Utilities/__mocks__/BackHandler.js | 16 +---- .../Utilities/__tests__/BackHandler-itest.js | 40 ------------- .../facebook/react/PredictiveBackEvent.java | 4 +- .../com/facebook/react/ReactActivity.java | 37 ------------ packages/react-native/ReactNativeApi.d.ts | 20 +------ packages/react-native/index.js | 4 -- packages/react-native/index.js.flow | 11 +--- .../PredictiveBackAnimatedView.d.ts | 6 -- .../Libraries/Utilities/BackHandler.d.ts | 17 ------ .../examples/Playground/RNTesterPlayground.js | 9 +-- .../PredictiveBack/PredictiveBackExample.js | 19 +++--- 18 files changed, 19 insertions(+), 290 deletions(-) diff --git a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.android.js b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.android.js index 755fcb02b55c..bf41f9a333c5 100644 --- a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.android.js +++ b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.android.js @@ -11,10 +11,8 @@ import type {PredictiveBackNativeEvent} from './PredictiveBackAnimatedViewNativeComponent'; import Animated from '../../Animated/Animated'; -import useAnimatedValue from '../../Animated/useAnimatedValue'; import PredictiveBackAnimatedViewNativeComponent from './PredictiveBackAnimatedViewNativeComponent'; import * as React from 'react'; -import {useMemo} from 'react'; /** * Hidden host view that emits predictive-back progress as a native event. @@ -47,18 +45,6 @@ const NativeAnimatedView = Animated.createAnimatedComponent( export type {PredictiveBackNativeEvent}; -export function usePredictiveBackAnimatedValue(): { - progress: Animated.Value, - onProgress: $FlowFixMe, -} { - const progress = useAnimatedValue(0); - const onProgress = useMemo( - () => Animated.event([{nativeEvent: {progress}}], {useNativeDriver: true}), - [progress], - ); - return {progress, onProgress}; -} - function PredictiveBackAnimatedView( props: React.ElementConfig, ): React.Node { diff --git a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.ios.js b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.ios.js index e7c1f6513fe1..dbd5c97477ab 100644 --- a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.ios.js +++ b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.ios.js @@ -10,8 +10,6 @@ import type {PredictiveBackNativeEvent} from './PredictiveBackAnimatedViewNativeComponent'; -import Animated from '../../Animated/Animated'; -import useAnimatedValue from '../../Animated/useAnimatedValue'; import * as React from 'react'; export type {PredictiveBackNativeEvent}; @@ -20,12 +18,4 @@ function PredictiveBackAnimatedView(_props: {...}): React.Node { return null; } -export function usePredictiveBackAnimatedValue(): { - progress: Animated.Value, - onProgress: $FlowFixMe, -} { - const progress = useAnimatedValue(0); - return {progress, onProgress: () => {}}; -} - export default PredictiveBackAnimatedView; diff --git a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js index 4e9118cfc4af..60caab97e3f2 100644 --- a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js +++ b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js @@ -12,5 +12,4 @@ // from 'react-native' with platform-specific extensions. It can be deleted // once we remove the "./*" mapping from package.json "exports". -export {usePredictiveBackAnimatedValue} from './PredictiveBackAnimatedView'; export {default} from './PredictiveBackAnimatedView'; diff --git a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js.flow b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js.flow index cbed37be1ab5..02ee696f83ef 100644 --- a/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js.flow +++ b/packages/react-native/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.js.flow @@ -12,7 +12,6 @@ import type {ViewProps} from '../View/ViewPropTypes'; -import Animated from '../../Animated/Animated'; import * as React from 'react'; export type PredictiveBackNativeEvent = { @@ -28,11 +27,6 @@ export type PredictiveBackAnimatedViewProps = { onProgress?: (event: {nativeEvent: PredictiveBackNativeEvent}) => mixed, }; -declare export function usePredictiveBackAnimatedValue(): { - progress: Animated.Value, - onProgress: $FlowFixMe, -}; - declare const PredictiveBackAnimatedView: React.AbstractComponent; declare export default typeof PredictiveBackAnimatedView; diff --git a/packages/react-native/Libraries/Utilities/BackHandler.android.js b/packages/react-native/Libraries/Utilities/BackHandler.android.js index 9e9743716316..da0ad1f25785 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.android.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.android.js @@ -14,23 +14,11 @@ import RCTDeviceEventEmitter from '../EventEmitter/RCTDeviceEventEmitter'; import {HardwareBackPressEvent} from './HardwareBackPressEvent'; const DEVICE_BACK_EVENT = 'hardwareBackPress'; -const PREDICTIVE_BACK_EVENT = 'predictiveBack'; type BackPressEventName = 'backPress' | 'hardwareBackPress'; type BackPressHandler = (event: HardwareBackPressEvent) => ?boolean; -export type PredictiveBackPhase = 'start' | 'progress' | 'cancel' | 'commit'; -export type PredictiveBackEvent = { - phase: PredictiveBackPhase, - progress: number, - swipeEdge: number, - touchX: number, - touchY: number, -}; -type PredictiveBackListener = (event: PredictiveBackEvent) => void; - const _backPressSubscriptions: Array = []; -const _predictiveBackSubscriptions: Array = []; RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function (nativeEvent) { const options = {}; @@ -48,22 +36,6 @@ RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function (nativeEvent) { BackHandler.exitApp(); }); -RCTDeviceEventEmitter.addListener( - PREDICTIVE_BACK_EVENT, - function (nativeEvent) { - const event: PredictiveBackEvent = { - phase: nativeEvent?.phase ?? 'progress', - progress: nativeEvent?.progress ?? 0, - swipeEdge: nativeEvent?.swipeEdge ?? 2, - touchX: nativeEvent?.touchX ?? 0, - touchY: nativeEvent?.touchY ?? 0, - }; - for (let i = _predictiveBackSubscriptions.length - 1; i >= 0; i--) { - _predictiveBackSubscriptions[i]?.(event); - } - }, -); - /** * Detects hardware button presses for back navigation and lets you register * event listeners for the system's back action. Event subscriptions are called @@ -87,15 +59,6 @@ type TBackHandler = { * BackHandler still observes app-exit commit. */ readonly setInterceptEnabled: (enabled: boolean) => void, - /** - * Android only. Observes in-app predictive-back phases. Progress is - * throttled and is not suitable for 60fps animation; native libraries - * should use PredictiveBackHandler on ReactActivity instead. - */ - readonly addPredictiveBackListener: (handler: PredictiveBackListener) => { - remove: () => void, - ... - }, }; const BackHandler: TBackHandler = { /** @@ -137,28 +100,6 @@ const BackHandler: TBackHandler = { }, }; }, - - /** - * Listen for in-app predictive-back phases (`start`, `progress`, - * `cancel`, `commit`). Returning a value does not consume the gesture; - * use `setInterceptEnabled` or a native `PredictiveBackHandler` for that. - */ - addPredictiveBackListener: function (handler: PredictiveBackListener): { - remove: () => void, - ... - } { - if (_predictiveBackSubscriptions.indexOf(handler) === -1) { - _predictiveBackSubscriptions.push(handler); - } - return { - remove: (): void => { - const index = _predictiveBackSubscriptions.indexOf(handler); - if (index !== -1) { - _predictiveBackSubscriptions.splice(index, 1); - } - }, - }; - }, }; export default BackHandler; diff --git a/packages/react-native/Libraries/Utilities/BackHandler.ios.js b/packages/react-native/Libraries/Utilities/BackHandler.ios.js index 61b1d412e5aa..6c3c19cd24f9 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.ios.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.ios.js @@ -13,15 +13,6 @@ import type {HardwareBackPressEvent} from './HardwareBackPressEvent'; type BackPressEventName = 'backPress' | 'hardwareBackPress'; type BackPressHandler = (event: HardwareBackPressEvent) => ?boolean; -export type PredictiveBackPhase = 'start' | 'progress' | 'cancel' | 'commit'; -export type PredictiveBackEvent = { - phase: PredictiveBackPhase, - progress: number, - swipeEdge: number, - touchX: number, - touchY: number, -}; - function emptyFunction(): void {} type TBackHandler = { @@ -31,10 +22,6 @@ type TBackHandler = { handler: BackPressHandler, ): {remove: () => void, ...}, setInterceptEnabled(enabled: boolean): void, - addPredictiveBackListener(handler: (event: PredictiveBackEvent) => void): { - remove: () => void, - ... - }, }; const BackHandler: TBackHandler = { @@ -45,11 +32,6 @@ const BackHandler: TBackHandler = { }; }, setInterceptEnabled(_enabled: boolean): void {}, - addPredictiveBackListener(_handler: (event: PredictiveBackEvent) => void) { - return { - remove: emptyFunction, - }; - }, }; export default BackHandler; diff --git a/packages/react-native/Libraries/Utilities/BackHandler.js.flow b/packages/react-native/Libraries/Utilities/BackHandler.js.flow index 0e66e08c8d25..3e8f68a16762 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.js.flow +++ b/packages/react-native/Libraries/Utilities/BackHandler.js.flow @@ -22,20 +22,6 @@ export interface HardwareBackPressEvent { readonly timeStamp: number; } -export type PredictiveBackPhase = 'start' | 'progress' | 'cancel' | 'commit'; - -/** - * Observational copy of an in-app predictive-back gesture. Progress is - * throttled and is not suitable for 60fps animation. - */ -export type PredictiveBackEvent = { - phase: PredictiveBackPhase, - progress: number, - swipeEdge: number, - touchX: number, - touchY: number, -}; - type TBackHandler = { exitApp(): void, addEventListener( @@ -43,10 +29,6 @@ type TBackHandler = { handler: (event: HardwareBackPressEvent) => ?boolean, ): {remove: () => void, ...}, setInterceptEnabled(enabled: boolean): void, - addPredictiveBackListener(handler: (event: PredictiveBackEvent) => void): { - remove: () => void, - ... - }, }; /** diff --git a/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js b/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js index ea417f7c3d0b..0523898fd782 100644 --- a/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js +++ b/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js @@ -8,7 +8,7 @@ * @format */ -import type {BackPressEventName, PredictiveBackEvent} from '../BackHandler'; +import type {BackPressEventName} from '../BackHandler'; import type {HardwareBackPressEvent} from '../HardwareBackPressEvent'; import {HardwareBackPressEvent as HardwareBackPressEventClass} from '../HardwareBackPressEvent'; @@ -16,25 +16,11 @@ import {HardwareBackPressEvent as HardwareBackPressEventClass} from '../Hardware const _backPressSubscriptions = new Set< (event: HardwareBackPressEvent) => ?boolean, >(); -const _predictiveBackSubscriptions = new Set< - (event: PredictiveBackEvent) => void, ->(); const BackHandler = { exitApp: jest.fn() as () => void, setInterceptEnabled: jest.fn() as (enabled: boolean) => void, - addPredictiveBackListener: function ( - handler: (event: PredictiveBackEvent) => void, - ): {remove: () => void, ...} { - _predictiveBackSubscriptions.add(handler); - return { - remove: () => { - _predictiveBackSubscriptions.delete(handler); - }, - }; - }, - addEventListener: function ( eventName: BackPressEventName, handler: (event: HardwareBackPressEvent) => ?boolean, diff --git a/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js b/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js index f6499833a4e3..2dfec3786236 100644 --- a/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js +++ b/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js @@ -141,44 +141,4 @@ describe('BackHandler', () => { expect(called).toBe(false); }); - - it('notifies predictiveBack listeners in reverse order', () => { - const callOrder: Array = []; - subscriptions.push( - BackHandler.addPredictiveBackListener(event => { - callOrder.push(`first:${event.phase}`); - }), - ); - subscriptions.push( - BackHandler.addPredictiveBackListener(event => { - callOrder.push(`second:${event.phase}`); - }), - ); - - RCTDeviceEventEmitter.emit('predictiveBack', { - phase: 'start', - progress: 0, - swipeEdge: 0, - touchX: 1, - touchY: 2, - }); - - expect(callOrder).toEqual(['second:start', 'first:start']); - }); - - it('does not call exitApp for predictiveBack', () => { - const exitApp = jest.spyOn(BackHandler, 'exitApp'); - subscriptions.push(BackHandler.addPredictiveBackListener(() => {})); - - RCTDeviceEventEmitter.emit('predictiveBack', { - phase: 'commit', - progress: 1, - swipeEdge: 0, - touchX: 0, - touchY: 0, - }); - - expect(exitApp).not.toHaveBeenCalled(); - exitApp.mockRestore(); - }); }); diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackEvent.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackEvent.java index 2cbe7818ee4f..8bbe4b32520a 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackEvent.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackEvent.java @@ -9,8 +9,8 @@ /** * Progress of an in-app predictive-back gesture. Native libraries (for example - * react-native-screens) receive this on the UI thread. JavaScript receives a copy via {@code - * BackHandler.addPredictiveBackListener}; that path is not suitable for 60fps animation. + * react-native-screens) receive this on the UI thread. JavaScript animates via {@code + * PredictiveBackAnimatedView} and {@code Animated.event}. */ public final class PredictiveBackEvent { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java index 69ff883b1993..7570be3c54e5 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java @@ -23,9 +23,6 @@ import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; -import com.facebook.react.bridge.Arguments; -import com.facebook.react.bridge.ReactContext; -import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.modules.core.PermissionAwareActivity; import com.facebook.react.modules.core.PermissionListener; @@ -39,8 +36,6 @@ public abstract class ReactActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler, PermissionAwareActivity { private static final String PREDICTIVE_BACK_TAG = "PredictiveBack"; - private static final String PREDICTIVE_BACK_JS_EVENT = "predictiveBack"; - private static final long JS_PROGRESS_THROTTLE_MS = 32; private static final PredictiveBackEvent EMPTY_PREDICTIVE_BACK_EVENT = new PredictiveBackEvent(0f, PredictiveBackEvent.EDGE_NONE, 0f, 0f); @@ -73,7 +68,6 @@ public void handleOnBackPressed() { private final List mPredictiveBackProgressListeners = new CopyOnWriteArrayList<>(); private PredictiveBackEvent mLastPredictiveBackEvent = EMPTY_PREDICTIVE_BACK_EVENT; - private long mLastJsProgressEmitMs; @SuppressWarnings("this-escape") protected ReactActivity() { @@ -238,12 +232,10 @@ private void updateConsumeCallback() { void dispatchPredictiveBackStarted(PredictiveBackEvent event) { mLastPredictiveBackEvent = event; - mLastJsProgressEmitMs = 0; for (int i = mPredictiveBackHandlers.size() - 1; i >= 0; i--) { mPredictiveBackHandlers.get(i).onPredictiveBackStarted(event); } notifyPredictiveBackProgressListeners(event, PredictiveBackEvent.PHASE_START); - emitPredictiveBackToJs("start", event, false); } void dispatchPredictiveBackProgressed(PredictiveBackEvent event) { @@ -252,7 +244,6 @@ void dispatchPredictiveBackProgressed(PredictiveBackEvent event) { mPredictiveBackHandlers.get(i).onPredictiveBackProgressed(event); } notifyPredictiveBackProgressListeners(event, PredictiveBackEvent.PHASE_PROGRESS); - emitPredictiveBackToJs("progress", event, true); } void dispatchPredictiveBackCancelled() { @@ -266,7 +257,6 @@ void dispatchPredictiveBackCancelled() { mLastPredictiveBackEvent.touchX, mLastPredictiveBackEvent.touchY); notifyPredictiveBackProgressListeners(reset, PredictiveBackEvent.PHASE_CANCEL); - emitPredictiveBackToJs("cancel", mLastPredictiveBackEvent, false); } void finishPredictiveBackCommit() { @@ -284,7 +274,6 @@ void finishPredictiveBackCommit() { mLastPredictiveBackEvent.touchX, mLastPredictiveBackEvent.touchY); notifyPredictiveBackProgressListeners(done, PredictiveBackEvent.PHASE_COMMIT); - emitPredictiveBackToJs("commit", mLastPredictiveBackEvent, false); if (!consumed) { notifyJsHardwareBackPressed(); } @@ -296,32 +285,6 @@ private void notifyPredictiveBackProgressListeners(PredictiveBackEvent event, in } } - private void emitPredictiveBackToJs( - String phase, PredictiveBackEvent event, boolean throttleProgress) { - if (throttleProgress) { - long now = SystemClock.uptimeMillis(); - if (mLastJsProgressEmitMs != 0 && now - mLastJsProgressEmitMs < JS_PROGRESS_THROTTLE_MS) { - return; - } - mLastJsProgressEmitMs = now; - } - ReactDelegate reactDelegate = getReactDelegate(); - if (reactDelegate == null) { - return; - } - ReactContext context = reactDelegate.getCurrentReactContext(); - if (context == null) { - return; - } - WritableMap map = Arguments.createMap(); - map.putString("phase", phase); - map.putDouble("progress", event.progress); - map.putInt("swipeEdge", event.swipeEdge); - map.putDouble("touchX", event.touchX); - map.putDouble("touchY", event.touchY); - context.emitDeviceEvent(PREDICTIVE_BACK_JS_EVENT, map); - } - void notifyJsHardwareBackPressed() { mDelegate.onBackPressed(); } diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index 852f861c84a3..74288e1e4c2a 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -3589,13 +3589,6 @@ declare type PredictiveBackAnimatedView = typeof PredictiveBackAnimatedView declare type PredictiveBackAnimatedViewProps = ViewProps & { onProgress?: (event: { nativeEvent: PredictiveBackNativeEvent }) => unknown } -declare type PredictiveBackEvent = { - phase: PredictiveBackPhase - progress: number - swipeEdge: number - touchX: number - touchY: number -} declare type PredictiveBackNativeEvent = { phase: number progress: number @@ -3603,7 +3596,6 @@ declare type PredictiveBackNativeEvent = { touchX: number touchY: number } -declare type PredictiveBackPhase = "cancel" | "commit" | "progress" | "start" declare type PresentLocalNotificationDetails = { alertAction?: string alertBody: string @@ -4881,9 +4873,6 @@ declare type TBackHandler = { ): { remove: () => void } - addPredictiveBackListener(handler: (event: PredictiveBackEvent) => void): { - remove: () => void - } exitApp(): void setInterceptEnabled(enabled: boolean): void } @@ -5478,10 +5467,6 @@ declare function useAnimatedValueXY( ): Animated.ValueXY declare function useAppState(): AppStateStatus declare function useColorScheme(): ColorSchemeName | null -declare function usePredictiveBackAnimatedValue(): { - onProgress: any - progress: Animated.Value -} declare function usePressability( config: null | PressabilityConfig | undefined, ): null | PressabilityEventHandlers @@ -5830,7 +5815,7 @@ export { AssetDestPathResolver, // 59047424 AssetRegistry, // 6070bb45 AutoCapitalize, // c0e857a0 - BackHandler, // c0042375 + BackHandler, // 51d37a56 BackPressEventName, // 4620fb76 BlurEvent, // d5e68e96 BoxShadowValue, // b679703f @@ -5979,9 +5964,7 @@ export { PointerEvent, // a506d9d7 PredictiveBackAnimatedView, // b7897c30 PredictiveBackAnimatedViewProps, // 9d8f7fe6 - PredictiveBackEvent, // e2919d69 PredictiveBackNativeEvent, // a7e9dafb - PredictiveBackPhase, // dcc1122c PressabilityConfig, // 0fd655fe PressabilityEventHandlers, // be359ba3 Pressable, // 56235a5f @@ -6123,7 +6106,6 @@ export { useAnimatedValueXY, // dc9057ea useAppState, // 9338748a useColorScheme, // d585efdb - usePredictiveBackAnimatedValue, // 99a81437 usePressability, // af291ad3 useWindowDimensions, // bb4b683f } diff --git a/packages/react-native/index.js b/packages/react-native/index.js index f62f4257969e..d43240a78a45 100644 --- a/packages/react-native/index.js +++ b/packages/react-native/index.js @@ -381,10 +381,6 @@ module.exports = { get useAnimatedValue() { return require('./Libraries/Animated/useAnimatedValue').default; }, - get usePredictiveBackAnimatedValue() { - return require('./Libraries/Components/PredictiveBack/PredictiveBackAnimatedView') - .usePredictiveBackAnimatedValue; - }, get useAnimatedValueXY() { return require('./Libraries/Animated/useAnimatedValueXY').default; }, diff --git a/packages/react-native/index.js.flow b/packages/react-native/index.js.flow index e7b67e72c236..d10783899c09 100644 --- a/packages/react-native/index.js.flow +++ b/packages/react-native/index.js.flow @@ -98,10 +98,7 @@ export type { PredictiveBackAnimatedViewProps, PredictiveBackNativeEvent, } from './Libraries/Components/PredictiveBack/PredictiveBackAnimatedView'; -export { - default as PredictiveBackAnimatedView, - usePredictiveBackAnimatedValue, -} from './Libraries/Components/PredictiveBack/PredictiveBackAnimatedView'; +export {default as PredictiveBackAnimatedView} from './Libraries/Components/PredictiveBack/PredictiveBackAnimatedView'; export type { ProgressBarAndroidInstance, @@ -297,11 +294,7 @@ export type { PackagerAsset, } from './src/private/assets/AssetRegistry'; -export type { - BackPressEventName, - PredictiveBackEvent, - PredictiveBackPhase, -} from './Libraries/Utilities/BackHandler'; +export type {BackPressEventName} from './Libraries/Utilities/BackHandler'; export {default as BackHandler} from './Libraries/Utilities/BackHandler'; export {default as Clipboard} from './Libraries/Components/Clipboard/Clipboard'; diff --git a/packages/react-native/types_DEPRECATED/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.d.ts b/packages/react-native/types_DEPRECATED/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.d.ts index bba4d03fb587..a4749c09b17f 100644 --- a/packages/react-native/types_DEPRECATED/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.d.ts +++ b/packages/react-native/types_DEPRECATED/Libraries/Components/PredictiveBack/PredictiveBackAnimatedView.d.ts @@ -8,7 +8,6 @@ */ import type * as React from 'react'; -import type {Animated} from '../../Animated/Animated'; import {ViewProps} from '../View/ViewPropTypes'; export interface PredictiveBackNativeEvent { @@ -23,10 +22,5 @@ export interface PredictiveBackAnimatedViewProps extends ViewProps { onProgress?: (event: {nativeEvent: PredictiveBackNativeEvent}) => void; } -export function usePredictiveBackAnimatedValue(): { - progress: Animated.Value; - onProgress: (...args: any[]) => void; -}; - export const PredictiveBackAnimatedView: React.ComponentType; export default PredictiveBackAnimatedView; diff --git a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts index 7e269c765d68..03f240589cbd 100644 --- a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts +++ b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts @@ -21,16 +21,6 @@ export interface HardwareBackPressEvent { readonly timeStamp: number; } -export type PredictiveBackPhase = 'start' | 'progress' | 'cancel' | 'commit'; - -export interface PredictiveBackEvent { - readonly phase: PredictiveBackPhase; - readonly progress: number; - readonly swipeEdge: number; - readonly touchX: number; - readonly touchY: number; -} - /** * Detect hardware back button presses, and programmatically invoke the * default back button functionality to exit the app if there are no @@ -56,13 +46,6 @@ export interface BackHandlerStatic { * BackHandler still observes app-exit commit. */ setInterceptEnabled(enabled: boolean): void; - /** - * Android only. Observes in-app predictive-back phases. Progress is - * throttled and is not suitable for 60fps animation. - */ - addPredictiveBackListener( - handler: (event: PredictiveBackEvent) => void, - ): NativeEventSubscription; } export const BackHandler: BackHandlerStatic; diff --git a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js index 147e5c22149b..4ad7b6fa3a5a 100644 --- a/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js +++ b/packages/rn-tester/js/examples/Playground/RNTesterPlayground.js @@ -69,15 +69,9 @@ function Playground() { return false; }, ); - const predictive = BackHandler.addPredictiveBackListener(event => { - const line = `${new Date().toISOString()} ${event.phase} progress=${event.progress.toFixed(2)}`; - console.log('[PredictiveBack]', line); - setEvents(current => [line, ...current].slice(0, 8)); - }); return () => { subscription.remove(); - predictive.remove(); }; }, []); @@ -86,8 +80,7 @@ function Playground() { Predictive back The blue box is driven by PredictiveBackAnimatedView + Animated.event - (native driver). Swipe from the edge: the box should shrink. Prefer the - APIs → PredictiveBack example for the hook helper. + (native driver). Swipe from the edge: the box should shrink. {Platform.OS === 'android' ? ( diff --git a/packages/rn-tester/js/examples/PredictiveBack/PredictiveBackExample.js b/packages/rn-tester/js/examples/PredictiveBack/PredictiveBackExample.js index 7783ccaf16a1..a65303e30e1f 100644 --- a/packages/rn-tester/js/examples/PredictiveBack/PredictiveBackExample.js +++ b/packages/rn-tester/js/examples/PredictiveBack/PredictiveBackExample.js @@ -21,11 +21,15 @@ import { PredictiveBackAnimatedView, StyleSheet, View, - usePredictiveBackAnimatedValue, + useAnimatedValue, } from 'react-native'; -function UsePredictiveBackAnimatedValueExample(): React.Node { - const {progress, onProgress} = usePredictiveBackAnimatedValue(); +function PredictiveBackAnimatedExample(): React.Node { + const progress = useAnimatedValue(0); + const onProgress = useMemo( + () => Animated.event([{nativeEvent: {progress}}], {useNativeDriver: true}), + [progress], + ); const boxStyle = useMemo( () => [ styles.box, @@ -53,7 +57,8 @@ function UsePredictiveBackAnimatedValueExample(): React.Node { Swipe from the edge and hold. The box is driven by - usePredictiveBackAnimatedValue through the native Animated driver. + PredictiveBackAnimatedView through Animated.event and the native + driver. {Platform.OS === 'android' ? ( @@ -80,15 +85,15 @@ const styles = StyleSheet.create({ exports.title = 'PredictiveBack'; exports.category = 'Android'; exports.description = - 'Drive RN Animated from Android predictive-back progress with usePredictiveBackAnimatedValue.'; + 'Drive RN Animated from Android predictive-back progress with PredictiveBackAnimatedView and Animated.event.'; exports.examples = [ { - title: 'usePredictiveBackAnimatedValue', + title: 'PredictiveBackAnimatedView', description: 'Native-driver progress from the system back gesture. Requires API 34+ gesture navigation.', platform: 'android', render(): React.Node { - return ; + return ; }, }, ] as Array; From 51f36dfc061064ad886c76898100b66f1879c14d Mon Sep 17 00:00:00 2001 From: Grzegorz Kruk Date: Fri, 11 Sep 2026 12:40:31 +0200 Subject: [PATCH 07/11] Add predictive back gesture handling to BackHandler and ReactActivity Summary: - Introduced `claimPredictiveBack` method to `BackHandler` for managing back gesture ownership in overlays. - Updated `ReactActivity` to support predictive back claims, allowing for better control over back gesture handling. - Enhanced type definitions to include new methods and properties related to predictive back functionality. - Added unit tests to validate the new predictive back behavior and ensure proper event handling. Changelog: [GENERAL][ADDED] - Support for predictive back gesture management in BackHandler and ReactActivity. --- .../Utilities/BackHandler.android.js | 61 ++++++++++++--- .../Libraries/Utilities/BackHandler.ios.js | 6 ++ .../Utilities/__mocks__/BackHandler.js | 4 + .../Utilities/__tests__/BackHandler-itest.js | 7 ++ .../ReactAndroid/api/ReactAndroid.api | 8 ++ .../facebook/react/PredictiveBackClaim.java | 46 +++++++++++ .../com/facebook/react/ReactActivity.java | 77 ++++++++++++++++--- .../ReactActivityBackPressedCallbackTest.kt | 65 ++++++++++++++++ packages/react-native/ReactNativeApi.d.ts | 3 + packages/react-native/gradle.properties | 6 +- .../Libraries/Utilities/BackHandler.d.ts | 20 +++-- 11 files changed, 277 insertions(+), 26 deletions(-) create mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackClaim.java diff --git a/packages/react-native/Libraries/Utilities/BackHandler.android.js b/packages/react-native/Libraries/Utilities/BackHandler.android.js index da0ad1f25785..d5e3aed09ba0 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.android.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.android.js @@ -17,8 +17,21 @@ const DEVICE_BACK_EVENT = 'hardwareBackPress'; type BackPressEventName = 'backPress' | 'hardwareBackPress'; type BackPressHandler = (event: HardwareBackPressEvent) => ?boolean; +type BackHandlerSubscription = {remove: () => void, ...}; const _backPressSubscriptions: Array = []; +let _interceptEnabled = false; +let _nextClaimId = 1; +const _activeClaims: Set = new Set(); + +function syncNativeConsume(): void { + if (!NativeDeviceEventManager) { + return; + } + NativeDeviceEventManager.setInterceptEnabled( + _interceptEnabled || _activeClaims.size > 0, + ); +} RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function (nativeEvent) { const options = {}; @@ -50,13 +63,26 @@ type TBackHandler = { readonly addEventListener: ( eventName: BackPressEventName, handler: BackPressHandler, - ) => {remove: () => void, ...}, + ) => BackHandlerSubscription, + /** + * Takes the Android back gesture until `remove()` is called. Stack claims + * for overlays (modal, sheet, JS chrome): the last remaining owner keeps + * the swipe. Releasing the last claim returns it to screens / the system. + * + * `PredictiveBackAnimatedView` only receives progress while some owner + * (a claim, setInterceptEnabled, or a native handler) is consuming. + * + * @platform android + */ + readonly claimPredictiveBack: () => BackHandlerSubscription, /** - * Android only. When true, React Native consumes the back gesture so - * BackHandler can pop an in-app screen. On Android 16+, progress is - * delivered to PredictiveBackAnimatedView and native PredictiveBackHandler - * plugins. When false, the system predictive-back animation can run; - * BackHandler still observes app-exit commit. + * Android only. Process-wide consume bit. Prefer `claimPredictiveBack` for + * something with a lifetime. When true, React Native consumes the back + * gesture so BackHandler can pop an in-app screen. On Android 16+, progress + * is delivered to PredictiveBackAnimatedView and native PredictiveBackHandler + * plugins. When false and nothing else owns the swipe, the system + * predictive-back animation can run; BackHandler still observes app-exit + * commit. */ readonly setInterceptEnabled: (enabled: boolean) => void, }; @@ -73,11 +99,26 @@ const BackHandler: TBackHandler = { }, setInterceptEnabled: function (enabled: boolean): void { - if (!NativeDeviceEventManager) { - return; - } + _interceptEnabled = enabled; + syncNativeConsume(); + }, - NativeDeviceEventManager.setInterceptEnabled(enabled); + claimPredictiveBack: function (): BackHandlerSubscription { + const id = _nextClaimId++; + _activeClaims.add(id); + syncNativeConsume(); + let removed = false; + return { + remove: (): void => { + if (removed) { + return; + } + removed = true; + if (_activeClaims.delete(id)) { + syncNativeConsume(); + } + }, + }; }, /** diff --git a/packages/react-native/Libraries/Utilities/BackHandler.ios.js b/packages/react-native/Libraries/Utilities/BackHandler.ios.js index 6c3c19cd24f9..a79cedc96a64 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.ios.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.ios.js @@ -21,6 +21,7 @@ type TBackHandler = { eventName: BackPressEventName, handler: BackPressHandler, ): {remove: () => void, ...}, + claimPredictiveBack(): {remove: () => void, ...}, setInterceptEnabled(enabled: boolean): void, }; @@ -31,6 +32,11 @@ const BackHandler: TBackHandler = { remove: emptyFunction, }; }, + claimPredictiveBack() { + return { + remove: emptyFunction, + }; + }, setInterceptEnabled(_enabled: boolean): void {}, }; diff --git a/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js b/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js index 0523898fd782..9df211468047 100644 --- a/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js +++ b/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js @@ -20,6 +20,10 @@ const _backPressSubscriptions = new Set< const BackHandler = { exitApp: jest.fn() as () => void, setInterceptEnabled: jest.fn() as (enabled: boolean) => void, + claimPredictiveBack: jest.fn(() => ({remove: jest.fn()})) as () => { + remove: () => void, + ... + }, addEventListener: function ( eventName: BackPressEventName, diff --git a/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js b/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js index 2dfec3786236..9a59c7c641ca 100644 --- a/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js +++ b/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js @@ -127,6 +127,13 @@ describe('BackHandler', () => { } }); + it('claimPredictiveBack returns an idempotent subscription', () => { + const sub = BackHandler.claimPredictiveBack(); + expect(typeof sub.remove).toBe('function'); + sub.remove(); + sub.remove(); + }); + it('removes handler on subscription.remove()', () => { let called = false; const handler = (_event: HardwareBackPressEventType) => { diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index 62910552d8c6..e7445c019769 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -73,6 +73,12 @@ public final class com/facebook/react/PredictiveBackEvent { public fun (FIFF)V } +public final class com/facebook/react/PredictiveBackClaim : java/lang/AutoCloseable { + public fun close ()V + public fun isReleased ()Z + public fun release ()V +} + public abstract interface class com/facebook/react/PredictiveBackHandler { public abstract fun onPredictiveBackCancelled ()V public abstract fun onPredictiveBackCommitted ()Z @@ -88,6 +94,7 @@ public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/ protected fun ()V public fun addPredictiveBackHandler (Lcom/facebook/react/PredictiveBackHandler;)V public fun addPredictiveBackProgressListener (Lcom/facebook/react/PredictiveBackProgressListener;)V + public fun claimPredictiveBack ()Lcom/facebook/react/PredictiveBackClaim; protected fun createReactActivityDelegate ()Lcom/facebook/react/ReactActivityDelegate; public fun getBackPressedCallback ()Landroidx/activity/OnBackPressedCallback; protected fun getMainComponentName ()Ljava/lang/String; @@ -96,6 +103,7 @@ public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/ protected fun getReactHost ()Lcom/facebook/react/ReactHost; protected final fun getReactInstanceManager ()Lcom/facebook/react/ReactInstanceManager; protected final fun getReactNativeHost ()Lcom/facebook/react/ReactNativeHost; + public fun hasPredictiveBackOwner ()Z public fun invokeDefaultOnBackPressed ()V protected final fun loadApp (Ljava/lang/String;)V public fun onActivityResult (IILandroid/content/Intent;)V diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackClaim.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackClaim.java new file mode 100644 index 000000000000..f3ee061d8087 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackClaim.java @@ -0,0 +1,46 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react; + +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * A token that owns the Android back gesture until {@link #release()} (or {@link #close()}). + * + *

Use this for something that is not a stack-slide pop: a modal, form sheet, bottom sheet, or + * custom JS chrome. While any claim is held, React Native consumes the swipe and + * FragmentManager does not seek a stack transition. Releasing the last claim returns the gesture + * to the next owner (another claim, a {@link PredictiveBackHandler}, {@code setInterceptEnabled}, + * or screens / the system). + * + * @see ReactActivity#claimPredictiveBack() + */ +public final class PredictiveBackClaim implements AutoCloseable { + + private final ReactActivity mActivity; + private final AtomicBoolean mReleased = new AtomicBoolean(false); + + PredictiveBackClaim(ReactActivity activity) { + mActivity = activity; + } + + public boolean isReleased() { + return mReleased.get(); + } + + public void release() { + if (mReleased.compareAndSet(false, true)) { + mActivity.releasePredictiveBackClaim(this); + } + } + + @Override + public void close() { + release(); + } +} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java index 7570be3c54e5..bd309dc39152 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java @@ -28,7 +28,9 @@ import com.facebook.react.modules.core.PermissionListener; import com.facebook.react.util.AndroidVersion; import java.util.List; +import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CopyOnWriteArraySet; import org.jetbrains.annotations.NotNull; /** Base Activity for React Native applications. */ @@ -41,11 +43,19 @@ public abstract class ReactActivity extends AppCompatActivity private final ReactActivityDelegate mDelegate; - // On targetSdk 36, Activity.onBackPressed() is no longer invoked by the system. This callback - // keeps JS BackHandler working by consuming back and forwarding it to JS. - // An enabled callback suppresses the system predictive-back animation (back-to-home, - // cross-activity, cross-task) and FragmentManager predictive-back transitions. Navigation - // libraries that implement predictive back should disable it via getBackPressedCallback(). + // Keeps JS BackHandler working. On targetSdk 36+ the system no longer calls + // Activity.onBackPressed(), so this callback is what turns a committed back into a JS + // hardwareBackPress; below 36 it only has to be enabled to win the dispatcher. + // + // Being enabled is also what claims the gesture: it suppresses the system predictive-back + // animation and keeps FragmentManager from receiving the swipe. On 36+ progress-carrying back + // goes through InAppPredictiveBack instead (see updateConsumeCallback), which keeps this + // callback disabled while it is active. + // + // A navigation library that wants to own the swipe (react-native-screens, so that + // FragmentManager can animate it) takes it either through claimPredictiveBack / + // addPredictiveBackHandler / setInterceptEnabled, or by disabling this callback via + // getBackPressedCallback(). private final OnBackPressedCallback mBackPressedCallback = new OnBackPressedCallback(true) { @Override @@ -64,6 +74,7 @@ public void handleOnBackPressed() { private @Nullable Object mInAppPredictiveBack; private boolean mJsInterceptEnabled; + private final Set mPredictiveBackClaims = new CopyOnWriteArraySet<>(); private final List mPredictiveBackHandlers = new CopyOnWriteArrayList<>(); private final List mPredictiveBackProgressListeners = new CopyOnWriteArrayList<>(); @@ -169,17 +180,49 @@ void onSystemNavigationBackInvoked() { } /** - * When {@code true}, React Native consumes the back gesture so JS {@code BackHandler} can pop an - * in-app screen. On Android 16+ (targetSdk 36) this registers a platform {@link + * Process-wide consume bit. Prefer {@link #claimPredictiveBack()} for something with a lifetime + * (modal, sheet, JS chrome): a claim releases itself, this flag does not. + * + *

When {@code true}, React Native consumes the back gesture so JS {@code BackHandler} can pop + * an in-app screen. On Android 16+ (targetSdk 36) this registers a platform {@link * OnBackAnimationCallback} that delivers progress to {@link PredictiveBackHandler} and {@link * PredictiveBackProgressListener} (used by {@code PredictiveBackAnimatedView}). When {@code - * false} and no native handler is registered, the system predictive-back animation can run. + * false} and nothing else owns the swipe, the system or FragmentManager can run predictive back. */ public void setInterceptEnabled(boolean enabled) { mJsInterceptEnabled = enabled; updateConsumeCallback(); } + /** + * Takes the back gesture until the returned token is released. Stack this for overlays: the last + * remaining owner keeps the swipe, and releasing the last claim returns it to screens / the + * system. + * + *

On Android 16+ the in-app callback is registered at {@code PRIORITY_OVERLAY} so it stays + * above FragmentManager after a later fragment transaction. + */ + public PredictiveBackClaim claimPredictiveBack() { + PredictiveBackClaim claim = new PredictiveBackClaim(this); + mPredictiveBackClaims.add(claim); + updateConsumeCallback(); + return claim; + } + + /** + * {@code true} while JS intercept, a {@link PredictiveBackClaim}, or a {@link + * PredictiveBackHandler} wants the swipe. + */ + public boolean hasPredictiveBackOwner() { + return shouldConsumeBack(); + } + + void releasePredictiveBackClaim(PredictiveBackClaim claim) { + if (mPredictiveBackClaims.remove(claim)) { + updateConsumeCallback(); + } + } + /** * Registers a native plugin (for example react-native-screens) as an owner of the back gesture. * While any handler is registered, React Native consumes the gesture. If a handler returns {@code @@ -212,8 +255,14 @@ public void removePredictiveBackProgressListener(PredictiveBackProgressListener mPredictiveBackProgressListeners.remove(listener); } + private boolean shouldConsumeBack() { + return mJsInterceptEnabled + || !mPredictiveBackClaims.isEmpty() + || !mPredictiveBackHandlers.isEmpty(); + } + private void updateConsumeCallback() { - boolean consume = mJsInterceptEnabled || !mPredictiveBackHandlers.isEmpty(); + boolean consume = shouldConsumeBack(); if (!AndroidVersion.isAtLeastTargetSdk36(this)) { mBackPressedCallback.setEnabled(consume); return; @@ -394,11 +443,19 @@ protected final void loadApp(String appKey) { @RequiresApi(34) private static final class InAppPredictiveBack { + // android.window.OnBackInvokedDispatcher.PRIORITY_OVERLAY (API 33). + // Inlined because this codebase is also compiled against older SDKs. + private static final int PRIORITY_OVERLAY = 1000000; + + @SuppressLint("WrongConstant") static Object register(ReactActivity activity) { Callback callback = new Callback(activity); + // OVERLAY, not DEFAULT: FragmentManager registers its seek callback lazily on a + // later transaction. Same-priority last-registered-wins would hand the swipe back + // to the stack after the next Push, even while a modal / JS claim is still held. activity .getOnBackInvokedDispatcher() - .registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT, callback); + .registerOnBackInvokedCallback(PRIORITY_OVERLAY, callback); return callback; } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt index f70f8ca8676f..b2ffc8ddd616 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt @@ -80,6 +80,71 @@ class ReactActivityBackPressedCallbackTest { assertThat(activity.backPressedCallback.isEnabled).isFalse() } + @Test + fun claimPredictiveBack_enablesCallbackWhenInterceptDisabled() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.setInterceptEnabled(false) + + val claim = activity.claimPredictiveBack() + + assertThat(activity.backPressedCallback.isEnabled).isTrue() + assertThat(activity.hasPredictiveBackOwner()).isTrue() + assertThat(claim.isReleased).isFalse() + } + + @Test + fun releasePredictiveBack_disablesCallbackWhenNoOtherOwner() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.setInterceptEnabled(false) + val claim = activity.claimPredictiveBack() + + claim.release() + + assertThat(activity.backPressedCallback.isEnabled).isFalse() + assertThat(activity.hasPredictiveBackOwner()).isFalse() + assertThat(claim.isReleased).isTrue() + } + + @Test + fun releasePredictiveBack_isIdempotent() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.setInterceptEnabled(false) + val claim = activity.claimPredictiveBack() + + claim.release() + claim.release() + + assertThat(activity.backPressedCallback.isEnabled).isFalse() + } + + @Test + fun claimPredictiveBack_keepsEnabledUntilLastClaimReleased() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.setInterceptEnabled(false) + val first = activity.claimPredictiveBack() + val second = activity.claimPredictiveBack() + + first.release() + + assertThat(activity.backPressedCallback.isEnabled).isTrue() + assertThat(activity.hasPredictiveBackOwner()).isTrue() + + second.release() + + assertThat(activity.backPressedCallback.isEnabled).isFalse() + } + + @Test + fun setInterceptEnabled_false_keepsEnabledWhileClaimHeld() { + val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() + activity.setInterceptEnabled(false) + activity.claimPredictiveBack() + + activity.setInterceptEnabled(false) + + assertThat(activity.backPressedCallback.isEnabled).isTrue() + } + @Test fun addPredictiveBackHandler_enablesCallbackWhenInterceptDisabled() { val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index 74288e1e4c2a..b74f57a83fdb 100644 --- a/packages/react-native/ReactNativeApi.d.ts +++ b/packages/react-native/ReactNativeApi.d.ts @@ -4873,6 +4873,9 @@ declare type TBackHandler = { ): { remove: () => void } + claimPredictiveBack(): { + remove: () => void + } exitApp(): void setInterceptEnabled(enabled: boolean): void } diff --git a/packages/react-native/gradle.properties b/packages/react-native/gradle.properties index 2d8d1e4dd150..80e274c34083 100644 --- a/packages/react-native/gradle.properties +++ b/packages/react-native/gradle.properties @@ -1 +1,5 @@ -android.useAndroidX=true \ No newline at end of file +android.useAndroidX=true + +# includeBuild does not inherit the app's gradle.properties. Without this, +# ReactAndroid compiles every ABI (~7GB extra) and fills the disk. +reactNativeArchitectures=arm64-v8a \ No newline at end of file diff --git a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts index 03f240589cbd..244049879efc 100644 --- a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts +++ b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts @@ -39,11 +39,21 @@ export interface BackHandlerStatic { handler: (event: HardwareBackPressEvent) => boolean | null | undefined, ): NativeEventSubscription; /** - * Android only. When true, React Native consumes the back gesture so - * BackHandler can pop an in-app screen. On Android 16+, progress is - * delivered to PredictiveBackAnimatedView and native PredictiveBackHandler - * plugins. When false, the system predictive-back animation can run; - * BackHandler still observes app-exit commit. + * Takes the Android back gesture until `remove()` is called. Use this for a + * modal, sheet, or other overlay so the swipe is yours until dismiss. + * Releasing the last claim returns the gesture to screens / the system. + * + * @platform android + */ + claimPredictiveBack(): NativeEventSubscription; + /** + * Android only. Process-wide consume bit. Prefer `claimPredictiveBack` for + * something with a lifetime. When true, React Native consumes the back + * gesture so BackHandler can pop an in-app screen. On Android 16+, progress + * is delivered to PredictiveBackAnimatedView and native PredictiveBackHandler + * plugins. When false and nothing else owns the swipe, the system + * predictive-back animation can run; BackHandler still observes app-exit + * commit. */ setInterceptEnabled(enabled: boolean): void; } From f776ba3850677cc4470779365d5e9d824da10bdb Mon Sep 17 00:00:00 2001 From: Grzegorz Kruk Date: Fri, 18 Sep 2026 09:48:08 +0200 Subject: [PATCH 08/11] refactor: remove predictive back claim functionality Summary: - Removed `claimPredictiveBack` method from `BackHandler` and related files to streamline back gesture management. - Updated type definitions and interfaces to reflect the removal of predictive back claims. - Cleaned up associated tests and mocks to ensure consistency with the new implementation. Changelog: [GENERAL][REMOVED] - Deprecated predictive back claim functionality from BackHandler and related components. --- .../Utilities/BackHandler.android.js | 65 ++++------------ .../Libraries/Utilities/BackHandler.ios.js | 6 -- .../Utilities/__mocks__/BackHandler.js | 4 - .../Utilities/__tests__/BackHandler-itest.js | 7 -- .../ReactAndroid/api/ReactAndroid.api | 8 -- .../facebook/react/PredictiveBackClaim.java | 46 ------------ .../com/facebook/react/ReactActivity.java | 74 ++++--------------- .../ReactActivityBackPressedCallbackTest.kt | 65 ---------------- packages/react-native/ReactNativeApi.d.ts | 9 +-- .../Libraries/Utilities/BackHandler.d.ts | 22 ++---- 10 files changed, 42 insertions(+), 264 deletions(-) delete mode 100644 packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackClaim.java diff --git a/packages/react-native/Libraries/Utilities/BackHandler.android.js b/packages/react-native/Libraries/Utilities/BackHandler.android.js index d5e3aed09ba0..c18e4c0a8d18 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.android.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.android.js @@ -17,21 +17,8 @@ const DEVICE_BACK_EVENT = 'hardwareBackPress'; type BackPressEventName = 'backPress' | 'hardwareBackPress'; type BackPressHandler = (event: HardwareBackPressEvent) => ?boolean; -type BackHandlerSubscription = {remove: () => void, ...}; const _backPressSubscriptions: Array = []; -let _interceptEnabled = false; -let _nextClaimId = 1; -const _activeClaims: Set = new Set(); - -function syncNativeConsume(): void { - if (!NativeDeviceEventManager) { - return; - } - NativeDeviceEventManager.setInterceptEnabled( - _interceptEnabled || _activeClaims.size > 0, - ); -} RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function (nativeEvent) { const options = {}; @@ -63,26 +50,19 @@ type TBackHandler = { readonly addEventListener: ( eventName: BackPressEventName, handler: BackPressHandler, - ) => BackHandlerSubscription, + ) => {remove: () => void, ...}, /** - * Takes the Android back gesture until `remove()` is called. Stack claims - * for overlays (modal, sheet, JS chrome): the last remaining owner keeps - * the swipe. Releasing the last claim returns it to screens / the system. + * Android only. When true, React Native consumes the back gesture so + * BackHandler can pop an in-app screen. On Android 16+, progress is + * delivered to PredictiveBackAnimatedView and native PredictiveBackHandler + * plugins. When false, the system predictive-back animation can run; + * BackHandler still observes app-exit commit. * - * `PredictiveBackAnimatedView` only receives progress while some owner - * (a claim, setInterceptEnabled, or a native handler) is consuming. - * - * @platform android - */ - readonly claimPredictiveBack: () => BackHandlerSubscription, - /** - * Android only. Process-wide consume bit. Prefer `claimPredictiveBack` for - * something with a lifetime. When true, React Native consumes the back - * gesture so BackHandler can pop an in-app screen. On Android 16+, progress - * is delivered to PredictiveBackAnimatedView and native PredictiveBackHandler - * plugins. When false and nothing else owns the swipe, the system - * predictive-back animation can run; BackHandler still observes app-exit - * commit. + * Consuming is not reserving: React Native registers at the platform + * default priority, the same one AndroidX' FragmentManager uses, so the + * gesture goes to whichever enabled callback registered last. A library + * that needs the gesture for itself takes it by disabling React Native's + * consuming callback. */ readonly setInterceptEnabled: (enabled: boolean) => void, }; @@ -99,26 +79,11 @@ const BackHandler: TBackHandler = { }, setInterceptEnabled: function (enabled: boolean): void { - _interceptEnabled = enabled; - syncNativeConsume(); - }, + if (!NativeDeviceEventManager) { + return; + } - claimPredictiveBack: function (): BackHandlerSubscription { - const id = _nextClaimId++; - _activeClaims.add(id); - syncNativeConsume(); - let removed = false; - return { - remove: (): void => { - if (removed) { - return; - } - removed = true; - if (_activeClaims.delete(id)) { - syncNativeConsume(); - } - }, - }; + NativeDeviceEventManager.setInterceptEnabled(enabled); }, /** diff --git a/packages/react-native/Libraries/Utilities/BackHandler.ios.js b/packages/react-native/Libraries/Utilities/BackHandler.ios.js index a79cedc96a64..6c3c19cd24f9 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.ios.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.ios.js @@ -21,7 +21,6 @@ type TBackHandler = { eventName: BackPressEventName, handler: BackPressHandler, ): {remove: () => void, ...}, - claimPredictiveBack(): {remove: () => void, ...}, setInterceptEnabled(enabled: boolean): void, }; @@ -32,11 +31,6 @@ const BackHandler: TBackHandler = { remove: emptyFunction, }; }, - claimPredictiveBack() { - return { - remove: emptyFunction, - }; - }, setInterceptEnabled(_enabled: boolean): void {}, }; diff --git a/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js b/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js index 9df211468047..0523898fd782 100644 --- a/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js +++ b/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js @@ -20,10 +20,6 @@ const _backPressSubscriptions = new Set< const BackHandler = { exitApp: jest.fn() as () => void, setInterceptEnabled: jest.fn() as (enabled: boolean) => void, - claimPredictiveBack: jest.fn(() => ({remove: jest.fn()})) as () => { - remove: () => void, - ... - }, addEventListener: function ( eventName: BackPressEventName, diff --git a/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js b/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js index 9a59c7c641ca..2dfec3786236 100644 --- a/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js +++ b/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js @@ -127,13 +127,6 @@ describe('BackHandler', () => { } }); - it('claimPredictiveBack returns an idempotent subscription', () => { - const sub = BackHandler.claimPredictiveBack(); - expect(typeof sub.remove).toBe('function'); - sub.remove(); - sub.remove(); - }); - it('removes handler on subscription.remove()', () => { let called = false; const handler = (_event: HardwareBackPressEventType) => { diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index e7445c019769..62910552d8c6 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -73,12 +73,6 @@ public final class com/facebook/react/PredictiveBackEvent { public fun (FIFF)V } -public final class com/facebook/react/PredictiveBackClaim : java/lang/AutoCloseable { - public fun close ()V - public fun isReleased ()Z - public fun release ()V -} - public abstract interface class com/facebook/react/PredictiveBackHandler { public abstract fun onPredictiveBackCancelled ()V public abstract fun onPredictiveBackCommitted ()Z @@ -94,7 +88,6 @@ public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/ protected fun ()V public fun addPredictiveBackHandler (Lcom/facebook/react/PredictiveBackHandler;)V public fun addPredictiveBackProgressListener (Lcom/facebook/react/PredictiveBackProgressListener;)V - public fun claimPredictiveBack ()Lcom/facebook/react/PredictiveBackClaim; protected fun createReactActivityDelegate ()Lcom/facebook/react/ReactActivityDelegate; public fun getBackPressedCallback ()Landroidx/activity/OnBackPressedCallback; protected fun getMainComponentName ()Ljava/lang/String; @@ -103,7 +96,6 @@ public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/ protected fun getReactHost ()Lcom/facebook/react/ReactHost; protected final fun getReactInstanceManager ()Lcom/facebook/react/ReactInstanceManager; protected final fun getReactNativeHost ()Lcom/facebook/react/ReactNativeHost; - public fun hasPredictiveBackOwner ()Z public fun invokeDefaultOnBackPressed ()V protected final fun loadApp (Ljava/lang/String;)V public fun onActivityResult (IILandroid/content/Intent;)V diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackClaim.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackClaim.java deleted file mode 100644 index f3ee061d8087..000000000000 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/PredictiveBackClaim.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -package com.facebook.react; - -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * A token that owns the Android back gesture until {@link #release()} (or {@link #close()}). - * - *

Use this for something that is not a stack-slide pop: a modal, form sheet, bottom sheet, or - * custom JS chrome. While any claim is held, React Native consumes the swipe and - * FragmentManager does not seek a stack transition. Releasing the last claim returns the gesture - * to the next owner (another claim, a {@link PredictiveBackHandler}, {@code setInterceptEnabled}, - * or screens / the system). - * - * @see ReactActivity#claimPredictiveBack() - */ -public final class PredictiveBackClaim implements AutoCloseable { - - private final ReactActivity mActivity; - private final AtomicBoolean mReleased = new AtomicBoolean(false); - - PredictiveBackClaim(ReactActivity activity) { - mActivity = activity; - } - - public boolean isReleased() { - return mReleased.get(); - } - - public void release() { - if (mReleased.compareAndSet(false, true)) { - mActivity.releasePredictiveBackClaim(this); - } - } - - @Override - public void close() { - release(); - } -} diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java index bd309dc39152..d883b6634883 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java @@ -28,9 +28,7 @@ import com.facebook.react.modules.core.PermissionListener; import com.facebook.react.util.AndroidVersion; import java.util.List; -import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CopyOnWriteArraySet; import org.jetbrains.annotations.NotNull; /** Base Activity for React Native applications. */ @@ -52,10 +50,11 @@ public abstract class ReactActivity extends AppCompatActivity // goes through InAppPredictiveBack instead (see updateConsumeCallback), which keeps this // callback disabled while it is active. // - // A navigation library that wants to own the swipe (react-native-screens, so that - // FragmentManager can animate it) takes it either through claimPredictiveBack / - // addPredictiveBackHandler / setInterceptEnabled, or by disabling this callback via - // getBackPressedCallback(). + // Claiming is not reserved: React Native registers at the platform default priority, the same + // one FragmentManager uses, so the gesture goes to whichever enabled callback registered last. + // A navigation library that wants it for itself (react-native-screens, so that FragmentManager + // can animate a transition) takes it through setInterceptEnabled / addPredictiveBackHandler, or + // by disabling this callback via getBackPressedCallback(). private final OnBackPressedCallback mBackPressedCallback = new OnBackPressedCallback(true) { @Override @@ -74,7 +73,6 @@ public void handleOnBackPressed() { private @Nullable Object mInAppPredictiveBack; private boolean mJsInterceptEnabled; - private final Set mPredictiveBackClaims = new CopyOnWriteArraySet<>(); private final List mPredictiveBackHandlers = new CopyOnWriteArrayList<>(); private final List mPredictiveBackProgressListeners = new CopyOnWriteArrayList<>(); @@ -180,49 +178,23 @@ void onSystemNavigationBackInvoked() { } /** - * Process-wide consume bit. Prefer {@link #claimPredictiveBack()} for something with a lifetime - * (modal, sheet, JS chrome): a claim releases itself, this flag does not. - * - *

When {@code true}, React Native consumes the back gesture so JS {@code BackHandler} can pop - * an in-app screen. On Android 16+ (targetSdk 36) this registers a platform {@link + * When {@code true}, React Native consumes the back gesture so JS {@code BackHandler} can pop an + * in-app screen. On Android 16+ (targetSdk 36) this registers a platform {@link * OnBackAnimationCallback} that delivers progress to {@link PredictiveBackHandler} and {@link * PredictiveBackProgressListener} (used by {@code PredictiveBackAnimatedView}). When {@code - * false} and nothing else owns the swipe, the system or FragmentManager can run predictive back. + * false} and no native handler is registered, the system predictive-back animation can run. + * + *

Consuming does not reserve the gesture. The in-app callback is registered at {@code + * PRIORITY_DEFAULT}, the same priority AndroidX' FragmentManager uses, so whichever was + * registered last enabled receives the swipe. A library that needs the gesture for itself (for + * example react-native-screens, so FragmentManager can seek a transition) takes it by disabling + * this activity's consuming callback -- see {@link #getBackPressedCallback()}. */ public void setInterceptEnabled(boolean enabled) { mJsInterceptEnabled = enabled; updateConsumeCallback(); } - /** - * Takes the back gesture until the returned token is released. Stack this for overlays: the last - * remaining owner keeps the swipe, and releasing the last claim returns it to screens / the - * system. - * - *

On Android 16+ the in-app callback is registered at {@code PRIORITY_OVERLAY} so it stays - * above FragmentManager after a later fragment transaction. - */ - public PredictiveBackClaim claimPredictiveBack() { - PredictiveBackClaim claim = new PredictiveBackClaim(this); - mPredictiveBackClaims.add(claim); - updateConsumeCallback(); - return claim; - } - - /** - * {@code true} while JS intercept, a {@link PredictiveBackClaim}, or a {@link - * PredictiveBackHandler} wants the swipe. - */ - public boolean hasPredictiveBackOwner() { - return shouldConsumeBack(); - } - - void releasePredictiveBackClaim(PredictiveBackClaim claim) { - if (mPredictiveBackClaims.remove(claim)) { - updateConsumeCallback(); - } - } - /** * Registers a native plugin (for example react-native-screens) as an owner of the back gesture. * While any handler is registered, React Native consumes the gesture. If a handler returns {@code @@ -255,14 +227,8 @@ public void removePredictiveBackProgressListener(PredictiveBackProgressListener mPredictiveBackProgressListeners.remove(listener); } - private boolean shouldConsumeBack() { - return mJsInterceptEnabled - || !mPredictiveBackClaims.isEmpty() - || !mPredictiveBackHandlers.isEmpty(); - } - private void updateConsumeCallback() { - boolean consume = shouldConsumeBack(); + boolean consume = mJsInterceptEnabled || !mPredictiveBackHandlers.isEmpty(); if (!AndroidVersion.isAtLeastTargetSdk36(this)) { mBackPressedCallback.setEnabled(consume); return; @@ -443,19 +409,11 @@ protected final void loadApp(String appKey) { @RequiresApi(34) private static final class InAppPredictiveBack { - // android.window.OnBackInvokedDispatcher.PRIORITY_OVERLAY (API 33). - // Inlined because this codebase is also compiled against older SDKs. - private static final int PRIORITY_OVERLAY = 1000000; - - @SuppressLint("WrongConstant") static Object register(ReactActivity activity) { Callback callback = new Callback(activity); - // OVERLAY, not DEFAULT: FragmentManager registers its seek callback lazily on a - // later transaction. Same-priority last-registered-wins would hand the swipe back - // to the stack after the next Push, even while a modal / JS claim is still held. activity .getOnBackInvokedDispatcher() - .registerOnBackInvokedCallback(PRIORITY_OVERLAY, callback); + .registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT, callback); return callback; } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt index b2ffc8ddd616..f70f8ca8676f 100644 --- a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityBackPressedCallbackTest.kt @@ -80,71 +80,6 @@ class ReactActivityBackPressedCallbackTest { assertThat(activity.backPressedCallback.isEnabled).isFalse() } - @Test - fun claimPredictiveBack_enablesCallbackWhenInterceptDisabled() { - val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() - activity.setInterceptEnabled(false) - - val claim = activity.claimPredictiveBack() - - assertThat(activity.backPressedCallback.isEnabled).isTrue() - assertThat(activity.hasPredictiveBackOwner()).isTrue() - assertThat(claim.isReleased).isFalse() - } - - @Test - fun releasePredictiveBack_disablesCallbackWhenNoOtherOwner() { - val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() - activity.setInterceptEnabled(false) - val claim = activity.claimPredictiveBack() - - claim.release() - - assertThat(activity.backPressedCallback.isEnabled).isFalse() - assertThat(activity.hasPredictiveBackOwner()).isFalse() - assertThat(claim.isReleased).isTrue() - } - - @Test - fun releasePredictiveBack_isIdempotent() { - val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() - activity.setInterceptEnabled(false) - val claim = activity.claimPredictiveBack() - - claim.release() - claim.release() - - assertThat(activity.backPressedCallback.isEnabled).isFalse() - } - - @Test - fun claimPredictiveBack_keepsEnabledUntilLastClaimReleased() { - val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() - activity.setInterceptEnabled(false) - val first = activity.claimPredictiveBack() - val second = activity.claimPredictiveBack() - - first.release() - - assertThat(activity.backPressedCallback.isEnabled).isTrue() - assertThat(activity.hasPredictiveBackOwner()).isTrue() - - second.release() - - assertThat(activity.backPressedCallback.isEnabled).isFalse() - } - - @Test - fun setInterceptEnabled_false_keepsEnabledWhileClaimHeld() { - val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() - activity.setInterceptEnabled(false) - activity.claimPredictiveBack() - - activity.setInterceptEnabled(false) - - assertThat(activity.backPressedCallback.isEnabled).isTrue() - } - @Test fun addPredictiveBackHandler_enablesCallbackWhenInterceptDisabled() { val activity = Robolectric.buildActivity(TestReactActivity::class.java).get() diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index b74f57a83fdb..e3f115d99470 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<<7f8ec26edc933e54103980360736ab9f>> * * This file was generated by scripts/js-api/build-types/index.js. */ @@ -4873,9 +4873,6 @@ declare type TBackHandler = { ): { remove: () => void } - claimPredictiveBack(): { - remove: () => void - } exitApp(): void setInterceptEnabled(enabled: boolean): void } @@ -5965,8 +5962,8 @@ export { PlatformSelectSpec, // 09ed7758 PointValue, // 69db075f PointerEvent, // a506d9d7 - PredictiveBackAnimatedView, // b7897c30 - PredictiveBackAnimatedViewProps, // 9d8f7fe6 + PredictiveBackAnimatedView, // ffd6bac0 + PredictiveBackAnimatedViewProps, // c4ca480e PredictiveBackNativeEvent, // a7e9dafb PressabilityConfig, // 0fd655fe PressabilityEventHandlers, // be359ba3 diff --git a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts index 244049879efc..4a60fe48d944 100644 --- a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts +++ b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts @@ -39,21 +39,15 @@ export interface BackHandlerStatic { handler: (event: HardwareBackPressEvent) => boolean | null | undefined, ): NativeEventSubscription; /** - * Takes the Android back gesture until `remove()` is called. Use this for a - * modal, sheet, or other overlay so the swipe is yours until dismiss. - * Releasing the last claim returns the gesture to screens / the system. + * Android only. When true, React Native consumes the back gesture so + * BackHandler can pop an in-app screen. On Android 16+, progress is + * delivered to PredictiveBackAnimatedView and native PredictiveBackHandler + * plugins. When false, the system predictive-back animation can run; + * BackHandler still observes app-exit commit. * - * @platform android - */ - claimPredictiveBack(): NativeEventSubscription; - /** - * Android only. Process-wide consume bit. Prefer `claimPredictiveBack` for - * something with a lifetime. When true, React Native consumes the back - * gesture so BackHandler can pop an in-app screen. On Android 16+, progress - * is delivered to PredictiveBackAnimatedView and native PredictiveBackHandler - * plugins. When false and nothing else owns the swipe, the system - * predictive-back animation can run; BackHandler still observes app-exit - * commit. + * Consuming is not reserving: React Native registers at the platform + * default priority, the same one AndroidX' FragmentManager uses, so the + * gesture goes to whichever enabled callback registered last. */ setInterceptEnabled(enabled: boolean): void; } From 651de61827a5115b34143499b3c820ae694110e8 Mon Sep 17 00:00:00 2001 From: Grzegorz Kruk Date: Wed, 21 Oct 2026 11:42:09 +0200 Subject: [PATCH 09/11] Add predictive back gesture support RCP Summary: - Introduced a RCP file detailing the predictive back gesture support in React Native applications. Changelog: [GENERAL][ADDED] - RCP for predictive back gesture support in React Native. --- docs/RCP-predictive-back.md | 261 ++++++++++++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 docs/RCP-predictive-back.md diff --git a/docs/RCP-predictive-back.md b/docs/RCP-predictive-back.md new file mode 100644 index 000000000000..cc5bdb417760 --- /dev/null +++ b/docs/RCP-predictive-back.md @@ -0,0 +1,261 @@ +# RCP: Predictive back gesture support in React Native applications + +## Proposal + +### What is predictive back? + +On Android, users go back by swiping from the left or right edge of the screen, or by pressing the back button. With **predictive back**, Android shows where back will lead _while the finger is still on the screen_. The current screen shrinks and slides, and the previous screen, or the home screen, shows up behind it. If the user lets go, back happens. If they swipe back the other way, it's cancelled and nothing changes. + +Android can only show that preview if it knows ahead of time what back will do. That's the core change: Android used to ask the app _after_ the back press; now the app has to say _before_ the gesture starts whether it wants to handle back. + +### How apps tell Android "I want back" + +Each Android screen (an _activity_) has a list of **back callbacks**. A callback is a piece of code that says "if back happens, call me". Each one is either on (enabled) or off. + +- **If any callback is on**, Android hands back to the app. The app does what it wants, for example closing a dialog or going to the previous tab. Android doesn't show its own animation, because it doesn't know what the app will do. +- **If all callbacks are off**, Android handles back itself. It plays its animation and closes the screen, or goes to the home screen. +- **If several callbacks are on**, the one turned on last wins. Any library or native screen can take back by turning its callback on later. + +### How Android rolled this out + +| Android version | What changed | +| --- | --- | +| Android 13 (API 33) | Predictive back added. Apps had to opt in with `android:enableOnBackInvokedCallback="true"`. The back-to-home animation was hidden behind a developer setting. | +| Android 14 (API 34) | Apps can animate their own screens during the swipe, because they get the gesture progress from 0 to 1 (`OnBackAnimationCallback`). System animations were still behind the developer setting. | +| Android 15 (API 35) | Opted-in apps get system animations without the developer setting: back to home, back to the previous activity, back to another app. | +| Android 16 (API 36) | For apps that **target** Android 16 (`targetSdk 36`), it's on by default. The old ways of hearing back, `onBackPressed()` and the `KEYCODE_BACK` key event, are no longer called. Apps can still opt out with `android:enableOnBackInvokedCallback="false"`, but Google calls this temporary. Android 16 also adds an "observer" callback type (`PRIORITY_SYSTEM_NAVIGATION_OBSERVER`) that can watch back without blocking the animation. | +| Android 17 (API 37) | Nothing new for predictive back. Google hasn't said when the opt-out will be removed. | + +The _targetSdk_ is the Android version an app says it was built and tested for. Google Play raises the minimum targetSdk every year, so every React Native app will reach targetSdk 36 soon. + +Sources: [Android 16 behaviour changes](https://developer.android.com/about/versions/16/behavior-changes-16), [Add support for the predictive back gesture](https://developer.android.com/guide/navigation/custom-back/predictive-back-gesture), [`OnBackInvokedDispatcher`](https://developer.android.com/reference/android/window/OnBackInvokedDispatcher). + +### What React Native needs + +React Native should work with Android's model instead of against it: take back only when the app has something to go back to, and otherwise let Android handle it and play its animation. + +### What we plan to change + +**1. React Native stops taking back by default (Android 16+, targetSdk 36+).** + +- **What:** the back callback in `ReactActivity` starts **off** instead of on. +- **Why:** with no callback on, Android plays its animation. Leaving a React Native screen looks the same as leaving a native one, with no work for the app developer. +- **Effect:** by default, back closes the React Native screen with the system animation. `BackHandler` listeners are not called, unless code opts in (point 2). + +**2. A new JS switch: `BackHandler.setInterceptEnabled(enabled)`.** + +- **What:** JS calls `setInterceptEnabled(true)` when the current screen has something to go back to inside JS. Examples: a pushed JS screen, an open modal, an unsaved form. It calls `setInterceptEnabled(false)` when there's nothing left to go back to. +- **Why:** this is how Android wants it, with the decision made before the gesture. Navigation libraries already know this; React Navigation knows `canGoBack`. +- **Effect while on:** React Native's callback is on, Android gives back to React Native, and `BackHandler` listeners run as they do today, including `return true` to block. +- **Effect while off:** Android handles back and plays its animation. +- **Important:** this is a **request, not a guarantee**. Native code turned on later can still take back. For example, react-native-screens might let its native navigation handle back, or a brownfield app might show a native screen on top. JS also can't ask Android "do I still own back?". + +**3. A native getter: `ReactActivity.getBackPressedCallback()`.** + +- **What:** native code can get React Native's back callback and turn it on or off. +- **Why:** native libraries such as react-native-screens, and brownfield apps (existing native apps that embed React Native screens), sometimes need to decide who handles back. Today they can't reach React Native's callback, so they have to work around it. +- **Effect:** a small public API for native code. Nothing changes for JS. + +**4. Bug fix: don't close the screen twice.** + +- **What:** `invokeDefaultOnBackPressed()` now does nothing if the activity is already closing. +- **Why:** when back reaches React Native and no JS listener handles it, React Native closes the activity. In some cases that ran twice. +- **Effect:** no API change. + +**5. Optional, may be a follow-up: a "back happened" notification.** + +- **What:** React Native could register an Android 16 observer callback and send JS a new event, for example `backCommitted`, so apps can log back or clean up. +- **Why it must be a new event and not `hardwareBackPress`:** the observer runs _after_ Android has already acted, often after the screen is gone. JS can't block it, so returning `true` would mean nothing. In our tests, a JS listener popped its screen stack while the whole screen was already closing. +- **Limits:** Android 16+ only. On Android 16, only one observer can be registered per window. It gets no gesture progress. + +### What stays out of React Native core + +- **Animations driven by the gesture**, such as a progress value from 0 to 1 sent to JS, an animated view that follows the finger, or in-app back animations. We built these in a prototype branch, and they worked in a plain `ReactActivity`. They didn't work inside React Native fragments used by brownfield apps, they used their own rule for "far enough to go back", and they added a lot of API. +- These belong in community packages, for example react-native-screens through Android's fragment navigation, or animation libraries. React Native core gives the basic switch and stays thin. + +## Summary + +Make the Android predictive back animation work by default in React Native apps. On Android 16+ with targetSdk 36+, React Native stops taking back unless it's asked to. Code that needs to handle back opts in with `BackHandler.setInterceptEnabled(true)`. + +This reduces the scope and guarantees of `BackHandler` on Android. It still works the same way when on, but it's off by default, and native code can override it. + +## Basic example + +A JS screen with its own back stack: + +```js +import {useEffect} from 'react'; +import {BackHandler} from 'react-native'; + +function useAndroidBack(canGoBack, goBack) { + useEffect(() => { + // Ask for back only while there is something to go back to. + BackHandler.setInterceptEnabled(canGoBack); + const subscription = BackHandler.addEventListener('hardwareBackPress', () => { + goBack(); + return true; + }); + return () => { + subscription.remove(); + BackHandler.setInterceptEnabled(false); + }; + }, [canGoBack, goBack]); +} +``` + +A native library or brownfield host taking back from React Native: + +```kotlin +reactActivity.backPressedCallback.isEnabled = false +``` + +## Motivation + +### Current state + +React Native's JS API for back is `BackHandler`. A listener returns `true` to say "I handled back, do nothing else" or `false` to say "not me, do the default". That model needs React Native to hear _every_ back press first, and decide only afterwards whether to keep it. + +On targetSdk 36, Android no longer calls `onBackPressed()`, so React Native would stop hearing back at all. To keep `BackHandler` working, [#51096](https://github.com/facebook/react-native/pull/51096) added a back callback to `ReactActivity` that is **always on**. [#54958](https://github.com/facebook/react-native/pull/54958) later fixed re-enabling it after the default back action. + +This keeps `BackHandler` working, but no React Native screen ever gets the system animation. React Native apps are quietly opted out of predictive back, while native apps get it. Users see the difference, and app developers can't fix it without fighting React Native. + +### Integration with native navigation + +react-native-screens uses Android fragments for native navigation, and wants Android's fragment system to handle back so it can animate screen transitions. Today it has to compete with `ReactActivity`'s always-on callback. + +### Brownfield apps + +In brownfield apps, React Native is one part of a bigger native app. We tested this with a demo app built on [react-native-brownfield](https://github.com/callstack/react-native-brownfield), with the path _native screen → React Native screen → native screen with an embedded React Native fragment_. We found: + +- **Back callbacks are per activity, and the last one turned on wins.** When a native fragment or native screen on top turns on its own callback, it takes back from React Native. `BackHandler` stops getting back, and JS isn't told. +- **The library that hosts React Native can block the animation too.** Core's `ReactFragment` registers no callback; the host has to call `onBackPressed()` itself. react-native-brownfield's fragment adds its own always-on callback, so the system animation never plays on that screen. +- **`BackHandler` listeners are shared by every React Native screen on the same JS runtime.** A back press meant for the embedded fragment also popped the React Native screen hidden behind it. +- **The pattern that works:** the native host owns back. It animates with the androidx activity 1.8 progress callbacks, then passes the final back press to the React Native fragment. + +The research write-ups are in the `rn-predictive-back-brownfield` repo, under `research/01-brownfield-demo.html` and `research/02-rn-branch-in-brownfield.html`. + +### The question: integrate, or be the only one? + +Should React Native on Android integrate with native back handling, or assume it's the only one handling back? This proposal says **integrate**. React Native should behave like any well-behaved Android component: take back only when it has something to go back to, and let others take it otherwise. + +### Expected benefits + +- The system animation works by default in every React Native app. +- Native navigation libraries and brownfield hosts can own back without hacks. +- React Native's back handling matches Android's model, so Android docs and patterns apply. + +## Design + +### `ReactActivity` + +- On targetSdk 36+, `ReactActivity` still registers `mBackPressedCallback` on the activity's `OnBackPressedDispatcher`, but creates it **disabled**. +- When the callback is on and back happens, it runs the old path: `ReactActivityDelegate.onBackPressed()`, then the `hardwareBackPress` JS event. If no listener returns `true`, it calls `invokeDefaultOnBackPressed()`. +- `invokeDefaultOnBackPressed()` returns early if `isFinishing()`. Otherwise it turns the callback off, runs the default back action, and turns the callback back on. +- New public method `getBackPressedCallback()` returns `mBackPressedCallback`. + +### JS API + +- `BackHandler.setInterceptEnabled(enabled: boolean): void` is a new method. It's a no-op on iOS. +- It calls `NativeDeviceEventManager.setInterceptEnabled(enabled)`. On Android, `DeviceEventManagerModule` turns the `ReactActivity` callback on or off. +- `addEventListener('hardwareBackPress', …)` doesn't change. Listeners only run while interception is on, or on older Android versions that still call `onBackPressed()`. + +### Which activity the call reaches + +In our prototype, the native module acts on `currentActivity`, the activity in front. In brownfield apps that's often a native activity. A call from a hidden React Native screen is then dropped, and that screen's activity keeps its old value. In our test, a React Native screen kept blocking back while JS believed it had let go. Options: + +- **A.** Store the requested value per React Native surface or per `ReactHost`, and apply it when a `ReactActivity` resumes. +- **B.** Pass the root tag of the calling surface, so native code can find the right activity. +- **C.** Keep `currentActivity`, and document that the call targets the React Native activity in front and must be repeated when a screen gets focus. + +We recommend A or B; C is the minimum. + +### Fragments and brownfield + +- Core adds no callback to `ReactFragment`. The host app owns back and passes the final back press to the fragment with `ReactFragment.onBackPressed()` (or `ReactDelegate.onBackPressed()`). +- A small host-facing API is an open question: for example, a way for the host to ask "does JS want back right now?". +- react-native-brownfield should expose or turn off its fragment callback. That's a change in that library, not in core. + +### Optional observer event + +- On API 36+, register one `OnBackInvokedCallback` at `PRIORITY_SYSTEM_NAVIGATION_OBSERVER`. It's called only when no other callback took back. +- Send a new JS event, for example `backCommitted`, that can't be cancelled. Never send `hardwareBackPress` from it. +- On Android 16, only one observer is allowed per window, so the host app can't register its own. This needs a decision before shipping. + +### Not in core + +- Gesture progress events, `PredictiveBackAnimatedView`, React Native's own in-app back animation, and native progress listener APIs. +- If core ever sends progress, it should use the androidx activity 1.8 callbacks (`handleOnBackStarted/Progressed/Cancelled`) on the same `OnBackPressedCallback`, not a second platform callback. + +## Drawbacks + +- **Breaking change on Android 16+ with targetSdk 36.** Code that blocks back with `BackHandler` stops getting back until it calls `setInterceptEnabled(true)`. Examples: JS-only navigators, modals, forms with unsaved changes, "press back twice to exit". +- **No ownership guarantee.** Native code turned on later wins. JS can't ask whether it still owns back, so a screen may think it blocks back when it doesn't. +- **Libraries must update.** React Navigation's JS stack, modals and drawers need to call `setInterceptEnabled(canGoBack)`. Until they do, back in those apps closes the screen instead of going back inside JS. +- **Different behaviour across Android versions.** Older Android versions still call `onBackPressed()`, so `BackHandler` keeps working there without opting in. Developers might test only on one version. + +## Alternatives + +**1. Keep today's always-on callback.** +`BackHandler` keeps working, but React Native apps never get the system animation. When Google removes the manifest opt-out, React Native will still block the animation, and React Native apps will stay behind native ones. + +**2. Use the observer only, never block.** +React Native would never turn on a callback. It would only watch with `PRIORITY_SYSTEM_NAVIGATION_OBSERVER` and report back to JS. Problems: + +- JS loses the power to prevent the default. Today a listener can return `true` to keep the user on the screen; with an observer, Android has already acted. +- It's called after the fact, often after the activity has closed. In our test, a JS listener popped its stack on a screen that was already going away. +- It works only on Android 16+, and only one observer is allowed per window on Android 16. +- It gets no gesture progress. + +It's good as an extra notification (point 5), but it can't replace `BackHandler`. Apps that need to block back still have to declare it ahead of time, which is Android's model. + +**3. Turn the callback on automatically while `hardwareBackPress` listeners exist.** +React Navigation and analytics libraries always add listeners, so back would be blocked in almost every app, the same as today. + +**4. Tell developers to use the manifest opt-out.** +Google calls it temporary, and it turns all predictive back animations off. + +**5. Full predictive back support in core.** +We built this in a prototype: gesture progress events, `PredictiveBackAnimatedView`, and React Native's own in-app back animation. It worked in a plain `ReactActivity`. It didn't work in React Native fragments, it chose the activity to listen to only once, used its own "far enough to go back" rule, and added a lot of public API. Community packages are a better home. + +**6. A claim or proxy API, or using `PRIORITY_OVERLAY`.** +React Native would try to always win against other callbacks. This works against Android's model, breaks native navigation libraries and brownfield hosts, and was rejected. + +## Prior-Art + +- **Android's own model.** `OnBackPressedCallback.isEnabled` means "I will handle back", and it's set ahead of time. This proposal maps `setInterceptEnabled` directly onto it. +- **Jetpack Compose.** `BackHandler(enabled = …)` is the same switch: back is handled only while `enabled` is true. +- **Flutter.** For Android predictive back, Flutter deprecated `WillPopScope`, where a widget decided after the back press whether to allow it. Its replacement is `PopScope(canPop: …)`, where the widget declares ahead of time. That's the same move this proposal makes for `BackHandler`. + +## After Review + +### Adoption strategy + +- **Rollout:** ship the new default behind a feature flag for one release, then make it the default for targetSdk 36+. +- **Breaking change:** yes, for apps on Android 16+ with targetSdk 36 that block back with `BackHandler`. Changelog: `[Android][Breaking]`. +- **Coordinate with:** + - React Navigation and Expo Router: call `setInterceptEnabled(canGoBack)` in JS stacks, modals and drawers. + - react-native-screens: use `getBackPressedCallback()` when native navigation owns back. + - react-native-brownfield: expose or turn off its fragment callback, and document "the host owns back". +- **Migration for app code:** + - If you never block back, there's nothing to do; you get the animation. + - If you do, call `setInterceptEnabled(true)` only while you need back, and turn it off when you're done. + +### How we teach this + +- **Terminology:** "intercept". Interception on means React Native takes back from Android; off means Android handles back and animates. +- **One-line message:** on Android 16+, the system animates back by default. Turn interception on only while your screen has something to go back to. It's a request, not a guarantee. +- **Docs:** + - Update the `BackHandler` page with `setInterceptEnabled`, the Android 16 behaviour, and the example above. + - Add a short brownfield section: the host app owns back and passes it to React Native. + - Add a migration note to the release blog post. +- **For existing developers:** present it as a continuation of `BackHandler`, with one new rule: say ahead of time when you need back. + +### Unresolved questions + +- Do we accept the breaking change of disabling by default, or do we need a softer path? +- How should `setInterceptEnabled` find the right activity? Per surface or per `ReactHost` (option A), a root tag (option B), or "the React Native activity in front" (option C)? +- Should core add the observer event? What should it be called, and how do we handle the one-observer-per-window limit on Android 16? +- Should `ReactDelegate` or `ReactFragment` get a host-facing API, for example "does JS want back?" +- How can JS learn that native code took back from it? +- `BackHandler` listeners are shared by all React Native surfaces on one runtime. Is that in scope, or a separate RFC? +- Needs checking: devices on Android 13–15 with targetSdk 36 should still call `onBackPressed()`, so `BackHandler` would work as today there. We haven't tested this. From a17a6ebc5837c1957d7841c0c0b2edcb32dd86cf Mon Sep 17 00:00:00 2001 From: Martin Glova Date: Mon, 23 Nov 2026 13:32:31 +0100 Subject: [PATCH 10/11] Add enablePredictiveBackAndroid feature flag --- .../featureflags/ReactNativeFeatureFlags.kt | 8 +- .../ReactNativeFeatureFlagsCxxAccessor.kt | 12 +- .../ReactNativeFeatureFlagsCxxInterop.kt | 4 +- .../ReactNativeFeatureFlagsDefaults.kt | 4 +- .../ReactNativeFeatureFlagsLocalAccessor.kt | 13 +- .../ReactNativeFeatureFlagsProvider.kt | 4 +- .../JReactNativeFeatureFlagsCxxInterop.cpp | 16 ++- .../JReactNativeFeatureFlagsCxxInterop.h | 5 +- .../featureflags/ReactNativeFeatureFlags.cpp | 6 +- .../featureflags/ReactNativeFeatureFlags.h | 7 +- .../ReactNativeFeatureFlagsAccessor.cpp | 120 ++++++++++-------- .../ReactNativeFeatureFlagsAccessor.h | 6 +- .../ReactNativeFeatureFlagsDefaults.h | 6 +- .../ReactNativeFeatureFlagsDynamicProvider.h | 11 +- .../ReactNativeFeatureFlagsProvider.h | 3 +- .../NativeReactNativeFeatureFlags.cpp | 7 +- .../NativeReactNativeFeatureFlags.h | 4 +- .../ReactNativeFeatureFlags.config.js | 10 ++ .../featureflags/ReactNativeFeatureFlags.js | 7 +- .../specs/NativeReactNativeFeatureFlags.js | 3 +- 20 files changed, 186 insertions(+), 70 deletions(-) diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlags.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlags.kt index 08e2938b26dd..5ae4ca9fabc5 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlags.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlags.kt @@ -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<<21e82647811131a7eca7a16411479aaa>> */ /** @@ -324,6 +324,12 @@ public object ReactNativeFeatureFlags { @JvmStatic public fun enablePreallocatedPropsDiffOnInsertAndroid(): Boolean = accessor.enablePreallocatedPropsDiffOnInsertAndroid() + /** + * On Android 16+ with targetSdk 36+, ReactActivity creates its back callback disabled so Android can play the predictive back animation. Back reaches JS only while a BackHandler listener asks for it with `intercept: true`. + */ + @JvmStatic + public fun enablePredictiveBackAndroid(): Boolean = accessor.enablePredictiveBackAndroid() + /** * Enables caching text layout artifacts for later reuse */ diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxAccessor.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxAccessor.kt index cf9ed4df14ad..13dfb9861536 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxAccessor.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxAccessor.kt @@ -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<<65a338adec02f003c8942f6c4112b7f9>> */ /** @@ -69,6 +69,7 @@ internal class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAcces private var enableMutationObserverByDefaultCache: Boolean? = null private var enableNativeCSSParsingCache: Boolean? = null private var enablePreallocatedPropsDiffOnInsertAndroidCache: Boolean? = null + private var enablePredictiveBackAndroidCache: Boolean? = null private var enablePreparedTextLayoutCache: Boolean? = null private var enablePropsUpdateReconciliationAndroidCache: Boolean? = null private var enableResizeObserverByDefaultCache: Boolean? = null @@ -561,6 +562,15 @@ internal class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAcces return cached } + override fun enablePredictiveBackAndroid(): Boolean { + var cached = enablePredictiveBackAndroidCache + if (cached == null) { + cached = ReactNativeFeatureFlagsCxxInterop.enablePredictiveBackAndroid() + enablePredictiveBackAndroidCache = cached + } + return cached + } + override fun enablePreparedTextLayout(): Boolean { var cached = enablePreparedTextLayoutCache if (cached == null) { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxInterop.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxInterop.kt index 0131ea2cd43c..580182ae753c 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxInterop.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsCxxInterop.kt @@ -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<<592cd695f98eb82a6d8098926af1be8a>> */ /** @@ -126,6 +126,8 @@ public object ReactNativeFeatureFlagsCxxInterop { @DoNotStrip @JvmStatic public external fun enablePreallocatedPropsDiffOnInsertAndroid(): Boolean + @DoNotStrip @JvmStatic public external fun enablePredictiveBackAndroid(): Boolean + @DoNotStrip @JvmStatic public external fun enablePreparedTextLayout(): Boolean @DoNotStrip @JvmStatic public external fun enablePropsUpdateReconciliationAndroid(): Boolean diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsDefaults.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsDefaults.kt index 1768643e3f64..359150a08c95 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsDefaults.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsDefaults.kt @@ -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<<0c48d40c626fc4618879ba5ca9df77ef>> */ /** @@ -121,6 +121,8 @@ public open class ReactNativeFeatureFlagsDefaults : ReactNativeFeatureFlagsProvi override fun enablePreallocatedPropsDiffOnInsertAndroid(): Boolean = false + override fun enablePredictiveBackAndroid(): Boolean = false + override fun enablePreparedTextLayout(): Boolean = true override fun enablePropsUpdateReconciliationAndroid(): Boolean = false diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsLocalAccessor.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsLocalAccessor.kt index e4bfaf0e7c1d..1218a7475886 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsLocalAccessor.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsLocalAccessor.kt @@ -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<<4d0de8e6c65d709e98e638afb976a665>> + * @generated SignedSource<<1c833938e138144ffd285a8902fae226>> */ /** @@ -73,6 +73,7 @@ internal class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcc private var enableMutationObserverByDefaultCache: Boolean? = null private var enableNativeCSSParsingCache: Boolean? = null private var enablePreallocatedPropsDiffOnInsertAndroidCache: Boolean? = null + private var enablePredictiveBackAndroidCache: Boolean? = null private var enablePreparedTextLayoutCache: Boolean? = null private var enablePropsUpdateReconciliationAndroidCache: Boolean? = null private var enableResizeObserverByDefaultCache: Boolean? = null @@ -614,6 +615,16 @@ internal class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcc return cached } + override fun enablePredictiveBackAndroid(): Boolean { + var cached = enablePredictiveBackAndroidCache + if (cached == null) { + cached = currentProvider.enablePredictiveBackAndroid() + accessedFeatureFlags.add("enablePredictiveBackAndroid") + enablePredictiveBackAndroidCache = cached + } + return cached + } + override fun enablePreparedTextLayout(): Boolean { var cached = enablePreparedTextLayoutCache if (cached == null) { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsProvider.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsProvider.kt index fad3f38bcaf5..7e0779116592 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsProvider.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/internal/featureflags/ReactNativeFeatureFlagsProvider.kt @@ -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<<337c8d0d14616dccbf881c443ffb0519>> + * @generated SignedSource<<3de992716d7405fc1cff2094a41e0b72>> */ /** @@ -121,6 +121,8 @@ public interface ReactNativeFeatureFlagsProvider { @DoNotStrip public fun enablePreallocatedPropsDiffOnInsertAndroid(): Boolean + @DoNotStrip public fun enablePredictiveBackAndroid(): Boolean + @DoNotStrip public fun enablePreparedTextLayout(): Boolean @DoNotStrip public fun enablePropsUpdateReconciliationAndroid(): Boolean diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.cpp b/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.cpp index a8963d7f5166..3207a83c6150 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.cpp +++ b/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.cpp @@ -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<<9ef15f2ab900b3afa8d01fcdbf9de178>> + * @generated SignedSource<> */ /** @@ -333,6 +333,12 @@ class ReactNativeFeatureFlagsJavaProvider return method(javaProvider_); } + bool enablePredictiveBackAndroid() override { + static const auto method = + getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enablePredictiveBackAndroid"); + return method(javaProvider_); + } + bool enablePreparedTextLayout() override { static const auto method = getReactNativeFeatureFlagsProviderJavaClass()->getMethod("enablePreparedTextLayout"); @@ -882,6 +888,11 @@ bool JReactNativeFeatureFlagsCxxInterop::enablePreallocatedPropsDiffOnInsertAndr return ReactNativeFeatureFlags::enablePreallocatedPropsDiffOnInsertAndroid(); } +bool JReactNativeFeatureFlagsCxxInterop::enablePredictiveBackAndroid( + facebook::jni::alias_ref /*unused*/) { + return ReactNativeFeatureFlags::enablePredictiveBackAndroid(); +} + bool JReactNativeFeatureFlagsCxxInterop::enablePreparedTextLayout( facebook::jni::alias_ref /*unused*/) { return ReactNativeFeatureFlags::enablePreparedTextLayout(); @@ -1310,6 +1321,9 @@ void JReactNativeFeatureFlagsCxxInterop::registerNatives() { makeNativeMethod( "enablePreallocatedPropsDiffOnInsertAndroid", JReactNativeFeatureFlagsCxxInterop::enablePreallocatedPropsDiffOnInsertAndroid), + makeNativeMethod( + "enablePredictiveBackAndroid", + JReactNativeFeatureFlagsCxxInterop::enablePredictiveBackAndroid), makeNativeMethod( "enablePreparedTextLayout", JReactNativeFeatureFlagsCxxInterop::enablePreparedTextLayout), diff --git a/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.h b/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.h index 9a940f99966a..adf06ba637c0 100644 --- a/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.h +++ b/packages/react-native/ReactAndroid/src/main/jni/react/featureflags/JReactNativeFeatureFlagsCxxInterop.h @@ -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<> */ /** @@ -177,6 +177,9 @@ class JReactNativeFeatureFlagsCxxInterop static bool enablePreallocatedPropsDiffOnInsertAndroid( facebook::jni::alias_ref); + static bool enablePredictiveBackAndroid( + facebook::jni::alias_ref); + static bool enablePreparedTextLayout( facebook::jni::alias_ref); diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.cpp b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.cpp index dfa5f4e26103..ca955c93a591 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.cpp +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.cpp @@ -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<<8fd30d0d29edead0c8d39d9f2107972e>> + * @generated SignedSource<> */ /** @@ -222,6 +222,10 @@ bool ReactNativeFeatureFlags::enablePreallocatedPropsDiffOnInsertAndroid() { return getAccessor().enablePreallocatedPropsDiffOnInsertAndroid(); } +bool ReactNativeFeatureFlags::enablePredictiveBackAndroid() { + return getAccessor().enablePredictiveBackAndroid(); +} + bool ReactNativeFeatureFlags::enablePreparedTextLayout() { return getAccessor().enablePreparedTextLayout(); } diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.h index 4ad1d61ec24b..96583a1399c7 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlags.h @@ -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<> */ /** @@ -286,6 +286,11 @@ class ReactNativeFeatureFlags { */ RN_EXPORT static bool enablePreallocatedPropsDiffOnInsertAndroid(); + /** + * On Android 16+ with targetSdk 36+, ReactActivity creates its back callback disabled so Android can play the predictive back animation. Back reaches JS only while a BackHandler listener asks for it with `intercept: true`. + */ + RN_EXPORT static bool enablePredictiveBackAndroid(); + /** * Enables caching text layout artifacts for later reuse */ diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.cpp b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.cpp index 426c1fed7911..bb4ea55a4edb 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.cpp +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.cpp @@ -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<<7a1914ec8b63b7a09b43547afda3ef3b>> + * @generated SignedSource<<74528f534578d628ead24ee2fbf2b9d0>> */ /** @@ -911,6 +911,24 @@ bool ReactNativeFeatureFlagsAccessor::enablePreallocatedPropsDiffOnInsertAndroid return flagValue.value(); } +bool ReactNativeFeatureFlagsAccessor::enablePredictiveBackAndroid() { + auto flagValue = enablePredictiveBackAndroid_.load(); + + if (!flagValue.has_value()) { + // This block is not exclusive but it is not necessary. + // If multiple threads try to initialize the feature flag, we would only + // be accessing the provider multiple times but the end state of this + // instance and the returned flag value would be the same. + + markFlagAsAccessed(49, "enablePredictiveBackAndroid"); + + flagValue = currentProvider_->enablePredictiveBackAndroid(); + enablePredictiveBackAndroid_ = flagValue; + } + + return flagValue.value(); +} + bool ReactNativeFeatureFlagsAccessor::enablePreparedTextLayout() { auto flagValue = enablePreparedTextLayout_.load(); @@ -920,7 +938,7 @@ bool ReactNativeFeatureFlagsAccessor::enablePreparedTextLayout() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(49, "enablePreparedTextLayout"); + markFlagAsAccessed(50, "enablePreparedTextLayout"); flagValue = currentProvider_->enablePreparedTextLayout(); enablePreparedTextLayout_ = flagValue; @@ -938,7 +956,7 @@ bool ReactNativeFeatureFlagsAccessor::enablePropsUpdateReconciliationAndroid() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(50, "enablePropsUpdateReconciliationAndroid"); + markFlagAsAccessed(51, "enablePropsUpdateReconciliationAndroid"); flagValue = currentProvider_->enablePropsUpdateReconciliationAndroid(); enablePropsUpdateReconciliationAndroid_ = flagValue; @@ -956,7 +974,7 @@ bool ReactNativeFeatureFlagsAccessor::enableResizeObserverByDefault() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(51, "enableResizeObserverByDefault"); + markFlagAsAccessed(52, "enableResizeObserverByDefault"); flagValue = currentProvider_->enableResizeObserverByDefault(); enableResizeObserverByDefault_ = flagValue; @@ -974,7 +992,7 @@ bool ReactNativeFeatureFlagsAccessor::enableSwiftUIBasedFilters() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(52, "enableSwiftUIBasedFilters"); + markFlagAsAccessed(53, "enableSwiftUIBasedFilters"); flagValue = currentProvider_->enableSwiftUIBasedFilters(); enableSwiftUIBasedFilters_ = flagValue; @@ -992,7 +1010,7 @@ bool ReactNativeFeatureFlagsAccessor::enableViewCulling() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(53, "enableViewCulling"); + markFlagAsAccessed(54, "enableViewCulling"); flagValue = currentProvider_->enableViewCulling(); enableViewCulling_ = flagValue; @@ -1010,7 +1028,7 @@ bool ReactNativeFeatureFlagsAccessor::enableViewRecycling() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(54, "enableViewRecycling"); + markFlagAsAccessed(55, "enableViewRecycling"); flagValue = currentProvider_->enableViewRecycling(); enableViewRecycling_ = flagValue; @@ -1028,7 +1046,7 @@ bool ReactNativeFeatureFlagsAccessor::enableViewRecyclingForImage() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(55, "enableViewRecyclingForImage"); + markFlagAsAccessed(56, "enableViewRecyclingForImage"); flagValue = currentProvider_->enableViewRecyclingForImage(); enableViewRecyclingForImage_ = flagValue; @@ -1046,7 +1064,7 @@ bool ReactNativeFeatureFlagsAccessor::enableViewRecyclingForScrollView() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(56, "enableViewRecyclingForScrollView"); + markFlagAsAccessed(57, "enableViewRecyclingForScrollView"); flagValue = currentProvider_->enableViewRecyclingForScrollView(); enableViewRecyclingForScrollView_ = flagValue; @@ -1064,7 +1082,7 @@ bool ReactNativeFeatureFlagsAccessor::enableViewRecyclingForText() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(57, "enableViewRecyclingForText"); + markFlagAsAccessed(58, "enableViewRecyclingForText"); flagValue = currentProvider_->enableViewRecyclingForText(); enableViewRecyclingForText_ = flagValue; @@ -1082,7 +1100,7 @@ bool ReactNativeFeatureFlagsAccessor::enableViewRecyclingForView() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(58, "enableViewRecyclingForView"); + markFlagAsAccessed(59, "enableViewRecyclingForView"); flagValue = currentProvider_->enableViewRecyclingForView(); enableViewRecyclingForView_ = flagValue; @@ -1100,7 +1118,7 @@ bool ReactNativeFeatureFlagsAccessor::enableVirtualViewContainerStateExperimenta // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(59, "enableVirtualViewContainerStateExperimental"); + markFlagAsAccessed(60, "enableVirtualViewContainerStateExperimental"); flagValue = currentProvider_->enableVirtualViewContainerStateExperimental(); enableVirtualViewContainerStateExperimental_ = flagValue; @@ -1118,7 +1136,7 @@ bool ReactNativeFeatureFlagsAccessor::fixBorderlessRippleAndroid() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(60, "fixBorderlessRippleAndroid"); + markFlagAsAccessed(61, "fixBorderlessRippleAndroid"); flagValue = currentProvider_->fixBorderlessRippleAndroid(); fixBorderlessRippleAndroid_ = flagValue; @@ -1136,7 +1154,7 @@ bool ReactNativeFeatureFlagsAccessor::fixMappingOfEventPrioritiesBetweenFabricAn // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(61, "fixMappingOfEventPrioritiesBetweenFabricAndReact"); + markFlagAsAccessed(62, "fixMappingOfEventPrioritiesBetweenFabricAndReact"); flagValue = currentProvider_->fixMappingOfEventPrioritiesBetweenFabricAndReact(); fixMappingOfEventPrioritiesBetweenFabricAndReact_ = flagValue; @@ -1154,7 +1172,7 @@ bool ReactNativeFeatureFlagsAccessor::fixTextInlineViewLineHeight() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(62, "fixTextInlineViewLineHeight"); + markFlagAsAccessed(63, "fixTextInlineViewLineHeight"); flagValue = currentProvider_->fixTextInlineViewLineHeight(); fixTextInlineViewLineHeight_ = flagValue; @@ -1172,7 +1190,7 @@ bool ReactNativeFeatureFlagsAccessor::fixTextLayoutOnPixelDensityChange() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(63, "fixTextLayoutOnPixelDensityChange"); + markFlagAsAccessed(64, "fixTextLayoutOnPixelDensityChange"); flagValue = currentProvider_->fixTextLayoutOnPixelDensityChange(); fixTextLayoutOnPixelDensityChange_ = flagValue; @@ -1190,7 +1208,7 @@ bool ReactNativeFeatureFlagsAccessor::fixYogaFlexBasisFitContentInMainAxis() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(64, "fixYogaFlexBasisFitContentInMainAxis"); + markFlagAsAccessed(65, "fixYogaFlexBasisFitContentInMainAxis"); flagValue = currentProvider_->fixYogaFlexBasisFitContentInMainAxis(); fixYogaFlexBasisFitContentInMainAxis_ = flagValue; @@ -1208,7 +1226,7 @@ bool ReactNativeFeatureFlagsAccessor::fuseboxAssertSingleHostState() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(65, "fuseboxAssertSingleHostState"); + markFlagAsAccessed(66, "fuseboxAssertSingleHostState"); flagValue = currentProvider_->fuseboxAssertSingleHostState(); fuseboxAssertSingleHostState_ = flagValue; @@ -1226,7 +1244,7 @@ bool ReactNativeFeatureFlagsAccessor::fuseboxEnabledRelease() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(66, "fuseboxEnabledRelease"); + markFlagAsAccessed(67, "fuseboxEnabledRelease"); flagValue = currentProvider_->fuseboxEnabledRelease(); fuseboxEnabledRelease_ = flagValue; @@ -1244,7 +1262,7 @@ bool ReactNativeFeatureFlagsAccessor::fuseboxFrameRecordingEnabled() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(67, "fuseboxFrameRecordingEnabled"); + markFlagAsAccessed(68, "fuseboxFrameRecordingEnabled"); flagValue = currentProvider_->fuseboxFrameRecordingEnabled(); fuseboxFrameRecordingEnabled_ = flagValue; @@ -1262,7 +1280,7 @@ bool ReactNativeFeatureFlagsAccessor::fuseboxScreenshotCaptureEnabled() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(68, "fuseboxScreenshotCaptureEnabled"); + markFlagAsAccessed(69, "fuseboxScreenshotCaptureEnabled"); flagValue = currentProvider_->fuseboxScreenshotCaptureEnabled(); fuseboxScreenshotCaptureEnabled_ = flagValue; @@ -1280,7 +1298,7 @@ bool ReactNativeFeatureFlagsAccessor::fuseboxWebSocketEventsEnabled() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(69, "fuseboxWebSocketEventsEnabled"); + markFlagAsAccessed(70, "fuseboxWebSocketEventsEnabled"); flagValue = currentProvider_->fuseboxWebSocketEventsEnabled(); fuseboxWebSocketEventsEnabled_ = flagValue; @@ -1298,7 +1316,7 @@ bool ReactNativeFeatureFlagsAccessor::keepTimersRunningWhileHostPausedAndroid() // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(70, "keepTimersRunningWhileHostPausedAndroid"); + markFlagAsAccessed(71, "keepTimersRunningWhileHostPausedAndroid"); flagValue = currentProvider_->keepTimersRunningWhileHostPausedAndroid(); keepTimersRunningWhileHostPausedAndroid_ = flagValue; @@ -1316,7 +1334,7 @@ bool ReactNativeFeatureFlagsAccessor::optimizedAnimatedPropUpdates() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(71, "optimizedAnimatedPropUpdates"); + markFlagAsAccessed(72, "optimizedAnimatedPropUpdates"); flagValue = currentProvider_->optimizedAnimatedPropUpdates(); optimizedAnimatedPropUpdates_ = flagValue; @@ -1334,7 +1352,7 @@ bool ReactNativeFeatureFlagsAccessor::overrideBySynchronousMountPropsAtMountingA // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(72, "overrideBySynchronousMountPropsAtMountingAndroid"); + markFlagAsAccessed(73, "overrideBySynchronousMountPropsAtMountingAndroid"); flagValue = currentProvider_->overrideBySynchronousMountPropsAtMountingAndroid(); overrideBySynchronousMountPropsAtMountingAndroid_ = flagValue; @@ -1352,7 +1370,7 @@ bool ReactNativeFeatureFlagsAccessor::perfIssuesEnabled() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(73, "perfIssuesEnabled"); + markFlagAsAccessed(74, "perfIssuesEnabled"); flagValue = currentProvider_->perfIssuesEnabled(); perfIssuesEnabled_ = flagValue; @@ -1370,7 +1388,7 @@ bool ReactNativeFeatureFlagsAccessor::perfMonitorV2Enabled() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(74, "perfMonitorV2Enabled"); + markFlagAsAccessed(75, "perfMonitorV2Enabled"); flagValue = currentProvider_->perfMonitorV2Enabled(); perfMonitorV2Enabled_ = flagValue; @@ -1388,7 +1406,7 @@ double ReactNativeFeatureFlagsAccessor::preparedTextCacheSize() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(75, "preparedTextCacheSize"); + markFlagAsAccessed(76, "preparedTextCacheSize"); flagValue = currentProvider_->preparedTextCacheSize(); preparedTextCacheSize_ = flagValue; @@ -1406,7 +1424,7 @@ bool ReactNativeFeatureFlagsAccessor::preventShadowTreeCommitExhaustion() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(76, "preventShadowTreeCommitExhaustion"); + markFlagAsAccessed(77, "preventShadowTreeCommitExhaustion"); flagValue = currentProvider_->preventShadowTreeCommitExhaustion(); preventShadowTreeCommitExhaustion_ = flagValue; @@ -1424,7 +1442,7 @@ bool ReactNativeFeatureFlagsAccessor::redBoxV2Android() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(77, "redBoxV2Android"); + markFlagAsAccessed(78, "redBoxV2Android"); flagValue = currentProvider_->redBoxV2Android(); redBoxV2Android_ = flagValue; @@ -1442,7 +1460,7 @@ bool ReactNativeFeatureFlagsAccessor::redBoxV2IOS() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(78, "redBoxV2IOS"); + markFlagAsAccessed(79, "redBoxV2IOS"); flagValue = currentProvider_->redBoxV2IOS(); redBoxV2IOS_ = flagValue; @@ -1460,7 +1478,7 @@ bool ReactNativeFeatureFlagsAccessor::shouldPressibilityUseW3CPointerEventsForHo // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(79, "shouldPressibilityUseW3CPointerEventsForHover"); + markFlagAsAccessed(80, "shouldPressibilityUseW3CPointerEventsForHover"); flagValue = currentProvider_->shouldPressibilityUseW3CPointerEventsForHover(); shouldPressibilityUseW3CPointerEventsForHover_ = flagValue; @@ -1478,7 +1496,7 @@ bool ReactNativeFeatureFlagsAccessor::shouldTriggerResponderTransferOnScrollAndr // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(80, "shouldTriggerResponderTransferOnScrollAndroid"); + markFlagAsAccessed(81, "shouldTriggerResponderTransferOnScrollAndroid"); flagValue = currentProvider_->shouldTriggerResponderTransferOnScrollAndroid(); shouldTriggerResponderTransferOnScrollAndroid_ = flagValue; @@ -1496,7 +1514,7 @@ bool ReactNativeFeatureFlagsAccessor::skipActivityIdentityAssertionOnHostPause() // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(81, "skipActivityIdentityAssertionOnHostPause"); + markFlagAsAccessed(82, "skipActivityIdentityAssertionOnHostPause"); flagValue = currentProvider_->skipActivityIdentityAssertionOnHostPause(); skipActivityIdentityAssertionOnHostPause_ = flagValue; @@ -1514,7 +1532,7 @@ bool ReactNativeFeatureFlagsAccessor::skipUnchangedChildrenInDifferentiator() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(82, "skipUnchangedChildrenInDifferentiator"); + markFlagAsAccessed(83, "skipUnchangedChildrenInDifferentiator"); flagValue = currentProvider_->skipUnchangedChildrenInDifferentiator(); skipUnchangedChildrenInDifferentiator_ = flagValue; @@ -1532,7 +1550,7 @@ bool ReactNativeFeatureFlagsAccessor::syncAndroidClipBoundsWithOverflow() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(83, "syncAndroidClipBoundsWithOverflow"); + markFlagAsAccessed(84, "syncAndroidClipBoundsWithOverflow"); flagValue = currentProvider_->syncAndroidClipBoundsWithOverflow(); syncAndroidClipBoundsWithOverflow_ = flagValue; @@ -1550,7 +1568,7 @@ bool ReactNativeFeatureFlagsAccessor::traceTurboModulePromiseRejectionsOnAndroid // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(84, "traceTurboModulePromiseRejectionsOnAndroid"); + markFlagAsAccessed(85, "traceTurboModulePromiseRejectionsOnAndroid"); flagValue = currentProvider_->traceTurboModulePromiseRejectionsOnAndroid(); traceTurboModulePromiseRejectionsOnAndroid_ = flagValue; @@ -1568,7 +1586,7 @@ bool ReactNativeFeatureFlagsAccessor::updateRuntimeShadowNodeReferencesOnCommit( // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(85, "updateRuntimeShadowNodeReferencesOnCommit"); + markFlagAsAccessed(86, "updateRuntimeShadowNodeReferencesOnCommit"); flagValue = currentProvider_->updateRuntimeShadowNodeReferencesOnCommit(); updateRuntimeShadowNodeReferencesOnCommit_ = flagValue; @@ -1586,7 +1604,7 @@ bool ReactNativeFeatureFlagsAccessor::updateRuntimeShadowNodeReferencesOnCommitT // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(86, "updateRuntimeShadowNodeReferencesOnCommitThread"); + markFlagAsAccessed(87, "updateRuntimeShadowNodeReferencesOnCommitThread"); flagValue = currentProvider_->updateRuntimeShadowNodeReferencesOnCommitThread(); updateRuntimeShadowNodeReferencesOnCommitThread_ = flagValue; @@ -1604,7 +1622,7 @@ bool ReactNativeFeatureFlagsAccessor::useAlwaysAvailableJSErrorHandling() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(87, "useAlwaysAvailableJSErrorHandling"); + markFlagAsAccessed(88, "useAlwaysAvailableJSErrorHandling"); flagValue = currentProvider_->useAlwaysAvailableJSErrorHandling(); useAlwaysAvailableJSErrorHandling_ = flagValue; @@ -1622,7 +1640,7 @@ bool ReactNativeFeatureFlagsAccessor::useFabricInterop() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(88, "useFabricInterop"); + markFlagAsAccessed(89, "useFabricInterop"); flagValue = currentProvider_->useFabricInterop(); useFabricInterop_ = flagValue; @@ -1640,7 +1658,7 @@ bool ReactNativeFeatureFlagsAccessor::useNativeViewConfigsInBridgelessMode() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(89, "useNativeViewConfigsInBridgelessMode"); + markFlagAsAccessed(90, "useNativeViewConfigsInBridgelessMode"); flagValue = currentProvider_->useNativeViewConfigsInBridgelessMode(); useNativeViewConfigsInBridgelessMode_ = flagValue; @@ -1658,7 +1676,7 @@ bool ReactNativeFeatureFlagsAccessor::useNestedScrollViewAndroid() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(90, "useNestedScrollViewAndroid"); + markFlagAsAccessed(91, "useNestedScrollViewAndroid"); flagValue = currentProvider_->useNestedScrollViewAndroid(); useNestedScrollViewAndroid_ = flagValue; @@ -1676,7 +1694,7 @@ bool ReactNativeFeatureFlagsAccessor::useSharedAnimatedBackend() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(91, "useSharedAnimatedBackend"); + markFlagAsAccessed(92, "useSharedAnimatedBackend"); flagValue = currentProvider_->useSharedAnimatedBackend(); useSharedAnimatedBackend_ = flagValue; @@ -1694,7 +1712,7 @@ bool ReactNativeFeatureFlagsAccessor::useTraitHiddenOnAndroid() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(92, "useTraitHiddenOnAndroid"); + markFlagAsAccessed(93, "useTraitHiddenOnAndroid"); flagValue = currentProvider_->useTraitHiddenOnAndroid(); useTraitHiddenOnAndroid_ = flagValue; @@ -1712,7 +1730,7 @@ bool ReactNativeFeatureFlagsAccessor::useTurboModuleInterop() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(93, "useTurboModuleInterop"); + markFlagAsAccessed(94, "useTurboModuleInterop"); flagValue = currentProvider_->useTurboModuleInterop(); useTurboModuleInterop_ = flagValue; @@ -1730,7 +1748,7 @@ bool ReactNativeFeatureFlagsAccessor::useWindowDensityForDisplayMetricsAndroid() // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(94, "useWindowDensityForDisplayMetricsAndroid"); + markFlagAsAccessed(95, "useWindowDensityForDisplayMetricsAndroid"); flagValue = currentProvider_->useWindowDensityForDisplayMetricsAndroid(); useWindowDensityForDisplayMetricsAndroid_ = flagValue; @@ -1748,7 +1766,7 @@ double ReactNativeFeatureFlagsAccessor::viewCullingOutsetRatio() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(95, "viewCullingOutsetRatio"); + markFlagAsAccessed(96, "viewCullingOutsetRatio"); flagValue = currentProvider_->viewCullingOutsetRatio(); viewCullingOutsetRatio_ = flagValue; @@ -1766,7 +1784,7 @@ bool ReactNativeFeatureFlagsAccessor::viewTransitionEnabled() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(96, "viewTransitionEnabled"); + markFlagAsAccessed(97, "viewTransitionEnabled"); flagValue = currentProvider_->viewTransitionEnabled(); viewTransitionEnabled_ = flagValue; @@ -1784,7 +1802,7 @@ bool ReactNativeFeatureFlagsAccessor::viewTransitionUseHardwareBitmapAndroid() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(97, "viewTransitionUseHardwareBitmapAndroid"); + markFlagAsAccessed(98, "viewTransitionUseHardwareBitmapAndroid"); flagValue = currentProvider_->viewTransitionUseHardwareBitmapAndroid(); viewTransitionUseHardwareBitmapAndroid_ = flagValue; @@ -1802,7 +1820,7 @@ double ReactNativeFeatureFlagsAccessor::virtualViewPrerenderRatio() { // be accessing the provider multiple times but the end state of this // instance and the returned flag value would be the same. - markFlagAsAccessed(98, "virtualViewPrerenderRatio"); + markFlagAsAccessed(99, "virtualViewPrerenderRatio"); flagValue = currentProvider_->virtualViewPrerenderRatio(); virtualViewPrerenderRatio_ = flagValue; diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.h index 52ce44ddcbed..880416ba9ab3 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsAccessor.h @@ -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<<0e427a7632512e804255c89c72233039>> + * @generated SignedSource<<6d01a135e00c9288230fd9be945b59bf>> */ /** @@ -83,6 +83,7 @@ class ReactNativeFeatureFlagsAccessor { bool enableMutationObserverByDefault(); bool enableNativeCSSParsing(); bool enablePreallocatedPropsDiffOnInsertAndroid(); + bool enablePredictiveBackAndroid(); bool enablePreparedTextLayout(); bool enablePropsUpdateReconciliationAndroid(); bool enableResizeObserverByDefault(); @@ -144,7 +145,7 @@ class ReactNativeFeatureFlagsAccessor { std::unique_ptr currentProvider_; bool wasOverridden_; - std::array, 99> accessedFeatureFlags_; + std::array, 100> accessedFeatureFlags_; std::atomic> commonTestFlag_; std::atomic> cdpInteractionMetricsEnabled_; @@ -195,6 +196,7 @@ class ReactNativeFeatureFlagsAccessor { std::atomic> enableMutationObserverByDefault_; std::atomic> enableNativeCSSParsing_; std::atomic> enablePreallocatedPropsDiffOnInsertAndroid_; + std::atomic> enablePredictiveBackAndroid_; std::atomic> enablePreparedTextLayout_; std::atomic> enablePropsUpdateReconciliationAndroid_; std::atomic> enableResizeObserverByDefault_; diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDefaults.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDefaults.h index a2e18990cc91..84616b4c9c0e 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDefaults.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDefaults.h @@ -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<<52caf72cdb257974eeaea08ea3c36801>> */ /** @@ -225,6 +225,10 @@ class ReactNativeFeatureFlagsDefaults : public ReactNativeFeatureFlagsProvider { return false; } + bool enablePredictiveBackAndroid() override { + return false; + } + bool enablePreparedTextLayout() override { return true; } diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDynamicProvider.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDynamicProvider.h index 70ee8eedc407..05f8b93209d0 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDynamicProvider.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsDynamicProvider.h @@ -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<> */ /** @@ -488,6 +488,15 @@ class ReactNativeFeatureFlagsDynamicProvider : public ReactNativeFeatureFlagsDef return ReactNativeFeatureFlagsDefaults::enablePreallocatedPropsDiffOnInsertAndroid(); } + bool enablePredictiveBackAndroid() override { + auto value = values_["enablePredictiveBackAndroid"]; + if (!value.isNull()) { + return value.getBool(); + } + + return ReactNativeFeatureFlagsDefaults::enablePredictiveBackAndroid(); + } + bool enablePreparedTextLayout() override { auto value = values_["enablePreparedTextLayout"]; if (!value.isNull()) { diff --git a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsProvider.h b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsProvider.h index d9a7323c8821..556c5e19a9e6 100644 --- a/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsProvider.h +++ b/packages/react-native/ReactCommon/react/featureflags/ReactNativeFeatureFlagsProvider.h @@ -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<<3d931993120e3615bc89e37388d0b6de>> + * @generated SignedSource<<7ccc5c73152b5730157c5cf6a2e744f9>> */ /** @@ -76,6 +76,7 @@ class ReactNativeFeatureFlagsProvider { virtual bool enableMutationObserverByDefault() = 0; virtual bool enableNativeCSSParsing() = 0; virtual bool enablePreallocatedPropsDiffOnInsertAndroid() = 0; + virtual bool enablePredictiveBackAndroid() = 0; virtual bool enablePreparedTextLayout() = 0; virtual bool enablePropsUpdateReconciliationAndroid() = 0; virtual bool enableResizeObserverByDefault() = 0; diff --git a/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.cpp b/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.cpp index e24394978716..9341f740f6ac 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.cpp +++ b/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.cpp @@ -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<<6087a9831bb088568d33a9a0c032c4a2>> + * @generated SignedSource<> */ /** @@ -289,6 +289,11 @@ bool NativeReactNativeFeatureFlags::enablePreallocatedPropsDiffOnInsertAndroid( return ReactNativeFeatureFlags::enablePreallocatedPropsDiffOnInsertAndroid(); } +bool NativeReactNativeFeatureFlags::enablePredictiveBackAndroid( + jsi::Runtime& /*runtime*/) { + return ReactNativeFeatureFlags::enablePredictiveBackAndroid(); +} + bool NativeReactNativeFeatureFlags::enablePreparedTextLayout( jsi::Runtime& /*runtime*/) { return ReactNativeFeatureFlags::enablePreparedTextLayout(); diff --git a/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.h b/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.h index efcdc1907b20..79fd700fa8eb 100644 --- a/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.h +++ b/packages/react-native/ReactCommon/react/nativemodule/featureflags/NativeReactNativeFeatureFlags.h @@ -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<> */ /** @@ -136,6 +136,8 @@ class NativeReactNativeFeatureFlags bool enablePreallocatedPropsDiffOnInsertAndroid(jsi::Runtime& runtime); + bool enablePredictiveBackAndroid(jsi::Runtime& runtime); + bool enablePreparedTextLayout(jsi::Runtime& runtime); bool enablePropsUpdateReconciliationAndroid(jsi::Runtime& runtime); diff --git a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js index f3e6dcdbef7e..d60883248e55 100644 --- a/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js +++ b/packages/react-native/scripts/featureflags/ReactNativeFeatureFlags.config.js @@ -577,6 +577,16 @@ const definitions: FeatureFlagDefinitions = { }, ossReleaseStage: 'none', }, + enablePredictiveBackAndroid: { + defaultValue: false, + metadata: { + description: + 'On Android 16+ with targetSdk 36+, ReactActivity creates its back callback disabled so Android can play the predictive back animation. Back reaches JS only while a BackHandler listener asks for it with `intercept: true`.', + expectedReleaseValue: true, + purpose: 'release', + }, + ossReleaseStage: 'none', + }, enablePreparedTextLayout: { defaultValue: true, metadata: { diff --git a/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js b/packages/react-native/src/private/featureflags/ReactNativeFeatureFlags.js index f827855b529b..4636176bfc9f 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<<705049f8ca1f9561e4fa3ee993023e85>> + * @generated SignedSource<> * @flow strict * @noformat */ @@ -97,6 +97,7 @@ export type ReactNativeFeatureFlags = Readonly<{ enableMutationObserverByDefault: Getter, enableNativeCSSParsing: Getter, enablePreallocatedPropsDiffOnInsertAndroid: Getter, + enablePredictiveBackAndroid: Getter, enablePreparedTextLayout: Getter, enablePropsUpdateReconciliationAndroid: Getter, enableResizeObserverByDefault: Getter, @@ -414,6 +415,10 @@ export const enableNativeCSSParsing: Getter = createNativeFlagGetter('e * When enabled together with `enableAccumulatedUpdatesInRawPropsAndroid`, the Insert of a preallocated view only sends the difference between the props the view was preallocated with and the inserted props, instead of sending all props again on every Insert. */ export const enablePreallocatedPropsDiffOnInsertAndroid: Getter = createNativeFlagGetter('enablePreallocatedPropsDiffOnInsertAndroid', false); +/** + * On Android 16+ with targetSdk 36+, ReactActivity creates its back callback disabled so Android can play the predictive back animation. Back reaches JS only while a BackHandler listener asks for it with `intercept: true`. + */ +export const enablePredictiveBackAndroid: Getter = createNativeFlagGetter('enablePredictiveBackAndroid', false); /** * Enables caching text layout artifacts for later reuse */ diff --git a/packages/react-native/src/private/featureflags/specs/NativeReactNativeFeatureFlags.js b/packages/react-native/src/private/featureflags/specs/NativeReactNativeFeatureFlags.js index 9ec863a00265..0f74066b2e8b 100644 --- a/packages/react-native/src/private/featureflags/specs/NativeReactNativeFeatureFlags.js +++ b/packages/react-native/src/private/featureflags/specs/NativeReactNativeFeatureFlags.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<<9e5c3896a783839b188cb8c23589df03>> + * @generated SignedSource<<906a5c0d76e55427dbdf0ea6ab57f059>> * @flow strict * @noformat */ @@ -74,6 +74,7 @@ export interface Spec extends TurboModule { readonly enableMutationObserverByDefault?: () => boolean; readonly enableNativeCSSParsing?: () => boolean; readonly enablePreallocatedPropsDiffOnInsertAndroid?: () => boolean; + readonly enablePredictiveBackAndroid?: () => boolean; readonly enablePreparedTextLayout?: () => boolean; readonly enablePropsUpdateReconciliationAndroid?: () => boolean; readonly enableResizeObserverByDefault?: () => boolean; From ad9f95b200ae1e4a5c646a66a405f0f2417bebba Mon Sep 17 00:00:00 2001 From: Martin Glova Date: Mon, 23 Nov 2026 16:41:38 +0100 Subject: [PATCH 11/11] Add intercept option to BackHandler for Android predictive back --- .../Utilities/BackHandler.android.js | 89 ++++++++++- .../Libraries/Utilities/BackHandler.ios.js | 20 ++- .../Libraries/Utilities/BackHandler.js.flow | 28 +++- .../Utilities/__mocks__/BackHandler.js | 10 +- .../Utilities/__tests__/BackHandler-itest.js | 140 ++++++++++++++++++ .../ReactAndroid/api/ReactAndroid.api | 3 + .../com/facebook/react/ReactActivity.java | 37 ++++- .../modules/core/DeviceEventManagerModule.kt | 11 ++ .../com/facebook/react/ReactActivityTest.kt | 87 +++++++++++ packages/react-native/ReactNativeApi.d.ts | 18 ++- packages/react-native/index.js.flow | 6 +- .../modules/NativeDeviceEventManager.js | 1 + .../Libraries/Utilities/BackHandler.d.ts | 27 +++- packages/rn-tester/js/RNTesterAppShared.js | 3 + 14 files changed, 458 insertions(+), 22 deletions(-) create mode 100644 packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityTest.kt diff --git a/packages/react-native/Libraries/Utilities/BackHandler.android.js b/packages/react-native/Libraries/Utilities/BackHandler.android.js index 597f2eacc59a..575a8dbcf95a 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.android.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.android.js @@ -9,6 +9,7 @@ */ import NativeDeviceEventManager from '../../Libraries/NativeModules/specs/NativeDeviceEventManager'; +import * as ReactNativeFeatureFlags from '../../src/private/featureflags/ReactNativeFeatureFlags'; import {setEventInitTimeStamp} from '../../src/private/webapis/dom/events/internals/EventInternals'; import RCTDeviceEventEmitter from '../EventEmitter/RCTDeviceEventEmitter'; import {HardwareBackPressEvent} from './HardwareBackPressEvent'; @@ -18,7 +19,37 @@ const DEVICE_BACK_EVENT = 'hardwareBackPress'; type BackPressEventName = 'backPress' | 'hardwareBackPress'; type BackPressHandler = (event: HardwareBackPressEvent) => ?boolean; -const _backPressSubscriptions: Array = []; +type BackPressSubscription = { + handler: BackPressHandler, + intercept: boolean, +}; + +const _backPressSubscriptions: Array = []; + +/** + * Turns interception on while at least one listener asks for it, and off + * when none does. Android reads this before the back gesture starts, so it + * has to be up to date ahead of time. + * + * With the `enablePredictiveBackAndroid` feature flag on, it sends the value on + * every change to the listeners, even when it is the same as before, so a + * repeated request (for example when a screen gets focus) applies again if + * native code or another activity changed it. With the flag off and no + * listener asking for back, nothing is sent. + */ +function updateIntercept(): void { + const interceptEnabled = _backPressSubscriptions.some( + subscription => subscription.intercept, + ); + if ( + !interceptEnabled && + !ReactNativeFeatureFlags.enablePredictiveBackAndroid() + ) { + return; + } + // Optional: native code built before this method existed doesn't have it. + NativeDeviceEventManager?.setInterceptEnabled?.(interceptEnabled); +} RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function (nativeEvent) { const options = {}; @@ -28,7 +59,7 @@ RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function (nativeEvent) { } const event = new HardwareBackPressEvent(options); for (let i = _backPressSubscriptions.length - 1; i >= 0; i--) { - if (_backPressSubscriptions[i]?.(event)) { + if (_backPressSubscriptions[i]?.handler(event)) { return; } } @@ -36,6 +67,29 @@ RCTDeviceEventEmitter.addListener(DEVICE_BACK_EVENT, function (nativeEvent) { BackHandler.exitApp(); }); +type BackHandlerOptions = { + /** + * Android 16+ with targetSdk 36+ only. Ask Android to send back to React + * Native while this listener exists, instead of handling back itself with + * the predictive back animation. React Native intercepts back while at + * least one listener asks for it. Set it ahead of time, for example to your + * navigator's `canGoBack`. Defaults to `false`. + * + * It is a request, not a guarantee: native code that adds its own back + * callback after React Native's still receives back first. + */ + intercept?: boolean, +}; + +type BackHandlerSubscription = { + remove: () => void, + /** + * Changes this listener's `intercept` request without removing it. + */ + setInterceptEnabled: (enabled: boolean) => void, + ... +}; + /** * Detects hardware button presses for back navigation and lets you register * event listeners for the system's back action. Event subscriptions are called @@ -50,7 +104,8 @@ type TBackHandler = { readonly addEventListener: ( eventName: BackPressEventName, handler: BackPressHandler, - ) => {remove: () => void, ...}, + options?: BackHandlerOptions, + ) => BackHandlerSubscription, }; const BackHandler: TBackHandler = { /** @@ -67,21 +122,41 @@ const BackHandler: TBackHandler = { /** * Listen for the `hardwareBackPress` event. The handler should return `true` * to prevent the event from bubbling to earlier registered listeners. + * + * Adding the same handler again reuses its listener: it keeps its place, + * and its request changes only if `intercept` is passed. */ addEventListener: function ( eventName: BackPressEventName, handler: BackPressHandler, - ): {remove: () => void, ...} { - if (_backPressSubscriptions.indexOf(handler) === -1) { - _backPressSubscriptions.push(handler); + options?: BackHandlerOptions, + ): BackHandlerSubscription { + let subscription: ?BackPressSubscription = _backPressSubscriptions.find( + existing => existing.handler === handler, + ); + if (subscription == null) { + const created: BackPressSubscription = {handler, intercept: false}; + _backPressSubscriptions.push(created); + subscription = created; + } + if (options?.intercept !== undefined) { + subscription.intercept = options.intercept === true; } + updateIntercept(); + + const registered = subscription; return { remove: (): void => { - const index = _backPressSubscriptions.indexOf(handler); + const index = _backPressSubscriptions.indexOf(registered); if (index !== -1) { _backPressSubscriptions.splice(index, 1); + updateIntercept(); } }, + setInterceptEnabled: (enabled: boolean): void => { + registered.intercept = enabled; + updateIntercept(); + }, }; }, }; diff --git a/packages/react-native/Libraries/Utilities/BackHandler.ios.js b/packages/react-native/Libraries/Utilities/BackHandler.ios.js index e9bb65f193bb..e6c0f870938f 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.ios.js +++ b/packages/react-native/Libraries/Utilities/BackHandler.ios.js @@ -13,6 +13,16 @@ import type {HardwareBackPressEvent} from './HardwareBackPressEvent'; type BackPressEventName = 'backPress' | 'hardwareBackPress'; type BackPressHandler = (event: HardwareBackPressEvent) => ?boolean; +type BackHandlerOptions = { + intercept?: boolean, +}; + +type BackHandlerSubscription = { + remove: () => void, + setInterceptEnabled: (enabled: boolean) => void, + ... +}; + function emptyFunction(): void {} type TBackHandler = { @@ -20,14 +30,20 @@ type TBackHandler = { addEventListener( eventName: BackPressEventName, handler: BackPressHandler, - ): {remove: () => void, ...}, + options?: BackHandlerOptions, + ): BackHandlerSubscription, }; const BackHandler: TBackHandler = { exitApp: emptyFunction, - addEventListener(_eventName: BackPressEventName, _handler: BackPressHandler) { + addEventListener( + _eventName: BackPressEventName, + _handler: BackPressHandler, + _options?: BackHandlerOptions, + ) { return { remove: emptyFunction, + setInterceptEnabled: emptyFunction, }; }, }; diff --git a/packages/react-native/Libraries/Utilities/BackHandler.js.flow b/packages/react-native/Libraries/Utilities/BackHandler.js.flow index 4c1debea88b0..736e3e120fbf 100644 --- a/packages/react-native/Libraries/Utilities/BackHandler.js.flow +++ b/packages/react-native/Libraries/Utilities/BackHandler.js.flow @@ -22,12 +22,38 @@ export interface HardwareBackPressEvent { readonly timeStamp: number; } +export type BackHandlerOptions = { + /** + * Android 16+ with targetSdk 36+ only. Ask Android to send back to React + * Native while this listener exists, instead of handling back itself with + * the predictive back animation. Defaults to `false`. + * + * It is a request, not a guarantee: native code that adds its own back + * callback after React Native's still receives back first. + */ + intercept?: boolean, +}; + +export type BackHandlerSubscription = { + remove: () => void, + /** + * Changes this listener's `intercept` request without removing it. + */ + setInterceptEnabled: (enabled: boolean) => void, + ... +}; + type TBackHandler = { exitApp(): void, + /** + * Adding the same handler again reuses its listener: it keeps its place, + * and its request changes only if `intercept` is passed. + */ addEventListener( eventName: BackPressEventName, handler: (event: HardwareBackPressEvent) => ?boolean, - ): {remove: () => void, ...}, + options?: BackHandlerOptions, + ): BackHandlerSubscription, }; /** diff --git a/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js b/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js index 9e964a069ba3..0b26d9c7628c 100644 --- a/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js +++ b/packages/react-native/Libraries/Utilities/__mocks__/BackHandler.js @@ -8,7 +8,11 @@ * @format */ -import type {BackPressEventName} from '../BackHandler'; +import type { + BackHandlerOptions, + BackHandlerSubscription, + BackPressEventName, +} from '../BackHandler'; import type {HardwareBackPressEvent} from '../HardwareBackPressEvent'; import {HardwareBackPressEvent as HardwareBackPressEventClass} from '../HardwareBackPressEvent'; @@ -23,12 +27,14 @@ const BackHandler = { addEventListener: function ( eventName: BackPressEventName, handler: (event: HardwareBackPressEvent) => ?boolean, - ): {remove: () => void, ...} { + _options?: BackHandlerOptions, + ): BackHandlerSubscription { _backPressSubscriptions.add(handler); return { remove: () => { _backPressSubscriptions.delete(handler); }, + setInterceptEnabled: (_enabled: boolean) => {}, }; }, diff --git a/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js b/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js index 2dfec3786236..5c6da225148f 100644 --- a/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js +++ b/packages/react-native/Libraries/Utilities/__tests__/BackHandler-itest.js @@ -142,3 +142,143 @@ describe('BackHandler', () => { expect(called).toBe(false); }); }); + +// Fantom has no DeviceEventManager native module, so the request BackHandler +// sends to native can't be observed. These cases cover the parts of the +// `intercept` option that are visible through the public API: it must not +// change which handlers run, or how often. +describe('BackHandler intercept option', () => { + const subscriptions: Array<{remove: () => void, ...}> = []; + + afterEach(() => { + for (const sub of subscriptions) { + sub.remove(); + } + subscriptions.length = 0; + }); + + it('calls a handler added with intercept', () => { + let called = false; + const handler = (_event: HardwareBackPressEventType) => { + called = true; + return true; + }; + + subscriptions.push( + BackHandler.addEventListener('hardwareBackPress', handler, { + intercept: true, + }), + ); + + DeviceEventEmitter.emit('hardwareBackPress', {timeStamp: 100}); + + expect(called).toBe(true); + }); + + it('keeps reverse order across listeners with and without intercept', () => { + const callOrder: Array = []; + const handler1 = (_event: HardwareBackPressEventType) => { + callOrder.push('first'); + return false; + }; + const handler2 = (_event: HardwareBackPressEventType) => { + callOrder.push('second'); + return false; + }; + const handler3 = (_event: HardwareBackPressEventType) => { + callOrder.push('third'); + return false; + }; + + subscriptions.push( + BackHandler.addEventListener('hardwareBackPress', handler1, { + intercept: true, + }), + ); + subscriptions.push( + BackHandler.addEventListener('hardwareBackPress', handler2), + ); + subscriptions.push( + BackHandler.addEventListener('hardwareBackPress', handler3, { + intercept: true, + }), + ); + + DeviceEventEmitter.emit('hardwareBackPress', {timeStamp: 100}); + + expect(callOrder).toEqual(['third', 'second', 'first']); + }); + + it('runs the same handlers after setInterceptEnabled', () => { + const callOrder: Array = []; + const intercepting = BackHandler.addEventListener( + 'hardwareBackPress', + (_event: HardwareBackPressEventType) => { + callOrder.push('intercepting'); + return false; + }, + {intercept: true}, + ); + const plain = BackHandler.addEventListener( + 'hardwareBackPress', + (_event: HardwareBackPressEventType) => { + callOrder.push('plain'); + return false; + }, + ); + subscriptions.push(intercepting, plain); + + intercepting.setInterceptEnabled(false); + plain.setInterceptEnabled(true); + DeviceEventEmitter.emit('hardwareBackPress', {timeStamp: 100}); + + intercepting.setInterceptEnabled(true); + plain.setInterceptEnabled(false); + DeviceEventEmitter.emit('hardwareBackPress', {timeStamp: 200}); + + expect(callOrder).toEqual([ + 'plain', + 'intercepting', + 'plain', + 'intercepting', + ]); + }); + + it('does not bring back a removed listener on setInterceptEnabled', () => { + let called = false; + const subscription = BackHandler.addEventListener( + 'hardwareBackPress', + (_event: HardwareBackPressEventType) => { + called = true; + return true; + }, + ); + subscription.remove(); + + subscription.setInterceptEnabled(true); + DeviceEventEmitter.emit('hardwareBackPress', {timeStamp: 100}); + + expect(called).toBe(false); + }); + + it('calls the same handler once when added twice', () => { + let calls = 0; + const handler = (_event: HardwareBackPressEventType) => { + calls++; + return false; + }; + + subscriptions.push( + BackHandler.addEventListener('hardwareBackPress', handler), + ); + subscriptions.push( + BackHandler.addEventListener('hardwareBackPress', handler, { + intercept: true, + }), + ); + + DeviceEventEmitter.emit('hardwareBackPress', {timeStamp: 100}); + + expect(calls).toBe(1); + }); +}); diff --git a/packages/react-native/ReactAndroid/api/ReactAndroid.api b/packages/react-native/ReactAndroid/api/ReactAndroid.api index 9f62f0c9b496..30d94603dd66 100644 --- a/packages/react-native/ReactAndroid/api/ReactAndroid.api +++ b/packages/react-native/ReactAndroid/api/ReactAndroid.api @@ -61,6 +61,7 @@ public final class com/facebook/react/NativeModuleRegistryBuilder { public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/AppCompatActivity, com/facebook/react/modules/core/DefaultHardwareBackBtnHandler, com/facebook/react/modules/core/PermissionAwareActivity { protected fun ()V protected fun createReactActivityDelegate ()Lcom/facebook/react/ReactActivityDelegate; + public fun getBackPressedCallback ()Landroidx/activity/OnBackPressedCallback; protected fun getMainComponentName ()Ljava/lang/String; public fun getReactActivityDelegate ()Lcom/facebook/react/ReactActivityDelegate; public fun getReactDelegate ()Lcom/facebook/react/ReactDelegate; @@ -84,6 +85,7 @@ public abstract class com/facebook/react/ReactActivity : androidx/appcompat/app/ public fun onUserLeaveHint ()V public fun onWindowFocusChanged (Z)V public fun requestPermissions ([Ljava/lang/String;ILcom/facebook/react/modules/core/PermissionListener;)V + public fun setInterceptEnabled (Z)V } public class com/facebook/react/ReactActivityDelegate { @@ -2535,6 +2537,7 @@ public class com/facebook/react/modules/core/DeviceEventManagerModule : com/face public fun emitHardwareBackPressed ()V public fun emitNewIntentReceived (Landroid/net/Uri;)V public fun invokeDefaultBackPressHandler ()V + public fun setInterceptEnabled (Z)V } public final class com/facebook/react/modules/core/DeviceEventManagerModule$Companion { diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java index b375d1859dbc..546fcc5e04cc 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/ReactActivity.java @@ -14,6 +14,8 @@ import androidx.activity.OnBackPressedCallback; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; +import com.facebook.react.bridge.UiThreadUtil; +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.modules.core.PermissionAwareActivity; import com.facebook.react.modules.core.PermissionListener; @@ -28,6 +30,9 @@ public abstract class ReactActivity extends AppCompatActivity // Due to enforced predictive back on targetSdk 36, 'onBackPressed()' is disabled by default. // Using a workaround to trigger it manually. + // With the enablePredictiveBackAndroid feature flag, the callback is disabled in onCreate, so + // Android handles back and plays its predictive back animation until JS (a BackHandler listener + // with `intercept: true`) or native code turns it on. private final OnBackPressedCallback mBackPressedCallback = new OnBackPressedCallback(true) { @Override @@ -38,6 +43,26 @@ public void handleOnBackPressed() { } }; + /** + * The callback React Native registers on Android 16+ with targetSdk 36+ to receive back. Native + * navigation libraries and brownfield hosts can disable it to handle back themselves. + */ + public OnBackPressedCallback getBackPressedCallback() { + return mBackPressedCallback; + } + + /** + * Called from JS while at least one BackHandler listener asks for back ({@code true}) or none + * does ({@code false}). Has no effect unless the enablePredictiveBackAndroid feature flag is on. + */ + public void setInterceptEnabled(boolean enabled) { + UiThreadUtil.assertOnUiThread(); + if (!ReactNativeFeatureFlags.enablePredictiveBackAndroid()) { + return; + } + mBackPressedCallback.setEnabled(enabled); + } + @SuppressWarnings("this-escape") protected ReactActivity() { mDelegate = createReactActivityDelegate(); @@ -61,6 +86,9 @@ protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDelegate.onCreate(savedInstanceState); if (AndroidVersion.isAtLeastTargetSdk36(this)) { + if (ReactNativeFeatureFlags.enablePredictiveBackAndroid()) { + mBackPressedCallback.setEnabled(false); + } getOnBackPressedDispatcher().addCallback(this, mBackPressedCallback); } } @@ -121,13 +149,16 @@ public void onBackPressed() { @Override public void invokeDefaultOnBackPressed() { + if (isFinishing()) { + return; + } // Disabling callback so the fallback logic (finish activity) can run // as super.onBackPressed() will call all enabled callbacks in the dispatcher. + boolean wasEnabled = mBackPressedCallback.isEnabled(); mBackPressedCallback.setEnabled(false); super.onBackPressed(); - // Re-enable callback to ensure custom back handling works after activity resume - // Without this, the callback remains disabled when the app returns from background - mBackPressedCallback.setEnabled(true); + // Restore the previous state: JS or native code may have disabled it on purpose. + mBackPressedCallback.setEnabled(wasEnabled); } @Override diff --git a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt index 9ee720cf8bbc..b84c9cfab968 100644 --- a/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt +++ b/packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/core/DeviceEventManagerModule.kt @@ -10,6 +10,7 @@ package com.facebook.react.modules.core import android.net.Uri import com.facebook.fbreact.specs.NativeDeviceEventManagerSpec import com.facebook.proguard.annotations.DoNotStripAny +import com.facebook.react.ReactActivity import com.facebook.react.bridge.JavaScriptModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.UiThreadUtil @@ -59,6 +60,16 @@ public open class DeviceEventManagerModule( reactApplicationContext.runOnUiQueueThread(invokeDefaultBackPressRunnable) } + /** + * Called by BackHandler whenever its listeners change, with whether at least one asks for back. + * Acts on the current activity if it is a [ReactActivity]. + */ + override fun setInterceptEnabled(enabled: Boolean) { + UiThreadUtil.runOnUiThread { + (reactApplicationContext.currentActivity as? ReactActivity)?.setInterceptEnabled(enabled) + } + } + public companion object { public const val NAME: String = NativeDeviceEventManagerSpec.NAME } diff --git a/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityTest.kt b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityTest.kt new file mode 100644 index 000000000000..fb62af7a6ff7 --- /dev/null +++ b/packages/react-native/ReactAndroid/src/test/java/com/facebook/react/ReactActivityTest.kt @@ -0,0 +1,87 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +package com.facebook.react + +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlags +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsDefaults +import com.facebook.react.internal.featureflags.ReactNativeFeatureFlagsForTests +import org.assertj.core.api.Assertions.assertThat +import org.junit.After +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class ReactActivityTest { + + // The callback registration in onCreate() isn't covered here: onCreate() needs a + // ReactApplication, and its SDK 36 check never passes with robolectric.properties at sdk=33. + class TestActivity : ReactActivity() + + private lateinit var activity: TestActivity + + @Before + fun setUp() { + ReactNativeFeatureFlagsForTests.setUp() + activity = Robolectric.buildActivity(TestActivity::class.java).get() + } + + @After + fun tearDown() { + ReactNativeFeatureFlags.dangerouslyReset() + } + + @Test + fun backPressedCallbackIsEnabledByDefault() { + assertThat(activity.backPressedCallback.isEnabled).isTrue() + } + + @Test + fun setInterceptEnabledHasNoEffectWithoutFeatureFlag() { + activity.setInterceptEnabled(false) + + assertThat(activity.backPressedCallback.isEnabled).isTrue() + } + + @Test + fun setInterceptEnabledTogglesCallbackWithFeatureFlag() { + enablePredictiveBack() + + activity.setInterceptEnabled(false) + assertThat(activity.backPressedCallback.isEnabled).isFalse() + + activity.setInterceptEnabled(true) + assertThat(activity.backPressedCallback.isEnabled).isTrue() + } + + @Test + fun invokeDefaultOnBackPressedRestoresDisabledState() { + activity.backPressedCallback.isEnabled = false + + activity.invokeDefaultOnBackPressed() + + assertThat(activity.backPressedCallback.isEnabled).isFalse() + } + + @Test + fun invokeDefaultOnBackPressedRestoresEnabledState() { + activity.invokeDefaultOnBackPressed() + + assertThat(activity.backPressedCallback.isEnabled).isTrue() + } + + private fun enablePredictiveBack() { + ReactNativeFeatureFlags.override( + object : ReactNativeFeatureFlagsDefaults() { + override fun enablePredictiveBackAndroid(): Boolean = true + }, + ) + } +} diff --git a/packages/react-native/ReactNativeApi.d.ts b/packages/react-native/ReactNativeApi.d.ts index 2835ab8241ea..b3db6e234a4b 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<<333aebdd9df90c6843d435b18e60bc4c>> * * This file was generated by scripts/js-api/build-types/index.js. */ @@ -1628,6 +1628,13 @@ declare type BackgroundSizeValue = { y: number | string } declare type BackHandler = typeof BackHandler +declare type BackHandlerOptions = { + intercept?: boolean +} +declare type BackHandlerSubscription = { + remove: () => void + setInterceptEnabled: (enabled: boolean) => void +} declare type BackPressEventName = "backPress" | "hardwareBackPress" declare type BaseKeyboardEvent = { duration: number @@ -4935,9 +4942,8 @@ declare type TBackHandler = { addEventListener( eventName: BackPressEventName, handler: (event: HardwareBackPressEvent) => boolean | undefined, - ): { - remove: () => void - } + options?: BackHandlerOptions, + ): BackHandlerSubscription exitApp(): void } declare type Text = typeof Text @@ -5887,7 +5893,9 @@ export { AssetDestPathResolver, // 59047424 AssetRegistry, // 6070bb45 AutoCapitalize, // c0e857a0 - BackHandler, // f139fc69 + BackHandler, // 3b7c22f7 + BackHandlerOptions, // e9af377e + BackHandlerSubscription, // 082347e4 BackPressEventName, // 4620fb76 BlurEvent, // 00c596e2 BoxShadowValue, // b679703f diff --git a/packages/react-native/index.js.flow b/packages/react-native/index.js.flow index d1397e29920b..113d30c59a0a 100644 --- a/packages/react-native/index.js.flow +++ b/packages/react-native/index.js.flow @@ -295,7 +295,11 @@ export type { PackagerAsset, } from './src/private/assets/AssetRegistry'; -export type {BackPressEventName} from './Libraries/Utilities/BackHandler'; +export type { + BackHandlerOptions, + BackHandlerSubscription, + BackPressEventName, +} from './Libraries/Utilities/BackHandler'; export {default as BackHandler} from './Libraries/Utilities/BackHandler'; export {default as codegenNativeComponent} from './Libraries/Utilities/codegenNativeComponent'; diff --git a/packages/react-native/src/private/specs_DEPRECATED/modules/NativeDeviceEventManager.js b/packages/react-native/src/private/specs_DEPRECATED/modules/NativeDeviceEventManager.js index 4efff76e66a0..98ad054746cb 100644 --- a/packages/react-native/src/private/specs_DEPRECATED/modules/NativeDeviceEventManager.js +++ b/packages/react-native/src/private/specs_DEPRECATED/modules/NativeDeviceEventManager.js @@ -14,6 +14,7 @@ import * as TurboModuleRegistry from '../../../../Libraries/TurboModule/TurboMod export interface Spec extends TurboModule { readonly invokeDefaultBackPressHandler: () => void; + readonly setInterceptEnabled?: (enabled: boolean) => void; } export default TurboModuleRegistry.get('DeviceEventManager') as ?Spec; diff --git a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts index ac2a530a9c05..6617a3eabe72 100644 --- a/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts +++ b/packages/react-native/types_DEPRECATED/Libraries/Utilities/BackHandler.d.ts @@ -32,12 +32,37 @@ export interface HardwareBackPressEvent { * * @see https://reactnative.dev/docs/backhandler */ +export interface BackHandlerOptions { + /** + * Android 16+ with targetSdk 36+ only. Ask Android to send back to React + * Native while this listener exists, instead of handling back itself with + * the predictive back animation. React Native intercepts back while at + * least one listener asks for it. Defaults to `false`. + * + * It is a request, not a guarantee: native code that adds its own back + * callback after React Native's still receives back first. + */ + intercept?: boolean | undefined; +} + +export interface BackHandlerSubscription extends NativeEventSubscription { + /** + * Changes this listener's `intercept` request without removing it. + */ + setInterceptEnabled(enabled: boolean): void; +} + export interface BackHandlerStatic { exitApp(): void; + /** + * Adding the same handler again reuses its listener: it keeps its place, + * and its request changes only if `intercept` is passed. + */ addEventListener( eventName: BackPressEventName, handler: (event: HardwareBackPressEvent) => boolean | null | undefined, - ): NativeEventSubscription; + options?: BackHandlerOptions, + ): BackHandlerSubscription; } export const BackHandler: BackHandlerStatic; diff --git a/packages/rn-tester/js/RNTesterAppShared.js b/packages/rn-tester/js/RNTesterAppShared.js index 1956e27c46a9..33a913dd2a51 100644 --- a/packages/rn-tester/js/RNTesterAppShared.js +++ b/packages/rn-tester/js/RNTesterAppShared.js @@ -134,6 +134,9 @@ const RNTesterApp = ({ const subscription = BackHandler.addEventListener( 'hardwareBackPress', handleHardwareBackPress, + // Ask for back only while an example is open. On the examples list, + // Android handles back and plays its predictive back animation. + {intercept: activeModuleKey != null}, ); return () => subscription.remove(); }, [activeModuleKey, handleBackPress]);