diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index 6a886f143b44..625cc71f62d2 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx @@ -108,6 +108,9 @@ function MoneyRequestReportActionsList({onLayout}: MoneyRequestReportListProps) const didLayout = useRef(false); const [isVisible, setIsVisible] = useState(Visibility.isVisible); const isFocused = useIsFocused(); + const {shouldUseNarrowLayout} = useResponsiveLayoutOnWideRHP(); + // The table is visible whenever it's wide, or — on narrow — only when focused (the RHP has closed). + const isReportVisible = shouldUseNarrowLayout ? isFocused : true; const route = useRoute>(); const reportIDFromRoute = route?.params?.reportID; @@ -160,8 +163,6 @@ function MoneyRequestReportActionsList({onLayout}: MoneyRequestReportListProps) const canPerformWriteAction = canUserPerformWriteAction(report, isReportArchived); const [visibleReportActionsData] = useOnyx(ONYXKEYS.DERIVED.VISIBLE_REPORT_ACTIONS); - const {shouldUseNarrowLayout} = useResponsiveLayoutOnWideRHP(); - const [reportNameValuePairs] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${getNonEmptyStringOnyxID(reportID)}`); const shouldShowHarvestCreatedAction = isHarvestCreatedExpenseReport(reportNameValuePairs?.origin, reportNameValuePairs?.originalID); const [enableScrollToEnd, setEnableScrollToEnd] = useState(false); @@ -753,6 +754,7 @@ function MoneyRequestReportActionsList({onLayout}: MoneyRequestReportListProps) onLayout={onLayout} transactions={transactions} newTransactions={newTransactions} + isReportVisible={isReportVisible} hasPendingDeletionTransaction={hasPendingDeletionTransaction} reportActions={reportActions} scrollToNewTransaction={scrollToNewTransaction} diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx index 47ec8dff64a3..2ed2384ad3e4 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx @@ -137,6 +137,9 @@ type MoneyRequestReportTransactionListProps = { /** List of transactions that arrived when the report was open */ newTransactions: OnyxTypes.Transaction[]; + /** Whether the report table is visible — gates the new-row highlight (background on wide, on-close on narrow) */ + isReportVisible?: boolean; + /** Array of report actions for the report that these transactions belong to */ reportActions: OnyxTypes.ReportAction[]; @@ -167,6 +170,7 @@ function MoneyRequestReportTransactionList({ report, transactions, newTransactions, + isReportVisible = true, reportActions, hasPendingDeletionTransaction = false, scrollToNewTransaction, @@ -706,7 +710,7 @@ function MoneyRequestReportTransactionList({ key={transaction.transactionID} transaction={transaction} violations={violationsByTransactionID.get(transaction.transactionID) ?? EMPTY_VIOLATIONS} - shouldBeHighlighted={highlightedTransactionIDs.has(transaction.transactionID)} + shouldBeHighlighted={isReportVisible && highlightedTransactionIDs.has(transaction.transactionID)} columns={columnsToShow} report={report} policy={policy} diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx index 6d8eca29164c..144546c0dc3f 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx @@ -47,7 +47,7 @@ function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromR const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); const [betas] = useOnyx(ONYXKEYS.BETAS); const {email: currentUserEmail, accountID: currentUserAccountID} = useCurrentUserPersonalDetails(); - const {markReportIDAsExpense} = useWideRHPActions(); + const {markReportRHPWidth} = useWideRHPActions(); const {prevTransactionID, nextTransactionID} = useMemo(() => { if (!transactionIDsList || transactionIDsList.length < 2) { @@ -142,7 +142,7 @@ function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromR if (nextDescriptor) { requestAnimationFrame(() => { const nextReportID = getReportIDToOpenForExpense(nextDescriptor, {introSelected, betas, currentUserEmail, currentUserAccountID}); - markReportIDAsExpense(nextReportID); + markReportRHPWidth(nextReportID, 'wide'); requestAnimationFrame(() => startTransition(() => Navigation.setParams({reportID: nextReportID, reportActionID: undefined, backTo}))); }); return; @@ -153,7 +153,7 @@ function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromR requestAnimationFrame(() => { if (nextThreadReportID) { - markReportIDAsExpense(nextThreadReportID); + markReportRHPWidth(nextThreadReportID, 'wide'); } // We know that the next thread report exists, it just wasn't fetched to Onyx yet, so we set it optimistically. if (!nextThreadReport && nextThreadReportID) { @@ -192,7 +192,7 @@ function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromR if (prevDescriptor) { requestAnimationFrame(() => { const prevReportID = getReportIDToOpenForExpense(prevDescriptor, {introSelected, betas, currentUserEmail, currentUserAccountID}); - markReportIDAsExpense(prevReportID); + markReportRHPWidth(prevReportID, 'wide'); requestAnimationFrame(() => startTransition(() => Navigation.setParams({reportID: prevReportID, reportActionID: undefined, backTo}))); }); return; @@ -203,7 +203,7 @@ function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromR requestAnimationFrame(() => { if (prevThreadReportID) { - markReportIDAsExpense(prevThreadReportID); + markReportRHPWidth(prevThreadReportID, 'wide'); } // We know that the previous thread report exists, it just wasn't fetched to Onyx yet, so we set it optimistically. if (!prevThreadReport && prevThreadReportID) { diff --git a/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx b/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx index 5b20ea8b54b7..587105679366 100644 --- a/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx +++ b/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx @@ -138,7 +138,9 @@ function MoneyRequestReportPreview({ }); const isFocused = useIsFocused(); const newTransactions = useNewTransactions(hasOnceLoadedReportActions, transactions, pendingNewTransactionIDs, chatReportID, isFocused); - const newTransactionIDs = new Set(newTransactions.map((transaction) => transaction.transactionID)); + // Don't surface the highlight while the preview is covered — it'd animate the one-shot off-screen and be missed. + const isReportVisible = shouldUseNarrowLayout ? isFocused : true; + const newTransactionIDs = new Set(isReportVisible ? newTransactions.map((transaction) => transaction.transactionID) : []); const transactionPreviewContainerStyles = [styles.h100, reportPreviewStyles.transactionPreviewCarouselStyle]; diff --git a/src/components/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx b/src/components/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx index 056bfc659982..8f3c8ed103a3 100644 --- a/src/components/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx +++ b/src/components/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx @@ -163,7 +163,7 @@ function TransactionGroupListExpanded({ const isActionColumnWide = transactions.some((transaction) => !!transaction.isActionColumnWide || isDeletedTransaction(transaction)); - const {markReportIDAsExpense} = useWideRHPActions(); + const {markReportRHPWidth} = useWideRHPActions(); const selectRow = onSelectRow as (item: TItem, transactionPreviewData?: TransactionPreviewData, event?: ModifiedMouseEvent) => void; const getTransactionPreviewData = (transactionItem: TransactionListItemType): TransactionPreviewData => { const parentReportAction = getReportAction(transactionItem?.reportID, transactionItem?.reportAction?.reportActionID); @@ -222,7 +222,7 @@ function TransactionGroupListExpanded({ }); return; } - markReportIDAsExpense(reportID); + markReportRHPWidth(reportID, 'wide'); const route = ROUTES.SEARCH_REPORT.getRoute({reportID, backTo}); if (openInternalRouteInNewTab(route, event)) { return; diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index 1aec03d8cdf5..d827d2157fa2 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -147,7 +147,7 @@ function Search({ const navigation = useNavigation>(); const isFocused = useIsFocused(); - const {markReportIDAsExpense, markReportIDAsMultiTransactionExpense, unmarkReportIDAsMultiTransactionExpense} = useWideRHPActions(); + const {markReportRHPWidth, unmarkReportRHPWidth} = useWideRHPActions(); const {currentSearchHash, currentSearchKey, shouldResetSearchQuery, suggestedSearches} = useSearchQueryContext(); const {lastSearchType, shouldUseLiveData} = useSearchResultsContext(); @@ -597,9 +597,9 @@ function Search({ } if (item.transactions.length > 1) { - markReportIDAsMultiTransactionExpense(reportID); + markReportRHPWidth(reportID, 'super-wide'); } else { - unmarkReportIDAsMultiTransactionExpense(reportID); + unmarkReportRHPWidth(reportID, 'super-wide'); } // Persist the current search context so prev/next navigation arrows @@ -644,7 +644,7 @@ function Search({ return; } - markReportIDAsExpense(reportID); + markReportRHPWidth(reportID, 'wide'); if (isTransactionItem && transactionPreviewData) { setOptimisticDataForTransactionThreadPreview(transactionItem, transactionPreviewData, transactionItem?.reportAction?.childReportID); @@ -657,10 +657,9 @@ function Search({ requestAnimationFrame(() => Navigation.navigate(route)); }, [ - markReportIDAsExpense, + markReportRHPWidth, handleSearch, - markReportIDAsMultiTransactionExpense, - unmarkReportIDAsMultiTransactionExpense, + unmarkReportRHPWidth, introSelected, betas, isSelfTourViewed, diff --git a/src/components/WideRHPContextProvider/default.ts b/src/components/WideRHPContextProvider/default.ts index ab34f0466ece..92960e90e646 100644 --- a/src/components/WideRHPContextProvider/default.ts +++ b/src/components/WideRHPContextProvider/default.ts @@ -12,15 +12,11 @@ const defaultWideRHPStateContextValue: WideRHPStateContextType = { }; const defaultWideRHPActionsContextValue: WideRHPActionsContextType = { - showWideRHPVersion: () => {}, - showSuperWideRHPVersion: () => {}, - removeWideRHPRouteKey: () => {}, - removeSuperWideRHPRouteKey: () => {}, - markReportIDAsExpense: () => {}, - markReportIDAsMultiTransactionExpense: () => {}, - unmarkReportIDAsMultiTransactionExpense: () => {}, - isReportIDMarkedAsExpense: () => false, - isReportIDMarkedAsMultiTransactionExpense: () => false, + setRHPWidth: () => {}, + removeRHPRouteKey: () => {}, + markReportRHPWidth: () => {}, + unmarkReportRHPWidth: () => {}, + getReportRHPWidthHint: () => undefined, syncRHPKeys: () => {}, clearWideRHPKeys: () => {}, setIsWideRHPClosing: () => {}, diff --git a/src/components/WideRHPContextProvider/index.tsx b/src/components/WideRHPContextProvider/index.tsx index 66c5426bbc37..1e6c98b455b7 100644 --- a/src/components/WideRHPContextProvider/index.tsx +++ b/src/components/WideRHPContextProvider/index.tsx @@ -21,7 +21,7 @@ import React, {createContext, useCallback, useContext, useEffect, useRef, useSta // eslint-disable-next-line no-restricted-imports import {Animated, Dimensions} from 'react-native'; -import type {WideRHPActionsContextType, WideRHPStateContextType} from './types'; +import type {RHPWidth, RHPWidthHint, WideRHPActionsContextType, WideRHPStateContextType} from './types'; import {defaultWideRHPActionsContextValue, defaultWideRHPStateContextValue} from './default'; import getIsRHPDisplayedBelow from './getIsRHPDisplayedBelow'; @@ -81,7 +81,7 @@ function showWideRHPRoute(route: NavigationRoute, setAllRHPRouteKeys: React.Disp // Function to remove a Wide/Super Wide RHP route key to the array including wide/super wide RHP route keys function removeWideRHPRoute(route: NavigationRoute, setAllRHPRouteKeys: React.Dispatch>) { if (!route.key) { - console.error(`The route passed to removeWideRHPRouteKey should have the "key" property defined.`); + console.error(`The route passed to removeWideRHPRoute should have the "key" property defined.`); return; } @@ -113,11 +113,12 @@ function WideRHPContextProvider({children}: React.PropsWithChildren) { const [allSuperWideRHPRouteKeys, setAllSuperWideRHPRouteKeys] = useState([]); const [superWideRHPRouteKeys, setSuperWideRHPRouteKeys] = useState([]); - // Report IDs that should be displayed in Wide/Super Wide RHP - const [expenseReportIDs, setExpenseReportIDs] = useState>(new Set()); - const [multiTransactionExpenseReportIDs, setMultiTransactionExpenseReportIDs] = useState>(new Set()); + // A reportID maps to at most one hint, making "wide vs super-wide" structurally mutually exclusive. + const [reportRHPWidthHints, setReportRHPWidthHints] = useState>(() => new Map()); - const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {selector: expenseReportSelector}); + const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, { + selector: expenseReportSelector, + }); const isWideRHPClosingRef = useRef(false); const isSuperWideRHPClosingRef = useRef(false); @@ -193,96 +194,76 @@ function WideRHPContextProvider({children}: React.PropsWithChildren) { const shouldRenderTertiaryOverlay = useShouldRenderOverlay(isRHPFocused && isWideRHPBelow && isSuperWideRHPBelow, thirdOverlayProgress); /** - * Removes a route from the super wide RHP route keys list, disabling wide RHP display for that route. - */ - const removeSuperWideRHPRouteKey = (route: NavigationRoute) => removeWideRHPRoute(route, setAllSuperWideRHPRouteKeys); - - /** - * Removes a route from the wide RHP route keys list, disabling wide RHP display for that route. - */ - const removeWideRHPRouteKey = (route: NavigationRoute) => removeWideRHPRoute(route, setAllWideRHPRouteKeys); - - /** - * Adds a route to the wide RHP route keys list, enabling wide RHP display for that route. - */ - const showWideRHPVersion = (route: NavigationRoute) => { - removeSuperWideRHPRouteKey(route); - showWideRHPRoute(route, setAllWideRHPRouteKeys); - }; - - /** - * Adds a route to the super wide RHP route keys list, enabling super wide RHP display for that route. + * Removes the route from both wide and super-wide sets. Used on screen unmount. */ - const showSuperWideRHPVersion = (route: NavigationRoute) => { - removeWideRHPRouteKey(route); - showWideRHPRoute(route, setAllSuperWideRHPRouteKeys); + const removeRHPRouteKey = (route: NavigationRoute) => { + removeWideRHPRoute(route, setAllSuperWideRHPRouteKeys); + removeWideRHPRoute(route, setAllWideRHPRouteKeys); }; /** - * Marks a report ID as an expense report, adding it to the expense reports set. - * This enables optimistic wide RHP display for expense reports. - * It helps us open expense as wide, before it fully loads. + * Single entry point for setting a route's RHP width. Registrations are mutually exclusive — the + * route lives in at most one of {wide, super-wide} sets at any time (or neither, for 'narrow'). */ - const markReportIDAsExpense = (reportID?: string) => { - if (!reportID) { + const setRHPWidth = (route: NavigationRoute, width: RHPWidth) => { + if (width === 'super-wide') { + removeWideRHPRoute(route, setAllWideRHPRouteKeys); + showWideRHPRoute(route, setAllSuperWideRHPRouteKeys); return; } - const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]; - const isInvoice = report?.type === CONST.REPORT.TYPE.INVOICE; - const isTask = report?.type === CONST.REPORT.TYPE.TASK; - if (isInvoice || isTask) { + if (width === 'wide') { + removeWideRHPRoute(route, setAllSuperWideRHPRouteKeys); + showWideRHPRoute(route, setAllWideRHPRouteKeys); return; } - setExpenseReportIDs((prev) => { - const newSet = new Set(prev); - newSet.add(reportID); - return newSet; - }); - }; - - /** - * Checks if a report ID is marked as an expense report. - * Used to determine if wide RHP should be displayed optimistically. - * It helps us open expense as wide, before it fully loads. - */ - const isReportIDMarkedAsExpense = (reportID: string) => { - return expenseReportIDs.has(reportID); + removeWideRHPRoute(route, setAllSuperWideRHPRouteKeys); + removeWideRHPRoute(route, setAllWideRHPRouteKeys); }; /** - * Marks a report ID as a multi-transaction expense report, adding it to the expense reports set. - * This enables optimistic super wide RHP display for expense reports. - * It helps us open expense as super wide, before it fully loads. + * Sets an optimistic width hint for a reportID before its screen renders, so the right width is + * registered on first paint. Invoices and tasks are excluded from the 'wide' hint. */ - const markReportIDAsMultiTransactionExpense = (reportID: string) => { - setMultiTransactionExpenseReportIDs((prev) => { - const newSet = new Set(prev); - newSet.add(reportID); - return newSet; + const markReportRHPWidth = (reportID: string | undefined, width: RHPWidthHint) => { + if (!reportID) { + return; + } + if (width === 'wide') { + const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]; + if (report?.type === CONST.REPORT.TYPE.INVOICE || report?.type === CONST.REPORT.TYPE.TASK) { + return; + } + } + setReportRHPWidthHints((prev) => { + if (prev.get(reportID) === width) { + return prev; + } + const next = new Map(prev); + next.set(reportID, width); + return next; }); }; /** - * Removes a report ID from the multi-transaction expense reports set. - * This disables optimistic super wide RHP display for that specific report - * (e.g., when transactions are deleted or report no longer qualifies as multi-transaction) + * Clears the optimistic width hint for a reportID. Pass `width` to clear only when it matches the + * current hint; omit to clear unconditionally. Called when a report no longer qualifies for a hint. */ - const unmarkReportIDAsMultiTransactionExpense = (reportID: string) => { - setMultiTransactionExpenseReportIDs((prev) => { - const newSet = new Set(prev); - newSet.delete(reportID); - return newSet; + const unmarkReportRHPWidth = (reportID: string, width?: RHPWidthHint) => { + setReportRHPWidthHints((prev) => { + const current = prev.get(reportID); + if (current === undefined) { + return prev; + } + if (width !== undefined && current !== width) { + return prev; + } + const next = new Map(prev); + next.delete(reportID); + return next; }); }; - /** - * Checks if a report ID is marked as a multi-transaction expense report. - * Used to determine if super wide RHP should be displayed optimistically. - * It helps us open expense as super wide, before it fully loads. - */ - const isReportIDMarkedAsMultiTransactionExpense = (reportID: string) => { - return multiTransactionExpenseReportIDs.has(reportID); - }; + const getReportRHPWidthHint = (reportID: string): RHPWidthHint | undefined => reportRHPWidthHints.get(reportID); /** * Effect that handles responsive RHP width calculation when window dimensions change. @@ -326,16 +307,12 @@ function WideRHPContextProvider({children}: React.PropsWithChildren) { // Because of the React Compiler we don't need to memoize it manually // eslint-disable-next-line react/jsx-no-constructed-context-values - const actionsValue = { - showWideRHPVersion, - showSuperWideRHPVersion, - removeWideRHPRouteKey, - removeSuperWideRHPRouteKey, - markReportIDAsExpense, - markReportIDAsMultiTransactionExpense, - unmarkReportIDAsMultiTransactionExpense, - isReportIDMarkedAsExpense, - isReportIDMarkedAsMultiTransactionExpense, + const actionsValue: WideRHPActionsContextType = { + setRHPWidth, + removeRHPRouteKey, + markReportRHPWidth, + unmarkReportRHPWidth, + getReportRHPWidthHint, syncRHPKeys, clearWideRHPKeys, setIsWideRHPClosing, @@ -373,3 +350,4 @@ export { useWideRHPState, useWideRHPActions, }; +export type {RHPWidth} from './types'; diff --git a/src/components/WideRHPContextProvider/types.ts b/src/components/WideRHPContextProvider/types.ts index 91e0ed9494a4..86e78c70e53e 100644 --- a/src/components/WideRHPContextProvider/types.ts +++ b/src/components/WideRHPContextProvider/types.ts @@ -1,5 +1,9 @@ import type {NavigationRoute} from '@libs/Navigation/types'; +type RHPWidth = 'narrow' | 'wide' | 'super-wide'; + +type RHPWidthHint = Exclude; + type WideRHPStateContextType = { // Route keys of screens that should be displayed in wide format wideRHPRouteKeys: string[]; @@ -27,32 +31,20 @@ type WideRHPStateContextType = { }; type WideRHPActionsContextType = { - // Show given route as in wide format - showWideRHPVersion: (route: NavigationRoute) => void; - - // Show given route as in super wide format - showSuperWideRHPVersion: (route: NavigationRoute) => void; - - // Remove given route from the array - removeWideRHPRouteKey: (route: NavigationRoute) => void; - - // Remove given route from the array - removeSuperWideRHPRouteKey: (route: NavigationRoute) => void; - - // Mark reportID as expense before condition check - markReportIDAsExpense: (reportID?: string) => void; + // Register the route at the given width. 'narrow' removes from both sets. + setRHPWidth: (route: NavigationRoute, width: RHPWidth) => void; - // Mark reportID as multi-transaction expense before condition check - markReportIDAsMultiTransactionExpense: (reportID: string) => void; + // Remove the route from both sets (used on screen unmount). + removeRHPRouteKey: (route: NavigationRoute) => void; - // Unmark reportID as multi-transaction expense before condition check - unmarkReportIDAsMultiTransactionExpense: (reportID: string) => void; + // Set an optimistic width hint for a reportID before navigation. + markReportRHPWidth: (reportID: string | undefined, width: RHPWidthHint) => void; - // Check if reportID is marked as expense - isReportIDMarkedAsExpense: (reportID: string) => boolean; + // Clear the hint(s) for a reportID. Pass `width` to clear only that one. + unmarkReportRHPWidth: (reportID: string, width?: RHPWidthHint) => void; - // Check if reportID is marked as multi-transaction expense - isReportIDMarkedAsMultiTransactionExpense: (reportID: string) => boolean; + // Read the optimistic width hint for a reportID. + getReportRHPWidthHint: (reportID: string) => RHPWidthHint | undefined; // Sync super wide and wide RHP keys with the visible RHP screens syncRHPKeys: () => void; @@ -67,4 +59,4 @@ type WideRHPActionsContextType = { setIsSuperWideRHPClosing: (isClosing: boolean) => void; }; -export type {WideRHPStateContextType, WideRHPActionsContextType}; +export type {RHPWidth, RHPWidthHint, WideRHPStateContextType, WideRHPActionsContextType}; diff --git a/src/components/WideRHPContextProvider/useRHPWidth/index.native.ts b/src/components/WideRHPContextProvider/useRHPWidth/index.native.ts new file mode 100644 index 000000000000..1d6b056e0b4c --- /dev/null +++ b/src/components/WideRHPContextProvider/useRHPWidth/index.native.ts @@ -0,0 +1,6 @@ +import type {RHPWidth} from '..'; + +// Wide/Super-Wide RHP is not displayed on native platforms. +const useRHPWidth: (width: RHPWidth) => void = () => {}; + +export default useRHPWidth; diff --git a/src/components/WideRHPContextProvider/useRHPWidth/index.ts b/src/components/WideRHPContextProvider/useRHPWidth/index.ts new file mode 100644 index 000000000000..9eb7cce50fc2 --- /dev/null +++ b/src/components/WideRHPContextProvider/useRHPWidth/index.ts @@ -0,0 +1,61 @@ +import {navigationRef} from '@libs/Navigation/Navigation'; + +import NAVIGATORS from '@src/NAVIGATORS'; + +import {useRoute} from '@react-navigation/native'; +import {useEffect} from 'react'; + +import type {RHPWidth} from '..'; + +import {expandedRHPProgress, useWideRHPActions} from '..'; + +function getWidthOrder(width: RHPWidth): number { + if (width === 'super-wide') { + return 2; + } + if (width === 'wide') { + return 1; + } + return 0; +} + +/** Sets a screen's RHP width. A per-report hint outranks the caller until the caller's own width catches up — so a pre-marked report opens at the right width without a loading-state flash. */ +function useRHPWidth(width: RHPWidth) { + const route = useRoute(); + const reportID = route.params && 'reportID' in route.params && typeof route.params.reportID === 'string' ? route.params.reportID : ''; + const {setRHPWidth, removeRHPRouteKey, getReportRHPWidthHint, unmarkReportRHPWidth} = useWideRHPActions(); + + const onClose = () => { + removeRHPRouteKey(route); + // Clear the one-shot hint on unmount so it can't pin the report wide on a later visit. + if (reportID) { + unmarkReportRHPWidth(reportID); + } + // When the RHP has been closed, expandedRHPProgress should be set to 0. + if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) { + expandedRHPProgress.setValue(0); + } + }; + + useEffect(() => () => onClose(), [onClose]); + + // Register the width; a higher hint outranks the caller so the screen opens pre-marked before its data loads. + useEffect(() => { + const hint = reportID ? getReportRHPWidthHint(reportID) : undefined; + const effectiveWidth: RHPWidth = hint && getWidthOrder(hint) > getWidthOrder(width) ? hint : width; + setRHPWidth(route, effectiveWidth); + }, [width, reportID, route, setRHPWidth, getReportRHPWidthHint]); + + // Clear the hint once the caller's width reaches it; onClose handles the never-reached case. + useEffect(() => { + if (!reportID) { + return; + } + const hint = getReportRHPWidthHint(reportID); + if (hint && getWidthOrder(width) >= getWidthOrder(hint)) { + unmarkReportRHPWidth(reportID, hint); + } + }, [width, reportID, getReportRHPWidthHint, unmarkReportRHPWidth]); +} + +export default useRHPWidth; diff --git a/src/components/WideRHPContextProvider/useShowSuperWideRHPVersion/index.native.ts b/src/components/WideRHPContextProvider/useShowSuperWideRHPVersion/index.native.ts deleted file mode 100644 index 837adaf502ca..000000000000 --- a/src/components/WideRHPContextProvider/useShowSuperWideRHPVersion/index.native.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Super Wide RHP is not displayed on native platforms -// eslint-disable-next-line @typescript-eslint/no-unused-vars -function useShowSuperWideRHPVersion(condition: boolean) {} - -export default useShowSuperWideRHPVersion; diff --git a/src/components/WideRHPContextProvider/useShowSuperWideRHPVersion/index.ts b/src/components/WideRHPContextProvider/useShowSuperWideRHPVersion/index.ts deleted file mode 100644 index e05ec483a8f3..000000000000 --- a/src/components/WideRHPContextProvider/useShowSuperWideRHPVersion/index.ts +++ /dev/null @@ -1,74 +0,0 @@ -import {navigationRef} from '@libs/Navigation/Navigation'; - -import NAVIGATORS from '@src/NAVIGATORS'; - -import {useRoute} from '@react-navigation/native'; -import {useCallback, useEffect} from 'react'; - -import {expandedRHPProgress, useWideRHPActions} from '..'; - -/** - * Hook that manages super wide RHP display for a screen based on condition or optimistic state. - * Automatically registers the route for super wide RHP when condition is met or report is marked as multi-transaction expense. - * Cleans up the route registration when the screen is removed. - * - * @param condition - Boolean condition determining if the screen should display as wide RHP - */ -function useShowSuperWideRHPVersion(condition: boolean) { - const route = useRoute(); - const reportID = route.params && 'reportID' in route.params && typeof route.params.reportID === 'string' ? route.params.reportID : ''; - const { - showWideRHPVersion, - showSuperWideRHPVersion, - removeWideRHPRouteKey, - unmarkReportIDAsMultiTransactionExpense, - removeSuperWideRHPRouteKey, - isReportIDMarkedAsExpense, - isReportIDMarkedAsMultiTransactionExpense, - } = useWideRHPActions(); - - const onSuperWideRHPClose = useCallback(() => { - removeWideRHPRouteKey(route); - removeSuperWideRHPRouteKey(route); - // When the RHP has been closed, expandedRHPProgress should be set to 0. - if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) { - expandedRHPProgress.setValue(0); - } - }, [removeSuperWideRHPRouteKey, removeWideRHPRouteKey, route]); - - /** - * Effect that sets up cleanup when the screen is unmounted. - */ - useEffect(() => () => onSuperWideRHPClose(), [onSuperWideRHPClose]); - - /** - * Effect that determines whether to show wide RHP based on condition or optimistic state. - * Shows wide RHP if either the condition is true OR the reportID is marked as an expense. - */ - useEffect(() => { - // Check if we should show wide RHP based on condition OR if reportID is in optimistic set - const isReportMultiTransactionExpense = reportID && isReportIDMarkedAsMultiTransactionExpense(reportID); - - if (condition || isReportMultiTransactionExpense) { - if (condition && isReportMultiTransactionExpense) { - unmarkReportIDAsMultiTransactionExpense(reportID); - } - - showSuperWideRHPVersion(route); - return; - } - - showWideRHPVersion(route); - }, [ - condition, - reportID, - isReportIDMarkedAsExpense, - route, - showWideRHPVersion, - showSuperWideRHPVersion, - isReportIDMarkedAsMultiTransactionExpense, - unmarkReportIDAsMultiTransactionExpense, - ]); -} - -export default useShowSuperWideRHPVersion; diff --git a/src/components/WideRHPContextProvider/useShowWideRHPVersion/index.native.ts b/src/components/WideRHPContextProvider/useShowWideRHPVersion/index.native.ts deleted file mode 100644 index d46a553f4de2..000000000000 --- a/src/components/WideRHPContextProvider/useShowWideRHPVersion/index.native.ts +++ /dev/null @@ -1,5 +0,0 @@ -// Wide RHP is not displayed on native platforms -// eslint-disable-next-line @typescript-eslint/no-unused-vars -function useShowWideRHPVersion(condition: boolean) {} - -export default useShowWideRHPVersion; diff --git a/src/components/WideRHPContextProvider/useShowWideRHPVersion/index.ts b/src/components/WideRHPContextProvider/useShowWideRHPVersion/index.ts deleted file mode 100644 index c6744f66fe1d..000000000000 --- a/src/components/WideRHPContextProvider/useShowWideRHPVersion/index.ts +++ /dev/null @@ -1,49 +0,0 @@ -import {navigationRef} from '@libs/Navigation/Navigation'; - -import NAVIGATORS from '@src/NAVIGATORS'; - -import {useRoute} from '@react-navigation/native'; -import {useCallback, useEffect} from 'react'; - -import {expandedRHPProgress, useWideRHPActions} from '..'; - -/** - * Hook that manages wide RHP display for a screen based on condition or optimistic state. - * Automatically registers the route for wide RHP when condition is met or report is marked as expense. - * Cleans up the route registration when the screen is removed. - * - * @param condition - Boolean condition determining if the screen should display as wide RHP - */ -function useShowWideRHPVersion(condition: boolean) { - const route = useRoute(); - const reportID = route.params && 'reportID' in route.params && typeof route.params.reportID === 'string' ? route.params.reportID : ''; - const {showWideRHPVersion, removeWideRHPRouteKey, isReportIDMarkedAsExpense} = useWideRHPActions(); - - const onWideRHPClose = useCallback(() => { - removeWideRHPRouteKey(route); - // When the RHP has been closed, expandedRHPProgress should be set to 0. - if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) { - expandedRHPProgress.setValue(0); - } - }, [removeWideRHPRouteKey, route]); - - /** - * Effect that sets up cleanup when the screen is unmounted. - */ - useEffect(() => () => onWideRHPClose(), [onWideRHPClose]); - - /** - * Effect that determines whether to show wide RHP based on condition or optimistic state. - * Shows wide RHP if either the condition is true OR the reportID is marked as an expense. - */ - useEffect(() => { - // Check if we should show wide RHP based on condition OR if reportID is in optimistic set - const shouldShow = condition || (reportID && isReportIDMarkedAsExpense(reportID)); - if (!shouldShow) { - return; - } - showWideRHPVersion(route); - }, [condition, reportID, isReportIDMarkedAsExpense, route, showWideRHPVersion]); -} - -export default useShowWideRHPVersion; diff --git a/src/hooks/useNavigateToTransactionThread.ts b/src/hooks/useNavigateToTransactionThread.ts index f381710f007a..1b5990418056 100644 --- a/src/hooks/useNavigateToTransactionThread.ts +++ b/src/hooks/useNavigateToTransactionThread.ts @@ -44,7 +44,7 @@ type NavigateToTransactionThreadParams = { * `siblingTransactionIDs` because the data sources differ per screen. */ function useNavigateToTransactionThread() { - const {markReportIDAsExpense} = useWideRHPActions(); + const {markReportRHPWidth} = useWideRHPActions(); const currentUserDetails = useCurrentUserPersonalDetails(); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); const [betas] = useOnyx(ONYXKEYS.BETAS); @@ -81,7 +81,7 @@ function useNavigateToTransactionThread() { // display prev/next arrows for navigation between expenses. setActiveTransactionIDs(siblingTransactionIDs).then(() => { if (reportIDToNavigate) { - markReportIDAsExpense(reportIDToNavigate); + markReportRHPWidth(reportIDToNavigate, 'wide'); } Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute(routeParams)); }); diff --git a/src/hooks/useNewTransactions.ts b/src/hooks/useNewTransactions.ts index 8fa695c49e05..6786b3d4ab94 100644 --- a/src/hooks/useNewTransactions.ts +++ b/src/hooks/useNewTransactions.ts @@ -2,12 +2,14 @@ import {deletePendingNewTransactionIDs} from '@libs/actions/IOU/PendingNewTransa import CONST from '@src/CONST'; import type {Transaction} from '@src/types/onyx'; -import {isEmptyObject} from '@src/types/utils/EmptyObject'; import {useEffect, useMemo, useRef} from 'react'; import usePrevious from './usePrevious'; +// Stable empty result so a "nothing new" return keeps a constant reference (no consumer re-render). +const EMPTY_TRANSACTIONS: Transaction[] = []; + /** * This hook returns new transactions that have been added since the last transactions update. * This hook should be used only in the context of highlighting the new transactions on the Report table view. @@ -15,6 +17,8 @@ import usePrevious from './usePrevious'; * When `pendingNewTransactionIDs` is provided, those transactions will be treated as new even on the * first load. This handles the case where a transaction was created before the component mounts * (e.g., submitting a tracked expense from Self DM to a workspace on Web). + * + * It marks a row "new" continuously, regardless of focus — the consumer gates when to show the highlight (e.g. only while the report is visible), keeping this hook free of layout concerns. */ function useNewTransactions( hasOnceLoadedReportActions: boolean | undefined, @@ -30,35 +34,37 @@ function useNewTransactions( const skipFirstTransactionsChange = useRef(!hasOnceLoadedReportActions); const newTransactions = useMemo(() => { - // If isFocused is not passed (=undefined) we will not return empty. - if (isFocused === false) { - return CONST.EMPTY_ARRAY as unknown as Transaction[]; - } + // Rail-flagged adds survive the remount the diff can't see. Truthy-only so an all-cleared tombstone rail falls through to the diff. + const activePendingTransactionIDs = pendingNewTransactionIDs ? Object.keys(pendingNewTransactionIDs).filter((id) => pendingNewTransactionIDs[id]) : []; + const railSet = new Set(activePendingTransactionIDs); + const railTransactions = + reportID && activePendingTransactionIDs.length && transactions?.length ? transactions.filter(({transactionID}) => railSet.has(transactionID)) : EMPTY_TRANSACTIONS; - if (transactions === undefined || prevTransactions === undefined || transactions.length <= prevTransactions.length) { - // When a transaction is submitted from another report (e.g., Self DM → workspace), it is - // already in the transactions list by the time this component mounts. - // So we use pendingNewTransactionIDs from report metadata to identify these transactions on first load. - if (isFocused && reportID && !isEmptyObject(pendingNewTransactionIDs) && transactions?.length) { - const pendingSet = new Set(Object.keys(pendingNewTransactionIDs)); - const pendingTransactions = transactions.filter(({transactionID}) => pendingSet.has(transactionID) && pendingNewTransactionIDs[transactionID]); - return pendingTransactions; + // Diff-detected adds the rail never flagged (e.g. a Pusher add). + let diffTransactions: Transaction[] = []; + if (transactions !== undefined && prevTransactions !== undefined && transactions.length > prevTransactions.length) { + if (skipFirstTransactionsChange.current) { + skipFirstTransactionsChange.current = false; + } else { + diffTransactions = transactions.filter((transaction) => !prevTransactions?.some((prevTransaction) => prevTransaction.transactionID === transaction.transactionID)); } - return CONST.EMPTY_ARRAY as unknown as Transaction[]; } - if (skipFirstTransactionsChange.current) { - skipFirstTransactionsChange.current = false; - return CONST.EMPTY_ARRAY as unknown as Transaction[]; + + // Union, rail first so newTransactions[0] (the scroll target) stays stable across a later add. + if (!railTransactions.length) { + return diffTransactions.length ? diffTransactions : EMPTY_TRANSACTIONS; } - return transactions.filter((transaction) => !prevTransactions?.some((prevTransaction) => prevTransaction.transactionID === transaction.transactionID)); + const extraDiff = diffTransactions.filter(({transactionID}) => !railSet.has(transactionID)); + return extraDiff.length ? [...railTransactions, ...extraDiff] : railTransactions; - // We don't need to recalculate on change of prevTransactions or pendingNewTransactionIDs as it will make the value + // We don't need to recalculate on change of prevTransactions as it will make the value // disappear quickly which will break the scroll and highlight on slower devices like mobile app. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [transactions, reportID, isFocused]); + }, [transactions, reportID, pendingNewTransactionIDs]); useEffect(() => { - if (!pendingNewTransactionIDs) { + // Only the focused consumer clears the rail, so a covered view can't clear the flag before the visible one highlights it. + if (isFocused === false || !pendingNewTransactionIDs) { return; } const pendingSet = new Set(Object.keys(pendingNewTransactionIDs)); @@ -74,7 +80,7 @@ function useNewTransactions( pendingTransactions.map((transaction) => transaction.transactionID), ); }, CONST.PENDING_TRANSACTION_DELETION_DELAY); - }, [pendingNewTransactionIDs, newTransactions, reportID]); + }, [isFocused, pendingNewTransactionIDs, newTransactions, reportID]); // In case when we have loaded the report, but there were no transactions in it, then we need to explicitly set skipFirstTransactionsChange to false, as it will be not set in the useMemo above. useEffect(() => { diff --git a/src/libs/actions/IOU/MoneyRequestBuilder.ts b/src/libs/actions/IOU/MoneyRequestBuilder.ts index 2cd5a8b197d2..20c0b4e15e26 100644 --- a/src/libs/actions/IOU/MoneyRequestBuilder.ts +++ b/src/libs/actions/IOU/MoneyRequestBuilder.ts @@ -30,6 +30,7 @@ import { isExpenseReport, isGroupChat, isInvoiceReport as isInvoiceReportReportUtils, + isMoneyRequestReport, isOneTransactionReport, isPolicyExpenseChat as isPolicyExpenseChatReportUtil, isSelfDM, @@ -668,6 +669,25 @@ function buildOnyxDataForMoneyRequest(moneyRequestParams: BuildOnyxDataForMoneyR }); } + // Flag for the highlight rail only when the add makes the report multi-tx (its table fresh-mounts with the tx present, so the diff misses it); never the first tx (0→1), which would leave a stale flag; no successData (races the mount). + const existingReportTransactions = iou.report?.reportID + ? getReportTransactions(iou.report.reportID).filter((reportTransaction) => reportTransaction.transactionID !== transaction.transactionID) + : []; + const addMakesReportMultiTransaction = + isMoneyRequestReport(iou.report) && existingReportTransactions.some((reportTransaction) => reportTransaction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE); + if (iou.report?.reportID && transaction.transactionID && !isSelfDMSplit && addMakesReportMultiTransaction) { + onyxData.optimisticData?.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${iou.report.reportID}`, + value: {pendingNewTransactionIDs: {[transaction.transactionID]: true}}, + }); + onyxData.failureData?.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${iou.report.reportID}`, + value: {pendingNewTransactionIDs: {[transaction.transactionID]: null}}, + }); + } + if (shouldGenerateTransactionThreadReport && !isSelfDMSplit && !isEmptyObject(transactionThreadCreatedReportAction)) { onyxData.optimisticData?.push({ onyxMethod: Onyx.METHOD.MERGE, @@ -1105,7 +1125,7 @@ function buildOnyxDataForMoneyRequest(moneyRequestParams: BuildOnyxDataForMoneyR }); if (violationsOnyxData) { - const reportTransactions = [...getReportTransactions(iou.report.reportID).filter((reportTransaction) => reportTransaction.transactionID !== transaction.transactionID), transaction]; + const reportTransactions = [...existingReportTransactions, transaction]; const shouldFixViolations = hasSubmissionBlockingViolationInReport( reportTransactions, transactionViolations, diff --git a/src/pages/Search/SearchMoneyRequestReportPage.tsx b/src/pages/Search/SearchMoneyRequestReportPage.tsx index 1232085d9d0c..2856303eb4da 100644 --- a/src/pages/Search/SearchMoneyRequestReportPage.tsx +++ b/src/pages/Search/SearchMoneyRequestReportPage.tsx @@ -3,7 +3,7 @@ import DragAndDropProvider from '@components/DragAndDrop/Provider'; import MoneyRequestReportView from '@components/MoneyRequestReportView/MoneyRequestReportView'; import ScreenWrapper from '@components/ScreenWrapper'; import {useSearchResultsContext} from '@components/Search/SearchContext'; -import useShowSuperWideRHPVersion from '@components/WideRHPContextProvider/useShowSuperWideRHPVersion'; +import useRHPWidth from '@components/WideRHPContextProvider/useRHPWidth'; import WideRHPOverlayWrapper from '@components/WideRHPOverlayWrapper'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; @@ -181,7 +181,7 @@ function SearchMoneyRequestReportPage({route}: SearchMoneyRequestPageProps) { // If there is more than one transaction, display the report in Super Wide RHP, otherwise it will be shown in Wide RHP const shouldShowSuperWideRHP = visibleTransactions.length > 1; - useShowSuperWideRHPVersion(shouldShowSuperWideRHP); + useRHPWidth(shouldShowSuperWideRHP ? 'super-wide' : 'wide'); // Tracks initial mount to ensure openReport is called once for multi-transaction reports const isInitialMountRef = useRef(true); diff --git a/src/pages/home/RecentlyAddedSection/index.tsx b/src/pages/home/RecentlyAddedSection/index.tsx index cf392bc04c0f..38de24753ccd 100644 --- a/src/pages/home/RecentlyAddedSection/index.tsx +++ b/src/pages/home/RecentlyAddedSection/index.tsx @@ -51,7 +51,7 @@ function RecentlyAddedSection() { // Once the screen blurs (e.g. after opening an expense), we hide the preview instead of leaving it floating over the RHP. const isFocused = useIsFocused(); const icons = useMemoizedLazyExpensifyIcons(['Receipt']); - const {markReportIDAsExpense} = useWideRHPActions(); + const {markReportRHPWidth} = useWideRHPActions(); const {email: currentUserEmail, accountID: currentUserAccountID} = useCurrentUserPersonalDetails(); const isAnonymousUser = useIsAnonymousUser(); const [betas] = useOnyx(ONYXKEYS.BETAS); @@ -88,7 +88,7 @@ function RecentlyAddedSection() { // arrows are available. Marking the report as an expense lets the RHP open wide immediately, before its // data loads, instead of flickering from narrow to wide. setActiveTransactionIDs(siblingTransactionIDs, siblingDescriptorsByTransactionID).then(() => { - markReportIDAsExpense(reportID); + markReportRHPWidth(reportID, 'wide'); Navigation.navigate(ROUTES.SEARCH_REPORT.getRoute({reportID, backTo: ROUTES.HOME})); }); }; diff --git a/src/pages/inbox/WideRHPReceiptPanel.tsx b/src/pages/inbox/WideRHPReceiptPanel.tsx index b6b9d47fcad4..1c936abeda2f 100644 --- a/src/pages/inbox/WideRHPReceiptPanel.tsx +++ b/src/pages/inbox/WideRHPReceiptPanel.tsx @@ -1,6 +1,7 @@ import MoneyRequestReceiptView from '@components/ReportActionItem/MoneyRequestReceiptView'; import ScrollView from '@components/ScrollView'; -import useShowWideRHPVersion from '@components/WideRHPContextProvider/useShowWideRHPVersion'; +import type {RHPWidth} from '@components/WideRHPContextProvider'; +import useRHPWidth from '@components/WideRHPContextProvider/useRHPWidth'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; @@ -62,17 +63,24 @@ function WideRHPReceiptPanelGate() { const [transactionThreadReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${transactionThreadReportID}`); const isMoneyRequestOrInvoiceReport = isMoneyRequestReport(report) || isInvoiceReport(report); - const shouldDisplayMoneyRequestActionsList = isMoneyRequestOrInvoiceReport && shouldDisplayReportTableView(report, visibleTransactions ?? []); + const hasMultipleTransactions = (visibleTransactions?.length ?? 0) > 1; + const isConfirmedMultiTransactionReport = isMoneyRequestOrInvoiceReport && hasMultipleTransactions && shouldDisplayReportTableView(report, visibleTransactions ?? []); const shouldShowWideRHP = - !shouldDisplayMoneyRequestActionsList && + !isConfirmedMultiTransactionReport && (isTransactionThread(parentReportAction) || parentReportAction?.childType === CONST.REPORT.TYPE.EXPENSE || parentReportAction?.childType === CONST.REPORT.TYPE.IOU || report?.type === CONST.REPORT.TYPE.EXPENSE || report?.type === CONST.REPORT.TYPE.IOU); - useShowWideRHPVersion(shouldShowWideRHP); + let rhpWidth: RHPWidth = 'narrow'; + if (isConfirmedMultiTransactionReport) { + rhpWidth = 'super-wide'; + } else if (shouldShowWideRHP) { + rhpWidth = 'wide'; + } + useRHPWidth(rhpWidth); if (!shouldShowWideRHP) { return null; diff --git a/tests/actions/IOU/GetMoneyRequestInformationTest.ts b/tests/actions/IOU/GetMoneyRequestInformationTest.ts index 431a95fb3f8e..ed8bea563ef2 100644 --- a/tests/actions/IOU/GetMoneyRequestInformationTest.ts +++ b/tests/actions/IOU/GetMoneyRequestInformationTest.ts @@ -214,4 +214,17 @@ describe('getMoneyRequestInformation', () => { expect(tagEntry?.value).toEqual({[TAG_LIST]: [TAG_NAME]}); }); }); + + describe('pendingNewTransactionIDs metadata rail', () => { + // Only the 0→1 negative is testable here (the resolved report has no existing txs); the >= 1 positive path lives in the useNewTransactions consumer tests. + it('does NOT flag the first transaction of a report (no stale flag to re-highlight the original on a later add)', () => { + const result = getMoneyRequestInformation(baseParams); + const expectedKey = `${ONYXKEYS.COLLECTION.REPORT_METADATA}${result.iouReport.reportID}`; + const newTxID = result.transaction.transactionID; + + expect(result.onyxData.optimisticData ?? []).not.toEqual( + expect.arrayContaining([expect.objectContaining({key: expectedKey, value: expect.objectContaining({pendingNewTransactionIDs: expect.objectContaining({[newTxID]: true})})})]), + ); + }); + }); }); diff --git a/tests/unit/useNewTransactionsTest.ts b/tests/unit/useNewTransactionsTest.ts index 305ac372fe80..0dd5cc99519f 100644 --- a/tests/unit/useNewTransactionsTest.ts +++ b/tests/unit/useNewTransactionsTest.ts @@ -2,8 +2,14 @@ import {renderHook} from '@testing-library/react-native'; import useNewTransactions from '@hooks/useNewTransactions'; +import CONST from '@src/CONST'; import type {Transaction} from '@src/types/onyx'; +// Keep the rail-cleanup timer from touching Onyx; tests assert on whether it is scheduled, not on the merge itself. +jest.mock('@libs/actions/IOU/PendingNewTransactions', () => ({ + deletePendingNewTransactionIDs: jest.fn(), +})); + // We need to mock requestAnimationFrame to mimic long Onyx merge overhead jest.spyOn(global, 'requestAnimationFrame').mockImplementation((callback: FrameRequestCallback) => { setTimeout(() => { @@ -19,10 +25,31 @@ const delay = (ms: number) => describe('useNewTransactions with empty cache', () => { const transactionsAlreadyInReport = [ - {transactionID: '2', amount: 200, created: '2023-10-02', currency: 'USD', reportID: 'report1', merchant: ''}, - {transactionID: '3', amount: 300, created: '2023-10-03', currency: 'USD', reportID: 'report1', merchant: ''}, + { + transactionID: '2', + amount: 200, + created: '2023-10-02', + currency: 'USD', + reportID: 'report1', + merchant: '', + }, + { + transactionID: '3', + amount: 300, + created: '2023-10-03', + currency: 'USD', + reportID: 'report1', + merchant: '', + }, ]; - const newTransaction = {transactionID: '1', amount: 100, created: '2023-10-01T00:00:00Z', currency: 'USD', reportID: 'report1', merchant: ''}; + const newTransaction = { + transactionID: '1', + amount: 100, + created: '2023-10-01T00:00:00Z', + currency: 'USD', + reportID: 'report1', + merchant: '', + }; it("doesn't return new transactions when no transactions are added", () => { // 1. Report and transactions data is not loaded yet @@ -174,10 +201,31 @@ describe('useNewTransactions with empty cache', () => { describe('useNewTransactions with transactions in cache', () => { const transactionsAlreadyInReport = [ - {transactionID: '2', amount: 200, created: '2023-10-02', currency: 'USD', reportID: 'report1', merchant: ''}, - {transactionID: '3', amount: 300, created: '2023-10-03', currency: 'USD', reportID: 'report1', merchant: ''}, + { + transactionID: '2', + amount: 200, + created: '2023-10-02', + currency: 'USD', + reportID: 'report1', + merchant: '', + }, + { + transactionID: '3', + amount: 300, + created: '2023-10-03', + currency: 'USD', + reportID: 'report1', + merchant: '', + }, ]; - const newTransaction = {transactionID: '1', amount: 100, created: '2023-10-01T00:00:00Z', currency: 'USD', reportID: 'report1', merchant: ''}; + const newTransaction = { + transactionID: '1', + amount: 100, + created: '2023-10-01T00:00:00Z', + currency: 'USD', + reportID: 'report1', + merchant: '', + }; it("doesn't return new transactions when no transactions are added", () => { // 1. Report and transactions data is loaded from Onyx @@ -298,10 +346,31 @@ describe('useNewTransactions with transactions in cache', () => { describe('useNewTransactions with pendingNewTransactionIDs (cross-navigation)', () => { const transactionsAlreadyInReport = [ - {transactionID: '2', amount: 200, created: '2023-10-02', currency: 'USD', reportID: 'report1', merchant: ''}, - {transactionID: '3', amount: 300, created: '2023-10-03', currency: 'USD', reportID: 'report1', merchant: ''}, + { + transactionID: '2', + amount: 200, + created: '2023-10-02', + currency: 'USD', + reportID: 'report1', + merchant: '', + }, + { + transactionID: '3', + amount: 300, + created: '2023-10-03', + currency: 'USD', + reportID: 'report1', + merchant: '', + }, ]; - const newTransaction = {transactionID: '1', amount: 100, created: '2023-10-01T00:00:00Z', currency: 'USD', reportID: 'report1', merchant: ''}; + const newTransaction = { + transactionID: '1', + amount: 100, + created: '2023-10-01T00:00:00Z', + currency: 'USD', + reportID: 'report1', + merchant: '', + }; it('returns pending new transactions on first load when submitted from another report', () => { // Simulates: user submitted expense from Self DM to workspace, then navigated to workspace chat. @@ -309,7 +378,12 @@ describe('useNewTransactions with pendingNewTransactionIDs (cross-navigation)', // 1. Component mounts, report not loaded yet, but transaction is already in Onyx const {rerender, result} = renderHook< Transaction[], - {transactions: Transaction[]; hasOnceLoadedReportActions: boolean; pendingNewTransactionIDs: Record | undefined; isFocused?: boolean} + { + transactions: Transaction[]; + hasOnceLoadedReportActions: boolean; + pendingNewTransactionIDs: Record | undefined; + isFocused?: boolean; + } >((props) => useNewTransactions(props.hasOnceLoadedReportActions, props.transactions, props.pendingNewTransactionIDs, '1', props.isFocused), { initialProps: { hasOnceLoadedReportActions: false, @@ -344,7 +418,11 @@ describe('useNewTransactions with pendingNewTransactionIDs (cross-navigation)', // Normal navigation to a report (no cross-navigation pending IDs) const {rerender, result} = renderHook< Transaction[], - {transactions: Transaction[]; hasOnceLoadedReportActions: boolean; pendingNewTransactionIDs: Record | undefined} + { + transactions: Transaction[]; + hasOnceLoadedReportActions: boolean; + pendingNewTransactionIDs: Record | undefined; + } >((props) => useNewTransactions(props.hasOnceLoadedReportActions, props.transactions, props.pendingNewTransactionIDs), { initialProps: { hasOnceLoadedReportActions: false, @@ -360,6 +438,308 @@ describe('useNewTransactions with pendingNewTransactionIDs (cross-navigation)', }); expect(result.current).toEqual([]); }); + + it('recomputes when only pendingNewTransactionIDs changes (stable transactions reference)', () => { + const stableTransactions = [...transactionsAlreadyInReport, newTransaction]; + + const {rerender, result} = renderHook< + Transaction[], + { + transactions: Transaction[]; + pendingNewTransactionIDs: Record | undefined; + } + >((props) => useNewTransactions(true, props.transactions, props.pendingNewTransactionIDs, 'report1', true), { + initialProps: { + transactions: stableTransactions, + pendingNewTransactionIDs: undefined, + }, + }); + expect(result.current).toEqual([]); + + rerender({ + transactions: stableTransactions, + pendingNewTransactionIDs: undefined, + }); + expect(result.current).toEqual([]); + + rerender({ + transactions: stableTransactions, + pendingNewTransactionIDs: {[newTransaction.transactionID]: true}, + }); + expect(result.current).toEqual([newTransaction]); + }); + + it('highlights the duplicate when the table view mounts post-optimistic add and pendingNewTransactionIDs arrives a few renders later', () => { + const [originalTx] = transactionsAlreadyInReport; + const duplicateTx = {...newTransaction, pendingAction: 'add' as const}; + + const {rerender, result} = renderHook< + Transaction[], + { + transactions: Transaction[]; + hasOnceLoadedReportActions: boolean; + pendingNewTransactionIDs: Record | undefined; + isFocused?: boolean; + } + >((props) => useNewTransactions(props.hasOnceLoadedReportActions, props.transactions, props.pendingNewTransactionIDs, 'report1', props.isFocused), { + initialProps: { + hasOnceLoadedReportActions: true, + transactions: [originalTx, duplicateTx], + pendingNewTransactionIDs: undefined, + isFocused: true, + }, + }); + expect(result.current).toEqual([]); + + rerender({ + hasOnceLoadedReportActions: true, + transactions: [originalTx, duplicateTx], + pendingNewTransactionIDs: undefined, + isFocused: true, + }); + expect(result.current).toEqual([]); + + rerender({ + hasOnceLoadedReportActions: true, + transactions: [originalTx, duplicateTx], + pendingNewTransactionIDs: {[duplicateTx.transactionID]: true}, + isFocused: true, + }); + expect(result.current).toEqual([duplicateTx]); + + rerender({ + hasOnceLoadedReportActions: true, + transactions: [originalTx, duplicateTx], + pendingNewTransactionIDs: undefined, + isFocused: true, + }); + expect(result.current).toEqual([]); + }); + + it('falls through to the diff when the rail holds only cleared tombstones', () => { + // A {clearedID: null} rail is not "active": a later add (e.g. Pusher/import) without its own flag must still be caught by the diff. + const [existingTx] = transactionsAlreadyInReport; + const pusherTx = newTransaction; + const {rerender, result} = renderHook< + Transaction[], + { + transactions: Transaction[]; + pendingNewTransactionIDs: Record; + } + >((props) => useNewTransactions(true, props.transactions, props.pendingNewTransactionIDs, 'report1', true), { + initialProps: { + transactions: [existingTx], + pendingNewTransactionIDs: {[existingTx.transactionID]: null}, + }, + }); + expect(result.current).toEqual([]); + + rerender({ + transactions: [existingTx, pusherTx], + pendingNewTransactionIDs: {[existingTx.transactionID]: null}, + }); + expect(result.current).toEqual([pusherTx]); + }); + + it('unions a rail-flagged add with a concurrent unflagged diff add (Pusher landing inside the cleanup delay)', () => { + // A rail flag (txB) must not make the branch swallow a concurrent unflagged diff add (txC) — both highlight, txB first. + const [existingTx] = transactionsAlreadyInReport; + const txB = { + transactionID: 'B', + amount: 100, + created: '2023-10-04', + currency: 'USD', + reportID: 'report1', + merchant: '', + }; + const txC = { + transactionID: 'C', + amount: 100, + created: '2023-10-05', + currency: 'USD', + reportID: 'report1', + merchant: '', + }; + const {rerender, result} = renderHook< + Transaction[], + { + transactions: Transaction[]; + pendingNewTransactionIDs: Record; + } + >((props) => useNewTransactions(true, props.transactions, props.pendingNewTransactionIDs, 'report1', true), { + initialProps: { + transactions: [existingTx], + pendingNewTransactionIDs: {}, + }, + }); + expect(result.current).toEqual([]); + + rerender({ + transactions: [existingTx, txB], + pendingNewTransactionIDs: {B: true}, + }); + expect(result.current).toEqual([txB]); + + rerender({ + transactions: [existingTx, txB, txC], + pendingNewTransactionIDs: {B: true}, + }); + expect(result.current).toEqual([txB, txC]); + expect(result.current.at(0)).toBe(txB); + }); +}); + +describe('useNewTransactions with an unfocused report', () => { + const transactionsAlreadyInReport = [ + { + transactionID: '2', + amount: 200, + created: '2023-10-02', + currency: 'USD', + reportID: 'report1', + merchant: '', + }, + { + transactionID: '3', + amount: 300, + created: '2023-10-03', + currency: 'USD', + reportID: 'report1', + merchant: '', + }, + ]; + const newTransaction = { + transactionID: '1', + amount: 100, + created: '2023-10-01T00:00:00Z', + currency: 'USD', + reportID: 'report1', + merchant: '', + }; + + it('returns newly added transactions even when the report is unfocused', () => { + // The diff emits regardless of focus — the consumer gates visibility, not this hook. + const {rerender, result} = renderHook( + (props) => useNewTransactions(true, props.transactions, undefined, 'report1', props.isFocused), + { + initialProps: { + transactions: transactionsAlreadyInReport, + isFocused: false, + }, + }, + ); + expect(result.current).toEqual([]); + + rerender({ + transactions: [...transactionsAlreadyInReport, newTransaction], + isFocused: false, + }); + expect(result.current).toEqual([newTransaction]); + }); + + it('emits a flagged add regardless of focus (the consumer gates visibility)', () => { + // The hook marks the row new continuously; the report table gates the highlight on visibility, not this hook. + const allTransactions = [...transactionsAlreadyInReport, newTransaction]; + const {result} = renderHook(() => useNewTransactions(true, allTransactions, {[newTransaction.transactionID]: true}, 'report1', false)); + expect(result.current).toEqual([newTransaction]); + }); + + it('keeps an earlier pending transaction highlighted continuously when a second one is added', () => { + // Adding a later transaction must not drop the earlier one out of the result and back in — that flicker would re-fire its highlight animation. + const txB = { + transactionID: 'B', + amount: 100, + created: '2023-10-04', + currency: 'USD', + reportID: 'report1', + merchant: '', + }; + const txC = { + transactionID: 'C', + amount: 100, + created: '2023-10-05', + currency: 'USD', + reportID: 'report1', + merchant: '', + }; + const {rerender, result} = renderHook< + Transaction[], + { + transactions: Transaction[]; + pendingNewTransactionIDs: Record; + } + >((props) => useNewTransactions(true, props.transactions, props.pendingNewTransactionIDs, 'report1', true), { + initialProps: { + transactions: transactionsAlreadyInReport, + pendingNewTransactionIDs: {}, + }, + }); + expect(result.current).toEqual([]); + + rerender({ + transactions: [...transactionsAlreadyInReport, txB], + pendingNewTransactionIDs: {B: true}, + }); + expect(result.current).toEqual([txB]); + + rerender({ + transactions: [...transactionsAlreadyInReport, txB], + pendingNewTransactionIDs: {B: true}, + }); + expect(result.current).toEqual([txB]); + + rerender({ + transactions: [...transactionsAlreadyInReport, txB, txC], + pendingNewTransactionIDs: {B: true, C: true}, + }); + expect(result.current).toEqual(expect.arrayContaining([txB, txC])); + expect(result.current).toHaveLength(2); + }); + + it('schedules the rail cleanup only from a focused consumer', () => { + // Narrow: only a focused consumer schedules the cleanup; an unfocused one must not clear a flag a later focused mount needs. + const setTimeoutSpy = jest.spyOn(global, 'setTimeout'); + const txD = { + transactionID: 'D', + amount: 100, + created: '2023-10-09', + currency: 'USD', + reportID: 'report1', + merchant: '', + }; + const scheduledCleanups = () => setTimeoutSpy.mock.calls.filter(([, ms]) => ms === CONST.PENDING_TRANSACTION_DELETION_DELAY).length; + + const {rerender} = renderHook< + Transaction[], + { + transactions: Transaction[]; + pendingNewTransactionIDs: Record; + isFocused: boolean; + } + >((props) => useNewTransactions(true, props.transactions, props.pendingNewTransactionIDs, 'report1', props.isFocused), { + initialProps: { + transactions: transactionsAlreadyInReport, + pendingNewTransactionIDs: {D: true}, + isFocused: false, + }, + }); + + rerender({ + transactions: [...transactionsAlreadyInReport, txD], + pendingNewTransactionIDs: {D: true}, + isFocused: false, + }); + expect(scheduledCleanups()).toBe(0); + + rerender({ + transactions: [...transactionsAlreadyInReport, txD], + pendingNewTransactionIDs: {D: true}, + isFocused: true, + }); + expect(scheduledCleanups()).toBeGreaterThan(0); + + setTimeoutSpy.mockRestore(); + }); }); afterAll(() => {