From 0997af17d0317e3669f6ce29ff78a31aed248708 Mon Sep 17 00:00:00 2001 From: TaduJR Date: Fri, 26 Jun 2026 08:23:30 +0300 Subject: [PATCH 01/11] fix: Reports - Highlight animation is visible on added expense after duplication --- ...neyRequestReportTransactionsNavigation.tsx | 10 +- .../ListItem/TransactionGroupListExpanded.tsx | 4 +- src/components/Search/index.tsx | 13 +- .../WideRHPContextProvider/default.ts | 14 +- .../WideRHPContextProvider/index.tsx | 144 ++++++++---------- .../WideRHPContextProvider/types.ts | 38 ++--- .../useRHPWidth/index.native.ts | 6 + .../useRHPWidth/index.ts | 60 ++++++++ .../index.native.ts | 5 - .../useShowSuperWideRHPVersion/index.ts | 71 --------- .../useShowWideRHPVersion/index.native.ts | 5 - .../useShowWideRHPVersion/index.ts | 46 ------ src/hooks/useNavigateToTransactionThread.ts | 4 +- src/hooks/useNewTransactions.ts | 20 +-- src/libs/actions/IOU/MoneyRequestBuilder.ts | 19 +++ .../Search/SearchMoneyRequestReportPage.tsx | 4 +- src/pages/home/RecentlyAddedSection/index.tsx | 4 +- src/pages/inbox/WideRHPReceiptPanel.tsx | 11 +- .../IOU/GetMoneyRequestInformationTest.ts | 53 +++++++ tests/unit/useNewTransactionsTest.ts | 122 +++++++++++++++ 20 files changed, 375 insertions(+), 278 deletions(-) create mode 100644 src/components/WideRHPContextProvider/useRHPWidth/index.native.ts create mode 100644 src/components/WideRHPContextProvider/useRHPWidth/index.ts delete mode 100644 src/components/WideRHPContextProvider/useShowSuperWideRHPVersion/index.native.ts delete mode 100644 src/components/WideRHPContextProvider/useShowSuperWideRHPVersion/index.ts delete mode 100644 src/components/WideRHPContextProvider/useShowWideRHPVersion/index.native.ts delete mode 100644 src/components/WideRHPContextProvider/useShowWideRHPVersion/index.ts diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx index 648c5f79c0e1..3c1dcaf4f686 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionsNavigation.tsx @@ -41,7 +41,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) { @@ -135,7 +135,7 @@ function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromR const nextDescriptor = nextTransactionID ? siblingDescriptorsByTransactionID?.[nextTransactionID] : undefined; if (nextDescriptor) { const nextReportID = getReportIDToOpenForExpense(nextDescriptor, {introSelected, betas, currentUserEmail, currentUserAccountID}); - markReportIDAsExpense(nextReportID); + markReportRHPWidth(nextReportID, 'wide'); requestAnimationFrame(() => Navigation.setParams({reportID: nextReportID, reportActionID: undefined, backTo})); return; } @@ -144,7 +144,7 @@ function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromR const navigationParams = {reportID: nextThreadReportID, reportActionID: undefined, backTo}; 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) { @@ -181,7 +181,7 @@ function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromR const prevDescriptor = prevTransactionID ? siblingDescriptorsByTransactionID?.[prevTransactionID] : undefined; if (prevDescriptor) { const prevReportID = getReportIDToOpenForExpense(prevDescriptor, {introSelected, betas, currentUserEmail, currentUserAccountID}); - markReportIDAsExpense(prevReportID); + markReportRHPWidth(prevReportID, 'wide'); requestAnimationFrame(() => Navigation.setParams({reportID: prevReportID, reportActionID: undefined, backTo})); return; } @@ -190,7 +190,7 @@ function MoneyRequestReportTransactionsNavigation({currentTransactionID, isFromR const navigationParams = {reportID: prevThreadReportID, reportActionID: undefined, backTo}; 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/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx b/src/components/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx index 26ef496102cf..263666802b64 100644 --- a/src/components/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx +++ b/src/components/Search/SearchList/ListItem/TransactionGroupListExpanded.tsx @@ -153,7 +153,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); @@ -212,7 +212,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 f7aa83f97303..00422404301c 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -135,7 +135,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(); @@ -580,9 +580,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 @@ -627,7 +627,7 @@ function Search({ return; } - markReportIDAsExpense(reportID); + markReportRHPWidth(reportID, 'wide'); if (isTransactionItem && transactionPreviewData) { setOptimisticDataForTransactionThreadPreview(transactionItem, transactionPreviewData, transactionItem?.reportAction?.childReportID); @@ -640,10 +640,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 687a7a7a1aaa..a390c5300aff 100644 --- a/src/components/WideRHPContextProvider/index.tsx +++ b/src/components/WideRHPContextProvider/index.tsx @@ -18,7 +18,7 @@ import type {Report} from '@src/types/onyx'; import {defaultWideRHPActionsContextValue, defaultWideRHPStateContextValue} from './default'; import getIsRHPDisplayedBelow from './getIsRHPDisplayedBelow'; import getVisibleRHPKeys from './getVisibleRHPRouteKeys'; -import type {WideRHPActionsContextType, WideRHPStateContextType} from './types'; +import type {RHPWidth, RHPWidthHint, WideRHPActionsContextType, WideRHPStateContextType} from './types'; import useShouldRenderOverlay from './useShouldRenderOverlay'; // 0 is folded/hidden, 1 is expanded/shown @@ -74,7 +74,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; } @@ -106,9 +106,8 @@ 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}); @@ -186,96 +185,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. + * Removes the route from both wide and super-wide sets. Used on screen unmount. */ - 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); + const removeRHPRouteKey = (route: NavigationRoute) => { + removeWideRHPRoute(route, setAllSuperWideRHPRouteKeys); + removeWideRHPRoute(route, setAllWideRHPRouteKeys); }; /** - * Adds a route to the super wide RHP route keys list, enabling super wide RHP display for that route. + * 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 showSuperWideRHPVersion = (route: NavigationRoute) => { - removeWideRHPRouteKey(route); - showWideRHPRoute(route, setAllSuperWideRHPRouteKeys); - }; - - /** - * 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. - */ - 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; - }); + removeWideRHPRoute(route, setAllSuperWideRHPRouteKeys); + removeWideRHPRoute(route, setAllWideRHPRouteKeys); }; /** - * 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. + * 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 isReportIDMarkedAsExpense = (reportID: string) => { - return expenseReportIDs.has(reportID); - }; - - /** - * 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. - */ - 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. @@ -319,16 +298,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, @@ -366,3 +341,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..10496d99b639 --- /dev/null +++ b/src/components/WideRHPContextProvider/useRHPWidth/index.ts @@ -0,0 +1,60 @@ +import {useRoute} from '@react-navigation/native'; +import {useCallback, useEffect} from 'react'; +import {navigationRef} from '@libs/Navigation/Navigation'; +import NAVIGATORS from '@src/NAVIGATORS'; +import {expandedRHPProgress, useWideRHPActions} from '..'; +import type {RHPWidth} from '..'; + +function getWidthOrder(width: RHPWidth): number { + if (width === 'super-wide') { + return 2; + } + if (width === 'wide') { + return 1; + } + return 0; +} + +/** + * Manages a screen's RHP width. Optimistic hints on the reportID win until the caller settles on a width that meets or exceeds the hint — + * so Search can pre-mark a multi-tx report as super-wide and the screen won't flash at the loading-state width first. + */ +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 = useCallback(() => { + removeRHPRouteKey(route); + // Clear the one-shot hint on unmount so a stale one can't outlive this screen and 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); + } + }, [removeRHPRouteKey, route, reportID, unmarkReportRHPWidth]); + + useEffect(() => () => onClose(), [onClose]); + + // Register the route's width. The optimistic hint outranks the caller while it's higher, so the screen opens at the pre-marked width before its own 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]); + + // Consume the hint once the caller's own width catches up to it (its data has loaded); onClose covers the case where it never does. + 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 89c000febd84..000000000000 --- a/src/components/WideRHPContextProvider/useShowSuperWideRHPVersion/index.ts +++ /dev/null @@ -1,71 +0,0 @@ -import {useRoute} from '@react-navigation/native'; -import {useCallback, useEffect} from 'react'; -import {navigationRef} from '@libs/Navigation/Navigation'; -import NAVIGATORS from '@src/NAVIGATORS'; -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 5e5bde4b0981..000000000000 --- a/src/components/WideRHPContextProvider/useShowWideRHPVersion/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -import {useRoute} from '@react-navigation/native'; -import {useCallback, useEffect} from 'react'; -import {navigationRef} from '@libs/Navigation/Navigation'; -import NAVIGATORS from '@src/NAVIGATORS'; -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 914a27ffdc4d..54732bcf7cf5 100644 --- a/src/hooks/useNavigateToTransactionThread.ts +++ b/src/hooks/useNavigateToTransactionThread.ts @@ -40,7 +40,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); @@ -77,7 +77,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 b381422af2f3..55d834c7c23c 100644 --- a/src/hooks/useNewTransactions.ts +++ b/src/hooks/useNewTransactions.ts @@ -27,20 +27,14 @@ 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-active path: return every still-flagged tx as one continuous set so a later add can't flicker an earlier one out and back in (which re-fires its highlight). isFocused stops unfocused previews consuming it. + if (isFocused && reportID && !isEmptyObject(pendingNewTransactionIDs) && transactions?.length) { + const pendingSet = new Set(Object.keys(pendingNewTransactionIDs)); + return transactions.filter(({transactionID}) => pendingSet.has(transactionID) && pendingNewTransactionIDs[transactionID]); } + // No rail (Pusher adds or unfocused): fall back to the diff. Runs regardless of focus — useAnimatedHighlightStyle latches until didScreenTransitionEnd, so an unfocused table behind an overlay still highlights. 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; - } return CONST.EMPTY_ARRAY as unknown as Transaction[]; } if (skipFirstTransactionsChange.current) { @@ -49,10 +43,10 @@ function useNewTransactions( } return transactions.filter((transaction) => !prevTransactions?.some((prevTransaction) => prevTransaction.transactionID === transaction.transactionID)); - // 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, isFocused, pendingNewTransactionIDs]); useEffect(() => { if (!pendingNewTransactionIDs) { diff --git a/src/libs/actions/IOU/MoneyRequestBuilder.ts b/src/libs/actions/IOU/MoneyRequestBuilder.ts index dee1d57cab96..de987967e840 100644 --- a/src/libs/actions/IOU/MoneyRequestBuilder.ts +++ b/src/libs/actions/IOU/MoneyRequestBuilder.ts @@ -663,6 +663,25 @@ function buildOnyxDataForMoneyRequest(moneyRequestParams: BuildOnyxDataForMoneyR }); } + // Flag the new tx for useNewTransactions. Cleared by success/failure on resolution, with useNewTransactions' timer as the offline fallback. Skipped for self-DM splits (tx routes to UNREPORTED_REPORT_ID). + if (iou.report?.reportID && transaction.transactionID && !isSelfDMSplit) { + onyxData.optimisticData?.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${iou.report.reportID}`, + value: {pendingNewTransactionIDs: {[transaction.transactionID]: true}}, + }); + onyxData.successData?.push({ + onyxMethod: Onyx.METHOD.MERGE, + key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${iou.report.reportID}`, + value: {pendingNewTransactionIDs: {[transaction.transactionID]: null}}, + }); + 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, diff --git a/src/pages/Search/SearchMoneyRequestReportPage.tsx b/src/pages/Search/SearchMoneyRequestReportPage.tsx index e8f476e86b01..691c9ce7107f 100644 --- a/src/pages/Search/SearchMoneyRequestReportPage.tsx +++ b/src/pages/Search/SearchMoneyRequestReportPage.tsx @@ -7,7 +7,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 useActionListContextValue from '@hooks/useActionListContextValue'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; @@ -176,7 +176,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 4b3d9ef06f84..d7b13e401d20 100644 --- a/src/pages/home/RecentlyAddedSection/index.tsx +++ b/src/pages/home/RecentlyAddedSection/index.tsx @@ -54,7 +54,7 @@ function RecentlyAddedSection() { const isFocused = useIsFocused(); const icons = useMemoizedLazyExpensifyIcons(['ThreeDots', 'Receipt']); const {calculatePopoverPosition} = usePopoverPosition(); - const {markReportIDAsExpense} = useWideRHPActions(); + const {markReportRHPWidth} = useWideRHPActions(); const {email: currentUserEmail, accountID: currentUserAccountID} = useCurrentUserPersonalDetails(); const [betas] = useOnyx(ONYXKEYS.BETAS); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); @@ -83,7 +83,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 5e0a87524b0f..83df110f5c47 100644 --- a/src/pages/inbox/WideRHPReceiptPanel.tsx +++ b/src/pages/inbox/WideRHPReceiptPanel.tsx @@ -4,7 +4,8 @@ import React from 'react'; import {Animated} from 'react-native'; 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'; import usePaginatedReportActions from '@hooks/usePaginatedReportActions'; @@ -68,7 +69,13 @@ function WideRHPReceiptPanelGate() { report?.type === CONST.REPORT.TYPE.EXPENSE || report?.type === CONST.REPORT.TYPE.IOU); - useShowWideRHPVersion(shouldShowWideRHP); + let rhpWidth: RHPWidth = 'narrow'; + if (shouldDisplayMoneyRequestActionsList) { + 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 5a381553375e..e4f5cb5d9af6 100644 --- a/tests/actions/IOU/GetMoneyRequestInformationTest.ts +++ b/tests/actions/IOU/GetMoneyRequestInformationTest.ts @@ -210,4 +210,57 @@ describe('getMoneyRequestInformation', () => { expect(tagEntry?.value).toEqual({[TAG_LIST]: [TAG_NAME]}); }); }); + + describe('pendingNewTransactionIDs metadata rail', () => { + it('writes the flag in optimisticData under REPORT_METADATA of the new IOU report', () => { + const result = getMoneyRequestInformation(baseParams); + const expectedKey = `${ONYXKEYS.COLLECTION.REPORT_METADATA}${result.iouReport.reportID}`; + const newTxID = result.transaction.transactionID; + + expect(result.onyxData.optimisticData).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + key: expectedKey, + value: expect.objectContaining({ + pendingNewTransactionIDs: expect.objectContaining({[newTxID]: true}), + }), + }), + ]), + ); + }); + + it('clears the flag in failureData when the optimistic write rolls back', () => { + const result = getMoneyRequestInformation(baseParams); + const expectedKey = `${ONYXKEYS.COLLECTION.REPORT_METADATA}${result.iouReport.reportID}`; + const newTxID = result.transaction.transactionID; + + expect(result.onyxData.failureData).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + key: expectedKey, + value: expect.objectContaining({ + pendingNewTransactionIDs: expect.objectContaining({[newTxID]: null}), + }), + }), + ]), + ); + }); + + it('clears the flag in successData so it cannot persist across sessions', () => { + const result = getMoneyRequestInformation(baseParams); + const expectedKey = `${ONYXKEYS.COLLECTION.REPORT_METADATA}${result.iouReport.reportID}`; + const newTxID = result.transaction.transactionID; + + expect(result.onyxData.successData).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + key: expectedKey, + value: expect.objectContaining({ + pendingNewTransactionIDs: expect.objectContaining({[newTxID]: null}), + }), + }), + ]), + ); + }); + }); }); diff --git a/tests/unit/useNewTransactionsTest.ts b/tests/unit/useNewTransactionsTest.ts index f7244506b64d..eba4ef80e036 100644 --- a/tests/unit/useNewTransactionsTest.ts +++ b/tests/unit/useNewTransactionsTest.ts @@ -358,6 +358,128 @@ 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 | 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([]); + + // Metadata-only update — same transactions reference, new pendingNewTransactionIDs + 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}; + + // 1. Table view mounts with both txs already in Onyx cache; metadata hasn't propagated yet + 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([]); + + // 2. Still no metadata, diff sees same tx set + rerender({ + hasOnceLoadedReportActions: true, + transactions: [originalTx, duplicateTx], + pendingNewTransactionIDs: undefined, + isFocused: true, + }); + expect(result.current).toEqual([]); + + // 3. pendingNewTransactionIDs propagates from Onyx → highlight fires + rerender({ + hasOnceLoadedReportActions: true, + transactions: [originalTx, duplicateTx], + pendingNewTransactionIDs: {[duplicateTx.transactionID]: true}, + isFocused: true, + }); + expect(result.current).toEqual([duplicateTx]); + + // 4. Deletion timeout clears the metadata; diff branch returns empty again + rerender({ + hasOnceLoadedReportActions: true, + transactions: [originalTx, duplicateTx], + pendingNewTransactionIDs: undefined, + isFocused: true, + }); + expect(result.current).toEqual([]); + }); +}); + +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 branch runs regardless of focus, so a report behind an overlay still highlights a new expense. + 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('returns pending transactions only once the report is focused', () => { + // The rail stays gated on focus so an unfocused consumer (e.g. a chat report preview) doesn't consume the flag early. + const allTransactions = [...transactionsAlreadyInReport, newTransaction]; + const {rerender, result} = renderHook( + (props) => useNewTransactions(true, allTransactions, {[newTransaction.transactionID]: true}, 'report1', props.isFocused), + {initialProps: {isFocused: false}}, + ); + expect(result.current).toEqual([]); + + rerender({isFocused: true}); + 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}>( + (props) => useNewTransactions(true, props.transactions, props.pendingNewTransactionIDs, 'report1', true), + {initialProps: {transactions: transactionsAlreadyInReport, pendingNewTransactionIDs: {}}}, + ); + expect(result.current).toEqual([]); + + // B is added. + rerender({transactions: [...transactionsAlreadyInReport, txB], pendingNewTransactionIDs: {B: true}}); + expect(result.current).toEqual([txB]); + + // Stable render while B is still flagged — B stays. + rerender({transactions: [...transactionsAlreadyInReport, txB], pendingNewTransactionIDs: {B: true}}); + expect(result.current).toEqual([txB]); + + // C is added while B is still flagged — B must remain present (continuous), now alongside C. + rerender({transactions: [...transactionsAlreadyInReport, txB, txC], pendingNewTransactionIDs: {B: true, C: true}}); + expect(result.current).toEqual(expect.arrayContaining([txB, txC])); + expect(result.current).toHaveLength(2); + }); }); afterAll(() => { From 772ba274e3b2c136fc14d0caebd17aeceac45e4e Mon Sep 17 00:00:00 2001 From: TaduJR Date: Sat, 27 Jun 2026 17:06:43 +0300 Subject: [PATCH 02/11] fix: drop successData clear of pendingNewTransactionIDs to avoid racing the report mount --- src/libs/actions/IOU/MoneyRequestBuilder.ts | 7 +------ tests/actions/IOU/GetMoneyRequestInformationTest.ts | 4 ++-- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/src/libs/actions/IOU/MoneyRequestBuilder.ts b/src/libs/actions/IOU/MoneyRequestBuilder.ts index de987967e840..56d86c317106 100644 --- a/src/libs/actions/IOU/MoneyRequestBuilder.ts +++ b/src/libs/actions/IOU/MoneyRequestBuilder.ts @@ -663,18 +663,13 @@ function buildOnyxDataForMoneyRequest(moneyRequestParams: BuildOnyxDataForMoneyR }); } - // Flag the new tx for useNewTransactions. Cleared by success/failure on resolution, with useNewTransactions' timer as the offline fallback. Skipped for self-DM splits (tx routes to UNREPORTED_REPORT_ID). + // Flag the new tx for useNewTransactions. No successData clear — it'd race the report mount; the hook's timer handles success. Skip self-DM splits (tx routes elsewhere). if (iou.report?.reportID && transaction.transactionID && !isSelfDMSplit) { onyxData.optimisticData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${iou.report.reportID}`, value: {pendingNewTransactionIDs: {[transaction.transactionID]: true}}, }); - onyxData.successData?.push({ - onyxMethod: Onyx.METHOD.MERGE, - key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${iou.report.reportID}`, - value: {pendingNewTransactionIDs: {[transaction.transactionID]: null}}, - }); onyxData.failureData?.push({ onyxMethod: Onyx.METHOD.MERGE, key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${iou.report.reportID}`, diff --git a/tests/actions/IOU/GetMoneyRequestInformationTest.ts b/tests/actions/IOU/GetMoneyRequestInformationTest.ts index e4f5cb5d9af6..84bf9f0602ec 100644 --- a/tests/actions/IOU/GetMoneyRequestInformationTest.ts +++ b/tests/actions/IOU/GetMoneyRequestInformationTest.ts @@ -246,12 +246,12 @@ describe('getMoneyRequestInformation', () => { ); }); - it('clears the flag in successData so it cannot persist across sessions', () => { + it('does NOT clear the flag in successData (the hook timer owns success-path cleanup, so it cannot race the highlight)', () => { const result = getMoneyRequestInformation(baseParams); const expectedKey = `${ONYXKEYS.COLLECTION.REPORT_METADATA}${result.iouReport.reportID}`; const newTxID = result.transaction.transactionID; - expect(result.onyxData.successData).toEqual( + expect(result.onyxData.successData ?? []).not.toEqual( expect.arrayContaining([ expect.objectContaining({ key: expectedKey, From 9aace7dc15ac22766baa47335f192be09c79b100 Mon Sep 17 00:00:00 2001 From: TaduJR Date: Sun, 28 Jun 2026 10:42:37 +0300 Subject: [PATCH 03/11] fix: fall through to diff when pending rail holds only cleared tombstones --- src/hooks/useNewTransactions.ts | 9 +++++---- tests/unit/useNewTransactionsTest.ts | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/hooks/useNewTransactions.ts b/src/hooks/useNewTransactions.ts index 55d834c7c23c..1ad00a1a75ef 100644 --- a/src/hooks/useNewTransactions.ts +++ b/src/hooks/useNewTransactions.ts @@ -2,7 +2,6 @@ import {useEffect, useMemo, useRef} from 'react'; import {deletePendingNewTransactionIDs} from '@libs/actions/IOU/PendingNewTransactions'; import CONST from '@src/CONST'; import type {Transaction} from '@src/types/onyx'; -import {isEmptyObject} from '@src/types/utils/EmptyObject'; import usePrevious from './usePrevious'; /** @@ -28,9 +27,11 @@ function useNewTransactions( const newTransactions = useMemo(() => { // Rail-active path: return every still-flagged tx as one continuous set so a later add can't flicker an earlier one out and back in (which re-fires its highlight). isFocused stops unfocused previews consuming it. - if (isFocused && reportID && !isEmptyObject(pendingNewTransactionIDs) && transactions?.length) { - const pendingSet = new Set(Object.keys(pendingNewTransactionIDs)); - return transactions.filter(({transactionID}) => pendingSet.has(transactionID) && pendingNewTransactionIDs[transactionID]); + // Gate on a TRUTHY flag — an all-cleared rail ({id: null} tombstones) must fall through to the diff so a later Pusher/import add still highlights. + const activePendingTransactionIDs = pendingNewTransactionIDs ? Object.keys(pendingNewTransactionIDs).filter((id) => pendingNewTransactionIDs[id]) : []; + if (isFocused && reportID && activePendingTransactionIDs.length && transactions?.length) { + const pendingSet = new Set(activePendingTransactionIDs); + return transactions.filter(({transactionID}) => pendingSet.has(transactionID)); } // No rail (Pusher adds or unfocused): fall back to the diff. Runs regardless of focus — useAnimatedHighlightStyle latches until didScreenTransitionEnd, so an unfocused table behind an overlay still highlights. diff --git a/tests/unit/useNewTransactionsTest.ts b/tests/unit/useNewTransactionsTest.ts index eba4ef80e036..e383381956d6 100644 --- a/tests/unit/useNewTransactionsTest.ts +++ b/tests/unit/useNewTransactionsTest.ts @@ -423,6 +423,23 @@ describe('useNewTransactions with pendingNewTransactionIDs (cross-navigation)', }); 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}>( + (props) => useNewTransactions(true, props.transactions, props.pendingNewTransactionIDs, 'report1', true), + { + initialProps: {transactions: [existingTx], pendingNewTransactionIDs: {[existingTx.transactionID]: null}}, + }, + ); + expect(result.current).toEqual([]); + + // A new tx arrives with no fresh flag while the rail still carries the tombstone — the diff must surface it. + rerender({transactions: [existingTx, pusherTx], pendingNewTransactionIDs: {[existingTx.transactionID]: null}}); + expect(result.current).toEqual([pusherTx]); + }); }); describe('useNewTransactions with an unfocused report', () => { From 1729366b87f873143bc14f9829321c604fd7ed2b Mon Sep 17 00:00:00 2001 From: TaduJR Date: Sun, 28 Jun 2026 11:17:03 +0300 Subject: [PATCH 04/11] fix: clear pending rail only from a focused consumer --- src/hooks/useNewTransactions.ts | 8 ++++---- tests/unit/useNewTransactionsTest.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/hooks/useNewTransactions.ts b/src/hooks/useNewTransactions.ts index 1ad00a1a75ef..d89ae9d0f24f 100644 --- a/src/hooks/useNewTransactions.ts +++ b/src/hooks/useNewTransactions.ts @@ -26,8 +26,7 @@ function useNewTransactions( const skipFirstTransactionsChange = useRef(!hasOnceLoadedReportActions); const newTransactions = useMemo(() => { - // Rail-active path: return every still-flagged tx as one continuous set so a later add can't flicker an earlier one out and back in (which re-fires its highlight). isFocused stops unfocused previews consuming it. - // Gate on a TRUTHY flag — an all-cleared rail ({id: null} tombstones) must fall through to the diff so a later Pusher/import add still highlights. + // Rail-active (truthy flags only — an all-cleared rail falls through to the diff): return all flagged txs at once so a later add can't flicker an earlier one's highlight. const activePendingTransactionIDs = pendingNewTransactionIDs ? Object.keys(pendingNewTransactionIDs).filter((id) => pendingNewTransactionIDs[id]) : []; if (isFocused && reportID && activePendingTransactionIDs.length && transactions?.length) { const pendingSet = new Set(activePendingTransactionIDs); @@ -50,7 +49,8 @@ function useNewTransactions( }, [transactions, reportID, isFocused, pendingNewTransactionIDs]); useEffect(() => { - if (!pendingNewTransactionIDs) { + // Only the focused consumer clears the rail — else an unfocused diff could clear the flag before the focused view of the same key consumes it. + if (isFocused === false || !pendingNewTransactionIDs) { return; } const pendingSet = new Set(Object.keys(pendingNewTransactionIDs)); @@ -66,7 +66,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/tests/unit/useNewTransactionsTest.ts b/tests/unit/useNewTransactionsTest.ts index e383381956d6..964e68695235 100644 --- a/tests/unit/useNewTransactionsTest.ts +++ b/tests/unit/useNewTransactionsTest.ts @@ -1,7 +1,13 @@ 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(() => { @@ -497,6 +503,28 @@ describe('useNewTransactions with an unfocused report', () => { expect(result.current).toEqual(expect.arrayContaining([txB, txC])); expect(result.current).toHaveLength(2); }); + + it('schedules the rail cleanup only from a focused consumer', () => { + // An unfocused consumer's diff can surface a pending tx, but it must not clear the rail — a later focused mount of the same key still needs it. + 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; isFocused: boolean}>( + (props) => useNewTransactions(true, props.transactions, props.pendingNewTransactionIDs, 'report1', props.isFocused), + {initialProps: {transactions: transactionsAlreadyInReport, pendingNewTransactionIDs: {D: true}, isFocused: false}}, + ); + + // Unfocused: D surfaces via the diff, but no cleanup is scheduled. + rerender({transactions: [...transactionsAlreadyInReport, txD], pendingNewTransactionIDs: {D: true}, isFocused: false}); + expect(scheduledCleanups()).toBe(0); + + // Focused: the cleanup is now scheduled. + rerender({transactions: [...transactionsAlreadyInReport, txD], pendingNewTransactionIDs: {D: true}, isFocused: true}); + expect(scheduledCleanups()).toBeGreaterThan(0); + + setTimeoutSpy.mockRestore(); + }); }); afterAll(() => { From 95d362c109baa41058950374f251d61648bac54f Mon Sep 17 00:00:00 2001 From: TaduJR Date: Sun, 28 Jun 2026 20:34:02 +0300 Subject: [PATCH 05/11] fix: gate highlight rail to multi-tx adds and union it with the render diff --- src/hooks/useNewTransactions.ts | 30 +++++++----- src/libs/actions/IOU/MoneyRequestBuilder.ts | 10 +++- .../IOU/GetMoneyRequestInformationTest.ts | 48 ++----------------- tests/unit/useNewTransactionsTest.ts | 30 +++++++----- 4 files changed, 49 insertions(+), 69 deletions(-) diff --git a/src/hooks/useNewTransactions.ts b/src/hooks/useNewTransactions.ts index d89ae9d0f24f..29c2905311d1 100644 --- a/src/hooks/useNewTransactions.ts +++ b/src/hooks/useNewTransactions.ts @@ -26,22 +26,28 @@ function useNewTransactions( const skipFirstTransactionsChange = useRef(!hasOnceLoadedReportActions); const newTransactions = useMemo(() => { - // Rail-active (truthy flags only — an all-cleared rail falls through to the diff): return all flagged txs at once so a later add can't flicker an earlier one's highlight. + // Rail-flagged adds survive the remount the diff can't see (a duplicate flips a 1-tx report to the table view). Truthy only — an all-cleared rail leaves just the diff. const activePendingTransactionIDs = pendingNewTransactionIDs ? Object.keys(pendingNewTransactionIDs).filter((id) => pendingNewTransactionIDs[id]) : []; - if (isFocused && reportID && activePendingTransactionIDs.length && transactions?.length) { - const pendingSet = new Set(activePendingTransactionIDs); - return transactions.filter(({transactionID}) => pendingSet.has(transactionID)); - } + const railSet = new Set(activePendingTransactionIDs); + const railTransactions = + isFocused && reportID && activePendingTransactionIDs.length && transactions?.length ? transactions.filter(({transactionID}) => railSet.has(transactionID)) : []; - // No rail (Pusher adds or unfocused): fall back to the diff. Runs regardless of focus — useAnimatedHighlightStyle latches until didScreenTransitionEnd, so an unfocused table behind an overlay still highlights. - if (transactions === undefined || prevTransactions === undefined || transactions.length <= prevTransactions.length) { - return CONST.EMPTY_ARRAY as unknown as Transaction[]; + // Diff-detected adds: render-to-render growth the rail never flagged (e.g. a Pusher add landing inside the rail's cleanup delay). Focus-independent — useAnimatedHighlightStyle latches until didScreenTransitionEnd, so an unfocused table behind an overlay still highlights. + 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)); + } } - if (skipFirstTransactionsChange.current) { - skipFirstTransactionsChange.current = false; - return CONST.EMPTY_ARRAY as unknown as Transaction[]; + + // Union both so a rail add and a concurrent diff add both highlight; rail first keeps newTransactions[0] (the scroll target) stable across a later add. + if (!railTransactions.length) { + return diffTransactions.length ? diffTransactions : (CONST.EMPTY_ARRAY as unknown as Transaction[]); } - 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 as it will make the value // disappear quickly which will break the scroll and highlight on slower devices like mobile app. diff --git a/src/libs/actions/IOU/MoneyRequestBuilder.ts b/src/libs/actions/IOU/MoneyRequestBuilder.ts index 56d86c317106..e151402e8c37 100644 --- a/src/libs/actions/IOU/MoneyRequestBuilder.ts +++ b/src/libs/actions/IOU/MoneyRequestBuilder.ts @@ -32,6 +32,7 @@ import { isExpenseReport, isGroupChat, isInvoiceReport as isInvoiceReportReportUtils, + isMoneyRequestReport, isOneTransactionReport, isPolicyExpenseChat as isPolicyExpenseChatReportUtil, isSelfDM, @@ -663,8 +664,13 @@ function buildOnyxDataForMoneyRequest(moneyRequestParams: BuildOnyxDataForMoneyR }); } - // Flag the new tx for useNewTransactions. No successData clear — it'd race the report mount; the hook's timer handles success. Skip self-DM splits (tx routes elsewhere). - if (iou.report?.reportID && transaction.transactionID && !isSelfDMSplit) { + // 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}`, diff --git a/tests/actions/IOU/GetMoneyRequestInformationTest.ts b/tests/actions/IOU/GetMoneyRequestInformationTest.ts index 84bf9f0602ec..1eb45d47d47c 100644 --- a/tests/actions/IOU/GetMoneyRequestInformationTest.ts +++ b/tests/actions/IOU/GetMoneyRequestInformationTest.ts @@ -212,54 +212,14 @@ describe('getMoneyRequestInformation', () => { }); describe('pendingNewTransactionIDs metadata rail', () => { - it('writes the flag in optimisticData under REPORT_METADATA of the new IOU report', () => { + // 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).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - key: expectedKey, - value: expect.objectContaining({ - pendingNewTransactionIDs: expect.objectContaining({[newTxID]: true}), - }), - }), - ]), - ); - }); - - it('clears the flag in failureData when the optimistic write rolls back', () => { - const result = getMoneyRequestInformation(baseParams); - const expectedKey = `${ONYXKEYS.COLLECTION.REPORT_METADATA}${result.iouReport.reportID}`; - const newTxID = result.transaction.transactionID; - - expect(result.onyxData.failureData).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - key: expectedKey, - value: expect.objectContaining({ - pendingNewTransactionIDs: expect.objectContaining({[newTxID]: null}), - }), - }), - ]), - ); - }); - - it('does NOT clear the flag in successData (the hook timer owns success-path cleanup, so it cannot race the highlight)', () => { - const result = getMoneyRequestInformation(baseParams); - const expectedKey = `${ONYXKEYS.COLLECTION.REPORT_METADATA}${result.iouReport.reportID}`; - const newTxID = result.transaction.transactionID; - - expect(result.onyxData.successData ?? []).not.toEqual( - expect.arrayContaining([ - expect.objectContaining({ - key: expectedKey, - value: expect.objectContaining({ - pendingNewTransactionIDs: expect.objectContaining({[newTxID]: null}), - }), - }), - ]), + 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 964e68695235..4302751983e0 100644 --- a/tests/unit/useNewTransactionsTest.ts +++ b/tests/unit/useNewTransactionsTest.ts @@ -379,7 +379,6 @@ describe('useNewTransactions with pendingNewTransactionIDs (cross-navigation)', rerender({transactions: stableTransactions, pendingNewTransactionIDs: undefined}); expect(result.current).toEqual([]); - // Metadata-only update — same transactions reference, new pendingNewTransactionIDs rerender({transactions: stableTransactions, pendingNewTransactionIDs: {[newTransaction.transactionID]: true}}); expect(result.current).toEqual([newTransaction]); }); @@ -388,7 +387,6 @@ describe('useNewTransactions with pendingNewTransactionIDs (cross-navigation)', const [originalTx] = transactionsAlreadyInReport; const duplicateTx = {...newTransaction, pendingAction: 'add' as const}; - // 1. Table view mounts with both txs already in Onyx cache; metadata hasn't propagated yet const {rerender, result} = renderHook< Transaction[], {transactions: Transaction[]; hasOnceLoadedReportActions: boolean; pendingNewTransactionIDs: Record | undefined; isFocused?: boolean} @@ -402,7 +400,6 @@ describe('useNewTransactions with pendingNewTransactionIDs (cross-navigation)', }); expect(result.current).toEqual([]); - // 2. Still no metadata, diff sees same tx set rerender({ hasOnceLoadedReportActions: true, transactions: [originalTx, duplicateTx], @@ -411,7 +408,6 @@ describe('useNewTransactions with pendingNewTransactionIDs (cross-navigation)', }); expect(result.current).toEqual([]); - // 3. pendingNewTransactionIDs propagates from Onyx → highlight fires rerender({ hasOnceLoadedReportActions: true, transactions: [originalTx, duplicateTx], @@ -420,7 +416,6 @@ describe('useNewTransactions with pendingNewTransactionIDs (cross-navigation)', }); expect(result.current).toEqual([duplicateTx]); - // 4. Deletion timeout clears the metadata; diff branch returns empty again rerender({ hasOnceLoadedReportActions: true, transactions: [originalTx, duplicateTx], @@ -442,10 +437,28 @@ describe('useNewTransactions with pendingNewTransactionIDs (cross-navigation)', ); expect(result.current).toEqual([]); - // A new tx arrives with no fresh flag while the rail still carries the tombstone — the diff must surface it. 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}>( + (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', () => { @@ -490,15 +503,12 @@ describe('useNewTransactions with an unfocused report', () => { ); expect(result.current).toEqual([]); - // B is added. rerender({transactions: [...transactionsAlreadyInReport, txB], pendingNewTransactionIDs: {B: true}}); expect(result.current).toEqual([txB]); - // Stable render while B is still flagged — B stays. rerender({transactions: [...transactionsAlreadyInReport, txB], pendingNewTransactionIDs: {B: true}}); expect(result.current).toEqual([txB]); - // C is added while B is still flagged — B must remain present (continuous), now alongside C. rerender({transactions: [...transactionsAlreadyInReport, txB, txC], pendingNewTransactionIDs: {B: true, C: true}}); expect(result.current).toEqual(expect.arrayContaining([txB, txC])); expect(result.current).toHaveLength(2); @@ -515,11 +525,9 @@ describe('useNewTransactions with an unfocused report', () => { {initialProps: {transactions: transactionsAlreadyInReport, pendingNewTransactionIDs: {D: true}, isFocused: false}}, ); - // Unfocused: D surfaces via the diff, but no cleanup is scheduled. rerender({transactions: [...transactionsAlreadyInReport, txD], pendingNewTransactionIDs: {D: true}, isFocused: false}); expect(scheduledCleanups()).toBe(0); - // Focused: the cleanup is now scheduled. rerender({transactions: [...transactionsAlreadyInReport, txD], pendingNewTransactionIDs: {D: true}, isFocused: true}); expect(scheduledCleanups()).toBeGreaterThan(0); From 19a87c8165a29a17a48e7aeae93f098c2da47bb9 Mon Sep 17 00:00:00 2001 From: TaduJR Date: Sun, 28 Jun 2026 22:03:33 +0300 Subject: [PATCH 06/11] fix: keep unfocused consumers silent so a background preview can't flash a highlight --- .../useRHPWidth/index.ts | 11 +++---- src/hooks/useNewTransactions.ts | 31 ++++++++++++++----- src/libs/actions/IOU/MoneyRequestBuilder.ts | 2 +- tests/unit/useNewTransactionsTest.ts | 8 ++--- 4 files changed, 32 insertions(+), 20 deletions(-) diff --git a/src/components/WideRHPContextProvider/useRHPWidth/index.ts b/src/components/WideRHPContextProvider/useRHPWidth/index.ts index 10496d99b639..5ab02c4a626d 100644 --- a/src/components/WideRHPContextProvider/useRHPWidth/index.ts +++ b/src/components/WideRHPContextProvider/useRHPWidth/index.ts @@ -15,10 +15,7 @@ function getWidthOrder(width: RHPWidth): number { return 0; } -/** - * Manages a screen's RHP width. Optimistic hints on the reportID win until the caller settles on a width that meets or exceeds the hint — - * so Search can pre-mark a multi-tx report as super-wide and the screen won't flash at the loading-state width first. - */ +/** 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 : ''; @@ -26,7 +23,7 @@ function useRHPWidth(width: RHPWidth) { const onClose = useCallback(() => { removeRHPRouteKey(route); - // Clear the one-shot hint on unmount so a stale one can't outlive this screen and pin the report wide on a later visit. + // Clear the one-shot hint on unmount so it can't pin the report wide on a later visit. if (reportID) { unmarkReportRHPWidth(reportID); } @@ -38,14 +35,14 @@ function useRHPWidth(width: RHPWidth) { useEffect(() => () => onClose(), [onClose]); - // Register the route's width. The optimistic hint outranks the caller while it's higher, so the screen opens at the pre-marked width before its own data loads. + // 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]); - // Consume the hint once the caller's own width catches up to it (its data has loaded); onClose covers the case where it never does. + // Clear the hint once the caller's width reaches it; onClose handles the never-reached case. useEffect(() => { if (!reportID) { return; diff --git a/src/hooks/useNewTransactions.ts b/src/hooks/useNewTransactions.ts index 29c2905311d1..6ebffd685c0b 100644 --- a/src/hooks/useNewTransactions.ts +++ b/src/hooks/useNewTransactions.ts @@ -4,6 +4,9 @@ import CONST from '@src/CONST'; import type {Transaction} from '@src/types/onyx'; 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. @@ -26,13 +29,25 @@ function useNewTransactions( const skipFirstTransactionsChange = useRef(!hasOnceLoadedReportActions); const newTransactions = useMemo(() => { - // Rail-flagged adds survive the remount the diff can't see (a duplicate flips a 1-tx report to the table view). Truthy only — an all-cleared rail leaves just the diff. - const activePendingTransactionIDs = pendingNewTransactionIDs ? Object.keys(pendingNewTransactionIDs).filter((id) => pendingNewTransactionIDs[id]) : []; - const railSet = new Set(activePendingTransactionIDs); - const railTransactions = - isFocused && reportID && activePendingTransactionIDs.length && transactions?.length ? transactions.filter(({transactionID}) => railSet.has(transactionID)) : []; + if (isFocused === false) { + return EMPTY_TRANSACTIONS; + } + + // Rail-flagged adds survive the remount the diff can't see. Built only when focused; truthy-only so an all-cleared tombstone rail falls through to the diff. + const railSet = new Set(); + let railTransactions: Transaction[] = EMPTY_TRANSACTIONS; + if (isFocused && reportID && transactions?.length && pendingNewTransactionIDs) { + for (const id of Object.keys(pendingNewTransactionIDs)) { + if (pendingNewTransactionIDs[id]) { + railSet.add(id); + } + } + if (railSet.size) { + railTransactions = transactions.filter(({transactionID}) => railSet.has(transactionID)); + } + } - // Diff-detected adds: render-to-render growth the rail never flagged (e.g. a Pusher add landing inside the rail's cleanup delay). Focus-independent — useAnimatedHighlightStyle latches until didScreenTransitionEnd, so an unfocused table behind an overlay still highlights. + // Diff-detected adds: render-to-render growth the rail never flagged (e.g. a Pusher add). let diffTransactions: Transaction[] = []; if (transactions !== undefined && prevTransactions !== undefined && transactions.length > prevTransactions.length) { if (skipFirstTransactionsChange.current) { @@ -42,9 +57,9 @@ function useNewTransactions( } } - // Union both so a rail add and a concurrent diff add both highlight; rail first keeps newTransactions[0] (the scroll target) stable across a later add. + // Union, rail first so newTransactions[0] (the scroll target) stays stable across a later add. if (!railTransactions.length) { - return diffTransactions.length ? diffTransactions : (CONST.EMPTY_ARRAY as unknown as Transaction[]); + return diffTransactions.length ? diffTransactions : EMPTY_TRANSACTIONS; } const extraDiff = diffTransactions.filter(({transactionID}) => !railSet.has(transactionID)); return extraDiff.length ? [...railTransactions, ...extraDiff] : railTransactions; diff --git a/src/libs/actions/IOU/MoneyRequestBuilder.ts b/src/libs/actions/IOU/MoneyRequestBuilder.ts index e151402e8c37..dcf17794fcc5 100644 --- a/src/libs/actions/IOU/MoneyRequestBuilder.ts +++ b/src/libs/actions/IOU/MoneyRequestBuilder.ts @@ -1120,7 +1120,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/tests/unit/useNewTransactionsTest.ts b/tests/unit/useNewTransactionsTest.ts index 4302751983e0..8e96010603b2 100644 --- a/tests/unit/useNewTransactionsTest.ts +++ b/tests/unit/useNewTransactionsTest.ts @@ -468,8 +468,8 @@ describe('useNewTransactions with an unfocused report', () => { ]; 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 branch runs regardless of focus, so a report behind an overlay still highlights a new expense. + it('stays silent for an explicitly-unfocused consumer (the rail re-delivers on refocus)', () => { + // A background chat preview must not animate a highlight off-screen; only a focused consumer surfaces adds. const {rerender, result} = renderHook( (props) => useNewTransactions(true, props.transactions, undefined, 'report1', props.isFocused), {initialProps: {transactions: transactionsAlreadyInReport, isFocused: false}}, @@ -477,7 +477,7 @@ describe('useNewTransactions with an unfocused report', () => { expect(result.current).toEqual([]); rerender({transactions: [...transactionsAlreadyInReport, newTransaction], isFocused: false}); - expect(result.current).toEqual([newTransaction]); + expect(result.current).toEqual([]); }); it('returns pending transactions only once the report is focused', () => { @@ -515,7 +515,7 @@ describe('useNewTransactions with an unfocused report', () => { }); it('schedules the rail cleanup only from a focused consumer', () => { - // An unfocused consumer's diff can surface a pending tx, but it must not clear the rail — a later focused mount of the same key still needs it. + // Only a focused consumer schedules the rail cleanup; an unfocused one stays silent and 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; From 1f092c1e338c5e80b5a20194fe6b05c6958e2b9f Mon Sep 17 00:00:00 2001 From: TaduJR Date: Tue, 30 Jun 2026 10:00:13 +0300 Subject: [PATCH 07/11] fix: highlight the new row in the background regardless of focus --- src/hooks/useNewTransactions.ts | 24 ++++++------------------ tests/unit/useNewTransactionsTest.ts | 6 +++--- 2 files changed, 9 insertions(+), 21 deletions(-) diff --git a/src/hooks/useNewTransactions.ts b/src/hooks/useNewTransactions.ts index 6ebffd685c0b..468f5dca7187 100644 --- a/src/hooks/useNewTransactions.ts +++ b/src/hooks/useNewTransactions.ts @@ -29,25 +29,13 @@ function useNewTransactions( const skipFirstTransactionsChange = useRef(!hasOnceLoadedReportActions); const newTransactions = useMemo(() => { - if (isFocused === false) { - return EMPTY_TRANSACTIONS; - } - - // Rail-flagged adds survive the remount the diff can't see. Built only when focused; truthy-only so an all-cleared tombstone rail falls through to the diff. - const railSet = new Set(); - let railTransactions: Transaction[] = EMPTY_TRANSACTIONS; - if (isFocused && reportID && transactions?.length && pendingNewTransactionIDs) { - for (const id of Object.keys(pendingNewTransactionIDs)) { - if (pendingNewTransactionIDs[id]) { - railSet.add(id); - } - } - if (railSet.size) { - railTransactions = transactions.filter(({transactionID}) => railSet.has(transactionID)); - } - } + // 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 = + isFocused && reportID && activePendingTransactionIDs.length && transactions?.length ? transactions.filter(({transactionID}) => railSet.has(transactionID)) : EMPTY_TRANSACTIONS; - // Diff-detected adds: render-to-render growth the rail never flagged (e.g. a Pusher add). + // Diff-detected adds the rail never flagged (e.g. a Pusher add). Focus-independent so a backgrounded table still highlights — design wants background highlighting. let diffTransactions: Transaction[] = []; if (transactions !== undefined && prevTransactions !== undefined && transactions.length > prevTransactions.length) { if (skipFirstTransactionsChange.current) { diff --git a/tests/unit/useNewTransactionsTest.ts b/tests/unit/useNewTransactionsTest.ts index 8e96010603b2..8d52f6b30e21 100644 --- a/tests/unit/useNewTransactionsTest.ts +++ b/tests/unit/useNewTransactionsTest.ts @@ -468,8 +468,8 @@ describe('useNewTransactions with an unfocused report', () => { ]; const newTransaction = {transactionID: '1', amount: 100, created: '2023-10-01T00:00:00Z', currency: 'USD', reportID: 'report1', merchant: ''}; - it('stays silent for an explicitly-unfocused consumer (the rail re-delivers on refocus)', () => { - // A background chat preview must not animate a highlight off-screen; only a focused consumer surfaces adds. + it('returns newly added transactions even when the report is unfocused', () => { + // The diff runs regardless of focus, so a backgrounded table still highlights — design wants background highlighting. const {rerender, result} = renderHook( (props) => useNewTransactions(true, props.transactions, undefined, 'report1', props.isFocused), {initialProps: {transactions: transactionsAlreadyInReport, isFocused: false}}, @@ -477,7 +477,7 @@ describe('useNewTransactions with an unfocused report', () => { expect(result.current).toEqual([]); rerender({transactions: [...transactionsAlreadyInReport, newTransaction], isFocused: false}); - expect(result.current).toEqual([]); + expect(result.current).toEqual([newTransaction]); }); it('returns pending transactions only once the report is focused', () => { From fcac4e9893f6c507432fcb3a705dd9ddc1dc0b59 Mon Sep 17 00:00:00 2001 From: TaduJR Date: Sun, 5 Jul 2026 18:37:31 +0300 Subject: [PATCH 08/11] fix: show the new-row highlight per device background on wide, on-close on narrow --- .../MoneyRequestReportActionsList.tsx | 6 ++++-- .../MoneyRequestReportTransactionList.tsx | 6 +++++- src/hooks/useNewTransactions.ts | 10 ++++++---- tests/unit/useNewTransactionsTest.ts | 16 +++++----------- 4 files changed, 20 insertions(+), 18 deletions(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index 4a2eb35278d3..e26e4fad5f2a 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); @@ -751,6 +752,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 806b7bae2458..15783c4b0511 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportTransactionList.tsx @@ -135,6 +135,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[]; @@ -165,6 +168,7 @@ function MoneyRequestReportTransactionList({ report, transactions, newTransactions, + isReportVisible = true, reportActions, hasPendingDeletionTransaction = false, scrollToNewTransaction, @@ -703,7 +707,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/hooks/useNewTransactions.ts b/src/hooks/useNewTransactions.ts index 37f416602d61..6786b3d4ab94 100644 --- a/src/hooks/useNewTransactions.ts +++ b/src/hooks/useNewTransactions.ts @@ -17,6 +17,8 @@ const EMPTY_TRANSACTIONS: Transaction[] = []; * 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, @@ -36,9 +38,9 @@ function useNewTransactions( const activePendingTransactionIDs = pendingNewTransactionIDs ? Object.keys(pendingNewTransactionIDs).filter((id) => pendingNewTransactionIDs[id]) : []; const railSet = new Set(activePendingTransactionIDs); const railTransactions = - isFocused && reportID && activePendingTransactionIDs.length && transactions?.length ? transactions.filter(({transactionID}) => railSet.has(transactionID)) : EMPTY_TRANSACTIONS; + reportID && activePendingTransactionIDs.length && transactions?.length ? transactions.filter(({transactionID}) => railSet.has(transactionID)) : EMPTY_TRANSACTIONS; - // Diff-detected adds the rail never flagged (e.g. a Pusher add). Focus-independent so a backgrounded table still highlights — design wants background highlighting. + // 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) { @@ -58,10 +60,10 @@ function useNewTransactions( // 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, pendingNewTransactionIDs]); + }, [transactions, reportID, pendingNewTransactionIDs]); useEffect(() => { - // Only the focused consumer clears the rail — else an unfocused diff could clear the flag before the focused view of the same key consumes it. + // 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; } diff --git a/tests/unit/useNewTransactionsTest.ts b/tests/unit/useNewTransactionsTest.ts index 6cc703410c2e..6ebeb77ccf55 100644 --- a/tests/unit/useNewTransactionsTest.ts +++ b/tests/unit/useNewTransactionsTest.ts @@ -618,7 +618,7 @@ describe('useNewTransactions with an unfocused report', () => { }; it('returns newly added transactions even when the report is unfocused', () => { - // The diff runs regardless of focus, so a backgrounded table still highlights — design wants background highlighting. + // Wide (no narrow flag): the table stays visible behind a stacked RHP, so an unfocused add still highlights. const {rerender, result} = renderHook( (props) => useNewTransactions(true, props.transactions, undefined, 'report1', props.isFocused), { @@ -637,16 +637,10 @@ describe('useNewTransactions with an unfocused report', () => { expect(result.current).toEqual([newTransaction]); }); - it('returns pending transactions only once the report is focused', () => { - // The rail stays gated on focus so an unfocused consumer (e.g. a chat report preview) doesn't consume the flag early. + 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 {rerender, result} = renderHook( - (props) => useNewTransactions(true, allTransactions, {[newTransaction.transactionID]: true}, 'report1', props.isFocused), - {initialProps: {isFocused: false}}, - ); - expect(result.current).toEqual([]); - - rerender({isFocused: true}); + const {result} = renderHook(() => useNewTransactions(true, allTransactions, {[newTransaction.transactionID]: true}, 'report1', false)); expect(result.current).toEqual([newTransaction]); }); @@ -703,7 +697,7 @@ describe('useNewTransactions with an unfocused report', () => { }); it('schedules the rail cleanup only from a focused consumer', () => { - // Only a focused consumer schedules the rail cleanup; an unfocused one stays silent and must not clear a flag a later focused mount needs. + // 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', From b177dbc7d0242904fb1fb097baadaa2c97b3af9b Mon Sep 17 00:00:00 2001 From: TaduJR Date: Sun, 5 Jul 2026 19:07:00 +0300 Subject: [PATCH 09/11] fix: gate the report-preview highlight on visibility so it can't play off-screen --- .../ReportActionItem/MoneyRequestReportPreview/index.tsx | 4 +++- tests/unit/useNewTransactionsTest.ts | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx b/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx index 5a482a3da42d..61ef741f3aeb 100644 --- a/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx +++ b/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx @@ -141,7 +141,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/tests/unit/useNewTransactionsTest.ts b/tests/unit/useNewTransactionsTest.ts index 6ebeb77ccf55..0dd5cc99519f 100644 --- a/tests/unit/useNewTransactionsTest.ts +++ b/tests/unit/useNewTransactionsTest.ts @@ -618,7 +618,7 @@ describe('useNewTransactions with an unfocused report', () => { }; it('returns newly added transactions even when the report is unfocused', () => { - // Wide (no narrow flag): the table stays visible behind a stacked RHP, so an unfocused add still highlights. + // 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), { From 0ecd8b7fe04424f44933e7ceba88a535070ca890 Mon Sep 17 00:00:00 2001 From: TaduJR Date: Sun, 5 Jul 2026 19:39:17 +0300 Subject: [PATCH 10/11] fix: don't flash single-expense RHPs at super-wide while transactions load --- src/pages/inbox/WideRHPReceiptPanel.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/pages/inbox/WideRHPReceiptPanel.tsx b/src/pages/inbox/WideRHPReceiptPanel.tsx index 1f71c46f4f0f..1c936abeda2f 100644 --- a/src/pages/inbox/WideRHPReceiptPanel.tsx +++ b/src/pages/inbox/WideRHPReceiptPanel.tsx @@ -63,10 +63,11 @@ 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 || @@ -74,7 +75,7 @@ function WideRHPReceiptPanelGate() { report?.type === CONST.REPORT.TYPE.IOU); let rhpWidth: RHPWidth = 'narrow'; - if (shouldDisplayMoneyRequestActionsList) { + if (isConfirmedMultiTransactionReport) { rhpWidth = 'super-wide'; } else if (shouldShowWideRHP) { rhpWidth = 'wide'; From 79576787dd85c13e45a8d74445be6bc88d750db8 Mon Sep 17 00:00:00 2001 From: TaduJR Date: Sun, 12 Jul 2026 23:04:04 +0300 Subject: [PATCH 11/11] refactor: drop redundant useCallback from useRHPWidth --- src/components/WideRHPContextProvider/useRHPWidth/index.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/components/WideRHPContextProvider/useRHPWidth/index.ts b/src/components/WideRHPContextProvider/useRHPWidth/index.ts index 6e582f8fff35..9eb7cce50fc2 100644 --- a/src/components/WideRHPContextProvider/useRHPWidth/index.ts +++ b/src/components/WideRHPContextProvider/useRHPWidth/index.ts @@ -3,7 +3,7 @@ import {navigationRef} from '@libs/Navigation/Navigation'; import NAVIGATORS from '@src/NAVIGATORS'; import {useRoute} from '@react-navigation/native'; -import {useCallback, useEffect} from 'react'; +import {useEffect} from 'react'; import type {RHPWidth} from '..'; @@ -25,7 +25,7 @@ function useRHPWidth(width: RHPWidth) { const reportID = route.params && 'reportID' in route.params && typeof route.params.reportID === 'string' ? route.params.reportID : ''; const {setRHPWidth, removeRHPRouteKey, getReportRHPWidthHint, unmarkReportRHPWidth} = useWideRHPActions(); - const onClose = useCallback(() => { + 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) { @@ -35,7 +35,7 @@ function useRHPWidth(width: RHPWidth) { if (navigationRef?.getRootState()?.routes?.at(-1)?.name !== NAVIGATORS.RIGHT_MODAL_NAVIGATOR) { expandedRHPProgress.setValue(0); } - }, [removeRHPRouteKey, route, reportID, unmarkReportRHPWidth]); + }; useEffect(() => () => onClose(), [onClose]);