From 2750b503ee99be0294ce333a6239dce740b2e129 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Tue, 16 Jun 2026 13:49:21 +0200 Subject: [PATCH 01/22] Push data hooks into the body, thin out ReportActionsView --- src/hooks/useReportActionsScroll.ts | 7 +- src/pages/inbox/report/ReportActionsList.tsx | 340 ++++++++++++------ src/pages/inbox/report/ReportActionsView.tsx | 241 +------------ .../perf-test/ReportActionsList.perf-test.tsx | 128 +++---- tests/ui/ReportActionsViewTest.tsx | 69 ++-- tests/unit/useReportActionsScrollTest.tsx | 1 + 6 files changed, 372 insertions(+), 414 deletions(-) diff --git a/src/hooks/useReportActionsScroll.ts b/src/hooks/useReportActionsScroll.ts index b69f1493ed6e..c59d0e85adab 100644 --- a/src/hooks/useReportActionsScroll.ts +++ b/src/hooks/useReportActionsScroll.ts @@ -28,8 +28,11 @@ import useReportScrollManager from './useReportScrollManager'; import useScrollToEndOnNewMessageReceived from './useScrollToEndOnNewMessageReceived'; type UseReportActionsScrollParams = { + /** The ID of the report currently being looked at */ + reportID: string; + /** The report currently being looked at */ - report: OnyxTypes.Report; + report: OnyxEntry; /** The transaction thread report associated with the current report, if any */ transactionThreadReport: OnyxEntry; @@ -112,6 +115,7 @@ type UseReportActionsScrollResult = { }; function useReportActionsScroll({ + reportID, report, transactionThreadReport, parentReportAction, @@ -127,7 +131,6 @@ function useReportActionsScroll({ treatAsNoPaginationAnchor, setTreatAsNoPaginationAnchor, }: UseReportActionsScrollParams): UseReportActionsScrollResult { - const reportID = report.reportID; const reportScrollManager = useReportScrollManager(); const {scrollOffsetRef} = useContext(ActionListContext); const route = useRoute>(); diff --git a/src/pages/inbox/report/ReportActionsList.tsx b/src/pages/inbox/report/ReportActionsList.tsx index f5db9e600f7c..25be7c961854 100644 --- a/src/pages/inbox/report/ReportActionsList.tsx +++ b/src/pages/inbox/report/ReportActionsList.tsx @@ -1,24 +1,32 @@ import {useRoute} from '@react-navigation/native'; import {isTrackIntentUserSelector} from '@selectors/Onboarding'; import type {ListRenderItemInfo} from '@shopify/flash-list'; -import React, {memo, useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react'; +import React, {memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react'; import type {LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent} from 'react-native'; import {View} from 'react-native'; import type {OnyxEntry} from 'react-native-onyx'; import {renderScrollComponent as renderActionSheetAwareScrollView} from '@components/ActionSheetAwareScrollView'; import InvertedFlashList from '@components/FlashList/InvertedFlashList'; import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; +import useCopySelectionHelper from '@hooks/useCopySelectionHelper'; +import {useCurrentReportIDState} from '@hooks/useCurrentReportID'; import useEnvironment from '@hooks/useEnvironment'; +import useLoadReportActions from '@hooks/useLoadReportActions'; import useLocalize from '@hooks/useLocalize'; import useMarkAsRead from '@hooks/useMarkAsRead'; import useNetworkWithOfflineStatus from '@hooks/useNetworkWithOfflineStatus'; import useOnyx from '@hooks/useOnyx'; +import useParentReportAction from '@hooks/useParentReportAction'; +import usePendingConciergeResponse from '@hooks/usePendingConciergeResponse'; +import useReportActionsPagination from '@hooks/useReportActionsPagination'; import useReportActionsScroll from '@hooks/useReportActionsScroll'; +import useReportActionsVisibility from '@hooks/useReportActionsVisibility'; import useReportIsArchived from '@hooks/useReportIsArchived'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useThemeStyles from '@hooks/useThemeStyles'; import useUnreadMarker from '@hooks/useUnreadMarker'; import useWindowDimensions from '@hooks/useWindowDimensions'; +import {updateLoadingInitialReportAction} from '@libs/actions/Report'; import {isConsecutiveChronosAutomaticTimerAction} from '@libs/ChronosUtils'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; @@ -34,6 +42,7 @@ import { isTransactionThread, } from '@libs/ReportActionsUtils'; import { + canUserPerformWriteAction, chatIncludesChronosWithID, isArchivedNonExpenseReport, isCanceledTaskReport, @@ -41,18 +50,22 @@ import { isHarvestCreatedExpenseReport, isInvoiceReport, isIOUReport, + isReportTransactionThread as isReportTransactionThreadUtil, isTaskReport, + isUnread, shouldShowMarkAsDone, } from '@libs/ReportUtils'; +import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; import type {ReportsSplitNavigatorParamList} from '@navigation/types'; import {useConciergeDraft, useConciergeDraftActions} from '@pages/inbox/ConciergeDraftContext'; -import {useConciergeSessionState} from '@pages/inbox/ConciergeSessionContext'; +import {useConciergeSessionActions, useConciergeSessionState} from '@pages/inbox/ConciergeSessionContext'; import {ActionListContext} from '@pages/inbox/ReportScreenContext'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type SCREENS from '@src/SCREENS'; import {getStableReportSelector} from '@src/selectors/Report'; import type * as OnyxTypes from '@src/types/onyx'; +import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; import FloatingMessageCounter from './FloatingMessageCounter'; import ReportActionIndexContext from './ReportActionIndexContext'; import ReportActionsListHeader from './ReportActionsListHeader'; @@ -61,61 +74,11 @@ import ReportActionsListPaddingView from './ReportActionsListPaddingView'; import ShowPreviousMessagesButton from './ShowPreviousMessagesButton'; type ReportActionsListProps = { - /** The report currently being looked at */ - report: OnyxTypes.Report; - - /** The transaction thread report associated with the current report, if any */ - transactionThreadReport: OnyxEntry; - - /** The report's parentReportAction */ - parentReportAction: OnyxEntry; - - /** The transaction thread report's parentReportAction */ - parentReportActionForTransactionThread: OnyxEntry; - - /** Sorted actions prepared for display */ - sortedReportActions: OnyxTypes.ReportAction[]; - - /** Sorted actions that should be visible to the user */ - sortedVisibleReportActions: OnyxTypes.ReportAction[]; + /** The ID of the report to display actions for */ + reportID: string; /** Callback executed on list layout */ - onLayout: (event: LayoutChangeEvent) => void; - - /** Callback executed on scroll */ - onScroll?: (event: NativeSyntheticEvent) => void; - - /** Function to load more chats */ - loadOlderChats: (force?: boolean) => void; - - /** Function to load newer chats */ - loadNewerChats: (force?: boolean) => void; - - /** Whether the report has newer actions to load */ - hasNewerActions: boolean; - - /** The oldest unread report action */ - oldestUnreadReportAction?: OnyxEntry | undefined; - - /** Full sorted report actions for collapsing stale pagination after a live-tail jump */ - sortedAllReportActionsForPagination: OnyxTypes.ReportAction[]; - - /** When true, the paginated hook ignores deep-link / unread anchors */ - treatAsNoPaginationAnchor: boolean; - - setTreatAsNoPaginationAnchor: (value: boolean) => void; - - /** Stable key to remount the list when the deep-linked action or unread anchor (or report) changes */ - listID: string; - - /** Whether the chat history is hidden (concierge side panel fresh state) */ - showHiddenHistory?: boolean; - - /** Whether there are previous messages that can be revealed */ - hasPreviousMessages?: boolean; - - /** Callback to show previous messages */ - onShowPreviousMessages?: () => void; + onLayout?: (event: LayoutChangeEvent) => void; }; /** @@ -132,27 +95,7 @@ function keyExtractor(item: OnyxTypes.ReportAction): string { return item.reportActionID; } -function ReportActionsList({ - report, - transactionThreadReport, - parentReportAction, - sortedReportActions, - sortedVisibleReportActions, - onScroll, - loadNewerChats, - loadOlderChats, - hasNewerActions, - oldestUnreadReportAction, - sortedAllReportActionsForPagination, - treatAsNoPaginationAnchor, - setTreatAsNoPaginationAnchor, - onLayout, - listID, - parentReportActionForTransactionThread, - showHiddenHistory, - hasPreviousMessages, - onShowPreviousMessages, -}: ReportActionsListProps) { +function ReportActionsList({reportID, onLayout}: ReportActionsListProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); const {windowHeight} = useWindowDimensions(); @@ -161,20 +104,134 @@ function ReportActionsList({ const {isOffline} = useNetworkWithOfflineStatus(); const route = useRoute>(); - const {scrollOffsetRef} = useContext(ActionListContext); - const {draftReportAction, hasActiveDraft, isDraftPendingCompletion} = useConciergeDraft(); - const {clearDraft} = useConciergeDraftActions(); - const {sessionStartTime: conciergeSessionStartTime} = useConciergeSessionState(); + const reportActionIDFromRoute = route?.params?.reportActionID; + + // Side effects that must run whenever the chat list is shown. + useCopySelectionHelper(); + usePendingConciergeResponse(reportID); + + const [report, reportResult] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); + + const { + reportActions, + allReportActions, + allReportActionIDs, + hasOlderActions, + hasNewerActions, + sortedAllReportActions, + oldestUnreadReportAction, + transactionThreadReportID, + transactionThreadReport, + parentReportActionForTransactionThread, + treatAsNoPaginationAnchor, + setTreatAsNoPaginationAnchor, + reportPreviewAction, + } = useReportActionsPagination(reportID, reportActionIDFromRoute); + + const parentReportAction = useParentReportAction(report); + + const [reportLoadingState] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${reportID}`); + const isLoadingInitialReportActions = reportLoadingState?.isLoadingInitialReportActions; + const hasOnceLoadedReportActions = reportLoadingState?.hasOnceLoadedReportActions; + + const {currentReportID} = useCurrentReportIDState(); + const {sessionStartTime, showFullHistory: conciergeShowFullHistory, hadMessagesAtSessionStart: conciergeHadMessagesAtSessionStart} = useConciergeSessionState(); + const {startSession, setShowFullHistory: setConciergeShowFullHistory, setHadMessagesAtSessionStart: setConciergeHadMessagesAtSessionStart} = useConciergeSessionActions(); + const isReportTransactionThread = isReportTransactionThreadUtil(report); + + const isReportArchived = useReportIsArchived(reportID); + const canPerformWriteAction = !!canUserPerformWriteAction(report, isReportArchived); + + const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); + + const [reportPaginationState] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_PAGINATION_STATE}${reportID}`); + + const didLayout = useRef(false); + + useEffect(() => { + didLayout.current = false; + }, [reportID]); + + useEffect(() => { + // When we linked to message - we do not need to wait for initial actions - they already exists + if (!reportActionIDFromRoute || !isOffline) { + return; + } + updateLoadingInitialReportAction(report?.reportID ?? reportID); + }, [isOffline, report?.reportID, reportID, reportActionIDFromRoute]); + + // Remount the list when the deep-linked message or unread anchor changes (scroll positioning), or when the report changes. + const listID = [reportID, reportActionIDFromRoute, hasOnceLoadedReportActions ? undefined : oldestUnreadReportAction?.reportActionID].join(':'); + + const {loadOlderChats, loadNewerChats} = useLoadReportActions({ + reportID, + reportActions, + allReportActionIDs, + transactionThreadReportID, + hasOlderActions, + hasNewerActions, + newestFetchedReportActionID: reportPaginationState?.newestFetchedReportActionID, + }); - const isReportArchived = useReportIsArchived(report?.reportID); - const [reportLoadingState] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${report.reportID}`); - const [reportNameValuePairs] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report.reportID}`); + const { + sortedReportActions, + sortedVisibleReportActions, + isConciergeMainDM, + isConciergeHiddenHistory, + showConciergeSidePanelWelcome, + showFullHistory, + hasPreviousMessages, + handleShowPreviousMessages, + } = useReportActionsVisibility({ + reportID, + reportActions, + allReportActions, + canPerformWriteAction, + hasOlderActions, + loadOlderChats, + mainDMSessionStartTime: sessionStartTime, + conciergeShowFullHistory: conciergeShowFullHistory || !!reportActionIDFromRoute || !!report?.hasOutstandingChildTask, + setConciergeShowFullHistory, + conciergeHadMessagesAtSessionStart, + setConciergeHadMessagesAtSessionStart, + }); + + // hasOnceLoadedReportActions is RAM-only and resets to falsy on a page + // refresh, but cached report actions persist in Onyx. Gating the session + // start on it alone would leave sessionStartTime null until openReport + // returns, during which filterActions collapses the cached history down to + // just the synthetic CREATED action (an almost-empty chat flash). Start the + // session as soon as cached actions exist so messages render immediately on + // refresh, matching the skeleton-suppression gate below. + const canStartConciergeSession = !!hasOnceLoadedReportActions || allReportActions.length > 0; + + useLayoutEffect(() => { + if (!isConciergeMainDM || !canStartConciergeSession) { + return; + } + startSession(oldestUnreadReportAction ? report?.lastReadTime : undefined); + // eslint-disable-next-line react-hooks/exhaustive-deps -- startSession is stable; captured values at mount only + }, [isConciergeMainDM, startSession, canStartConciergeSession]); + + // On native the component stays mounted in the navigation stack, so the + // effect above never re-fires (its isConciergeMainDM dep is always true). + // Re-trigger startSession when the globally-focused report matches this + // report so the session age check runs after navigating away and back. + useLayoutEffect(() => { + if (!isConciergeMainDM || !canStartConciergeSession || currentReportID !== reportID) { + return; + } + startSession(oldestUnreadReportAction ? report?.lastReadTime : undefined); + // eslint-disable-next-line react-hooks/exhaustive-deps -- only react to currentReportID returning to this report + }, [currentReportID, reportID, isConciergeMainDM, canStartConciergeSession, startSession]); + + const [reportNameValuePairs] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${reportID}`); const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector}); const [policy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${getNonEmptyStringOnyxID(report?.policyID)}`); const reportAttributesSelector = useCallback( (value: OnyxEntry) => { - const attrs = value?.reports?.[report.reportID]; + const attrs = value?.reports?.[reportID]; if (!attrs) { return undefined; } @@ -184,7 +241,7 @@ function ReportActionsList({ brickRoadStatus: attrs.brickRoadStatus, }; }, - [report.reportID], + [reportID], ); const [reportAttributes] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, { selector: reportAttributesSelector, @@ -192,26 +249,33 @@ function ReportActionsList({ const isHarvestCreatedExpenseReportAction = isHarvestCreatedExpenseReport(reportNameValuePairs?.origin, reportNameValuePairs?.originalID); const stableReportSelector = useCallback((reportEntry: OnyxEntry) => getStableReportSelector(reportEntry), []); - const [reportStable] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`, {selector: stableReportSelector}); + const [reportStable] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {selector: stableReportSelector}); const [chatReportStable] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${getNonEmptyStringOnyxID(reportStable?.chatReportID)}`, {selector: stableReportSelector}); - const linkedReportActionID = route?.params?.reportActionID; + const linkedReportActionID = reportActionIDFromRoute; const hasHeaderRendered = useRef(false); + const {scrollOffsetRef} = useContext(ActionListContext); + const {draftReportAction, hasActiveDraft, isDraftPendingCompletion} = useConciergeDraft(); + const {clearDraft} = useConciergeDraftActions(); + + const showHiddenHistory = isConciergeHiddenHistory && !showFullHistory; + const onShowPreviousMessages = handleShowPreviousMessages; + const [hasScrolledOverThreshold, setHasScrolledOverThreshold] = useState(() => scrollOffsetRef.current >= CONST.REPORT.ACTIONS.ACTION_VISIBLE_THRESHOLD); const {unreadMarkerReportActionID, unreadMarkerReportActionIndex} = useUnreadMarker({ - reportID: report.reportID, + reportID, sortedVisibleReportActions, sortedReportActions, oldestUnreadReportActionID: oldestUnreadReportAction?.reportActionID, isScrolledOverThreshold: hasScrolledOverThreshold, - hasOnceLoadedReportActions: !!reportLoadingState?.hasOnceLoadedReportActions, + hasOnceLoadedReportActions: !!hasOnceLoadedReportActions, }); const {markNewestActionAsRead, completeSkippedMarkAsRead} = useMarkAsRead({ - reportID: report.reportID, + reportID, report, transactionThreadReport, sortedVisibleReportActions, @@ -224,7 +288,7 @@ function ReportActionsList({ return sortedVisibleReportActions; } - if (showHiddenHistory && conciergeSessionStartTime && draftReportAction.created < conciergeSessionStartTime) { + if (showHiddenHistory && sessionStartTime && draftReportAction.created < sessionStartTime) { return sortedVisibleReportActions; } @@ -249,7 +313,7 @@ function ReportActionsList({ const visibleReportActionsWithDraft = [...sortedVisibleReportActions]; visibleReportActionsWithDraft.push(draftReportAction); return visibleReportActionsWithDraft; - }, [conciergeSessionStartTime, draftReportAction, isDraftPendingCompletion, showHiddenHistory, sortedVisibleReportActions]); + }, [sessionStartTime, draftReportAction, isDraftPendingCompletion, showHiddenHistory, sortedVisibleReportActions]); const draftMessageHTML = draftReportAction ? getReportActionMessage(draftReportAction)?.html : undefined; const draftReportActionID = draftReportAction?.reportActionID; @@ -288,6 +352,7 @@ function ReportActionsList({ shouldAutoscrollToBottom, onLoad, } = useReportActionsScroll({ + reportID, report, transactionThreadReport, parentReportAction, @@ -299,7 +364,7 @@ function ReportActionsList({ hasNewerActions, draftAutoScrollKey, actionBadgeTargetIndex, - sortedAllReportActionsForPagination, + sortedAllReportActionsForPagination: sortedAllReportActions ?? [], treatAsNoPaginationAnchor, setTreatAsNoPaginationAnchor, }); @@ -307,7 +372,6 @@ function ReportActionsList({ const trackScrollPositionAndThreshold = (event: NativeSyntheticEvent) => { trackVerticalScrolling(event); setHasScrolledOverThreshold(event.nativeEvent.contentOffset.y >= CONST.REPORT.ACTIONS.ACTION_VISIBLE_THRESHOLD); - onScroll?.(event); }; const loadNewerChatsAfterTransitions = () => { @@ -328,7 +392,7 @@ function ReportActionsList({ // Same-screen report switches reuse this instance; per-report one-shot flags must not leak across reports. useEffect(() => { hasHeaderRendered.current = false; - }, [report.reportID]); + }, [reportID]); /** * Thread's divider line should hide when the first chat in the thread is marked as unread. @@ -453,22 +517,22 @@ function ReportActionsList({ return ( loadNewerChats(true)} hasActiveDraft={hasActiveDraft} /> ); - }, [canShowHeader, hasActiveDraft, report.reportID, loadNewerChats, shouldBeAlignedToTop]); + }, [canShowHeader, hasActiveDraft, reportID, loadNewerChats, shouldBeAlignedToTop]); - const shouldShowSkeleton = isOffline && !sortedVisibleReportActions.some((action) => action.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED); + const shouldShowOfflineSkeleton = isOffline && !sortedVisibleReportActions.some((action) => action.actionName === CONST.REPORT.ACTIONS.TYPE.CREATED); const listFooterComponent = useMemo(() => { - if (!shouldShowSkeleton) { + if (!shouldShowOfflineSkeleton) { return; } return ; - }, [shouldShowSkeleton]); + }, [shouldShowOfflineSkeleton]); const shouldUseMarkAsDoneCopy = shouldShowMarkAsDone({ policy, @@ -476,6 +540,80 @@ function ReportActionsList({ isTrackIntentUser, }); + const isSingleExpenseReport = reportPreviewAction?.childMoneyRequestCount === 1; + const isMissingTransactionThreadReportID = !transactionThreadReport?.reportID; + const isReportDataIncomplete = isSingleExpenseReport && isMissingTransactionThreadReportID; + const isMissingReportActions = sortedVisibleReportActions.length === 0; + + /** + * Runs when the FlatList finishes laying out + */ + const recordTimeToMeasureItemLayout = (event: LayoutChangeEvent) => { + onLayout?.(event); + if (didLayout.current) { + return; + } + + didLayout.current = true; + + if (report) { + markOpenReportEnd(report, {warm: true}); + } + }; + + // Show skeleton while loading initial report actions when data is incomplete/missing and online + const shouldShowSkeletonForInitialLoad = !!isLoadingInitialReportActions && (isReportDataIncomplete || isMissingReportActions) && !isOffline; + + // Show skeleton while the app is loading and we're online + const shouldShowSkeletonForAppLoad = isLoadingApp && !isOffline; + + // Show skeleton for the Concierge chat (side panel or main DM) until report + // data has been loaded at least once. Before the first openReport response, + // hasOlderActions is unreliable, so we can't determine whether to show the + // greeting or onboarding messages. The skeleton avoids flashing wrong content. + // hasOnceLoadedReportActions is RAM-only and resets on a page refresh, but + // cached report actions persist in Onyx. For the main DM, render those cached + // actions immediately (matching production) instead of flashing a skeleton on + // every refresh; the side panel always opens fresh so it keeps gating on + // hasOnceLoadedReportActions only. allReportActions excludes the synthetic + // CREATED action that is always injected for Concierge, so it is empty only on + // a genuinely cold load with no cached history. + const shouldShowSkeletonForConciergePanel = isConciergeHiddenHistory && !hasOnceLoadedReportActions && !(isConciergeMainDM && allReportActions.length > 0) && !isOffline; + + const shouldShowInitialSkeleton = shouldShowSkeletonForConciergePanel || shouldShowSkeletonForInitialLoad || shouldShowSkeletonForAppLoad; + + useEffect(() => { + if (!shouldShowInitialSkeleton || !report) { + return; + } + markOpenReportEnd(report, {warm: false}); + }, [report, shouldShowInitialSkeleton]); + + const isReportUnread = isUnread(report, transactionThreadReport, isReportArchived); + + // When opening an unread report, it is very likely that the message we will open to is not the latest, + // which is the only one we will have in cache. + const isInitiallyLoadingReport = isReportUnread && !!reportLoadingState?.isLoadingInitialReportActions && reportActions.length <= 1; + + // Same for unread messages, we need to wait for the results from the OpenReport API call + // if the oldest unread report action is not available yet. Only applies during the *first* load + // for this report: after `hasOnceLoadedReportActions` is set, a later "mark as unread" must not + // bring back this loading gate (we are not re-opening the report from a cold cache). + const isUnreadMessagePageLoadingInitially = !reportActionIDFromRoute && isReportUnread && !oldestUnreadReportAction && !hasOnceLoadedReportActions; + + // Once all the above conditions are met, we can consider the report ready. + const isReportLoading = isInitiallyLoadingReport || isUnreadMessagePageLoadingInitially; + const isReportReady = isOffline || !isReportLoading; + + if (isLoadingOnyxValue(reportResult) || !report || !isReportReady || shouldShowInitialSkeleton) { + return ; + } + + const hasDerivedValueTimingIssue = reportActions.length > 0 && isMissingReportActions; + if ((hasDerivedValueTimingIssue || (!isReportTransactionThread && isMissingReportActions)) && !showConciergeSidePanelWelcome) { + return ; + } + return ( <> { - onLayout(event); + recordTimeToMeasureItemLayout(event); flushPendingScrollToBottom(); }} onScroll={trackScrollPositionAndThreshold} diff --git a/src/pages/inbox/report/ReportActionsView.tsx b/src/pages/inbox/report/ReportActionsView.tsx index 384511099632..e4c2d5d61861 100755 --- a/src/pages/inbox/report/ReportActionsView.tsx +++ b/src/pages/inbox/report/ReportActionsView.tsx @@ -1,24 +1,8 @@ -import {useRoute} from '@react-navigation/native'; -import React, {useEffect, useLayoutEffect, useRef} from 'react'; +import React from 'react'; import type {LayoutChangeEvent} from 'react-native'; -import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; -import useCopySelectionHelper from '@hooks/useCopySelectionHelper'; -import {useCurrentReportIDState} from '@hooks/useCurrentReportID'; -import useLoadReportActions from '@hooks/useLoadReportActions'; -import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; -import useParentReportAction from '@hooks/useParentReportAction'; -import usePendingConciergeResponse from '@hooks/usePendingConciergeResponse'; -import useReportActionsPagination from '@hooks/useReportActionsPagination'; -import useReportActionsVisibility from '@hooks/useReportActionsVisibility'; -import useReportIsArchived from '@hooks/useReportIsArchived'; -import {updateLoadingInitialReportAction} from '@libs/actions/Report'; -import {canUserPerformWriteAction, isReportTransactionThread as isReportTransactionThreadUtil, isUnread} from '@libs/ReportUtils'; -import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; -import {useConciergeSessionActions, useConciergeSessionState} from '@pages/inbox/ConciergeSessionContext'; -import type ReportScreenNavigationProps from '@pages/inbox/types'; import ONYXKEYS from '@src/ONYXKEYS'; -import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; +import {getStableReportSelector} from '@src/selectors/Report'; import ReportActionsList from './ReportActionsList'; import UserTypingEventListener from './UserTypingEventListener'; @@ -30,224 +14,23 @@ type ReportActionsViewProps = { onLayout?: (event: LayoutChangeEvent) => void; }; +/** + * Thin host around the hook-driven ReportActionsList body. It owns the report + * subscription needed to mount the typing listener; all data orchestration and + * skeleton handling now live inside the body itself. + */ function ReportActionsView({reportID, onLayout}: ReportActionsViewProps) { - const route = useRoute(); - const reportActionIDFromRoute = route?.params?.reportActionID; + const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {selector: getStableReportSelector}); - useCopySelectionHelper(); - usePendingConciergeResponse(reportID); - const {isOffline} = useNetwork(); - - const [report, reportResult] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); - - const { - reportActions, - allReportActions, - allReportActionIDs, - hasOlderActions, - hasNewerActions, - sortedAllReportActions, - oldestUnreadReportAction, - transactionThreadReportID, - transactionThreadReport, - parentReportActionForTransactionThread, - treatAsNoPaginationAnchor, - setTreatAsNoPaginationAnchor, - reportPreviewAction, - } = useReportActionsPagination(reportID, reportActionIDFromRoute); - - const parentReportAction = useParentReportAction(report); - - const [reportLoadingState] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${reportID}`); - const isLoadingInitialReportActions = reportLoadingState?.isLoadingInitialReportActions; - const hasOnceLoadedReportActions = reportLoadingState?.hasOnceLoadedReportActions; - - const {currentReportID} = useCurrentReportIDState(); - const {sessionStartTime: mainDMSessionStartTime, showFullHistory: conciergeShowFullHistory, hadMessagesAtSessionStart: conciergeHadMessagesAtSessionStart} = useConciergeSessionState(); - const {startSession, setShowFullHistory: setConciergeShowFullHistory, setHadMessagesAtSessionStart: setConciergeHadMessagesAtSessionStart} = useConciergeSessionActions(); - const isReportTransactionThread = isReportTransactionThreadUtil(report); - - const isReportArchived = useReportIsArchived(reportID); - const canPerformWriteAction = !!canUserPerformWriteAction(report, isReportArchived); - - const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); - - const [reportPaginationState] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_PAGINATION_STATE}${reportID}`); - - const didLayout = useRef(false); - - useEffect(() => { - didLayout.current = false; - }, [reportID]); - - useEffect(() => { - // When we linked to message - we do not need to wait for initial actions - they already exists - if (!reportActionIDFromRoute || !isOffline) { - return; - } - updateLoadingInitialReportAction(report?.reportID ?? reportID); - }, [isOffline, report?.reportID, reportID, reportActionIDFromRoute]); - - // Remount the list when the deep-linked message or unread anchor changes (scroll positioning), or when the report changes. - const listID = [reportID, reportActionIDFromRoute, hasOnceLoadedReportActions ? undefined : oldestUnreadReportAction?.reportActionID].join(':'); - - const {loadOlderChats, loadNewerChats} = useLoadReportActions({ - reportID, - reportActions, - allReportActionIDs, - transactionThreadReportID, - hasOlderActions, - hasNewerActions, - newestFetchedReportActionID: reportPaginationState?.newestFetchedReportActionID, - }); - - const { - sortedReportActions, - sortedVisibleReportActions, - isConciergeMainDM, - isConciergeHiddenHistory, - showConciergeSidePanelWelcome, - showFullHistory, - hasPreviousMessages, - handleShowPreviousMessages, - } = useReportActionsVisibility({ - reportID, - reportActions, - allReportActions, - canPerformWriteAction, - hasOlderActions, - loadOlderChats, - mainDMSessionStartTime, - conciergeShowFullHistory: conciergeShowFullHistory || !!reportActionIDFromRoute || !!report?.hasOutstandingChildTask, - setConciergeShowFullHistory, - conciergeHadMessagesAtSessionStart, - setConciergeHadMessagesAtSessionStart, - }); - - // hasOnceLoadedReportActions is RAM-only and resets to falsy on a page - // refresh, but cached report actions persist in Onyx. Gating the session - // start on it alone would leave sessionStartTime null until openReport - // returns, during which filterActions collapses the cached history down to - // just the synthetic CREATED action (an almost-empty chat flash). Start the - // session as soon as cached actions exist so messages render immediately on - // refresh, matching the skeleton-suppression gate below. - const canStartConciergeSession = !!hasOnceLoadedReportActions || allReportActions.length > 0; - - useLayoutEffect(() => { - if (!isConciergeMainDM || !canStartConciergeSession) { - return; - } - startSession(oldestUnreadReportAction ? report?.lastReadTime : undefined); - // eslint-disable-next-line react-hooks/exhaustive-deps -- startSession is stable; captured values at mount only - }, [isConciergeMainDM, startSession, canStartConciergeSession]); - - // On native the component stays mounted in the navigation stack, so the - // effect above never re-fires (its isConciergeMainDM dep is always true). - // Re-trigger startSession when the globally-focused report matches this - // report so the session age check runs after navigating away and back. - useLayoutEffect(() => { - if (!isConciergeMainDM || !canStartConciergeSession || currentReportID !== reportID) { - return; - } - startSession(oldestUnreadReportAction ? report?.lastReadTime : undefined); - // eslint-disable-next-line react-hooks/exhaustive-deps -- only react to currentReportID returning to this report - }, [currentReportID, reportID, isConciergeMainDM, canStartConciergeSession, startSession]); - - const isSingleExpenseReport = reportPreviewAction?.childMoneyRequestCount === 1; - const isMissingTransactionThreadReportID = !transactionThreadReport?.reportID; - const isReportDataIncomplete = isSingleExpenseReport && isMissingTransactionThreadReportID; - const isMissingReportActions = sortedVisibleReportActions.length === 0; - - /** - * Runs when the FlatList finishes laying out - */ - const recordTimeToMeasureItemLayout = (event: LayoutChangeEvent) => { - onLayout?.(event); - if (didLayout.current) { - return; - } - - didLayout.current = true; - - if (report) { - markOpenReportEnd(report, {warm: true}); - } - }; - - // Show skeleton while loading initial report actions when data is incomplete/missing and online - const shouldShowSkeletonForInitialLoad = !!isLoadingInitialReportActions && (isReportDataIncomplete || isMissingReportActions) && !isOffline; - - // Show skeleton while the app is loading and we're online - const shouldShowSkeletonForAppLoad = isLoadingApp && !isOffline; - - // Show skeleton for the Concierge chat (side panel or main DM) until report - // data has been loaded at least once. Before the first openReport response, - // hasOlderActions is unreliable, so we can't determine whether to show the - // greeting or onboarding messages. The skeleton avoids flashing wrong content. - // hasOnceLoadedReportActions is RAM-only and resets on a page refresh, but - // cached report actions persist in Onyx. For the main DM, render those cached - // actions immediately (matching production) instead of flashing a skeleton on - // every refresh; the side panel always opens fresh so it keeps gating on - // hasOnceLoadedReportActions only. allReportActions excludes the synthetic - // CREATED action that is always injected for Concierge, so it is empty only on - // a genuinely cold load with no cached history. - const shouldShowSkeletonForConciergePanel = isConciergeHiddenHistory && !hasOnceLoadedReportActions && !(isConciergeMainDM && allReportActions.length > 0) && !isOffline; - - const shouldShowSkeleton = shouldShowSkeletonForConciergePanel || shouldShowSkeletonForInitialLoad || shouldShowSkeletonForAppLoad; - - useEffect(() => { - if (!shouldShowSkeleton || !report) { - return; - } - markOpenReportEnd(report, {warm: false}); - }, [report, shouldShowSkeleton]); - - const isReportUnread = isUnread(report, transactionThreadReport, isReportArchived); - - // When opening an unread report, it is very likely that the message we will open to is not the latest, - // which is the only one we will have in cache. - const isInitiallyLoadingReport = isReportUnread && !!reportLoadingState?.isLoadingInitialReportActions && reportActions.length <= 1; - - // Same for unread messages, we need to wait for the results from the OpenReport API call - // if the oldest unread report action is not available yet. Only applies during the *first* load - // for this report: after `hasOnceLoadedReportActions` is set, a later "mark as unread" must not - // bring back this loading gate (we are not re-opening the report from a cold cache). - const isUnreadMessagePageLoadingInitially = !reportActionIDFromRoute && isReportUnread && !oldestUnreadReportAction && !hasOnceLoadedReportActions; - - // Once all the above conditions are met, we can consider the report ready. - const isReportLoading = isInitiallyLoadingReport || isUnreadMessagePageLoadingInitially; - const isReportReady = isOffline || !isReportLoading; - - if (isLoadingOnyxValue(reportResult) || !report || !isReportReady || shouldShowSkeleton) { - return ; - } - - const hasDerivedValueTimingIssue = reportActions.length > 0 && isMissingReportActions; - if ((hasDerivedValueTimingIssue || (!isReportTransactionThread && isMissingReportActions)) && !showConciergeSidePanelWelcome) { - return ; + if (!reportID || !report) { + return null; } return ( <> diff --git a/tests/perf-test/ReportActionsList.perf-test.tsx b/tests/perf-test/ReportActionsList.perf-test.tsx index 34be32abe350..0de9be30fde4 100644 --- a/tests/perf-test/ReportActionsList.perf-test.tsx +++ b/tests/perf-test/ReportActionsList.perf-test.tsx @@ -1,10 +1,8 @@ import {NavigationContainer} from '@react-navigation/native'; -import {screen} from '@testing-library/react-native'; -import type {ComponentType} from 'react'; +import {act, screen} from '@testing-library/react-native'; import Onyx from 'react-native-onyx'; import {measureRenders} from 'reassure'; import OnyxListItemProvider from '@components/OnyxListItemProvider'; -import type {WithCurrentUserPersonalDetailsProps} from '@components/withCurrentUserPersonalDetails'; import type Navigation from '@libs/Navigation/Navigation'; import navigationRef from '@libs/Navigation/navigationRef'; import {setHasRadio} from '@libs/NetworkState'; @@ -13,46 +11,17 @@ import {ActionListContext, ReactionListContext} from '@pages/inbox/ReportScreenC import {AttachmentModalContextProvider} from '@pages/media/AttachmentModalScreen/AttachmentModalContext'; import ComposeProviders from '@src/components/ComposeProviders'; import {LocaleContextProvider} from '@src/components/LocaleContextProvider'; +import CONST from '@src/CONST'; +import IntlStore from '@src/languages/IntlStore'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {PersonalDetailsList} from '@src/types/onyx'; -import createRandomReportAction from '../utils/collections/reportActions'; -import {createRandomReport} from '../utils/collections/reports'; +import type {PersonalDetailsList, ReportAction, ReportActions} from '@src/types/onyx'; import * as ReportTestUtils from '../utils/ReportTestUtils'; import * as TestHelper from '../utils/TestHelper'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; import wrapOnyxWithWaitForBatchedUpdates from '../utils/wrapOnyxWithWaitForBatchedUpdates'; -const REPORT_ACTIONS_LIST_ID = 'perf-test-list'; - -type LazyLoadLHNTestUtils = { - fakePersonalDetails: PersonalDetailsList; -}; - const mockedNavigate = jest.fn(); -jest.mock('@components/withCurrentUserPersonalDetails', () => { - // Lazy loading of LHNTestUtils - const lazyLoadLHNTestUtils = () => require('../utils/LHNTestUtils'); - - return (Component: ComponentType) => { - function WrappedComponent(props: Omit) { - const currentUserAccountID = 5; - const LHNTestUtils = lazyLoadLHNTestUtils(); // Load LHNTestUtils here - - return ( - - ); - } - - WrappedComponent.displayName = 'WrappedComponent'; - - return WrappedComponent; - }; -}); - jest.mock('@react-navigation/native', () => { const actualNav = jest.requireActual('@react-navigation/native'); return { @@ -62,8 +31,6 @@ jest.mock('@react-navigation/native', () => { }; }); -jest.mock('@src/components/ConfirmedRoute.tsx'); - beforeAll(() => Onyx.init({ keys: ONYXKEYS, @@ -72,8 +39,6 @@ beforeAll(() => ); const mockOnLayout = jest.fn(); -const mockOnScroll = jest.fn(); -const mockLoadChats = jest.fn(); const mockRef = {current: null, flatListRef: null, scrollPositionRef: {current: {}}, scrollOffsetRef: {current: 0}}; const mockReactionListContextValue = { showReactionList: () => {}, @@ -84,47 +49,90 @@ const mockReactionListContextValue = { const TEST_USER_ACCOUNT_ID = 1; const TEST_USER_LOGIN = 'test@test.com'; +const REPORT_ID = '1'; + const signUpWithTestUser = () => { TestHelper.signInWithTestUser(TEST_USER_ACCOUNT_ID, TEST_USER_LOGIN); }; -const report = createRandomReport(1, undefined); -const parentReportAction = createRandomReportAction(1); +// Seed 500 report actions through Onyx (keyed by reportActionID, as production stores them) so the +// hook-driven body fetches and runs the real pagination + visibility pipeline — instead of receiving a +// pre-sorted array via props as the previous harness did. This is strictly more production-faithful, so +// the measured number is a fresh baseline and is not comparable to the pre-PR-6 figure. +const sortedReportActions = ReportTestUtils.getMockedSortedReportActions(500); +const reportActions: ReportActions = Object.fromEntries(sortedReportActions.map((action: ReportAction) => [action.reportActionID, action])); +const report = ReportTestUtils.createMockReport({reportID: REPORT_ID, lastVisibleActionCreated: sortedReportActions.at(0)?.created}); + +// getFakeReportAction sets actorAccountID = index, so the 500 mocked actions have actors 1..500 +const ACTOR_PERSONAL_DETAILS: PersonalDetailsList = Object.fromEntries( + Array.from({length: 500}, (_, i) => { + const accountID = i + 1; + return [ + accountID, + { + accountID, + login: `user${accountID}@test.com`, + avatar: 'https://d2k5nsl2zxldvw.cloudfront.net/images/avatars/avatar_7.png', + avatarThumbnail: 'https://d2k5nsl2zxldvw.cloudfront.net/images/avatars/avatar_7.png', + displayName: `User ${accountID}`, + firstName: 'User', + lastName: `${accountID}`, + pronouns: '', + timezone: CONST.DEFAULT_TIME_ZONE, + phoneNumber: '', + }, + ]; + }), +); -beforeEach(() => { +beforeEach(async () => { // Initialize the network key for OfflineWithFeedback setHasRadio(true); wrapOnyxWithWaitForBatchedUpdates(Onyx); - signUpWithTestUser(); + // Pre-seed the locale so LocaleContextProvider's mount effect is a no-op (setLocale/IntlStore.load + // early-return), avoiding post-mount Onyx writes that re-render outside act(). Personal details back + // the 500 actors so avatars/display names resolve through the real selectors. + await act(async () => { + signUpWithTestUser(); + await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, ACTOR_PERSONAL_DETAILS); + await Onyx.merge(ONYXKEYS.NVP_PREFERRED_LOCALE, CONST.LOCALES.DEFAULT); + await IntlStore.load(CONST.LOCALES.DEFAULT); + + // Seed the report under test: the report, its 500 actions, and a settled loading state. + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, report); + await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${REPORT_ID}`, reportActions); + await Onyx.set(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${REPORT_ID}`, { + isLoadingInitialReportActions: false, + hasOnceLoadedReportActions: true, + isLoadingOlderReportActions: false, + hasLoadingOlderReportActionsError: false, + isLoadingNewerReportActions: false, + hasLoadingNewerReportActionsError: false, + }); + await waitForBatchedUpdates(); + }); }); -afterEach(() => { - Onyx.clear(); +afterEach(async () => { + // Await the clear so its broadcasts settle in teardown instead of leaking into the next test. + await Onyx.clear(); + await waitForBatchedUpdates(); }); +// Mirror the production data flow (usePaginatedReportActions): the wrapper plays the role of the parent +// (ReportActionsView) — it reads REPORT_ACTIONS from Onyx and sorts inside a useOnyx selector, instead of +// holding the actions in local state. "Sending a message" is then an Onyx.merge into REPORT_ACTIONS +// (exactly like addActions' optimistic update), so the list updates through the real subscription/selector +// path rather than prop injection. function ReportActionsListWrapper() { - const reportActions = ReportTestUtils.getMockedSortedReportActions(500); return ( {}} - transactionThreadReport={report} /> diff --git a/tests/ui/ReportActionsViewTest.tsx b/tests/ui/ReportActionsViewTest.tsx index 3ef5ee8e5f25..a0cd75bfa344 100644 --- a/tests/ui/ReportActionsViewTest.tsx +++ b/tests/ui/ReportActionsViewTest.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-unsafe-type-assertion */ import type * as ReactNavigation from '@react-navigation/native'; import {render, screen} from '@testing-library/react-native'; import React from 'react'; @@ -96,20 +97,44 @@ jest.mock('@hooks/usePrevious', () => jest.fn()); const mockUseCurrentUserPersonalDetails = useCurrentUserPersonalDetails as jest.MockedFunction; -jest.mock('@pages/inbox/report/ReportActionsList', () => - jest.fn(({sortedReportActions}: {sortedReportActions: OnyxTypes.ReportAction[]}) => { - if (sortedReportActions && sortedReportActions.length > 0) { - return null; // Simulate normal content - } - return null; - }), +// PR 6 makes the ReportActionsList body hook-driven, so we mount the REAL body (no longer a prop-fed +// child) and observe what it feeds the list via InvertedFlashList's `data`. The heavy scroll/marker +// hooks have their own unit tests, so they are stubbed here to isolate the body's visibility/skeleton +// logic — the actual subject of these tests. +jest.mock('@components/FlashList/InvertedFlashList', () => jest.fn(() => null)); +jest.mock('@hooks/useUnreadMarker', () => jest.fn(() => ({unreadMarkerReportActionID: null, unreadMarkerReportActionIndex: -1}))); +jest.mock('@hooks/useMarkAsRead', () => jest.fn(() => ({markNewestActionAsRead: jest.fn(), completeSkippedMarkAsRead: jest.fn()}))); +jest.mock('@hooks/useReportActionsScroll', () => + jest.fn(() => ({ + listRef: {current: null}, + trackVerticalScrolling: jest.fn(), + onViewableItemsChanged: jest.fn(), + isFloatingMessageCounterVisible: false, + isActionBadgeAboveViewport: false, + scrollToBottomAndMarkReportAsRead: jest.fn(), + scrollToActionBadgeTarget: jest.fn(), + flushPendingScrollToBottom: jest.fn(), + shouldBeAlignedToTop: false, + shouldFocusToTopOnMount: false, + initialScrollKey: undefined, + shouldAutoscrollToBottom: false, + onLoad: jest.fn(), + })), ); +jest.mock('@pages/inbox/report/FloatingMessageCounter', () => jest.fn(() => null)); +jest.mock('@pages/inbox/report/ReportActionsListPaddingView', () => { + const reactModule = jest.requireActual('react'); + return jest.fn(({children}: {children: React.ReactNode}) => reactModule.createElement(reactModule.Fragment, null, children)); +}); jest.mock('@pages/inbox/report/UserTypingEventListener', () => jest.fn(() => null)); jest.mock('@pages/inbox/report/ReportActionItemCreated', () => jest.fn(() => null)); -const mockReportActionsList: jest.Mock = jest.requireMock('@pages/inbox/report/ReportActionsList'); +const mockInvertedFlashList: jest.MockedFunction<(props: {data?: OnyxTypes.ReportAction[]}) => null> = jest.requireMock('@components/FlashList/InvertedFlashList'); const mockReportActionItemCreated: jest.Mock = jest.requireMock('@pages/inbox/report/ReportActionItemCreated'); +/** Returns the report actions the body fed into the (mocked) inverted list on its latest render. */ +const getCapturedVisibleActions = (): OnyxTypes.ReportAction[] | undefined => mockInvertedFlashList.mock.calls.at(-1)?.at(0)?.data; + jest.mock('@libs/actions/Report', () => ({ updateLoadingInitialReportAction: jest.fn(), })); @@ -440,8 +465,8 @@ describe('ReportActionsView', () => { renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); - expect(mockReportActionsList).toHaveBeenCalled(); - const passedActions = (mockReportActionsList.mock.calls.at(0) as [{sortedVisibleReportActions: OnyxTypes.ReportAction[]}]).at(0)?.sortedVisibleReportActions; + expect(mockInvertedFlashList).toHaveBeenCalled(); + const passedActions = getCapturedVisibleActions(); expect(passedActions?.length).toBeGreaterThanOrEqual(1); expect(passedActions?.at(0)?.reportActionID).toBe(CONST.CONCIERGE_GREETING_ACTION_ID); }); @@ -507,7 +532,7 @@ describe('ReportActionsView', () => { // Welcome should not be shown since user has sent a message expect(mockReportActionItemCreated).not.toHaveBeenCalled(); // ReportActionsList should be rendered with filtered actions - expect(mockReportActionsList).toHaveBeenCalled(); + expect(mockInvertedFlashList).toHaveBeenCalled(); }); }); @@ -600,8 +625,8 @@ describe('ReportActionsView', () => { renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); - expect(mockReportActionsList).toHaveBeenCalled(); - const passedActions = (mockReportActionsList.mock.calls.at(0) as [{sortedVisibleReportActions: OnyxTypes.ReportAction[]}]).at(0)?.sortedVisibleReportActions; + expect(mockInvertedFlashList).toHaveBeenCalled(); + const passedActions = getCapturedVisibleActions(); expect(passedActions?.some((a) => a.reportActionID === CONST.CONCIERGE_GREETING_ACTION_ID)).toBe(true); expect(passedActions?.some((a) => a.reportActionID === 'old-user-msg')).toBe(false); expect(passedActions?.some((a) => a.reportActionID === 'old-concierge-msg')).toBe(false); @@ -618,8 +643,8 @@ describe('ReportActionsView', () => { renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); - expect(mockReportActionsList).toHaveBeenCalled(); - const passedActions = (mockReportActionsList.mock.calls.at(0) as [{sortedVisibleReportActions: OnyxTypes.ReportAction[]}]).at(0)?.sortedVisibleReportActions; + expect(mockInvertedFlashList).toHaveBeenCalled(); + const passedActions = getCapturedVisibleActions(); expect(passedActions?.some((a) => a.reportActionID === 'old-user-msg')).toBe(true); expect(passedActions?.some((a) => a.reportActionID === 'old-concierge-msg')).toBe(true); }); @@ -651,8 +676,8 @@ describe('ReportActionsView', () => { renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); - expect(mockReportActionsList).toHaveBeenCalled(); - const passedActions = (mockReportActionsList.mock.calls.at(0) as [{sortedVisibleReportActions: OnyxTypes.ReportAction[]}]).at(0)?.sortedVisibleReportActions; + expect(mockInvertedFlashList).toHaveBeenCalled(); + const passedActions = getCapturedVisibleActions(); // After user sends a message, the greeting stays visible alongside session actions expect(passedActions?.some((a) => a.reportActionID === CONST.CONCIERGE_GREETING_ACTION_ID)).toBe(true); expect(passedActions?.some((a) => a.reportActionID === 'new-user-msg')).toBe(true); @@ -669,8 +694,8 @@ describe('ReportActionsView', () => { renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); - expect(mockReportActionsList).toHaveBeenCalled(); - const passedActions = (mockReportActionsList.mock.calls.at(0) as [{sortedVisibleReportActions: OnyxTypes.ReportAction[]}]).at(0)?.sortedVisibleReportActions; + expect(mockInvertedFlashList).toHaveBeenCalled(); + const passedActions = getCapturedVisibleActions(); // With no session, old messages should not be shown expect(passedActions?.some((a) => a.reportActionID === 'old-user-msg')).toBe(false); expect(passedActions?.some((a) => a.reportActionID === 'old-concierge-msg')).toBe(false); @@ -715,8 +740,8 @@ describe('ReportActionsView', () => { renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); - expect(mockReportActionsList).toHaveBeenCalled(); - const passedActions = (mockReportActionsList.mock.calls.at(0) as [{sortedVisibleReportActions: OnyxTypes.ReportAction[]}]).at(0)?.sortedVisibleReportActions; + expect(mockInvertedFlashList).toHaveBeenCalled(); + const passedActions = getCapturedVisibleActions(); // New user with no prior messages — onboarding messages pass through (no filtering) expect(passedActions?.some((a) => a.reportActionID === 'onboarding-msg')).toBe(true); }); @@ -752,7 +777,7 @@ describe('ReportActionsView', () => { renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); - expect(mockReportActionsList).toHaveBeenCalled(); + expect(mockInvertedFlashList).toHaveBeenCalled(); }); it('should show a skeleton on a cold load when hasOnceLoadedReportActions is false and there are no cached actions', () => { diff --git a/tests/unit/useReportActionsScrollTest.tsx b/tests/unit/useReportActionsScrollTest.tsx index e045ed621a12..f2ac2a34b3b8 100644 --- a/tests/unit/useReportActionsScrollTest.tsx +++ b/tests/unit/useReportActionsScrollTest.tsx @@ -165,6 +165,7 @@ function makeAction(reportActionID: string, overrides: Partial = { function buildParams(overrides: Partial = {}): ScrollParams { return { + reportID: REPORT_ID, report: createMockReport({reportID: REPORT_ID}), transactionThreadReport: undefined, parentReportAction: undefined, From 950d4ce1a08320f85cfe29d06bd1da48f33220b7 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Tue, 16 Jun 2026 14:26:49 +0200 Subject: [PATCH 02/22] Introduce ReportActions orchestrator; route ReportScreen through it Add src/pages/inbox/ReportActions.tsx as the route-only orchestrator that owns the coarse branching (skeleton / money-request table view / chat list) and subscribes to only what those branches need. ReportScreen now mounts it instead of the old 58-LOC inbox/ReportActionsList.tsx wrapper, which is removed. ReportActionsView stays for now (still used by MoneyRequestReportView) and is deleted in the next commit. The app-load skeleton is hoisted out of the hook-driven body into the orchestrator so the body's data hooks/effects never run during app boot. It is evaluated on the chat path only (after the money-request branch) to preserve the prior behavior, where that skeleton lived inside the chat-only ReportActionsView, and it owns the warm:false markOpenReportEnd telemetry for the branch it gates. Add tests/ui/ReportActionsTest.tsx covering the orchestrator's branching decisions and the app-load telemetry mark. --- ...eportActionsList.tsx => ReportActions.tsx} | 47 +++- src/pages/inbox/ReportScreen.tsx | 4 +- tests/ui/ReportActionsTest.tsx | 206 ++++++++++++++++++ 3 files changed, 247 insertions(+), 10 deletions(-) rename src/pages/inbox/{ReportActionsList.tsx => ReportActions.tsx} (55%) create mode 100644 tests/ui/ReportActionsTest.tsx diff --git a/src/pages/inbox/ReportActionsList.tsx b/src/pages/inbox/ReportActions.tsx similarity index 55% rename from src/pages/inbox/ReportActionsList.tsx rename to src/pages/inbox/ReportActions.tsx index f94f73f20402..6a271d75ae2b 100644 --- a/src/pages/inbox/ReportActionsList.tsx +++ b/src/pages/inbox/ReportActions.tsx @@ -1,5 +1,5 @@ import {useRoute} from '@react-navigation/native'; -import React from 'react'; +import React, {useEffect} from 'react'; import MoneyRequestReportActionsList from '@components/MoneyRequestReportView/MoneyRequestReportActionsList'; import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; import useNetwork from '@hooks/useNetwork'; @@ -9,8 +9,10 @@ import useReportTransactionsCollection from '@hooks/useReportTransactionsCollect import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {getAllNonDeletedTransactions, shouldDisplayReportTableView, shouldWaitForTransactions as shouldWaitForTransactionsUtil} from '@libs/MoneyRequestReportUtils'; import {isInvoiceReport, isMoneyRequestReport} from '@libs/ReportUtils'; +import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; import ONYXKEYS from '@src/ONYXKEYS'; -import ReportActionsView from './report/ReportActionsView'; +import ReportActionsList from './report/ReportActionsList'; +import UserTypingEventListener from './report/UserTypingEventListener'; import type ReportScreenNavigationProps from './types'; const defaultReportLoadingState = { @@ -23,11 +25,12 @@ const defaultReportLoadingState = { }; /** - * Lightweight orchestrator that decides between skeleton, ReportActionsView, - * or MoneyRequestReportActionsList. Only subscribes to what the branching - * conditions need — heavy data derivation is pushed into each child. + * Route-only orchestrator for the report actions surface. It owns the coarse branching only — + * skeleton vs. money-request table view vs. the chat list — and subscribes to just what those + * branches need. All heavy data derivation lives inside the hook-driven `ReportActionsList` body, + * which is mounted only for the chat path so its hooks/effects never run while a skeleton shows. */ -function ReportActionsList() { +function ReportActions() { const route = useRoute(); const reportIDFromRoute = getNonEmptyStringOnyxID(route.params?.reportID); @@ -35,6 +38,7 @@ function ReportActionsList() { const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportIDFromRoute}`); const [reportLoadingState = defaultReportLoadingState] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${reportIDFromRoute}`); + const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); const {reportActions} = usePaginatedReportActions(reportIDFromRoute); const allReportTransactions = useReportTransactionsCollection(reportIDFromRoute); @@ -44,6 +48,21 @@ function ReportActionsList() { const shouldWaitForTransactions = shouldWaitForTransactionsUtil(report, reportTransactions, reportLoadingState, isOffline); const shouldDisplayMoneyRequestActionsList = isMoneyRequestOrInvoiceReport && shouldDisplayReportTableView(report, reportTransactions); + // The app-load skeleton is hoisted out of the body so the body's data hooks/effects never run + // during app boot. It only applies on the chat path (after the skeleton and money-request + // branches below) — matching the previous behavior, where this skeleton lived inside the + // chat-only ReportActionsView. Because the body won't mount for this branch, its own + // markOpenReportEnd(report, {warm:false}) effect can't close the open-report span, so we own + // that telemetry mark here for the branch we gate. + const shouldShowAppLoadSkeleton = !!isLoadingApp && !isOffline && !!report && !shouldWaitForTransactions && !shouldDisplayMoneyRequestActionsList; + + useEffect(() => { + if (!shouldShowAppLoadSkeleton || !report) { + return; + } + markOpenReportEnd(report, {warm: false}); + }, [report, shouldShowAppLoadSkeleton]); + if (!report || shouldWaitForTransactions) { return ; } @@ -52,7 +71,19 @@ function ReportActionsList() { return ; } - return ; + if (shouldShowAppLoadSkeleton) { + return ; + } + + return ( + <> + + + + ); } -export default ReportActionsList; +export default ReportActions; diff --git a/src/pages/inbox/ReportScreen.tsx b/src/pages/inbox/ReportScreen.tsx index 0fe5cab9d7fb..dca27dd65bd1 100644 --- a/src/pages/inbox/ReportScreen.tsx +++ b/src/pages/inbox/ReportScreen.tsx @@ -32,7 +32,7 @@ import ReportActionCompose from './report/ReportActionCompose/ReportActionCompos import {ReportActionEditMessageContextProvider, ReportScreenEditMessageProviderWithTransactionThread} from './report/ReportActionEditMessageContext'; import ReportFooter from './report/ReportFooter'; import useClearReportActionDraftsOnReportChange from './report/useClearReportActionDraftsOnReportChange'; -import ReportActionsList from './ReportActionsList'; +import ReportActions from './ReportActions'; import ReportDragAndDropProvider from './ReportDragAndDropProvider'; import ReportFetchHandler from './ReportFetchHandler'; import ReportHeader from './ReportHeader'; @@ -147,7 +147,7 @@ function ReportScreen({route, navigation}: ReportScreenProps) { style={[styles.flex1, styles.justifyContentEnd, styles.overflowHidden]} testID="report-actions-view-wrapper" > - + {shouldDeferNonEssentials ? : } diff --git a/tests/ui/ReportActionsTest.tsx b/tests/ui/ReportActionsTest.tsx new file mode 100644 index 000000000000..91f3e4f9fc5b --- /dev/null +++ b/tests/ui/ReportActionsTest.tsx @@ -0,0 +1,206 @@ +import type * as ReactNavigation from '@react-navigation/native'; +import {render, screen} from '@testing-library/react-native'; +import React from 'react'; +import Onyx from 'react-native-onyx'; +import MoneyRequestReportActionsList from '@components/MoneyRequestReportView/MoneyRequestReportActionsList'; +import useNetwork from '@hooks/useNetwork'; +import useOnyx from '@hooks/useOnyx'; +import usePaginatedReportActions from '@hooks/usePaginatedReportActions'; +import useReportTransactionsCollection from '@hooks/useReportTransactionsCollection'; +import {shouldDisplayReportTableView, shouldWaitForTransactions} from '@libs/MoneyRequestReportUtils'; +import {isInvoiceReport, isMoneyRequestReport} from '@libs/ReportUtils'; +import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; +import ReportActionsListBody from '@pages/inbox/report/ReportActionsList'; +import UserTypingEventListener from '@pages/inbox/report/UserTypingEventListener'; +import ReportActions from '@pages/inbox/ReportActions'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type * as OnyxTypes from '@src/types/onyx'; +import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; + +const REPORT_ID = '123'; + +jest.mock('@react-navigation/native', () => { + const actualNav = jest.requireActual('@react-navigation/native'); + return { + ...actualNav, + useRoute: jest.fn(() => ({params: {reportID: REPORT_ID}})), + }; +}); + +jest.mock('@hooks/useNetwork', () => jest.fn()); +jest.mock('@hooks/useOnyx', () => jest.fn()); +jest.mock('@hooks/usePaginatedReportActions', () => jest.fn()); +jest.mock('@hooks/useReportTransactionsCollection', () => jest.fn()); + +// Only the two helpers the orchestrator branches on are mocked, so each branch can be driven +// deterministically without constructing full transaction fixtures. +jest.mock('@libs/MoneyRequestReportUtils', () => ({ + getAllNonDeletedTransactions: jest.fn(() => []), + shouldDisplayReportTableView: jest.fn(() => false), + shouldWaitForTransactions: jest.fn(() => false), +})); +jest.mock('@libs/ReportUtils', () => ({ + isMoneyRequestReport: jest.fn(() => false), + isInvoiceReport: jest.fn(() => false), +})); + +// The children are mocked so these tests assert only the orchestrator's branching decision, not the +// children's internals (the body has its own dedicated coverage). The skeleton view is kept real so +// we can observe it via its testID. +jest.mock('@components/MoneyRequestReportView/MoneyRequestReportActionsList', () => jest.fn(() => null)); +jest.mock('@pages/inbox/report/ReportActionsList', () => jest.fn(() => null)); +jest.mock('@pages/inbox/report/UserTypingEventListener', () => jest.fn(() => null)); +jest.mock('@libs/telemetry/markOpenReportEnd', () => jest.fn()); + +const mockUseNetwork = useNetwork as jest.MockedFunction; +const mockUseOnyx = useOnyx as jest.MockedFunction; +const mockUsePaginatedReportActions = usePaginatedReportActions as jest.MockedFunction; +const mockUseReportTransactionsCollection = useReportTransactionsCollection as jest.MockedFunction; +const mockShouldDisplayReportTableView = shouldDisplayReportTableView as jest.MockedFunction; +const mockShouldWaitForTransactions = shouldWaitForTransactions as jest.MockedFunction; +const mockIsMoneyRequestReport = isMoneyRequestReport as jest.MockedFunction; +const mockIsInvoiceReport = isInvoiceReport as jest.MockedFunction; +const mockMoneyRequestList = MoneyRequestReportActionsList as jest.MockedFunction; +const mockReportActionsListBody = ReportActionsListBody as jest.MockedFunction; +const mockUserTypingEventListener = UserTypingEventListener as jest.MockedFunction; +const mockMarkOpenReportEnd = markOpenReportEnd as jest.MockedFunction; + +const defaultPaginatedReportActionsResult: ReturnType = { + reportActions: [], + linkedAction: undefined, + oldestUnreadReportAction: undefined, + sortedAllReportActions: undefined, + hasNewerActions: false, + hasOlderActions: false, + report: undefined, +}; + +const mockReport: OnyxTypes.Report = { + reportID: REPORT_ID, + reportName: 'Test Report', + chatReportID: '456', + ownerAccountID: 123, + lastVisibleActionCreated: '2023-01-01', + total: 0, +}; + +type ReportLoadingStateOverrides = Partial<{isLoadingInitialReportActions: boolean; hasOnceLoadedReportActions: boolean}>; + +/** Builds the keyed useOnyx mock the orchestrator reads: the report, its loading state and IS_LOADING_APP. */ +const setupUseOnyx = (options: {report?: OnyxTypes.Report | undefined; isLoadingApp?: boolean; loadingState?: ReportLoadingStateOverrides} = {}) => { + // `'report' in options` distinguishes "not passed" (default to mockReport) from an explicit + // `{report: undefined}` (the report-not-available case) — a destructuring default would swallow the latter. + const report = 'report' in options ? options.report : mockReport; + const isLoadingApp = options.isLoadingApp ?? false; + const loadingState = options.loadingState ?? {}; + mockUseOnyx.mockImplementation((key: string) => { + if (key === ONYXKEYS.IS_LOADING_APP) { + return [isLoadingApp, {status: 'loaded'}]; + } + if (key.includes('reportLoadingState')) { + return [{isLoadingInitialReportActions: false, hasOnceLoadedReportActions: true, ...loadingState}, {status: 'loaded'}]; + } + if (key === `${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`) { + return [report, {status: 'loaded'}]; + } + return [undefined, {status: 'loaded'}]; + }); +}; + +describe('ReportActions (orchestrator)', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(() => { + jest.clearAllMocks(); + mockUseNetwork.mockReturnValue({isOffline: false}); + mockUsePaginatedReportActions.mockReturnValue(defaultPaginatedReportActionsResult); + mockUseReportTransactionsCollection.mockReturnValue({}); + mockShouldWaitForTransactions.mockReturnValue(false); + mockShouldDisplayReportTableView.mockReturnValue(false); + mockIsMoneyRequestReport.mockReturnValue(false); + mockIsInvoiceReport.mockReturnValue(false); + setupUseOnyx(); + }); + + afterEach(async () => { + await waitForBatchedUpdatesWithAct(); + await Onyx.clear(); + }); + + it('renders a skeleton when the report is not available yet', () => { + setupUseOnyx({report: undefined}); + + render(); + + expect(screen.getByTestId('ReportActionsSkeletonView')).toBeTruthy(); + expect(mockReportActionsListBody).not.toHaveBeenCalled(); + expect(mockMoneyRequestList).not.toHaveBeenCalled(); + }); + + it('renders a skeleton while waiting for transactions', () => { + mockShouldWaitForTransactions.mockReturnValue(true); + + render(); + + expect(screen.getByTestId('ReportActionsSkeletonView')).toBeTruthy(); + expect(mockReportActionsListBody).not.toHaveBeenCalled(); + expect(mockMoneyRequestList).not.toHaveBeenCalled(); + }); + + it('renders the money-request table view for a money-request report', () => { + mockIsMoneyRequestReport.mockReturnValue(true); + mockShouldDisplayReportTableView.mockReturnValue(true); + + render(); + + expect(mockMoneyRequestList).toHaveBeenCalled(); + expect(mockReportActionsListBody).not.toHaveBeenCalled(); + expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); + }); + + it('renders the chat list body and the typing listener for a chat report', () => { + render(); + + expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); + expect(mockMoneyRequestList).not.toHaveBeenCalled(); + expect(mockReportActionsListBody).toHaveBeenCalled(); + expect(mockReportActionsListBody.mock.calls.at(-1)?.at(0)).toEqual(expect.objectContaining({reportID: REPORT_ID})); + expect(mockUserTypingEventListener).toHaveBeenCalled(); + expect(mockUserTypingEventListener.mock.calls.at(-1)?.at(0)).toEqual(expect.objectContaining({report: mockReport})); + }); + + it('renders the app-load skeleton on the chat path and closes the open-report span with warm:false', () => { + setupUseOnyx({isLoadingApp: true}); + + render(); + + expect(screen.getByTestId('ReportActionsSkeletonView')).toBeTruthy(); + expect(mockReportActionsListBody).not.toHaveBeenCalled(); + expect(mockMarkOpenReportEnd).toHaveBeenCalledWith(mockReport, {warm: false}); + }); + + it('does not show the app-load skeleton (or fire telemetry) while offline', () => { + mockUseNetwork.mockReturnValue({isOffline: true}); + setupUseOnyx({isLoadingApp: true}); + + render(); + + expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); + expect(mockReportActionsListBody).toHaveBeenCalled(); + expect(mockMarkOpenReportEnd).not.toHaveBeenCalled(); + }); + + it('does not show the app-load skeleton for a money-request report', () => { + mockIsMoneyRequestReport.mockReturnValue(true); + mockShouldDisplayReportTableView.mockReturnValue(true); + setupUseOnyx({isLoadingApp: true}); + + render(); + + expect(mockMoneyRequestList).toHaveBeenCalled(); + expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); + expect(mockMarkOpenReportEnd).not.toHaveBeenCalled(); + }); +}); From 73e8c3ab45345d3d5c2724cd2d4d3fd9da7bca9b Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Tue, 16 Jun 2026 15:12:59 +0200 Subject: [PATCH 03/22] Rewire MoneyRequestReportView to the body --- .../MoneyRequestReportView.tsx | 14 ++++--- ...ViewTest.tsx => ReportActionsListTest.tsx} | 40 +++++++++---------- 2 files changed, 29 insertions(+), 25 deletions(-) rename tests/ui/{ReportActionsViewTest.tsx => ReportActionsListTest.tsx} (96%) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx index 87b80abbb82f..cb6224192ecd 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx @@ -31,8 +31,9 @@ import {cancelSpan} from '@libs/telemetry/activeSpans'; import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; import type {SkeletonSpanReasonAttributes} from '@libs/telemetry/useSkeletonSpan'; import Navigation from '@navigation/Navigation'; -import ReportActionsView from '@pages/inbox/report/ReportActionsView'; +import ReportActionsList from '@pages/inbox/report/ReportActionsList'; import ReportFooter from '@pages/inbox/report/ReportFooter'; +import UserTypingEventListener from '@pages/inbox/report/UserTypingEventListener'; import CONST from '@src/CONST'; import NAVIGATORS from '@src/NAVIGATORS'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -274,10 +275,13 @@ function MoneyRequestReportView({report, reportLoadingState, shouldDisplayReport {shouldDisplayMoneyRequestActionsList ? ( ) : ( - + <> + + + )} {shouldDisplayReportFooter ? ( <> diff --git a/tests/ui/ReportActionsViewTest.tsx b/tests/ui/ReportActionsListTest.tsx similarity index 96% rename from tests/ui/ReportActionsViewTest.tsx rename to tests/ui/ReportActionsListTest.tsx index a0cd75bfa344..54741e65e72c 100644 --- a/tests/ui/ReportActionsViewTest.tsx +++ b/tests/ui/ReportActionsListTest.tsx @@ -16,7 +16,7 @@ import useTransactionsAndViolationsForReport from '@hooks/useTransactionsAndViol import DateUtils from '@libs/DateUtils'; import * as ReportActionsUtils from '@libs/ReportActionsUtils'; import {useConciergeSessionActions, useConciergeSessionState} from '@pages/inbox/ConciergeSessionContext'; -import ReportActionsView from '@pages/inbox/report/ReportActionsView'; +import ReportActionsList from '@pages/inbox/report/ReportActionsList'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type * as OnyxTypes from '@src/types/onyx'; @@ -176,12 +176,12 @@ const mockReportActions: OnyxTypes.ReportAction[] = [ }, ]; -const renderReportActionsView = (props: {reportID?: string} = {}) => { +const renderReportActionsList = (props: {reportID?: string} = {}) => { const reportID = props.reportID ?? mockReport.reportID; - return render(); + return render(); }; -describe('ReportActionsView', () => { +describe('ReportActionsList (body)', () => { beforeAll(() => { Onyx.init({ keys: ONYXKEYS, @@ -290,7 +290,7 @@ describe('ReportActionsView', () => { ...defaultPaginatedReportActionsResult, }); - renderReportActionsView(); + renderReportActionsList(); expect(screen.getByTestId('ReportActionsSkeletonView')).toBeTruthy(); }); @@ -322,7 +322,7 @@ describe('ReportActionsView', () => { return [undefined, {status: 'loaded'}]; }); - renderReportActionsView(); + renderReportActionsList(); expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); }); @@ -354,7 +354,7 @@ describe('ReportActionsView', () => { return [undefined, {status: 'loaded'}]; }); - renderReportActionsView(); + renderReportActionsList(); expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); }); @@ -386,7 +386,7 @@ describe('ReportActionsView', () => { return [undefined, {status: 'loaded'}]; }); - renderReportActionsView(); + renderReportActionsList(); expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); }); @@ -463,7 +463,7 @@ describe('ReportActionsView', () => { mockUseIsInSidePanel.mockReturnValue(true); mockUseSidePanelState.mockReturnValue({...defaultSidePanelState, sessionStartTime: DateUtils.getDBTime()}); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(mockInvertedFlashList).toHaveBeenCalled(); const passedActions = getCapturedVisibleActions(); @@ -480,7 +480,7 @@ describe('ReportActionsView', () => { }); mockUseIsInSidePanel.mockReturnValue(false); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(mockReportActionItemCreated).not.toHaveBeenCalled(); }); @@ -494,7 +494,7 @@ describe('ReportActionsView', () => { }); mockUseIsInSidePanel.mockReturnValue(false); - renderReportActionsView({reportID: 'non-concierge-999'}); + renderReportActionsList({reportID: 'non-concierge-999'}); expect(mockReportActionItemCreated).not.toHaveBeenCalled(); }); @@ -527,7 +527,7 @@ describe('ReportActionsView', () => { mockUseIsInSidePanel.mockReturnValue(true); mockUseSidePanelState.mockReturnValue({...defaultSidePanelState, sessionStartTime: sessionStart}); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); // Welcome should not be shown since user has sent a message expect(mockReportActionItemCreated).not.toHaveBeenCalled(); @@ -623,7 +623,7 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(mockInvertedFlashList).toHaveBeenCalled(); const passedActions = getCapturedVisibleActions(); @@ -641,7 +641,7 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(mockInvertedFlashList).toHaveBeenCalled(); const passedActions = getCapturedVisibleActions(); @@ -674,7 +674,7 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(mockInvertedFlashList).toHaveBeenCalled(); const passedActions = getCapturedVisibleActions(); @@ -692,7 +692,7 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(mockInvertedFlashList).toHaveBeenCalled(); const passedActions = getCapturedVisibleActions(); @@ -738,7 +738,7 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(mockInvertedFlashList).toHaveBeenCalled(); const passedActions = getCapturedVisibleActions(); @@ -758,7 +758,7 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(mockStartSession).toHaveBeenCalled(); }); @@ -774,7 +774,7 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); expect(mockInvertedFlashList).toHaveBeenCalled(); @@ -789,7 +789,7 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(screen.getByTestId('ReportActionsSkeletonView')).toBeTruthy(); }); From 9b61f3cc963b38cdedffb2b9140480e7cc74ce2b Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Tue, 16 Jun 2026 15:13:06 +0200 Subject: [PATCH 04/22] Delete ReportActionsView --- src/pages/inbox/report/ReportActionsView.tsx | 40 -------------------- 1 file changed, 40 deletions(-) delete mode 100755 src/pages/inbox/report/ReportActionsView.tsx diff --git a/src/pages/inbox/report/ReportActionsView.tsx b/src/pages/inbox/report/ReportActionsView.tsx deleted file mode 100755 index e4c2d5d61861..000000000000 --- a/src/pages/inbox/report/ReportActionsView.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import React from 'react'; -import type {LayoutChangeEvent} from 'react-native'; -import useOnyx from '@hooks/useOnyx'; -import ONYXKEYS from '@src/ONYXKEYS'; -import {getStableReportSelector} from '@src/selectors/Report'; -import ReportActionsList from './ReportActionsList'; -import UserTypingEventListener from './UserTypingEventListener'; - -type ReportActionsViewProps = { - /** The ID of the report to display actions for */ - reportID: string | undefined; - - /** Callback executed on layout */ - onLayout?: (event: LayoutChangeEvent) => void; -}; - -/** - * Thin host around the hook-driven ReportActionsList body. It owns the report - * subscription needed to mount the typing listener; all data orchestration and - * skeleton handling now live inside the body itself. - */ -function ReportActionsView({reportID, onLayout}: ReportActionsViewProps) { - const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {selector: getStableReportSelector}); - - if (!reportID || !report) { - return null; - } - - return ( - <> - - - - ); -} - -export default ReportActionsView; From 4075453a09e9a497ac17e7fe7cb78f9f2f1532c2 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Tue, 16 Jun 2026 15:26:25 +0200 Subject: [PATCH 05/22] Add MoneyRequestReportView unit test --- tests/ui/MoneyRequestReportViewTest.tsx | 187 ++++++++++++++++++++++++ 1 file changed, 187 insertions(+) create mode 100644 tests/ui/MoneyRequestReportViewTest.tsx diff --git a/tests/ui/MoneyRequestReportViewTest.tsx b/tests/ui/MoneyRequestReportViewTest.tsx new file mode 100644 index 000000000000..949aa494b14c --- /dev/null +++ b/tests/ui/MoneyRequestReportViewTest.tsx @@ -0,0 +1,187 @@ +/* eslint-disable @typescript-eslint/no-unsafe-type-assertion */ +import {render} from '@testing-library/react-native'; +import React from 'react'; +import type {LayoutChangeEvent} from 'react-native'; +import Onyx from 'react-native-onyx'; +import MoneyRequestReportActionsList from '@components/MoneyRequestReportView/MoneyRequestReportActionsList'; +import MoneyRequestReportView from '@components/MoneyRequestReportView/MoneyRequestReportView'; +import useNetwork from '@hooks/useNetwork'; +import useOnyx from '@hooks/useOnyx'; +import usePaginatedReportActions from '@hooks/usePaginatedReportActions'; +import useReportTransactionsCollection from '@hooks/useReportTransactionsCollection'; +import useResponsiveLayout from '@hooks/useResponsiveLayout'; +import * as MoneyRequestReportUtils from '@libs/MoneyRequestReportUtils'; +import * as ReportActionsUtils from '@libs/ReportActionsUtils'; +import ReportActionsList from '@pages/inbox/report/ReportActionsList'; +import UserTypingEventListener from '@pages/inbox/report/UserTypingEventListener'; +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type * as OnyxTypes from '@src/types/onyx'; +import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; + +const REPORT_ID = '777'; + +jest.mock('@hooks/useNetwork', () => jest.fn()); +jest.mock('@hooks/useOnyx', () => jest.fn()); +jest.mock('@hooks/useResponsiveLayout', () => jest.fn()); +jest.mock('@hooks/usePaginatedReportActions', () => jest.fn()); +jest.mock('@hooks/useReportTransactionsCollection', () => jest.fn()); + +// useThemeStyles throws without a ; return a proxy that yields an empty style object +// for any key so the (mostly-mocked) tree renders without wiring up the full provider stack. +jest.mock('@hooks/useThemeStyles', () => { + const styleProxy = new Proxy({}, {get: () => ({})}); + return jest.fn(() => styleProxy); +}); + +// The children whose mounting we assert on are mocked so these tests observe only MoneyRequestReportView's +// branch decision (table view vs. chat body + typing listener), not the children's internals. +jest.mock('@components/MoneyRequestReportView/MoneyRequestReportActionsList', () => jest.fn(() => null)); +jest.mock('@pages/inbox/report/ReportActionsList', () => jest.fn(() => null)); +jest.mock('@pages/inbox/report/UserTypingEventListener', () => jest.fn(() => null)); + +// Header / footer / receipt children are stubbed to keep the render lightweight; OfflineWithFeedback must +// pass its children through because the chat body is mounted inside it. +jest.mock('@components/MoneyReportHeader', () => jest.fn(() => null)); +jest.mock('@components/MoneyRequestHeader', () => jest.fn(() => null)); +jest.mock('@components/CollapsibleHeaderOnKeyboard', () => jest.fn(() => null)); +jest.mock('@components/ReportActionItem/MoneyRequestReceiptView', () => jest.fn(() => null)); +jest.mock('@pages/inbox/report/ReportFooter', () => jest.fn(() => null)); +jest.mock('@components/OfflineWithFeedback', () => { + const reactModule = jest.requireActual('react'); + return jest.fn(({children}: {children: React.ReactNode}) => reactModule.createElement(reactModule.Fragment, null, children)); +}); + +const mockUseNetwork = useNetwork as jest.MockedFunction; +const mockUseOnyx = useOnyx as jest.MockedFunction; +const mockUseResponsiveLayout = useResponsiveLayout as jest.MockedFunction; +const mockUsePaginatedReportActions = usePaginatedReportActions as jest.MockedFunction; +const mockUseReportTransactionsCollection = useReportTransactionsCollection as jest.MockedFunction; +const mockMoneyRequestReportActionsList = MoneyRequestReportActionsList as jest.MockedFunction; +const mockReportActionsListBody = ReportActionsList as jest.MockedFunction; +const mockUserTypingEventListener = UserTypingEventListener as jest.MockedFunction; + +const defaultPaginatedReportActionsResult: ReturnType = { + reportActions: [], + linkedAction: undefined, + oldestUnreadReportAction: undefined, + sortedAllReportActions: undefined, + hasNewerActions: false, + hasOlderActions: false, + report: undefined, +}; + +const mockReport: OnyxTypes.Report = { + reportID: REPORT_ID, + reportName: 'Money Request Report', + chatReportID: '888', + ownerAccountID: 1, + lastVisibleActionCreated: '2024-01-01', + total: 0, +}; + +const mockReportLoadingState: OnyxTypes.ReportLoadingState = { + isLoadingInitialReportActions: false, + isLoadingOlderReportActions: false, + hasLoadingOlderReportActionsError: false, + isLoadingNewerReportActions: false, + hasLoadingNewerReportActionsError: false, + hasOnceLoadedReportActions: true, +}; + +// A single non-empty action so the component clears its "no actions yet" skeleton and reaches the branch. +const mockReportActions: OnyxTypes.ReportAction[] = [ + { + reportActionID: 'a1', + actionName: CONST.REPORT.ACTIONS.TYPE.ADD_COMMENT, + created: '2024-01-01', + actorAccountID: 1, + message: [{type: 'COMMENT', html: 'Hi', text: 'Hi'}], + originalMessage: {}, + shouldShow: true, + person: [{type: 'TEXT', style: 'strong', text: 'User'}], + pendingAction: null, + errors: {}, + }, +]; + +const renderMoneyRequestReportView = (onLayout: (event: LayoutChangeEvent) => void) => + render( + , + ); + +describe('MoneyRequestReportView', () => { + beforeAll(() => { + Onyx.init({keys: ONYXKEYS}); + }); + + beforeEach(() => { + jest.clearAllMocks(); + + mockUseNetwork.mockReturnValue({isOffline: false}); + mockUsePaginatedReportActions.mockReturnValue(defaultPaginatedReportActionsResult); + mockUseReportTransactionsCollection.mockReturnValue({}); + mockUseResponsiveLayout.mockReturnValue({ + shouldUseNarrowLayout: false, + isSmallScreenWidth: false, + isInNarrowPaneModal: false, + isExtraSmallScreenHeight: false, + isMediumScreenWidth: false, + isLargeScreenWidth: true, + isExtraLargeScreenWidth: false, + isExtraSmallScreenWidth: false, + isSmallScreen: false, + onboardingIsMediumOrLargerScreenWidth: true, + isInLandscapeMode: false, + }); + mockUseOnyx.mockImplementation((key: string) => { + if (key === ONYXKEYS.IS_LOADING_APP) { + return [false, {status: 'loaded'}]; + } + return [undefined, {status: 'loaded'}]; + }); + + // Drive the branch deterministically: no transactions, a resolved transaction-thread id (so the + // report isn't treated as empty), and a non-empty filtered action set. + jest.spyOn(MoneyRequestReportUtils, 'getAllNonDeletedTransactions').mockReturnValue([]); + jest.spyOn(MoneyRequestReportUtils, 'shouldWaitForTransactions').mockReturnValue(false); + jest.spyOn(MoneyRequestReportUtils, 'shouldDisplayReportTableView').mockReturnValue(false); + jest.spyOn(ReportActionsUtils, 'getFilteredReportActionsForReportView').mockReturnValue(mockReportActions); + jest.spyOn(ReportActionsUtils, 'getOneTransactionThreadReportID').mockReturnValue('thread-1'); + }); + + afterEach(async () => { + await waitForBatchedUpdatesWithAct(); + await Onyx.clear(); + }); + + it('mounts the chat list body and the typing listener (not the table view) for a transaction-thread report', () => { + const onLayout = jest.fn(); + + renderMoneyRequestReportView(onLayout); + + expect(mockMoneyRequestReportActionsList).not.toHaveBeenCalled(); + expect(mockReportActionsListBody).toHaveBeenCalled(); + // The body is fed the report's own id and the warm-timing onLayout is forwarded through. + expect(mockReportActionsListBody.mock.calls.at(-1)?.at(0)).toEqual(expect.objectContaining({reportID: REPORT_ID, onLayout})); + // Typing is preserved in the transaction-thread view by mounting the listener as a sibling of the body. + expect(mockUserTypingEventListener).toHaveBeenCalled(); + expect(mockUserTypingEventListener.mock.calls.at(-1)?.at(0)).toEqual(expect.objectContaining({report: mockReport})); + }); + + it('mounts the money-request table view (not the chat body or typing listener) when a table view should display', () => { + jest.spyOn(MoneyRequestReportUtils, 'shouldDisplayReportTableView').mockReturnValue(true); + + renderMoneyRequestReportView(jest.fn()); + + expect(mockMoneyRequestReportActionsList).toHaveBeenCalled(); + expect(mockReportActionsListBody).not.toHaveBeenCalled(); + expect(mockUserTypingEventListener).not.toHaveBeenCalled(); + }); +}); From 0929b0a17ba1e7f7d35387ccf3e1c808a7e51fbf Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Tue, 16 Jun 2026 15:40:03 +0200 Subject: [PATCH 06/22] Update stale ReportActionsView doc comments to ReportActionsList --- .../MoneyRequestReportView/MoneyRequestReportView.tsx | 2 +- src/hooks/useIsReportReadyToDisplay.ts | 2 +- src/libs/ReportActionsUtils.ts | 2 +- src/libs/actions/Report/index.ts | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx index cb6224192ecd..fb4199e0c335 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx @@ -149,7 +149,7 @@ function MoneyRequestReportView({report, reportLoadingState, shouldDisplayReport }, [reportID]); // Special case handling a report that is a transaction thread - // If true we will use standard `ReportActionsView` to display report data and a special header, anything else is handled via `MoneyRequestReportActionsList` + // If true we will use the standard `ReportActionsList` to display report data and a special header, anything else is handled via `MoneyRequestReportActionsList` const isTransactionThreadView = isReportTransactionThread(report); // Prevent the empty state flash by ensuring transaction data is fully loaded before deciding which view to render diff --git a/src/hooks/useIsReportReadyToDisplay.ts b/src/hooks/useIsReportReadyToDisplay.ts index a764dff6678a..cb10d5bd8065 100644 --- a/src/hooks/useIsReportReadyToDisplay.ts +++ b/src/hooks/useIsReportReadyToDisplay.ts @@ -8,7 +8,7 @@ function useIsReportReadyToDisplay(report: OnyxEntry, reportIDFromRoute: * When false the report is not ready to be fully displayed */ const isCurrentReportLoadedFromOnyx = useMemo((): boolean => { - // This is necessary so that when we are retrieving the next report data from Onyx the ReportActionsView will remount completely + // This is necessary so that when we are retrieving the next report data from Onyx the ReportActionsList will remount completely const isTransitioning = report && report?.reportID?.toString() !== reportIDFromRoute; return reportIDFromRoute !== '' && !!report?.reportID && !isTransitioning; }, [report, reportIDFromRoute]); diff --git a/src/libs/ReportActionsUtils.ts b/src/libs/ReportActionsUtils.ts index f5a1e1ff5a2e..4c2939893299 100644 --- a/src/libs/ReportActionsUtils.ts +++ b/src/libs/ReportActionsUtils.ts @@ -1563,7 +1563,7 @@ function withDEWRoutedActionsObject(reportActions: OnyxEntry): On } /** - * This method returns the report actions that are ready for display in the ReportActionsView. + * This method returns the report actions that are ready for display in the ReportActionsList. * The report actions need to be sorted by created timestamp first, and reportActionID second * to ensure they will always be displayed in the same order (in case multiple actions have the same timestamp). * This is all handled with getSortedReportActions() which is used by several other methods to keep the code DRY. diff --git a/src/libs/actions/Report/index.ts b/src/libs/actions/Report/index.ts index 22ef4053682f..9a8b90f70a0d 100644 --- a/src/libs/actions/Report/index.ts +++ b/src/libs/actions/Report/index.ts @@ -744,7 +744,7 @@ function clearAgentZeroProcessingIndicator(reportID: string, agentAccountID: num let newActionSubscribers: ActionSubscriber[] = []; /** - * Enables the Report actions file to let the ReportActionsView know that a new comment has arrived in realtime for the current report + * Enables the Report actions file to let the ReportActionsList know that a new comment has arrived in realtime for the current report * Add subscriber for report id * @returns Remove subscriber for report id */ @@ -755,7 +755,7 @@ function subscribeToNewActionEvent(reportID: string, callback: SubscriberCallbac }; } -/** Notify the ReportActionsView that a new comment has arrived */ +/** Notify the ReportActionsList that a new comment has arrived */ function notifyNewAction(reportID: string | string[] | undefined, reportAction: ReportAction | undefined, isFromCurrentUser: boolean) { if (!reportID) { return; From 09a9340ec9a8825f3301995936de3f6061e8b1d8 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Tue, 16 Jun 2026 16:39:59 +0200 Subject: [PATCH 07/22] update ReportActionsList perf test --- .../perf-test/ReportActionsList.perf-test.tsx | 45 +++---------------- 1 file changed, 6 insertions(+), 39 deletions(-) diff --git a/tests/perf-test/ReportActionsList.perf-test.tsx b/tests/perf-test/ReportActionsList.perf-test.tsx index 0de9be30fde4..0d6213f2dd46 100644 --- a/tests/perf-test/ReportActionsList.perf-test.tsx +++ b/tests/perf-test/ReportActionsList.perf-test.tsx @@ -12,9 +12,8 @@ import {AttachmentModalContextProvider} from '@pages/media/AttachmentModalScreen import ComposeProviders from '@src/components/ComposeProviders'; import {LocaleContextProvider} from '@src/components/LocaleContextProvider'; import CONST from '@src/CONST'; -import IntlStore from '@src/languages/IntlStore'; import ONYXKEYS from '@src/ONYXKEYS'; -import type {PersonalDetailsList, ReportAction, ReportActions} from '@src/types/onyx'; +import type {ReportAction, ReportActions} from '@src/types/onyx'; import * as ReportTestUtils from '../utils/ReportTestUtils'; import * as TestHelper from '../utils/TestHelper'; import waitForBatchedUpdates from '../utils/waitForBatchedUpdates'; @@ -48,55 +47,25 @@ const mockReactionListContextValue = { const TEST_USER_ACCOUNT_ID = 1; const TEST_USER_LOGIN = 'test@test.com'; - const REPORT_ID = '1'; const signUpWithTestUser = () => { TestHelper.signInWithTestUser(TEST_USER_ACCOUNT_ID, TEST_USER_LOGIN); }; -// Seed 500 report actions through Onyx (keyed by reportActionID, as production stores them) so the -// hook-driven body fetches and runs the real pagination + visibility pipeline — instead of receiving a -// pre-sorted array via props as the previous harness did. This is strictly more production-faithful, so -// the measured number is a fresh baseline and is not comparable to the pre-PR-6 figure. const sortedReportActions = ReportTestUtils.getMockedSortedReportActions(500); const reportActions: ReportActions = Object.fromEntries(sortedReportActions.map((action: ReportAction) => [action.reportActionID, action])); const report = ReportTestUtils.createMockReport({reportID: REPORT_ID, lastVisibleActionCreated: sortedReportActions.at(0)?.created}); -// getFakeReportAction sets actorAccountID = index, so the 500 mocked actions have actors 1..500 -const ACTOR_PERSONAL_DETAILS: PersonalDetailsList = Object.fromEntries( - Array.from({length: 500}, (_, i) => { - const accountID = i + 1; - return [ - accountID, - { - accountID, - login: `user${accountID}@test.com`, - avatar: 'https://d2k5nsl2zxldvw.cloudfront.net/images/avatars/avatar_7.png', - avatarThumbnail: 'https://d2k5nsl2zxldvw.cloudfront.net/images/avatars/avatar_7.png', - displayName: `User ${accountID}`, - firstName: 'User', - lastName: `${accountID}`, - pronouns: '', - timezone: CONST.DEFAULT_TIME_ZONE, - phoneNumber: '', - }, - ]; - }), -); - beforeEach(async () => { // Initialize the network key for OfflineWithFeedback setHasRadio(true); wrapOnyxWithWaitForBatchedUpdates(Onyx); - // Pre-seed the locale so LocaleContextProvider's mount effect is a no-op (setLocale/IntlStore.load - // early-return), avoiding post-mount Onyx writes that re-render outside act(). Personal details back - // the 500 actors so avatars/display names resolve through the real selectors. + // Pre-seed the locale so LocaleContextProvider's mount effect is a no-op (setLocale early-returns), + // avoiding post-mount Onyx writes that would re-render outside act(). await act(async () => { signUpWithTestUser(); - await Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, ACTOR_PERSONAL_DETAILS); await Onyx.merge(ONYXKEYS.NVP_PREFERRED_LOCALE, CONST.LOCALES.DEFAULT); - await IntlStore.load(CONST.LOCALES.DEFAULT); // Seed the report under test: the report, its 500 actions, and a settled loading state. await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${REPORT_ID}`, report); @@ -119,11 +88,9 @@ afterEach(async () => { await waitForBatchedUpdates(); }); -// Mirror the production data flow (usePaginatedReportActions): the wrapper plays the role of the parent -// (ReportActionsView) — it reads REPORT_ACTIONS from Onyx and sorts inside a useOnyx selector, instead of -// holding the actions in local state. "Sending a message" is then an Onyx.merge into REPORT_ACTIONS -// (exactly like addActions' optimistic update), so the list updates through the real subscription/selector -// path rather than prop injection. +// Mirror the production data flow (usePaginatedReportActions): the body reads REPORT_ACTIONS from Onyx and +// sorts inside a useOnyx selector, then runs it through the real continuous-chain pagination and the +// visibility filter. function ReportActionsListWrapper() { return ( From faa7faaf0fca3a983dc3eaeef78eb9a59d066b51 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Tue, 16 Jun 2026 17:05:24 +0200 Subject: [PATCH 08/22] clean up comments --- src/pages/inbox/report/ReportActionsList.tsx | 2 -- tests/ui/ReportActionsListTest.tsx | 8 +++----- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/pages/inbox/report/ReportActionsList.tsx b/src/pages/inbox/report/ReportActionsList.tsx index 25be7c961854..de288fad72e8 100644 --- a/src/pages/inbox/report/ReportActionsList.tsx +++ b/src/pages/inbox/report/ReportActionsList.tsx @@ -561,10 +561,8 @@ function ReportActionsList({reportID, onLayout}: ReportActionsListProps) { } }; - // Show skeleton while loading initial report actions when data is incomplete/missing and online const shouldShowSkeletonForInitialLoad = !!isLoadingInitialReportActions && (isReportDataIncomplete || isMissingReportActions) && !isOffline; - // Show skeleton while the app is loading and we're online const shouldShowSkeletonForAppLoad = isLoadingApp && !isOffline; // Show skeleton for the Concierge chat (side panel or main DM) until report diff --git a/tests/ui/ReportActionsListTest.tsx b/tests/ui/ReportActionsListTest.tsx index 54741e65e72c..196de6cdc5de 100644 --- a/tests/ui/ReportActionsListTest.tsx +++ b/tests/ui/ReportActionsListTest.tsx @@ -97,10 +97,9 @@ jest.mock('@hooks/usePrevious', () => jest.fn()); const mockUseCurrentUserPersonalDetails = useCurrentUserPersonalDetails as jest.MockedFunction; -// PR 6 makes the ReportActionsList body hook-driven, so we mount the REAL body (no longer a prop-fed -// child) and observe what it feeds the list via InvertedFlashList's `data`. The heavy scroll/marker -// hooks have their own unit tests, so they are stubbed here to isolate the body's visibility/skeleton -// logic — the actual subject of these tests. +// We mount the real hook-driven body and observe what it feeds the list via InvertedFlashList's `data`. +// The heavy scroll/marker hooks have their own unit tests, so they are stubbed here to isolate the +// body's visibility/skeleton logic — the actual subject of these tests. jest.mock('@components/FlashList/InvertedFlashList', () => jest.fn(() => null)); jest.mock('@hooks/useUnreadMarker', () => jest.fn(() => ({unreadMarkerReportActionID: null, unreadMarkerReportActionIndex: -1}))); jest.mock('@hooks/useMarkAsRead', () => jest.fn(() => ({markNewestActionAsRead: jest.fn(), completeSkippedMarkAsRead: jest.fn()}))); @@ -139,7 +138,6 @@ jest.mock('@libs/actions/Report', () => ({ updateLoadingInitialReportAction: jest.fn(), })); -// Mock report data const mockReport: OnyxTypes.Report = { reportID: '123', reportName: 'Test Report', From 5ec39cb02efe63f1ab59374a34ae207948cd1610 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Wed, 17 Jun 2026 12:33:25 +0200 Subject: [PATCH 09/22] add no-unsafe-type-assertion for mocks --- tests/ui/ReportActionsTest.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/ui/ReportActionsTest.tsx b/tests/ui/ReportActionsTest.tsx index 91f3e4f9fc5b..793c5d0c55d5 100644 --- a/tests/ui/ReportActionsTest.tsx +++ b/tests/ui/ReportActionsTest.tsx @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-unsafe-type-assertion */ import type * as ReactNavigation from '@react-navigation/native'; import {render, screen} from '@testing-library/react-native'; import React from 'react'; From 33f49705922d2297b7f700668c27f860111cf225 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Mon, 22 Jun 2026 18:42:01 +0200 Subject: [PATCH 10/22] Add ReportActionsSkeletonGuard with useReportActionsDataContext --- src/hooks/useReportActionsData.ts | 154 ++++++++++++ .../inbox/report/ReportActionsDataContext.tsx | 108 +++++++++ src/pages/inbox/report/ReportActionsList.tsx | 228 ++++-------------- .../report/ReportActionsSkeletonGuard.tsx | 101 ++++++++ tests/ui/ReportActionsListTest.tsx | 196 ++++++++++++++- 5 files changed, 604 insertions(+), 183 deletions(-) create mode 100644 src/hooks/useReportActionsData.ts create mode 100644 src/pages/inbox/report/ReportActionsDataContext.tsx create mode 100644 src/pages/inbox/report/ReportActionsSkeletonGuard.tsx diff --git a/src/hooks/useReportActionsData.ts b/src/hooks/useReportActionsData.ts new file mode 100644 index 000000000000..abfa85de8fd4 --- /dev/null +++ b/src/hooks/useReportActionsData.ts @@ -0,0 +1,154 @@ +import {useRoute} from '@react-navigation/native'; +import type {PlatformStackRouteProp} from '@libs/Navigation/PlatformStackNavigation/types'; +import {canUserPerformWriteAction, isReportTransactionThread as isReportTransactionThreadUtil} from '@libs/ReportUtils'; +import type {ReportsSplitNavigatorParamList} from '@navigation/types'; +import {useConciergeSessionActions, useConciergeSessionState} from '@pages/inbox/ConciergeSessionContext'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type SCREENS from '@src/SCREENS'; +import {useCurrentReportIDState} from './useCurrentReportID'; +import useLoadReportActions from './useLoadReportActions'; +import useNetworkWithOfflineStatus from './useNetworkWithOfflineStatus'; +import useOnyx from './useOnyx'; +import useParentReportAction from './useParentReportAction'; +import useReportActionsPagination from './useReportActionsPagination'; +import useReportActionsVisibility from './useReportActionsVisibility'; +import useReportIsArchived from './useReportIsArchived'; + +/** + * Read/derive-only data pipeline for the report-actions list. + * + * Bundles every subscription + derivation needed for both the skeleton decision and the list render, so + * the guard's decision and the content's render share one pipeline. Intentionally side-effect-free: NO + * Onyx writes, navigation, telemetry, or session-start. `ReportActionsSkeletonGuard` calls this once and + * provides the result via `ReportActionsDataContext`, so the content reads it instead of subscribing again. + */ +function useReportActionsData(reportID: string) { + const {isOffline} = useNetworkWithOfflineStatus(); + const route = useRoute>(); + const reportActionIDFromRoute = route?.params?.reportActionID; + + const [report, reportResult] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); + + const { + reportActions, + allReportActions, + allReportActionIDs, + hasOlderActions, + hasNewerActions, + sortedAllReportActions, + oldestUnreadReportAction, + transactionThreadReportID, + transactionThreadReport, + parentReportActionForTransactionThread, + treatAsNoPaginationAnchor, + setTreatAsNoPaginationAnchor, + reportPreviewAction, + } = useReportActionsPagination(reportID, reportActionIDFromRoute); + + const parentReportAction = useParentReportAction(report); + + const [reportLoadingState] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${reportID}`); + const isLoadingInitialReportActions = reportLoadingState?.isLoadingInitialReportActions; + const hasOnceLoadedReportActions = reportLoadingState?.hasOnceLoadedReportActions; + + const {currentReportID} = useCurrentReportIDState(); + const {sessionStartTime, showFullHistory: conciergeShowFullHistory, hadMessagesAtSessionStart: conciergeHadMessagesAtSessionStart} = useConciergeSessionState(); + const {startSession, setShowFullHistory: setConciergeShowFullHistory, setHadMessagesAtSessionStart: setConciergeHadMessagesAtSessionStart} = useConciergeSessionActions(); + const isReportTransactionThread = isReportTransactionThreadUtil(report); + + const isReportArchived = useReportIsArchived(reportID); + const canPerformWriteAction = !!canUserPerformWriteAction(report, isReportArchived); + + const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); + + const [reportPaginationState] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_PAGINATION_STATE}${reportID}`); + + const {loadOlderChats, loadNewerChats} = useLoadReportActions({ + reportID, + reportActions, + allReportActionIDs, + transactionThreadReportID, + hasOlderActions, + hasNewerActions, + newestFetchedReportActionID: reportPaginationState?.newestFetchedReportActionID, + }); + + const { + sortedReportActions, + sortedVisibleReportActions, + isConciergeMainDM, + isConciergeHiddenHistory, + showConciergeSidePanelWelcome, + showFullHistory, + hasPreviousMessages, + handleShowPreviousMessages, + } = useReportActionsVisibility({ + reportID, + reportActions, + allReportActions, + canPerformWriteAction, + hasOlderActions, + loadOlderChats, + mainDMSessionStartTime: sessionStartTime, + conciergeShowFullHistory: conciergeShowFullHistory || !!reportActionIDFromRoute || !!report?.hasOutstandingChildTask, + setConciergeShowFullHistory, + conciergeHadMessagesAtSessionStart, + setConciergeHadMessagesAtSessionStart, + }); + + // hasOnceLoadedReportActions is RAM-only and resets to falsy on a page + // refresh, but cached report actions persist in Onyx. Gating the session + // start on it alone would leave sessionStartTime null until openReport + // returns, during which filterActions collapses the cached history down to + // just the synthetic CREATED action (an almost-empty chat flash). Start the + // session as soon as cached actions exist so messages render immediately on + // refresh, matching the concierge skeleton condition. + const canStartConciergeSession = !!hasOnceLoadedReportActions || allReportActions.length > 0; + + return { + isOffline, + reportActionIDFromRoute, + report, + reportResult, + reportActions, + allReportActions, + allReportActionIDs, + hasOlderActions, + hasNewerActions, + sortedAllReportActions, + oldestUnreadReportAction, + transactionThreadReportID, + transactionThreadReport, + parentReportActionForTransactionThread, + treatAsNoPaginationAnchor, + setTreatAsNoPaginationAnchor, + reportPreviewAction, + parentReportAction, + reportLoadingState, + isLoadingInitialReportActions, + hasOnceLoadedReportActions, + currentReportID, + sessionStartTime, + startSession, + isReportTransactionThread, + isReportArchived, + canPerformWriteAction, + isLoadingApp, + loadOlderChats, + loadNewerChats, + sortedReportActions, + sortedVisibleReportActions, + isConciergeMainDM, + isConciergeHiddenHistory, + showConciergeSidePanelWelcome, + showFullHistory, + hasPreviousMessages, + handleShowPreviousMessages, + canStartConciergeSession, + }; +} + +type ReportActionsData = ReturnType; + +export default useReportActionsData; +export type {ReportActionsData}; diff --git a/src/pages/inbox/report/ReportActionsDataContext.tsx b/src/pages/inbox/report/ReportActionsDataContext.tsx new file mode 100644 index 000000000000..06a8c6fbb6a9 --- /dev/null +++ b/src/pages/inbox/report/ReportActionsDataContext.tsx @@ -0,0 +1,108 @@ +import {createContext, useContext} from 'react'; +import type {ReportActionsData} from '@hooks/useReportActionsData'; +import {isUnread} from '@libs/ReportUtils'; +import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; + +/** + * Carries the single `useReportActionsData` pipeline result from `ReportActionsSkeletonGuard` + * down to `ReportActionsListContent`, so the content renders from the same data that drives the + * skeleton decision without subscribing again. + */ +const ReportActionsDataContext = createContext(null); + +/** Read the report-actions pipeline bundle. Throws if used outside the guard's provider. */ +function useReportActionsDataContext(): ReportActionsData { + const value = useContext(ReportActionsDataContext); + if (value === null) { + throw new Error('useReportActionsDataContext must be used within a ReportActionsDataContext.Provider'); + } + return value; +} + +type ReportActionsSkeletonState = { + shouldShowLoadingSkeleton: boolean; + shouldShowDerivedTimingSkeleton: boolean; + shouldShowInitialSkeleton: boolean; +}; + +/** + * Pure derivation of the two skeleton states from the pipeline bundle: a loading skeleton and the + * derived-value-timing skeleton. The guard uses these to decide whether to render the list. + */ +function computeReportActionsSkeletonState(data: ReportActionsData): ReportActionsSkeletonState { + const { + report, + reportResult, + isOffline, + reportActionIDFromRoute, + transactionThreadReport, + isReportArchived, + isReportTransactionThread, + isLoadingInitialReportActions, + hasOnceLoadedReportActions, + isLoadingApp, + reportActions, + oldestUnreadReportAction, + reportPreviewAction, + sortedVisibleReportActions, + isConciergeHiddenHistory, + isConciergeMainDM, + allReportActions, + showConciergeSidePanelWelcome, + } = data; + + const isReportUnread = isUnread(report, transactionThreadReport, isReportArchived); + + // When opening an unread report, it is very likely that the message we will open to is not the latest, + // which is the only one we will have in cache. + const isInitiallyLoadingReport = isReportUnread && !!isLoadingInitialReportActions && reportActions.length <= 1; + + // Same for unread messages, we need to wait for the results from the OpenReport API call + // if the oldest unread report action is not available yet. Only applies during the *first* load + // for this report: after `hasOnceLoadedReportActions` is set, a later "mark as unread" must not + // bring back this loading gate (we are not re-opening the report from a cold cache). + const isUnreadMessagePageLoadingInitially = !reportActionIDFromRoute && isReportUnread && !oldestUnreadReportAction && !hasOnceLoadedReportActions; + + // Once all the above conditions are met, we can consider the report ready. + const isReportLoading = isInitiallyLoadingReport || isUnreadMessagePageLoadingInitially; + const isReportReady = isOffline || !isReportLoading; + + const isSingleExpenseReport = reportPreviewAction?.childMoneyRequestCount === 1; + const isMissingTransactionThreadReportID = !transactionThreadReport?.reportID; + const isReportDataIncomplete = isSingleExpenseReport && isMissingTransactionThreadReportID; + const isMissingReportActions = sortedVisibleReportActions.length === 0; + + const shouldShowSkeletonForInitialLoad = !!isLoadingInitialReportActions && (isReportDataIncomplete || isMissingReportActions) && !isOffline; + + const shouldShowSkeletonForAppLoad = !!isLoadingApp && !isOffline; + + // Show skeleton for the Concierge chat (side panel or main DM) until report + // data has been loaded at least once. Before the first openReport response, + // hasOlderActions is unreliable, so we can't determine whether to show the + // greeting or onboarding messages. The skeleton avoids flashing wrong content. + // hasOnceLoadedReportActions is RAM-only and resets on a page refresh, but + // cached report actions persist in Onyx. For the main DM, render those cached + // actions immediately (matching production) instead of flashing a skeleton on + // every refresh; the side panel always opens fresh so it keeps gating on + // hasOnceLoadedReportActions only. allReportActions excludes the synthetic + // CREATED action that is always injected for Concierge, so it is empty only on + // a genuinely cold load with no cached history. + const shouldShowSkeletonForConciergePanel = isConciergeHiddenHistory && !hasOnceLoadedReportActions && !(isConciergeMainDM && allReportActions.length > 0) && !isOffline; + + const shouldShowInitialSkeleton = shouldShowSkeletonForConciergePanel || shouldShowSkeletonForInitialLoad || shouldShowSkeletonForAppLoad; + + const hasDerivedValueTimingIssue = reportActions.length > 0 && isMissingReportActions; + + const shouldShowLoadingSkeleton = isLoadingOnyxValue(reportResult) || !report || !isReportReady || shouldShowInitialSkeleton; + const shouldShowDerivedTimingSkeleton = (hasDerivedValueTimingIssue || (!isReportTransactionThread && isMissingReportActions)) && !showConciergeSidePanelWelcome; + + return { + shouldShowLoadingSkeleton, + shouldShowDerivedTimingSkeleton, + shouldShowInitialSkeleton, + }; +} + +export default ReportActionsDataContext; +export {useReportActionsDataContext, computeReportActionsSkeletonState}; +export type {ReportActionsSkeletonState}; diff --git a/src/pages/inbox/report/ReportActionsList.tsx b/src/pages/inbox/report/ReportActionsList.tsx index de288fad72e8..93397d556d7c 100644 --- a/src/pages/inbox/report/ReportActionsList.tsx +++ b/src/pages/inbox/report/ReportActionsList.tsx @@ -1,36 +1,24 @@ -import {useRoute} from '@react-navigation/native'; import {isTrackIntentUserSelector} from '@selectors/Onboarding'; import type {ListRenderItemInfo} from '@shopify/flash-list'; -import React, {memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState} from 'react'; +import React, {memo, useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react'; import type {LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent} from 'react-native'; import {View} from 'react-native'; import type {OnyxEntry} from 'react-native-onyx'; import {renderScrollComponent as renderActionSheetAwareScrollView} from '@components/ActionSheetAwareScrollView'; import InvertedFlashList from '@components/FlashList/InvertedFlashList'; import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; -import useCopySelectionHelper from '@hooks/useCopySelectionHelper'; -import {useCurrentReportIDState} from '@hooks/useCurrentReportID'; import useEnvironment from '@hooks/useEnvironment'; -import useLoadReportActions from '@hooks/useLoadReportActions'; import useLocalize from '@hooks/useLocalize'; import useMarkAsRead from '@hooks/useMarkAsRead'; -import useNetworkWithOfflineStatus from '@hooks/useNetworkWithOfflineStatus'; import useOnyx from '@hooks/useOnyx'; -import useParentReportAction from '@hooks/useParentReportAction'; -import usePendingConciergeResponse from '@hooks/usePendingConciergeResponse'; -import useReportActionsPagination from '@hooks/useReportActionsPagination'; import useReportActionsScroll from '@hooks/useReportActionsScroll'; -import useReportActionsVisibility from '@hooks/useReportActionsVisibility'; -import useReportIsArchived from '@hooks/useReportIsArchived'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useThemeStyles from '@hooks/useThemeStyles'; import useUnreadMarker from '@hooks/useUnreadMarker'; import useWindowDimensions from '@hooks/useWindowDimensions'; -import {updateLoadingInitialReportAction} from '@libs/actions/Report'; import {isConsecutiveChronosAutomaticTimerAction} from '@libs/ChronosUtils'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; -import type {PlatformStackRouteProp} from '@libs/Navigation/PlatformStackNavigation/types'; import TransitionTracker from '@libs/Navigation/TransitionTracker'; import { getFirstVisibleReportActionID, @@ -42,7 +30,6 @@ import { isTransactionThread, } from '@libs/ReportActionsUtils'; import { - canUserPerformWriteAction, chatIncludesChronosWithID, isArchivedNonExpenseReport, isCanceledTaskReport, @@ -50,27 +37,23 @@ import { isHarvestCreatedExpenseReport, isInvoiceReport, isIOUReport, - isReportTransactionThread as isReportTransactionThreadUtil, isTaskReport, - isUnread, shouldShowMarkAsDone, } from '@libs/ReportUtils'; import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; -import type {ReportsSplitNavigatorParamList} from '@navigation/types'; import {useConciergeDraft, useConciergeDraftActions} from '@pages/inbox/ConciergeDraftContext'; -import {useConciergeSessionActions, useConciergeSessionState} from '@pages/inbox/ConciergeSessionContext'; import {ActionListContext} from '@pages/inbox/ReportScreenContext'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import type SCREENS from '@src/SCREENS'; import {getStableReportSelector} from '@src/selectors/Report'; import type * as OnyxTypes from '@src/types/onyx'; -import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; import FloatingMessageCounter from './FloatingMessageCounter'; import ReportActionIndexContext from './ReportActionIndexContext'; +import {useReportActionsDataContext} from './ReportActionsDataContext'; import ReportActionsListHeader from './ReportActionsListHeader'; import ReportActionsListItemRenderer from './ReportActionsListItemRenderer'; import ReportActionsListPaddingView from './ReportActionsListPaddingView'; +import ReportActionsSkeletonGuard from './ReportActionsSkeletonGuard'; import ShowPreviousMessagesButton from './ShowPreviousMessagesButton'; type ReportActionsListProps = { @@ -95,56 +78,43 @@ function keyExtractor(item: OnyxTypes.ReportAction): string { return item.reportActionID; } -function ReportActionsList({reportID, onLayout}: ReportActionsListProps) { +/** + * Renders the report-actions list. Reads its data from `ReportActionsDataContext` and holds the + * UI-close hooks (`useUnreadMarker` / `useMarkAsRead` / `useReportActionsScroll`). `ReportActionsSkeletonGuard` + * mounts it only once content is ready, so those hooks never run while a skeleton shows. + */ +function ReportActionsListContent({reportID, onLayout}: ReportActionsListProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); const {windowHeight} = useWindowDimensions(); const {shouldUseNarrowLayout} = useResponsiveLayout(); const {isProduction} = useEnvironment(); - const {isOffline} = useNetworkWithOfflineStatus(); - const route = useRoute>(); - const reportActionIDFromRoute = route?.params?.reportActionID; - - // Side effects that must run whenever the chat list is shown. - useCopySelectionHelper(); - usePendingConciergeResponse(reportID); - - const [report, reportResult] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); - + const data = useReportActionsDataContext(); const { - reportActions, - allReportActions, - allReportActionIDs, - hasOlderActions, + isOffline, + reportActionIDFromRoute, + report, hasNewerActions, sortedAllReportActions, oldestUnreadReportAction, - transactionThreadReportID, transactionThreadReport, parentReportActionForTransactionThread, treatAsNoPaginationAnchor, setTreatAsNoPaginationAnchor, - reportPreviewAction, - } = useReportActionsPagination(reportID, reportActionIDFromRoute); - - const parentReportAction = useParentReportAction(report); - - const [reportLoadingState] = useOnyx(`${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${reportID}`); - const isLoadingInitialReportActions = reportLoadingState?.isLoadingInitialReportActions; - const hasOnceLoadedReportActions = reportLoadingState?.hasOnceLoadedReportActions; - - const {currentReportID} = useCurrentReportIDState(); - const {sessionStartTime, showFullHistory: conciergeShowFullHistory, hadMessagesAtSessionStart: conciergeHadMessagesAtSessionStart} = useConciergeSessionState(); - const {startSession, setShowFullHistory: setConciergeShowFullHistory, setHadMessagesAtSessionStart: setConciergeHadMessagesAtSessionStart} = useConciergeSessionActions(); - const isReportTransactionThread = isReportTransactionThreadUtil(report); - - const isReportArchived = useReportIsArchived(reportID); - const canPerformWriteAction = !!canUserPerformWriteAction(report, isReportArchived); - - const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP); - - const [reportPaginationState] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_PAGINATION_STATE}${reportID}`); + parentReportAction, + hasOnceLoadedReportActions, + sessionStartTime, + isReportArchived, + loadOlderChats, + loadNewerChats, + sortedReportActions, + sortedVisibleReportActions, + isConciergeHiddenHistory, + showFullHistory, + hasPreviousMessages, + handleShowPreviousMessages, + } = data; const didLayout = useRef(false); @@ -152,79 +122,9 @@ function ReportActionsList({reportID, onLayout}: ReportActionsListProps) { didLayout.current = false; }, [reportID]); - useEffect(() => { - // When we linked to message - we do not need to wait for initial actions - they already exists - if (!reportActionIDFromRoute || !isOffline) { - return; - } - updateLoadingInitialReportAction(report?.reportID ?? reportID); - }, [isOffline, report?.reportID, reportID, reportActionIDFromRoute]); - // Remount the list when the deep-linked message or unread anchor changes (scroll positioning), or when the report changes. const listID = [reportID, reportActionIDFromRoute, hasOnceLoadedReportActions ? undefined : oldestUnreadReportAction?.reportActionID].join(':'); - const {loadOlderChats, loadNewerChats} = useLoadReportActions({ - reportID, - reportActions, - allReportActionIDs, - transactionThreadReportID, - hasOlderActions, - hasNewerActions, - newestFetchedReportActionID: reportPaginationState?.newestFetchedReportActionID, - }); - - const { - sortedReportActions, - sortedVisibleReportActions, - isConciergeMainDM, - isConciergeHiddenHistory, - showConciergeSidePanelWelcome, - showFullHistory, - hasPreviousMessages, - handleShowPreviousMessages, - } = useReportActionsVisibility({ - reportID, - reportActions, - allReportActions, - canPerformWriteAction, - hasOlderActions, - loadOlderChats, - mainDMSessionStartTime: sessionStartTime, - conciergeShowFullHistory: conciergeShowFullHistory || !!reportActionIDFromRoute || !!report?.hasOutstandingChildTask, - setConciergeShowFullHistory, - conciergeHadMessagesAtSessionStart, - setConciergeHadMessagesAtSessionStart, - }); - - // hasOnceLoadedReportActions is RAM-only and resets to falsy on a page - // refresh, but cached report actions persist in Onyx. Gating the session - // start on it alone would leave sessionStartTime null until openReport - // returns, during which filterActions collapses the cached history down to - // just the synthetic CREATED action (an almost-empty chat flash). Start the - // session as soon as cached actions exist so messages render immediately on - // refresh, matching the skeleton-suppression gate below. - const canStartConciergeSession = !!hasOnceLoadedReportActions || allReportActions.length > 0; - - useLayoutEffect(() => { - if (!isConciergeMainDM || !canStartConciergeSession) { - return; - } - startSession(oldestUnreadReportAction ? report?.lastReadTime : undefined); - // eslint-disable-next-line react-hooks/exhaustive-deps -- startSession is stable; captured values at mount only - }, [isConciergeMainDM, startSession, canStartConciergeSession]); - - // On native the component stays mounted in the navigation stack, so the - // effect above never re-fires (its isConciergeMainDM dep is always true). - // Re-trigger startSession when the globally-focused report matches this - // report so the session age check runs after navigating away and back. - useLayoutEffect(() => { - if (!isConciergeMainDM || !canStartConciergeSession || currentReportID !== reportID) { - return; - } - startSession(oldestUnreadReportAction ? report?.lastReadTime : undefined); - // eslint-disable-next-line react-hooks/exhaustive-deps -- only react to currentReportID returning to this report - }, [currentReportID, reportID, isConciergeMainDM, canStartConciergeSession, startSession]); - const [reportNameValuePairs] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${reportID}`); const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector}); const [policy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${getNonEmptyStringOnyxID(report?.policyID)}`); @@ -540,11 +440,6 @@ function ReportActionsList({reportID, onLayout}: ReportActionsListProps) { isTrackIntentUser, }); - const isSingleExpenseReport = reportPreviewAction?.childMoneyRequestCount === 1; - const isMissingTransactionThreadReportID = !transactionThreadReport?.reportID; - const isReportDataIncomplete = isSingleExpenseReport && isMissingTransactionThreadReportID; - const isMissingReportActions = sortedVisibleReportActions.length === 0; - /** * Runs when the FlatList finishes laying out */ @@ -561,57 +456,13 @@ function ReportActionsList({reportID, onLayout}: ReportActionsListProps) { } }; - const shouldShowSkeletonForInitialLoad = !!isLoadingInitialReportActions && (isReportDataIncomplete || isMissingReportActions) && !isOffline; - - const shouldShowSkeletonForAppLoad = isLoadingApp && !isOffline; - - // Show skeleton for the Concierge chat (side panel or main DM) until report - // data has been loaded at least once. Before the first openReport response, - // hasOlderActions is unreliable, so we can't determine whether to show the - // greeting or onboarding messages. The skeleton avoids flashing wrong content. - // hasOnceLoadedReportActions is RAM-only and resets on a page refresh, but - // cached report actions persist in Onyx. For the main DM, render those cached - // actions immediately (matching production) instead of flashing a skeleton on - // every refresh; the side panel always opens fresh so it keeps gating on - // hasOnceLoadedReportActions only. allReportActions excludes the synthetic - // CREATED action that is always injected for Concierge, so it is empty only on - // a genuinely cold load with no cached history. - const shouldShowSkeletonForConciergePanel = isConciergeHiddenHistory && !hasOnceLoadedReportActions && !(isConciergeMainDM && allReportActions.length > 0) && !isOffline; - - const shouldShowInitialSkeleton = shouldShowSkeletonForConciergePanel || shouldShowSkeletonForInitialLoad || shouldShowSkeletonForAppLoad; - - useEffect(() => { - if (!shouldShowInitialSkeleton || !report) { - return; - } - markOpenReportEnd(report, {warm: false}); - }, [report, shouldShowInitialSkeleton]); - - const isReportUnread = isUnread(report, transactionThreadReport, isReportArchived); - - // When opening an unread report, it is very likely that the message we will open to is not the latest, - // which is the only one we will have in cache. - const isInitiallyLoadingReport = isReportUnread && !!reportLoadingState?.isLoadingInitialReportActions && reportActions.length <= 1; - - // Same for unread messages, we need to wait for the results from the OpenReport API call - // if the oldest unread report action is not available yet. Only applies during the *first* load - // for this report: after `hasOnceLoadedReportActions` is set, a later "mark as unread" must not - // bring back this loading gate (we are not re-opening the report from a cold cache). - const isUnreadMessagePageLoadingInitially = !reportActionIDFromRoute && isReportUnread && !oldestUnreadReportAction && !hasOnceLoadedReportActions; - - // Once all the above conditions are met, we can consider the report ready. - const isReportLoading = isInitiallyLoadingReport || isUnreadMessagePageLoadingInitially; - const isReportReady = isOffline || !isReportLoading; - - if (isLoadingOnyxValue(reportResult) || !report || !isReportReady || shouldShowInitialSkeleton) { + // The guard only mounts this content when the report is loaded, so this is effectively unreachable. + // It narrows `report` to non-undefined for the render below and stays a safe fallback if the report + // is cleared mid-session while the latch keeps the content mounted. + if (!report) { return ; } - const hasDerivedValueTimingIssue = reportActions.length > 0 && isMissingReportActions; - if ((hasDerivedValueTimingIssue || (!isReportTransactionThread && isMissingReportActions)) && !showConciergeSidePanelWelcome) { - return ; - } - return ( <> + + + ); +} + +export default ReportActionsList; diff --git a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx new file mode 100644 index 000000000000..f47ce72c6d65 --- /dev/null +++ b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx @@ -0,0 +1,101 @@ +import type {ReactNode} from 'react'; +import React, {useEffect, useLayoutEffect, useState} from 'react'; +import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; +import useCopySelectionHelper from '@hooks/useCopySelectionHelper'; +import usePendingConciergeResponse from '@hooks/usePendingConciergeResponse'; +import useReportActionsData from '@hooks/useReportActionsData'; +import {updateLoadingInitialReportAction} from '@libs/actions/Report'; +import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; +import ReportActionsDataContext, {computeReportActionsSkeletonState} from './ReportActionsDataContext'; + +type ReportActionsSkeletonGuardProps = { + /** The ID of the report to display actions for */ + reportID: string; + + /** The report-actions list content, rendered only once content is ready */ + children: ReactNode; +}; + +/** + * Skeleton gate for the report-actions list, modeled on `ReportNotFoundGuard`. + * + * Owns the single data pipeline (`useReportActionsData`) and the fine-grained skeleton decision, plus + * every effect that must run while the skeleton shows (concierge session start, the linked-message + * offline loading effect, and the warm:false open-report telemetry). It returns either the skeleton or + * the `children` (wrapped in `ReportActionsDataContext` so they render from the same pipeline). + * + * Because the UI-close hooks live in `children`, gating here means they are never mounted while a + * skeleton shows, so they cannot run during it. + * + * A forward latch keeps the full skeleton from reappearing once content has rendered: a transient + * empty visible-actions set must not unmount the content mid-session (which would tear down its scroll + * position and subscriptions). Because the UI-close hooks are no longer gated, this also means that + * after first content they stay active through such transients (mark-as-read, live-tail subscription) + * instead of being suppressed. That is intentional: content is on screen, so it should behave as visible. + */ +function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonGuardProps) { + const data = useReportActionsData(reportID); + const {report, isOffline, reportActionIDFromRoute, isConciergeMainDM, canStartConciergeSession, startSession, oldestUnreadReportAction, currentReportID} = data; + + const {shouldShowLoadingSkeleton, shouldShowDerivedTimingSkeleton, shouldShowInitialSkeleton} = computeReportActionsSkeletonState(data); + const shouldShowSkeleton = shouldShowLoadingSkeleton || shouldShowDerivedTimingSkeleton; + + // Forward latch: once content has shown, never return the full skeleton again for this mount. + const [hasShownContent, setHasShownContent] = useState(false); + if (!hasShownContent && !shouldShowSkeleton) { + setHasShownContent(true); + } + + // Side effects that must run whenever the chat list is shown, including while the skeleton renders. + useCopySelectionHelper(); + usePendingConciergeResponse(reportID); + + useEffect(() => { + // When we linked to message - we do not need to wait for initial actions - they already exists + if (!reportActionIDFromRoute || !isOffline) { + return; + } + updateLoadingInitialReportAction(report?.reportID ?? reportID); + }, [isOffline, report?.reportID, reportID, reportActionIDFromRoute]); + + useLayoutEffect(() => { + if (!isConciergeMainDM || !canStartConciergeSession) { + return; + } + startSession(oldestUnreadReportAction ? report?.lastReadTime : undefined); + // eslint-disable-next-line react-hooks/exhaustive-deps -- startSession is stable; captured values at mount only + }, [isConciergeMainDM, startSession, canStartConciergeSession]); + + // On native the component stays mounted in the navigation stack, so the + // effect above never re-fires (its isConciergeMainDM dep is always true). + // Re-trigger startSession when the globally-focused report matches this + // report so the session age check runs after navigating away and back. + useLayoutEffect(() => { + if (!isConciergeMainDM || !canStartConciergeSession || currentReportID !== reportID) { + return; + } + startSession(oldestUnreadReportAction ? report?.lastReadTime : undefined); + // eslint-disable-next-line react-hooks/exhaustive-deps -- only react to currentReportID returning to this report + }, [currentReportID, reportID, isConciergeMainDM, canStartConciergeSession, startSession]); + + useEffect(() => { + if (!shouldShowInitialSkeleton || !report) { + return; + } + markOpenReportEnd(report, {warm: false}); + }, [report, shouldShowInitialSkeleton]); + + if (!hasShownContent && shouldShowLoadingSkeleton) { + return ; + } + + if (!hasShownContent && shouldShowDerivedTimingSkeleton) { + return ; + } + + return {children}; +} + +ReportActionsSkeletonGuard.displayName = 'ReportActionsSkeletonGuard'; + +export default ReportActionsSkeletonGuard; diff --git a/tests/ui/ReportActionsListTest.tsx b/tests/ui/ReportActionsListTest.tsx index 196de6cdc5de..e68a941c8ce5 100644 --- a/tests/ui/ReportActionsListTest.tsx +++ b/tests/ui/ReportActionsListTest.tsx @@ -2,6 +2,7 @@ import type * as ReactNavigation from '@react-navigation/native'; import {render, screen} from '@testing-library/react-native'; import React from 'react'; +import {View} from 'react-native'; import Onyx from 'react-native-onyx'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useIsInSidePanel from '@hooks/useIsInSidePanel'; @@ -17,6 +18,7 @@ import DateUtils from '@libs/DateUtils'; import * as ReportActionsUtils from '@libs/ReportActionsUtils'; import {useConciergeSessionActions, useConciergeSessionState} from '@pages/inbox/ConciergeSessionContext'; import ReportActionsList from '@pages/inbox/report/ReportActionsList'; +import ReportActionsSkeletonGuard from '@pages/inbox/report/ReportActionsSkeletonGuard'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type * as OnyxTypes from '@src/types/onyx'; @@ -97,9 +99,11 @@ jest.mock('@hooks/usePrevious', () => jest.fn()); const mockUseCurrentUserPersonalDetails = useCurrentUserPersonalDetails as jest.MockedFunction; -// We mount the real hook-driven body and observe what it feeds the list via InvertedFlashList's `data`. -// The heavy scroll/marker hooks have their own unit tests, so they are stubbed here to isolate the -// body's visibility/skeleton logic — the actual subject of these tests. +// We mount the public ReportActionsList (the skeleton guard + its content) and observe what the content +// feeds the list via InvertedFlashList's `data`. The heavy scroll/marker hooks have their own unit tests, +// so they are stubbed here to isolate the skeleton logic. Because the guard only mounts the content when +// the skeleton is not showing, these stubs double as a probe for dormancy: while a skeleton renders the +// content is never mounted, so useMarkAsRead/useReportActionsScroll are never called. jest.mock('@components/FlashList/InvertedFlashList', () => jest.fn(() => null)); jest.mock('@hooks/useUnreadMarker', () => jest.fn(() => ({unreadMarkerReportActionID: null, unreadMarkerReportActionIndex: -1}))); jest.mock('@hooks/useMarkAsRead', () => jest.fn(() => ({markNewestActionAsRead: jest.fn(), completeSkippedMarkAsRead: jest.fn()}))); @@ -134,9 +138,14 @@ const mockReportActionItemCreated: jest.Mock = jest.requireMock('@pages/inbox/re /** Returns the report actions the body fed into the (mocked) inverted list on its latest render. */ const getCapturedVisibleActions = (): OnyxTypes.ReportAction[] | undefined => mockInvertedFlashList.mock.calls.at(-1)?.at(0)?.data; +const mockUseMarkAsRead: jest.Mock = jest.requireMock('@hooks/useMarkAsRead'); +const mockUseReportActionsScroll: jest.Mock = jest.requireMock('@hooks/useReportActionsScroll'); +const mockMarkOpenReportEnd: jest.Mock = jest.requireMock('@libs/telemetry/markOpenReportEnd'); + jest.mock('@libs/actions/Report', () => ({ updateLoadingInitialReportAction: jest.fn(), })); +jest.mock('@libs/telemetry/markOpenReportEnd', () => jest.fn()); const mockReport: OnyxTypes.Report = { reportID: '123', @@ -291,6 +300,10 @@ describe('ReportActionsList (body)', () => { renderReportActionsList(); expect(screen.getByTestId('ReportActionsSkeletonView')).toBeTruthy(); + // The guard does not mount the content while the skeleton shows, so the UI-close hooks never + // run and cannot consume unread state or open a new-action subscription. + expect(mockUseMarkAsRead).not.toHaveBeenCalled(); + expect(mockUseReportActionsScroll).not.toHaveBeenCalled(); }); it('should not show skeleton when shouldShowSkeletonForAppLoad is false (isLoadingApp is false and isOffline is false)', () => { @@ -323,6 +336,9 @@ describe('ReportActionsList (body)', () => { renderReportActionsList(); expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); + // The list is visible, so the guard mounts the content and the UI-close hooks run. + expect(mockUseMarkAsRead).toHaveBeenCalled(); + expect(mockUseReportActionsScroll).toHaveBeenCalled(); }); it('should not show skeleton when shouldShowSkeletonForAppLoad is false (isLoadingApp is true and isOffline is true)', () => { @@ -390,6 +406,57 @@ describe('ReportActionsList (body)', () => { }); }); + describe('Open-report telemetry', () => { + it('fires markOpenReportEnd with warm:false while the initial skeleton shows', () => { + mockUseNetwork.mockReturnValue({isOffline: false}); + + mockUseOnyx.mockImplementation((key: string) => { + if (key === ONYXKEYS.IS_LOADING_APP) { + return [true, {status: 'loaded'}]; + } + if (key === ONYXKEYS.RAM_ONLY_ARE_TRANSLATIONS_LOADING) { + return [false, {status: 'loaded'}]; + } + if (key.includes('reportLoadingState')) { + return [{isLoadingInitialReportActions: false, hasOnceLoadedReportActions: true}, {status: 'loaded'}]; + } + if (key.includes('reportActions')) { + return [[], {status: 'loaded'}]; + } + if (key === `${ONYXKEYS.COLLECTION.REPORT}${mockReport.reportID}`) { + return [mockReport, {status: 'loaded'}]; + } + if (key.includes('report')) { + return [undefined, {status: 'loaded'}]; + } + return [undefined, {status: 'loaded'}]; + }); + + // Empty report actions so the app-load skeleton renders. + mockUsePaginatedReportActions.mockReturnValue({ + ...defaultPaginatedReportActionsResult, + }); + + renderReportActionsList(); + + // The guard owns this mark now (it used to live in the body); it must still fire while the + // initial skeleton shows, otherwise the open-report span regresses. + expect(screen.getByTestId('ReportActionsSkeletonView')).toBeTruthy(); + expect(mockMarkOpenReportEnd).toHaveBeenCalledWith(mockReport, {warm: false}); + }); + + it('does not fire the warm:false mark once content is visible', () => { + // Default mocks render the list (no skeleton). warm:false is gated on the initial skeleton, so + // it must not fire here; warm:true comes from the list layout, not this path. + mockUseNetwork.mockReturnValue({isOffline: false}); + + renderReportActionsList(); + + expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); + expect(mockMarkOpenReportEnd).not.toHaveBeenCalledWith(mockReport, {warm: false}); + }); + }); + describe('Concierge Side Panel', () => { const CONCIERGE_REPORT_ID = '123'; const CURRENT_USER_ACCOUNT_ID = 100; @@ -790,6 +857,129 @@ describe('ReportActionsList (body)', () => { renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(screen.getByTestId('ReportActionsSkeletonView')).toBeTruthy(); + // The concierge-hidden-history skeleton shows while the report is otherwise "ready"; the content + // is still not mounted, so the UI-close hooks never run here either. + expect(mockUseMarkAsRead).not.toHaveBeenCalled(); + expect(mockUseReportActionsScroll).not.toHaveBeenCalled(); + }); + }); + + describe('Skeleton guard latch', () => { + // We render the guard directly (not via the ReportActionsList wrapper) so rerender() actually + // re-runs it. The wrapper's JSX is React-Compiler-memoized, so re-rendering it with an unchanged + // reportID returns the same guard element and React bails before the guard re-evaluates. + // The stub child only proves the guard keeps returning its children; that the real content's hooks + // and scroll state survive the transient (not just that *something* renders) rests on manual QA. + const renderGuard = () => + render( + + + , + ); + + it('keeps the content mounted once shown even if a skeleton condition flips back true mid-session', () => { + mockUseNetwork.mockReturnValue({isOffline: false}); + // isLoadingApp drives the app-load skeleton; flip it true after content has rendered. + let isLoadingApp = false; + mockUseOnyx.mockImplementation((key: string) => { + if (key === ONYXKEYS.IS_LOADING_APP) { + return [isLoadingApp, {status: 'loaded'}]; + } + if (key.includes('reportLoadingState')) { + return [{isLoadingInitialReportActions: false, hasOnceLoadedReportActions: true}, {status: 'loaded'}]; + } + if (key.includes('reportActions')) { + return [[], {status: 'loaded'}]; + } + if (key === `${ONYXKEYS.COLLECTION.REPORT}${mockReport.reportID}`) { + return [mockReport, {status: 'loaded'}]; + } + return [undefined, {status: 'loaded'}]; + }); + mockUsePaginatedReportActions.mockReturnValue({ + ...defaultPaginatedReportActionsResult, + reportActions: mockReportActions, + }); + + // Control (non-vacuity): a fresh mount with isLoadingApp true DOES show the skeleton, proving the + // trigger below is skeleton-inducing. + isLoadingApp = true; + const control = renderGuard(); + expect(screen.getByTestId('ReportActionsSkeletonView')).toBeTruthy(); + expect(screen.queryByTestId('latch-content')).toBeNull(); + control.unmount(); + + // First render with isLoadingApp false: the guard renders the content. + isLoadingApp = false; + const {rerender} = renderGuard(); + expect(screen.getByTestId('latch-content')).toBeTruthy(); + expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); + + // isLoadingApp flips back true mid-session. Without the latch the guard would unmount the content + // and show the skeleton again; the latch must keep the content mounted. + isLoadingApp = true; + rerender( + + + , + ); + + expect(screen.getByTestId('latch-content')).toBeTruthy(); + expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); + }); + + it('keeps the content mounted when the derived-value-timing skeleton flips true mid-session', () => { + // This covers the derived-timing return specifically (the transient empty visible-actions set + // that originally motivated the latch), which the isLoadingApp case above does not exercise. + mockUseNetwork.mockReturnValue({isOffline: false}); + mockUseOnyx.mockImplementation((key: string) => { + if (key === ONYXKEYS.IS_LOADING_APP) { + return [false, {status: 'loaded'}]; + } + if (key.includes('reportLoadingState')) { + return [{isLoadingInitialReportActions: false, hasOnceLoadedReportActions: true}, {status: 'loaded'}]; + } + if (key.includes('reportActions')) { + return [[], {status: 'loaded'}]; + } + if (key === `${ONYXKEYS.COLLECTION.REPORT}${mockReport.reportID}`) { + return [mockReport, {status: 'loaded'}]; + } + return [undefined, {status: 'loaded'}]; + }); + + // Control (non-vacuity): empty visible actions on a fresh mount DOES show the derived-timing skeleton. + mockUsePaginatedReportActions.mockReturnValue({ + ...defaultPaginatedReportActionsResult, + reportActions: [], + }); + const control = renderGuard(); + expect(screen.getByTestId('ReportActionsSkeletonView')).toBeTruthy(); + expect(screen.queryByTestId('latch-content')).toBeNull(); + control.unmount(); + + // First render with actions present: the guard renders the content. + mockUsePaginatedReportActions.mockReturnValue({ + ...defaultPaginatedReportActionsResult, + reportActions: mockReportActions, + }); + const {rerender} = renderGuard(); + expect(screen.getByTestId('latch-content')).toBeTruthy(); + expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); + + // Visible actions transiently empty out (derived-timing skeleton condition). The latch must hold. + mockUsePaginatedReportActions.mockReturnValue({ + ...defaultPaginatedReportActionsResult, + reportActions: [], + }); + rerender( + + + , + ); + + expect(screen.getByTestId('latch-content')).toBeTruthy(); + expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); }); }); }); From 0c8a4c18754682eafc58e43f9f359e2eaef78837 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Tue, 23 Jun 2026 09:57:14 +0200 Subject: [PATCH 11/22] split context to guardData and contentData --- src/hooks/useReportActionsData.ts | 62 ++++++++++++------- .../inbox/report/ReportActionsDataContext.tsx | 24 +++---- src/pages/inbox/report/ReportActionsList.tsx | 23 +++++-- .../report/ReportActionsSkeletonGuard.tsx | 12 ++-- 4 files changed, 71 insertions(+), 50 deletions(-) diff --git a/src/hooks/useReportActionsData.ts b/src/hooks/useReportActionsData.ts index abfa85de8fd4..ff102a8a321c 100644 --- a/src/hooks/useReportActionsData.ts +++ b/src/hooks/useReportActionsData.ts @@ -105,50 +105,66 @@ function useReportActionsData(reportID: string) { // refresh, matching the concierge skeleton condition. const canStartConciergeSession = !!hasOnceLoadedReportActions || allReportActions.length > 0; - return { - isOffline, - reportActionIDFromRoute, + // What the skeleton decision (`computeReportActionsSkeletonState`) and the guard's effects read. The + // guard consumes this locally; it is never put on the context, so changes to these (loading flags, + // app-load, concierge-session start, navigation) do not re-render the list content. + const guardData = { report, reportResult, + isOffline, + reportActionIDFromRoute, + transactionThreadReport, + isReportArchived, + isReportTransactionThread, + isLoadingInitialReportActions, + hasOnceLoadedReportActions, + isLoadingApp, reportActions, + oldestUnreadReportAction, + reportPreviewAction, + sortedVisibleReportActions, + isConciergeHiddenHistory, + isConciergeMainDM, allReportActions, - allReportActionIDs, - hasOlderActions, + showConciergeSidePanelWelcome, + canStartConciergeSession, + startSession, + currentReportID, + }; + + // The report-actions pipeline outputs the list needs. This is the only slice carried through + // `ReportActionsDataContext`. `report` and `hasOnceLoadedReportActions` stay here even though they look + // ambient: this hook already subscribes to them, and the list's pipeline derivations were built from + // this `report`, so re-reading them in the content would only add a duplicate subscription and split + // `report` from its own derivations. Truly ambient state (network, route, archived, concierge session) + // is read locally in the content instead, since it adds no subscription the pipeline doesn't hold. + const contentData = { + report, + hasOnceLoadedReportActions, hasNewerActions, sortedAllReportActions, oldestUnreadReportAction, - transactionThreadReportID, transactionThreadReport, parentReportActionForTransactionThread, treatAsNoPaginationAnchor, setTreatAsNoPaginationAnchor, - reportPreviewAction, parentReportAction, - reportLoadingState, - isLoadingInitialReportActions, - hasOnceLoadedReportActions, - currentReportID, - sessionStartTime, - startSession, - isReportTransactionThread, - isReportArchived, - canPerformWriteAction, - isLoadingApp, - loadOlderChats, - loadNewerChats, sortedReportActions, sortedVisibleReportActions, - isConciergeMainDM, isConciergeHiddenHistory, - showConciergeSidePanelWelcome, showFullHistory, hasPreviousMessages, handleShowPreviousMessages, - canStartConciergeSession, + loadOlderChats, + loadNewerChats, }; + + return {guardData, contentData}; } type ReportActionsData = ReturnType; +type ReportActionsGuardData = ReportActionsData['guardData']; +type ReportActionsContentData = ReportActionsData['contentData']; export default useReportActionsData; -export type {ReportActionsData}; +export type {ReportActionsData, ReportActionsGuardData, ReportActionsContentData}; diff --git a/src/pages/inbox/report/ReportActionsDataContext.tsx b/src/pages/inbox/report/ReportActionsDataContext.tsx index 06a8c6fbb6a9..057b34d12f70 100644 --- a/src/pages/inbox/report/ReportActionsDataContext.tsx +++ b/src/pages/inbox/report/ReportActionsDataContext.tsx @@ -1,17 +1,18 @@ import {createContext, useContext} from 'react'; -import type {ReportActionsData} from '@hooks/useReportActionsData'; +import type {ReportActionsContentData, ReportActionsGuardData} from '@hooks/useReportActionsData'; import {isUnread} from '@libs/ReportUtils'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; /** - * Carries the single `useReportActionsData` pipeline result from `ReportActionsSkeletonGuard` - * down to `ReportActionsListContent`, so the content renders from the same data that drives the - * skeleton decision without subscribing again. + * Carries the heavy report-actions pipeline outputs (`contentData`) from `ReportActionsSkeletonGuard` + * down to `ReportActionsListContent`, so the content renders from the same derivations that drive the + * skeleton decision without subscribing again. Ambient state (network, route, archived, loading flag, + * concierge session) is intentionally NOT carried here — the content reads it locally. */ -const ReportActionsDataContext = createContext(null); +const ReportActionsDataContext = createContext(null); -/** Read the report-actions pipeline bundle. Throws if used outside the guard's provider. */ -function useReportActionsDataContext(): ReportActionsData { +/** Read the report-actions pipeline outputs. Throws if used outside the guard's provider. */ +function useReportActionsDataContext(): ReportActionsContentData { const value = useContext(ReportActionsDataContext); if (value === null) { throw new Error('useReportActionsDataContext must be used within a ReportActionsDataContext.Provider'); @@ -19,17 +20,11 @@ function useReportActionsDataContext(): ReportActionsData { return value; } -type ReportActionsSkeletonState = { - shouldShowLoadingSkeleton: boolean; - shouldShowDerivedTimingSkeleton: boolean; - shouldShowInitialSkeleton: boolean; -}; - /** * Pure derivation of the two skeleton states from the pipeline bundle: a loading skeleton and the * derived-value-timing skeleton. The guard uses these to decide whether to render the list. */ -function computeReportActionsSkeletonState(data: ReportActionsData): ReportActionsSkeletonState { +function computeReportActionsSkeletonState(data: ReportActionsGuardData) { const { report, reportResult, @@ -105,4 +100,3 @@ function computeReportActionsSkeletonState(data: ReportActionsData): ReportActio export default ReportActionsDataContext; export {useReportActionsDataContext, computeReportActionsSkeletonState}; -export type {ReportActionsSkeletonState}; diff --git a/src/pages/inbox/report/ReportActionsList.tsx b/src/pages/inbox/report/ReportActionsList.tsx index 93397d556d7c..b571bb34bc6f 100644 --- a/src/pages/inbox/report/ReportActionsList.tsx +++ b/src/pages/inbox/report/ReportActionsList.tsx @@ -1,3 +1,4 @@ +import {useRoute} from '@react-navigation/native'; import {isTrackIntentUserSelector} from '@selectors/Onboarding'; import type {ListRenderItemInfo} from '@shopify/flash-list'; import React, {memo, useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react'; @@ -10,6 +11,7 @@ import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; import useEnvironment from '@hooks/useEnvironment'; import useLocalize from '@hooks/useLocalize'; import useMarkAsRead from '@hooks/useMarkAsRead'; +import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import useReportActionsScroll from '@hooks/useReportActionsScroll'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; @@ -19,6 +21,7 @@ import useWindowDimensions from '@hooks/useWindowDimensions'; import {isConsecutiveChronosAutomaticTimerAction} from '@libs/ChronosUtils'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; +import type {PlatformStackRouteProp} from '@libs/Navigation/PlatformStackNavigation/types'; import TransitionTracker from '@libs/Navigation/TransitionTracker'; import { getFirstVisibleReportActionID, @@ -32,6 +35,7 @@ import { import { chatIncludesChronosWithID, isArchivedNonExpenseReport, + isArchivedReport, isCanceledTaskReport, isExpenseReport, isHarvestCreatedExpenseReport, @@ -41,10 +45,13 @@ import { shouldShowMarkAsDone, } from '@libs/ReportUtils'; import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; +import type {ReportsSplitNavigatorParamList} from '@navigation/types'; import {useConciergeDraft, useConciergeDraftActions} from '@pages/inbox/ConciergeDraftContext'; +import {useConciergeSessionState} from '@pages/inbox/ConciergeSessionContext'; import {ActionListContext} from '@pages/inbox/ReportScreenContext'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; +import type SCREENS from '@src/SCREENS'; import {getStableReportSelector} from '@src/selectors/Report'; import type * as OnyxTypes from '@src/types/onyx'; import FloatingMessageCounter from './FloatingMessageCounter'; @@ -91,10 +98,10 @@ function ReportActionsListContent({reportID, onLayout}: ReportActionsListProps) const {isProduction} = useEnvironment(); const data = useReportActionsDataContext(); + const { - isOffline, - reportActionIDFromRoute, report, + hasOnceLoadedReportActions, hasNewerActions, sortedAllReportActions, oldestUnreadReportAction, @@ -103,9 +110,6 @@ function ReportActionsListContent({reportID, onLayout}: ReportActionsListProps) treatAsNoPaginationAnchor, setTreatAsNoPaginationAnchor, parentReportAction, - hasOnceLoadedReportActions, - sessionStartTime, - isReportArchived, loadOlderChats, loadNewerChats, sortedReportActions, @@ -116,6 +120,14 @@ function ReportActionsListContent({reportID, onLayout}: ReportActionsListProps) handleShowPreviousMessages, } = data; + // Truly ambient state read locally instead of via the context. These add no Onyx subscription the + // pipeline doesn't already hold: network and route are not Onyx, the concierge session is a context, + // and archived is derived from the report NVPs we already subscribe to below. + const {isOffline} = useNetwork(); + const route = useRoute>(); + const reportActionIDFromRoute = route?.params?.reportActionID; + const {sessionStartTime} = useConciergeSessionState(); + const didLayout = useRef(false); useEffect(() => { @@ -126,6 +138,7 @@ function ReportActionsListContent({reportID, onLayout}: ReportActionsListProps) const listID = [reportID, reportActionIDFromRoute, hasOnceLoadedReportActions ? undefined : oldestUnreadReportAction?.reportActionID].join(':'); const [reportNameValuePairs] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${reportID}`); + const isReportArchived = !!isArchivedReport(reportNameValuePairs); const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector}); const [policy] = useOnyx(`${ONYXKEYS.COLLECTION.POLICY}${getNonEmptyStringOnyxID(report?.policyID)}`); diff --git a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx index f47ce72c6d65..cf017d5bd6ac 100644 --- a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx +++ b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx @@ -34,10 +34,8 @@ type ReportActionsSkeletonGuardProps = { * instead of being suppressed. That is intentional: content is on screen, so it should behave as visible. */ function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonGuardProps) { - const data = useReportActionsData(reportID); - const {report, isOffline, reportActionIDFromRoute, isConciergeMainDM, canStartConciergeSession, startSession, oldestUnreadReportAction, currentReportID} = data; - - const {shouldShowLoadingSkeleton, shouldShowDerivedTimingSkeleton, shouldShowInitialSkeleton} = computeReportActionsSkeletonState(data); + const {guardData, contentData} = useReportActionsData(reportID); + const {shouldShowLoadingSkeleton, shouldShowDerivedTimingSkeleton, shouldShowInitialSkeleton} = computeReportActionsSkeletonState(guardData); const shouldShowSkeleton = shouldShowLoadingSkeleton || shouldShowDerivedTimingSkeleton; // Forward latch: once content has shown, never return the full skeleton again for this mount. @@ -50,6 +48,8 @@ function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonG useCopySelectionHelper(); usePendingConciergeResponse(reportID); + const {report, isOffline, reportActionIDFromRoute, isConciergeMainDM, canStartConciergeSession, startSession, oldestUnreadReportAction, currentReportID} = guardData; + useEffect(() => { // When we linked to message - we do not need to wait for initial actions - they already exists if (!reportActionIDFromRoute || !isOffline) { @@ -93,9 +93,7 @@ function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonG return ; } - return {children}; + return {children}; } -ReportActionsSkeletonGuard.displayName = 'ReportActionsSkeletonGuard'; - export default ReportActionsSkeletonGuard; From db5f1e67a6d3931c38b8c8c78c784cabc21e0a3a Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Tue, 23 Jun 2026 10:04:16 +0200 Subject: [PATCH 12/22] clean up comments --- src/hooks/useReportActionsData.ts | 14 +++++--------- .../inbox/report/ReportActionsDataContext.tsx | 7 +++---- src/pages/inbox/report/ReportActionsList.tsx | 4 ---- 3 files changed, 8 insertions(+), 17 deletions(-) diff --git a/src/hooks/useReportActionsData.ts b/src/hooks/useReportActionsData.ts index ff102a8a321c..15456f947a9d 100644 --- a/src/hooks/useReportActionsData.ts +++ b/src/hooks/useReportActionsData.ts @@ -105,9 +105,8 @@ function useReportActionsData(reportID: string) { // refresh, matching the concierge skeleton condition. const canStartConciergeSession = !!hasOnceLoadedReportActions || allReportActions.length > 0; - // What the skeleton decision (`computeReportActionsSkeletonState`) and the guard's effects read. The - // guard consumes this locally; it is never put on the context, so changes to these (loading flags, - // app-load, concierge-session start, navigation) do not re-render the list content. + // Guard-only slice: skeleton decision + effects. Kept off the context so its churn (loading, + // app-load, concierge-session, navigation) never re-renders the list. const guardData = { report, reportResult, @@ -132,12 +131,9 @@ function useReportActionsData(reportID: string) { currentReportID, }; - // The report-actions pipeline outputs the list needs. This is the only slice carried through - // `ReportActionsDataContext`. `report` and `hasOnceLoadedReportActions` stay here even though they look - // ambient: this hook already subscribes to them, and the list's pipeline derivations were built from - // this `report`, so re-reading them in the content would only add a duplicate subscription and split - // `report` from its own derivations. Truly ambient state (network, route, archived, concierge session) - // is read locally in the content instead, since it adds no subscription the pipeline doesn't hold. + // The only slice on the context: pipeline outputs the list renders. `report` and + // `hasOnceLoadedReportActions` stay here (already subscribed here; keeps `report` consistent with its + // derivations). Ambient state (network, route, archived, concierge session) is read locally instead. const contentData = { report, hasOnceLoadedReportActions, diff --git a/src/pages/inbox/report/ReportActionsDataContext.tsx b/src/pages/inbox/report/ReportActionsDataContext.tsx index 057b34d12f70..6b52aa47af64 100644 --- a/src/pages/inbox/report/ReportActionsDataContext.tsx +++ b/src/pages/inbox/report/ReportActionsDataContext.tsx @@ -4,10 +4,9 @@ import {isUnread} from '@libs/ReportUtils'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; /** - * Carries the heavy report-actions pipeline outputs (`contentData`) from `ReportActionsSkeletonGuard` - * down to `ReportActionsListContent`, so the content renders from the same derivations that drive the - * skeleton decision without subscribing again. Ambient state (network, route, archived, loading flag, - * concierge session) is intentionally NOT carried here — the content reads it locally. + * Carries `contentData` (the pipeline outputs the list renders) from `ReportActionsSkeletonGuard` to + * `ReportActionsListContent`, so the list renders from the same derivations as the skeleton decision + * without re-subscribing. Ambient state (network, route, archived, concierge session) is read locally. */ const ReportActionsDataContext = createContext(null); diff --git a/src/pages/inbox/report/ReportActionsList.tsx b/src/pages/inbox/report/ReportActionsList.tsx index b571bb34bc6f..ff8de041bf20 100644 --- a/src/pages/inbox/report/ReportActionsList.tsx +++ b/src/pages/inbox/report/ReportActionsList.tsx @@ -119,10 +119,6 @@ function ReportActionsListContent({reportID, onLayout}: ReportActionsListProps) hasPreviousMessages, handleShowPreviousMessages, } = data; - - // Truly ambient state read locally instead of via the context. These add no Onyx subscription the - // pipeline doesn't already hold: network and route are not Onyx, the concierge session is a context, - // and archived is derived from the report NVPs we already subscribe to below. const {isOffline} = useNetwork(); const route = useRoute>(); const reportActionIDFromRoute = route?.params?.reportActionID; From 73582a3fed85a106001295a2e993ceed9c523c13 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Tue, 23 Jun 2026 10:53:43 +0200 Subject: [PATCH 13/22] fix knip --- src/hooks/useReportActionsData.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hooks/useReportActionsData.ts b/src/hooks/useReportActionsData.ts index 15456f947a9d..3eb027e69e8a 100644 --- a/src/hooks/useReportActionsData.ts +++ b/src/hooks/useReportActionsData.ts @@ -163,4 +163,4 @@ type ReportActionsGuardData = ReportActionsData['guardData']; type ReportActionsContentData = ReportActionsData['contentData']; export default useReportActionsData; -export type {ReportActionsData, ReportActionsGuardData, ReportActionsContentData}; +export type {ReportActionsGuardData, ReportActionsContentData}; From 3ab6856df9f895a348bf94ba4748357ae92b9fb1 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Thu, 25 Jun 2026 09:18:04 +0200 Subject: [PATCH 14/22] Split into custom hooks --- src/hooks/useLinkedMessageOfflineLoading.ts | 30 ++++++++ src/hooks/useReportActionsData.ts | 49 +++++------- .../useReportActionsSkeletonTelemetry.ts | 23 ++++++ src/hooks/useStartConciergeSession.ts | 55 ++++++++++++++ .../inbox/report/ReportActionsDataContext.tsx | 27 +++---- src/pages/inbox/report/ReportActionsList.tsx | 3 + .../report/ReportActionsSkeletonGuard.tsx | 74 ++++++------------- 7 files changed, 164 insertions(+), 97 deletions(-) create mode 100644 src/hooks/useLinkedMessageOfflineLoading.ts create mode 100644 src/hooks/useReportActionsSkeletonTelemetry.ts create mode 100644 src/hooks/useStartConciergeSession.ts diff --git a/src/hooks/useLinkedMessageOfflineLoading.ts b/src/hooks/useLinkedMessageOfflineLoading.ts new file mode 100644 index 000000000000..98c1ec2458f2 --- /dev/null +++ b/src/hooks/useLinkedMessageOfflineLoading.ts @@ -0,0 +1,30 @@ +import {useEffect} from 'react'; +import {updateLoadingInitialReportAction} from '@libs/actions/Report'; +import useNetwork from './useNetwork'; + +type UseLinkedMessageOfflineLoadingParams = { + /** The ID of the report whose initial-actions loading flag should be cleared */ + reportID: string; + + /** The report action ID linked from the route, if any */ + reportActionIDFromRoute: string | undefined; +}; + +/** + * When deep-linking to a message while offline, the linked actions are already cached, so clear the + * initial-actions loading flag instead of waiting for OpenReport. In the content, not the guard, because it + * only runs offline, where no skeleton shows. + */ +function useLinkedMessageOfflineLoading({reportID, reportActionIDFromRoute}: UseLinkedMessageOfflineLoadingParams) { + const {isOffline} = useNetwork(); + + useEffect(() => { + // When we linked to message - we do not need to wait for initial actions - they already exists + if (!reportActionIDFromRoute || !isOffline) { + return; + } + updateLoadingInitialReportAction(reportID); + }, [isOffline, reportID, reportActionIDFromRoute]); +} + +export default useLinkedMessageOfflineLoading; diff --git a/src/hooks/useReportActionsData.ts b/src/hooks/useReportActionsData.ts index 3eb027e69e8a..7d23dabf2bef 100644 --- a/src/hooks/useReportActionsData.ts +++ b/src/hooks/useReportActionsData.ts @@ -5,7 +5,6 @@ import type {ReportsSplitNavigatorParamList} from '@navigation/types'; import {useConciergeSessionActions, useConciergeSessionState} from '@pages/inbox/ConciergeSessionContext'; import ONYXKEYS from '@src/ONYXKEYS'; import type SCREENS from '@src/SCREENS'; -import {useCurrentReportIDState} from './useCurrentReportID'; import useLoadReportActions from './useLoadReportActions'; import useNetworkWithOfflineStatus from './useNetworkWithOfflineStatus'; import useOnyx from './useOnyx'; @@ -15,12 +14,10 @@ import useReportActionsVisibility from './useReportActionsVisibility'; import useReportIsArchived from './useReportIsArchived'; /** - * Read/derive-only data pipeline for the report-actions list. - * - * Bundles every subscription + derivation needed for both the skeleton decision and the list render, so - * the guard's decision and the content's render share one pipeline. Intentionally side-effect-free: NO - * Onyx writes, navigation, telemetry, or session-start. `ReportActionsSkeletonGuard` calls this once and - * provides the result via `ReportActionsDataContext`, so the content reads it instead of subscribing again. + * Single read/derive pipeline for the report-actions list: the subscriptions and derivations the skeleton + * decision and the list render both need, computed once. Side-effect-free (no writes/navigation/telemetry/ + * session-start). The guard calls it once and passes `contentData` via `ReportActionsDataContext` so the + * content doesn't re-subscribe. */ function useReportActionsData(reportID: string) { const {isOffline} = useNetworkWithOfflineStatus(); @@ -51,9 +48,8 @@ function useReportActionsData(reportID: string) { const isLoadingInitialReportActions = reportLoadingState?.isLoadingInitialReportActions; const hasOnceLoadedReportActions = reportLoadingState?.hasOnceLoadedReportActions; - const {currentReportID} = useCurrentReportIDState(); const {sessionStartTime, showFullHistory: conciergeShowFullHistory, hadMessagesAtSessionStart: conciergeHadMessagesAtSessionStart} = useConciergeSessionState(); - const {startSession, setShowFullHistory: setConciergeShowFullHistory, setHadMessagesAtSessionStart: setConciergeHadMessagesAtSessionStart} = useConciergeSessionActions(); + const {setShowFullHistory: setConciergeShowFullHistory, setHadMessagesAtSessionStart: setConciergeHadMessagesAtSessionStart} = useConciergeSessionActions(); const isReportTransactionThread = isReportTransactionThreadUtil(report); const isReportArchived = useReportIsArchived(reportID); @@ -96,17 +92,14 @@ function useReportActionsData(reportID: string) { setConciergeHadMessagesAtSessionStart, }); - // hasOnceLoadedReportActions is RAM-only and resets to falsy on a page - // refresh, but cached report actions persist in Onyx. Gating the session - // start on it alone would leave sessionStartTime null until openReport - // returns, during which filterActions collapses the cached history down to - // just the synthetic CREATED action (an almost-empty chat flash). Start the - // session as soon as cached actions exist so messages render immediately on - // refresh, matching the concierge skeleton condition. - const canStartConciergeSession = !!hasOnceLoadedReportActions || allReportActions.length > 0; - - // Guard-only slice: skeleton decision + effects. Kept off the context so its churn (loading, - // app-load, concierge-session, navigation) never re-renders the list. + const isMissingReportActions = sortedVisibleReportActions.length === 0; + const isSingleExpenseReport = reportPreviewAction?.childMoneyRequestCount === 1; + // allReportActions excludes the synthetic CREATED action always injected for Concierge, so this is + // false only on a genuinely cold load with no cached history. + const hasCachedReportActions = allReportActions.length > 0; + + // Guard-only inputs to the skeleton decision (some also read by the guard's effect hooks). Off the + // context so its churn (loading, app-load, concierge-session, navigation) never re-renders the list. const guardData = { report, reportResult, @@ -118,22 +111,18 @@ function useReportActionsData(reportID: string) { isLoadingInitialReportActions, hasOnceLoadedReportActions, isLoadingApp, - reportActions, + reportActionsLength: reportActions.length, oldestUnreadReportAction, - reportPreviewAction, - sortedVisibleReportActions, + isSingleExpenseReport, + isMissingReportActions, isConciergeHiddenHistory, isConciergeMainDM, - allReportActions, + hasCachedReportActions, showConciergeSidePanelWelcome, - canStartConciergeSession, - startSession, - currentReportID, }; - // The only slice on the context: pipeline outputs the list renders. `report` and - // `hasOnceLoadedReportActions` stay here (already subscribed here; keeps `report` consistent with its - // derivations). Ambient state (network, route, archived, concierge session) is read locally instead. + // The only slice on the context, so it alone drives list re-renders. Ambient state (network, route, + // archived, concierge session) is read locally in the content instead of carried here. const contentData = { report, hasOnceLoadedReportActions, diff --git a/src/hooks/useReportActionsSkeletonTelemetry.ts b/src/hooks/useReportActionsSkeletonTelemetry.ts new file mode 100644 index 000000000000..b6ec8132a7bd --- /dev/null +++ b/src/hooks/useReportActionsSkeletonTelemetry.ts @@ -0,0 +1,23 @@ +import {useEffect} from 'react'; +import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; +import type {ReportActionsGuardData} from './useReportActionsData'; + +type UseReportActionsSkeletonTelemetryParams = Pick & { + /** Whether the initial-load skeleton is showing */ + shouldShowInitialSkeleton: boolean; +}; + +/** + * Records the warm:false open-report end. Lives in the guard, not the content, because it must fire while + * the skeleton shows, when the content isn't mounted. + */ +function useReportActionsSkeletonTelemetry({report, shouldShowInitialSkeleton}: UseReportActionsSkeletonTelemetryParams) { + useEffect(() => { + if (!shouldShowInitialSkeleton || !report) { + return; + } + markOpenReportEnd(report, {warm: false}); + }, [report, shouldShowInitialSkeleton]); +} + +export default useReportActionsSkeletonTelemetry; diff --git a/src/hooks/useStartConciergeSession.ts b/src/hooks/useStartConciergeSession.ts new file mode 100644 index 000000000000..c1e954bd36c8 --- /dev/null +++ b/src/hooks/useStartConciergeSession.ts @@ -0,0 +1,55 @@ +import {useLayoutEffect} from 'react'; +import {useConciergeSessionActions} from '@pages/inbox/ConciergeSessionContext'; +import {useCurrentReportIDState} from './useCurrentReportID'; +import type {ReportActionsGuardData} from './useReportActionsData'; + +type UseStartConciergeSessionParams = Pick & { + /** The ID of the report to display actions for */ + reportID: string; + + /** The report's lastReadTime, used as the unread boundary when starting the session */ + lastReadTime: string | undefined; + + /** Whether actions are already cached, excluding the synthetic CREATED action */ + hasCachedReportActions: boolean; +}; + +/** + * Starts the Concierge main-DM session. Subscribes to currentReportID/startSession itself so the pipeline + * doesn't carry them; currentReportID re-renders the guard but never the list. + */ +function useStartConciergeSession({reportID, lastReadTime, isConciergeMainDM, oldestUnreadReportAction, hasOnceLoadedReportActions, hasCachedReportActions}: UseStartConciergeSessionParams) { + const {currentReportID} = useCurrentReportIDState(); + const {startSession} = useConciergeSessionActions(); + + // hasOnceLoadedReportActions is RAM-only and resets to falsy on a page + // refresh, but cached report actions persist in Onyx. Gating the session + // start on it alone would leave sessionStartTime null until openReport + // returns, during which filterActions collapses the cached history down to + // just the synthetic CREATED action (an almost-empty chat flash). Start the + // session as soon as cached actions exist so messages render immediately on + // refresh, matching the concierge skeleton condition. + const canStartConciergeSession = !!hasOnceLoadedReportActions || hasCachedReportActions; + + useLayoutEffect(() => { + if (!isConciergeMainDM || !canStartConciergeSession) { + return; + } + startSession(oldestUnreadReportAction ? lastReadTime : undefined); + // eslint-disable-next-line react-hooks/exhaustive-deps -- startSession is stable; captured values at mount only + }, [isConciergeMainDM, startSession, canStartConciergeSession]); + + // On native the component stays mounted in the navigation stack, so the + // effect above never re-fires (its isConciergeMainDM dep is always true). + // Re-trigger startSession when the globally-focused report matches this + // report so the session age check runs after navigating away and back. + useLayoutEffect(() => { + if (!isConciergeMainDM || !canStartConciergeSession || currentReportID !== reportID) { + return; + } + startSession(oldestUnreadReportAction ? lastReadTime : undefined); + // eslint-disable-next-line react-hooks/exhaustive-deps -- only react to currentReportID returning to this report + }, [currentReportID, reportID, isConciergeMainDM, canStartConciergeSession, startSession]); +} + +export default useStartConciergeSession; diff --git a/src/pages/inbox/report/ReportActionsDataContext.tsx b/src/pages/inbox/report/ReportActionsDataContext.tsx index 6b52aa47af64..4183cbb53659 100644 --- a/src/pages/inbox/report/ReportActionsDataContext.tsx +++ b/src/pages/inbox/report/ReportActionsDataContext.tsx @@ -4,9 +4,8 @@ import {isUnread} from '@libs/ReportUtils'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; /** - * Carries `contentData` (the pipeline outputs the list renders) from `ReportActionsSkeletonGuard` to - * `ReportActionsListContent`, so the list renders from the same derivations as the skeleton decision - * without re-subscribing. Ambient state (network, route, archived, concierge session) is read locally. + * Carries `contentData` from the guard to `ReportActionsListContent` so the list renders from the same + * derivations as the skeleton decision without re-subscribing. */ const ReportActionsDataContext = createContext(null); @@ -35,13 +34,13 @@ function computeReportActionsSkeletonState(data: ReportActionsGuardData) { isLoadingInitialReportActions, hasOnceLoadedReportActions, isLoadingApp, - reportActions, + reportActionsLength, oldestUnreadReportAction, - reportPreviewAction, - sortedVisibleReportActions, + isSingleExpenseReport, + isMissingReportActions, isConciergeHiddenHistory, isConciergeMainDM, - allReportActions, + hasCachedReportActions, showConciergeSidePanelWelcome, } = data; @@ -49,7 +48,7 @@ function computeReportActionsSkeletonState(data: ReportActionsGuardData) { // When opening an unread report, it is very likely that the message we will open to is not the latest, // which is the only one we will have in cache. - const isInitiallyLoadingReport = isReportUnread && !!isLoadingInitialReportActions && reportActions.length <= 1; + const isInitiallyLoadingReport = isReportUnread && !!isLoadingInitialReportActions && reportActionsLength <= 1; // Same for unread messages, we need to wait for the results from the OpenReport API call // if the oldest unread report action is not available yet. Only applies during the *first* load @@ -61,10 +60,8 @@ function computeReportActionsSkeletonState(data: ReportActionsGuardData) { const isReportLoading = isInitiallyLoadingReport || isUnreadMessagePageLoadingInitially; const isReportReady = isOffline || !isReportLoading; - const isSingleExpenseReport = reportPreviewAction?.childMoneyRequestCount === 1; const isMissingTransactionThreadReportID = !transactionThreadReport?.reportID; const isReportDataIncomplete = isSingleExpenseReport && isMissingTransactionThreadReportID; - const isMissingReportActions = sortedVisibleReportActions.length === 0; const shouldShowSkeletonForInitialLoad = !!isLoadingInitialReportActions && (isReportDataIncomplete || isMissingReportActions) && !isOffline; @@ -78,14 +75,14 @@ function computeReportActionsSkeletonState(data: ReportActionsGuardData) { // cached report actions persist in Onyx. For the main DM, render those cached // actions immediately (matching production) instead of flashing a skeleton on // every refresh; the side panel always opens fresh so it keeps gating on - // hasOnceLoadedReportActions only. allReportActions excludes the synthetic - // CREATED action that is always injected for Concierge, so it is empty only on - // a genuinely cold load with no cached history. - const shouldShowSkeletonForConciergePanel = isConciergeHiddenHistory && !hasOnceLoadedReportActions && !(isConciergeMainDM && allReportActions.length > 0) && !isOffline; + // hasOnceLoadedReportActions only. hasCachedReportActions is false only on a + // genuinely cold load with no cached history (it excludes the synthetic CREATED + // action that is always injected for Concierge). + const shouldShowSkeletonForConciergePanel = isConciergeHiddenHistory && !hasOnceLoadedReportActions && !(isConciergeMainDM && hasCachedReportActions) && !isOffline; const shouldShowInitialSkeleton = shouldShowSkeletonForConciergePanel || shouldShowSkeletonForInitialLoad || shouldShowSkeletonForAppLoad; - const hasDerivedValueTimingIssue = reportActions.length > 0 && isMissingReportActions; + const hasDerivedValueTimingIssue = reportActionsLength > 0 && isMissingReportActions; const shouldShowLoadingSkeleton = isLoadingOnyxValue(reportResult) || !report || !isReportReady || shouldShowInitialSkeleton; const shouldShowDerivedTimingSkeleton = (hasDerivedValueTimingIssue || (!isReportTransactionThread && isMissingReportActions)) && !showConciergeSidePanelWelcome; diff --git a/src/pages/inbox/report/ReportActionsList.tsx b/src/pages/inbox/report/ReportActionsList.tsx index ff8de041bf20..dc5918535030 100644 --- a/src/pages/inbox/report/ReportActionsList.tsx +++ b/src/pages/inbox/report/ReportActionsList.tsx @@ -9,6 +9,7 @@ import {renderScrollComponent as renderActionSheetAwareScrollView} from '@compon import InvertedFlashList from '@components/FlashList/InvertedFlashList'; import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; import useEnvironment from '@hooks/useEnvironment'; +import useLinkedMessageOfflineLoading from '@hooks/useLinkedMessageOfflineLoading'; import useLocalize from '@hooks/useLocalize'; import useMarkAsRead from '@hooks/useMarkAsRead'; import useNetwork from '@hooks/useNetwork'; @@ -130,6 +131,8 @@ function ReportActionsListContent({reportID, onLayout}: ReportActionsListProps) didLayout.current = false; }, [reportID]); + useLinkedMessageOfflineLoading({reportID: report?.reportID ?? reportID, reportActionIDFromRoute}); + // Remount the list when the deep-linked message or unread anchor changes (scroll positioning), or when the report changes. const listID = [reportID, reportActionIDFromRoute, hasOnceLoadedReportActions ? undefined : oldestUnreadReportAction?.reportActionID].join(':'); diff --git a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx index cf017d5bd6ac..63567bddc63f 100644 --- a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx +++ b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx @@ -1,11 +1,11 @@ import type {ReactNode} from 'react'; -import React, {useEffect, useLayoutEffect, useState} from 'react'; +import React, {useState} from 'react'; import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; import useCopySelectionHelper from '@hooks/useCopySelectionHelper'; import usePendingConciergeResponse from '@hooks/usePendingConciergeResponse'; import useReportActionsData from '@hooks/useReportActionsData'; -import {updateLoadingInitialReportAction} from '@libs/actions/Report'; -import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; +import useReportActionsSkeletonTelemetry from '@hooks/useReportActionsSkeletonTelemetry'; +import useStartConciergeSession from '@hooks/useStartConciergeSession'; import ReportActionsDataContext, {computeReportActionsSkeletonState} from './ReportActionsDataContext'; type ReportActionsSkeletonGuardProps = { @@ -17,21 +17,15 @@ type ReportActionsSkeletonGuardProps = { }; /** - * Skeleton gate for the report-actions list, modeled on `ReportNotFoundGuard`. + * Skeleton gate for the report-actions list, modeled on `ReportNotFoundGuard`. Owns the data pipeline + * (`useReportActionsData`) and the skeleton decision, returning either the skeleton or `children` (wrapped + * in `ReportActionsDataContext` so they render from the same pipeline). Skeleton-phase effects live in + * dedicated hooks here because `children` isn't mounted yet; the list's UI-close hooks live in `children`, + * so they can't run while the skeleton shows. * - * Owns the single data pipeline (`useReportActionsData`) and the fine-grained skeleton decision, plus - * every effect that must run while the skeleton shows (concierge session start, the linked-message - * offline loading effect, and the warm:false open-report telemetry). It returns either the skeleton or - * the `children` (wrapped in `ReportActionsDataContext` so they render from the same pipeline). - * - * Because the UI-close hooks live in `children`, gating here means they are never mounted while a - * skeleton shows, so they cannot run during it. - * - * A forward latch keeps the full skeleton from reappearing once content has rendered: a transient - * empty visible-actions set must not unmount the content mid-session (which would tear down its scroll - * position and subscriptions). Because the UI-close hooks are no longer gated, this also means that - * after first content they stay active through such transients (mark-as-read, live-tail subscription) - * instead of being suppressed. That is intentional: content is on screen, so it should behave as visible. + * The forward latch stops a transient empty visible-actions set from unmounting content mid-session (which + * would tear down its scroll position and subscriptions). After first content the UI-close hooks therefore + * stay active through such transients, which is intended: content is on screen, so treat it as visible. */ function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonGuardProps) { const {guardData, contentData} = useReportActionsData(reportID); @@ -44,46 +38,22 @@ function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonG setHasShownContent(true); } + const {report, isConciergeMainDM, oldestUnreadReportAction, hasOnceLoadedReportActions, hasCachedReportActions} = guardData; + // Side effects that must run whenever the chat list is shown, including while the skeleton renders. useCopySelectionHelper(); usePendingConciergeResponse(reportID); - const {report, isOffline, reportActionIDFromRoute, isConciergeMainDM, canStartConciergeSession, startSession, oldestUnreadReportAction, currentReportID} = guardData; - - useEffect(() => { - // When we linked to message - we do not need to wait for initial actions - they already exists - if (!reportActionIDFromRoute || !isOffline) { - return; - } - updateLoadingInitialReportAction(report?.reportID ?? reportID); - }, [isOffline, report?.reportID, reportID, reportActionIDFromRoute]); - - useLayoutEffect(() => { - if (!isConciergeMainDM || !canStartConciergeSession) { - return; - } - startSession(oldestUnreadReportAction ? report?.lastReadTime : undefined); - // eslint-disable-next-line react-hooks/exhaustive-deps -- startSession is stable; captured values at mount only - }, [isConciergeMainDM, startSession, canStartConciergeSession]); - - // On native the component stays mounted in the navigation stack, so the - // effect above never re-fires (its isConciergeMainDM dep is always true). - // Re-trigger startSession when the globally-focused report matches this - // report so the session age check runs after navigating away and back. - useLayoutEffect(() => { - if (!isConciergeMainDM || !canStartConciergeSession || currentReportID !== reportID) { - return; - } - startSession(oldestUnreadReportAction ? report?.lastReadTime : undefined); - // eslint-disable-next-line react-hooks/exhaustive-deps -- only react to currentReportID returning to this report - }, [currentReportID, reportID, isConciergeMainDM, canStartConciergeSession, startSession]); + useStartConciergeSession({ + reportID, + lastReadTime: report?.lastReadTime, + isConciergeMainDM, + oldestUnreadReportAction, + hasOnceLoadedReportActions, + hasCachedReportActions, + }); - useEffect(() => { - if (!shouldShowInitialSkeleton || !report) { - return; - } - markOpenReportEnd(report, {warm: false}); - }, [report, shouldShowInitialSkeleton]); + useReportActionsSkeletonTelemetry({report, shouldShowInitialSkeleton}); if (!hasShownContent && shouldShowLoadingSkeleton) { return ; From 5f2f3103c21f9a011f9c57dba6781dc8006f2d48 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Thu, 25 Jun 2026 09:53:37 +0200 Subject: [PATCH 15/22] Rename, split context --- ...nsData.ts => useReportActionsListModel.ts} | 39 +++++++++++-------- .../useReportActionsSkeletonTelemetry.ts | 4 +- src/hooks/useStartConciergeSession.ts | 4 +- src/pages/inbox/report/ReportActionsList.tsx | 15 +++---- ...ntext.tsx => ReportActionsListContext.tsx} | 39 +++++++++++++------ .../report/ReportActionsSkeletonGuard.tsx | 24 +++++++----- 6 files changed, 74 insertions(+), 51 deletions(-) rename src/hooks/{useReportActionsData.ts => useReportActionsListModel.ts} (80%) rename src/pages/inbox/report/{ReportActionsDataContext.tsx => ReportActionsListContext.tsx} (70%) diff --git a/src/hooks/useReportActionsData.ts b/src/hooks/useReportActionsListModel.ts similarity index 80% rename from src/hooks/useReportActionsData.ts rename to src/hooks/useReportActionsListModel.ts index 7d23dabf2bef..b248f4141bb2 100644 --- a/src/hooks/useReportActionsData.ts +++ b/src/hooks/useReportActionsListModel.ts @@ -16,10 +16,10 @@ import useReportIsArchived from './useReportIsArchived'; /** * Single read/derive pipeline for the report-actions list: the subscriptions and derivations the skeleton * decision and the list render both need, computed once. Side-effect-free (no writes/navigation/telemetry/ - * session-start). The guard calls it once and passes `contentData` via `ReportActionsDataContext` so the - * content doesn't re-subscribe. + * session-start). The guard calls it once and passes `state`/`actions` via `ReportActionsListStateContext` + * and `ReportActionsListActionsContext` so the content doesn't re-subscribe. */ -function useReportActionsData(reportID: string) { +function useReportActionsListModel(reportID: string) { const {isOffline} = useNetworkWithOfflineStatus(); const route = useRoute>(); const reportActionIDFromRoute = route?.params?.reportActionID; @@ -98,9 +98,9 @@ function useReportActionsData(reportID: string) { // false only on a genuinely cold load with no cached history. const hasCachedReportActions = allReportActions.length > 0; - // Guard-only inputs to the skeleton decision (some also read by the guard's effect hooks). Off the - // context so its churn (loading, app-load, concierge-session, navigation) never re-renders the list. - const guardData = { + // Readiness signals for the skeleton decision (some also read by the guard's effect hooks). Off the + // context so their churn (loading, app-load, concierge-session, navigation) never re-renders the list. + const readinessSignals = { report, reportResult, isOffline, @@ -121,9 +121,10 @@ function useReportActionsData(reportID: string) { showConciergeSidePanelWelcome, }; - // The only slice on the context, so it alone drives list re-renders. Ambient state (network, route, - // archived, concierge session) is read locally in the content instead of carried here. - const contentData = { + // The render state slice on `ReportActionsListStateContext`; this is what drives list re-renders. + // Ambient state (network, route, archived, concierge session) is read locally in the content instead + // of carried here. + const state = { report, hasOnceLoadedReportActions, hasNewerActions, @@ -132,24 +133,30 @@ function useReportActionsData(reportID: string) { transactionThreadReport, parentReportActionForTransactionThread, treatAsNoPaginationAnchor, - setTreatAsNoPaginationAnchor, parentReportAction, sortedReportActions, sortedVisibleReportActions, isConciergeHiddenHistory, showFullHistory, hasPreviousMessages, + }; + + // The command handles on `ReportActionsListActionsContext`. Referentially stable, so actions-only + // consumers don't re-render when the state slice churns. + const actions = { + setTreatAsNoPaginationAnchor, handleShowPreviousMessages, loadOlderChats, loadNewerChats, }; - return {guardData, contentData}; + return {readinessSignals, state, actions}; } -type ReportActionsData = ReturnType; -type ReportActionsGuardData = ReportActionsData['guardData']; -type ReportActionsContentData = ReportActionsData['contentData']; +type ReportActionsListModel = ReturnType; +type ReportActionsReadinessSignals = ReportActionsListModel['readinessSignals']; +type ReportActionsListState = ReportActionsListModel['state']; +type ReportActionsListActions = ReportActionsListModel['actions']; -export default useReportActionsData; -export type {ReportActionsGuardData, ReportActionsContentData}; +export default useReportActionsListModel; +export type {ReportActionsReadinessSignals, ReportActionsListState, ReportActionsListActions}; diff --git a/src/hooks/useReportActionsSkeletonTelemetry.ts b/src/hooks/useReportActionsSkeletonTelemetry.ts index b6ec8132a7bd..b19c8b50b3fa 100644 --- a/src/hooks/useReportActionsSkeletonTelemetry.ts +++ b/src/hooks/useReportActionsSkeletonTelemetry.ts @@ -1,8 +1,8 @@ import {useEffect} from 'react'; import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; -import type {ReportActionsGuardData} from './useReportActionsData'; +import type {ReportActionsReadinessSignals} from './useReportActionsListModel'; -type UseReportActionsSkeletonTelemetryParams = Pick & { +type UseReportActionsSkeletonTelemetryParams = Pick & { /** Whether the initial-load skeleton is showing */ shouldShowInitialSkeleton: boolean; }; diff --git a/src/hooks/useStartConciergeSession.ts b/src/hooks/useStartConciergeSession.ts index c1e954bd36c8..5861f5e863b6 100644 --- a/src/hooks/useStartConciergeSession.ts +++ b/src/hooks/useStartConciergeSession.ts @@ -1,9 +1,9 @@ import {useLayoutEffect} from 'react'; import {useConciergeSessionActions} from '@pages/inbox/ConciergeSessionContext'; import {useCurrentReportIDState} from './useCurrentReportID'; -import type {ReportActionsGuardData} from './useReportActionsData'; +import type {ReportActionsReadinessSignals} from './useReportActionsListModel'; -type UseStartConciergeSessionParams = Pick & { +type UseStartConciergeSessionParams = Pick & { /** The ID of the report to display actions for */ reportID: string; diff --git a/src/pages/inbox/report/ReportActionsList.tsx b/src/pages/inbox/report/ReportActionsList.tsx index dc5918535030..aecaac31f88f 100644 --- a/src/pages/inbox/report/ReportActionsList.tsx +++ b/src/pages/inbox/report/ReportActionsList.tsx @@ -57,7 +57,7 @@ import {getStableReportSelector} from '@src/selectors/Report'; import type * as OnyxTypes from '@src/types/onyx'; import FloatingMessageCounter from './FloatingMessageCounter'; import ReportActionIndexContext from './ReportActionIndexContext'; -import {useReportActionsDataContext} from './ReportActionsDataContext'; +import {useReportActionsListActions, useReportActionsListState} from './ReportActionsListContext'; import ReportActionsListHeader from './ReportActionsListHeader'; import ReportActionsListItemRenderer from './ReportActionsListItemRenderer'; import ReportActionsListPaddingView from './ReportActionsListPaddingView'; @@ -87,7 +87,7 @@ function keyExtractor(item: OnyxTypes.ReportAction): string { } /** - * Renders the report-actions list. Reads its data from `ReportActionsDataContext` and holds the + * Renders the report-actions list. Reads its data from `ReportActionsListStateContext` / `ReportActionsListActionsContext` and holds the * UI-close hooks (`useUnreadMarker` / `useMarkAsRead` / `useReportActionsScroll`). `ReportActionsSkeletonGuard` * mounts it only once content is ready, so those hooks never run while a skeleton shows. */ @@ -98,8 +98,6 @@ function ReportActionsListContent({reportID, onLayout}: ReportActionsListProps) const {shouldUseNarrowLayout} = useResponsiveLayout(); const {isProduction} = useEnvironment(); - const data = useReportActionsDataContext(); - const { report, hasOnceLoadedReportActions, @@ -109,17 +107,16 @@ function ReportActionsListContent({reportID, onLayout}: ReportActionsListProps) transactionThreadReport, parentReportActionForTransactionThread, treatAsNoPaginationAnchor, - setTreatAsNoPaginationAnchor, parentReportAction, - loadOlderChats, - loadNewerChats, sortedReportActions, sortedVisibleReportActions, isConciergeHiddenHistory, showFullHistory, hasPreviousMessages, - handleShowPreviousMessages, - } = data; + } = useReportActionsListState(); + + const {setTreatAsNoPaginationAnchor, loadOlderChats, loadNewerChats, handleShowPreviousMessages} = useReportActionsListActions(); + const {isOffline} = useNetwork(); const route = useRoute>(); const reportActionIDFromRoute = route?.params?.reportActionID; diff --git a/src/pages/inbox/report/ReportActionsDataContext.tsx b/src/pages/inbox/report/ReportActionsListContext.tsx similarity index 70% rename from src/pages/inbox/report/ReportActionsDataContext.tsx rename to src/pages/inbox/report/ReportActionsListContext.tsx index 4183cbb53659..de8b4828b691 100644 --- a/src/pages/inbox/report/ReportActionsDataContext.tsx +++ b/src/pages/inbox/report/ReportActionsListContext.tsx @@ -1,28 +1,44 @@ import {createContext, useContext} from 'react'; -import type {ReportActionsContentData, ReportActionsGuardData} from '@hooks/useReportActionsData'; +import type {ReportActionsListActions, ReportActionsListState, ReportActionsReadinessSignals} from '@hooks/useReportActionsListModel'; import {isUnread} from '@libs/ReportUtils'; import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; /** - * Carries `contentData` from the guard to `ReportActionsListContent` so the list renders from the same + * Carries the render `state` slice from the guard to `ReportActionsList` so the list renders from the same * derivations as the skeleton decision without re-subscribing. */ -const ReportActionsDataContext = createContext(null); +const ReportActionsListStateContext = createContext(null); -/** Read the report-actions pipeline outputs. Throws if used outside the guard's provider. */ -function useReportActionsDataContext(): ReportActionsContentData { - const value = useContext(ReportActionsDataContext); +/** + * Carries the command handles (load older/newer, show previous messages). Kept on a separate context from + * the state slice because the handles are referentially stable, so actions-only consumers don't re-render + * when the state slice churns. + */ +const ReportActionsListActionsContext = createContext(null); + +/** Read the report-actions render state. Throws if used outside the guard's provider. */ +function useReportActionsListState(): ReportActionsListState { + const value = useContext(ReportActionsListStateContext); + if (value === null) { + throw new Error('useReportActionsListState must be used within a ReportActionsListStateContext.Provider'); + } + return value; +} + +/** Read the report-actions command handles. Throws if used outside the guard's provider. */ +function useReportActionsListActions(): ReportActionsListActions { + const value = useContext(ReportActionsListActionsContext); if (value === null) { - throw new Error('useReportActionsDataContext must be used within a ReportActionsDataContext.Provider'); + throw new Error('useReportActionsListActions must be used within a ReportActionsListActionsContext.Provider'); } return value; } /** - * Pure derivation of the two skeleton states from the pipeline bundle: a loading skeleton and the + * Pure derivation of the two skeleton states from the readiness signals: a loading skeleton and the * derived-value-timing skeleton. The guard uses these to decide whether to render the list. */ -function computeReportActionsSkeletonState(data: ReportActionsGuardData) { +function computeReportActionsSkeletonState(readinessSignals: ReportActionsReadinessSignals) { const { report, reportResult, @@ -42,7 +58,7 @@ function computeReportActionsSkeletonState(data: ReportActionsGuardData) { isConciergeMainDM, hasCachedReportActions, showConciergeSidePanelWelcome, - } = data; + } = readinessSignals; const isReportUnread = isUnread(report, transactionThreadReport, isReportArchived); @@ -94,5 +110,4 @@ function computeReportActionsSkeletonState(data: ReportActionsGuardData) { }; } -export default ReportActionsDataContext; -export {useReportActionsDataContext, computeReportActionsSkeletonState}; +export {ReportActionsListStateContext, ReportActionsListActionsContext, useReportActionsListState, useReportActionsListActions, computeReportActionsSkeletonState}; diff --git a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx index 63567bddc63f..f67c70f8c3b4 100644 --- a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx +++ b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx @@ -3,10 +3,10 @@ import React, {useState} from 'react'; import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; import useCopySelectionHelper from '@hooks/useCopySelectionHelper'; import usePendingConciergeResponse from '@hooks/usePendingConciergeResponse'; -import useReportActionsData from '@hooks/useReportActionsData'; +import useReportActionsListModel from '@hooks/useReportActionsListModel'; import useReportActionsSkeletonTelemetry from '@hooks/useReportActionsSkeletonTelemetry'; import useStartConciergeSession from '@hooks/useStartConciergeSession'; -import ReportActionsDataContext, {computeReportActionsSkeletonState} from './ReportActionsDataContext'; +import {computeReportActionsSkeletonState, ReportActionsListActionsContext, ReportActionsListStateContext} from './ReportActionsListContext'; type ReportActionsSkeletonGuardProps = { /** The ID of the report to display actions for */ @@ -18,18 +18,18 @@ type ReportActionsSkeletonGuardProps = { /** * Skeleton gate for the report-actions list, modeled on `ReportNotFoundGuard`. Owns the data pipeline - * (`useReportActionsData`) and the skeleton decision, returning either the skeleton or `children` (wrapped - * in `ReportActionsDataContext` so they render from the same pipeline). Skeleton-phase effects live in - * dedicated hooks here because `children` isn't mounted yet; the list's UI-close hooks live in `children`, - * so they can't run while the skeleton shows. + * (`useReportActionsListModel`) and the skeleton decision, returning either the skeleton or `children` + * (wrapped in `ReportActionsListStateContext`/`ReportActionsListActionsContext` so they render from the same + * pipeline). Skeleton-phase effects live in dedicated hooks here because `children` isn't mounted yet; the + * list's UI-close hooks live in `children`, so they can't run while the skeleton shows. * * The forward latch stops a transient empty visible-actions set from unmounting content mid-session (which * would tear down its scroll position and subscriptions). After first content the UI-close hooks therefore * stay active through such transients, which is intended: content is on screen, so treat it as visible. */ function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonGuardProps) { - const {guardData, contentData} = useReportActionsData(reportID); - const {shouldShowLoadingSkeleton, shouldShowDerivedTimingSkeleton, shouldShowInitialSkeleton} = computeReportActionsSkeletonState(guardData); + const {readinessSignals, state, actions} = useReportActionsListModel(reportID); + const {shouldShowLoadingSkeleton, shouldShowDerivedTimingSkeleton, shouldShowInitialSkeleton} = computeReportActionsSkeletonState(readinessSignals); const shouldShowSkeleton = shouldShowLoadingSkeleton || shouldShowDerivedTimingSkeleton; // Forward latch: once content has shown, never return the full skeleton again for this mount. @@ -38,7 +38,7 @@ function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonG setHasShownContent(true); } - const {report, isConciergeMainDM, oldestUnreadReportAction, hasOnceLoadedReportActions, hasCachedReportActions} = guardData; + const {report, isConciergeMainDM, oldestUnreadReportAction, hasOnceLoadedReportActions, hasCachedReportActions} = readinessSignals; // Side effects that must run whenever the chat list is shown, including while the skeleton renders. useCopySelectionHelper(); @@ -63,7 +63,11 @@ function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonG return ; } - return {children}; + return ( + + {children} + + ); } export default ReportActionsSkeletonGuard; From f3ed3653b36e999c1f1ab292cfd69297cea5fcf1 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Thu, 25 Jun 2026 10:01:57 +0200 Subject: [PATCH 16/22] resolve conflicts --- src/hooks/useStartConciergeSession.ts | 20 +++++++++---------- .../report/ReportActionsSkeletonGuard.tsx | 1 - 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/src/hooks/useStartConciergeSession.ts b/src/hooks/useStartConciergeSession.ts index 5861f5e863b6..f08c11812601 100644 --- a/src/hooks/useStartConciergeSession.ts +++ b/src/hooks/useStartConciergeSession.ts @@ -7,9 +7,6 @@ type UseStartConciergeSessionParams = Pick Date: Thu, 25 Jun 2026 10:13:07 +0200 Subject: [PATCH 17/22] add useMarkOpenReportEndOnSkeleton --- .../MoneyRequestReportActionsList.tsx | 8 ++----- .../MoneyRequestReportView.tsx | 9 ++------ src/hooks/useMarkOpenReportEndOnSkeleton.ts | 21 +++++++++++++++++ .../useReportActionsSkeletonTelemetry.ts | 23 ------------------- src/pages/inbox/ReportActions.tsx | 16 ++++--------- .../report/ReportActionsSkeletonGuard.tsx | 4 ++-- 6 files changed, 32 insertions(+), 49 deletions(-) create mode 100644 src/hooks/useMarkOpenReportEndOnSkeleton.ts delete mode 100644 src/hooks/useReportActionsSkeletonTelemetry.ts diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx index 3cc3062dac33..4105ad51d902 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportActionsList.tsx @@ -11,6 +11,7 @@ import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails' import useIsReportActionsLoaded from '@hooks/useIsReportActionsLoaded'; import useLoadReportActions from '@hooks/useLoadReportActions'; import useLocalize from '@hooks/useLocalize'; +import useMarkOpenReportEndOnSkeleton from '@hooks/useMarkOpenReportEndOnSkeleton'; import useNetworkWithOfflineStatus from '@hooks/useNetworkWithOfflineStatus'; import useNewTransactions from '@hooks/useNewTransactions'; import useOnyx from '@hooks/useOnyx'; @@ -191,12 +192,7 @@ function MoneyRequestReportActionsList({onLayout}: MoneyRequestReportListProps) isOffline, showReportActionsLoadingState: !!showReportActionsLoadingState, }; - useEffect(() => { - if (!shouldShowOpenReportLoadingSkeleton || !report) { - return; - } - markOpenReportEnd(report, {warm: false}); - }, [report, shouldShowOpenReportLoadingSkeleton]); + useMarkOpenReportEndOnSkeleton(report, shouldShowOpenReportLoadingSkeleton); const lastAction = visibleReportActions.at(-1); diff --git a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx index 6934aac0ea1e..762e19b746eb 100644 --- a/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx +++ b/src/components/MoneyRequestReportView/MoneyRequestReportView.tsx @@ -13,6 +13,7 @@ import OfflineWithFeedback from '@components/OfflineWithFeedback'; import MoneyRequestReceiptView from '@components/ReportActionItem/MoneyRequestReceiptView'; import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; import ReportHeaderSkeletonView from '@components/ReportHeaderSkeletonView'; +import useMarkOpenReportEndOnSkeleton from '@hooks/useMarkOpenReportEndOnSkeleton'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import usePaginatedReportActions from '@hooks/usePaginatedReportActions'; @@ -28,7 +29,6 @@ import {getFilteredReportActionsForReportView, getOneTransactionThreadReportID} import {getReportOfflinePendingActionAndErrors, isReportTransactionThread} from '@libs/ReportUtils'; import {buildCannedSearchQuery} from '@libs/SearchQueryUtils'; import {cancelSpan} from '@libs/telemetry/activeSpans'; -import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; import type {SkeletonSpanReasonAttributes} from '@libs/telemetry/useSkeletonSpan'; import Navigation from '@navigation/Navigation'; import ReportActionsList from '@pages/inbox/report/ReportActionsList'; @@ -201,12 +201,7 @@ function MoneyRequestReportView({report, reportLoadingState, shouldDisplayReport }; }, [reportID]); - useEffect(() => { - if (!shouldShowOpenReportLoadingSkeleton || !report) { - return; - } - markOpenReportEnd(report, {warm: false}); - }, [report, shouldShowOpenReportLoadingSkeleton]); + useMarkOpenReportEndOnSkeleton(report, shouldShowOpenReportLoadingSkeleton); if (shouldShowOpenReportLoadingSkeleton) { const skeletonReasonAttributes: SkeletonSpanReasonAttributes = { diff --git a/src/hooks/useMarkOpenReportEndOnSkeleton.ts b/src/hooks/useMarkOpenReportEndOnSkeleton.ts new file mode 100644 index 000000000000..35f74cfecf9c --- /dev/null +++ b/src/hooks/useMarkOpenReportEndOnSkeleton.ts @@ -0,0 +1,21 @@ +import {useEffect} from 'react'; +import type {OnyxEntry} from 'react-native-onyx'; +import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; +import type * as OnyxTypes from '@src/types/onyx'; + +/** + * Closes the open-report performance span as a cold open (`warm: false`) the moment a cold-load skeleton + * appears. Shared by every report surface that gates its own skeleton (the chat-list guard, the route + * orchestrator, and the money-request views): the open-report span must still close even though the list + * body — which would otherwise own this mark once mounted — isn't mounted while the skeleton shows. + */ +function useMarkOpenReportEndOnSkeleton(report: OnyxEntry, isSkeletonVisible: boolean) { + useEffect(() => { + if (!isSkeletonVisible || !report) { + return; + } + markOpenReportEnd(report, {warm: false}); + }, [report, isSkeletonVisible]); +} + +export default useMarkOpenReportEndOnSkeleton; diff --git a/src/hooks/useReportActionsSkeletonTelemetry.ts b/src/hooks/useReportActionsSkeletonTelemetry.ts deleted file mode 100644 index b19c8b50b3fa..000000000000 --- a/src/hooks/useReportActionsSkeletonTelemetry.ts +++ /dev/null @@ -1,23 +0,0 @@ -import {useEffect} from 'react'; -import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; -import type {ReportActionsReadinessSignals} from './useReportActionsListModel'; - -type UseReportActionsSkeletonTelemetryParams = Pick & { - /** Whether the initial-load skeleton is showing */ - shouldShowInitialSkeleton: boolean; -}; - -/** - * Records the warm:false open-report end. Lives in the guard, not the content, because it must fire while - * the skeleton shows, when the content isn't mounted. - */ -function useReportActionsSkeletonTelemetry({report, shouldShowInitialSkeleton}: UseReportActionsSkeletonTelemetryParams) { - useEffect(() => { - if (!shouldShowInitialSkeleton || !report) { - return; - } - markOpenReportEnd(report, {warm: false}); - }, [report, shouldShowInitialSkeleton]); -} - -export default useReportActionsSkeletonTelemetry; diff --git a/src/pages/inbox/ReportActions.tsx b/src/pages/inbox/ReportActions.tsx index 6a271d75ae2b..b6f3d24a1767 100644 --- a/src/pages/inbox/ReportActions.tsx +++ b/src/pages/inbox/ReportActions.tsx @@ -1,7 +1,8 @@ import {useRoute} from '@react-navigation/native'; -import React, {useEffect} from 'react'; +import React from 'react'; import MoneyRequestReportActionsList from '@components/MoneyRequestReportView/MoneyRequestReportActionsList'; import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; +import useMarkOpenReportEndOnSkeleton from '@hooks/useMarkOpenReportEndOnSkeleton'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import usePaginatedReportActions from '@hooks/usePaginatedReportActions'; @@ -9,7 +10,6 @@ import useReportTransactionsCollection from '@hooks/useReportTransactionsCollect import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {getAllNonDeletedTransactions, shouldDisplayReportTableView, shouldWaitForTransactions as shouldWaitForTransactionsUtil} from '@libs/MoneyRequestReportUtils'; import {isInvoiceReport, isMoneyRequestReport} from '@libs/ReportUtils'; -import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; import ONYXKEYS from '@src/ONYXKEYS'; import ReportActionsList from './report/ReportActionsList'; import UserTypingEventListener from './report/UserTypingEventListener'; @@ -51,17 +51,11 @@ function ReportActions() { // The app-load skeleton is hoisted out of the body so the body's data hooks/effects never run // during app boot. It only applies on the chat path (after the skeleton and money-request // branches below) — matching the previous behavior, where this skeleton lived inside the - // chat-only ReportActionsView. Because the body won't mount for this branch, its own - // markOpenReportEnd(report, {warm:false}) effect can't close the open-report span, so we own - // that telemetry mark here for the branch we gate. + // chat-only ReportActionsView. Because the body won't mount for this branch, it can't close the + // open-report span itself, so we close it here for the branch we gate. const shouldShowAppLoadSkeleton = !!isLoadingApp && !isOffline && !!report && !shouldWaitForTransactions && !shouldDisplayMoneyRequestActionsList; - useEffect(() => { - if (!shouldShowAppLoadSkeleton || !report) { - return; - } - markOpenReportEnd(report, {warm: false}); - }, [report, shouldShowAppLoadSkeleton]); + useMarkOpenReportEndOnSkeleton(report, shouldShowAppLoadSkeleton); if (!report || shouldWaitForTransactions) { return ; diff --git a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx index 7d6e1dacb341..719e558bb81d 100644 --- a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx +++ b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx @@ -2,9 +2,9 @@ import type {ReactNode} from 'react'; import React, {useState} from 'react'; import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; import useCopySelectionHelper from '@hooks/useCopySelectionHelper'; +import useMarkOpenReportEndOnSkeleton from '@hooks/useMarkOpenReportEndOnSkeleton'; import usePendingConciergeResponse from '@hooks/usePendingConciergeResponse'; import useReportActionsListModel from '@hooks/useReportActionsListModel'; -import useReportActionsSkeletonTelemetry from '@hooks/useReportActionsSkeletonTelemetry'; import useStartConciergeSession from '@hooks/useStartConciergeSession'; import {computeReportActionsSkeletonState, ReportActionsListActionsContext, ReportActionsListStateContext} from './ReportActionsListContext'; @@ -52,7 +52,7 @@ function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonG hasCachedReportActions, }); - useReportActionsSkeletonTelemetry({report, shouldShowInitialSkeleton}); + useMarkOpenReportEndOnSkeleton(report, shouldShowInitialSkeleton); if (!hasShownContent && shouldShowLoadingSkeleton) { return ; From c95f9994b19bd32380274933104d2d64b094236d Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Thu, 25 Jun 2026 11:08:20 +0200 Subject: [PATCH 18/22] fix loading edge case window --- src/pages/inbox/report/ReportActionsSkeletonGuard.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx index 719e558bb81d..62bd78756ded 100644 --- a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx +++ b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx @@ -52,7 +52,7 @@ function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonG hasCachedReportActions, }); - useMarkOpenReportEndOnSkeleton(report, shouldShowInitialSkeleton); + useMarkOpenReportEndOnSkeleton(report, !hasShownContent && shouldShowInitialSkeleton); if (!hasShownContent && shouldShowLoadingSkeleton) { return ; From 2c4a6ea5e7a81435b6ffd4fef7419bf932dcb068 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Thu, 25 Jun 2026 12:34:52 +0200 Subject: [PATCH 19/22] Make visibleReportActionsData stable --- src/hooks/useReportActionsVisibility.ts | 4 +--- src/selectors/ReportAction.ts | 7 +++++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/hooks/useReportActionsVisibility.ts b/src/hooks/useReportActionsVisibility.ts index 90b8dfeb9617..d1fa1076072e 100644 --- a/src/hooks/useReportActionsVisibility.ts +++ b/src/hooks/useReportActionsVisibility.ts @@ -5,7 +5,6 @@ import {isConciergeChatReport} from '@libs/ReportUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {ReportAction} from '@src/types/onyx'; -import type {VisibleReportActionsDerivedValue} from '@src/types/onyx/DerivedValues'; import useConciergeSidePanelReportActions from './useConciergeSidePanelReportActions'; import useCurrentUserPersonalDetails from './useCurrentUserPersonalDetails'; import useIsInSidePanel from './useIsInSidePanel'; @@ -60,10 +59,9 @@ function useReportActionsVisibility({ const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID); - const [reportVisibleActions] = useOnyx(ONYXKEYS.DERIVED.VISIBLE_REPORT_ACTIONS, { + const [visibleReportActionsData] = useOnyx(ONYXKEYS.DERIVED.VISIBLE_REPORT_ACTIONS, { selector: reportVisibleActionsSelector(reportID), }); - const visibleReportActionsData: VisibleReportActionsDerivedValue | undefined = reportID && reportVisibleActions ? {[reportID]: reportVisibleActions} : undefined; const isInSidePanel = useIsInSidePanel(); const isConciergeSidePanel = isInSidePanel && isConciergeChatReport(report, conciergeReportID); diff --git a/src/selectors/ReportAction.ts b/src/selectors/ReportAction.ts index 2f89fb50fbcf..8a69f7270b8e 100644 --- a/src/selectors/ReportAction.ts +++ b/src/selectors/ReportAction.ts @@ -6,9 +6,12 @@ import type {ReportAction, ReportActions} from '@src/types/onyx'; import type {VisibleReportActionsDerivedValue} from '@src/types/onyx/DerivedValues'; /** - * Module-level selector factory that scopes the VISIBLE_REPORT_ACTIONS derived value to a single report + * Scopes VISIBLE_REPORT_ACTIONS to one report, pre-wrapped in the `{[reportID]: slice}` shape + * `isReportActionVisible` expects. Built here (not inline in the hook) so the consumer has no computed-key + * literal, which the React Compiler won't memoize; `useOnyx` returns a stable ref while the slice is unchanged. */ -const reportVisibleActionsSelector = (reportID: string | undefined) => (data: VisibleReportActionsDerivedValue | undefined) => (reportID ? data?.[reportID] : undefined); +const reportVisibleActionsSelector = (reportID: string | undefined) => (data: VisibleReportActionsDerivedValue | undefined) => + reportID && data?.[reportID] ? {[reportID]: data[reportID]} : undefined; function getParentReportActionSelector(parentReportActions: OnyxEntry, parentReportActionID?: string): OnyxEntry { if (!parentReportActions || !parentReportActionID) { From ce3e927a32ca2d7d31bff6cfed57a5f33545e341 Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Thu, 25 Jun 2026 13:26:59 +0200 Subject: [PATCH 20/22] remove latch --- .../report/ReportActionsSkeletonGuard.tsx | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx index 62bd78756ded..a7fbc3d66099 100644 --- a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx +++ b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx @@ -1,5 +1,5 @@ import type {ReactNode} from 'react'; -import React, {useState} from 'react'; +import React from 'react'; import ReportActionsSkeletonView from '@components/ReportActionsSkeletonView'; import useCopySelectionHelper from '@hooks/useCopySelectionHelper'; import useMarkOpenReportEndOnSkeleton from '@hooks/useMarkOpenReportEndOnSkeleton'; @@ -23,20 +23,10 @@ type ReportActionsSkeletonGuardProps = { * pipeline). Skeleton-phase effects live in dedicated hooks here because `children` isn't mounted yet; the * list's UI-close hooks live in `children`, so they can't run while the skeleton shows. * - * The forward latch stops a transient empty visible-actions set from unmounting content mid-session (which - * would tear down its scroll position and subscriptions). After first content the UI-close hooks therefore - * stay active through such transients, which is intended: content is on screen, so treat it as visible. */ function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonGuardProps) { const {readinessSignals, state, actions} = useReportActionsListModel(reportID); const {shouldShowLoadingSkeleton, shouldShowDerivedTimingSkeleton, shouldShowInitialSkeleton} = computeReportActionsSkeletonState(readinessSignals); - const shouldShowSkeleton = shouldShowLoadingSkeleton || shouldShowDerivedTimingSkeleton; - - // Forward latch: once content has shown, never return the full skeleton again for this mount. - const [hasShownContent, setHasShownContent] = useState(false); - if (!hasShownContent && !shouldShowSkeleton) { - setHasShownContent(true); - } const {report, isConciergeMainDM, oldestUnreadReportAction, hasOnceLoadedReportActions, hasCachedReportActions} = readinessSignals; @@ -52,13 +42,13 @@ function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonG hasCachedReportActions, }); - useMarkOpenReportEndOnSkeleton(report, !hasShownContent && shouldShowInitialSkeleton); + useMarkOpenReportEndOnSkeleton(report, shouldShowInitialSkeleton); - if (!hasShownContent && shouldShowLoadingSkeleton) { + if (shouldShowLoadingSkeleton) { return ; } - if (!hasShownContent && shouldShowDerivedTimingSkeleton) { + if (shouldShowDerivedTimingSkeleton) { return ; } From f97d91f3668f497babf35e42665c0fbce45dddfe Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Thu, 25 Jun 2026 13:56:49 +0200 Subject: [PATCH 21/22] move isConciergeMainDM logic up --- src/pages/inbox/ReportActions.tsx | 8 +- tests/ui/ReportActionsListTest.tsx | 121 ----------------------------- tests/ui/ReportActionsTest.tsx | 16 +++- 3 files changed, 21 insertions(+), 124 deletions(-) diff --git a/src/pages/inbox/ReportActions.tsx b/src/pages/inbox/ReportActions.tsx index b6f3d24a1767..6971e5ece48f 100644 --- a/src/pages/inbox/ReportActions.tsx +++ b/src/pages/inbox/ReportActions.tsx @@ -9,7 +9,7 @@ import usePaginatedReportActions from '@hooks/usePaginatedReportActions'; import useReportTransactionsCollection from '@hooks/useReportTransactionsCollection'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {getAllNonDeletedTransactions, shouldDisplayReportTableView, shouldWaitForTransactions as shouldWaitForTransactionsUtil} from '@libs/MoneyRequestReportUtils'; -import {isInvoiceReport, isMoneyRequestReport} from '@libs/ReportUtils'; +import {isConciergeChatReport, isInvoiceReport, isMoneyRequestReport} from '@libs/ReportUtils'; import ONYXKEYS from '@src/ONYXKEYS'; import ReportActionsList from './report/ReportActionsList'; import UserTypingEventListener from './report/UserTypingEventListener'; @@ -53,7 +53,11 @@ function ReportActions() { // branches below) — matching the previous behavior, where this skeleton lived inside the // chat-only ReportActionsView. Because the body won't mount for this branch, it can't close the // open-report span itself, so we close it here for the branch we gate. - const shouldShowAppLoadSkeleton = !!isLoadingApp && !isOffline && !!report && !shouldWaitForTransactions && !shouldDisplayMoneyRequestActionsList; + // + // Concierge is excluded so the body still mounts under the app-load skeleton, seeding sessionStartTime + // before content appeared. + const isConciergeMainDM = isConciergeChatReport(report); + const shouldShowAppLoadSkeleton = !!isLoadingApp && !isOffline && !!report && !shouldWaitForTransactions && !shouldDisplayMoneyRequestActionsList && !isConciergeMainDM; useMarkOpenReportEndOnSkeleton(report, shouldShowAppLoadSkeleton); diff --git a/tests/ui/ReportActionsListTest.tsx b/tests/ui/ReportActionsListTest.tsx index e68a941c8ce5..2196472da9e6 100644 --- a/tests/ui/ReportActionsListTest.tsx +++ b/tests/ui/ReportActionsListTest.tsx @@ -2,7 +2,6 @@ import type * as ReactNavigation from '@react-navigation/native'; import {render, screen} from '@testing-library/react-native'; import React from 'react'; -import {View} from 'react-native'; import Onyx from 'react-native-onyx'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useIsInSidePanel from '@hooks/useIsInSidePanel'; @@ -18,7 +17,6 @@ import DateUtils from '@libs/DateUtils'; import * as ReportActionsUtils from '@libs/ReportActionsUtils'; import {useConciergeSessionActions, useConciergeSessionState} from '@pages/inbox/ConciergeSessionContext'; import ReportActionsList from '@pages/inbox/report/ReportActionsList'; -import ReportActionsSkeletonGuard from '@pages/inbox/report/ReportActionsSkeletonGuard'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type * as OnyxTypes from '@src/types/onyx'; @@ -863,123 +861,4 @@ describe('ReportActionsList (body)', () => { expect(mockUseReportActionsScroll).not.toHaveBeenCalled(); }); }); - - describe('Skeleton guard latch', () => { - // We render the guard directly (not via the ReportActionsList wrapper) so rerender() actually - // re-runs it. The wrapper's JSX is React-Compiler-memoized, so re-rendering it with an unchanged - // reportID returns the same guard element and React bails before the guard re-evaluates. - // The stub child only proves the guard keeps returning its children; that the real content's hooks - // and scroll state survive the transient (not just that *something* renders) rests on manual QA. - const renderGuard = () => - render( - - - , - ); - - it('keeps the content mounted once shown even if a skeleton condition flips back true mid-session', () => { - mockUseNetwork.mockReturnValue({isOffline: false}); - // isLoadingApp drives the app-load skeleton; flip it true after content has rendered. - let isLoadingApp = false; - mockUseOnyx.mockImplementation((key: string) => { - if (key === ONYXKEYS.IS_LOADING_APP) { - return [isLoadingApp, {status: 'loaded'}]; - } - if (key.includes('reportLoadingState')) { - return [{isLoadingInitialReportActions: false, hasOnceLoadedReportActions: true}, {status: 'loaded'}]; - } - if (key.includes('reportActions')) { - return [[], {status: 'loaded'}]; - } - if (key === `${ONYXKEYS.COLLECTION.REPORT}${mockReport.reportID}`) { - return [mockReport, {status: 'loaded'}]; - } - return [undefined, {status: 'loaded'}]; - }); - mockUsePaginatedReportActions.mockReturnValue({ - ...defaultPaginatedReportActionsResult, - reportActions: mockReportActions, - }); - - // Control (non-vacuity): a fresh mount with isLoadingApp true DOES show the skeleton, proving the - // trigger below is skeleton-inducing. - isLoadingApp = true; - const control = renderGuard(); - expect(screen.getByTestId('ReportActionsSkeletonView')).toBeTruthy(); - expect(screen.queryByTestId('latch-content')).toBeNull(); - control.unmount(); - - // First render with isLoadingApp false: the guard renders the content. - isLoadingApp = false; - const {rerender} = renderGuard(); - expect(screen.getByTestId('latch-content')).toBeTruthy(); - expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); - - // isLoadingApp flips back true mid-session. Without the latch the guard would unmount the content - // and show the skeleton again; the latch must keep the content mounted. - isLoadingApp = true; - rerender( - - - , - ); - - expect(screen.getByTestId('latch-content')).toBeTruthy(); - expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); - }); - - it('keeps the content mounted when the derived-value-timing skeleton flips true mid-session', () => { - // This covers the derived-timing return specifically (the transient empty visible-actions set - // that originally motivated the latch), which the isLoadingApp case above does not exercise. - mockUseNetwork.mockReturnValue({isOffline: false}); - mockUseOnyx.mockImplementation((key: string) => { - if (key === ONYXKEYS.IS_LOADING_APP) { - return [false, {status: 'loaded'}]; - } - if (key.includes('reportLoadingState')) { - return [{isLoadingInitialReportActions: false, hasOnceLoadedReportActions: true}, {status: 'loaded'}]; - } - if (key.includes('reportActions')) { - return [[], {status: 'loaded'}]; - } - if (key === `${ONYXKEYS.COLLECTION.REPORT}${mockReport.reportID}`) { - return [mockReport, {status: 'loaded'}]; - } - return [undefined, {status: 'loaded'}]; - }); - - // Control (non-vacuity): empty visible actions on a fresh mount DOES show the derived-timing skeleton. - mockUsePaginatedReportActions.mockReturnValue({ - ...defaultPaginatedReportActionsResult, - reportActions: [], - }); - const control = renderGuard(); - expect(screen.getByTestId('ReportActionsSkeletonView')).toBeTruthy(); - expect(screen.queryByTestId('latch-content')).toBeNull(); - control.unmount(); - - // First render with actions present: the guard renders the content. - mockUsePaginatedReportActions.mockReturnValue({ - ...defaultPaginatedReportActionsResult, - reportActions: mockReportActions, - }); - const {rerender} = renderGuard(); - expect(screen.getByTestId('latch-content')).toBeTruthy(); - expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); - - // Visible actions transiently empty out (derived-timing skeleton condition). The latch must hold. - mockUsePaginatedReportActions.mockReturnValue({ - ...defaultPaginatedReportActionsResult, - reportActions: [], - }); - rerender( - - - , - ); - - expect(screen.getByTestId('latch-content')).toBeTruthy(); - expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); - }); - }); }); diff --git a/tests/ui/ReportActionsTest.tsx b/tests/ui/ReportActionsTest.tsx index 793c5d0c55d5..79ed870d9071 100644 --- a/tests/ui/ReportActionsTest.tsx +++ b/tests/ui/ReportActionsTest.tsx @@ -9,7 +9,7 @@ import useOnyx from '@hooks/useOnyx'; import usePaginatedReportActions from '@hooks/usePaginatedReportActions'; import useReportTransactionsCollection from '@hooks/useReportTransactionsCollection'; import {shouldDisplayReportTableView, shouldWaitForTransactions} from '@libs/MoneyRequestReportUtils'; -import {isInvoiceReport, isMoneyRequestReport} from '@libs/ReportUtils'; +import {isConciergeChatReport, isInvoiceReport, isMoneyRequestReport} from '@libs/ReportUtils'; import markOpenReportEnd from '@libs/telemetry/markOpenReportEnd'; import ReportActionsListBody from '@pages/inbox/report/ReportActionsList'; import UserTypingEventListener from '@pages/inbox/report/UserTypingEventListener'; @@ -43,6 +43,7 @@ jest.mock('@libs/MoneyRequestReportUtils', () => ({ jest.mock('@libs/ReportUtils', () => ({ isMoneyRequestReport: jest.fn(() => false), isInvoiceReport: jest.fn(() => false), + isConciergeChatReport: jest.fn(() => false), })); // The children are mocked so these tests assert only the orchestrator's branching decision, not the @@ -61,6 +62,7 @@ const mockShouldDisplayReportTableView = shouldDisplayReportTableView as jest.Mo const mockShouldWaitForTransactions = shouldWaitForTransactions as jest.MockedFunction; const mockIsMoneyRequestReport = isMoneyRequestReport as jest.MockedFunction; const mockIsInvoiceReport = isInvoiceReport as jest.MockedFunction; +const mockIsConciergeChatReport = isConciergeChatReport as jest.MockedFunction; const mockMoneyRequestList = MoneyRequestReportActionsList as jest.MockedFunction; const mockReportActionsListBody = ReportActionsListBody as jest.MockedFunction; const mockUserTypingEventListener = UserTypingEventListener as jest.MockedFunction; @@ -122,6 +124,7 @@ describe('ReportActions (orchestrator)', () => { mockShouldDisplayReportTableView.mockReturnValue(false); mockIsMoneyRequestReport.mockReturnValue(false); mockIsInvoiceReport.mockReturnValue(false); + mockIsConciergeChatReport.mockReturnValue(false); setupUseOnyx(); }); @@ -182,6 +185,17 @@ describe('ReportActions (orchestrator)', () => { expect(mockMarkOpenReportEnd).toHaveBeenCalledWith(mockReport, {warm: false}); }); + it('mounts the body (not the orchestrator app-load skeleton) for a Concierge report during app load', () => { + mockIsConciergeChatReport.mockReturnValue(true); + setupUseOnyx({isLoadingApp: true}); + + render(); + + expect(mockReportActionsListBody).toHaveBeenCalled(); + expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); + expect(mockMarkOpenReportEnd).not.toHaveBeenCalled(); + }); + it('does not show the app-load skeleton (or fire telemetry) while offline', () => { mockUseNetwork.mockReturnValue({isOffline: true}); setupUseOnyx({isLoadingApp: true}); From 36f14bf1a435fa545c69c5fb9da52ef81c15c81f Mon Sep 17 00:00:00 2001 From: Lukasz Modzelewski Date: Thu, 25 Jun 2026 14:43:22 +0200 Subject: [PATCH 22/22] remove old ref to ReportActionsView --- contributingGuides/OBSERVABILITY_METRICS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contributingGuides/OBSERVABILITY_METRICS.md b/contributingGuides/OBSERVABILITY_METRICS.md index 1fbbb4144a87..33269e4cb8e4 100644 --- a/contributingGuides/OBSERVABILITY_METRICS.md +++ b/contributingGuides/OBSERVABILITY_METRICS.md @@ -42,7 +42,7 @@ This document lists all implemented telemetry metrics in the Expensify App. - Technical: Report actions list rendered (onLayout event) - Report data loaded from Onyx (reportID, type, chatType) - Report actions list layout complete (we are waiting for the first page data render, so if there is any data in the Onyx, we'll not wait for the API) - - Called in [`src/pages/home/report/ReportActionsView.tsx`](https://github.com/Expensify/App/blob/8f123f449f1a4533830b18a1040c9a5f1949821d/src/pages/home/report/ReportActionsView.tsx#L272) and [`src/components/MoneyRequestReportActionsList.tsx`](https://github.com/Expensify/App/blob/8f123f449f1a4533830b18a1040c9a5f1949821d/src/components/MoneyRequestReportActionsList.tsx#L649) + - Called in the list body `src/pages/inbox/report/ReportActionsList.tsx` **Span ID**: `${CONST.TELEMETRY.SPAN_OPEN_REPORT}_${reportID}` **Attributes**: `is_transaction_thread`, `is_one_transaction_report`, `report_type`, `chat_type`