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` 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 3585be7ece9c..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,11 +29,11 @@ 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 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'; @@ -149,7 +150,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 @@ -200,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 = { @@ -275,10 +271,13 @@ function MoneyRequestReportView({report, reportLoadingState, shouldDisplayReport {shouldDisplayMoneyRequestActionsList ? ( ) : ( - + <> + + + )} {shouldDisplayReportFooter ? ( <> 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/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/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/useReportActionsListModel.ts b/src/hooks/useReportActionsListModel.ts new file mode 100644 index 000000000000..b248f4141bb2 --- /dev/null +++ b/src/hooks/useReportActionsListModel.ts @@ -0,0 +1,162 @@ +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 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'; + +/** + * 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 `state`/`actions` via `ReportActionsListStateContext` + * and `ReportActionsListActionsContext` so the content doesn't re-subscribe. + */ +function useReportActionsListModel(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 {sessionStartTime, showFullHistory: conciergeShowFullHistory, hadMessagesAtSessionStart: conciergeHadMessagesAtSessionStart} = useConciergeSessionState(); + const {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, + }); + + 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; + + // 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, + reportActionIDFromRoute, + transactionThreadReport, + isReportArchived, + isReportTransactionThread, + isLoadingInitialReportActions, + hasOnceLoadedReportActions, + isLoadingApp, + reportActionsLength: reportActions.length, + oldestUnreadReportAction, + isSingleExpenseReport, + isMissingReportActions, + isConciergeHiddenHistory, + isConciergeMainDM, + hasCachedReportActions, + showConciergeSidePanelWelcome, + }; + + // 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, + sortedAllReportActions, + oldestUnreadReportAction, + transactionThreadReport, + parentReportActionForTransactionThread, + treatAsNoPaginationAnchor, + 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 {readinessSignals, state, actions}; +} + +type ReportActionsListModel = ReturnType; +type ReportActionsReadinessSignals = ReportActionsListModel['readinessSignals']; +type ReportActionsListState = ReportActionsListModel['state']; +type ReportActionsListActions = ReportActionsListModel['actions']; + +export default useReportActionsListModel; +export type {ReportActionsReadinessSignals, ReportActionsListState, ReportActionsListActions}; 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/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/hooks/useStartConciergeSession.ts b/src/hooks/useStartConciergeSession.ts new file mode 100644 index 000000000000..f08c11812601 --- /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 {ReportActionsReadinessSignals} from './useReportActionsListModel'; + +type UseStartConciergeSessionParams = Pick & { + /** The ID of the report to display actions for */ + reportID: string; + + /** 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, 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; + } + // Anchor the session to the unread action's created time, a stable pre-read + // boundary, rather than the live report.lastReadTime which readNewestAction + // bumps to `now` when the report opens. Re-runs when oldestUnreadReportAction + // resolves so a session that locked to `now` before the anchor loaded is + // pulled back to keep the unread message visible. + startSession(oldestUnreadReportAction?.created); + }, [isConciergeMainDM, startSession, canStartConciergeSession, oldestUnreadReportAction?.created]); + + // 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?.created); + }, [currentReportID, reportID, isConciergeMainDM, canStartConciergeSession, startSession, oldestUnreadReportAction?.created]); +} + +export default useStartConciergeSession; diff --git a/src/libs/ReportActionsUtils.ts b/src/libs/ReportActionsUtils.ts index 41094f686eeb..749b4dbb7215 100644 --- a/src/libs/ReportActionsUtils.ts +++ b/src/libs/ReportActionsUtils.ts @@ -1598,7 +1598,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 d76d52390bf3..a41639f795d9 100644 --- a/src/libs/actions/Report/index.ts +++ b/src/libs/actions/Report/index.ts @@ -746,7 +746,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 */ @@ -757,7 +757,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; diff --git a/src/pages/inbox/ReportActionsList.tsx b/src/pages/inbox/ReportActions.tsx similarity index 53% rename from src/pages/inbox/ReportActionsList.tsx rename to src/pages/inbox/ReportActions.tsx index f94f73f20402..6971e5ece48f 100644 --- a/src/pages/inbox/ReportActionsList.tsx +++ b/src/pages/inbox/ReportActions.tsx @@ -2,15 +2,17 @@ import {useRoute} from '@react-navigation/native'; 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'; 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 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,19 @@ 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, it can't close the + // open-report span itself, so we close it here for the branch we gate. + // + // 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); + if (!report || shouldWaitForTransactions) { return ; } @@ -52,7 +69,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 0853a5699126..2f8b831522b8 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/src/pages/inbox/report/ReportActionsList.tsx b/src/pages/inbox/report/ReportActionsList.tsx index 1b0a90e97ea1..c709aeec7560 100644 --- a/src/pages/inbox/report/ReportActionsList.tsx +++ b/src/pages/inbox/report/ReportActionsList.tsx @@ -9,12 +9,12 @@ 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 useNetworkWithOfflineStatus from '@hooks/useNetworkWithOfflineStatus'; +import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import useReportActionsScroll from '@hooks/useReportActionsScroll'; -import useReportIsArchived from '@hooks/useReportIsArchived'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useThemeStyles from '@hooks/useThemeStyles'; import useUnreadMarker from '@hooks/useUnreadMarker'; @@ -36,6 +36,7 @@ import { import { chatIncludesChronosWithID, isArchivedNonExpenseReport, + isArchivedReport, isCanceledTaskReport, isExpenseReport, isHarvestCreatedExpenseReport, @@ -44,6 +45,7 @@ import { isTaskReport, 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'; @@ -55,67 +57,19 @@ import {getStableReportSelector} from '@src/selectors/Report'; import type * as OnyxTypes from '@src/types/onyx'; import FloatingMessageCounter from './FloatingMessageCounter'; import ReportActionIndexContext from './ReportActionIndexContext'; +import {useReportActionsListActions, useReportActionsListState} from './ReportActionsListContext'; import ReportActionsListHeader from './ReportActionsListHeader'; import ReportActionsListItemRenderer from './ReportActionsListItemRenderer'; import ReportActionsListPaddingView from './ReportActionsListPaddingView'; +import ReportActionsSkeletonGuard from './ReportActionsSkeletonGuard'; 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,49 +86,61 @@ 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) { +/** + * 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. + */ +function ReportActionsListContent({reportID, onLayout}: ReportActionsListProps) { const styles = useThemeStyles(); const {translate} = useLocalize(); const {windowHeight} = useWindowDimensions(); const {shouldUseNarrowLayout} = useResponsiveLayout(); const {isProduction} = useEnvironment(); - const {isOffline} = useNetworkWithOfflineStatus(); + const { + report, + hasOnceLoadedReportActions, + hasNewerActions, + sortedAllReportActions, + oldestUnreadReportAction, + transactionThreadReport, + parentReportActionForTransactionThread, + treatAsNoPaginationAnchor, + parentReportAction, + sortedReportActions, + sortedVisibleReportActions, + isConciergeHiddenHistory, + showFullHistory, + hasPreviousMessages, + } = useReportActionsListState(); + + const {setTreatAsNoPaginationAnchor, loadOlderChats, loadNewerChats, handleShowPreviousMessages} = useReportActionsListActions(); + + const {isOffline} = useNetwork(); const route = useRoute>(); - const {scrollOffsetRef} = useContext(ActionListContext); - const {draftReportAction, hasActiveDraft, isDraftPendingCompletion} = useConciergeDraft(); - const {clearDraft} = useConciergeDraftActions(); - const {sessionStartTime: conciergeSessionStartTime} = useConciergeSessionState(); + const reportActionIDFromRoute = route?.params?.reportActionID; + const {sessionStartTime} = useConciergeSessionState(); + + const didLayout = useRef(false); + + useEffect(() => { + didLayout.current = false; + }, [reportID]); - 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}`); + 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(':'); + + 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)}`); const reportAttributesSelector = useCallback( (value: OnyxEntry) => { - const attrs = value?.reports?.[report.reportID]; + const attrs = value?.reports?.[reportID]; if (!attrs) { return undefined; } @@ -184,7 +150,7 @@ function ReportActionsList({ brickRoadStatus: attrs.brickRoadStatus, }; }, - [report.reportID], + [reportID], ); const [reportAttributes] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES, { selector: reportAttributesSelector, @@ -192,26 +158,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 +197,7 @@ function ReportActionsList({ return sortedVisibleReportActions; } - if (showHiddenHistory && conciergeSessionStartTime && draftReportAction.created < conciergeSessionStartTime) { + if (showHiddenHistory && sessionStartTime && draftReportAction.created < sessionStartTime) { return sortedVisibleReportActions; } @@ -249,7 +222,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 +261,7 @@ function ReportActionsList({ shouldAutoscrollToBottom, onLoad, } = useReportActionsScroll({ + reportID, report, transactionThreadReport, parentReportAction, @@ -299,7 +273,7 @@ function ReportActionsList({ hasNewerActions, draftAutoScrollKey, actionBadgeTargetIndex, - sortedAllReportActionsForPagination, + sortedAllReportActionsForPagination: sortedAllReportActions ?? [], treatAsNoPaginationAnchor, setTreatAsNoPaginationAnchor, }); @@ -307,7 +281,6 @@ function ReportActionsList({ const trackScrollPositionAndThreshold = (event: NativeSyntheticEvent) => { trackVerticalScrolling(event); setHasScrolledOverThreshold(event.nativeEvent.contentOffset.y >= CONST.REPORT.ACTIONS.ACTION_VISIBLE_THRESHOLD); - onScroll?.(event); }; const loadOlderChatsOnEndReached = () => { @@ -335,7 +308,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. @@ -460,22 +433,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, @@ -483,6 +456,29 @@ function ReportActionsList({ isTrackIntentUser, }); + /** + * 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}); + } + }; + + // 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 ; + } + return ( <> { - onLayout(event); + recordTimeToMeasureItemLayout(event); flushPendingScrollToBottom(); }} onScroll={trackScrollPositionAndThreshold} @@ -547,4 +543,21 @@ function ReportActionsList({ ); } -export default memo(ReportActionsList); +const MemoizedReportActionsListContent = memo(ReportActionsListContent); + +/** + * Public report-actions list. Thin composition that wraps the content in `ReportActionsSkeletonGuard`, + * which owns the data pipeline + skeleton decision and only mounts the content once it is ready. + */ +function ReportActionsList({reportID, onLayout}: ReportActionsListProps) { + return ( + + + + ); +} + +export default ReportActionsList; diff --git a/src/pages/inbox/report/ReportActionsListContext.tsx b/src/pages/inbox/report/ReportActionsListContext.tsx new file mode 100644 index 000000000000..f4ee4b221f04 --- /dev/null +++ b/src/pages/inbox/report/ReportActionsListContext.tsx @@ -0,0 +1,117 @@ +import {createContext, useContext} from 'react'; +import type {ReportActionsListActions, ReportActionsListState, ReportActionsReadinessSignals} from '@hooks/useReportActionsListModel'; +import {isUnread} from '@libs/ReportUtils'; +import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue'; + +/** + * 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 ReportActionsListStateContext = createContext(null); + +/** + * 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('useReportActionsListActions must be used within a ReportActionsListActionsContext.Provider'); + } + return value; +} + +/** + * 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(readinessSignals: ReportActionsReadinessSignals) { + const { + report, + reportResult, + isOffline, + reportActionIDFromRoute, + transactionThreadReport, + isReportArchived, + isReportTransactionThread, + isLoadingInitialReportActions, + hasOnceLoadedReportActions, + isLoadingApp, + reportActionsLength, + oldestUnreadReportAction, + isSingleExpenseReport, + isMissingReportActions, + isConciergeHiddenHistory, + isConciergeMainDM, + hasCachedReportActions, + showConciergeSidePanelWelcome, + } = readinessSignals; + + 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 && 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 + // 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 isMissingTransactionThreadReportID = !transactionThreadReport?.reportID; + const isReportDataIncomplete = isSingleExpenseReport && isMissingTransactionThreadReportID; + + 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. 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; + + // When opening a linked message online, wait for the first load before rendering the list: the batch of + // actions that arrives right after the initial load shifts the list and breaks the anchor to the linked action. + const shouldShowSkeletonForLinkedMessageLoad = !!reportActionIDFromRoute && !isOffline && !hasOnceLoadedReportActions && !!isLoadingInitialReportActions; + + const shouldShowInitialSkeleton = shouldShowSkeletonForConciergePanel || shouldShowSkeletonForInitialLoad || shouldShowSkeletonForAppLoad || shouldShowSkeletonForLinkedMessageLoad; + + const hasDerivedValueTimingIssue = reportActionsLength > 0 && isMissingReportActions; + + const shouldShowLoadingSkeleton = isLoadingOnyxValue(reportResult) || !report || !isReportReady || shouldShowInitialSkeleton; + const shouldShowDerivedTimingSkeleton = (hasDerivedValueTimingIssue || (!isReportTransactionThread && isMissingReportActions)) && !showConciergeSidePanelWelcome; + + return { + shouldShowLoadingSkeleton, + shouldShowDerivedTimingSkeleton, + shouldShowInitialSkeleton, + }; +} + +export {ReportActionsListStateContext, ReportActionsListActionsContext, useReportActionsListState, useReportActionsListActions, computeReportActionsSkeletonState}; diff --git a/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx new file mode 100644 index 000000000000..a7fbc3d66099 --- /dev/null +++ b/src/pages/inbox/report/ReportActionsSkeletonGuard.tsx @@ -0,0 +1,62 @@ +import type {ReactNode} from 'react'; +import React 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 useStartConciergeSession from '@hooks/useStartConciergeSession'; +import {computeReportActionsSkeletonState, ReportActionsListActionsContext, ReportActionsListStateContext} from './ReportActionsListContext'; + +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 data pipeline + * (`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. + * + */ +function ReportActionsSkeletonGuard({reportID, children}: ReportActionsSkeletonGuardProps) { + const {readinessSignals, state, actions} = useReportActionsListModel(reportID); + const {shouldShowLoadingSkeleton, shouldShowDerivedTimingSkeleton, shouldShowInitialSkeleton} = computeReportActionsSkeletonState(readinessSignals); + + const {report, isConciergeMainDM, oldestUnreadReportAction, hasOnceLoadedReportActions, hasCachedReportActions} = readinessSignals; + + // Side effects that must run whenever the chat list is shown, including while the skeleton renders. + useCopySelectionHelper(); + usePendingConciergeResponse(reportID); + + useStartConciergeSession({ + reportID, + isConciergeMainDM, + oldestUnreadReportAction, + hasOnceLoadedReportActions, + hasCachedReportActions, + }); + + useMarkOpenReportEndOnSkeleton(report, shouldShowInitialSkeleton); + + if (shouldShowLoadingSkeleton) { + return ; + } + + if (shouldShowDerivedTimingSkeleton) { + return ; + } + + return ( + + {children} + + ); +} + +export default ReportActionsSkeletonGuard; diff --git a/src/pages/inbox/report/ReportActionsView.tsx b/src/pages/inbox/report/ReportActionsView.tsx deleted file mode 100755 index 2661d5601878..000000000000 --- a/src/pages/inbox/report/ReportActionsView.tsx +++ /dev/null @@ -1,260 +0,0 @@ -import {useRoute} from '@react-navigation/native'; -import React, {useEffect, useLayoutEffect, useRef} 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 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; -}; - -function ReportActionsView({reportID, onLayout}: ReportActionsViewProps) { - const route = useRoute(); - const reportActionIDFromRoute = route?.params?.reportActionID; - - 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; - } - // Anchor the session to the unread action's created time, a stable pre-read - // boundary, rather than the live report.lastReadTime which readNewestAction - // bumps to `now` when the report opens. Re-runs when oldestUnreadReportAction - // resolves so a session that locked to `now` before the anchor loaded is - // pulled back to keep the unread message visible. - startSession(oldestUnreadReportAction?.created); - }, [isConciergeMainDM, startSession, canStartConciergeSession, oldestUnreadReportAction?.created]); - - // 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?.created); - }, [currentReportID, reportID, isConciergeMainDM, canStartConciergeSession, startSession, oldestUnreadReportAction?.created]); - - 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 ; - } - - return ( - <> - - - - ); -} - -export default ReportActionsView; 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) { diff --git a/tests/perf-test/ReportActionsList.perf-test.tsx b/tests/perf-test/ReportActionsList.perf-test.tsx index 34be32abe350..0d6213f2dd46 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,16 @@ 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 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 {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 +30,6 @@ jest.mock('@react-navigation/native', () => { }; }); -jest.mock('@src/components/ConfirmedRoute.tsx'); - beforeAll(() => Onyx.init({ keys: ONYXKEYS, @@ -72,8 +38,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: () => {}, @@ -83,48 +47,59 @@ 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); +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}); -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 early-returns), + // avoiding post-mount Onyx writes that would re-render outside act(). + await act(async () => { + signUpWithTestUser(); + await Onyx.merge(ONYXKEYS.NVP_PREFERRED_LOCALE, 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 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() { - const reportActions = ReportTestUtils.getMockedSortedReportActions(500); return ( {}} - transactionThreadReport={report} /> 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(); + }); +}); diff --git a/tests/ui/ReportActionsViewTest.tsx b/tests/ui/ReportActionsListTest.tsx similarity index 80% rename from tests/ui/ReportActionsViewTest.tsx rename to tests/ui/ReportActionsListTest.tsx index 3ef5ee8e5f25..2196472da9e6 100644 --- a/tests/ui/ReportActionsViewTest.tsx +++ b/tests/ui/ReportActionsListTest.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'; @@ -15,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'; @@ -96,25 +97,54 @@ 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; - }), +// 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()}))); +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; + +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()); -// Mock report data const mockReport: OnyxTypes.Report = { reportID: '123', reportName: 'Test Report', @@ -151,12 +181,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, @@ -265,9 +295,13 @@ describe('ReportActionsView', () => { ...defaultPaginatedReportActionsResult, }); - renderReportActionsView(); + 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)', () => { @@ -297,9 +331,12 @@ describe('ReportActionsView', () => { return [undefined, {status: 'loaded'}]; }); - renderReportActionsView(); + 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)', () => { @@ -329,7 +366,7 @@ describe('ReportActionsView', () => { return [undefined, {status: 'loaded'}]; }); - renderReportActionsView(); + renderReportActionsList(); expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); }); @@ -361,9 +398,60 @@ describe('ReportActionsView', () => { return [undefined, {status: 'loaded'}]; }); - renderReportActionsView(); + renderReportActionsList(); + + expect(screen.queryByTestId('ReportActionsSkeletonView')).toBeNull(); + }); + }); + + 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}); }); }); @@ -438,10 +526,10 @@ describe('ReportActionsView', () => { mockUseIsInSidePanel.mockReturnValue(true); mockUseSidePanelState.mockReturnValue({...defaultSidePanelState, sessionStartTime: DateUtils.getDBTime()}); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({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); }); @@ -455,7 +543,7 @@ describe('ReportActionsView', () => { }); mockUseIsInSidePanel.mockReturnValue(false); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(mockReportActionItemCreated).not.toHaveBeenCalled(); }); @@ -469,7 +557,7 @@ describe('ReportActionsView', () => { }); mockUseIsInSidePanel.mockReturnValue(false); - renderReportActionsView({reportID: 'non-concierge-999'}); + renderReportActionsList({reportID: 'non-concierge-999'}); expect(mockReportActionItemCreated).not.toHaveBeenCalled(); }); @@ -502,12 +590,12 @@ 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(); // ReportActionsList should be rendered with filtered actions - expect(mockReportActionsList).toHaveBeenCalled(); + expect(mockInvertedFlashList).toHaveBeenCalled(); }); }); @@ -598,10 +686,10 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({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); @@ -616,10 +704,10 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({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); }); @@ -649,10 +737,10 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({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); @@ -667,10 +755,10 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({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); @@ -713,10 +801,10 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({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); }); @@ -733,7 +821,7 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({reportID: CONCIERGE_REPORT_ID}); expect(mockStartSession).toHaveBeenCalled(); }); @@ -749,10 +837,10 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + renderReportActionsList({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', () => { @@ -764,9 +852,13 @@ describe('ReportActionsView', () => { hasOlderActions: false, }); - renderReportActionsView({reportID: CONCIERGE_REPORT_ID}); + 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(); }); }); }); diff --git a/tests/ui/ReportActionsTest.tsx b/tests/ui/ReportActionsTest.tsx new file mode 100644 index 000000000000..79ed870d9071 --- /dev/null +++ b/tests/ui/ReportActionsTest.tsx @@ -0,0 +1,221 @@ +/* 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'; +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 {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'; +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), + isConciergeChatReport: 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 mockIsConciergeChatReport = isConciergeChatReport 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); + mockIsConciergeChatReport.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('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}); + + 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(); + }); +}); 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,