diff --git a/src/App.tsx b/src/App.tsx index 9ed0e2bac6ed..17a127928d99 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -23,6 +23,7 @@ import {InputBlurContextProvider} from './components/InputBlurContext'; import KeyboardProvider from './components/KeyboardProvider'; import KYCWallContextProvider from './components/KYCWall/KYCWallContext'; import {LocaleContextProvider} from './components/LocaleContextProvider'; +import {ModalProvider} from './components/Modal/Global/ModalContext'; import NavigationBar from './components/NavigationBar'; import OnyxListItemProvider from './components/OnyxListItemProvider'; import PopoverContextProvider from './components/PopoverProvider'; @@ -124,6 +125,7 @@ function App() { InputBlurContextProvider, FullScreenBlockingViewContextProvider, FullScreenLoaderContextProvider, + ModalProvider, SidePanelContextProvider, ExpensifyCardContextProvider, KYCWallContextProvider, diff --git a/src/components/ButtonWithDropdownMenu/types.ts b/src/components/ButtonWithDropdownMenu/types.ts index ffcdb76f10ad..1f36af13c57b 100644 --- a/src/components/ButtonWithDropdownMenu/types.ts +++ b/src/components/ButtonWithDropdownMenu/types.ts @@ -30,7 +30,7 @@ type DropdownOption = { iconHeight?: number; iconDescription?: string; additionalIconStyles?: StyleProp; - onSelected?: () => void; + onSelected?: () => void | Promise; disabled?: boolean; iconFill?: string; interactive?: boolean; diff --git a/src/components/ConfirmModal.tsx b/src/components/ConfirmModal.tsx index e1e43be55752..ca379190348c 100755 --- a/src/components/ConfirmModal.tsx +++ b/src/components/ConfirmModal.tsx @@ -219,3 +219,4 @@ function ConfirmModal({ ConfirmModal.displayName = 'ConfirmModal'; export default ConfirmModal; +export type {ConfirmModalProps}; diff --git a/src/components/Modal/Global/ConfirmModalWrapper.tsx b/src/components/Modal/Global/ConfirmModalWrapper.tsx new file mode 100644 index 000000000000..d0535fbbfd08 --- /dev/null +++ b/src/components/Modal/Global/ConfirmModalWrapper.tsx @@ -0,0 +1,61 @@ +import React, {useState} from 'react'; +import type {ConfirmModalProps} from '@components/ConfirmModal'; +import ConfirmModal from '@components/ConfirmModal'; +import useActiveElementRole from '@hooks/useActiveElementRole'; +import useKeyboardShortcut from '@hooks/useKeyboardShortcut'; +import CONST from '@src/CONST'; +import {ModalActions} from './ModalContext'; +import type {ModalProps} from './ModalContext'; + +type ConfirmModalWrapperProps = ModalProps & Omit; + +// This wrapper bridges the ConfirmModal API with the global modal system, providing handlers for the onConfirm and onCancel callbacks to ConfirmModal. +// TODOS after migrating all ConfirmModal instances to use showConfirmModal: +// - handle closeModal inside ConfirmModal +// - remove ConfirmModalWrapper + +function ConfirmModalWrapper({closeModal, ...props}: ConfirmModalWrapperProps) { + const activeElementRole = useActiveElementRole(); + const [isVisible, setIsVisible] = useState(true); + const [closeAction, setCloseAction] = useState(ModalActions.CLOSE); + + const handleConfirm = () => { + setCloseAction(ModalActions.CONFIRM); + setIsVisible(false); + }; + + const handleCancel = () => { + setCloseAction(ModalActions.CLOSE); + setIsVisible(false); + }; + + const handleModalHide = () => { + if (isVisible) { + return; + } + closeModal({action: closeAction}); + }; + + const shortcutConfig = { + isActive: activeElementRole !== CONST.ROLE.BUTTON, + shouldPreventDefault: false, + shouldBubble: false, + }; + + useKeyboardShortcut(CONST.KEYBOARD_SHORTCUTS.ENTER, handleConfirm, shortcutConfig); + + return ( + + ); +} + +ConfirmModalWrapper.displayName = 'ConfirmModalWrapper'; + +export default ConfirmModalWrapper; diff --git a/src/components/Modal/Global/ModalContext.tsx b/src/components/Modal/Global/ModalContext.tsx new file mode 100644 index 000000000000..91bbcf679969 --- /dev/null +++ b/src/components/Modal/Global/ModalContext.tsx @@ -0,0 +1,107 @@ +import noop from 'lodash/noop'; +import React, {useCallback, useContext, useMemo, useState} from 'react'; +import Log from '@libs/Log'; +import CONST from '@src/CONST'; + +const ModalActions = { + CONFIRM: 'CONFIRM', + CLOSE: 'CLOSE', +} as const; + +type ModalAction = (typeof ModalActions)[keyof typeof ModalActions]; + +type ModalStateChangePayload = {action: A}; + +type ModalProps = { + closeModal: (param?: ModalStateChangePayload) => void; +}; + +type ModalContextType = { + showModal

(options: {component: React.FunctionComponent

; props?: Omit; id?: string; isCloseable?: boolean}): Promise; + closeModal(data?: ModalStateChangePayload): void; +}; + +const ModalContext = React.createContext({ + showModal: () => Promise.resolve({action: 'CLOSE'}), + closeModal: noop, +}); + +const useModal = () => useContext(ModalContext); + +let modalID = 1; + +type ModalInfo = { + id: string; + component: React.FunctionComponent; + props?: Record; + promiseWithResolvers: ReturnType>; + isCloseable: boolean; +}; + +function ModalProvider({children}: {children: React.ReactNode}) { + const [modalStack, setModalStack] = useState<{modals: ModalInfo[]}>({modals: []}); + + const showModal = useCallback(({component, props, id, isCloseable = true}) => { + // This is a promise that will resolve when the modal is closed + let closeModalPromise: Promise | null = null; + + setModalStack((prevState) => { + // Check current state for existing modal + const existingModal = id ? prevState.modals.find((modal: ModalInfo) => modal.id === id) : undefined; + if (existingModal) { + // There is already a modal with this ID. Return the existing promise and don't modify state. + closeModalPromise = existingModal.promiseWithResolvers.promise; + return prevState; // No state change needed + } + + // Create a new promise with resolvers to be resolved when the modal is closed + const promiseWithResolvers = Promise.withResolvers(); + closeModalPromise = promiseWithResolvers.promise; + + return { + ...prevState, + modals: [...prevState.modals, {component: component as React.FunctionComponent, props, promiseWithResolvers, isCloseable, id: id ?? String(modalID++)}], + }; + }); + + // At this point, closeModalPromise should always be assigned + if (!closeModalPromise) { + Log.alert(`${CONST.ERROR.ENSURE_BUG_BOT} Failed to create modal promise. This should never happen.`); + throw new Error('Failed to create modal promise'); + } + + return closeModalPromise; + }, []); + + const closeModal = useCallback((data = {action: 'CLOSE'}) => { + setModalStack((prevState) => { + const lastModal = prevState.modals.at(-1); + lastModal?.promiseWithResolvers.resolve(data); + return { + ...prevState, + modals: prevState.modals.slice(0, -1), + }; + }); + }, []); + + const contextValue = useMemo(() => ({showModal, closeModal}), [closeModal, showModal]); + const modalToRender = modalStack.modals.length > 0 ? modalStack.modals.at(modalStack.modals.length - 1) : null; + const ModalComponent = modalToRender?.component; + + return ( + + {children} + {!!ModalComponent && ( + + )} + + ); +} + +export type {ModalProps}; +export {ModalProvider, useModal, ModalActions}; diff --git a/src/components/MoneyReportHeader.tsx b/src/components/MoneyReportHeader.tsx index 7221c6aa8c7f..cfc61aef9196 100644 --- a/src/components/MoneyReportHeader.tsx +++ b/src/components/MoneyReportHeader.tsx @@ -5,6 +5,7 @@ import React, {useCallback, useContext, useEffect, useMemo, useState} from 'reac import {InteractionManager, View} from 'react-native'; import type {OnyxEntry} from 'react-native-onyx'; import type {ValueOf} from 'type-fest'; +import useConfirmModal from '@hooks/useConfirmModal'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useDeleteTransactions from '@hooks/useDeleteTransactions'; import useDuplicateTransactionsAndViolations from '@hooks/useDuplicateTransactionsAndViolations'; @@ -118,7 +119,6 @@ import BrokenConnectionDescription from './BrokenConnectionDescription'; import Button from './Button'; import ButtonWithDropdownMenu from './ButtonWithDropdownMenu'; import type {DropdownOption} from './ButtonWithDropdownMenu/types'; -import ConfirmModal from './ConfirmModal'; import DecisionModal from './DecisionModal'; import {DelegateNoAccessContext} from './DelegateNoAccessModalProvider'; import Header from './Header'; @@ -130,6 +130,7 @@ import {KYCWallContext} from './KYCWall/KYCWallContext'; import type {PaymentMethod} from './KYCWall/types'; import LoadingBar from './LoadingBar'; import Modal from './Modal'; +import {ModalActions} from './Modal/Global/ModalContext'; import MoneyReportHeaderKYCDropdown from './MoneyReportHeaderKYCDropdown'; import MoneyReportHeaderStatusBar from './MoneyReportHeaderStatusBar'; import MoneyReportHeaderStatusBarSkeleton from './MoneyReportHeaderStatusBarSkeleton'; @@ -257,14 +258,7 @@ function MoneyReportHeader({ const transactionViolations = useTransactionViolations(transaction?.transactionID); const [downloadErrorModalVisible, setDownloadErrorModalVisible] = useState(false); - const [isCancelPaymentModalVisible, setIsCancelPaymentModalVisible] = useState(false); - const [isDeleteExpenseModalVisible, setIsDeleteExpenseModalVisible] = useState(false); - const [isDeleteReportModalVisible, setIsDeleteReportModalVisible] = useState(false); - const [isUnapproveModalVisible, setIsUnapproveModalVisible] = useState(false); - const [isReopenWarningModalVisible, setIsReopenWarningModalVisible] = useState(false); const [isPDFModalVisible, setIsPDFModalVisible] = useState(false); - const [isExportWithTemplateModalVisible, setIsExportWithTemplateModalVisible] = useState(false); - const [isDEWModalVisible, setIsDEWModalVisible] = useState(false); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {canBeMissing: true}); const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS, {canBeMissing: true}); const {isBetaEnabled} = usePermissions(); @@ -272,7 +266,7 @@ function MoneyReportHeader({ const hasViolations = hasViolationsReportUtils(moneyRequestReport?.reportID, allTransactionViolations); const [exportModalStatus, setExportModalStatus] = useState(null); - + const {showConfirmModal} = useConfirmModal(); const {isPaidAnimationRunning, isApprovedAnimationRunning, isSubmittingAnimationRunning, startAnimation, stopAnimation, startApprovedAnimation, startSubmittingAnimation} = usePaymentAnimations(); const styles = useThemeStyles(); @@ -332,13 +326,27 @@ function MoneyReportHeader({ const {wideRHPRouteKeys} = useContext(WideRHPContext); const shouldDisplayNarrowMoreButton = !shouldDisplayNarrowVersion || (wideRHPRouteKeys.length > 0 && !isSmallScreenWidth); + const showExportProgressModal = useCallback(() => { + return showConfirmModal({ + title: translate('export.exportInProgress'), + prompt: translate('export.conciergeWillSend'), + confirmText: translate('common.buttonConfirm'), + shouldShowCancelButton: false, + }); + }, [showConfirmModal, translate]); + const beginExportWithTemplate = useCallback( (templateName: string, templateType: string, transactionIDList: string[], policyID?: string) => { if (!moneyRequestReport) { return; } - setIsExportWithTemplateModalVisible(true); + showExportProgressModal().then((result) => { + if (result.action !== ModalActions.CONFIRM) { + return; + } + clearSelectedTransactions(undefined, true); + }); queueExportSearchWithTemplate({ templateName, templateType, @@ -348,16 +356,11 @@ function MoneyReportHeader({ policyID, }); }, - [moneyRequestReport], + [moneyRequestReport, showExportProgressModal, clearSelectedTransactions], ); const [offlineModalVisible, setOfflineModalVisible] = useState(false); - const { - options: selectedTransactionsOptions, - handleDeleteTransactions, - isDeleteModalVisible: hookDeleteModalVisible, - hideDeleteModal, - } = useSelectedTransactionsActions({ + const {options: originalSelectedTransactionsOptions, handleDeleteTransactions} = useSelectedTransactionsActions({ report: moneyRequestReport, reportActions, allTransactionsLength: transactions.length, @@ -368,8 +371,6 @@ function MoneyReportHeader({ beginExportWithTemplate: (templateName, templateType, transactionIDList, policyID) => beginExportWithTemplate(templateName, templateType, transactionIDList, policyID), }); - const shouldShowSelectedTransactionsButton = !!selectedTransactionsOptions.length && !transactionThreadReportID; - const canIOUBePaid = useMemo(() => getCanIOUBePaid(), [getCanIOUBePaid]); const onlyShowPayElsewhere = useMemo(() => !canIOUBePaid && getCanIOUBePaid(true), [canIOUBePaid, getCanIOUBePaid]); @@ -470,9 +471,22 @@ function MoneyReportHeader({ ], ); + const showDWEModal = async () => { + const result = await showConfirmModal({ + confirmText: translate('customApprovalWorkflow.goToExpensifyClassic'), + title: translate('customApprovalWorkflow.title'), + prompt: translate('customApprovalWorkflow.description'), + shouldShowCancelButton: false, + }); + + if (result.action === ModalActions.CONFIRM) { + openOldDotLink(CONST.OLDDOT_URLS.INBOX); + } + }; + const confirmApproval = () => { if (hasDynamicExternalWorkflow(policy)) { - setIsDEWModalVisible(true); + showDWEModal(); return; } setRequestType(CONST.IOU.REPORT_ACTION_TYPE.APPROVE); @@ -721,7 +735,7 @@ function MoneyReportHeader({ return; } if (hasDynamicExternalWorkflow(policy)) { - setIsDEWModalVisible(true); + showDWEModal(); return; } startSubmittingAnimation(); @@ -878,6 +892,24 @@ function MoneyReportHeader({ return getSecondaryExportReportActions(moneyRequestReport, policy, exportTemplates); }, [moneyRequestReport, policy, exportTemplates]); + const connectedIntegrationName = connectedIntegration ? translate('workspace.accounting.connectionName', {connectionName: connectedIntegration}) : ''; + const unapproveWarningText = useMemo( + () => ( + + {translate('iou.headsUp')}{' '} + {translate('iou.unapproveWithIntegrationWarning', {accountingIntegration: connectedIntegrationName})} + + ), + [connectedIntegrationName, styles.noWrap, styles.textStrong, translate], + ); + + const reopenExportedReportWarningText = ( + + {translate('iou.headsUp')} + {translate('iou.reopenExportedReportConfirmation', {connectionName: integrationNameFromExportMessage ?? ''})} + + ); + const secondaryActionsImplementation: Record< ValueOf, DropdownOption> & Pick @@ -918,7 +950,7 @@ function MoneyReportHeader({ return; } if (hasDynamicExternalWorkflow(policy)) { - setIsDEWModalVisible(true); + showDWEModal(); return; } submitReport(moneyRequestReport, policy, accountID, email ?? '', hasViolations, isASAPSubmitBetaEnabled); @@ -934,14 +966,25 @@ function MoneyReportHeader({ text: translate('iou.unapprove'), icon: Expensicons.CircularArrowBackwards, value: CONST.REPORT.SECONDARY_ACTIONS.UNAPPROVE, - onSelected: () => { + onSelected: async () => { if (isDelegateAccessRestricted) { showDelegateNoAccessModal(); return; } if (isExported) { - setIsUnapproveModalVisible(true); + const result = await showConfirmModal({ + title: translate('iou.unapproveReport'), + prompt: unapproveWarningText, + confirmText: translate('iou.unapproveReport'), + cancelText: translate('common.cancel'), + danger: true, + }); + + if (result.action !== ModalActions.CONFIRM) { + return; + } + unapproveExpenseReport(moneyRequestReport, policy, accountID, email ?? '', hasViolations, isASAPSubmitBetaEnabled); return; } @@ -952,8 +995,19 @@ function MoneyReportHeader({ text: translate('iou.cancelPayment'), icon: Expensicons.Clear, value: CONST.REPORT.SECONDARY_ACTIONS.CANCEL_PAYMENT, - onSelected: () => { - setIsCancelPaymentModalVisible(true); + onSelected: async () => { + const result = await showConfirmModal({ + title: translate('iou.cancelPayment'), + prompt: translate('iou.cancelPaymentConfirmation'), + confirmText: translate('iou.cancelPayment'), + cancelText: translate('common.dismiss'), + danger: true, + }); + + if (result.action !== ModalActions.CONFIRM || !chatReport) { + return; + } + cancelPayment(moneyRequestReport, chatReport, policy, isASAPSubmitBetaEnabled, accountID, email ?? '', hasViolations); }, }, [CONST.REPORT.SECONDARY_ACTIONS.HOLD]: { @@ -1039,12 +1093,57 @@ function MoneyReportHeader({ text: translate('common.delete'), icon: Expensicons.Trashcan, value: CONST.REPORT.SECONDARY_ACTIONS.DELETE, - onSelected: () => { - if (Object.keys(transactions).length === 1) { - setIsDeleteExpenseModalVisible(true); - } else { - setIsDeleteReportModalVisible(true); + onSelected: async () => { + const transactionCount = Object.keys(transactions).length; + + if (transactionCount === 1) { + const result = await showConfirmModal({ + title: translate('iou.deleteExpense', {count: 1}), + prompt: translate('iou.deleteConfirmation', {count: 1}), + confirmText: translate('common.delete'), + cancelText: translate('common.cancel'), + danger: true, + }); + + if (result.action !== ModalActions.CONFIRM) { + return; + } + let goBackRoute: Route | undefined; + if (transactionThreadReportID) { + if (!requestParentReportAction || !transaction?.transactionID) { + throw new Error('Missing data!'); + } + // it's deleting transaction but not the report which leads to bug (that is actually also on staging) + // Money request should be deleted when interactions are done, to not show the not found page before navigating to goBackRoute + // eslint-disable-next-line @typescript-eslint/no-deprecated + InteractionManager.runAfterInteractions(() => { + deleteTransactions([transaction.transactionID], duplicateTransactions, duplicateTransactionViolations, currentSearchHash, false); + removeTransaction(transaction.transactionID); + }); + goBackRoute = getNavigationUrlOnMoneyRequestDelete(transaction.transactionID, requestParentReportAction, iouReport, chatIOUReport, isChatIOUReportArchived, false); + } + + if (goBackRoute) { + Navigation.setNavigationActionToMicrotaskQueue(() => navigateOnDeleteExpense(goBackRoute)); + } + return; } + + const result = await showConfirmModal({ + title: translate('iou.deleteReport'), + prompt: translate('iou.deleteReportConfirmation'), + confirmText: translate('common.delete'), + cancelText: translate('common.cancel'), + danger: true, + }); + if (result.action !== ModalActions.CONFIRM) { + return; + } + Navigation.goBack(route.params?.backTo); + // eslint-disable-next-line @typescript-eslint/no-deprecated + InteractionManager.runAfterInteractions(() => { + deleteAppReport(moneyRequestReport?.reportID); + }); }, }, [CONST.REPORT.SECONDARY_ACTIONS.RETRACT]: { @@ -1059,9 +1158,20 @@ function MoneyReportHeader({ text: translate('iou.retract'), icon: Expensicons.CircularArrowBackwards, value: CONST.REPORT.SECONDARY_ACTIONS.REOPEN, - onSelected: () => { + onSelected: async () => { if (isExported) { - setIsReopenWarningModalVisible(true); + const result = await showConfirmModal({ + title: translate('iou.reopenReport'), + prompt: reopenExportedReportWarningText, + confirmText: translate('iou.reopenReport'), + cancelText: translate('common.cancel'), + danger: true, + }); + + if (result.action !== ModalActions.CONFIRM) { + return; + } + reopenReport(moneyRequestReport, policy, accountID, email ?? '', hasViolations, isASAPSubmitBetaEnabled); return; } reopenReport(moneyRequestReport, policy, accountID, email ?? '', hasViolations, isASAPSubmitBetaEnabled); @@ -1131,17 +1241,6 @@ function MoneyReportHeader({ const shouldShowBackButton = shouldDisplayBackButton || shouldUseNarrowLayout; - const connectedIntegrationName = connectedIntegration ? translate('workspace.accounting.connectionName', {connectionName: connectedIntegration}) : ''; - const unapproveWarningText = useMemo( - () => ( - - {translate('iou.headsUp')}{' '} - {translate('iou.unapproveWithIntegrationWarning', {accountingIntegration: connectedIntegrationName})} - - ), - [connectedIntegrationName, styles.noWrap, styles.textStrong, translate], - ); - const isMobileSelectionModeEnabled = useMobileSelectionMode(); useEffect(() => { @@ -1150,6 +1249,67 @@ function MoneyReportHeader({ }; }, []); + const showDeleteModal = useCallback(() => { + showConfirmModal({ + title: translate('iou.deleteExpense', {count: selectedTransactionIDs.length}), + prompt: translate('iou.deleteConfirmation', {count: selectedTransactionIDs.length}), + confirmText: translate('common.delete'), + cancelText: translate('common.cancel'), + danger: true, + }).then((result) => { + if (result.action !== ModalActions.CONFIRM) { + return; + } + if (transactions.filter((trans) => trans.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE).length === selectedTransactionIDs.length) { + const backToRoute = route.params?.backTo ?? (chatReport?.reportID ? ROUTES.REPORT_WITH_ID.getRoute(chatReport.reportID) : undefined); + Navigation.goBack(backToRoute); + } + handleDeleteTransactions(); + }); + }, [showConfirmModal, translate, selectedTransactionIDs.length, transactions, handleDeleteTransactions, route.params?.backTo, chatReport?.reportID]); + + const showExportAgainModal = useCallback(() => { + if (!connectedIntegration) { + return; + } + showConfirmModal({ + title: translate('workspace.exportAgainModal.title'), + prompt: translate('workspace.exportAgainModal.description', { + connectionName: connectedIntegration ?? connectedIntegrationFallback, + reportName: moneyRequestReport?.reportName ?? '', + }), + confirmText: translate('workspace.exportAgainModal.confirmText'), + cancelText: translate('workspace.exportAgainModal.cancelText'), + }).then((result) => { + if (result.action !== ModalActions.CONFIRM) { + setExportModalStatus(null); + return; + } + confirmExport(); + }); + }, [showConfirmModal, translate, connectedIntegration, connectedIntegrationFallback, moneyRequestReport?.reportName, confirmExport]); + + useEffect(() => { + if (!exportModalStatus) { + return; + } + showExportAgainModal(); + }, [exportModalStatus, showExportAgainModal]); + + const selectedTransactionsOptions = useMemo(() => { + return originalSelectedTransactionsOptions.map((option) => { + if (option.text === translate('common.delete')) { + return { + ...option, + onSelected: showDeleteModal, + }; + } + return option; + }); + }, [originalSelectedTransactionsOptions, translate, showDeleteModal]); + + const shouldShowSelectedTransactionsButton = !!selectedTransactionsOptions.length && !transactionThreadReportID; + if (isMobileSelectionModeEnabled && shouldUseNarrowLayout) { // If mobile selection mode is enabled but only one or no transactions remain, turn it off const visibleTransactions = transactions.filter((t) => t.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || isOffline); @@ -1167,13 +1327,6 @@ function MoneyReportHeader({ /> ); } - - const reopenExportedReportWarningText = ( - - {translate('iou.headsUp')} - {translate('iou.reopenExportedReportConfirmation', {connectionName: integrationNameFromExportMessage ?? ''})} - - ); const onPaymentSelect = (event: KYCFlowEvent, iouPaymentType: PaymentMethodType, triggerKYCFlow: TriggerKYCFlow) => selectPaymentType({ event, @@ -1315,128 +1468,6 @@ function MoneyReportHeader({ isVisible={downloadErrorModalVisible} onClose={() => setDownloadErrorModalVisible(false)} /> - { - if (!chatReport) { - return; - } - cancelPayment(moneyRequestReport, chatReport, policy, isASAPSubmitBetaEnabled, accountID, email ?? '', hasViolations); - setIsCancelPaymentModalVisible(false); - }} - onCancel={() => setIsCancelPaymentModalVisible(false)} - prompt={translate('iou.cancelPaymentConfirmation')} - confirmText={translate('iou.cancelPayment')} - cancelText={translate('common.dismiss')} - danger - shouldEnableNewFocusManagement - /> - { - let goBackRoute: Route | undefined; - setIsDeleteExpenseModalVisible(false); - if (transactionThreadReportID) { - if (!requestParentReportAction || !transaction?.transactionID) { - throw new Error('Missing data!'); - } - // it's deleting transaction but not the report which leads to bug (that is actually also on staging) - // Money request should be deleted when interactions are done, to not show the not found page before navigating to goBackRoute - // eslint-disable-next-line @typescript-eslint/no-deprecated - InteractionManager.runAfterInteractions(() => { - deleteTransactions([transaction.transactionID], duplicateTransactions, duplicateTransactionViolations, currentSearchHash, false); - removeTransaction(transaction.transactionID); - }); - goBackRoute = getNavigationUrlOnMoneyRequestDelete(transaction.transactionID, requestParentReportAction, iouReport, chatIOUReport, isChatIOUReportArchived, false); - } - - if (goBackRoute) { - Navigation.setNavigationActionToMicrotaskQueue(() => navigateOnDeleteExpense(goBackRoute)); - } - }} - onCancel={() => setIsDeleteExpenseModalVisible(false)} - prompt={translate('iou.deleteConfirmation', {count: 1})} - confirmText={translate('common.delete')} - cancelText={translate('common.cancel')} - danger - shouldEnableNewFocusManagement - /> - { - if (transactions.filter((trans) => trans.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE).length === selectedTransactionIDs.length) { - const backToRoute = route.params?.backTo ?? (chatReport?.reportID ? ROUTES.REPORT_WITH_ID.getRoute(chatReport.reportID) : undefined); - Navigation.goBack(backToRoute); - } - handleDeleteTransactions(); - }} - onCancel={hideDeleteModal} - prompt={translate('iou.deleteConfirmation', {count: selectedTransactionIDs.length})} - confirmText={translate('common.delete')} - cancelText={translate('common.cancel')} - danger - shouldEnableNewFocusManagement - /> - { - setIsDeleteReportModalVisible(false); - - Navigation.goBack(); - // eslint-disable-next-line @typescript-eslint/no-deprecated - InteractionManager.runAfterInteractions(() => { - deleteAppReport(moneyRequestReport?.reportID); - }); - }} - onCancel={() => setIsDeleteReportModalVisible(false)} - prompt={translate('iou.deleteReportConfirmation')} - confirmText={translate('common.delete')} - cancelText={translate('common.cancel')} - danger - shouldEnableNewFocusManagement - /> - {!!connectedIntegration && ( - setExportModalStatus(null)} - prompt={translate('workspace.exportAgainModal.description', {connectionName: connectedIntegration, reportName: moneyRequestReport?.reportName ?? ''})} - confirmText={translate('workspace.exportAgainModal.confirmText')} - cancelText={translate('workspace.exportAgainModal.cancelText')} - isVisible={!!exportModalStatus} - /> - )} - { - setIsUnapproveModalVisible(false); - unapproveExpenseReport(moneyRequestReport, policy, accountID, email ?? '', hasViolations, isASAPSubmitBetaEnabled); - }} - cancelText={translate('common.cancel')} - onCancel={() => setIsUnapproveModalVisible(false)} - prompt={unapproveWarningText} - /> - { - setIsReopenWarningModalVisible(false); - reopenReport(moneyRequestReport, policy, accountID, email ?? '', hasViolations, isASAPSubmitBetaEnabled); - }} - cancelText={translate('common.cancel')} - onCancel={() => setIsReopenWarningModalVisible(false)} - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - prompt={reopenExportedReportWarningText} - /> - { - setIsExportWithTemplateModalVisible(false); - clearSelectedTransactions(undefined, true); - }} - onCancel={() => setIsExportWithTemplateModalVisible(false)} - isVisible={isExportWithTemplateModalVisible} - title={translate('export.exportInProgress')} - prompt={translate('export.conciergeWillSend')} - confirmText={translate('common.buttonConfirm')} - shouldShowCancelButton={false} - /> - { - setIsDEWModalVisible(false); - openOldDotLink(CONST.OLDDOT_URLS.INBOX); - }} - onCancel={() => setIsDEWModalVisible(false)} - prompt={translate('customApprovalWorkflow.description')} - confirmText={translate('customApprovalWorkflow.goToExpensifyClassic')} - shouldShowCancelButton={false} - /> ); } diff --git a/src/hooks/useConfirmModal.ts b/src/hooks/useConfirmModal.ts new file mode 100644 index 000000000000..ef1d586021f0 --- /dev/null +++ b/src/hooks/useConfirmModal.ts @@ -0,0 +1,22 @@ +import ConfirmModalWrapper from '@components/Modal/Global/ConfirmModalWrapper'; +import type {ModalProps} from '@components/Modal/Global/ModalContext'; +import {useModal} from '@components/Modal/Global/ModalContext'; + +type ConfirmModalOptions = Omit, keyof ModalProps>; + +const useConfirmModal = () => { + const context = useModal(); + + const showConfirmModal = (options: ConfirmModalOptions) => { + return context.showModal({ + component: ConfirmModalWrapper, + props: options, + }); + }; + + return { + ...context, + showConfirmModal, + }; +}; +export default useConfirmModal;