diff --git a/src/components/Navigation/SearchSidebar.tsx b/src/components/Navigation/SearchSidebar.tsx index 8b3f14f7e499..4d463a0607aa 100644 --- a/src/components/Navigation/SearchSidebar.tsx +++ b/src/components/Navigation/SearchSidebar.tsx @@ -1,7 +1,7 @@ import type {ParamListBase} from '@react-navigation/native'; -import React, {useEffect} from 'react'; +import React from 'react'; import {View} from 'react-native'; -import {useSearchActionsContext, useSearchStateContext} from '@components/Search/SearchContext'; +import {useSearchStateContext} from '@components/Search/SearchContext'; import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; @@ -27,22 +27,12 @@ function SearchSidebar({state}: SearchSidebarProps) { const route = state.routes.at(-1); const params = route?.params as SearchFullscreenNavigatorParamList[typeof SCREENS.SEARCH.ROOT] | undefined; - const {lastSearchType, currentSearchResults} = useSearchStateContext(); - const {setLastSearchType} = useSearchActionsContext(); + const {currentSearchResults} = useSearchStateContext(); const queryJSON = params?.q ? buildSearchQueryJSON(params.q, params.rawQuery) : undefined; - const searchType = currentSearchResults?.search?.type; const isSearchLoading = currentSearchResults?.search?.isLoading; - useEffect(() => { - if (!searchType) { - return; - } - - setLastSearchType(searchType); - }, [lastSearchType, queryJSON, setLastSearchType, searchType]); - const shouldShowLoadingState = route?.name === SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT ? false : !isOffline && !!isSearchLoading; if (shouldUseNarrowLayout) { diff --git a/src/components/Search/SearchContext.tsx b/src/components/Search/SearchContext.tsx index c392aed7c72b..2c7e4f8f8602 100644 --- a/src/components/Search/SearchContext.tsx +++ b/src/components/Search/SearchContext.tsx @@ -1,9 +1,13 @@ -import React, {useContext, useLayoutEffect, useRef, useState} from 'react'; +import React, {useContext, useEffect, useLayoutEffect, useRef, useState} from 'react'; // We need direct access to useOnyx from react-native-onyx to avoid circular dependencies in SearchContext // eslint-disable-next-line no-restricted-imports import {useOnyx} from 'react-native-onyx'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; +import useFilterFormValues from '@hooks/useFilterFormValues'; +import useMobileSelectionMode from '@hooks/useMobileSelectionMode'; +import useSearchShouldCalculateTotals from '@hooks/useSearchShouldCalculateTotals'; import useTodos from '@hooks/useTodos'; +import {updateAdvancedFilters} from '@libs/actions/Search'; import {isMoneyRequestReport} from '@libs/ReportUtils'; import {getSuggestedSearches, isTodoSearch, isTransactionListItemType, isTransactionReportGroupListItemType} from '@libs/SearchUIUtils'; import type {SearchKey} from '@libs/SearchUIUtils'; @@ -51,7 +55,11 @@ const defaultSearchStateContext: SearchStateContextValue = { shouldShowSelectAllMatchingItems: false, shouldShowFiltersBarLoading: false, currentSearchResults: undefined, + lastNonEmptySearchResults: undefined, shouldUseLiveData: false, + isMobileSelectionModeEnabled: false, + shouldShowFooter: false, + footerMetadata: undefined, }; const defaultSearchActionsContext: SearchActionsContextValue = { @@ -118,6 +126,30 @@ function SearchContextProvider({children}: ChildrenProps) { const currentSearchResults = getCurrentSearchResults(); + const [lastNonEmptySearchResults, setLastNonEmptySearchResults] = useState(undefined); + useLayoutEffect(() => { + if (!currentSearchResults?.data) { + return; + } + // eslint-disable-next-line react-hooks/set-state-in-effect + setLastNonEmptySearchResults(currentSearchResults); + }, [currentSearchResults]); + + const currentSearchType = currentSearchResults?.search?.type; + useLayoutEffect(() => { + if (!currentSearchType) { + return; + } + // eslint-disable-next-line react-hooks/set-state-in-effect + setLastSearchType(currentSearchType); + }, [currentSearchType]); + + const {currentSearchQueryJSON} = searchContextData; + const filterFormValues = useFilterFormValues(currentSearchQueryJSON); + useEffect(() => { + updateAdvancedFilters(filterFormValues, true); + }, [filterFormValues]); + const setCurrentSearchHashAndKey = (searchHash: number, recentHash: number, searchKey: SearchKey | undefined) => { setSearchContextData((prevState) => { if (searchHash === prevState.currentSearchHash && recentHash === prevState.currentRecentSearchHash && searchKey === prevState.currentSearchKey) { @@ -273,14 +305,26 @@ function SearchContextProvider({children}: ChildrenProps) { })); }; + const isMobileSelectionModeEnabled = useMobileSelectionMode(clearSelectedTransactions); + + const footerSearchResults = currentSearchResults?.data ? currentSearchResults : lastNonEmptySearchResults; + const footerMetadata = footerSearchResults?.search; + const selectedTransactionsKeys = Object.keys(selectedTransactions ?? {}); + const shouldAllowFooterTotals = useSearchShouldCalculateTotals(currentSearchKey, currentSearchQueryJSON?.hash, true); + const shouldShowFooter = selectedTransactionsKeys.length > 0 || (shouldAllowFooterTotals && !!footerMetadata?.count); + const searchStateContextValue: SearchStateContextValue = { ...searchContextData, currentSearchResults, + lastNonEmptySearchResults, shouldUseLiveData, shouldShowFiltersBarLoading, lastSearchType, shouldShowSelectAllMatchingItems, areAllMatchingItemsSelected, + isMobileSelectionModeEnabled, + shouldShowFooter, + footerMetadata, }; const searchActionsContextValue: SearchActionsContextValue = { diff --git a/src/components/Search/SearchPageFooter.tsx b/src/components/Search/SearchPageFooter.tsx index 95ba35a3214d..52f619287e7d 100644 --- a/src/components/Search/SearchPageFooter.tsx +++ b/src/components/Search/SearchPageFooter.tsx @@ -4,28 +4,54 @@ import Text from '@components/Text'; import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; +import useSearchShouldCalculateTotals from '@hooks/useSearchShouldCalculateTotals'; import useStyleUtils from '@hooks/useStyleUtils'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; import {convertToDisplayString} from '@libs/CurrencyUtils'; +import CONST from '@src/CONST'; +import {useSearchStateContext} from './SearchContext'; -type SearchPageFooterProps = { - count: number | undefined; - total: number | undefined; - currency: string | undefined; -}; - -function SearchPageFooter({count, total, currency}: SearchPageFooterProps) { +function SearchPageFooter() { const theme = useTheme(); const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); const {translate} = useLocalize(); const {isOffline} = useNetwork(); - const {shouldUseNarrowLayout} = useResponsiveLayout(); + const {selectedTransactions, areAllMatchingItemsSelected, currentSearchKey, currentSearchHash, shouldShowFooter, footerMetadata} = useSearchStateContext(); + + const selectedTransactionsKeys = Object.keys(selectedTransactions ?? {}); + const shouldAllowFooterTotals = useSearchShouldCalculateTotals(currentSearchKey, currentSearchHash, true); + + const {count, total, currency} = useMemo(() => { + if (!shouldAllowFooterTotals && selectedTransactionsKeys.length === 0) { + return {count: undefined, total: undefined, currency: undefined}; + } + + const shouldUseClientTotal = selectedTransactionsKeys.length > 0 || !footerMetadata?.count || (selectedTransactionsKeys.length > 0 && !areAllMatchingItemsSelected); + const selectedTransactionItems = Object.values(selectedTransactions); + const resolvedCurrency = footerMetadata?.currency ?? selectedTransactionItems.at(0)?.groupCurrency; + const numberOfExpense = shouldUseClientTotal + ? selectedTransactionsKeys.reduce((acc, key) => { + const item = selectedTransactions[key]; + if (item.action === CONST.SEARCH.ACTION_TYPES.VIEW && key === item.reportID) { + return acc; + } + return acc + 1; + }, 0) + : footerMetadata?.count; + const resolvedTotal = shouldUseClientTotal ? selectedTransactionItems.reduce((acc, transaction) => acc - (transaction.groupAmount ?? 0), 0) : footerMetadata?.total; + + return {count: numberOfExpense, total: resolvedTotal, currency: resolvedCurrency}; + }, [areAllMatchingItemsSelected, footerMetadata?.count, footerMetadata?.currency, footerMetadata?.total, selectedTransactions, selectedTransactionsKeys, shouldAllowFooterTotals]); const valueTextStyle = useMemo(() => (isOffline ? [styles.textLabelSupporting, styles.labelStrong] : [styles.labelStrong]), [isOffline, styles]); + if (!shouldShowFooter) { + return null; + } + return ( ({closeOverlay, translationKey, ); } -function SearchFiltersBar({queryJSON, isMobileSelectionModeEnabled}: SearchFiltersBarProps) { +function SearchFiltersBar({queryJSON}: SearchFiltersBarProps) { const scrollRef = useRef>(null); const [searchAdvancedFiltersForm = getEmptyObject>()] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM); const {type: unsafeType, groupBy: unsafeGroupBy, status: unsafeStatus, view: unsafeView, flatFilters} = queryJSON; @@ -131,7 +130,7 @@ function SearchFiltersBar({queryJSON, isMobileSelectionModeEnabled}: SearchFilte const personalDetails = usePersonalDetails(); const filterFormValues = useFilterFormValues(queryJSON); const {shouldUseNarrowLayout, isLargeScreenWidth} = useResponsiveLayout(); - const {selectedTransactions, shouldShowFiltersBarLoading, currentSearchResults} = useSearchStateContext(); + const {selectedTransactions, shouldShowFiltersBarLoading, currentSearchResults, isMobileSelectionModeEnabled} = useSearchStateContext(); const {currencyList} = useCurrencyListState(); const {getCurrencySymbol} = useCurrencyListActions(); diff --git a/src/components/Search/SearchPageHeader/SearchPageHeader.tsx b/src/components/Search/SearchPageHeader/SearchPageHeader.tsx index b451853ab879..72cf49aeaa65 100644 --- a/src/components/Search/SearchPageHeader/SearchPageHeader.tsx +++ b/src/components/Search/SearchPageHeader/SearchPageHeader.tsx @@ -1,4 +1,5 @@ import React from 'react'; +import {useSearchStateContext} from '@components/Search/SearchContext'; import type {SearchQueryJSON} from '@components/Search/types'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import SearchSelectedNarrow from '@pages/Search/SearchSelectedNarrow'; @@ -12,13 +13,13 @@ type SearchPageHeaderProps = { hideSearchRouterList?: () => void; onSearchRouterFocus?: () => void; handleSearch: (value: string) => void; - isMobileSelectionModeEnabled: boolean; }; type SearchHeaderOptionValue = DeepValueOf | undefined; -function SearchPageHeader({queryJSON, searchRouterListVisible, hideSearchRouterList, onSearchRouterFocus, handleSearch, isMobileSelectionModeEnabled}: SearchPageHeaderProps) { +function SearchPageHeader({queryJSON, searchRouterListVisible, hideSearchRouterList, onSearchRouterFocus, handleSearch}: SearchPageHeaderProps) { const {shouldUseNarrowLayout} = useResponsiveLayout(); + const {isMobileSelectionModeEnabled} = useSearchStateContext(); if (shouldUseNarrowLayout && isMobileSelectionModeEnabled) { return ; diff --git a/src/components/Search/SearchReceiptDropZone.tsx b/src/components/Search/SearchReceiptDropZone.tsx new file mode 100644 index 000000000000..627ffa3ced7d --- /dev/null +++ b/src/components/Search/SearchReceiptDropZone.tsx @@ -0,0 +1,61 @@ +import React from 'react'; +import type {StyleProp, ViewStyle} from 'react-native'; +import DragAndDropConsumer from '@components/DragAndDrop/Consumer'; +import DragAndDropProvider from '@components/DragAndDrop/Provider'; +import DropZoneUI from '@components/DropZone/DropZoneUI'; +import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; +import useLocalize from '@hooks/useLocalize'; +import useReceiptScanDrop from '@hooks/useReceiptScanDrop'; +import useTheme from '@hooks/useTheme'; +import useThemeStyles from '@hooks/useThemeStyles'; +import type ChildrenProps from '@src/types/utils/ChildrenProps'; + +type SearchReceiptDropZoneProps = ChildrenProps & { + /** Extra styles applied to the drop zone overlay wrapper (e.g. bottom padding for the nav tab bar on narrow layouts) */ + dropWrapperStyles?: StyleProp; + /** + * When true the ErrorModal is rendered inside the DragAndDropProvider (narrow layout). + * When false (default) the ErrorModal is rendered as the last sibling of the returned fragment, + * outside any scroll/screen containers (wide layout). + */ + renderErrorModalInside?: boolean; +}; + +/** + * Wraps page content in a DragAndDrop zone for receipt scanning. + * Owns all drag-and-drop hook calls so the parent page stays hook-free for this feature. + */ +function SearchReceiptDropZone({children, dropWrapperStyles, renderErrorModalInside = false}: SearchReceiptDropZoneProps) { + const {initScanRequest, PDFValidationComponent, ErrorModal, isDragDisabled} = useReceiptScanDrop(); + const expensifyIcons = useMemoizedLazyExpensifyIcons(['SmartScan'] as const); + const {translate} = useLocalize(); + const theme = useTheme(); + const styles = useThemeStyles(); + + const dropZoneConsumer = ( + + + + ); + + return ( + <> + + {PDFValidationComponent} + {children} + {dropZoneConsumer} + {renderErrorModalInside && ErrorModal} + + {!renderErrorModalInside && ErrorModal} + + ); +} + +export default SearchReceiptDropZone; diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index afa08d82a3bd..12d7e7ca2672 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -92,8 +92,6 @@ type SearchProps = { contentContainerStyle?: StyleProp; searchResults?: SearchResults; handleSearch: (value: SearchParams) => void; - onSortPressedCallback?: () => void; - isMobileSelectionModeEnabled: boolean; searchRequestResponseStatusCode?: number | null; onDEWModalOpen?: () => void; }; @@ -201,17 +199,7 @@ function prepareTransactionsList( }; } -function Search({ - queryJSON, - searchResults, - onSearchListScroll, - contentContainerStyle, - handleSearch, - isMobileSelectionModeEnabled, - onSortPressedCallback, - searchRequestResponseStatusCode, - onDEWModalOpen, -}: SearchProps) { +function Search({queryJSON, searchResults, onSearchListScroll, contentContainerStyle, handleSearch, searchRequestResponseStatusCode, onDEWModalOpen}: SearchProps) { const {type, status, sortBy, sortOrder, hash, recentSearchHash, similarSearchHash, groupBy, view} = queryJSON; const {isOffline} = useNetwork(); @@ -227,8 +215,16 @@ function Search({ const navigation = useNavigation>(); const isFocused = useIsFocused(); const {markReportIDAsExpense} = useWideRHPActions(); - const {currentSearchHash, selectedTransactions, shouldTurnOffSelectionMode, lastSearchType, areAllMatchingItemsSelected, shouldResetSearchQuery, shouldUseLiveData} = - useSearchStateContext(); + const { + currentSearchHash, + selectedTransactions, + shouldTurnOffSelectionMode, + lastSearchType, + areAllMatchingItemsSelected, + shouldResetSearchQuery, + shouldUseLiveData, + isMobileSelectionModeEnabled, + } = useSearchStateContext(); const { setCurrentSearchHashAndKey, setCurrentSearchQueryJSON, @@ -1258,7 +1254,6 @@ function Search({ const onSortPress = (column: SearchColumnType, order: SortOrder) => { clearSelectedTransactions(); const newQuery = buildSearchQueryString({...queryJSON, sortBy: column, sortOrder: order}); - onSortPressedCallback?.(); // We want to explicitly clear stale rawQuery since it's only used for manually typed-in queries. navigation.setParams({q: newQuery, rawQuery: undefined}); }; diff --git a/src/components/Search/types.ts b/src/components/Search/types.ts index ef343d6c5ef7..137892c99f4b 100644 --- a/src/components/Search/types.ts +++ b/src/components/Search/types.ts @@ -20,7 +20,7 @@ import type { import type {SearchKey} from '@libs/SearchUIUtils'; import type CONST from '@src/CONST'; import type {Report, ReportAction, SearchResults, Transaction} from '@src/types/onyx'; -import type {SearchDataTypes} from '@src/types/onyx/SearchResults'; +import type {SearchDataTypes, SearchResultsInfo} from '@src/types/onyx/SearchResults'; import type IconAsset from '@src/types/utils/IconAsset'; /** Model of the selected transaction */ @@ -168,12 +168,19 @@ type SearchContextData = { type SearchStateContextValue = SearchContextData & { currentSearchResults: SearchResults | undefined; + /** The most recent search results that contained data. Used to avoid blank states during loading transitions (e.g. sorting). */ + lastNonEmptySearchResults: SearchResults | undefined; /** Whether we're on a main to-do search and should use live Onyx data instead of snapshots */ shouldUseLiveData: boolean; shouldShowFiltersBarLoading: boolean; lastSearchType: string | undefined; shouldShowSelectAllMatchingItems: boolean; areAllMatchingItemsSelected: boolean; + isMobileSelectionModeEnabled: boolean; + /** Whether the search page footer should be shown (selection active or totals eligible) */ + shouldShowFooter: boolean; + /** The search result metadata used by the footer (count, total, currency). Derived from the most recent non-empty results. */ + footerMetadata: SearchResultsInfo | undefined; }; type SearchActionsContextValue = { diff --git a/src/hooks/useSearchBulkActions.ts b/src/hooks/useSearchBulkActions.ts index 9f223d2ac07d..f1a4c23ec82b 100644 --- a/src/hooks/useSearchBulkActions.ts +++ b/src/hooks/useSearchBulkActions.ts @@ -1,4 +1,4 @@ -import {useCallback, useEffect, useMemo, useRef, useState} from 'react'; +import {useCallback, useMemo, useRef, useState} from 'react'; import {InteractionManager} from 'react-native'; import type {ValueOf} from 'type-fest'; import type {DropdownOption} from '@components/ButtonWithDropdownMenu/types'; @@ -51,7 +51,7 @@ import {openOldDotLink} from '@userActions/Link'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; -import type {Report, SearchResults, Transaction, TransactionViolations} from '@src/types/onyx'; +import type {Report, Transaction, TransactionViolations} from '@src/types/onyx'; import useAllTransactions from './useAllTransactions'; import useBulkPayOptions from './useBulkPayOptions'; import useConfirmModal from './useConfirmModal'; @@ -76,7 +76,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { const {isOffline} = useNetwork(); const {isDelegateAccessRestricted} = useDelegateNoAccessState(); const {showDelegateNoAccessModal} = useDelegateNoAccessActions(); - const {selectedTransactions, selectedReports, areAllMatchingItemsSelected, currentSearchResults} = useSearchStateContext(); + const {selectedTransactions, selectedReports, areAllMatchingItemsSelected, currentSearchResults, lastNonEmptySearchResults} = useSearchStateContext(); const {clearSelectedTransactions, selectAllMatchingItems} = useSearchActionsContext(); const currentUserPersonalDetails = useCurrentUserPersonalDetails(); const {accountID} = currentUserPersonalDetails; @@ -92,16 +92,7 @@ function useSearchBulkActions({queryJSON}: UseSearchBulkActionsParams) { const [transactions] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION); const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS); - // Cache the last search results that had data, so the merge option remains available - // while results are temporarily unset (e.g. during sorting/loading). - const lastNonEmptySearchResultsRef = useRef(undefined); - useEffect(() => { - if (!currentSearchResults?.data) { - return; - } - lastNonEmptySearchResultsRef.current = currentSearchResults; - }, [currentSearchResults]); - const searchResults = currentSearchResults?.data ? currentSearchResults : lastNonEmptySearchResultsRef.current; + const searchResults = currentSearchResults?.data ? currentSearchResults : lastNonEmptySearchResults; const [isOfflineModalVisible, setIsOfflineModalVisible] = useState(false); const [isDownloadErrorModalVisible, setIsDownloadErrorModalVisible] = useState(false); diff --git a/src/pages/Search/SearchPage.tsx b/src/pages/Search/SearchPage.tsx index ce9f6d13e801..c690b8e0ab21 100644 --- a/src/pages/Search/SearchPage.tsx +++ b/src/pages/Search/SearchPage.tsx @@ -1,207 +1,17 @@ -import React, {useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react'; -import type {NativeScrollEvent, NativeSyntheticEvent} from 'react-native'; -import Animated from 'react-native-reanimated'; -import DragAndDropConsumer from '@components/DragAndDrop/Consumer'; -import DragAndDropProvider from '@components/DragAndDrop/Provider'; -import DropZoneUI from '@components/DropZone/DropZoneUI'; -import {ScrollOffsetContext} from '@components/ScrollOffsetContextProvider'; -import {useSearchActionsContext, useSearchStateContext} from '@components/Search/SearchContext'; -import type {SearchParams} from '@components/Search/types'; -import {usePlaybackActionsContext} from '@components/VideoPlayerContexts/PlaybackContext'; +import React from 'react'; import useConfirmReadyToOpenApp from '@hooks/useConfirmReadyToOpenApp'; -import useFilterFormValues from '@hooks/useFilterFormValues'; -import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; -import useLocalize from '@hooks/useLocalize'; -import useMobileSelectionMode from '@hooks/useMobileSelectionMode'; -import usePrevious from '@hooks/usePrevious'; -import useReceiptScanDrop from '@hooks/useReceiptScanDrop'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; -import useSearchShouldCalculateTotals from '@hooks/useSearchShouldCalculateTotals'; -import useTheme from '@hooks/useTheme'; -import useThemeStyles from '@hooks/useThemeStyles'; -import {searchInServer} from '@libs/actions/Report'; -import {search, updateAdvancedFilters} from '@libs/actions/Search'; -import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types'; -import type {SearchFullscreenNavigatorParamList} from '@libs/Navigation/types'; -import {buildSearchQueryJSON} from '@libs/SearchQueryUtils'; -import variables from '@styles/variables'; -import CONST from '@src/CONST'; -import type SCREENS from '@src/SCREENS'; -import type {SearchResults} from '@src/types/onyx'; import SearchPageNarrow from './SearchPageNarrow'; import SearchPageWide from './SearchPageWide'; -type SearchPageProps = PlatformStackScreenProps; - -function SearchPage({route}: SearchPageProps) { - const {translate} = useLocalize(); +function SearchPage() { const {shouldUseNarrowLayout} = useResponsiveLayout(); - const styles = useThemeStyles(); - const theme = useTheme(); - const {selectedTransactions, lastSearchType, areAllMatchingItemsSelected, currentSearchKey, currentSearchResults} = useSearchStateContext(); - const {clearSelectedTransactions, setLastSearchType} = useSearchActionsContext(); - const isMobileSelectionModeEnabled = useMobileSelectionMode(clearSelectedTransactions); - - const queryJSON = useMemo(() => buildSearchQueryJSON(route.params.q, route.params.rawQuery), [route.params.q, route.params.rawQuery]); - const {saveScrollOffset} = useContext(ScrollOffsetContext); - const expensifyIcons = useMemoizedLazyExpensifyIcons(['SmartScan'] as const); - - const lastNonEmptySearchResults = useRef(undefined); - - const formValues = useFilterFormValues(queryJSON); - - useEffect(() => { - updateAdvancedFilters(formValues, true); - }, [formValues]); - useConfirmReadyToOpenApp(); - useEffect(() => { - if (!currentSearchResults?.search?.type) { - return; - } - - setLastSearchType(currentSearchResults.search.type); - if (currentSearchResults.data) { - lastNonEmptySearchResults.current = currentSearchResults; - } - }, [lastSearchType, queryJSON, setLastSearchType, currentSearchResults]); - - const selectedTransactionsKeys = Object.keys(selectedTransactions ?? {}); - - const {initScanRequest, PDFValidationComponent, ErrorModal, isDragDisabled} = useReceiptScanDrop(); - const {resetVideoPlayerData} = usePlaybackActionsContext(); - - const [isSorting, setIsSorting] = useState(false); - let searchResults: SearchResults | undefined; - if (currentSearchResults?.data) { - searchResults = currentSearchResults; - } else if (isSorting) { - searchResults = lastNonEmptySearchResults.current; + if (shouldUseNarrowLayout) { + return ; } - - const metadata = searchResults?.search; - const shouldAllowFooterTotals = useSearchShouldCalculateTotals(currentSearchKey, queryJSON?.hash, true); - const shouldShowFooter = selectedTransactionsKeys.length > 0 || (shouldAllowFooterTotals && !!metadata?.count); - - useEffect(() => { - if (shouldUseNarrowLayout) { - return; - } - resetVideoPlayerData(); - return () => { - if (shouldUseNarrowLayout) { - return; - } - resetVideoPlayerData(); - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - const prevIsLoading = usePrevious(currentSearchResults?.isLoading); - - useEffect(() => { - if (!isSorting || !prevIsLoading || currentSearchResults?.isLoading) { - return; - } - - setIsSorting(false); - }, [currentSearchResults?.isLoading, isSorting, prevIsLoading]); - - const [searchRequestResponseStatusCode, setSearchRequestResponseStatusCode] = useState(null); - - const handleSearchAction = useCallback((value: SearchParams | string) => { - if (typeof value === 'string') { - searchInServer(value); - } else { - setSearchRequestResponseStatusCode(null); - search(value)?.then((jsonCode) => { - setSearchRequestResponseStatusCode(Number(jsonCode ?? 0)); - }); - } - }, []); - - const footerData = useMemo(() => { - if (!shouldAllowFooterTotals && selectedTransactionsKeys.length === 0) { - return {count: undefined, total: undefined, currency: undefined}; - } - - const shouldUseClientTotal = selectedTransactionsKeys.length > 0 || !metadata?.count || (selectedTransactionsKeys.length > 0 && !areAllMatchingItemsSelected); - const selectedTransactionItems = Object.values(selectedTransactions); - const currency = metadata?.currency ?? selectedTransactionItems.at(0)?.groupCurrency; - const numberOfExpense = shouldUseClientTotal - ? selectedTransactionsKeys.reduce((count, key) => { - const item = selectedTransactions[key]; - if (item.action === CONST.SEARCH.ACTION_TYPES.VIEW && key === item.reportID) { - return count; - } - return count + 1; - }, 0) - : metadata?.count; - const total = shouldUseClientTotal ? selectedTransactionItems.reduce((acc, transaction) => acc - (transaction.groupAmount ?? 0), 0) : metadata?.total; - - return {count: numberOfExpense, total, currency}; - }, [areAllMatchingItemsSelected, metadata?.count, metadata?.currency, metadata?.total, selectedTransactions, selectedTransactionsKeys, shouldAllowFooterTotals]); - - const onSortPressedCallback = useCallback(() => { - setIsSorting(true); - }, []); - - const scrollHandler = useCallback( - (e: NativeSyntheticEvent) => { - if (!e.nativeEvent.contentOffset.y) { - return; - } - - saveScrollOffset(route, e.nativeEvent.contentOffset.y); - }, - [saveScrollOffset, route], - ); - - return ( - - {shouldUseNarrowLayout ? ( - - {PDFValidationComponent} - - - - - {ErrorModal} - - ) : ( - - )} - - ); + return ; } SearchPage.whyDidYouRender = true; diff --git a/src/pages/Search/SearchPageNarrow.tsx b/src/pages/Search/SearchPageNarrow.tsx index 0cd54fe4b190..64d37d667725 100644 --- a/src/pages/Search/SearchPageNarrow.tsx +++ b/src/pages/Search/SearchPageNarrow.tsx @@ -1,5 +1,6 @@ +import type {RouteProp} from '@react-navigation/native'; import {useRoute} from '@react-navigation/native'; -import React, {useCallback, useContext, useEffect, useState} from 'react'; +import React, {useCallback, useContext, useEffect, useMemo, useState} from 'react'; import {View} from 'react-native'; import Animated, {clamp, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, withTiming} from 'react-native-reanimated'; import {scheduleOnRN} from 'react-native-worklets'; @@ -12,11 +13,12 @@ import TopBar from '@components/Navigation/TopBar'; import ScreenWrapper from '@components/ScreenWrapper'; import {ScrollOffsetContext} from '@components/ScrollOffsetContextProvider'; import Search from '@components/Search'; -import {useSearchActionsContext} from '@components/Search/SearchContext'; +import {useSearchActionsContext, useSearchStateContext} from '@components/Search/SearchContext'; import SearchPageFooter from '@components/Search/SearchPageFooter'; import SearchFiltersBar from '@components/Search/SearchPageHeader/SearchFiltersBar'; import SearchPageHeader from '@components/Search/SearchPageHeader/SearchPageHeader'; -import type {SearchParams, SearchQueryJSON} from '@components/Search/types'; +import SearchReceiptDropZone from '@components/Search/SearchReceiptDropZone'; +import type {SearchParams} from '@components/Search/types'; import useAndroidBackButtonHandler from '@hooks/useAndroidBackButtonHandler'; import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; @@ -27,45 +29,34 @@ import useThemeStyles from '@hooks/useThemeStyles'; import useWindowDimensions from '@hooks/useWindowDimensions'; import {turnOffMobileSelectionMode} from '@libs/actions/MobileSelectionMode'; import Navigation from '@libs/Navigation/Navigation'; -import {buildCannedSearchQuery} from '@libs/SearchQueryUtils'; +import type {SearchFullscreenNavigatorParamList} from '@libs/Navigation/types'; +import {buildCannedSearchQuery, buildSearchQueryJSON} from '@libs/SearchQueryUtils'; import {isSearchDataLoaded} from '@libs/SearchUIUtils'; import variables from '@styles/variables'; import {searchInServer} from '@userActions/Report'; import {search} from '@userActions/Search'; import ROUTES from '@src/ROUTES'; -import type {SearchResults} from '@src/types/onyx'; -import type {SearchResultsInfo} from '@src/types/onyx/SearchResults'; +import type SCREENS from '@src/SCREENS'; const TOO_CLOSE_TO_TOP_DISTANCE = 10; const TOO_CLOSE_TO_BOTTOM_DISTANCE = 10; const ANIMATION_DURATION_IN_MS = 300; -type SearchPageNarrowProps = { - queryJSON?: SearchQueryJSON; - metadata?: SearchResultsInfo; - searchResults?: SearchResults; - isMobileSelectionModeEnabled: boolean; - footerData: { - count: number | undefined; - total: number | undefined; - currency: string | undefined; - }; - shouldShowFooter: boolean; -}; - -function SearchPageNarrow({queryJSON, searchResults, isMobileSelectionModeEnabled, metadata, footerData, shouldShowFooter}: SearchPageNarrowProps) { - const {translate} = useLocalize(); +function SearchPageNarrow() { + const route = useRoute>(); + const queryJSON = useMemo(() => buildSearchQueryJSON(route.params.q, route.params.rawQuery), [route.params.q, route.params.rawQuery]); const {shouldUseNarrowLayout} = useResponsiveLayout(); const {windowHeight} = useWindowDimensions(); const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); + const {currentSearchResults, lastNonEmptySearchResults, isMobileSelectionModeEnabled} = useSearchStateContext(); + const searchResults = currentSearchResults?.data ? currentSearchResults : lastNonEmptySearchResults; + const metadata = searchResults?.search; const {clearSelectedTransactions} = useSearchActionsContext(); + const {translate} = useLocalize(); const [searchRouterListVisible, setSearchRouterListVisible] = useState(false); const {isOffline} = useNetwork(); - // Controls the visibility of the educational tooltip based on user scrolling. - // Hides the tooltip when the user is scrolling and displays it once scrolling stops. const triggerScrollEvent = useScrollEventEmitter(); - const route = useRoute(); const {saveScrollOffset} = useContext(ScrollOffsetContext); const [searchRequestResponseStatusCode, setSearchRequestResponseStatusCode] = useState(null); @@ -120,7 +111,7 @@ function SearchPageNarrow({queryJSON, searchResults, isMobileSelectionModeEnable const shouldDisplayCancelSearch = shouldUseNarrowLayout && searchRouterListVisible; const cancelSearchCallback = useCallback(() => { setSearchRouterListVisible(false); - }, []); + }, [setSearchRouterListVisible]); const handleSearchAction = useCallback((value: SearchParams | string) => { if (typeof value === 'string') { @@ -162,100 +153,89 @@ function SearchPageNarrow({queryJSON, searchResults, isMobileSelectionModeEnable const shouldShowLoadingState = !isOffline && (!isDataLoaded || !!metadata?.isLoading); return ( - } - shouldShowOfflineIndicator={!!searchResults} + - - {!isMobileSelectionModeEnabled ? ( - - - - - - - - { - setSearchRouterListVisible(false); - }} - onSearchRouterFocus={() => { - topBarOffset.set(StyleUtils.searchHeaderDefaultOffset); - setSearchRouterListVisible(true); - }} - handleSearch={handleSearchAction} - isMobileSelectionModeEnabled={isMobileSelectionModeEnabled} - /> - - - {!searchRouterListVisible && ( - } + shouldShowOfflineIndicator={!!searchResults} + > + + {!isMobileSelectionModeEnabled ? ( + + + + + + + + { + setSearchRouterListVisible(false); + }} + onSearchRouterFocus={() => { + topBarOffset.set(StyleUtils.searchHeaderDefaultOffset); + setSearchRouterListVisible(true); + }} + handleSearch={handleSearchAction} /> - )} - - + + {!searchRouterListVisible && } + + - - ) : ( - <> - { - topBarOffset.set(StyleUtils.searchHeaderDefaultOffset); - clearSelectedTransactions(); - turnOffMobileSelectionMode(); - }} - /> - - - )} - {!searchRouterListVisible && ( - - - - )} - {shouldShowFooter && !searchRouterListVisible && ( - - )} - - + ) : ( + <> + { + topBarOffset.set(StyleUtils.searchHeaderDefaultOffset); + clearSelectedTransactions(); + turnOffMobileSelectionMode(); + }} + /> + + + )} + {!searchRouterListVisible && ( + + + + )} + {!searchRouterListVisible && } + + + ); } diff --git a/src/pages/Search/SearchPageWide.tsx b/src/pages/Search/SearchPageWide.tsx index f98317865f3f..c760d24529a0 100644 --- a/src/pages/Search/SearchPageWide.tsx +++ b/src/pages/Search/SearchPageWide.tsx @@ -1,64 +1,61 @@ -import React, {useMemo} from 'react'; +import type {RouteProp} from '@react-navigation/native'; +import {useRoute} from '@react-navigation/native'; +import React, {useCallback, useContext, useEffect, useMemo, useState} from 'react'; import type {NativeScrollEvent, NativeSyntheticEvent} from 'react-native'; import {View} from 'react-native'; -import type {OnyxEntry} from 'react-native-onyx'; import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView'; -import DragAndDropConsumer from '@components/DragAndDrop/Consumer'; -import DragAndDropProvider from '@components/DragAndDrop/Provider'; -import DropZoneUI from '@components/DropZone/DropZoneUI'; import ScreenWrapper from '@components/ScreenWrapper'; +import {ScrollOffsetContext} from '@components/ScrollOffsetContextProvider'; import Search from '@components/Search'; +import {useSearchStateContext} from '@components/Search/SearchContext'; import SearchPageFooter from '@components/Search/SearchPageFooter'; import SearchFiltersBar from '@components/Search/SearchPageHeader/SearchFiltersBar'; import SearchPageHeader from '@components/Search/SearchPageHeader/SearchPageHeader'; -import type {SearchParams, SearchQueryJSON} from '@components/Search/types'; -import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; -import useLocalize from '@hooks/useLocalize'; -import useTheme from '@hooks/useTheme'; +import SearchReceiptDropZone from '@components/Search/SearchReceiptDropZone'; +import type {SearchParams} from '@components/Search/types'; +import {usePlaybackActionsContext} from '@components/VideoPlayerContexts/PlaybackContext'; import useThemeStyles from '@hooks/useThemeStyles'; -import {buildCannedSearchQuery} from '@libs/SearchQueryUtils'; +import type {SearchFullscreenNavigatorParamList} from '@libs/Navigation/types'; +import {buildCannedSearchQuery, buildSearchQueryJSON} from '@libs/SearchQueryUtils'; import Navigation from '@navigation/Navigation'; +import {searchInServer} from '@userActions/Report'; +import {search} from '@userActions/Search'; import ROUTES from '@src/ROUTES'; -import type {SearchResults} from '@src/types/onyx'; +import type SCREENS from '@src/SCREENS'; -type SearchPageWideProps = { - queryJSON?: SearchQueryJSON; - searchResults: OnyxEntry; - searchRequestResponseStatusCode: number | null; - isMobileSelectionModeEnabled: boolean; - footerData: { - count: number | undefined; - total: number | undefined; - currency: string | undefined; - }; - handleSearchAction: (value: SearchParams | string) => void; - onSortPressedCallback: () => void; - scrollHandler: (event: NativeSyntheticEvent) => void; - initScanRequest: (e: DragEvent) => void; - isDragDisabled: boolean; - PDFValidationComponent: React.ReactNode; - ErrorModal: React.ReactNode; - shouldShowFooter: boolean; -}; - -function SearchPageWide({ - queryJSON, - searchResults, - searchRequestResponseStatusCode, - isMobileSelectionModeEnabled, - footerData, - handleSearchAction, - onSortPressedCallback, - scrollHandler, - initScanRequest, - isDragDisabled, - PDFValidationComponent, - ErrorModal, - shouldShowFooter, -}: SearchPageWideProps) { +function SearchPageWide() { + const route = useRoute>(); + const queryJSON = useMemo(() => buildSearchQueryJSON(route.params.q, route.params.rawQuery), [route.params.q, route.params.rawQuery]); const styles = useThemeStyles(); - const theme = useTheme(); - const {translate} = useLocalize(); + const {currentSearchResults, lastNonEmptySearchResults, shouldShowFooter} = useSearchStateContext(); + const searchResults = currentSearchResults?.data ? currentSearchResults : lastNonEmptySearchResults; + const {saveScrollOffset} = useContext(ScrollOffsetContext); + const scrollHandler = useCallback( + (e: NativeSyntheticEvent) => { + if (!e.nativeEvent.contentOffset.y) { + return; + } + + saveScrollOffset(route, e.nativeEvent.contentOffset.y); + }, + [saveScrollOffset, route], + ); + const {resetVideoPlayerData} = usePlaybackActionsContext(); + const [searchRequestResponseStatusCode, setSearchRequestResponseStatusCode] = useState(null); + const handleSearchAction = useCallback((value: SearchParams | string) => { + if (typeof value === 'string') { + searchInServer(value); + } else { + setSearchRequestResponseStatusCode(null); + search(value)?.then((jsonCode) => { + setSearchRequestResponseStatusCode(Number(jsonCode ?? 0)); + }); + } + }, []); + useEffect(() => { + resetVideoPlayerData(); + return resetVideoPlayerData; + }, [resetVideoPlayerData]); const offlineIndicatorStyle = useMemo(() => { if (shouldShowFooter) { @@ -68,7 +65,6 @@ function SearchPageWide({ return [styles.mtAuto]; }, [shouldShowFooter, styles]); - const expensifyIcons = useMemoizedLazyExpensifyIcons(['SmartScan']); const handleOnBackButtonPress = () => Navigation.goBack(ROUTES.SEARCH_ROOT.getRoute({query: buildCannedSearchQuery()})); return ( @@ -76,7 +72,7 @@ function SearchPageWide({ {!!queryJSON && ( - - {PDFValidationComponent} + - + - {shouldShowFooter && ( - - )} - - - - + + )} - {ErrorModal} ); }