diff --git a/src/components/AddExistingExpenseFooter.tsx b/src/components/AddExistingExpenseFooter.tsx index 3e5df261535a..2e0a07da4fe1 100644 --- a/src/components/AddExistingExpenseFooter.tsx +++ b/src/components/AddExistingExpenseFooter.tsx @@ -31,7 +31,7 @@ import {usePersonalDetails, useSession} from './OnyxListItemProvider'; type AddExistingExpenseFooterProps = { /** Selected transaction IDs */ - selectedIds: Set; + selectedIds: string[]; /** The report to add expenses to */ report: OnyxEntry; reportToConfirm: OnyxEntry; @@ -64,11 +64,11 @@ function AddExistingExpenseFooter({selectedIds, report, reportToConfirm, policy, const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector}); const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE); - const [transactions] = useTransactionsByID([...selectedIds]); + const [transactions] = useTransactionsByID(selectedIds); const reports = useChangeTransactionsReportReports(transactions, reportToConfirm?.reportID); const handleConfirm = () => { - if (selectedIds.size === 0) { + if (selectedIds.length === 0) { setErrorMessage(translate('iou.selectExistingExpense')); return; } @@ -99,7 +99,7 @@ function AddExistingExpenseFooter({selectedIds, report, reportToConfirm, policy, } else { changeTransactionsReport({ isVendorMatchingBetaEnabled, - transactionIDs: [...selectedIds], + transactionIDs: selectedIds, isASAPSubmitBetaEnabled, accountID: session?.accountID ?? CONST.DEFAULT_NUMBER_ID, email: session?.email ?? '', diff --git a/src/components/MoneyReportHeader.tsx b/src/components/MoneyReportHeader.tsx index 017af6e8975c..6485bf8e97ab 100644 --- a/src/components/MoneyReportHeader.tsx +++ b/src/components/MoneyReportHeader.tsx @@ -17,7 +17,7 @@ import ONYXKEYS from '@src/ONYXKEYS'; import type {Route} from '@src/ROUTES'; import SCREENS from '@src/SCREENS'; -import {useRoute} from '@react-navigation/native'; +import {useIsFocused, useRoute} from '@react-navigation/native'; import React, {useEffect} from 'react'; import {View} from 'react-native'; @@ -91,6 +91,7 @@ function MoneyReportHeaderContent({reportID: reportIDProp, shouldDisplayBackButt const shouldShowBackButton = shouldDisplayBackButton || shouldUseNarrowLayout; const isMobileSelectionModeEnabled = useMobileSelectionMode(); + const isFocused = useIsFocused(); useEffect(() => { return () => { @@ -99,9 +100,11 @@ function MoneyReportHeaderContent({reportID: reportIDProp, shouldDisplayBackButt }, []); if (isMobileSelectionModeEnabled && shouldUseNarrowLayout) { - // If mobile selection mode is enabled but only one or no transactions remain, turn it off + // If mobile selection mode is enabled but only one or no transactions remain, turn it off. The selection mode + // is shared with every screen, so this report only gets to turn it off while it is the focused one. Another + // screen on top of it, such as the add existing expense modal, owns the mode for as long as it is open. const visibleTransactions = transactions.filter((t) => t.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || isOffline); - if (visibleTransactions.length <= 1) { + if (isFocused && visibleTransactions.length <= 1) { turnOffMobileSelectionMode(); } diff --git a/src/components/Search/FilterDropdowns/MultiSelectPopup.tsx b/src/components/Search/FilterDropdowns/MultiSelectPopup.tsx index b798ea48a574..bf403e285763 100644 --- a/src/components/Search/FilterDropdowns/MultiSelectPopup.tsx +++ b/src/components/Search/FilterDropdowns/MultiSelectPopup.tsx @@ -65,5 +65,4 @@ function MultiSelectPopup({showLabel, label, loading, value, i ); } -export type {MultiSelectItem}; export default MultiSelectPopup; diff --git a/src/components/Skeletons/UnreportedExpensesSkeleton.tsx b/src/components/Skeletons/UnreportedExpensesSkeleton.tsx index 8f9f1b04af14..acc84dde3944 100644 --- a/src/components/Skeletons/UnreportedExpensesSkeleton.tsx +++ b/src/components/Skeletons/UnreportedExpensesSkeleton.tsx @@ -41,31 +41,44 @@ type UnreportedExpensesSkeletonProps = { function UnreportedExpensesSkeleton({fixedNumberOfItems}: UnreportedExpensesSkeletonProps) { const {onLayout, containerWidth: pageWidth} = useContainerWidth(40); const styles = useThemeStyles(); + // Passed only when the skeleton is the footer appended below rows that are already on screen, so it gets a top + // divider joining it to the row above instead of rounding its own top corners. + const isPaginationFooter = !!fixedNumberOfItems; const skeletonItem = useCallback( (args: {itemIndex: number}) => { return ( <> + + ); }, @@ -78,8 +91,10 @@ function UnreportedExpensesSkeleton({fixedNumberOfItems}: UnreportedExpensesSkel onLayout={onLayout} > ) { const {translate} = useLocalize(); const isMobileSelectionEnabled = useMobileSelectionMode(); + + const setMobileSelectionModeEnabled = (isEnabled: boolean) => { + if (isEnabled) { + turnOnMobileSelectionMode(); + return; + } + + turnOffMobileSelectionMode(); + }; const icons = useMemoizedLazyExpensifyIcons(['CheckSquare']); const {shouldUseNarrowLayout, isMediumScreenWidth} = useResponsiveLayout(); const bottomSafeAreaPaddingStyle = useBottomSafeSafeAreaPaddingStyle({addBottomSafeAreaPadding: true, addOfflineIndicatorBottomSafeAreaPadding: false}); @@ -304,6 +316,7 @@ function Table({ compareItems, initialSortColumn, + initialSortOrder, narrowLayoutSortColumn, shouldUseNarrowTableLayout, onSortingChange, @@ -322,6 +335,9 @@ function Table void; }; @@ -129,6 +137,7 @@ const defaultTableContextValue: TableContextValue = { order: 'asc', }, initialSortColumn: undefined, + initialSortOrder: CONST.SEARCH.SORT_ORDER.ASC, narrowLayoutSortColumn: undefined, activeSearchString: '', tableMethods: {} as TableMethods, diff --git a/src/components/Table/TableFilterBar/TableDisplaySettingsPopoverComponent.tsx b/src/components/Table/TableFilterBar/TableDisplaySettingsPopoverComponent.tsx index 015297a4f182..94cf4372d32c 100644 --- a/src/components/Table/TableFilterBar/TableDisplaySettingsPopoverComponent.tsx +++ b/src/components/Table/TableFilterBar/TableDisplaySettingsPopoverComponent.tsx @@ -93,13 +93,14 @@ export default function TableDisplaySettingsPopoverComponent({closeOverlay}: Tab columns, activeSorting, initialSortColumn, + initialSortOrder, tableMethods: {updateSorting}, } = useTableContext(); const [selectedSetting, setSelectedSetting] = useState<'sortBy' | 'sortOrder' | null>(null); const defaultSorting: ActiveSorting = { columnKey: initialSortColumn, - order: CONST.SEARCH.SORT_ORDER.ASC, + order: initialSortOrder, }; const [pendingSorting, setPendingSorting] = useState>(defaultSorting); @@ -168,7 +169,7 @@ export default function TableDisplaySettingsPopoverComponent({closeOverlay}: Tab ]} value={selectedOrder} label={translate('search.display.sortOrder')} - defaultValue={CONST.SEARCH.SORT_ORDER.ASC} + defaultValue={defaultSorting.order} onBackButtonPress={() => setSelectedSetting('sortBy')} closeOverlay={closeSettingsOverlay} onChange={(item) => { diff --git a/src/components/Table/TableRow.tsx b/src/components/Table/TableRow.tsx index 1c91306ebbf5..768002e2bfc9 100644 --- a/src/components/Table/TableRow.tsx +++ b/src/components/Table/TableRow.tsx @@ -88,6 +88,8 @@ export default function TableRow({ shouldEnableSelectionInNarrowPaneModal = false, tableListMetadata, dynamicGridTemplateColumns, + listProps, + shouldFooterRenderAsLastRow, } = useTableContext(); const semanticRowID = useTableRowSemanticID(); const semanticTableHasHeader = !tableListMetadata.hasPageHeader || tableListMetadata.shouldRenderStickyHeader; @@ -110,7 +112,9 @@ export default function TableRow({ const isDisabled = !!disabled || isAccessibilityHidden; const isFirstRow = rowIndex === 0; - const isLastRow = rowIndex === rowCount - 1; + // A footer that continues the rows owns the rounded bottom corners instead of the last row. + const doesFooterOwnBottomRadius = !!shouldFooterRenderAsLastRow && !!listProps?.ListFooterComponent; + const isLastRow = rowIndex === rowCount - 1 && !doesFooterOwnBottomRadius; if (selectionEnabled && isSelectionCheckboxVisible) { gridTemplateColumns.unshift(`${variables.tableCheckboxColumnWidth}px`); diff --git a/src/components/Table/middlewares/selection.ts b/src/components/Table/middlewares/selection.ts index c47b22ca1ad4..4e7b3aceb096 100644 --- a/src/components/Table/middlewares/selection.ts +++ b/src/components/Table/middlewares/selection.ts @@ -1,12 +1,10 @@ import type {TableData, TableRow} from '@components/Table/types'; import useAndroidBackButtonHandler from '@hooks/useAndroidBackButtonHandler'; -import useMobileSelectionMode from '@hooks/useMobileSelectionMode'; import usePrevious from '@hooks/usePrevious'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useShiftRangeSelection from '@hooks/useShiftRangeSelection'; -import {turnOffMobileSelectionMode, turnOnMobileSelectionMode} from '@libs/actions/MobileSelectionMode'; import {applyShiftRangeBatchToKeySet} from '@libs/shiftRangeSelection'; import type {Dispatch, SetStateAction} from 'react'; @@ -34,6 +32,15 @@ type UseSelectionProps = { /** Whether the selection mode should key off the real screen size instead of shouldUseNarrowLayout (for tables inside a narrow pane modal / RHP) */ shouldEnableSelectionInNarrowPaneModal?: boolean; + + /** Whether the mobile selection mode is currently on */ + isSelectionModeEnabled: boolean; + + /** Turns the mobile selection mode on or off */ + setSelectionModeEnabled: (isEnabled: boolean) => void; + + /** Whether the selection survives a change to the search string or the filters */ + shouldPreserveSelectionOnSearchAndFilter?: boolean; }; type SelectionMethods = { @@ -66,6 +73,9 @@ export default function useSelection({ activeSearchString, onRowSelectionChange, shouldEnableSelectionInNarrowPaneModal, + isSelectionModeEnabled, + setSelectionModeEnabled, + shouldPreserveSelectionOnSearchAndFilter, }: UseSelectionProps): UseSelectionResult { // When a table opts into selection inside a narrow pane modal (RHP), the selection-mode auto-sync keys off the real // screen size (isSmallScreenWidth) so it behaves correctly there (shouldUseNarrowLayout is always true in an RHP). @@ -73,7 +83,6 @@ export default function useSelection({ // eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth const {shouldUseNarrowLayout, isSmallScreenWidth} = useResponsiveLayout(); const selectionUsesNarrowLayout = shouldEnableSelectionInNarrowPaneModal ? isSmallScreenWidth : shouldUseNarrowLayout; - const isSelectionModeEnabled = useMobileSelectionMode(); // When a user long-presses a row on mobile, store the key of the row that will be selected if // the user confirms the selection @@ -103,9 +112,9 @@ export default function useSelection({ } clearSelection(); - turnOffMobileSelectionMode(); + setSelectionModeEnabled(false); return true; - }, [isSelectionModeEnabled, clearSelection]); + }, [isSelectionModeEnabled, clearSelection, setSelectionModeEnabled]); useAndroidBackButtonHandler(androidBackButtonDisableSelectionMode); @@ -116,10 +125,13 @@ export default function useSelection({ const isSelectionModeEnabledWithoutSelectableKeys = isSelectionModeEnabled && !selectableKeys.length && !originalSelectableCount; if (isMobileMissingSelectionMode) { - turnOnMobileSelectionMode(); + setSelectionModeEnabled(true); } else if (isDesktopWithoutSelectableKeys || isSelectionModeEnabledWithoutSelectableKeys) { - turnOffMobileSelectionMode(); + setSelectionModeEnabled(false); } + // setSelectionModeEnabled is omitted from the dependencies below because a caller is free to pass an inline + // callback, and re-running this effect on every render would fight the selection mode it just set. + // eslint-disable-next-line react-hooks/exhaustive-deps }, [selectionUsesNarrowLayout, isSelectionModeEnabled, selectedKeys.length, originalSelectableCount, selectableKeys.length]); // When selection mode is turned off, clear the list of selected keys, so that re-enabling selection mode doesn't retain rows @@ -133,7 +145,13 @@ export default function useSelection({ }, [isSelectionModeEnabled, selectedKeys.length, clearSelection, wasSelectionModeEnabled]); // When the table filters or the search string change, clear the current selection - useEffect(() => clearSelection(), [currentFilters, activeSearchString, clearSelection]); + useEffect(() => { + if (shouldPreserveSelectionOnSearchAndFilter) { + return; + } + + clearSelection(); + }, [currentFilters, activeSearchString, clearSelection, shouldPreserveSelectionOnSearchAndFilter]); // When the table unmounts, clear the selection. Should only run on unmount // eslint-disable-next-line react-hooks/exhaustive-deps diff --git a/src/components/Table/middlewares/sorting.ts b/src/components/Table/middlewares/sorting.ts index 7a6c33e62249..16a62d8fc07a 100644 --- a/src/components/Table/middlewares/sorting.ts +++ b/src/components/Table/middlewares/sorting.ts @@ -1,4 +1,7 @@ +import CONST from '@src/CONST'; + import type {SetStateAction} from 'react'; +import type {ValueOf} from 'type-fest'; import {useState} from 'react'; @@ -7,7 +10,7 @@ import type {Middleware, MiddlewareHookResult} from './types'; /** * The sort order of a column in the table. */ -type SortOrder = 'asc' | 'desc'; +type SortOrder = ValueOf; /** * The active sorting configuration of the table. @@ -61,6 +64,7 @@ type SortingMethods = { type UseSortingProps = { compareItems?: CompareItemsCallback; initialSortColumn?: ColumnKey; + initialSortOrder?: SortOrder; narrowLayoutSortColumn?: ColumnKey; shouldUseNarrowTableLayout?: boolean; onSortingChange?: (sorting: ActiveSorting) => void; @@ -113,13 +117,14 @@ function resolveActiveSorting( function useSorting({ compareItems, initialSortColumn, + initialSortOrder = CONST.SEARCH.SORT_ORDER.ASC, narrowLayoutSortColumn, shouldUseNarrowTableLayout, onSortingChange, }: UseSortingProps): UseSortingResult { const [userSorting, setUserSorting] = useState>({ columnKey: initialSortColumn, - order: 'asc', + order: initialSortOrder, }); const activeSorting = resolveActiveSorting(shouldUseNarrowTableLayout, narrowLayoutSortColumn, userSorting); diff --git a/src/components/Table/types.ts b/src/components/Table/types.ts index 4c71345b29d5..af82b04d96f3 100644 --- a/src/components/Table/types.ts +++ b/src/components/Table/types.ts @@ -6,7 +6,7 @@ import type {FilterConfig, FilteringMethods, IsItemInFilterCallback} from './mid import type {HighlightingMethods} from './middlewares/highlight'; import type {IsItemInSearchCallback, SearchingMethods} from './middlewares/searching'; import type {SelectionMethods} from './middlewares/selection'; -import type {ActiveSorting, CompareItemsCallback, SortingMethods} from './middlewares/sorting'; +import type {ActiveSorting, CompareItemsCallback, SortingMethods, SortOrder} from './middlewares/sorting'; /** * Defines the required minimum shape for each row of data in the table @@ -200,6 +200,12 @@ type TableProps>; @@ -219,6 +225,9 @@ type TableProps(); + // eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth + const {isSmallScreenWidth} = useResponsiveLayout(); + const rowData = processedData.at(rowIndex); + const isSelected = !!rowData?.selected; + const isRowDisabled = !!rowData?.disabled; + + const transactionReportID = getNonEmptyStringOnyxID(item.reportID); + const [transactionReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${transactionReportID}`); + const transactionPolicy = usePolicy(transactionReport?.policyID); + + // Merchant or description doubles as the row's accessible name, matching what the row visibly shows. + const accessibilityLabel = getMerchantName(item, translate) || getDescription(item); + + return ( + { + if (isSmallScreenWidth) { + return; + } + tableMethods.handleSingleRowSelection(item.keyForList); + }} + > + + + + + ); +} + +export default AddExistingExpenseTableRow; diff --git a/src/components/Tables/AddExistingExpenseTable/index.tsx b/src/components/Tables/AddExistingExpenseTable/index.tsx new file mode 100644 index 000000000000..1c6c1f112054 --- /dev/null +++ b/src/components/Tables/AddExistingExpenseTable/index.tsx @@ -0,0 +1,152 @@ +import type {CompareItemsCallback, FilterConfig, IsItemInFilterCallback, IsItemInSearchCallback, TableColumn, TableData, TableProps} from '@components/Table'; +import Table from '@components/Table'; + +import {useCurrencyListActions} from '@hooks/useCurrencyList'; +import useLocalize from '@hooks/useLocalize'; + +import tokenizedSearch from '@libs/tokenizedSearch'; +import {getAmount, getCreated, getCurrency, getDescription, getMerchant, isUnreportedTransaction} from '@libs/TransactionUtils'; + +import CONST from '@src/CONST'; +import type Transaction from '@src/types/onyx/Transaction'; + +import type {ListRenderItemInfo} from '@shopify/flash-list'; + +import AddExistingExpenseTableRow from './AddExistingExpenseTableRow'; + +type ExpenseTableColumnKey = 'date' | 'amount'; +type ExpenseTableFilterKey = 'status'; +type UnreportedExpenseTableRowData = Transaction & TableData; + +type AddExistingExpenseTableProps = Pick< + TableProps, + 'onEndReached' | 'onEndReachedThreshold' | 'ListFooterComponent' +> & { + data: UnreportedExpenseTableRowData[]; + selectedKeys: string[]; + onRowSelectionChange: (selectedRowKeys: string[]) => void; +}; + +function AddExistingExpenseTable({data, selectedKeys, onRowSelectionChange, onEndReached, onEndReachedThreshold, ListFooterComponent}: AddExistingExpenseTableProps) { + const {translate, localeCompare} = useLocalize(); + const {convertToDisplayString} = useCurrencyListActions(); + + const columns: Array> = [ + {key: 'date', label: translate('common.date'), sortable: true}, + {key: 'amount', label: translate('iou.amount'), sortable: true}, + ]; + + const filters: FilterConfig = { + status: { + label: translate('common.status'), + filterType: CONST.TABLES.FILTER_TYPE.MULTI_SELECT, + options: [ + {label: translate('common.unreported'), value: CONST.SEARCH.STATUS.EXPENSE.UNREPORTED}, + {label: translate('common.draft'), value: CONST.SEARCH.STATUS.EXPENSE.DRAFTS}, + ], + }, + }; + + const isItemInFilter: IsItemInFilterCallback = (item, values) => { + if (values.length === 0) { + return true; + } + + const includesUnreported = values.includes(CONST.SEARCH.STATUS.EXPENSE.UNREPORTED); + const includesDrafts = values.includes(CONST.SEARCH.STATUS.EXPENSE.DRAFTS); + const isUnreported = isUnreportedTransaction(item); + + if (includesUnreported && isUnreported) { + return true; + } + return includesDrafts && !isUnreported; + }; + + const isItemInSearch: IsItemInSearchCallback = (item, searchValue) => { + const results = tokenizedSearch([item], searchValue, (transaction) => { + const searchableFields: string[] = []; + + const merchant = getMerchant(transaction); + if (merchant !== CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT && merchant !== CONST.TRANSACTION.DEFAULT_MERCHANT) { + searchableFields.push(merchant); + } + + const description = getDescription(transaction); + if (description.trim()) { + searchableFields.push(description); + } + + const amount = getAmount(transaction); + const currency = getCurrency(transaction); + const formattedAmount = convertToDisplayString(amount, currency); + searchableFields.push(formattedAmount); + + // This allows users to search "2000" and find "$2,000.00" for example + const normalizedAmount = (amount / 100).toString(); + searchableFields.push(normalizedAmount); + + return searchableFields; + }); + + return results.length > 0; + }; + + const compareItems: CompareItemsCallback = (item1, item2, activeSorting) => { + const orderMultiplier = activeSorting.order === 'desc' ? -1 : 1; + + if (activeSorting.columnKey === 'amount') { + return (getAmount(item1) - getAmount(item2)) * orderMultiplier; + } + + // Default: sort by the expense date, matching how Spend > Expenses orders rows by default. The dates are + // compared as strings because an optimistic transaction stores a timestamp while a server one stores a plain + // date, and both formats still order lexicographically. + return localeCompare(getCreated(item1), getCreated(item2)) * orderMultiplier; + }; + + const renderExpenseTableRow = ({item, index}: ListRenderItemInfo) => ( + + ); + + return ( + + data={data} + title={translate('common.expenses')} + columns={columns} + selectionEnabled + shouldEnableSelectionInNarrowPaneModal + // Expenses are confirmed in one batch, so searching or filtering must not drop what is already picked. + shouldPreserveSelectionOnSearchAndFilter + // The skeleton appended while the next page loads continues the rows, so it draws the bottom corners. + shouldFooterRenderAsLastRow + selectedKeys={selectedKeys} + onRowSelectionChange={onRowSelectionChange} + initialSortColumn="date" + initialSortOrder={CONST.SEARCH.SORT_ORDER.DESC} + compareItems={compareItems} + filters={filters} + isItemInFilter={isItemInFilter} + isItemInSearch={isItemInSearch} + renderItem={renderExpenseTableRow} + keyExtractor={(item) => item.keyForList} + onEndReached={onEndReached} + onEndReachedThreshold={onEndReachedThreshold} + maintainVisibleContentPosition={{disabled: true}} + ListFooterComponent={ListFooterComponent} + > + + + + + + + + ); +} + +export default AddExistingExpenseTable; +export type {UnreportedExpenseTableRowData}; diff --git a/src/pages/AddExistingExpense.tsx b/src/pages/AddExistingExpense.tsx index 31a7ef0add91..f24c4a1ceba6 100644 --- a/src/pages/AddExistingExpense.tsx +++ b/src/pages/AddExistingExpense.tsx @@ -1,35 +1,31 @@ import AddExistingExpenseFooter from '@components/AddExistingExpenseFooter'; import EmptyStateComponent from '@components/EmptyStateComponent'; +import FixedFooter from '@components/FixedFooter'; import HeaderWithBackButton from '@components/HeaderWithBackButton'; -import {PressableWithFeedback} from '@components/Pressable'; import ScreenWrapper from '@components/ScreenWrapper'; import ScrollView from '@components/ScrollView'; -import DropdownButton from '@components/Search/FilterDropdowns/DropdownButton'; -import type {MultiSelectItem} from '@components/Search/FilterDropdowns/MultiSelectPopup'; -import MultiSelectPopup from '@components/Search/FilterDropdowns/MultiSelectPopup'; -import SelectionList from '@components/SelectionList'; -import type {ListItem, SelectionListHandle} from '@components/SelectionList/types'; import UnreportedExpensesSkeleton from '@components/Skeletons/UnreportedExpensesSkeleton'; -import Text from '@components/Text'; +import type {UnreportedExpenseTableRowData} from '@components/Tables/AddExistingExpenseTable'; +import AddExistingExpenseTable from '@components/Tables/AddExistingExpenseTable'; -import {useCurrencyListActions} from '@hooks/useCurrencyList'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; -import useDebouncedState from '@hooks/useDebouncedState'; import useIsInLandscapeMode from '@hooks/useIsInLandscapeMode'; import {useMemoizedLazyIllustrations} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; +import useMobileSelectionMode from '@hooks/useMobileSelectionMode'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import usePolicy from '@hooks/usePolicy'; +import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useThemeStyles from '@hooks/useThemeStyles'; +import {turnOffMobileSelectionMode} from '@libs/actions/MobileSelectionMode'; import {fetchUnreportedExpenses} from '@libs/actions/UnreportedExpenses'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import interceptAnonymousUser from '@libs/interceptAnonymousUser'; import type {AddExistingExpensesParamList} from '@libs/Navigation/types'; import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; -import tokenizedSearch from '@libs/tokenizedSearch'; -import {createUnreportedExpenses, getAmount, getCurrency, getDescription, getEligibleTransactionsToAdd, getMerchant, isUnreportedTransaction} from '@libs/TransactionUtils'; +import {createUnreportedExpenses, getEligibleTransactionsToAdd} from '@libs/TransactionUtils'; import Navigation from '@navigation/Navigation'; import type {PlatformStackScreenProps} from '@navigation/PlatformStackNavigation/types'; @@ -47,24 +43,18 @@ import getEmptyArray from '@src/types/utils/getEmptyArray'; import type {OnyxCollection} from 'react-native-onyx'; -import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react'; +import {useCallback, useEffect, useState} from 'react'; import {View} from 'react-native'; -import UnreportedExpenseListItem from './UnreportedExpenseListItem'; - type AddExistingExpensePageType = PlatformStackScreenProps; -type ExpenseStatus = typeof CONST.SEARCH.STATUS.EXPENSE.UNREPORTED | typeof CONST.SEARCH.STATUS.EXPENSE.DRAFTS; function AddExistingExpense({route}: AddExistingExpensePageType) { - const {convertToDisplayString} = useCurrencyListActions(); const {translate} = useLocalize(); const illustrations = useMemoizedLazyIllustrations(['FolderWithPapersAndWatch']); const [errorMessage, setErrorMessage] = useState(''); const [offset, setOffset] = useState(0); const {isOffline} = useNetwork(); - const [selectedIds, setSelectedIds] = useState(new Set()); - const [selectedStatuses, setSelectedStatuses] = useState>>([]); - const [searchValue, debouncedSearchValue, setSearchValue] = useDebouncedState(''); + const [selectedIds, setSelectedIds] = useState([]); const {reportID, backToReport} = route.params; const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); const [reportToConfirm] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${report?.reportID ?? CONST.REPORT.UNREPORTED_REPORT_ID}`); @@ -82,10 +72,16 @@ function AddExistingExpense({route}: AddExistingExpensePageType) { const [allOpenReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT, {selector: openExpenseReportIDsSelector}); const [openReportDrafts] = useOnyx(ONYXKEYS.COLLECTION.REPORT_DRAFT, {selector: openExpenseReportIDsSelector}); const isInLandscapeMode = useIsInLandscapeMode(); + const styles = useThemeStyles(); + // The table enables selection in this narrow pane modal off the real screen size, so the header has to match it. + // eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth + const {isSmallScreenWidth} = useResponsiveLayout(); + const isMobileSelectionModeEnabled = useMobileSelectionMode(); + const shouldShowSelectionModeHeader = isMobileSelectionModeEnabled && isSmallScreenWidth; const transactionsSelector = useCallback( - (transactions: OnyxCollection) => - getEligibleTransactionsToAdd({transactions, report, policy, cardList, currentUserAccountID, reportID, allOpenReports, openReportDrafts}), + (allTransactions: OnyxCollection) => + getEligibleTransactionsToAdd({transactions: allTransactions, report, policy, cardList, currentUserAccountID, reportID, allOpenReports, openReportDrafts}), [report, policy, cardList, currentUserAccountID, reportID, allOpenReports, openReportDrafts], ); const [transactions = getEmptyArray()] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION, {selector: transactionsSelector}); @@ -102,75 +98,16 @@ function AddExistingExpense({route}: AddExistingExpensePageType) { fetchUnreportedExpenses(0); }, []); - const styles = useThemeStyles(); - const selectionListRef = useRef>(null); - - const shouldShowTextInput = useMemo(() => { - return transactions.length >= CONST.STANDARD_LIST_ITEM_LIMIT; - }, [transactions.length]); - - const filteredTransactions = useMemo(() => { - if (!debouncedSearchValue.trim() || !shouldShowTextInput) { - return transactions; - } - - return tokenizedSearch(transactions, debouncedSearchValue, (transaction) => { - const searchableFields: string[] = []; - - const merchant = getMerchant(transaction); - if (merchant !== CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT && merchant !== CONST.TRANSACTION.DEFAULT_MERCHANT) { - searchableFields.push(merchant); - } - - const description = getDescription(transaction); - if (description.trim()) { - searchableFields.push(description); - } - - const amount = getAmount(transaction); - const currency = getCurrency(transaction); - const formattedAmount = convertToDisplayString(amount, currency); - searchableFields.push(formattedAmount); - - // This allows users to search "2000" and find "$2,000.00" for example - const normalizedAmount = (amount / 100).toString(); - searchableFields.push(normalizedAmount); + const unreportedExpenses: UnreportedExpenseTableRowData[] = createUnreportedExpenses(transactions).map((item) => ({ + ...item, + disabled: item.isDisabled, + })); - return searchableFields; - }); - }, [convertToDisplayString, debouncedSearchValue, shouldShowTextInput, transactions]); - - const selectedStatusValues = useMemo(() => selectedStatuses.map((s) => s.value), [selectedStatuses]); - - const statusFilteredTransactions = useMemo(() => { - if (selectedStatusValues.length === 0) { - return filteredTransactions; - } - - const includesUnreported = selectedStatusValues.includes(CONST.SEARCH.STATUS.EXPENSE.UNREPORTED); - const includesDrafts = selectedStatusValues.includes(CONST.SEARCH.STATUS.EXPENSE.DRAFTS); - - return filteredTransactions.filter((item) => { - const isUnreported = isUnreportedTransaction(item); - if (includesUnreported && isUnreported) { - return true; - } - if (includesDrafts && !isUnreported) { - return true; - } - return false; - }); - }, [filteredTransactions, selectedStatusValues]); - - const unreportedExpenses = useMemo(() => { - return createUnreportedExpenses(statusFilteredTransactions).map((item) => ({ - ...item, - isSelected: selectedIds.has(item.transactionID), - })); - }, [statusFilteredTransactions, selectedIds]); - - const footerContent = useMemo( - () => ( + const footerContent = ( + - ), - [selectedIds, report, reportToConfirm, policy, policyCategories, errorMessage, setErrorMessage], + ); - const headerMessage = useMemo(() => { - if ((debouncedSearchValue.trim() || selectedStatusValues.length > 0) && unreportedExpenses?.length === 0) { - return translate('common.noResultsFound'); - } - return ''; - }, [debouncedSearchValue, unreportedExpenses?.length, translate, selectedStatusValues.length]); - - const textInputOptions = useMemo( - () => ({ - value: searchValue, - label: shouldShowTextInput ? translate('iou.findExpense') : undefined, - onChangeText: setSearchValue, - }), - [searchValue, shouldShowTextInput, translate, setSearchValue], - ); - - const onSelectRow = useCallback( - (item: {transactionID: string}) => { - setSelectedIds((prevIds) => { - const newIds = new Set(prevIds); - if (newIds.has(item.transactionID)) { - newIds.delete(item.transactionID); - } else { - newIds.add(item.transactionID); - if (errorMessage) { - setErrorMessage(''); - } - } - return newIds; - }); - }, - [errorMessage], - ); - - const onSelectAll = () => { - setSelectedIds((prevSelectedIDs) => { - const availableUnreportedExpenses = unreportedExpenses.filter(({isDisabled}) => !isDisabled); - if (availableUnreportedExpenses.some(({transactionID}) => prevSelectedIDs.has(transactionID))) { - return new Set(); - } - if (errorMessage) { - setErrorMessage(''); - } - return new Set(availableUnreportedExpenses.map(({transactionID}) => transactionID)); - }); + // Must not read errorMessage. The Table re-runs its clear-selection effects when this callback's identity changes, + // so setting the error would immediately clear it again. + const onRowSelectionChange = (selectedRowKeys: string[]) => { + setSelectedIds(selectedRowKeys); + setErrorMessage(''); }; - const statusItems: Array> = useMemo( - () => [ - {text: translate('common.unreported'), value: CONST.SEARCH.STATUS.EXPENSE.UNREPORTED}, - {text: translate('common.draft'), value: CONST.SEARCH.STATUS.EXPENSE.DRAFTS}, - ], - [translate], - ); - - const statusPopoverComponent = useCallback( - (props: {closeOverlay: () => void}) => ( - - ), - [translate, statusItems, selectedStatuses], - ); - - const customListHeader = useMemo( - () => ( - - - {translate('workspace.people.selectAll')} - - s.text)} - PopoverComponent={statusPopoverComponent} - /> - - ), - [ - styles.flex1, - styles.flexRow, - styles.alignItemsCenter, - styles.justifyContentBetween, - styles.userSelectNone, - styles.textStrong, - styles.ph3, - onSelectAll, - translate, - selectedStatuses, - statusPopoverComponent, - ], - ); - - const listFooterContent = useMemo(() => { - if (shouldShowUnreportedTransactionsSkeletons) { - return ; - } - if (headerMessage) { - return ( - - {headerMessage} - - ); - } - return undefined; - }, [shouldShowUnreportedTransactionsSkeletons, headerMessage, styles.ph5, styles.pt3, styles.textLabel, styles.colorMuted]); + const paginationFooterContent = shouldShowUnreportedTransactionsSkeletons ? : undefined; - const hasSearchTerm = debouncedSearchValue.trim().length > 0; - const isShowingEmptyState = !hasSearchTerm && transactions.length === 0; + const isShowingEmptyState = transactions.length === 0; if (isShowingEmptyState && isLoadingUnreportedTransactions) { return ( @@ -381,28 +208,27 @@ function AddExistingExpense({route}: AddExistingExpensePageType) { focusTrapSettings={{active: false}} > - - data={unreportedExpenses} - ref={selectionListRef} - onSelectRow={onSelectRow} - onSelectAll={onSelectAll} - customListHeader={customListHeader} - style={{listHeaderWrapperStyle: styles.ph8}} - textInputOptions={textInputOptions} - shouldShowTextInput={shouldShowTextInput} - shouldShowListEmptyContent={false} - canSelectMultiple - ListItem={UnreportedExpenseListItem} - onEndReached={fetchMoreUnreportedTransactions} - onEndReachedThreshold={0.75} - addBottomSafeAreaPadding - listFooterContent={listFooterContent} - footerContent={footerContent} - disableMaintainingScrollPosition + title={shouldShowSelectionModeHeader ? translate('common.selectMultiple') : translate('iou.addExistingExpense')} + onBackButtonPress={() => { + if (shouldShowSelectionModeHeader) { + setSelectedIds([]); + turnOffMobileSelectionMode(); + return; + } + Navigation.goBack(); + }} /> + + + + {footerContent} ); } diff --git a/tests/ui/components/MoneyReportHeaderSelectionModeTest.tsx b/tests/ui/components/MoneyReportHeaderSelectionModeTest.tsx index 794c3eab3a71..a6b2bf67464b 100644 --- a/tests/ui/components/MoneyReportHeaderSelectionModeTest.tsx +++ b/tests/ui/components/MoneyReportHeaderSelectionModeTest.tsx @@ -34,6 +34,9 @@ jest.mock('@react-navigation/native', () => { return { ...actualNavigation, __esModule: true, + // The header only turns the shared selection mode off while it is the focused screen, and these tests render + // it on its own rather than inside a navigator. + useIsFocused: () => true, useRoute: () => { const SCREENS_MOCK = jest.requireActual<{default: typeof SCREENS}>('@src/SCREENS').default; return {key: 'rhp-route-key', name: SCREENS_MOCK.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT, params: {reportID: REPORT_ID}};