diff --git a/src/hooks/useDiscardChangesConfirmation/index.native.ts b/src/hooks/useDiscardChangesConfirmation/index.native.ts index 28e199ccc11c..aaff5b5bd1d7 100644 --- a/src/hooks/useDiscardChangesConfirmation/index.native.ts +++ b/src/hooks/useDiscardChangesConfirmation/index.native.ts @@ -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'; @@ -24,6 +25,7 @@ function useDiscardChangesConfirmation({ onVisibilityChange, onConfirm, onTabSwitchDiscard, + shouldCloseRHPOnDiscard = false, }: UseDiscardChangesConfirmationOptions): DiscardChangesConfirmation { const route = useRoute(); const {translate} = useLocalize(); @@ -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; @@ -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(); @@ -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) { diff --git a/src/hooks/useDiscardChangesConfirmation/index.ts b/src/hooks/useDiscardChangesConfirmation/index.ts index eb5409f63715..829b6fbb0543 100644 --- a/src/hooks/useDiscardChangesConfirmation/index.ts +++ b/src/hooks/useDiscardChangesConfirmation/index.ts @@ -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'; @@ -32,6 +33,7 @@ function useDiscardChangesConfirmation({ onVisibilityChange, onConfirm, onTabSwitchDiscard, + shouldCloseRHPOnDiscard = false, }: UseDiscardChangesConfirmationOptions): DiscardChangesConfirmation { const route = useRoute(); const {translate} = useLocalize(); @@ -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; }; diff --git a/src/hooks/useDiscardChangesConfirmation/types.ts b/src/hooks/useDiscardChangesConfirmation/types.ts index fa42ee5b0d13..9bfec1261711 100644 --- a/src/hooks/useDiscardChangesConfirmation/types.ts +++ b/src/hooks/useDiscardChangesConfirmation/types.ts @@ -5,6 +5,11 @@ type UseDiscardChangesConfirmationOptions = { onVisibilityChange?: (visible: boolean) => void; onConfirm?: () => void | Promise; onTabSwitchDiscard?: () => void | Promise; + /** + * 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 = { diff --git a/src/libs/Navigation/helpers/getNavigationActionForReplay.ts b/src/libs/Navigation/helpers/getNavigationActionForReplay.ts new file mode 100644 index 000000000000..773db928058a --- /dev/null +++ b/src/libs/Navigation/helpers/getNavigationActionForReplay.ts @@ -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([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; diff --git a/src/pages/iou/request/step/DynamicIOURequestStepDistance.tsx b/src/pages/iou/request/step/DynamicIOURequestStepDistance.tsx index 1da17f4cfbe5..acb59eb107da 100644 --- a/src/pages/iou/request/step/DynamicIOURequestStepDistance.tsx +++ b/src/pages/iou/request/step/DynamicIOURequestStepDistance.tsx @@ -228,6 +228,7 @@ function DynamicIOURequestStepDistance({ }; const {suppressDiscardPrompt} = useDiscardChangesConfirmation({ + shouldCloseRHPOnDiscard: action === CONST.IOU.ACTION.CREATE, getHasUnsavedChanges: () => { const typedManualDistance = manualDistanceValue ? roundToTwoDecimalPlaces(parseFloat(manualDistanceValue)) : undefined; const manualDistanceChanged = manualDistanceValue !== undefined && typedManualDistance !== currentDistance; diff --git a/src/pages/iou/request/step/DynamicIOURequestStepDistanceManual.tsx b/src/pages/iou/request/step/DynamicIOURequestStepDistanceManual.tsx index 0f1e725b318c..fac5c41b8f02 100644 --- a/src/pages/iou/request/step/DynamicIOURequestStepDistanceManual.tsx +++ b/src/pages/iou/request/step/DynamicIOURequestStepDistanceManual.tsx @@ -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); diff --git a/src/pages/iou/request/step/IOURequestStepDistanceMap.tsx b/src/pages/iou/request/step/IOURequestStepDistanceMap.tsx index 12ff396036c9..853bcc4f2f5d 100644 --- a/src/pages/iou/request/step/IOURequestStepDistanceMap.tsx +++ b/src/pages/iou/request/step/IOURequestStepDistanceMap.tsx @@ -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), }); diff --git a/src/pages/iou/request/step/IOURequestStepDistanceOdometer.tsx b/src/pages/iou/request/step/IOURequestStepDistanceOdometer.tsx index bb685d1e1a35..b6580a1814e9 100644 --- a/src/pages/iou/request/step/IOURequestStepDistanceOdometer.tsx +++ b/src/pages/iou/request/step/IOURequestStepDistanceOdometer.tsx @@ -597,6 +597,7 @@ function IOURequestStepDistanceOdometer({ }; useDiscardChangesConfirmation({ + shouldCloseRHPOnDiscard: action === CONST.IOU.ACTION.CREATE, getHasUnsavedChanges, onCancel: restoreLastInputFocus, onConfirm: isEditingConfirmation diff --git a/src/pages/iou/request/step/IOURequestStepHours.tsx b/src/pages/iou/request/step/IOURequestStepHours.tsx index dfeac1033e17..ba5f8d2c6226 100644 --- a/src/pages/iou/request/step/IOURequestStepHours.tsx +++ b/src/pages/iou/request/step/IOURequestStepHours.tsx @@ -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); diff --git a/tests/navigation/DiscardChangesReplayTests.tsx b/tests/navigation/DiscardChangesReplayTests.tsx new file mode 100644 index 000000000000..cdd6f0c771ed --- /dev/null +++ b/tests/navigation/DiscardChangesReplayTests.tsx @@ -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('@react-navigation/native')); +jest.mock('@hooks/useResponsiveLayout', () => jest.fn()); +jest.mock('@libs/getIsNarrowLayout', () => jest.fn()); + +jest.mock('@hooks/useConfirmModal', () => { + const {default: mockUseConfirmModal} = jest.requireActual('../utils/mockUseConfirmModal'); + return mockUseConfirmModal; +}); + +jest.mock('@components/Modal/Global/ModalContext', () => { + const {createMockModalContextModule} = jest.requireActual('../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('@hooks/useDiscardChangesConfirmation/index.ts').default; +const useNativeDiscardChangesConfirmation = jest.requireActual('@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]); + }); +}); diff --git a/tests/unit/Navigation/getNavigationActionForReplayTest.ts b/tests/unit/Navigation/getNavigationActionForReplayTest.ts new file mode 100644 index 000000000000..12a67324b5a4 --- /dev/null +++ b/tests/unit/Navigation/getNavigationActionForReplayTest.ts @@ -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); + }); +}); diff --git a/tests/unit/hooks/useDiscardChangesConfirmation.test.ts b/tests/unit/hooks/useDiscardChangesConfirmation.test.ts index 7d457f80d2fe..963871d689b7 100644 --- a/tests/unit/hooks/useDiscardChangesConfirmation.test.ts +++ b/tests/unit/hooks/useDiscardChangesConfirmation.test.ts @@ -3,8 +3,14 @@ import {act, renderHook} from '@testing-library/react-native'; import type {DiscardChangesConfirmation} from '@hooks/useDiscardChangesConfirmation/types'; import type UseDiscardChangesConfirmationOptions from '@hooks/useDiscardChangesConfirmation/types'; +type MockNavigationAction = { + type: string; + source?: string; + target?: string; +}; + type MockBeforeRemoveEvent = { - data: {action: {type: string}}; + data: {action: MockNavigationAction}; defaultPrevented: boolean; preventDefault: () => void; }; @@ -61,6 +67,8 @@ jest.mock('@libs/Navigation/navigationRef', () => ({ get current() { return {dispatch: mockNavigationDispatch, goBack: jest.fn()}; }, + isReady: () => true, + getRootState: () => ({key: 'root', routes: [{key: 'rhp-route'}]}), }, })); @@ -75,9 +83,9 @@ const dispatchPopstate = () => { }); }; -const createBeforeRemoveEvent = (type: string): MockBeforeRemoveEvent => { +const createBeforeRemoveEvent = (type: string, action: Omit = {}): MockBeforeRemoveEvent => { const event: MockBeforeRemoveEvent = { - data: {action: {type}}, + data: {action: {type, ...action}}, defaultPrevented: false, preventDefault: () => { event.defaultPrevented = true; @@ -86,8 +94,8 @@ const createBeforeRemoveEvent = (type: string): MockBeforeRemoveEvent => { return event; }; -const invokeBeforeRemove = (type: string): MockBeforeRemoveEvent => { - const event = createBeforeRemoveEvent(type); +const invokeBeforeRemove = (type: string, action?: Omit): MockBeforeRemoveEvent => { + const event = createBeforeRemoveEvent(type, action); act(() => { mockBeforeRemoveCallback?.(event); }); @@ -98,7 +106,8 @@ describe('useDiscardChangesConfirmation (web)', () => { let historyGoSpy: jest.SpyInstance; let resolveModal: ((result: {action: string}) => void) | undefined; - const renderDiscardHook = (getHasUnsavedChanges: () => boolean) => renderHook(() => useDiscardChangesConfirmation({getHasUnsavedChanges})); + const renderDiscardHook = (getHasUnsavedChanges: () => boolean, shouldCloseRHPOnDiscard?: boolean) => + renderHook(() => useDiscardChangesConfirmation({getHasUnsavedChanges, shouldCloseRHPOnDiscard})); const resolveModalWith = async (action: string) => { await act(async () => { @@ -313,6 +322,42 @@ describe('useDiscardChangesConfirmation (web)', () => { expect(afterSave.defaultPrevented).toBe(true); expect(mockShowConfirmModal).toHaveBeenCalledTimes(1); }); + + it('replays a click outside the RHP at the root navigator on Discard, so the whole RHP closes', async () => { + // Given a dirty create expense step stacked in the RHP, which closes the whole RHP on Discard + renderDiscardHook(() => true, true); + + // When the user clicks outside the RHP, which sends a GO_BACK without a target from the root-level RHP route, and picks Discard + invokeBeforeRemove('GO_BACK', {source: 'rhp-route'}); + await resolveModalWith('CONFIRM'); + + // Then the replay targets the root, which closes the whole RHP instead of only the top screen + expect(mockNavigationDispatch).toHaveBeenCalledWith({type: 'GO_BACK', source: 'rhp-route', target: 'root'}); + }); + + it('replays a click outside the RHP unchanged on Discard by default, so only the screen closes', async () => { + // Given a dirty screen stacked in the RHP outside the create expense flow, such as the agent avatar page + renderDiscardHook(() => true); + + // When the user clicks outside the RHP and picks Discard + invokeBeforeRemove('GO_BACK', {source: 'rhp-route'}); + await resolveModalWith('CONFIRM'); + + // Then it is sent again as it was, so the user goes back to the previous page as before + expect(mockNavigationDispatch).toHaveBeenCalledWith({type: 'GO_BACK', source: 'rhp-route'}); + }); + + it('replays other blocked navigations unchanged on Discard', async () => { + // Given a dirty create expense step, which closes the whole RHP on Discard after a click outside + renderDiscardHook(() => true, true); + + // When a targeted pop, such as a header back, is blocked and the user picks Discard + invokeBeforeRemove('POP', {source: 'some-screen', target: 'rhp-stack'}); + await resolveModalWith('CONFIRM'); + + // Then it is sent again as it was, since the navigator it targets handles it the same way + expect(mockNavigationDispatch).toHaveBeenCalledWith({type: 'POP', source: 'some-screen', target: 'rhp-stack'}); + }); }); describe('popstate guards', () => { diff --git a/tests/unit/hooks/useDiscardChangesConfirmationNative.test.ts b/tests/unit/hooks/useDiscardChangesConfirmationNative.test.ts index 58b15963c8b3..9d99080755b9 100644 --- a/tests/unit/hooks/useDiscardChangesConfirmationNative.test.ts +++ b/tests/unit/hooks/useDiscardChangesConfirmationNative.test.ts @@ -7,7 +7,9 @@ import type {HardwareBackPressEvent} from '@src/types/utils/ReactNativeCompat'; import {BackHandler} from 'react-native'; -type MockBeforeRemoveEvent = {data: {action: {type: string}}}; +type MockNavigationAction = {type: string; source?: string; target?: string}; + +type MockBeforeRemoveEvent = {data: {action: MockNavigationAction}}; const mockHardwareBackPressEvent: HardwareBackPressEvent = {type: 'hardwareBackPress', timeStamp: 0}; @@ -56,6 +58,8 @@ jest.mock('@libs/Navigation/navigationRef', () => ({ get current() { return {dispatch: mockNavigationDispatch, goBack: mockNavigationGoBack}; }, + isReady: () => true, + getRootState: () => ({key: 'root', routes: [{key: 'rhp-route'}]}), }, })); @@ -69,7 +73,8 @@ describe('useDiscardChangesConfirmation (native)', () => { const removeSubscription = jest.fn(); let resolveModal: ((result: {action: string}) => void) | undefined; - const renderDiscardHook = (getHasUnsavedChanges: () => boolean) => renderHook(() => useDiscardChangesConfirmation({getHasUnsavedChanges})); + const renderDiscardHook = (getHasUnsavedChanges: () => boolean, shouldCloseRHPOnDiscard?: boolean) => + renderHook(() => useDiscardChangesConfirmation({getHasUnsavedChanges, shouldCloseRHPOnDiscard})); const pressHardwareBack = (): boolean | null | undefined => { let consumed: boolean | null | undefined; @@ -243,9 +248,9 @@ describe('useDiscardChangesConfirmation (native)', () => { }); describe('usePreventRemove (removal case: header back, in-app pop)', () => { - const invokeBeforeRemove = (type: string) => { + const invokeBeforeRemove = (type: string, action: Omit = {}) => { act(() => { - mockPreventRemoveCallback?.({data: {action: {type}}}); + mockPreventRemoveCallback?.({data: {action: {type, ...action}}}); }); }; @@ -291,5 +296,42 @@ describe('useDiscardChangesConfirmation (native)', () => { expect(mockNavigationDispatch).not.toHaveBeenCalled(); expect(mockNavigationGoBack).toHaveBeenCalledTimes(1); }); + + it('replays a click outside the RHP at the root navigator on Discard, so the whole RHP closes', async () => { + // Given a dirty create expense step stacked in the RHP, which closes the whole RHP on Discard + renderDiscardHook(() => true, true); + + // When the user clicks outside the RHP, which sends a GO_BACK without a target from the root-level RHP route, and picks Discard + invokeBeforeRemove('GO_BACK', {source: 'rhp-route'}); + await resolveModalWith('CONFIRM'); + + // Then the replay targets the root, which closes the whole RHP instead of only the top screen + expect(mockNavigationDispatch).toHaveBeenCalledWith({type: 'GO_BACK', source: 'rhp-route', target: 'root'}); + }); + + it('replays a click outside the RHP unchanged on Discard by default, so only the screen closes', async () => { + // Given a dirty screen stacked in the RHP outside the create expense flow, such as the agent avatar page + renderDiscardHook(() => true); + + // When the user clicks outside the RHP and picks Discard + invokeBeforeRemove('GO_BACK', {source: 'rhp-route'}); + await resolveModalWith('CONFIRM'); + + // Then it is sent again as it was, so the user goes back to the previous page as before + expect(mockNavigationDispatch).toHaveBeenCalledWith({type: 'GO_BACK', source: 'rhp-route'}); + }); + + it('lets a click outside the RHP close the whole RHP while the prompt is suppressed', () => { + // Given a dirty create expense step, so prevention stays armed, whose prompt is suppressed during a save + const {result} = renderDiscardHook(() => true, true); + act(() => result.current.suppressDiscardPrompt()); + + // When the user clicks outside the RHP + invokeBeforeRemove('GO_BACK', {source: 'rhp-route'}); + + // Then the close goes through at the root, so the whole RHP closes instead of only the top screen + expect(mockShowConfirmModal).not.toHaveBeenCalled(); + expect(mockNavigationDispatch).toHaveBeenCalledWith({type: 'GO_BACK', source: 'rhp-route', target: 'root'}); + }); }); }); diff --git a/tests/utils/MoneyRequestTestNavigator.tsx b/tests/utils/MoneyRequestTestNavigator.tsx new file mode 100644 index 000000000000..b91cd62d9518 --- /dev/null +++ b/tests/utils/MoneyRequestTestNavigator.tsx @@ -0,0 +1,162 @@ +/** + * Renders a real navigation tree with a tab navigator, the right modal navigator (RHP) and the create expense + * (MoneyRequest) stack inside it, so tests can drive steps of a create expense flow through the real navigators. + * Each step renders the component a test passes in, or nothing. + */ + +import {act, render} from '@testing-library/react-native'; + +import createRootStackNavigator from '@libs/Navigation/AppNavigator/createRootStackNavigator'; +import createSplitNavigator from '@libs/Navigation/AppNavigator/createSplitNavigator'; +import navigationRef from '@libs/Navigation/navigationRef'; +import type {MoneyRequestNavigatorParamList, RightModalNavigatorParamList, TabNavigatorParamList} from '@libs/Navigation/types'; + +import createPlatformStackNavigator from '@navigation/PlatformStackNavigation/createPlatformStackNavigator'; + +import CONST from '@src/CONST'; +import NAVIGATORS from '@src/NAVIGATORS'; +import SCREENS from '@src/SCREENS'; + +import type {NavigationProp, ParamListBase} from '@react-navigation/native'; +import type {TupleToUnion} from 'type-fest'; + +import {createBottomTabNavigator} from '@react-navigation/bottom-tabs'; +import {NavigationContainer, useNavigation} from '@react-navigation/native'; +import React, {useEffect} from 'react'; + +/** The create expense steps this tree registers */ +const MONEY_REQUEST_TEST_SCREENS = [SCREENS.MONEY_REQUEST.CREATE, SCREENS.MONEY_REQUEST.DYNAMIC_STEP_DESTINATION, SCREENS.MONEY_REQUEST.DYNAMIC_STEP_TIME] as const; + +type MoneyRequestTestScreen = TupleToUnion; + +type RenderMoneyRequestNavigationParams = { + /** The steps open in the create expense stack, from the first one to the one on top */ + openSteps: MoneyRequestTestScreen[]; + + /** The component each step renders. Steps left out render nothing. */ + stepComponents?: Partial>; + + /** The params every open step gets */ + stepParams?: Record; +}; + +const RootStack = createRootStackNavigator(); +const TabNav = createBottomTabNavigator(); +const RightModalNavigatorStack = createSplitNavigator(); +const MoneyRequestStack = createPlatformStackNavigator(); + +function EmptyScreen() { + return null; +} + +/** The navigation of the RHP route in the root stack. Clicking outside the RHP calls `goBack` on it. */ +let rhpNavigation: Pick, 'goBack'> | undefined; + +let stepComponentsForRender: Partial> = {}; + +function TestMoneyRequestNavigator() { + return ( + + {MONEY_REQUEST_TEST_SCREENS.map((screenName) => ( + stepComponentsForRender[screenName] ?? EmptyScreen} + /> + ))} + + ); +} + +function TestRightModalNavigator() { + const navigation = useNavigation(); + + useEffect(() => { + rhpNavigation = navigation; + return () => { + rhpNavigation = undefined; + }; + }, [navigation]); + + return ( + + + + ); +} + +function TestTabNavigator() { + return ( + + + + ); +} + +function renderMoneyRequestNavigation({openSteps, stepComponents = {}, stepParams = {}}: RenderMoneyRequestNavigationParams) { + stepComponentsForRender = stepComponents; + return render( + ({name, params: stepParams}))}, + }, + ], + }, + }, + ], + }} + > + + + + + , + ); +} + +/** Sends the same action as clicking the overlay outside the RHP: a back without a target from the RHP route */ +function clickOutsideRHP() { + act(() => { + rhpNavigation?.goBack(); + }); +} + +function getRootRouteNames() { + return navigationRef.current?.getRootState().routes.map((route) => route.name); +} + +function getMoneyRequestStepNames() { + return navigationRef.current + ?.getRootState() + .routes.find((route) => route.name === NAVIGATORS.RIGHT_MODAL_NAVIGATOR) + ?.state?.routes.at(0) + ?.state?.routes.map((route) => route.name); +} + +export {renderMoneyRequestNavigation, clickOutsideRHP, getRootRouteNames, getMoneyRequestStepNames};