Skip to content
Closed
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
20 changes: 10 additions & 10 deletions src/hooks/useDiscardChangesConfirmation/index.native.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
import type {NavigationAction} from '@react-navigation/native';
import {useIsFocused, usePreventRemove} from '@react-navigation/native';
import {useCallback, useRef, useState} from 'react';
import {useCallback, useEffect, useRef, useState} from 'react';
import {ModalActions} from '@components/Modal/Global/ModalContext';
import useConfirmModal from '@hooks/useConfirmModal';
import useLocalize from '@hooks/useLocalize';
import navigationRef from '@libs/Navigation/navigationRef';
import type UseDiscardChangesConfirmationOptions from './types';

function useDiscardChangesConfirmation({getHasUnsavedChanges, onVisibilityChange, isEnabled = true}: UseDiscardChangesConfirmationOptions) {
function useDiscardChangesConfirmation({hasUnsavedChanges, onVisibilityChange, shouldNavigateAfterSave, navigateBack = () => {}}: UseDiscardChangesConfirmationOptions) {
const {translate} = useLocalize();
const isFocused = useIsFocused();
const {showConfirmModal} = useConfirmModal();
const [shouldAllowNavigation, setShouldAllowNavigation] = useState(false);
const blockedNavigationAction = useRef<NavigationAction | undefined>(undefined);

const shouldPrevent = isEnabled && isFocused && !shouldAllowNavigation;
useEffect(() => {
if (!shouldNavigateAfterSave) {
return;
}
navigateBack();
}, [shouldNavigateAfterSave, navigateBack]);

usePreventRemove(
shouldPrevent,
hasUnsavedChanges && isFocused && !shouldAllowNavigation,
useCallback(
({data}: {data: {action: NavigationAction}}) => {
if (!getHasUnsavedChanges()) {
setShouldAllowNavigation(true);
navigationRef.current?.dispatch(data.action);
return;
}
blockedNavigationAction.current = data.action;
onVisibilityChange?.(true);
showConfirmModal({
Expand All @@ -47,7 +47,7 @@ function useDiscardChangesConfirmation({getHasUnsavedChanges, onVisibilityChange
}
});
},
[getHasUnsavedChanges, onVisibilityChange, showConfirmModal, translate],
[onVisibilityChange, showConfirmModal, translate],
),
);
}
Expand Down
70 changes: 39 additions & 31 deletions src/hooks/useDiscardChangesConfirmation/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import type {NavigationAction} from '@react-navigation/native';
import {useIsFocused, useNavigation} from '@react-navigation/native';
import {useCallback, useEffect, useRef} from 'react';
import {useIsFocused, useNavigation, usePreventRemove} from '@react-navigation/native';
import {useCallback, useEffect, useRef, useState} from 'react';
import {ModalActions} from '@components/Modal/Global/ModalContext';
import useBeforeRemove from '@hooks/useBeforeRemove';
import useConfirmModal from '@hooks/useConfirmModal';
import useLocalize from '@hooks/useLocalize';
import setNavigationActionToMicrotaskQueue from '@libs/Navigation/helpers/setNavigationActionToMicrotaskQueue';
Expand All @@ -12,25 +11,27 @@ import type {PlatformStackNavigationProp} from '@libs/Navigation/PlatformStackNa
import type {RootNavigatorParamList} from '@libs/Navigation/types';
import type UseDiscardChangesConfirmationOptions from './types';

function useDiscardChangesConfirmation({getHasUnsavedChanges, onCancel, onVisibilityChange, isEnabled = true}: UseDiscardChangesConfirmationOptions) {
function useDiscardChangesConfirmation({hasUnsavedChanges, onCancel, onVisibilityChange, shouldNavigateAfterSave = false, navigateBack = () => {}}: UseDiscardChangesConfirmationOptions) {
const navigation = useNavigation<PlatformStackNavigationProp<RootNavigatorParamList>>();
const isFocused = useIsFocused();
const {translate} = useLocalize();
const {showConfirmModal, closeModal} = useConfirmModal();
const blockedNavigationAction = useRef<NavigationAction>(undefined);
const shouldNavigateBack = useRef(false);
const [shouldNavigateBack, setShouldNavigateBack] = useState(false);
const isDiscardModalOpenRef = useRef(false);
const isFocused = useIsFocused();
const isConfirmed = useRef(false);
const [discardConfirmed, setDiscardConfirmed] = useState(false);

const navigateBack = useCallback(() => {
const goBack = useCallback(() => {
if (blockedNavigationAction.current) {
navigationRef.current?.dispatch(blockedNavigationAction.current);
return;
}
if (!shouldNavigateBack.current) {
if (!shouldNavigateBack) {
return;
}
navigationRef.current?.goBack();
}, []);
}, [shouldNavigateBack]);

const showDiscardModal = useCallback(() => {
onVisibilityChange?.(true);
Expand All @@ -42,50 +43,57 @@ function useDiscardChangesConfirmation({getHasUnsavedChanges, onCancel, onVisibi
confirmText: translate('discardChangesConfirmation.confirmText'),
cancelText: translate('common.cancel'),
shouldIgnoreBackHandlerDuringTransition: true,
onModalHide: () => {
if (isConfirmed.current) {
setNavigationActionToMicrotaskQueue(goBack);
} else {
setShouldNavigateBack(false);
onCancel?.();
}
Comment on lines +46 to +52

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Set confirm state before handling modal hide

onModalHide branches on isConfirmed.current, but this ref is never updated to true anywhere in the hook, so the cancel path runs on every close. In practice this means onCancel is triggered even after a confirm, and on a real cancel it can run twice (once in onModalHide, once in the .then cancel branch), which causes incorrect side effects for callers that use onCancel (e.g., refocusing inputs while navigating away).

Useful? React with 👍 / 👎.

},
}).then((result) => {
isDiscardModalOpenRef.current = false;
onVisibilityChange?.(false);
if (result.action === ModalActions.CONFIRM) {
setNavigationActionToMicrotaskQueue(navigateBack);
setDiscardConfirmed(true);
setNavigationActionToMicrotaskQueue(goBack);
} else {
blockedNavigationAction.current = undefined;
shouldNavigateBack.current = false;
setShouldNavigateBack(false);
onCancel?.();
}
});
}, [showConfirmModal, translate, navigateBack, onCancel, onVisibilityChange]);
}, [showConfirmModal, translate, goBack, onCancel, onVisibilityChange]);

useBeforeRemove(
usePreventRemove(
(hasUnsavedChanges && !discardConfirmed) || shouldNavigateBack,
useCallback(
(e) => {
if (!isEnabled || !isFocused || !getHasUnsavedChanges() || shouldNavigateBack.current) {
return;
}

e.preventDefault();
blockedNavigationAction.current = e.data.action;
navigateAfterInteraction(showDiscardModal);
},
[getHasUnsavedChanges, isFocused, isEnabled, showDiscardModal],
[showDiscardModal],
),
isEnabled && isFocused,
);

useEffect(() => {
if (!shouldNavigateAfterSave) {
return;
}
navigateBack();
}, [shouldNavigateAfterSave, navigateBack]);

/**
* We cannot programmatically stop the browser's back navigation like react-navigation's beforeRemove.
* Events like popstate and transitionStart are triggered AFTER the back navigation has already completed.
* So we need to go forward to get back to the current page.
*/
useEffect(() => {
if (!isEnabled || !isFocused) {
return undefined;
}
const unsubscribe = navigation.addListener('transitionStart', ({data: {closing}}) => {
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
if (!getHasUnsavedChanges()) {
if (!hasUnsavedChanges || isConfirmed.current) {
return;
}
shouldNavigateBack.current = true;
setShouldNavigateBack(true);
if (closing) {
window.history.go(1);
return;
Expand All @@ -95,20 +103,20 @@ function useDiscardChangesConfirmation({getHasUnsavedChanges, onCancel, onVisibi
});

return unsubscribe;
}, [navigation, getHasUnsavedChanges, isFocused, isEnabled, showDiscardModal]);
}, [hasUnsavedChanges, navigation, showDiscardModal]);

/**
* When the screen loses focus (or is disabled) while the discard modal is open,
* When the screen loses focus while the discard modal is open,
* close the modal and reset refs so we don't leave the modal visible or stale state.
*/
useEffect(() => {
if ((isFocused && isEnabled) || !isDiscardModalOpenRef.current) {
if (isFocused) {
return;
}
closeModal();
blockedNavigationAction.current = undefined;
shouldNavigateBack.current = false;
}, [isFocused, isEnabled, closeModal]);
setShouldNavigateBack(false);
}, [isFocused, closeModal]);
}

export default useDiscardChangesConfirmation;
8 changes: 5 additions & 3 deletions src/hooks/useDiscardChangesConfirmation/types.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
type UseDiscardChangesConfirmationOptions = {
getHasUnsavedChanges: () => boolean;
onCancel?: () => void;
onVisibilityChange?: (visible: boolean) => void;
isEnabled?: boolean;
hasUnsavedChanges: boolean;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ CONSISTENCY-4 (docs)

isEnabled (line 2) remains in UseDiscardChangesConfirmationOptions but is no longer destructured or referenced by either the native or web hook implementation after the changes in this PR. It is dead code in the type.

Remove isEnabled from the type definition.


Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

onVisibilityChange?: (visible: boolean) => void;
onCancel?: () => void;
shouldNavigateAfterSave?: boolean;
navigateBack?: () => void;
};

export default UseDiscardChangesConfirmationOptions;
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import {usePreventRemove} from '@react-navigation/native';
import type {NavigationAction} from '@react-navigation/native';
import React, {memo, useCallback, useRef, useState} from 'react';
import ConfirmModal from '@components/ConfirmModal';
import useLocalize from '@hooks/useLocalize';
import navigationRef from '@libs/Navigation/navigationRef';
import type DiscardChangesConfirmationProps from './types';

function DiscardChangesConfirmation({hasUnsavedChanges, onVisibilityChange}: DiscardChangesConfirmationProps) {
const {translate} = useLocalize();
const [isVisible, setIsVisible] = useState(false);
const blockedNavigationAction = useRef<NavigationAction | undefined>(undefined);

usePreventRemove(
hasUnsavedChanges,
useCallback((e) => {
blockedNavigationAction.current = e.data.action;
setIsVisible(true);
}, []),
);

const setModalVisible = useCallback(
(nextVisible: boolean) => {
setIsVisible(nextVisible);
onVisibilityChange?.(nextVisible);
},
[onVisibilityChange],
);

return (
<ConfirmModal
isVisible={isVisible}
title={translate('discardChangesConfirmation.title')}
prompt={translate('discardChangesConfirmation.body')}
danger
confirmText={translate('discardChangesConfirmation.confirmText')}
cancelText={translate('common.cancel')}
onConfirm={() => {
setIsVisible(false);
setModalVisible(false);
if (blockedNavigationAction.current) {
navigationRef.current?.dispatch(blockedNavigationAction.current);
blockedNavigationAction.current = undefined;
} else {
navigationRef.current?.goBack();
}
}}
onCancel={() => {
setModalVisible(false);
blockedNavigationAction.current = undefined;
}}
shouldHandleNavigationBack
/>
);
}

export default memo(DiscardChangesConfirmation);
10 changes: 10 additions & 0 deletions src/pages/iou/request/step/DiscardChangesConfirmation/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
type DiscardChangesConfirmationProps = {
onCancel?: () => void;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

❌ CONSISTENCY-4 (docs)

onCancel, shouldNavigateAfterSave, and navigateBack are declared in DiscardChangesConfirmationProps but are not used by DiscardChangesConfirmation in index.native.tsx (which only destructures hasUnsavedChanges and onVisibilityChange). There is also no web counterpart that could consume them, and no file imports this component.

Remove the unused fields or add the consuming code first.


Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

hasUnsavedChanges: boolean;
shouldNavigateAfterSave?: boolean;
navigateBack?: () => void;
/** Notifies when the discard modal visibility changes */
onVisibilityChange?: (isVisible: boolean) => void;
};

export default DiscardChangesConfirmationProps;
49 changes: 21 additions & 28 deletions src/pages/iou/request/step/IOURequestStepDescription.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import lodashIsEmpty from 'lodash/isEmpty';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import React, {useCallback, useMemo, useState} from 'react';
import {InteractionManager, View} from 'react-native';
import type {OnyxEntry} from 'react-native-onyx';
import FormProvider from '@components/Form/FormProvider';
Expand Down Expand Up @@ -73,10 +73,8 @@ function IOURequestStepDescription({
return isEditingSplit && !lodashIsEmpty(splitDraftTransaction) ? (splitDraftTransaction?.comment?.comment ?? '') : (transaction?.comment?.comment ?? '');
}, [isTransactionDraft, iouType, isEditingSplit, splitDraftTransaction, transaction?.comment?.comment]);

const [currentDescription, setCurrentDescription] = useState(currentDescriptionInMarkdown);
const [isSaved, setIsSaved] = useState(false);
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
const [isDiscardModalVisible, setIsDiscardModalVisible] = useState(false);
const shouldNavigateAfterSaveRef = useRef(false);
useRestartOnReceiptFailure(transaction, reportID, iouType, action);
const currentUserPersonalDetails = useCurrentUserPersonalDetails();
const currentUserAccountIDParam = currentUserPersonalDetails.accountID;
Expand Down Expand Up @@ -122,35 +120,35 @@ function IOURequestStepDescription({
Navigation.goBack(backTo);
}, [backTo]);

useEffect(() => {
if (!isSaved || !shouldNavigateAfterSaveRef.current) {
return;
}
shouldNavigateAfterSaveRef.current = false;
navigateBack();
}, [isSaved, navigateBack]);
const [shouldNavigateAfterSave, setShouldNavigateAfterSave] = useState(false);

const updateDescriptionRef = (value: string) => {
setCurrentDescription(value);
};
const updateHasUnsavedChanges = useCallback(
(value: string) => {
if (value === currentDescriptionInMarkdown) {
setHasUnsavedChanges(false);
return;
}
setHasUnsavedChanges(true);
},
[currentDescriptionInMarkdown],
);

const updateComment = (value: FormOnyxValues<typeof ONYXKEYS.FORMS.MONEY_REQUEST_DESCRIPTION_FORM>) => {
if (!transaction?.transactionID) {
return;
}

setHasUnsavedChanges(false);
const newComment = value.moneyRequestComment.trim();

if (newComment === currentDescriptionInMarkdown) {
setIsSaved(true);
shouldNavigateAfterSaveRef.current = true;
setShouldNavigateAfterSave(true);
return;
}

if (isEditingSplit) {
setDraftSplitTransaction(transaction?.transactionID, splitDraftTransaction, {comment: newComment});
setIsSaved(true);
shouldNavigateAfterSaveRef.current = true;
setShouldNavigateAfterSave(true);
return;
}

Expand All @@ -171,9 +169,7 @@ function IOURequestStepDescription({
parentReportNextStep,
});
}

setIsSaved(true);
shouldNavigateAfterSaveRef.current = true;
setShouldNavigateAfterSave(true);
};

// eslint-disable-next-line rulesdir/no-negated-variables
Expand All @@ -191,13 +187,10 @@ function IOURequestStepDescription({
inputRef.current?.focus();
});
},
getHasUnsavedChanges: () => {
if (isSaved) {
return false;
}
return currentDescription !== currentDescriptionInMarkdown;
},
hasUnsavedChanges,
onVisibilityChange: setIsDiscardModalVisible,
shouldNavigateAfterSave,
navigateBack,
});

return (
Expand All @@ -224,7 +217,7 @@ function IOURequestStepDescription({
inputID={INPUT_IDS.MONEY_REQUEST_COMMENT}
name={INPUT_IDS.MONEY_REQUEST_COMMENT}
defaultValue={currentDescriptionInMarkdown}
onValueChange={updateDescriptionRef}
onValueChange={updateHasUnsavedChanges}
label={translate('moneyRequestConfirmationList.whatsItFor')}
accessibilityLabel={translate('moneyRequestConfirmationList.whatsItFor')}
role={CONST.ROLE.PRESENTATION}
Expand Down
Loading
Loading