Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 3 additions & 13 deletions src/components/Navigation/SearchSidebar.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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) {
Expand Down
46 changes: 45 additions & 1 deletion src/components/Search/SearchContext.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -118,6 +126,30 @@ function SearchContextProvider({children}: ChildrenProps) {

const currentSearchResults = getCurrentSearchResults();

const [lastNonEmptySearchResults, setLastNonEmptySearchResults] = useState<SearchResults | undefined>(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) {
Expand Down Expand Up @@ -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 = {
Expand Down
42 changes: 34 additions & 8 deletions src/components/Search/SearchPageFooter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<View
style={[
Expand Down
5 changes: 2 additions & 3 deletions src/components/Search/SearchPageHeader/SearchFiltersBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ type FilterItem = WithSentryLabel & {

type SearchFiltersBarProps = {
queryJSON: SearchQueryJSON;
isMobileSelectionModeEnabled: boolean;
};

type DatePickerFilterPopupProps = PopoverComponentProps & {
Expand Down Expand Up @@ -119,7 +118,7 @@ function MultiSelectFilterPopup<T extends string>({closeOverlay, translationKey,
);
}

function SearchFiltersBar({queryJSON, isMobileSelectionModeEnabled}: SearchFiltersBarProps) {
function SearchFiltersBar({queryJSON}: SearchFiltersBarProps) {
const scrollRef = useRef<FlatList<FilterItem>>(null);
const [searchAdvancedFiltersForm = getEmptyObject<Partial<SearchAdvancedFiltersForm>>()] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM);
const {type: unsafeType, groupBy: unsafeGroupBy, status: unsafeStatus, view: unsafeView, flatFilters} = queryJSON;
Expand All @@ -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();

Expand Down
5 changes: 3 additions & 2 deletions src/components/Search/SearchPageHeader/SearchPageHeader.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -12,13 +13,13 @@ type SearchPageHeaderProps = {
hideSearchRouterList?: () => void;
onSearchRouterFocus?: () => void;
handleSearch: (value: string) => void;
isMobileSelectionModeEnabled: boolean;
};

type SearchHeaderOptionValue = DeepValueOf<typeof CONST.SEARCH.BULK_ACTION_TYPES> | 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 <SearchSelectedNarrow queryJSON={queryJSON} />;
Expand Down
61 changes: 61 additions & 0 deletions src/components/Search/SearchReceiptDropZone.tsx
Original file line number Diff line number Diff line change
@@ -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<ViewStyle>;
/**
* 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 = (
<DragAndDropConsumer onDrop={initScanRequest}>
<DropZoneUI
icon={expensifyIcons.SmartScan}
dropTitle={translate('dropzone.scanReceipts')}
dropStyles={styles.receiptDropOverlay(true)}
dropTextStyles={styles.receiptDropText}
dropWrapperStyles={dropWrapperStyles}
dashedBorderStyles={[styles.dropzoneArea, styles.easeInOpacityTransition, styles.activeDropzoneDashedBorder(theme.receiptDropBorderColorActive, true)]}
/>
</DragAndDropConsumer>
);

return (
<>
<DragAndDropProvider isDisabled={isDragDisabled}>
{PDFValidationComponent}
{children}
{dropZoneConsumer}
{renderErrorModalInside && ErrorModal}
</DragAndDropProvider>
{!renderErrorModalInside && ErrorModal}
</>
);
}

export default SearchReceiptDropZone;
27 changes: 11 additions & 16 deletions src/components/Search/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,6 @@ type SearchProps = {
contentContainerStyle?: StyleProp<ViewStyle>;
searchResults?: SearchResults;
handleSearch: (value: SearchParams) => void;
onSortPressedCallback?: () => void;
isMobileSelectionModeEnabled: boolean;
searchRequestResponseStatusCode?: number | null;
onDEWModalOpen?: () => void;
};
Expand Down Expand Up @@ -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();
Expand All @@ -227,8 +215,16 @@ function Search({
const navigation = useNavigation<PlatformStackNavigationProp<SearchFullscreenNavigatorParamList>>();
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,
Expand Down Expand Up @@ -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});
};
Expand Down
9 changes: 8 additions & 1 deletion src/components/Search/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down Expand Up @@ -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 = {
Expand Down
Loading
Loading