Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 82 additions & 7 deletions packages/react-native/Libraries/Utilities/BackHandler.android.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -18,7 +19,37 @@ const DEVICE_BACK_EVENT = 'hardwareBackPress';
type BackPressEventName = 'backPress' | 'hardwareBackPress';
type BackPressHandler = (event: HardwareBackPressEvent) => ?boolean | void;

const _backPressSubscriptions: Array<BackPressHandler> = [];
type BackPressSubscription = {
handler: BackPressHandler,
intercept: boolean,
};

const _backPressSubscriptions: Array<BackPressSubscription> = [];

/**
* 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 = {};
Expand All @@ -28,14 +59,37 @@ 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;
}
}

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
Expand All @@ -50,7 +104,8 @@ type TBackHandler = {
readonly addEventListener: (
eventName: BackPressEventName,
handler: BackPressHandler,
) => {remove: () => void, ...},
options?: BackHandlerOptions,
) => BackHandlerSubscription,
};
const BackHandler: TBackHandler = {
/**
Expand All @@ -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();
},
};
},
};
Expand Down
20 changes: 18 additions & 2 deletions packages/react-native/Libraries/Utilities/BackHandler.ios.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,37 @@ import type {HardwareBackPressEvent} from './HardwareBackPressEvent';
type BackPressEventName = 'backPress' | 'hardwareBackPress';
type BackPressHandler = (event: HardwareBackPressEvent) => ?boolean | void;

type BackHandlerOptions = {
intercept?: boolean,
};

type BackHandlerSubscription = {
remove: () => void,
setInterceptEnabled: (enabled: boolean) => void,
...
};

function emptyFunction(): void {}

type TBackHandler = {
exitApp(): void,
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,
};
},
};
Expand Down
28 changes: 27 additions & 1 deletion packages/react-native/Libraries/Utilities/BackHandler.js.flow
Original file line number Diff line number Diff line change
Expand Up @@ -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 | void,
): {remove: () => void, ...},
options?: BackHandlerOptions,
): BackHandlerSubscription,
};

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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) => {},
};
},

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> = [];
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<string> = [];
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);
});
});
Loading