Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
dbc139d
Add getNavigationActionForReplay to replay an overlay back at the root
gijoe0295 Nov 16, 2026
18489dc
Close the whole RHP when Discard follows a click outside it on web
gijoe0295 Nov 16, 2026
7fade8c
Close the whole RHP when Discard follows a click outside it on native
gijoe0295 Nov 16, 2026
2967c57
Add MoneyRequestTestNavigator to drive create expense steps through r…
gijoe0295 Nov 16, 2026
abea713
Test with real navigators that Discard after a click outside closes t…
gijoe0295 Nov 16, 2026
08a8cea
Fix the RHP navigation type and drop an unused export in MoneyRequest…
gijoe0295 Nov 16, 2026
fe88018
Type the RHP navigation as a NavigationProp goBack in MoneyRequestTes…
gijoe0295 Nov 16, 2026
c818714
Close the whole RHP on Discard only for pages that opt in on web
gijoe0295 Nov 16, 2026
bc3dbbb
Close the whole RHP on Discard only for pages that opt in on native
gijoe0295 Nov 16, 2026
d6023f6
Test with real navigators that Discard after a click outside only clo…
gijoe0295 Nov 16, 2026
e743143
Close the whole RHP on Discard from the Amount step while creating an…
gijoe0295 Nov 16, 2026
c6f852c
Close the whole RHP on Discard from the Hours step while creating an …
gijoe0295 Nov 16, 2026
3609e24
Close the whole RHP on Discard from the map Distance step while creat…
gijoe0295 Nov 16, 2026
8f38253
Close the whole RHP on Discard from the Map distance tab while creati…
gijoe0295 Nov 16, 2026
48e7b0a
Close the whole RHP on Discard from the manual Distance step while cr…
gijoe0295 Nov 16, 2026
bf1afdc
Close the whole RHP on Discard from the Odometer step while creating …
gijoe0295 Nov 16, 2026
fdd6ee6
Simplify comments
gijoe0295 Nov 16, 2026
9877c80
Simplify comments
gijoe0295 Nov 16, 2026
12eb6b5
Remove shouldCloseRHPOnDiscard from Amount step
gijoe0295 Nov 17, 2026
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
8 changes: 6 additions & 2 deletions src/hooks/useDiscardChangesConfirmation/index.native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {ModalActions} from '@components/Modal/Global/ModalContext';
import useConfirmModal from '@hooks/useConfirmModal';
import useLocalize from '@hooks/useLocalize';

import getNavigationActionForReplay from '@libs/Navigation/helpers/getNavigationActionForReplay';
import navigationRef from '@libs/Navigation/navigationRef';
import {useRegisterTabSwitchGuard} from '@libs/Navigation/TabSwitchGuardContext';

