diff --git a/src/components/Search/ChatSearchView.tsx b/src/components/Search/ChatSearchView.tsx index 8e296959a048..04a7f719d6ea 100644 --- a/src/components/Search/ChatSearchView.tsx +++ b/src/components/Search/ChatSearchView.tsx @@ -48,6 +48,7 @@ function ChatSearchView({ onEndReached, onLayout, onScroll, + onViewableItemsChanged, contentContainerStyle, containerStyle, ref, @@ -123,6 +124,7 @@ function ChatSearchView({ onSelectRow={handleSelectRow} keyExtractor={keyExtractor} onScroll={onScroll} + onViewableItemsChanged={onViewableItemsChanged} showsVerticalScrollIndicator={false} ref={listRef} columns={columns} diff --git a/src/components/Search/ExpenseFlatSearchView.tsx b/src/components/Search/ExpenseFlatSearchView.tsx index 60a319602e58..d148b8e1599e 100644 --- a/src/components/Search/ExpenseFlatSearchView.tsx +++ b/src/components/Search/ExpenseFlatSearchView.tsx @@ -56,6 +56,7 @@ function ExpenseFlatSearchView({ onEndReached, onLayout, onScroll, + onViewableItemsChanged, contentContainerStyle, containerStyle, ref, @@ -169,6 +170,7 @@ function ExpenseFlatSearchView({ onSelectRow={handleSelectRow} keyExtractor={keyExtractor} onScroll={onScroll} + onViewableItemsChanged={onViewableItemsChanged} showsVerticalScrollIndicator={false} ref={listRef} columns={columns} diff --git a/src/components/Search/ExpenseGroupedSearchView.tsx b/src/components/Search/ExpenseGroupedSearchView.tsx index 5273c9cde901..3f36466241a2 100644 --- a/src/components/Search/ExpenseGroupedSearchView.tsx +++ b/src/components/Search/ExpenseGroupedSearchView.tsx @@ -113,6 +113,7 @@ function ExpenseGroupedSearchView({ onEndReached, onLayout, onScroll, + onViewableItemsChanged, contentContainerStyle, containerStyle, ref, @@ -375,6 +376,7 @@ function ExpenseGroupedSearchView({ onSelectRow={handleSelectRow} keyExtractor={keyExtractor} onScroll={onScroll} + onViewableItemsChanged={onViewableItemsChanged} showsVerticalScrollIndicator={false} ref={listRef} columns={columns} diff --git a/src/components/Search/ExpenseReportSearchView.tsx b/src/components/Search/ExpenseReportSearchView.tsx index 45ca76d7c7f7..8c314f4eae4a 100644 --- a/src/components/Search/ExpenseReportSearchView.tsx +++ b/src/components/Search/ExpenseReportSearchView.tsx @@ -54,6 +54,7 @@ function ExpenseReportSearchView({ onEndReached, onLayout, onScroll, + onViewableItemsChanged, contentContainerStyle, containerStyle, ref, @@ -159,6 +160,7 @@ function ExpenseReportSearchView({ onSelectRow={handleSelectRow} keyExtractor={keyExtractor} onScroll={onScroll} + onViewableItemsChanged={onViewableItemsChanged} showsVerticalScrollIndicator={false} ref={listRef} columns={columns} diff --git a/src/components/Search/SearchResultsProvider.tsx b/src/components/Search/SearchResultsProvider.tsx index 4f83c08a85ab..1b8d5620bba8 100644 --- a/src/components/Search/SearchResultsProvider.tsx +++ b/src/components/Search/SearchResultsProvider.tsx @@ -62,6 +62,7 @@ function SearchResultsProvider({children}: SearchResultsProviderProps) { const hasResults = Object.keys(liveData.data).length > 0; // For to-do searches, always return a valid SearchResults object (even with empty data) // This ensures we show the empty state instead of loading/blocking views + // isLoading forced off: the shared flag survives a reload and would strand the skeletons currentSearchResults = { search: {...searchInfo, isLoading: false, hasResults}, data: liveData.data, diff --git a/src/components/Search/TaskSearchView.tsx b/src/components/Search/TaskSearchView.tsx index 30f17ea54fcc..845bed020086 100644 --- a/src/components/Search/TaskSearchView.tsx +++ b/src/components/Search/TaskSearchView.tsx @@ -47,6 +47,7 @@ function TaskSearchView({ onEndReached, onLayout, onScroll, + onViewableItemsChanged, contentContainerStyle, containerStyle, ref, @@ -121,6 +122,7 @@ function TaskSearchView({ onSelectRow={handleSelectRow} keyExtractor={keyExtractor} onScroll={onScroll} + onViewableItemsChanged={onViewableItemsChanged} showsVerticalScrollIndicator={false} ref={listRef} columns={columns} diff --git a/src/components/Search/hooks/useLiveRowLimit.ts b/src/components/Search/hooks/useLiveRowLimit.ts new file mode 100644 index 000000000000..27e37fd6d4f9 --- /dev/null +++ b/src/components/Search/hooks/useLiveRowLimit.ts @@ -0,0 +1,38 @@ +import CONST from '@src/CONST'; + +import {useState} from 'react'; + +type LiveRowLimit = { + liveRowLimit: number; + + /** Offset of the last page the server answered. Unlike the snapshot offset, which every search() caller rewrites, it only moves forward. */ + answeredOffset: number; + + /** Shows one more page of live rows without the server, for when it has no pages left. */ + revealNextPage: () => void; +}; + +/** Row cap for a live (to-do) search. Reset rides on `` remounting, so there is no reset here. */ +function useLiveRowLimit(offset = 0, hasUnconfirmedPage = false): LiveRowLimit { + // offset is written when the request fires, so a page still running or failed there only confirms the one before it + const confirmedOffset = Math.max(0, hasUnconfirmedPage ? offset - CONST.SEARCH.RESULTS_PAGE_SIZE : offset); + + // a refresh rewinds offset to 0, but the pages past it already answered and their rows are still in Onyx + const [answeredOffset, setAnsweredOffset] = useState(confirmedOffset); + if (answeredOffset < confirmedOffset) { + setAnsweredOffset(confirmedOffset); + } + const currentAnsweredOffset = Math.max(answeredOffset, confirmedOffset); + const answeredRows = currentAnsweredOffset + CONST.SEARCH.RESULTS_PAGE_SIZE; + + const [revealedRows, setRevealedRows] = useState(answeredRows); + if (revealedRows < answeredRows) { + setRevealedRows(answeredRows); + } + + const revealNextPage = () => setRevealedRows((rows) => rows + CONST.SEARCH.RESULTS_PAGE_SIZE); + + return {liveRowLimit: Math.max(revealedRows, answeredRows), answeredOffset: currentAnsweredOffset, revealNextPage}; +} + +export default useLiveRowLimit; diff --git a/src/components/Search/hooks/useSearchSnapshot.ts b/src/components/Search/hooks/useSearchSnapshot.ts index dba8eee36d7e..b3eec433969d 100644 --- a/src/components/Search/hooks/useSearchSnapshot.ts +++ b/src/components/Search/hooks/useSearchSnapshot.ts @@ -1,6 +1,6 @@ import {useSearchQueryContext, useSearchResultsContext} from '@components/Search/SearchContext'; import type {ReportActionListItemType, SearchListItem, TransactionGroupListItemType, TransactionListItemType} from '@components/Search/SearchList/ListItem/types'; -import type {SearchColumnType, SearchData, SearchQueryJSON} from '@components/Search/types'; +import type {SearchColumnType, SearchData, SearchQueryJSON, SelectedTransactions} from '@components/Search/types'; import useActionLoadingReportIDs from '@hooks/useActionLoadingReportIDs'; import {useCurrencyListActions} from '@hooks/useCurrencyList'; @@ -15,7 +15,7 @@ import usePolicyForMovingExpenses from '@hooks/usePolicyForMovingExpenses'; import useReportAttributes from '@hooks/useReportAttributes'; import {isDefaultExpensesQuery, queryHasViolationFilter} from '@libs/SearchQueryUtils'; -import {getColumnsToShow, getSections, getSortedSections, getSortedTransactionData, getValidGroupBy, isSearchDataLoaded} from '@libs/SearchUIUtils'; +import {getColumnsToShow, getSections, getSortedSections, getSortedTransactionData, getValidGroupBy, isSearchDataLoaded, isTransactionGroupListItemType} from '@libs/SearchUIUtils'; import {shouldShowAttendees} from '@libs/TransactionUtils'; import CONST from '@src/CONST'; @@ -47,7 +47,7 @@ type SearchSnapshotResult = { data: SearchListItem[]; /** Sorted row items BEFORE optimistic stabilization. The chart view consumes this, not `data`. */ chartData: SearchListItem[]; - /** Group-enriched sections before sort. Consumed for selection counts and bulk-action wiring. */ + /** Group-enriched sections before sort, capped to `visibleRowLimit`. Consumed for selection counts and bulk-action wiring. */ filteredData: SearchData; /** Length of the base (pre-sort) sections (used as `prevReportsLength` when firing the next search). */ filteredDataLength: number; @@ -85,6 +85,11 @@ type UseSearchSnapshotParams = { * full-collection reads. */ transactions: OptimisticTrackingParams['transactions']; reportActions: OptimisticTrackingParams['reportActions']; + /** Row cap for `data`. Live (to-do) searches page on this instead of a server cursor; their rows are all report groups. */ + visibleRowLimit?: number; + + /** Rows ticked here stay rendered past `visibleRowLimit`. */ + selectedTransactions?: SelectedTransactions; }; const EMPTY_DATA: SearchListItem[] = []; @@ -92,6 +97,25 @@ const EMPTY_COLUMNS: SearchColumnType[] = []; const EMPTY_HASHES: string[] = []; const EMPTY_GROUP_ITEMS: TransactionGroupListItemType[] = []; +/** How many leading rows the cap keeps: `rowLimit` rows on screen, stretched down to the last ticked or highlighted row. */ +function getRowLimitEnd(rows: SearchListItem[], rowLimit: number, selectedTransactions: SelectedTransactions | undefined, isOffline: boolean): number { + const isKeySelected = (key: string | undefined) => !!key && !!selectedTransactions?.[key]?.isSelected; + let shownRowCount = 0; + let end = 0; + for (const [index, row] of rows.entries()) { + // online, a row being deleted is hidden, so it doesn't use up the cap + if (!isOffline && row.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE) { + continue; + } + shownRowCount += 1; + const isRowSelected = isKeySelected(row.keyForList) || (isTransactionGroupListItemType(row) && row.transactions.some((transaction) => isKeySelected(transaction.keyForList))); + if (shownRowCount <= rowLimit || !!row.shouldAnimateInHighlight || isRowSelected) { + end = index + 1; + } + } + return end; +} + const hashToString = (queryHash?: number) => (queryHash || queryHash === 0 ? String(queryHash) : undefined); /** @@ -102,7 +126,15 @@ const hashToString = (queryHash?: number) => (queryHash || queryHash === 0 ? Str * per-group sub-snapshots, and absorbs the optimistic-row resilience. Returns the sorted rows plus the * list-level meta and the optimistic-tracking carriers that `` consumes. */ -function useSearchSnapshot({queryJSON, searchResults, newSearchResultKeys, transactions, reportActions}: UseSearchSnapshotParams): SearchSnapshotResult { +function useSearchSnapshot({ + queryJSON, + searchResults, + newSearchResultKeys, + transactions, + reportActions, + visibleRowLimit, + selectedTransactions, +}: UseSearchSnapshotParams): SearchSnapshotResult { const {type, sortBy, sortOrder, hash, groupBy} = queryJSON; const {isOffline} = useNetwork(); @@ -413,10 +445,17 @@ function useSearchSnapshot({queryJSON, searchResults, newSearchResultKeys, trans return item.transactions.length === 0 || !subSnapshot || !subSnapshot?.search?.hasMoreResults; }); + // slice after the sort so page 2 continues the order on screen + const rowLimitEnd = visibleRowLimit === undefined ? stableSortedData.length : getRowLimitEnd(stableSortedData, visibleRowLimit, selectedTransactions, isOffline); + const isRowLimitApplied = rowLimitEnd < stableSortedData.length; + const visibleData = isRowLimitApplied ? stableSortedData.slice(0, rowLimitEnd) : stableSortedData; + // selection runs off this, so cap it too or "select all" reaches rows that were never rendered; live rows are all report groups + const visibleFilteredData = isRowLimitApplied ? visibleData.filter(isTransactionGroupListItemType) : filteredData; + return { - data: stableSortedData, + data: visibleData, chartData, - filteredData, + filteredData: visibleFilteredData, filteredDataLength, allDataLength, hasDeletedTransaction, diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index aea1479aff19..856e20ec0fdd 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -103,6 +103,7 @@ import ChatSearchView from './ChatSearchView'; import ExpenseFlatSearchView from './ExpenseFlatSearchView'; import ExpenseGroupedSearchView from './ExpenseGroupedSearchView'; import ExpenseReportSearchView from './ExpenseReportSearchView'; +import useLiveRowLimit from './hooks/useLiveRowLimit'; import useSearchSnapshot from './hooks/useSearchSnapshot'; import useShouldShowBulkActionBar from './hooks/useShouldShowBulkActionBar'; import SearchChartView from './SearchChartView'; @@ -160,10 +161,15 @@ function Search({ const {setShouldResetSearchQuery} = useSearchQueryActions(); const {setShouldShowFiltersBarLoading} = useSearchResultsActions(); const {clearSelectedTransactions} = useSearchSelectionActions(); - const {areAllMatchingItemsSelected} = useSearchSelectionContext(); + const {areAllMatchingItemsSelected, selectedTransactions} = useSearchSelectionContext(); // Wide layout floats the bulk action bar over the end of the list, so the list has to leave room for it. const shouldReserveBulkActionBarSpace = useShouldShowBulkActionBar(queryJSON); const [offset, setOffset] = useState(0); + // a page left running by a previous mount is still in flight, so wait for it rather than revealing or skipping its rows + const isLivePageRunningAtMount = () => shouldUseLiveData && isSearchPending(searchResults) && (searchResults?.search?.offset ?? 0) > 0; + // live paging owns its in-flight flag, keyed to the offset it asked for so other searches on this hash don't read as ours + const [livePageOffset, setLivePageOffset] = useState(() => (isLivePageRunningAtMount() ? searchResults?.search?.offset : undefined)); + const [isLivePageAdopted, setIsLivePageAdopted] = useState(isLivePageRunningAtMount); const [transactions] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION); const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); @@ -194,6 +200,20 @@ function Search({ const [, cardFeedsResult] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER); + const isSnapshotPending = isSearchPending(searchResults); + + // gate on state: loading so it self-clears — Onyx resolves loading on every response + const isLivePageInFlight = shouldUseLiveData && livePageOffset !== undefined && livePageOffset === searchResults?.search?.offset && isSnapshotPending; + // once the adopted page settles, a later page in flight is ours and must not be re-asked + if (isLivePageAdopted && !isLivePageInFlight) { + setIsLivePageAdopted(false); + } + + // live results drop `errors`, so the response code is the only failure signal left + const didLastLivePageFail = shouldUseLiveData && typeof searchResults?.search?.responseJsonCode === 'number'; + + const {liveRowLimit, answeredOffset: answeredLiveOffset, revealNextPage: revealNextLivePage} = useLiveRowLimit(searchResults?.search?.offset, isSnapshotPending || didLastLivePageFail); + const searchDataType = useMemo(() => (shouldUseLiveData ? CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT : searchResults?.search?.type), [shouldUseLiveData, searchResults?.search?.type]); const isExpenseAllMatchingSelection = type === CONST.SEARCH.DATA_TYPES.EXPENSE && areAllMatchingItemsSelected; const isAllMatchingItemsCountMissing = isExpenseAllMatchingSelection && typeof searchResults?.search?.count !== 'number'; @@ -291,6 +311,8 @@ function Search({ newSearchResultKeys, transactions, reportActions, + visibleRowLimit: shouldUseLiveData ? liveRowLimit : undefined, + selectedTransactions, }); // Mirror `hasQueuedHighlights` into a ref so the post-create-flow `useFocusEffect` @@ -398,7 +420,8 @@ function Search({ const shouldShowLoadingState = isDeferringHeavyWork || isWaitingForInitialData; const shouldShowRowSkeleton = (!skeletonWasDisplayed || shouldShowLoadingState) && showPendingExpensePlaceholder && !hasErrors; - const shouldShowLoadingMoreItems = !shouldShowLoadingState && searchResults?.search?.isLoading && searchResults?.search?.offset > 0; + const isLoadingMorePage = shouldUseLiveData ? isLivePageInFlight : !!searchResults?.search?.isLoading; + const shouldShowLoadingMoreItems = !shouldShowLoadingState && isLoadingMorePage && (searchResults?.search?.offset ?? 0) > 0; const prevIsSearchResultEmpty = usePrevious(isSearchResultsEmpty); @@ -445,7 +468,8 @@ function Search({ return; } - if (searchResults?.search?.isLoading) { + // the offset change from paging would otherwise fire a duplicate page alongside fetchMoreResults + if (isLoadingMorePage) { if (validGroupBy || (shouldCalculateTotals && isRequiredAllMatchingTotalMissing)) { shouldRetrySearchWithTotalsOrGroupedRef.current = true; } @@ -834,23 +858,65 @@ function Search({ // dropped. Stays set until that page actually shows up in the snapshot. const wantedOffsetRef = useRef(undefined); + // rebuilds report ends too, only a scroll moves the visible rows; not onScroll, it's a worklet on native + const hasScrolledSinceLastEndRef = useRef(true); + const onViewableItemsChanged = () => { + hasScrolledSinceLastEndRef.current = true; + }; + const fetchMoreResults = useCallback(() => { - if (!searchResults?.search?.hasMoreResults) { + // A first-page response replaces the snapshot rather than appending to it, so deriving the next page + // from `offset` instead of the snapshot's own cursor drifts the moment one lands mid-pagination. + // Live rows don't come from the snapshot, so live paging follows the pages that answered instead. + const serverOffset = shouldUseLiveData ? answeredLiveOffset : (searchResults?.search?.offset ?? 0); + const nextOffset = serverOffset + CONST.SEARCH.RESULTS_PAGE_SIZE; + + // a failed page never writes `hasMoreResults`, and a failure doesn't mean the server is out of rows + if (!searchResults?.search?.hasMoreResults && !didLastLivePageFail) { + // before the first answer `hasMoreResults` is only the default, so wait for the server to say it is out of pages; + // no `state` means no request for this tab has even gone out yet + const hasLiveSearchStarted = searchResults?.search?.state !== undefined; + if (shouldUseLiveData && (!hasLiveSearchStarted || (isSnapshotPending && !isOffline))) { + wantedOffsetRef.current = nextOffset; + return; + } + // the server has nothing left, but the live scan can still hold rows past the cap: page those in locally + if (shouldUseLiveData && allDataLength > liveRowLimit) { + revealNextLivePage(); + } wantedOffsetRef.current = undefined; return; } - // A first-page response replaces the snapshot rather than appending to it, so deriving the next page - // from `offset` instead of the snapshot's own cursor drifts the moment one lands mid-pagination. - const serverOffset = searchResults?.search?.offset ?? 0; - if (!isFocused || shouldShowLoadingState || serverOffset > allDataLength - CONST.SEARCH.RESULTS_PAGE_SIZE) { + if (!isFocused || shouldShowLoadingState) { return; } - const nextOffset = serverOffset + CONST.SEARCH.RESULTS_PAGE_SIZE; + const hasScrolledToEnd = hasScrolledSinceLastEndRef.current; + hasScrolledSinceLastEndRef.current = false; + // a failed page retries once per end the user scrolls to, not on every rebuild while they sit at the bottom + if (didLastLivePageFail && !hasScrolledToEnd) { + return; + } + + // onEndReached refires mid-flight under the skeleton; recording the next offset would chase past the loading page + if (shouldUseLiveData && isLoadingMorePage) { + // a reload strands an adopted page in loading, so re-ask it once; search() drops it if it is still running + if (isLivePageAdopted && !isOffline) { + setIsLivePageAdopted(false); + handleSearch({queryJSON, searchKey: currentSearchKey, offset: nextOffset, shouldCalculateTotals, prevReportsLength: filteredDataLength, isLoading: false}); + } + return; + } + + if (serverOffset > allDataLength - CONST.SEARCH.RESULTS_PAGE_SIZE) { + return; + } + + // the cap can outrun the cursor, and pulling the cursor up to it would skip server pages for good wantedOffsetRef.current = nextOffset; // Offline, the request would only fail and leave an error on the snapshot. Hold the page until reconnect. - if (searchResults?.search?.isLoading || isOffline) { + if (isLoadingMorePage || isOffline) { return; } @@ -865,11 +931,23 @@ function Search({ prevReportsLength: filteredDataLength, isLoading: false, }); + // offline path returned above, so we never arm with no request running + if (shouldUseLiveData) { + setLivePageOffset(nextOffset); + } }, [ isFocused, isOffline, + shouldUseLiveData, + answeredLiveOffset, + isSnapshotPending, + liveRowLimit, + revealNextLivePage, + didLastLivePageFail, + isLivePageAdopted, searchResults?.search?.hasMoreResults, - searchResults?.search?.isLoading, + searchResults?.search?.state, + isLoadingMorePage, searchResults?.search?.offset, shouldShowLoadingState, allDataLength, @@ -883,25 +961,27 @@ function Search({ // Ask again for a page that never arrived, either because a search was still running when the list hit // its end or because a first-page response replaced it. Both leave the request with nothing to retry it. useEffect(() => { - const serverOffset = searchResults?.search?.offset ?? 0; + const serverOffset = shouldUseLiveData ? answeredLiveOffset : (searchResults?.search?.offset ?? 0); // A first-page response that lands after the page it displaces drags the cursor back below the page we // hold, after that page's arrival already cleared the intent. The list has not moved, so arm it again. - if (wantedOffsetRef.current === undefined && searchResults?.search?.hasMoreResults && serverOffset < offset) { + // Live rows stay in Onyx through that, so there is nothing to fetch again. + if (!shouldUseLiveData && wantedOffsetRef.current === undefined && searchResults?.search?.hasMoreResults && serverOffset < offset) { wantedOffsetRef.current = offset; } const wantedOffset = wantedOffsetRef.current; - if (wantedOffset === undefined || searchResults?.search?.isLoading) { + if (wantedOffset === undefined || isLoadingMorePage) { return; } - if (serverOffset >= wantedOffset) { + // a failed live page waits for the next end rather than retrying on its own + if (serverOffset >= wantedOffset || didLastLivePageFail) { wantedOffsetRef.current = undefined; return; } fetchMoreResults(); - }, [fetchMoreResults, offset, searchResults?.search?.hasMoreResults, searchResults?.search?.isLoading, searchResults?.search?.offset]); + }, [answeredLiveOffset, didLastLivePageFail, fetchMoreResults, isLoadingMorePage, offset, searchResults?.search?.hasMoreResults, searchResults?.search?.offset, shouldUseLiveData]); const onLayoutBase = useCallback(() => { hasHadFirstLayout.current = true; @@ -1317,6 +1397,7 @@ function Search({ contentContainerStyle: [styles.pb3, shouldReserveBulkActionBarSpace && styles.bulkActionBarListSpacing, contentContainerStyle], containerStyle: [styles.pv0], onScroll: onSearchListScroll, + onViewableItemsChanged, onEndReached: fetchMoreResults, ListFooterComponent: listFooterComponent, onLayout, diff --git a/src/components/Search/searchViewProps.ts b/src/components/Search/searchViewProps.ts index 4c511a65d25d..5893f3202faf 100644 --- a/src/components/Search/searchViewProps.ts +++ b/src/components/Search/searchViewProps.ts @@ -73,6 +73,8 @@ type CommonSearchViewProps = { /** Scroll handler forwarded to the list. */ onScroll?: (event: NativeSyntheticEvent) => void; + onViewableItemsChanged?: () => void; + contentContainerStyle: StyleProp; containerStyle: StyleProp; diff --git a/tests/ui/SearchPageTest.tsx b/tests/ui/SearchPageTest.tsx index e9aa509fc00b..53235410763c 100644 --- a/tests/ui/SearchPageTest.tsx +++ b/tests/ui/SearchPageTest.tsx @@ -4,8 +4,12 @@ import ComposeProviders from '@components/ComposeProviders'; import FullScreenBlockingViewContextProvider from '@components/FullScreenBlockingViewContextProvider'; import {LocaleContextProvider} from '@components/LocaleContextProvider'; import OnyxListItemProvider from '@components/OnyxListItemProvider'; +import type * as SearchContext from '@components/Search/SearchContext'; import {SearchContextProvider} from '@components/Search/SearchContextProvider'; +import type {SearchListItem} from '@components/Search/SearchList/ListItem/types'; import SearchLoadingSkeleton from '@components/Search/SearchLoadingSkeleton'; +import type * as SearchWriteActionsProviderModule from '@components/Search/SearchWriteActionsProvider'; +import type {SearchData, SearchSelectionActionsValue, SelectedTransactionInfo} from '@components/Search/types'; import {PlaybackContextProvider} from '@components/VideoPlayerContexts/PlaybackContext'; import useNetwork from '@hooks/useNetwork'; @@ -20,6 +24,7 @@ import createPlatformStackNavigator from '@libs/Navigation/PlatformStackNavigati import Animations from '@libs/Navigation/PlatformStackNavigation/navigationOptions/animation'; import type {SearchFullscreenNavigatorParamList} from '@libs/Navigation/types'; import * as SearchQueryUtils from '@libs/SearchQueryUtils'; +import {getSuggestedSearches} from '@libs/SearchUIUtils'; import EmptySearchView from '@pages/Search/EmptySearchView'; import SearchPage from '@pages/Search/SearchPage'; @@ -28,16 +33,19 @@ import CONST from '@src/CONST'; import NAVIGATORS from '@src/NAVIGATORS'; import ONYXKEYS from '@src/ONYXKEYS'; import SCREENS from '@src/SCREENS'; +import type {Policy, Report, Transaction} from '@src/types/onyx'; import type SearchResults from '@src/types/onyx/SearchResults'; import type * as CoreNavigation from '@react-navigation/core'; import type * as reactNavigationNativeImport from '@react-navigation/native'; +import type React from 'react'; import {PortalProvider} from '@gorhom/portal'; import {NavigationContainer} from '@react-navigation/native'; import Onyx from 'react-native-onyx'; import createMock from '../utils/createMock'; +import getOnyxValue from '../utils/getOnyxValue'; registerMiddlewares(); @@ -75,16 +83,49 @@ jest.mock('@react-navigation/core', () => ({ useNavigation: jest.fn(() => ({getState: jest.fn(() => undefined), isFocused: jest.fn(() => true)})), })); -// FlashList never lays out here, so stand in for it to get at onEndReached. -const listProps: {onEndReached?: () => void} = {}; +type ListProps = {onEndReached?: () => void; onViewableItemsChanged?: () => void; onSelectRow?: (item: SearchListItem) => void; ListFooterComponent?: unknown}; + +// Captures the list's handlers, since FlashList never lays out in tests. +const listProps: ListProps = {}; jest.mock('@components/Search/SearchList/BaseSearchList', () => ({ __esModule: true, - default: (props: {onEndReached?: () => void}) => { + default: (props: ListProps) => { listProps.onEndReached = props.onEndReached; + listProps.onViewableItemsChanged = props.onViewableItemsChanged; + listProps.onSelectRow = props.onSelectRow; + listProps.ListFooterComponent = props.ListFooterComponent; return null; }, })); +type WriteActionsRender = { + filteredData: SearchData; + applySelection: SearchSelectionActionsValue['applySelection']; +}; +type WriteActionsProviderProps = Parameters[0]; + +// The rows hands this provider are the rows selection can reach. +const mockRenderWriteActions = jest.fn(); +jest.mock('@components/Search/SearchWriteActionsProvider', () => { + const {createElement} = jest.requireActual('react'); + const {useSearchSelectionActions} = jest.requireActual('@components/Search/SearchContext'); + const {default: SearchWriteActionsProvider} = jest.requireActual('@components/Search/SearchWriteActionsProvider'); + function MockSearchWriteActionsProvider(props: WriteActionsProviderProps) { + const {applySelection} = useSearchSelectionActions(); + mockRenderWriteActions({filteredData: props.filteredData, applySelection}); + return createElement(SearchWriteActionsProvider, props); + } + return {__esModule: true, default: MockSearchWriteActionsProvider}; +}); + +function lastWriteActionsRender() { + return mockRenderWriteActions.mock.lastCall?.[0]; +} + +function renderedRowKeys() { + return lastWriteActionsRender()?.filteredData.map((row) => row.keyForList) ?? []; +} + const mockIsFocused = jest.fn(() => true); jest.mock('@react-navigation/native', () => ({ ...jest.requireActual('@react-navigation/native'), @@ -261,6 +302,10 @@ describe('SearchPageNarrow', () => { mockSearchQueryParam.mockReturnValue(FAILED_QUERY); mockIsFocused.mockReturnValue(true); listProps.onEndReached = undefined; + listProps.onViewableItemsChanged = undefined; + listProps.onSelectRow = undefined; + listProps.ListFooterComponent = undefined; + mockRenderWriteActions.mockReset(); }); it('SearchPageNarrow renders correctly', async () => { @@ -659,4 +704,683 @@ describe('SearchPageNarrow', () => { expect(wasSearchedAtNextPage()).toBe(true); }); + + describe('a to-do search, which reads live Onyx rows instead of the snapshot', () => { + const TODO_EMAIL = 'submitter@expensify.com'; + const TODO_POLICY_ID = 'todoPolicy'; + // Without a CurrentUserPersonalDetailsProvider, the screen builds its suggested searches for this ID. + const TODO_ACCOUNT_ID = CONST.DEFAULT_NUMBER_ID; + // From the screen's own builder, since a hand-written query hashes differently and isn't a to-do search. + const TODO_QUERY = getSuggestedSearches(TODO_ACCOUNT_ID, undefined, false, undefined)[CONST.SEARCH.SEARCH_KEYS.SUBMIT].searchQuery; + const todoQueryJSON = SearchQueryUtils.buildSearchQueryJSON(TODO_QUERY); + + // An open expense report with no expenses is a Submit to-do. + const buildTodoReport = (index: number) => + createMock({ + reportID: `todo_${index}`, + chatReportID: `chat_todo_${index}`, + policyID: TODO_POLICY_ID, + ownerAccountID: TODO_ACCOUNT_ID, + stateNum: CONST.REPORT.STATE_NUM.OPEN, + statusNum: CONST.REPORT.STATUS_NUM.OPEN, + type: CONST.REPORT.TYPE.EXPENSE, + reportName: 'Draft report', + currency: 'USD', + total: 0, + }); + + const seedTodoReports = async (count: number) => { + await act(async () => { + await Onyx.set(ONYXKEYS.SESSION, {accountID: TODO_ACCOUNT_ID, email: TODO_EMAIL}); + await Onyx.set( + `${ONYXKEYS.COLLECTION.POLICY}${TODO_POLICY_ID}`, + createMock({id: TODO_POLICY_ID, name: 'Todo policy', type: CONST.POLICY.TYPE.TEAM, role: CONST.POLICY.ROLE.USER, owner: TODO_EMAIL, outputCurrency: 'USD'}), + ); + // An empty draft only counts once transactions have loaded, and an untouched collection never loads. + await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}unrelated`, createMock({transactionID: 'unrelated', reportID: 'not_a_todo', amount: -1, currency: 'USD'})); + await Promise.all(Array.from({length: count}, (_value, index) => Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}todo_${index + 1}`, buildTodoReport(index + 1)))); + }); + mockSearchQueryParam.mockReturnValue(TODO_QUERY); + }; + + const seedTodoSnapshot = (hasMoreResults: boolean, overrides: Record = {}) => + act(async () => { + await Onyx.set(`${ONYXKEYS.COLLECTION.SNAPSHOT}${todoQueryJSON?.hash}`, { + search: { + type: CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT, + offset: 0, + hash: todoQueryJSON?.hash, + isLoading: false, + state: CONST.SEARCH.SNAPSHOT_STATE.LOADED, + hasMoreResults, + ...overrides, + }, + }); + }); + + // The real search() optimistically writes the page's offset and parks the snapshot in its loading state; the + // live row cap holds there until the answer lands, so the mock has to write it too. + const searchWritesLoadingState = () => + mockSearch.mockImplementation((params?: Parameters[0]) => { + if ((params?.offset ?? 0) <= 0) { + return Promise.resolve(200); + } + return Onyx.merge(`${ONYXKEYS.COLLECTION.SNAPSHOT}${todoQueryJSON?.hash}`, { + search: {offset: params?.offset, state: CONST.SEARCH.SNAPSHOT_STATE.LOADING, isLoading: true}, + }).then(() => 200); + }); + + const answerTodoPage = (pageOffset: number, hasMoreResults = false) => + act(async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.SNAPSHOT}${todoQueryJSON?.hash}`, { + search: {offset: pageOffset, isLoading: false, state: CONST.SEARCH.SNAPSHOT_STATE.LOADED, hasMoreResults}, + }); + }); + + beforeEach(() => { + // clearAllMocks keeps mockImplementation overrides, so pin the default back down per test. + mockSearch.mockImplementation(() => Promise.resolve(200)); + }); + + it('asks for its first page exactly once', async () => { + await seedTodoReports(3); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + expect(mockSearch).toHaveBeenCalledTimes(1); + expect(mockSearch).toHaveBeenCalledWith(expect.objectContaining({offset: 0, searchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT})); + }); + + it('asks the server for the next page when the list reaches its end', async () => { + // The cursor only pages once the device already holds a full page of live rows. + await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE + 10); + await seedTodoSnapshot(true); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + mockSearch.mockClear(); + + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + expect(mockSearch).toHaveBeenCalledWith(expect.objectContaining({offset: CONST.SEARCH.RESULTS_PAGE_SIZE})); + }); + + it('shows the next rows only once the server answers their page, and ignores ends meanwhile', async () => { + const rowCount = CONST.SEARCH.RESULTS_PAGE_SIZE + 20; + await seedTodoReports(rowCount); + await seedTodoSnapshot(true); + searchWritesLoadingState(); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + mockSearch.mockClear(); + + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // The page is on the wire: the cap holds at the rows already answered. + expect(renderedRowKeys()).toHaveLength(CONST.SEARCH.RESULTS_PAGE_SIZE); + + // onEndReached refires under the loading footer; the second page must not chase past the one in flight. + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + expect(mockSearch).toHaveBeenCalledTimes(1); + + await answerTodoPage(CONST.SEARCH.RESULTS_PAGE_SIZE); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + expect(renderedRowKeys()).toHaveLength(rowCount); + expect(mockSearch).toHaveBeenCalledTimes(1); + }); + + it('pages in live rows past the cap locally once the server reports no more pages', async () => { + const rowCount = CONST.SEARCH.RESULTS_PAGE_SIZE + 20; + await seedTodoReports(rowCount); + await seedTodoSnapshot(false); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + expect(renderedRowKeys()).toHaveLength(CONST.SEARCH.RESULTS_PAGE_SIZE); + mockSearch.mockClear(); + + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // The Onyx scan still holds rows past the cap: reveal another page without the server. + expect(renderedRowKeys()).toHaveLength(rowCount); + expect(mockSearch).not.toHaveBeenCalled(); + + // Nothing left to reveal, so a further end changes nothing. + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + expect(renderedRowKeys()).toHaveLength(rowCount); + expect(mockSearch).not.toHaveBeenCalled(); + }); + + it('retries the failed page offset instead of skipping ahead past it', async () => { + await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE * 2 + 20); + // The live response drops errors, so a failed page only leaves its response code behind. + await seedTodoSnapshot(true, {offset: CONST.SEARCH.RESULTS_PAGE_SIZE, responseJsonCode: 500}); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + mockSearch.mockClear(); + + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + expect(mockSearch).toHaveBeenCalledWith(expect.objectContaining({offset: CONST.SEARCH.RESULTS_PAGE_SIZE})); + expect(mockSearch.mock.calls.some(([params]) => params?.offset === CONST.SEARCH.RESULTS_PAGE_SIZE * 2)).toBe(false); + }); + + it('retries a failed page only on an end the user scrolled to, not on every rebuild of the rows', async () => { + // Given a to-do tab whose second page failed and keeps failing + await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE * 2); + await seedTodoSnapshot(true, {offset: CONST.SEARCH.RESULTS_PAGE_SIZE, responseJsonCode: 500}); + searchWritesLoadingState(); + const failTodoPage = () => + act(async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.SNAPSHOT}${todoQueryJSON?.hash}`, { + search: {isLoading: false, state: CONST.SEARCH.SNAPSHOT_STATE.LOADED, responseJsonCode: 500}, + }); + }); + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + mockSearch.mockClear(); + + // When the list reaches its end and the retry fails too, then the list reports more ends without a scroll, as it does when a report in it changes + await act(async () => { + listProps.onEndReached?.(); + }); + await failTodoPage(); + for (let i = 0; i < 2; i++) { + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + } + + // Then only the first end retries the page + expect(mockSearch).toHaveBeenCalledTimes(1); + + // When the user scrolls back to the end + await act(async () => { + listProps.onViewableItemsChanged?.(); + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then that end retries the page again + expect(mockSearch).toHaveBeenCalledTimes(2); + expect(mockSearch).toHaveBeenLastCalledWith(expect.objectContaining({offset: CONST.SEARCH.RESULTS_PAGE_SIZE})); + }); + + it('saves the page it has for report navigation to page on from', async () => { + await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE + 10); + await seedTodoSnapshot(true); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + const report = lastWriteActionsRender()?.filteredData.at(0); + await act(async () => { + if (!report) { + return; + } + listProps.onSelectRow?.(report); + }); + + expect(await getOnyxValue(ONYXKEYS.REPORT_NAVIGATION_LAST_SEARCH_QUERY)).toEqual(expect.objectContaining({offset: CONST.SEARCH.RESULTS_PAGE_SIZE})); + }); + + it('holds a page reached offline and requests it once back online', async () => { + await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE + 10); + await seedTodoSnapshot(true); + + // Offline before the list mounts, so the paging closure sees it. + mockUseNetwork.mockReturnValue({isOffline: true} as ReturnType); + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + mockSearch.mockClear(); + + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Nothing goes on the wire offline: the request would only fail and leave an error on the snapshot. + expect(mockSearch).not.toHaveBeenCalled(); + + mockUseNetwork.mockReturnValue({isOffline: false} as ReturnType); + await act(async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.SNAPSHOT}${todoQueryJSON?.hash}`, {search: {isLoading: true}}); + }); + await act(async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.SNAPSHOT}${todoQueryJSON?.hash}`, {search: {isLoading: false}}); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + expect(mockSearch).toHaveBeenCalledWith(expect.objectContaining({offset: CONST.SEARCH.RESULTS_PAGE_SIZE})); + }); + + it('renders a selected report the cap would cut off, so selection only holds rows the user can see', async () => { + // Given a to-do tab holding more reports than one page, so the cap cuts the rest off + const rowCount = CONST.SEARCH.RESULTS_PAGE_SIZE + 10; + await seedTodoReports(rowCount); + await seedTodoSnapshot(true); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + const renderedKeys = new Set(renderedRowKeys()); + expect(renderedKeys.size).toBe(CONST.SEARCH.RESULTS_PAGE_SIZE); + const cutOffKey = Array.from({length: rowCount}, (_value, index) => `todo_${index + 1}`).find((key) => !renderedKeys.has(key)) ?? ''; + + // When a report below the cap is ticked, which a bulk action or a restored selection can do + await act(async () => { + lastWriteActionsRender()?.applySelection(() => ({[cutOffKey]: createMock({isSelected: true})})); + }); + + // Then the list renders down to that report, because the selection sync drops any ticked row it cannot see + expect(renderedRowKeys()).toContain(cutOffKey); + }); + + it('waits for a page already running at mount instead of revealing its rows or skipping past it', async () => { + // Given a to-do tab remounting while its second page is still on the wire + const rowCount = CONST.SEARCH.RESULTS_PAGE_SIZE + 20; + await seedTodoReports(rowCount); + await seedTodoSnapshot(true, {offset: CONST.SEARCH.RESULTS_PAGE_SIZE, isLoading: true, state: CONST.SEARCH.SNAPSHOT_STATE.LOADING}); + + // When the screen mounts + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then the rows stay at one page, because the page covering the rest hasn't answered yet + expect(renderedRowKeys()).toHaveLength(CONST.SEARCH.RESULTS_PAGE_SIZE); + + // When the list reaches its end while that page is still running + mockSearch.mockClear(); + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then it re-asks the running page, in case a reload stranded it, and never the page after, which would leave it unaccounted for + expect(mockSearch).toHaveBeenCalledWith(expect.objectContaining({offset: CONST.SEARCH.RESULTS_PAGE_SIZE})); + expect(mockSearch.mock.calls.some(([params]) => (params?.offset ?? 0) > CONST.SEARCH.RESULTS_PAGE_SIZE)).toBe(false); + + // When the running page answers + await answerTodoPage(CONST.SEARCH.RESULTS_PAGE_SIZE); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then the rows it covers appear + expect(renderedRowKeys()).toHaveLength(rowCount); + }); + + it('does not re-ask a later page once the page adopted at mount has settled', async () => { + // Given a to-do tab remounting while its second page is still on the wire + await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE * 3); + await seedTodoSnapshot(true, {offset: CONST.SEARCH.RESULTS_PAGE_SIZE, isLoading: true, state: CONST.SEARCH.SNAPSHOT_STATE.LOADING}); + searchWritesLoadingState(); + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // When that page answers before the list ever reaches its end, and the next end asks for the page after it + await answerTodoPage(CONST.SEARCH.RESULTS_PAGE_SIZE, true); + mockSearch.mockClear(); + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + expect(mockSearch).toHaveBeenCalledTimes(1); + + // When the list reaches its end again while that page is running + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then it is not asked for again, because only the adopted page could have been stranded by a reload + expect(mockSearch).toHaveBeenCalledTimes(1); + }); + + it('hides the loading footer once the page it waits for fails', async () => { + // Given a to-do tab whose next page is on its way + await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE + 20); + await seedTodoSnapshot(true); + searchWritesLoadingState(); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + expect(listProps.ListFooterComponent).toBeTruthy(); + + // When that page fails, which settles the snapshot with only a response code behind + await act(async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.SNAPSHOT}${todoQueryJSON?.hash}`, { + search: {isLoading: false, state: CONST.SEARCH.SNAPSHOT_STATE.LOADED, responseJsonCode: 500}, + }); + }); + + // Then the footer goes away and the rows stay at the page they had, since nothing is loading any more + expect(listProps.ListFooterComponent).toBeFalsy(); + expect(renderedRowKeys()).toHaveLength(CONST.SEARCH.RESULTS_PAGE_SIZE); + }); + + it('keeps the loading footer hidden when the list ends offline', async () => { + // Given a to-do tab with more rows to page, opened offline + await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE + 20); + await seedTodoSnapshot(true); + mockUseNetwork.mockReturnValue({isOffline: true} as ReturnType); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // When the list reaches its end + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then no footer shows, because the page is only held for reconnect, not on its way + expect(listProps.ListFooterComponent).toBeFalsy(); + }); + + it('asks again at the next end for a page search() never sent', async () => { + // Given a to-do tab where search() drops the next page without writing anything, as it does for a request it skips + await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE * 2 + 20); + await seedTodoSnapshot(true); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + expect(mockSearch).toHaveBeenCalledWith(expect.objectContaining({offset: CONST.SEARCH.RESULTS_PAGE_SIZE})); + mockSearch.mockClear(); + + // When the list reaches its end again + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then the same page is asked for again rather than the one after, which would leave a hole in the list + expect(mockSearch).toHaveBeenCalledWith(expect.objectContaining({offset: CONST.SEARCH.RESULTS_PAGE_SIZE})); + expect(mockSearch.mock.calls.some(([params]) => (params?.offset ?? 0) > CONST.SEARCH.RESULTS_PAGE_SIZE)).toBe(false); + }); + + it('does not fetch pages already on screen again after a first-page refresh rewinds the snapshot', async () => { + // Given a to-do tab whose second page already answered + await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE * 3 + 10); + await seedTodoSnapshot(true); + searchWritesLoadingState(); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + await act(async () => { + listProps.onEndReached?.(); + }); + await answerTodoPage(CONST.SEARCH.RESULTS_PAGE_SIZE, true); + await act(async () => { + jest.advanceTimersByTime(0); + }); + expect(renderedRowKeys()).toHaveLength(CONST.SEARCH.RESULTS_PAGE_SIZE * 2); + mockSearch.mockClear(); + + // When a bulk action refreshes the first page, which rewinds the snapshot offset to 0 + await act(async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.SNAPSHOT}${todoQueryJSON?.hash}`, {search: {offset: 0, state: CONST.SEARCH.SNAPSHOT_STATE.LOADING, isLoading: true}}); + }); + await answerTodoPage(0, true); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then nothing is fetched again and the rows stay, because live rows are still in Onyx + expect(mockSearch).not.toHaveBeenCalled(); + expect(renderedRowKeys()).toHaveLength(CONST.SEARCH.RESULTS_PAGE_SIZE * 2); + + // When the list reaches its end + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then it asks for the page after the rows on screen, not the ones the refresh rewound past + expect(mockSearch).toHaveBeenCalledTimes(1); + expect(mockSearch).toHaveBeenCalledWith(expect.objectContaining({offset: CONST.SEARCH.RESULTS_PAGE_SIZE * 2})); + }); + + it('counts a page that lands after a remount rewound the snapshot to the first page', async () => { + // Given a to-do tab whose second page is on the wire + await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE * 3); + await seedTodoSnapshot(true); + searchWritesLoadingState(); + const snapshotKey = `${ONYXKEYS.COLLECTION.SNAPSHOT}${todoQueryJSON?.hash}` as const; + const firstRender = renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + await act(async () => { + listProps.onEndReached?.(); + }); + + // When the tab remounts and a first-page request rewinds the snapshot before that page answers + firstRender.unmount(); + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + await act(async () => { + await Onyx.merge(snapshotKey, {search: {offset: 0, state: CONST.SEARCH.SNAPSHOT_STATE.LOADING, isLoading: true}}); + }); + + // And the second page answers, then the first page, as the response and finallyData of each request write them + for (const pageOffset of [CONST.SEARCH.RESULTS_PAGE_SIZE, 0]) { + await act(async () => { + await Onyx.merge(snapshotKey, {search: {offset: pageOffset, hasMoreResults: true}}); + await Onyx.merge(snapshotKey, {search: {isLoading: false, state: CONST.SEARCH.SNAPSHOT_STATE.LOADED}}); + }); + } + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then the second page's rows are on screen, because its response brings its own offset back before the first page rewinds it + expect(renderedRowKeys()).toHaveLength(CONST.SEARCH.RESULTS_PAGE_SIZE * 2); + }); + + it('keeps paging while another search on the same tab is running', async () => { + // Given a to-do tab whose second page already answered + await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE * 2 + 20); + await seedTodoSnapshot(true); + searchWritesLoadingState(); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + await act(async () => { + listProps.onEndReached?.(); + }); + await answerTodoPage(CONST.SEARCH.RESULTS_PAGE_SIZE, true); + await act(async () => { + jest.advanceTimersByTime(0); + }); + mockSearch.mockClear(); + + // When a first-page refresh is on the wire, which parks the shared snapshot in its loading state + await act(async () => { + await Onyx.merge(`${ONYXKEYS.COLLECTION.SNAPSHOT}${todoQueryJSON?.hash}`, {search: {offset: 0, state: CONST.SEARCH.SNAPSHOT_STATE.LOADING, isLoading: true}}); + }); + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then the next page is still asked for, because the running request is not the page the list is waiting on + expect(mockSearch).toHaveBeenCalledWith(expect.objectContaining({offset: CONST.SEARCH.RESULTS_PAGE_SIZE * 2})); + }); + + it('waits for the first page to answer before paging in cached rows locally', async () => { + // Given a first visit to a to-do tab, where the first page is still on the wire and the server hasn't said whether it has more + const rowCount = CONST.SEARCH.RESULTS_PAGE_SIZE + 20; + await seedTodoReports(rowCount); + await act(async () => { + await Onyx.set(`${ONYXKEYS.COLLECTION.SNAPSHOT}${todoQueryJSON?.hash}`, { + search: {type: CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT, offset: 0, hash: todoQueryJSON?.hash, isLoading: true, state: CONST.SEARCH.SNAPSHOT_STATE.LOADING}, + }); + }); + + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + mockSearch.mockClear(); + + // When the list reaches its end + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then the rows stay at one page, because `hasMoreResults` is only a default until the server answers + expect(renderedRowKeys()).toHaveLength(CONST.SEARCH.RESULTS_PAGE_SIZE); + expect(mockSearch).not.toHaveBeenCalled(); + + // When the first page answers that the server has nothing more + await answerTodoPage(0, false); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // Then the end the list already reached pages the cached rows in, without waiting for another end + expect(renderedRowKeys()).toHaveLength(rowCount); + expect(mockSearch).not.toHaveBeenCalled(); + }); + + it('does not page in cached rows locally on a tab no request has gone out for yet', async () => { + // Given a to-do tab this device has never opened, viewed offline, so there is no snapshot and no request on the wire + const rowCount = CONST.SEARCH.RESULTS_PAGE_SIZE * 2 + 7; + await seedTodoReports(rowCount); + mockUseNetwork.mockReturnValue({isOffline: true} as ReturnType); + renderPage(TODO_QUERY); + await act(async () => { + jest.advanceTimersByTime(0); + }); + + // When the list reaches its end twice + for (let i = 0; i < 2; i++) { + await act(async () => { + listProps.onEndReached?.(); + }); + await act(async () => { + jest.advanceTimersByTime(0); + }); + } + + // Then the rows stay at one page, because the missing snapshot's `hasMoreResults: false` is a default, not the server's answer + expect(renderedRowKeys()).toHaveLength(CONST.SEARCH.RESULTS_PAGE_SIZE); + }); + }); }); diff --git a/tests/unit/Search/SearchResultsProviderLiveLoadingTest.tsx b/tests/unit/Search/SearchResultsProviderLiveLoadingTest.tsx new file mode 100644 index 000000000000..0bc1c4fbce45 --- /dev/null +++ b/tests/unit/Search/SearchResultsProviderLiveLoadingTest.tsx @@ -0,0 +1,69 @@ +import {renderHook} from '@testing-library/react-native'; + +import {SearchResultsContext} from '@components/Search/SearchContextDefinitions'; +import SearchResultsProvider from '@components/Search/SearchResultsProvider'; + +import CONST from '@src/CONST'; + +import React, {use} from 'react'; + +const mockUseOnyx = jest.fn(); +jest.mock('react-native-onyx', () => ({ + __esModule: true, + ...jest.requireActual>('react-native-onyx'), + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + useOnyx: (...args: unknown[]) => mockUseOnyx(...args), +})); + +let mockIsTodoSearch = true; +jest.mock('@libs/SearchUIUtils', () => ({ + isTodoSearch: () => mockIsTodoSearch, + getTransactionsByReportID: () => ({}), + getViolationsFromSearchData: () => ({}), +})); + +jest.mock('@hooks/useTodoSearchResults', () => ({ + __esModule: true, + default: () => ({data: {}, metadata: {count: 0, total: 0, currency: undefined}}), +})); + +jest.mock('@components/Search/SearchContext', () => ({ + useSearchQueryContext: () => ({ + currentSearchHash: 1, + currentSearchKey: 'approve', + currentSearchQueryJSON: {recentSearchHash: 1}, + suggestedSearches: {}, + }), +})); + +function renderProvider(snapshotSearch: Record) { + mockUseOnyx.mockReturnValue([{search: snapshotSearch, data: {}}]); + // read the context object directly, SearchContext is mocked for useSearchQueryContext + return renderHook(() => use(SearchResultsContext), { + wrapper: ({children}: {children: React.ReactNode}) => {children}, + }); +} + +describe('SearchResultsProvider live to-do loading flag', () => { + beforeEach(() => { + mockUseOnyx.mockReset(); + mockIsTodoSearch = true; + }); + + it('forces isLoading off for a live to-do search even when the snapshot left it stuck true', () => { + // a stale true survives a reload and would strand the skeletons + const {result} = renderProvider({isLoading: true, state: CONST.SEARCH.SNAPSHOT_STATE.LOADING, offset: CONST.SEARCH.RESULTS_PAGE_SIZE, hash: 1}); + + expect(result.current.shouldUseLiveData).toBe(true); + expect(result.current.currentSearchResults?.search.isLoading).toBe(false); + expect(result.current.currentSearchResults?.search.offset).toBe(CONST.SEARCH.RESULTS_PAGE_SIZE); + }); + + it('still reports live results when the snapshot has none, so the empty state wins over a skeleton', () => { + const {result} = renderProvider({isLoading: false, offset: 0, hash: 1}); + + expect(result.current.currentSearchResults?.search.isLoading).toBe(false); + expect(result.current.currentSearchResults?.search.hasResults).toBe(false); + expect(result.current.currentSearchResults?.data).toEqual({}); + }); +}); diff --git a/tests/unit/Search/useLiveRowLimitTest.ts b/tests/unit/Search/useLiveRowLimitTest.ts new file mode 100644 index 000000000000..dc979a8e247a --- /dev/null +++ b/tests/unit/Search/useLiveRowLimitTest.ts @@ -0,0 +1,121 @@ +import {act, renderHook} from '@testing-library/react-native'; + +import useLiveRowLimit from '@components/Search/hooks/useLiveRowLimit'; + +import CONST from '@src/CONST'; + +const PAGE: number = CONST.SEARCH.RESULTS_PAGE_SIZE; + +describe('useLiveRowLimit', () => { + it('starts a fresh mount at one page', () => { + // is keyed by hash, so a new query must not inherit the old cap + const {result} = renderHook(() => useLiveRowLimit(0, false)); + + expect(result.current.liveRowLimit).toBe(PAGE); + }); + + it('holds the cap at the cursor while a page is in flight, then releases it', () => { + const {result, rerender} = renderHook(({offset, hasUnconfirmedPage}) => useLiveRowLimit(offset, hasUnconfirmedPage), {initialProps: {offset: PAGE, hasUnconfirmedPage: true}}); + + // offset is written when the request fires, so the pending page must not reveal early + expect(result.current.liveRowLimit).toBe(PAGE); + + rerender({offset: PAGE, hasUnconfirmedPage: false}); + + expect(result.current.liveRowLimit).toBe(PAGE * 2); + }); + + it('never lowers the cap when a refresh rewinds the cursor to 0', () => { + const {result, rerender} = renderHook(({offset, hasUnconfirmedPage}) => useLiveRowLimit(offset, hasUnconfirmedPage), {initialProps: {offset: PAGE, hasUnconfirmedPage: false}}); + + expect(result.current.liveRowLimit).toBe(PAGE * 2); + + // a first-page refresh resets offset, but those rows are still in Onyx + rerender({offset: 0, hasUnconfirmedPage: true}); + + expect(result.current.liveRowLimit).toBe(PAGE * 2); + + rerender({offset: 0, hasUnconfirmedPage: false}); + + expect(result.current.liveRowLimit).toBe(PAGE * 2); + }); + + it('floors at one page while the very first request is in flight', () => { + const {result} = renderHook(() => useLiveRowLimit(0, true)); + + expect(result.current.liveRowLimit).toBe(PAGE); + }); + + it('treats a missing cursor as offset 0', () => { + const {result} = renderHook(() => useLiveRowLimit(undefined, undefined)); + + expect(result.current.liveRowLimit).toBe(PAGE); + }); + + it('raises the cap by one page when the reveal is bumped past the cursor', () => { + // the server is out of pages, so pages the live rows in itself + const {result, rerender} = renderHook(({offset, hasUnconfirmedPage}) => useLiveRowLimit(offset, hasUnconfirmedPage), {initialProps: {offset: 0, hasUnconfirmedPage: false}}); + + act(() => { + result.current.revealNextPage(); + }); + + rerender({offset: 0, hasUnconfirmedPage: false}); + + expect(result.current.liveRowLimit).toBe(PAGE * 2); + }); + + it('keeps a bumped reveal when the cursor later runs past it', () => { + const {result, rerender} = renderHook(({offset, hasUnconfirmedPage}) => useLiveRowLimit(offset, hasUnconfirmedPage), {initialProps: {offset: 0, hasUnconfirmedPage: false}}); + + act(() => { + result.current.revealNextPage(); + }); + + // a page the server answered anyway moves the cursor past the reveal + rerender({offset: PAGE, hasUnconfirmedPage: false}); + + expect(result.current.liveRowLimit).toBe(PAGE * 2); + + rerender({offset: PAGE * 2, hasUnconfirmedPage: false}); + + expect(result.current.liveRowLimit).toBe(PAGE * 3); + }); + + it('keeps the answered offset when a refresh rewinds the cursor, so paging resumes after the rows on screen', () => { + // Given a tab whose third page already answered + const {result, rerender} = renderHook(({offset, hasUnconfirmedPage}) => useLiveRowLimit(offset, hasUnconfirmedPage), { + initialProps: {offset: PAGE * 2, hasUnconfirmedPage: false}, + }); + expect(result.current.answeredOffset).toBe(PAGE * 2); + + // When a first-page refresh rewinds the snapshot offset and then answers + rerender({offset: 0, hasUnconfirmedPage: true}); + rerender({offset: 0, hasUnconfirmedPage: false}); + + // Then the answered offset stays put, because those pages' rows are still in Onyx and asking for them again adds nothing + expect(result.current.answeredOffset).toBe(PAGE * 2); + }); + + it('does not count a page as answered while it is running or after it failed', () => { + // Given a page on the wire, since search() writes its offset before the response + const {result, rerender} = renderHook(({offset, hasUnconfirmedPage}) => useLiveRowLimit(offset, hasUnconfirmedPage), { + initialProps: {offset: PAGE, hasUnconfirmedPage: true}, + }); + + // Then only the page before it counts as answered + expect(result.current.answeredOffset).toBe(0); + + // When it fails, which parks the offset on the page it never delivered + rerender({offset: PAGE, hasUnconfirmedPage: true}); + + // Then it still doesn't count, so the next request retries it + expect(result.current.answeredOffset).toBe(0); + + // When it answers + rerender({offset: PAGE, hasUnconfirmedPage: false}); + + // Then it counts + expect(result.current.answeredOffset).toBe(PAGE); + }); +}); diff --git a/tests/unit/Search/useSearchSnapshotTest.ts b/tests/unit/Search/useSearchSnapshotTest.ts index 552ce1086644..4aa25273d333 100644 --- a/tests/unit/Search/useSearchSnapshotTest.ts +++ b/tests/unit/Search/useSearchSnapshotTest.ts @@ -1,12 +1,14 @@ import {renderHook} from '@testing-library/react-native'; import useSearchSnapshot from '@components/Search/hooks/useSearchSnapshot'; -import type {SearchQueryJSON} from '@components/Search/types'; +import type {SearchQueryJSON, SelectedTransactionInfo} from '@components/Search/types'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type SearchResults from '@src/types/onyx/SearchResults'; +import createMock from '../../utils/createMock'; + const onyxData: Record = {}; // Aux Onyx reads (cards, bank accounts, etc.) are irrelevant here because getSections is mocked. @@ -16,9 +18,10 @@ jest.mock('@hooks/useOnyx', () => ({ default: (key: string) => mockUseOnyx(key), })); +let mockIsOffline = false; jest.mock('@hooks/useNetwork', () => ({ __esModule: true, - default: () => ({isOffline: false}), + default: () => ({isOffline: mockIsOffline}), })); // Stable object so the returned helpers keep their identity across renders, mirroring the real // useLocalize. The referential-stability test below relies on these not being a memo dependency churn. @@ -92,6 +95,7 @@ jest.mock('@libs/SearchUIUtils', () => ({ getValidGroupBy: (...args: unknown[]) => mockGetValidGroupBy(...args), // eslint-disable-next-line @typescript-eslint/no-unsafe-return isSearchDataLoaded: (...args: unknown[]) => mockIsSearchDataLoaded(...args), + isTransactionGroupListItemType: (item: Record) => 'transactions' in item, })); // The optimistic-tracking hooks are mocked so this suite exercises the hook's WIRING (correct inputs in, @@ -152,6 +156,7 @@ function trackingReturn(searchDataWithOptimisticTransaction: unknown, optimistic describe('useSearchSnapshot', () => { beforeEach(() => { + mockIsOffline = false; for (const key of Object.keys(onyxData)) { delete onyxData[key]; } @@ -430,4 +435,253 @@ describe('useSearchSnapshot', () => { expect(result.current.chartData).toBe(firstChartData); expect(result.current.data).toBe(firstData); }); + + it('caps data at visibleRowLimit while leaving chartData and the row count untouched', () => { + const searchResults = makeSearchResults(); + mockUseOptimisticSearchTracking.mockReturnValue(trackingReturn(searchResults.data)); + const rows = Array.from({length: 5}, (_value, index) => ({transactionID: `${index}`, keyForList: `${index}`})); + mockGetSections.mockReturnValue([rows, rows.length, false]); + mockGetSortedSections.mockReturnValue(rows); + + const {result, rerender} = renderHook((visibleRowLimit?: number) => + useSearchSnapshot({ + queryJSON: makeQueryJSON(), + searchResults, + newSearchResultKeys: undefined, + transactions: undefined, + reportActions: undefined, + visibleRowLimit, + }), + ); + + expect(result.current.data).toHaveLength(5); + + rerender(2); + + expect(result.current.data.map((item) => item.keyForList)).toEqual(['0', '1']); + expect(result.current.chartData).toHaveLength(5); + expect(result.current.filteredDataLength).toBe(5); + + rerender(10); + + // a fresh array here re-renders the list on every pass + expect(result.current.data).toBe(result.current.chartData); + }); + + it('caps filteredData to the rendered rows so bulk actions cannot reach unrendered ones', () => { + const searchResults = makeSearchResults(); + mockUseOptimisticSearchTracking.mockReturnValue(trackingReturn(searchResults.data)); + // live to-do rows, the only ones capped, are report groups + const rows = Array.from({length: 5}, (_value, index) => ({reportID: `${index}`, keyForList: `${index}`, transactions: []})); + mockGetSections.mockReturnValue([rows, rows.length, false]); + // sorted order reverses the section order, so slicing `filteredData` on its own would select the wrong rows + mockGetSortedSections.mockReturnValue([...rows].reverse()); + + const {result} = renderHook(() => + useSearchSnapshot({ + queryJSON: makeQueryJSON(), + searchResults, + newSearchResultKeys: undefined, + transactions: undefined, + reportActions: undefined, + visibleRowLimit: 2, + }), + ); + + expect(result.current.data.map((item) => item.keyForList)).toEqual(['4', '3']); + expect(result.current.filteredData).toEqual(result.current.data); + // uncapped, or the offline reveal would never know there are more cached rows + expect(result.current.filteredDataLength).toBe(5); + }); + + it('leaves filteredData as the unsorted sections when the limit exactly matches the row count', () => { + const searchResults = makeSearchResults(); + mockUseOptimisticSearchTracking.mockReturnValue(trackingReturn(searchResults.data)); + const rows = Array.from({length: 3}, (_value, index) => ({transactionID: `${index}`, keyForList: `${index}`})); + mockGetSections.mockReturnValue([rows, rows.length, false]); + mockGetSortedSections.mockReturnValue([...rows].reverse()); + + const {result} = renderHook(() => + useSearchSnapshot({ + queryJSON: makeQueryJSON(), + searchResults, + newSearchResultKeys: undefined, + transactions: undefined, + reportActions: undefined, + visibleRowLimit: 3, + }), + ); + + // cap only engages above the limit, so filteredData stays the pre-sort sections + expect(result.current.data.map((item) => item.keyForList)).toEqual(['2', '1', '0']); + expect(result.current.filteredData).toBe(rows); + }); + + it('keeps the capped data reference across a rerender at the same limit', () => { + const searchResults = makeSearchResults(); + mockUseOptimisticSearchTracking.mockReturnValue(trackingReturn(searchResults.data)); + const rows = Array.from({length: 5}, (_value, index) => ({transactionID: `${index}`, keyForList: `${index}`})); + mockGetSections.mockReturnValue([rows, rows.length, false]); + mockGetSortedSections.mockReturnValue(rows); + + const {result, rerender} = renderHook(() => + useSearchSnapshot({ + queryJSON: makeQueryJSON(), + searchResults, + newSearchResultKeys: undefined, + transactions: undefined, + reportActions: undefined, + visibleRowLimit: 2, + }), + ); + + const firstData = result.current.data; + + rerender({}); + + // slice is a fresh array per call, so losing the memo re-renders the whole list every pass + expect(result.current.data).toBe(firstData); + }); + + it('caps grouped rows by group, keeping unrendered groups out of selection', () => { + const searchResults = makeSearchResults(); + mockUseOptimisticSearchTracking.mockReturnValue(trackingReturn(searchResults.data)); + const groups = Array.from({length: 3}, (_value, index) => ({ + groupID: `group${index}`, + keyForList: `group${index}`, + transactions: [{transactionID: `${index}-a`}, {transactionID: `${index}-b`}], + })); + mockGetSections.mockReturnValue([groups, groups.length, false]); + mockGetSortedSections.mockReturnValue(groups); + + const {result} = renderHook(() => + useSearchSnapshot({ + queryJSON: makeQueryJSON({groupBy: CONST.SEARCH.GROUP_BY.FROM}), + searchResults, + newSearchResultKeys: undefined, + transactions: undefined, + reportActions: undefined, + visibleRowLimit: 2, + }), + ); + + expect(result.current.data.map((item) => item.keyForList)).toEqual(['group0', 'group1']); + // cap slices whole groups, so group2's transactions must be unreachable for bulk actions + expect(result.current.filteredData).toEqual(groups.slice(0, 2).map((group) => expect.objectContaining({keyForList: group.keyForList, transactions: group.transactions}))); + }); + + it('keeps a highlighted row past visibleRowLimit on screen', () => { + // Given a live list capped at two groups, where a new expense just landed in the last group + const searchResults = makeSearchResults(); + mockUseOptimisticSearchTracking.mockReturnValue(trackingReturn(searchResults.data)); + const groups = Array.from({length: 5}, (_value, index) => ({ + groupID: `group${index}`, + keyForList: `group${index}`, + transactions: [{transactionID: `${index}`}], + })); + mockGetSections.mockReturnValue([groups, groups.length, false]); + mockGetSortedSections.mockReturnValue(groups); + + // When the snapshot is projected with that expense queued for highlight + const {result} = renderHook(() => + useSearchSnapshot({ + queryJSON: makeQueryJSON({groupBy: CONST.SEARCH.GROUP_BY.FROM}), + searchResults, + newSearchResultKeys: new Set([`${ONYXKEYS.COLLECTION.TRANSACTION}4`]), + transactions: undefined, + reportActions: undefined, + visibleRowLimit: 2, + }), + ); + + // Then the highlighted group still renders, or the scroll-to-new-expense has no row to land on + expect(result.current.data.map((item) => item.keyForList)).toContain('group4'); + }); + + it('does not spend visibleRowLimit on rows being deleted online', () => { + // Given a live list capped at two rows, whose first two rows are being deleted while online + const searchResults = makeSearchResults(); + mockUseOptimisticSearchTracking.mockReturnValue(trackingReturn(searchResults.data)); + const rows = Array.from({length: 5}, (_value, index) => ({ + transactionID: `${index}`, + keyForList: `${index}`, + pendingAction: index < 2 ? CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE : undefined, + })); + mockGetSections.mockReturnValue([rows, rows.length, false]); + mockGetSortedSections.mockReturnValue(rows); + + // When the snapshot is projected under the cap + const {result} = renderHook(() => + useSearchSnapshot({ + queryJSON: makeQueryJSON(), + searchResults, + newSearchResultKeys: undefined, + transactions: undefined, + reportActions: undefined, + visibleRowLimit: 2, + }), + ); + + // Then two rows the user can see still render, because online the deleted rows are hidden and would leave the page short + const shownRows = result.current.data.filter((item) => item.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE); + expect(shownRows.map((item) => item.keyForList)).toEqual(['2', '3']); + }); + + it('keeps a group past visibleRowLimit on screen while one of its expenses is ticked', () => { + // Given a live list capped at two groups, where an expense inside the last group is ticked + const searchResults = makeSearchResults(); + mockUseOptimisticSearchTracking.mockReturnValue(trackingReturn(searchResults.data)); + const groups = Array.from({length: 5}, (_value, index) => ({ + groupID: `group${index}`, + keyForList: `group${index}`, + transactions: [{transactionID: `${index}`, keyForList: `transaction${index}`}], + })); + mockGetSections.mockReturnValue([groups, groups.length, false]); + mockGetSortedSections.mockReturnValue(groups); + + // When the snapshot is projected with that selection + const {result} = renderHook(() => + useSearchSnapshot({ + queryJSON: makeQueryJSON({groupBy: CONST.SEARCH.GROUP_BY.FROM}), + searchResults, + newSearchResultKeys: undefined, + transactions: undefined, + reportActions: undefined, + visibleRowLimit: 2, + selectedTransactions: {transaction4: createMock({isSelected: true})}, + }), + ); + + // Then the list renders down to that group, because the selection sync drops any tick it cannot see + expect(result.current.data.map((item) => item.keyForList)).toEqual(['group0', 'group1', 'group2', 'group3', 'group4']); + }); + + it('counts rows being deleted against visibleRowLimit while offline, where they show struck through', () => { + // Given an offline live list capped at two rows, whose first two rows are being deleted + mockIsOffline = true; + const searchResults = makeSearchResults(); + mockUseOptimisticSearchTracking.mockReturnValue(trackingReturn(searchResults.data)); + const rows = Array.from({length: 5}, (_value, index) => ({ + transactionID: `${index}`, + keyForList: `${index}`, + pendingAction: index < 2 ? CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE : undefined, + })); + mockGetSections.mockReturnValue([rows, rows.length, false]); + mockGetSortedSections.mockReturnValue(rows); + + // When the snapshot is projected under the cap + const {result} = renderHook(() => + useSearchSnapshot({ + queryJSON: makeQueryJSON(), + searchResults, + newSearchResultKeys: undefined, + transactions: undefined, + reportActions: undefined, + visibleRowLimit: 2, + }), + ); + + // Then the two deleted rows fill the page, because offline the user sees them + expect(result.current.data.map((item) => item.keyForList)).toEqual(['0', '1']); + }); }); diff --git a/tests/unit/hooks/useSearchPageSetup.test.ts b/tests/unit/hooks/useSearchPageSetup.test.ts index 4ecbb0baba5e..dbee71f6e904 100644 --- a/tests/unit/hooks/useSearchPageSetup.test.ts +++ b/tests/unit/hooks/useSearchPageSetup.test.ts @@ -11,10 +11,11 @@ import type * as NativeNavigation from '@react-navigation/native'; const mockSearch = jest.fn(); let mockCurrentSearchResults: SearchResults | undefined; +let mockShouldUseLiveData = false; jest.mock('@components/Search/SearchContext', () => ({ useSearchQueryContext: () => ({currentSearchKey: 'expenses'}), - useSearchResultsContext: () => ({currentSearchResults: mockCurrentSearchResults, shouldUseLiveData: false}), + useSearchResultsContext: () => ({currentSearchResults: mockCurrentSearchResults, shouldUseLiveData: mockShouldUseLiveData}), useSearchSelectionActions: () => ({clearSelectedTransactions: jest.fn()}), useSearchSelectionContext: () => ({areAllMatchingItemsSelected: false}), })); @@ -88,6 +89,7 @@ function getQueryJSON() { describe('useSearchPageSetup', () => { beforeEach(() => { mockSearch.mockClear(); + mockShouldUseLiveData = false; }); it('retries an unresolved search when temporary search prevention clears', async () => { @@ -128,6 +130,36 @@ describe('useSearchPageSetup', () => { expect(mockSearch).not.toHaveBeenCalled(); }); + it('does not fetch a first page for a live to-do tab with nothing stranded', async () => { + const queryJSON = getQueryJSON(); + mockShouldUseLiveData = true; + mockCurrentSearchResults = makeCachedSearchResults(queryJSON.hash, false, CONST.SEARCH.SNAPSHOT_STATE.LOADED); + + renderHook(() => useSearchPageSetup(queryJSON)); + + await Promise.resolve(); + expect(mockSearch).not.toHaveBeenCalled(); + }); + + it('never restarts a stranded page on a live to-do tab; paging owns its own requests', async () => { + const queryJSON = getQueryJSON(); + mockShouldUseLiveData = true; + mockCurrentSearchResults = makeCachedSearchResults(queryJSON.hash, true, CONST.SEARCH.SNAPSHOT_STATE.LOADING, CONST.SEARCH.RESULTS_PAGE_SIZE); + + const {rerender} = renderHook( + ({isLoading}) => { + mockCurrentSearchResults = makeCachedSearchResults(queryJSON.hash, isLoading, CONST.SEARCH.SNAPSHOT_STATE.LOADING, CONST.SEARCH.RESULTS_PAGE_SIZE); + useSearchPageSetup(queryJSON); + }, + {initialProps: {isLoading: true}}, + ); + + await Promise.resolve(); + rerender({isLoading: false}); + await Promise.resolve(); + expect(mockSearch).not.toHaveBeenCalled(); + }); + it('does not retry a cached snapshot whose terminal state is loaded when the legacy isLoading flag is stale', async () => { const queryJSON = getQueryJSON(); mockCurrentSearchResults = makeCachedSearchResults(queryJSON.hash, true, CONST.SEARCH.SNAPSHOT_STATE.LOADED);