Expand All @@ -24,6 +25,7 @@ function useDiscardChangesConfirmation({
onVisibilityChange,
onConfirm,
onTabSwitchDiscard,
shouldCloseRHPOnDiscard = false,
}: UseDiscardChangesConfirmationOptions): DiscardChangesConfirmation {
const route = useRoute();
const {translate} = useLocalize();
Expand All @@ -46,6 +48,8 @@ function useDiscardChangesConfirmation({

useRegisterTabSwitchGuard(route.name, hasUnsavedChanges, onTabSwitchDiscard, onCancel);

const getActionToReplay = (action: NavigationAction) => (shouldCloseRHPOnDiscard ? getNavigationActionForReplay(action) : action);

const showDiscardModal = (blockedAction?: NavigationAction) => {
blockedNavigationAction.current = blockedAction;
isDiscardModalOpen.current = true;
Expand All @@ -61,7 +65,7 @@ function useDiscardChangesConfirmation({
const confirmNavigation = () => {
isReplayingBlockedNavigation.current = true;
if (blockedNavigationAction.current) {
navigationRef.current?.dispatch(blockedNavigationAction.current);
navigationRef.current?.dispatch(getActionToReplay(blockedNavigationAction.current));
blockedNavigationAction.current = undefined;
} else {
navigationRef.current?.goBack();
Expand All @@ -77,7 +81,7 @@ function useDiscardChangesConfirmation({
usePreventRemove(shouldPreventRemove, ({data}: {data: {action: NavigationAction}}) => {
// The action delivered here carries react-navigation's visited-routes marker, so re-dispatching it skips this screen's prevention
if (isReplayingBlockedNavigation.current || !hasUnsavedChanges()) {
navigationRef.current?.dispatch(data.action);
navigationRef.current?.dispatch(getActionToReplay(data.action));
return;
}
if (isDiscardModalOpen.current) {
Expand Down
5 changes: 4 additions & 1 deletion src/hooks/useDiscardChangesConfirmation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import useBeforeRemove from '@hooks/useBeforeRemove';
import useConfirmModal from '@hooks/useConfirmModal';
import useLocalize from '@hooks/useLocalize';

import getNavigationActionForReplay from '@libs/Navigation/helpers/getNavigationActionForReplay';
import setNavigationActionToMicrotaskQueue from '@libs/Navigation/helpers/setNavigationActionToMicrotaskQueue';
import navigationRef from '@libs/Navigation/navigationRef';
import {useRegisterTabSwitchGuard} from '@libs/Navigation/TabSwitchGuardContext';
Expand Down Expand Up @@ -32,6 +33,7 @@ function useDiscardChangesConfirmation({
onVisibilityChange,
onConfirm,
onTabSwitchDiscard,
shouldCloseRHPOnDiscard = false,
}: UseDiscardChangesConfirmationOptions): DiscardChangesConfirmation {
const route = useRoute();
const {translate} = useLocalize();
Expand All @@ -57,7 +59,8 @@ function useDiscardChangesConfirmation({
return;
}
shouldNavigateBack.current = true;
navigationRef.current?.dispatch(blockedNavigationAction.current);
const blockedAction = blockedNavigationAction.current;
navigationRef.current?.dispatch(shouldCloseRHPOnDiscard ? getNavigationActionForReplay(blockedAction) : blockedAction);
shouldNavigateBack.current = false;
};

Expand Down
5 changes: 5 additions & 0 deletions src/hooks/useDiscardChangesConfirmation/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ type UseDiscardChangesConfirmationOptions = {
onVisibilityChange?: (visible: boolean) => void;
onConfirm?: () => void | Promise<void>;
onTabSwitchDiscard?: () => void | Promise<void>;
/**
* When the user clicks outside the RHP and picks Discard, close the whole RHP instead of only the focused page.
* Going back still closes only this page.
*/
shouldCloseRHPOnDiscard?: boolean;
};

type DiscardChangesConfirmation = {
Expand Down
32 changes: 32 additions & 0 deletions src/libs/Navigation/helpers/getNavigationActionForReplay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Prepares a navigation that a "Discard changes?" prompt blocked, so sending it again after Discard resumes it.
*/
import navigationRef from '@libs/Navigation/navigationRef';

import CONST from '@src/CONST';

import type {NavigationAction} from '@react-navigation/native';

const BACK_ACTION_TYPES = new Set<string>([CONST.NAVIGATION.ACTION_TYPE.GO_BACK, CONST.NAVIGATION.ACTION_TYPE.POP]);

/**
* Makes Discard close the whole RHP when the user clicked outside it.
*
* That click sends a "go back" with no target from the RHP's route, so the root closes the RHP. Sent again as is, the innermost
* navigator handles it and only closes the top screen, so it's aimed at the root instead. Other actions are returned unchanged.
* The copy keeps react-navigation's marker that stops the same screen from blocking it again.
*/
function getNavigationActionForReplay(action: NavigationAction): NavigationAction {
if (action.target || !action.source || !BACK_ACTION_TYPES.has(action.type)) {
return action;
}

const rootState = navigationRef.isReady() ? navigationRef.getRootState() : undefined;
if (!rootState?.routes.some((route) => route.key === action.source)) {
return action;
}

return {...action, target: rootState.key};
}

export default getNavigationActionForReplay;
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ function DynamicIOURequestStepDistance({
};

const {suppressDiscardPrompt} = useDiscardChangesConfirmation({
shouldCloseRHPOnDiscard: action === CONST.IOU.ACTION.CREATE,
Comment thread
gijoe0295 marked this conversation as resolved.
Resolved
getHasUnsavedChanges: () => {
const typedManualDistance = manualDistanceValue ? roundToTwoDecimalPlaces(parseFloat(manualDistanceValue)) : undefined;
const manualDistanceChanged = manualDistanceValue !== undefined && typedManualDistance !== currentDistance;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ function DynamicIOURequestStepDistanceManual({
const [typedDistance, setTypedDistance] = useState(committedDistance);

const {suppressDiscardPrompt} = useDiscardChangesConfirmation({
shouldCloseRHPOnDiscard: action === CONST.IOU.ACTION.CREATE,
getHasUnsavedChanges: () => getStringFieldHasUnsavedChanges(typedDistance, committedDistance, isCreatingNewRequest),
onCancel: () => {
focusTimeoutRef.current = setTimeout(() => textInput.current?.focus(), CONST.ANIMATED_TRANSITION);
Expand Down
1 change: 1 addition & 0 deletions src/pages/iou/request/step/IOURequestStepDistanceMap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ function IOURequestStepDistanceMap({
const shouldShowNotFoundPage = useShowNotFoundPageInIOUStep(action, iouType, reportActionID, report, transaction);

const {suppressDiscardPrompt} = useDiscardChangesConfirmation({
shouldCloseRHPOnDiscard: action === CONST.IOU.ACTION.CREATE,
getHasUnsavedChanges: () => doesMoneyRequestDraftHaveUserInput(transaction),
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,7 @@ function IOURequestStepDistanceOdometer({
};

useDiscardChangesConfirmation({
shouldCloseRHPOnDiscard: action === CONST.IOU.ACTION.CREATE,
getHasUnsavedChanges,
onCancel: restoreLastInputFocus,
onConfirm: isEditingConfirmation
Expand Down
1 change: 1 addition & 0 deletions src/pages/iou/request/step/IOURequestStepHours.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ function IOURequestStepHours({
}, [selectedTab, committedCount]);

const {suppressDiscardPrompt} = useDiscardChangesConfirmation({
shouldCloseRHPOnDiscard: action === CONST.IOU.ACTION.CREATE,
getHasUnsavedChanges: () => getStringFieldHasUnsavedChanges(typedCount, committedCount, isEmbeddedInStartPage),
onCancel: () => {
focusTimeoutRef.current = setTimeout(() => textInputRef.current?.focus(), CONST.ANIMATED_TRANSITION);
Expand Down
156 changes: 156 additions & 0 deletions tests/navigation/DiscardChangesReplayTests.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import {act, waitFor} from '@testing-library/react-native';

import type {DiscardChangesConfirmation} from '@hooks/useDiscardChangesConfirmation/types';
import type UseDiscardChangesConfirmationOptions from '@hooks/useDiscardChangesConfirmation/types';
import useResponsiveLayout from '@hooks/useResponsiveLayout';

import getIsNarrowLayout from '@libs/getIsNarrowLayout';
import Navigation from '@libs/Navigation/Navigation';
import navigationRef from '@libs/Navigation/navigationRef';

import CONST from '@src/CONST';
import NAVIGATORS from '@src/NAVIGATORS';
import SCREENS from '@src/SCREENS';

import type * as ReactNavigation from '@react-navigation/native';

import type * as MockUseConfirmModalUtil from '../utils/mockUseConfirmModal';

import {MockModalActions, mockShowConfirmModal, resetMockConfirmModal, resolveShowConfirmModal} from '../utils/mockUseConfirmModal';
import {clickOutsideRHP, getMoneyRequestStepNames, getRootRouteNames, renderMoneyRequestNavigation} from '../utils/MoneyRequestTestNavigator';

// The shared mock stubs `usePreventRemove`, which the native hook relies on, so this test uses the real module
jest.mock('@react-navigation/native', () => jest.requireActual<typeof ReactNavigation>('@react-navigation/native'));
jest.mock('@hooks/useResponsiveLayout', () => jest.fn());
jest.mock('@libs/getIsNarrowLayout', () => jest.fn());

jest.mock('@hooks/useConfirmModal', () => {
const {default: mockUseConfirmModal} = jest.requireActual<typeof MockUseConfirmModalUtil>('../utils/mockUseConfirmModal');
return mockUseConfirmModal;
});

jest.mock('@components/Modal/Global/ModalContext', () => {
const {createMockModalContextModule} = jest.requireActual<typeof MockUseConfirmModalUtil>('../utils/mockUseConfirmModal');
return createMockModalContextModule();
});

jest.mock('@hooks/useLocalize', () => ({
__esModule: true,
default: () => ({translate: (key: string) => key}),
}));

type DiscardHookModule = {default: (options: UseDiscardChangesConfirmationOptions) => DiscardChangesConfirmation};

// Jest resolves platform extensions native-first, so each implementation is loaded explicitly to run the same scenarios on both
const useWebDiscardChangesConfirmation = jest.requireActual<DiscardHookModule>('@hooks/useDiscardChangesConfirmation/index.ts').default;
const useNativeDiscardChangesConfirmation = jest.requireActual<DiscardHookModule>('@hooks/useDiscardChangesConfirmation/index.native.ts').default;

describe.each([
['web', useWebDiscardChangesConfirmation],
['native', useNativeDiscardChangesConfirmation],
])('Discarding changes on a step stacked in the RHP (%s)', (_, useDiscardChangesConfirmation) => {
/** A create expense step with unsaved changes, which closes the whole RHP on Discard */
function DirtyStep() {
useDiscardChangesConfirmation({getHasUnsavedChanges: () => true, shouldCloseRHPOnDiscard: true});
return null;
}

/** A page with unsaved changes outside the create expense flow, such as the agent avatar page */
function DirtyPageOutsideCreateFlow() {
useDiscardChangesConfirmation({getHasUnsavedChanges: () => true});
return null;
}

function renderDirtyStepOverFirstStep(dirtyStep = DirtyStep) {
renderMoneyRequestNavigation({
openSteps: [SCREENS.MONEY_REQUEST.CREATE, SCREENS.MONEY_REQUEST.DYNAMIC_STEP_DESTINATION],
stepComponents: {[SCREENS.MONEY_REQUEST.DYNAMIC_STEP_DESTINATION]: dirtyStep},
stepParams: {action: CONST.IOU.ACTION.CREATE, iouType: CONST.IOU.TYPE.CREATE, transactionID: '1', reportID: '1'},
});
}

beforeEach(() => {
resetMockConfirmModal();
jest.mocked(getIsNarrowLayout).mockReturnValue(true);
jest.mocked(useResponsiveLayout).mockReturnValue({...CONST.NAVIGATION_TESTS.DEFAULT_USE_RESPONSIVE_LAYOUT_VALUE, shouldUseNarrowLayout: true});
});

it('closes the whole RHP when the user clicks outside it and picks Discard', async () => {
// Given a step with unsaved changes stacked on another step in the RHP
renderDirtyStepOverFirstStep();

// When the user clicks outside the RHP
clickOutsideRHP();

// Then the RHP stays open while the user is asked
expect(mockShowConfirmModal).toHaveBeenCalledTimes(1);
expect(getRootRouteNames()).toEqual([NAVIGATORS.TAB_NAVIGATOR, NAVIGATORS.RIGHT_MODAL_NAVIGATOR]);

// When the user picks Discard
resolveShowConfirmModal({action: MockModalActions.CONFIRM});

// Then the whole RHP closes, as the click asked, instead of only the step on top.
await waitFor(() => expect(getRootRouteNames()).toEqual([NAVIGATORS.TAB_NAVIGATOR]));
});

it('only closes a page outside the create expense flow when the user clicks outside the RHP and picks Discard', async () => {
// Given a page with unsaved changes outside the create expense flow, stacked on another page in the RHP
renderDirtyStepOverFirstStep(DirtyPageOutsideCreateFlow);

// When the user clicks outside the RHP and picks Discard
clickOutsideRHP();
expect(mockShowConfirmModal).toHaveBeenCalledTimes(1);
resolveShowConfirmModal({action: MockModalActions.CONFIRM});

// Then only that page closes and the RHP stays on the page below it, as before
await waitFor(() => expect(getMoneyRequestStepNames()).toEqual([SCREENS.MONEY_REQUEST.CREATE]));
expect(getRootRouteNames()).toEqual([NAVIGATORS.TAB_NAVIGATOR, NAVIGATORS.RIGHT_MODAL_NAVIGATOR]);
});

it('keeps the RHP and the step open when the user cancels', async () => {
// Given a step with unsaved changes stacked on another step in the RHP
renderDirtyStepOverFirstStep();

// When the user clicks outside the RHP and cancels the prompt
clickOutsideRHP();
expect(mockShowConfirmModal).toHaveBeenCalledTimes(1);
await act(async () => {
resolveShowConfirmModal({action: MockModalActions.CLOSE});
});

// Then nothing closes, so the changes are still there
expect(getRootRouteNames()).toEqual([NAVIGATORS.TAB_NAVIGATOR, NAVIGATORS.RIGHT_MODAL_NAVIGATOR]);
expect(getMoneyRequestStepNames()).toEqual([SCREENS.MONEY_REQUEST.CREATE, SCREENS.MONEY_REQUEST.DYNAMIC_STEP_DESTINATION]);
});

it('closes the whole RHP when the user presses Esc and picks Discard', async () => {
// Given a step with unsaved changes stacked on another step in the RHP
renderDirtyStepOverFirstStep();

// When the user presses Esc, which dismisses the modal, and picks Discard
act(() => {
Navigation.dismissModal();
});
expect(mockShowConfirmModal).toHaveBeenCalledTimes(1);
resolveShowConfirmModal({action: MockModalActions.CONFIRM});

// Then the whole RHP closes
await waitFor(() => expect(getRootRouteNames()).toEqual([NAVIGATORS.TAB_NAVIGATOR]));
});

it('only leaves the step when the user goes back from it and picks Discard', async () => {
// Given a step with unsaved changes stacked on another step in the RHP
renderDirtyStepOverFirstStep();

// When the user goes back from the step, which the step's own stack handles, and picks Discard
act(() => {
navigationRef.current?.goBack();
});
expect(mockShowConfirmModal).toHaveBeenCalledTimes(1);
resolveShowConfirmModal({action: MockModalActions.CONFIRM});

// Then only the step closes and the RHP stays on the step below it
await waitFor(() => expect(getMoneyRequestStepNames()).toEqual([SCREENS.MONEY_REQUEST.CREATE]));
expect(getRootRouteNames()).toEqual([NAVIGATORS.TAB_NAVIGATOR, NAVIGATORS.RIGHT_MODAL_NAVIGATOR]);
});
});
49 changes: 49 additions & 0 deletions tests/unit/Navigation/getNavigationActionForReplayTest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import getNavigationActionForReplay from '@libs/Navigation/helpers/getNavigationActionForReplay';

let mockIsNavigationReady = true;
jest.mock('@libs/Navigation/navigationRef', () => ({
__esModule: true,
default: {
isReady: () => mockIsNavigationReady,
getRootState: () => ({key: 'root', routes: [{key: 'tab-navigator'}, {key: 'rhp-route'}]}),
},
}));

describe('getNavigationActionForReplay', () => {
beforeEach(() => {
mockIsNavigationReady = true;
});

it('targets the root navigator for a back without a target, sent from a root-level route', () => {
// Given the RHP overlay's GO_BACK without a target, sent from the root-level RHP route
const action = {type: 'GO_BACK', source: 'rhp-route'};

// When preparing it for replay through the container
const actionForReplay = getNavigationActionForReplay(action);

// Then it targets the root, which closed the whole RHP the first time
expect(actionForReplay).toEqual({type: 'GO_BACK', source: 'rhp-route', target: 'root'});
});

it.each([
['a targeted action', {type: 'POP', source: 'rhp-route', target: 'money-request-stack'}],
['an action without a source', {type: 'GO_BACK'}],
['an action that is not a back', {type: 'NAVIGATE', source: 'rhp-route'}],
['an action sent from a nested screen', {type: 'GO_BACK', source: 'confirmation-route'}],
])('replays %s unchanged', (_, action) => {
// Given an action the deepest navigator handles the same way on replay
// When preparing it for replay
// Then it's left as is
expect(getNavigationActionForReplay(action)).toBe(action);
});

it('replays the action unchanged before navigation is ready', () => {
// Given a navigation container that isn't ready
mockIsNavigationReady = false;
const action = {type: 'GO_BACK', source: 'rhp-route'};

// When preparing an overlay back for replay
// Then it's left as is
expect(getNavigationActionForReplay(action)).toBe(action);
});
});
Loading
Loading