From d0891e0efe65721a49e5e83316ef393abcc6449d Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Sun, 14 Jun 2026 17:27:11 +0800 Subject: [PATCH 01/36] show search button --- .../Search/SearchPageHeader/SearchPageHeaderNarrow.tsx | 1 - src/components/Search/SearchPageHeader/SearchPageHeaderWide.tsx | 1 - 2 files changed, 2 deletions(-) diff --git a/src/components/Search/SearchPageHeader/SearchPageHeaderNarrow.tsx b/src/components/Search/SearchPageHeader/SearchPageHeaderNarrow.tsx index 3101e8bbb967..7187c1580672 100644 --- a/src/components/Search/SearchPageHeader/SearchPageHeaderNarrow.tsx +++ b/src/components/Search/SearchPageHeader/SearchPageHeaderNarrow.tsx @@ -22,7 +22,6 @@ function SearchPageHeaderNarrow({queryJSON, shouldShowLoadingBar = false, isMobi diff --git a/src/components/Search/SearchPageHeader/SearchPageHeaderWide.tsx b/src/components/Search/SearchPageHeader/SearchPageHeaderWide.tsx index 74b2e636e1a6..79c5942f9111 100644 --- a/src/components/Search/SearchPageHeader/SearchPageHeaderWide.tsx +++ b/src/components/Search/SearchPageHeader/SearchPageHeaderWide.tsx @@ -34,7 +34,6 @@ function SearchPageHeaderWide({queryJSON}: SearchPageHeaderWideProps) { ); From f35bba708db74027145b612229893a632156ae60 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Sun, 14 Jun 2026 17:27:36 +0800 Subject: [PATCH 02/36] rework search input to be a keyword search only --- src/ONYXKEYS.ts | 4 - src/ROUTES.ts | 5 +- .../AdvancedFiltersPopup/index.tsx | 8 +- .../Search/FilterDropdowns/SortByPopup.tsx | 3 +- .../Search/FilterDropdowns/SortOrderPopup.tsx | 3 +- .../Search/SearchAutocompleteInput.tsx | 2 - .../SearchActionsBarNarrow.tsx | 2 +- .../SearchPageHeader/SearchActionsBarWide.tsx | 9 +- .../SearchPageHeader/SearchPageInput.tsx | 82 ++++++ .../SearchPageInputNarrow.tsx | 94 ------- .../SearchPageHeader/SearchPageInputWide.tsx | 115 -------- .../SearchPageHeader/useSearchFiltersBar.tsx | 2 - .../SearchPageHeader/useSearchPageInput.tsx | 234 ---------------- src/components/Search/SearchQueryProvider.tsx | 8 +- .../Search/SearchRouter/SearchRouter.tsx | 2 - .../SearchRouter/SearchRouterContext.tsx | 35 +-- .../Search/hooks/useUpdateFilterQuery.tsx | 2 +- src/components/Search/index.tsx | 8 +- src/components/Search/types.ts | 12 - src/libs/Navigation/types.ts | 1 - src/libs/SearchParser/searchParser.js | 23 -- src/libs/SearchParser/searchParser.peggy | 23 -- src/libs/SearchQueryUtils.ts | 251 +----------------- src/libs/actions/Search.ts | 9 - src/pages/Search/SavedSearchList.tsx | 2 - .../Search/SearchAdvancedFiltersProvider.tsx | 17 +- .../StaticSearchPageInput.tsx | 38 ++- .../Search/SearchPageNarrow/Switches.tsx | 8 +- src/pages/Search/SearchPageNarrow/index.tsx | 219 ++++++--------- src/pages/Search/SearchTypeMenuNarrow.tsx | 5 +- src/pages/Search/SearchTypeMenuWide.tsx | 2 - .../Subscription/CardSection/CardSection.tsx | 2 +- src/styles/index.ts | 10 +- tests/actions/IOU/SearchUpdateTest.ts | 8 - tests/unit/NavigationFocusReturnTest.ts | 8 - .../unit/Search/SearchListRenderCountTest.tsx | 1 - tests/unit/Search/SearchQueryUtilsTest.ts | 86 +----- .../unit/Search/yourSpendQueryBuildersTest.ts | 3 - tests/unit/SearchParserTest.ts | 16 +- 39 files changed, 229 insertions(+), 1133 deletions(-) create mode 100644 src/components/Search/SearchPageHeader/SearchPageInput.tsx delete mode 100644 src/components/Search/SearchPageHeader/SearchPageInputNarrow.tsx delete mode 100644 src/components/Search/SearchPageHeader/SearchPageInputWide.tsx delete mode 100644 src/components/Search/SearchPageHeader/useSearchPageInput.tsx diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts index f6972f1de197..b6b0062f3c9c 100755 --- a/src/ONYXKEYS.ts +++ b/src/ONYXKEYS.ts @@ -626,9 +626,6 @@ const ONYXKEYS = { /** Stores the information about the recent searches */ RECENT_SEARCHES: 'nvp_recentSearches', - /** Stores the current search page context (e.g., whether to show the search query) */ - SEARCH_CONTEXT: 'searchContext', - /** Stores recently used currencies */ RECENTLY_USED_CURRENCIES: 'nvp_recentlyUsedCurrencies', @@ -1436,7 +1433,6 @@ type OnyxValuesMapping = { [ONYXKEYS.NVP_TRY_NEW_DOT]: OnyxTypes.TryNewDot; [ONYXKEYS.RECENT_SEARCHES]: Record; [ONYXKEYS.SAVED_SEARCHES]: OnyxTypes.SaveSearch; - [ONYXKEYS.SEARCH_CONTEXT]: OnyxTypes.SearchContext; [ONYXKEYS.RECENTLY_USED_CURRENCIES]: string[]; [ONYXKEYS.ACTIVE_CLIENTS]: string[]; [ONYXKEYS.DEVICE_ID]: string; diff --git a/src/ROUTES.ts b/src/ROUTES.ts index 03d6054d2a70..a7e81ac96a9d 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -875,9 +875,8 @@ const ROUTES = { SEARCH_ROUTER: 'search-router', SEARCH_ROOT: { route: 'search', - getRoute: ({query, rawQuery, name}: {query: SearchQueryString; rawQuery?: SearchQueryString; name?: string}) => { - const rawQuerySegment = rawQuery ? `&rawQuery=${encodeURIComponent(rawQuery)}` : ''; - return `search?q=${encodeURIComponent(query)}${name ? `&name=${name}` : ''}${rawQuerySegment}` as const; + getRoute: ({query, name}: {query: SearchQueryString; name?: string}) => { + return `search?q=${encodeURIComponent(query)}${name ? `&name=${name}` : ''}` as const; }, }, SEARCH_ROOT_VERIFY_ACCOUNT: `search/${VERIFY_ACCOUNT}`, diff --git a/src/components/Search/FilterDropdowns/AdvancedFilters/AdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/AdvancedFilters/AdvancedFiltersPopup/index.tsx index 28a9246bedcb..6a64fc93192a 100644 --- a/src/components/Search/FilterDropdowns/AdvancedFilters/AdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/AdvancedFilters/AdvancedFiltersPopup/index.tsx @@ -9,7 +9,6 @@ import useOnyx from '@hooks/useOnyx'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; import useWindowDimensions from '@hooks/useWindowDimensions'; -import {setSearchContext} from '@libs/actions/Search'; import type {SearchFilter} from '@libs/SearchUIUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -47,12 +46,7 @@ function AdvancedFiltersPopup({queryJSON}: AdvancedFiltersPopupProps) { values={searchAdvancedFiltersForm} filterKey={selectedFilter} policyIDQuery={queryJSON.policyID} - onChange={(values) => { - updateFilterQueryParams(values); - if (values.keyword) { - setSearchContext(true); - } - }} + onChange={updateFilterQueryParams} /> diff --git a/src/components/Search/FilterDropdowns/SortByPopup.tsx b/src/components/Search/FilterDropdowns/SortByPopup.tsx index 3624b564f96d..cdbed340f194 100644 --- a/src/components/Search/FilterDropdowns/SortByPopup.tsx +++ b/src/components/Search/FilterDropdowns/SortByPopup.tsx @@ -65,9 +65,8 @@ function SortByPopup({searchResults, queryJSON, groupBy, onSort, onSortOrderPres clearSelectedTransactions(); const newQuery = buildSearchQueryString({...queryJSON, sortBy: column}); onSort(); - // We want to explicitly clear stale rawQuery since it's only used for manually typed-in queries. close(() => { - Navigation.setParams({q: newQuery, rawQuery: undefined}); + Navigation.setParams({q: newQuery}); }); }; diff --git a/src/components/Search/FilterDropdowns/SortOrderPopup.tsx b/src/components/Search/FilterDropdowns/SortOrderPopup.tsx index 33e66e4a01f6..65d072352c6b 100644 --- a/src/components/Search/FilterDropdowns/SortOrderPopup.tsx +++ b/src/components/Search/FilterDropdowns/SortOrderPopup.tsx @@ -23,9 +23,8 @@ function SortOrderPopup({queryJSON, onSort, onBackButtonPress, closeOverlay}: So clearSelectedTransactions(); const newQuery = buildSearchQueryString({...queryJSON, sortOrder}); onSort(); - // We want to explicitly clear stale rawQuery since it's only used for manually typed-in queries. close(() => { - Navigation.setParams({q: newQuery, rawQuery: undefined}); + Navigation.setParams({q: newQuery}); }); }; diff --git a/src/components/Search/SearchAutocompleteInput.tsx b/src/components/Search/SearchAutocompleteInput.tsx index 5f1f80c5d3f7..11c919a79caa 100644 --- a/src/components/Search/SearchAutocompleteInput.tsx +++ b/src/components/Search/SearchAutocompleteInput.tsx @@ -17,7 +17,6 @@ import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; -import {setSearchContext} from '@libs/actions/Search'; import scheduleOnLiveMarkdownRuntime from '@libs/scheduleOnLiveMarkdownRuntime'; import {getAutocompleteCategories, getAutocompleteTags, parseForLiveMarkdown} from '@libs/SearchAutocompleteUtils'; import {expensifyLoginsSelector} from '@libs/UserUtils'; @@ -194,7 +193,6 @@ function SearchAutocompleteInput({ const clearInput = () => { onSearchQueryChange(''); - setSearchContext(false); }; const inputWidth = isFullWidth ? styles.w100 : {width: variables.popoverWidth}; diff --git a/src/components/Search/SearchPageHeader/SearchActionsBarNarrow.tsx b/src/components/Search/SearchPageHeader/SearchActionsBarNarrow.tsx index 73d85a6e306a..7fe51d158f31 100644 --- a/src/components/Search/SearchPageHeader/SearchActionsBarNarrow.tsx +++ b/src/components/Search/SearchPageHeader/SearchActionsBarNarrow.tsx @@ -21,7 +21,7 @@ function SearchActionsBarNarrow({queryJSON, searchResults, onSort}: SearchAction const styles = useThemeStyles(); return ( - + void; }; -function SearchActionsBarWide({queryJSON, searchResults, handleSearch, onSort}: SearchActionsBarWideProps) { +function SearchActionsBarWide({queryJSON, searchResults, onSort}: SearchActionsBarWideProps) { const styles = useThemeStyles(); const {selected} = useSelectionCounts(); const hasSelectedItems = selected > 0; @@ -34,10 +34,7 @@ function SearchActionsBarWide({queryJSON, searchResults, handleSearch, onSort}: ) : ( <> - + diff --git a/src/components/Search/SearchPageHeader/SearchPageInput.tsx b/src/components/Search/SearchPageHeader/SearchPageInput.tsx new file mode 100644 index 000000000000..05d2e993da65 --- /dev/null +++ b/src/components/Search/SearchPageHeader/SearchPageInput.tsx @@ -0,0 +1,82 @@ +// NOTE: This component has a static twin in SearchPageNarrow/StaticSearchPageInput.tsx +// used for fast perceived performance. If you change the UI here, verify the +// static version still looks visually identical. +import React, {useEffect, useState} from 'react'; +import type {SearchQueryJSON} from '@components/Search/types'; +import TextInput from '@components/TextInput'; +import useLocalize from '@hooks/useLocalize'; +import useResponsiveLayout from '@hooks/useResponsiveLayout'; +import useTheme from '@hooks/useTheme'; +import useThemeStyles from '@hooks/useThemeStyles'; +import Navigation from '@libs/Navigation/Navigation'; +import {buildFilterValuesString, getKeywordQueryWithCurrentSearchContext, getQueryWithUpdatedValues} from '@libs/SearchQueryUtils'; +import CONST from '@src/CONST'; +import ROUTES from '@src/ROUTES'; +import KeyboardUtils from '@src/utils/keyboard'; + +type SearchPageInputProps = { + queryJSON: SearchQueryJSON; + onFocus?: () => void; +}; + +function SearchPageInput({queryJSON, onFocus}: SearchPageInputProps) { + const {translate} = useLocalize(); + const styles = useThemeStyles(); + const theme = useTheme(); + const {shouldUseNarrowLayout} = useResponsiveLayout(); + + const [textInputValue, setTextInputValue] = useState(''); + + const keywordFilters = queryJSON.flatFilters.find((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD)?.filters ?? []; + const keywordQuery = buildFilterValuesString(CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD, keywordFilters).trim(); + + function submitSearch() { + const queryWithContext = getKeywordQueryWithCurrentSearchContext(textInputValue, queryJSON); + const updatedQuery = getQueryWithUpdatedValues(queryWithContext); + + if (!updatedQuery) { + return; + } + + Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query: updatedQuery})); + } + + useEffect(() => { + setTextInputValue(keywordQuery); + }, [keywordQuery]); + + return ( + { + if (shouldUseNarrowLayout) { + KeyboardUtils.dismiss().then(submitSearch); + return; + } + submitSearch(); + }} + containerStyles={[shouldUseNarrowLayout ? styles.flex1 : undefined]} + textInputContainerStyles={[styles.pb0, shouldUseNarrowLayout ? styles.ph3 : styles.ph2]} + inputStyle={[styles.w100, styles.lineHeightUndefined, shouldUseNarrowLayout ? undefined : styles.fontSizeLabel]} + touchableInputWrapperStyle={shouldUseNarrowLayout ? styles.searchPageInputNarrowTouchableWrapper : styles.searchPageInputWideTouchableWrapper} + clearButtonStyle={shouldUseNarrowLayout ? undefined : styles.mh0} + placeholderTextColor={theme.textSupporting} + shouldShowClearButton={!!textInputValue} + shouldHideClearButton={false} + onClearInput={() => setTextInputValue('')} + onFocus={onFocus} + /> + ); +} + +export default SearchPageInput; +export type {SearchPageInputProps}; diff --git a/src/components/Search/SearchPageHeader/SearchPageInputNarrow.tsx b/src/components/Search/SearchPageHeader/SearchPageInputNarrow.tsx deleted file mode 100644 index a141048624e1..000000000000 --- a/src/components/Search/SearchPageHeader/SearchPageInputNarrow.tsx +++ /dev/null @@ -1,94 +0,0 @@ -// NOTE: This component has a static twin in SearchPageNarrow/StaticSearchPageInput.tsx -// used for fast perceived performance. If you change the UI here, verify the -// static version still looks visually identical. -import React, {useEffect} from 'react'; -import {View} from 'react-native'; -import Animated from 'react-native-reanimated'; -import SearchAutocompleteList from '@components/Search/SearchAutocompleteList'; -import SearchInputSelectionWrapper from '@components/Search/SearchInputSelectionWrapper'; -import type {SearchQueryJSON} from '@components/Search/types'; -import useThemeStyles from '@hooks/useThemeStyles'; -import KeyboardUtils from '@src/utils/keyboard'; -import useSearchPageInput from './useSearchPageInput'; - -type SearchPageInputNarrowProps = { - queryJSON: SearchQueryJSON; - searchRouterListVisible: boolean; - hideSearchRouterList: () => void; - onSearchRouterFocus: () => void; - handleSearch: (value: string) => void; - skipSkeleton: boolean; -}; -function SearchPageInputNarrow({queryJSON, searchRouterListVisible, hideSearchRouterList, onSearchRouterFocus, handleSearch, skipSkeleton}: SearchPageInputNarrowProps) { - const styles = useThemeStyles(); - - const { - autocompleteSubstitutions, - autocompleteQueryValue, - searchQueryItems, - selection, - textInputRef, - textInputValue, - handleKeyPress, - handleSearchAction, - onListItemPress, - onSearchQueryChange, - submitSearch, - } = useSearchPageInput({ - queryJSON, - onSearch: handleSearch, - onSubmit: hideSearchRouterList, - }); - - // useEffect for blurring TextInput when we cancel SearchRouter interaction on narrow layout - useEffect(() => { - if (!!searchRouterListVisible || !textInputRef.current?.isFocused()) { - return; - } - textInputRef.current.blur(); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [searchRouterListVisible]); - - return ( - - - - { - KeyboardUtils.dismiss().then(() => submitSearch(textInputValue)); - }} - autoFocus={false} - onFocus={onSearchRouterFocus} - touchableInputWrapperStyle={styles.searchPageInputNarrowTouchableWrapper} - wrapperStyle={{...styles.searchAutocompleteInputResults, ...styles.br2}} - wrapperFocusedStyle={styles.searchAutocompleteInputResultsFocused} - ref={textInputRef} - onKeyPress={handleKeyPress} - skipSkeleton={skipSkeleton} - /> - - - {!!searchRouterListVisible && ( - - )} - - ); -} - -export default SearchPageInputNarrow; -export type {SearchPageInputNarrowProps}; diff --git a/src/components/Search/SearchPageHeader/SearchPageInputWide.tsx b/src/components/Search/SearchPageHeader/SearchPageInputWide.tsx deleted file mode 100644 index bd3b50034ddc..000000000000 --- a/src/components/Search/SearchPageHeader/SearchPageInputWide.tsx +++ /dev/null @@ -1,115 +0,0 @@ -import {useIsFocused} from '@react-navigation/native'; -import React, {useEffect, useRef, useState} from 'react'; -import {View} from 'react-native'; -import SearchAutocompleteList from '@components/Search/SearchAutocompleteList'; -import SearchInputSelectionWrapper from '@components/Search/SearchInputSelectionWrapper'; -import {useSearchRouterActions} from '@components/Search/SearchRouter/SearchRouterContext'; -import type {SearchQueryJSON} from '@components/Search/types'; -import type {SelectionListWithSectionsHandle} from '@components/SelectionList/SelectionListWithSections/types'; -import useTheme from '@hooks/useTheme'; -import useThemeStyles from '@hooks/useThemeStyles'; -import useSearchPageInput from './useSearchPageInput'; - -type SearchPageInputWideProps = { - queryJSON: SearchQueryJSON; - handleSearch: (value: string) => void; -}; - -function SearchPageInputWide({queryJSON, handleSearch}: SearchPageInputWideProps) { - const styles = useThemeStyles(); - const theme = useTheme(); - const isFocused = useIsFocused(); - const {registerSearchPageInput} = useSearchRouterActions(); - - const [isAutocompleteListVisible, setIsAutocompleteListVisible] = useState(false); - - const listRef = useRef(null); - - const { - autocompleteSubstitutions, - autocompleteQueryValue, - searchQueryItems, - selection, - textInputRef, - textInputValue, - handleKeyPress, - handleSearchAction, - onListItemPress, - onSearchQueryChange, - submitSearch, - } = useSearchPageInput({ - queryJSON, - onSearch: handleSearch, - onSubmit: () => setIsAutocompleteListVisible(false), - }); - - useEffect(() => { - if (!isFocused || !textInputRef.current) { - return; - } - - registerSearchPageInput(textInputRef.current); - }, [isFocused, registerSearchPageInput, textInputRef]); - - const hideAutocompleteList = () => setIsAutocompleteListVisible(false); - const showAutocompleteList = () => setIsAutocompleteListVisible(true); - - const autocompleteInputStyle = isAutocompleteListVisible - ? [styles.border, styles.borderRadiusComponentLarge, styles.pAbsolute, styles.pt2, styles.w100, styles.zIndex10, {top: 0, maxWidth: 675}, {boxShadow: theme.shadow}] - : []; - const inputWrapperActiveStyle = isAutocompleteListVisible ? styles.ph2 : null; - - return ( - <> - {/* An empty view as the input placeholder so that the applied filters won't move when the real input position becomes absolute */} - {isAutocompleteListVisible && } - - { - const focusedOption = listRef.current?.getFocusedOption(); - if (focusedOption) { - return; - } - submitSearch(textInputValue); - }} - autoFocus={false} - onFocus={showAutocompleteList} - onBlur={hideAutocompleteList} - wrapperStyle={{...styles.searchAutocompleteInputResults, ...styles.br2}} - wrapperFocusedStyle={styles.searchAutocompleteInputResultsFocused} - outerWrapperStyle={[inputWrapperActiveStyle, styles.flex1]} - ref={textInputRef} - selection={selection} - substitutionMap={autocompleteSubstitutions} - onKeyPress={handleKeyPress} - /> - {isAutocompleteListVisible && ( - - - - )} - - - ); -} - -export default SearchPageInputWide; diff --git a/src/components/Search/SearchPageHeader/useSearchFiltersBar.tsx b/src/components/Search/SearchPageHeader/useSearchFiltersBar.tsx index e0a67471c22e..92e9a94d07df 100644 --- a/src/components/Search/SearchPageHeader/useSearchFiltersBar.tsx +++ b/src/components/Search/SearchPageHeader/useSearchFiltersBar.tsx @@ -13,7 +13,6 @@ import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import {close} from '@libs/actions/Modal'; -import {setSearchContext} from '@libs/actions/Search'; import {getAdvancedFiltersToReset} from '@libs/SearchQueryUtils'; import {FILTER_VIEW_MAP, isAmountFilterKey, isDateFilterKey, mapFiltersFormToLabelValueList, SKIPPED_SEARCH_FILTERS} from '@libs/SearchUIUtils'; import type {SearchFilter} from '@libs/SearchUIUtils'; @@ -183,7 +182,6 @@ function useSearchFiltersBar(queryJSON: SearchQueryJSON): UseSearchFiltersBarRes const clearFilters = () => { setFilterQueryParams(getAdvancedFiltersToReset(searchAdvancedFiltersForm ?? {})); - setSearchContext(false); }; return { diff --git a/src/components/Search/SearchPageHeader/useSearchPageInput.tsx b/src/components/Search/SearchPageHeader/useSearchPageInput.tsx deleted file mode 100644 index 0522d14a1435..000000000000 --- a/src/components/Search/SearchPageHeader/useSearchPageInput.tsx +++ /dev/null @@ -1,234 +0,0 @@ -import {deepEqual} from 'fast-equals'; -import {useEffect, useRef, useState} from 'react'; -import type {TextInputKeyPressEvent} from 'react-native'; -import {usePersonalDetails} from '@components/OnyxListItemProvider'; -import type {AnimatedTextInputRef} from '@components/RNTextInput'; -import {isSearchQueryItem} from '@components/Search/SearchList/ListItem/SearchQueryListItem'; -import type {SearchQueryItem} from '@components/Search/SearchList/ListItem/SearchQueryListItem'; -import {buildSubstitutionsMap} from '@components/Search/SearchRouter/buildSubstitutionsMap'; -import {getQueryWithSubstitutions} from '@components/Search/SearchRouter/getQueryWithSubstitutions'; -import type {SubstitutionMap} from '@components/Search/SearchRouter/getQueryWithSubstitutions'; -import {getUpdatedSubstitutionsMap} from '@components/Search/SearchRouter/getUpdatedSubstitutionsMap'; -import updateAutocompleteSubstitutionsForSelection from '@components/Search/SearchRouter/updateAutocompleteSubstitutionsForSelection'; -import type {SearchQueryJSON, SearchQueryString} from '@components/Search/types'; -import useFeedKeysWithAssignedCards from '@hooks/useFeedKeysWithAssignedCards'; -import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; -import useLocalize from '@hooks/useLocalize'; -import useOnyx from '@hooks/useOnyx'; -import useReportAttributes from '@hooks/useReportAttributes'; -import useThemeStyles from '@hooks/useThemeStyles'; -import {navigateToAndOpenReport} from '@libs/actions/Report'; -import {setSearchContext} from '@libs/actions/Search'; -import Navigation from '@libs/Navigation/Navigation'; -import {getAllTaxRates} from '@libs/PolicyUtils'; -import type {OptionData} from '@libs/ReportUtils'; -import {getAutocompleteQueryWithComma, getTrimmedUserSearchQueryPreservingComma} from '@libs/SearchAutocompleteUtils'; -import {buildUserReadableQueryString, getKeywordQueryWithCurrentSearchContext, getQueryWithUpdatedValues, sanitizeSearchValue} from '@libs/SearchQueryUtils'; -import StringUtils from '@libs/StringUtils'; -import CONST from '@src/CONST'; -import ONYXKEYS from '@src/ONYXKEYS'; -import ROUTES from '@src/ROUTES'; -import {hasSeenTourSelector} from '@src/selectors/Onboarding'; -import {accountIDSelector} from '@src/selectors/Session'; - -type UseSearchPageInputProps = { - queryJSON: SearchQueryJSON; - onSearch: (value: string) => void; - onSubmit: () => void; -}; - -function useSearchPageInput({queryJSON, onSearch, onSubmit}: UseSearchPageInputProps) { - const styles = useThemeStyles(); - const {translate} = useLocalize(); - const expensifyIcons = useMemoizedLazyExpensifyIcons(['MagnifyingGlass']); - const feedKeysWithCards = useFeedKeysWithAssignedCards(); - const personalDetails = usePersonalDetails(); - const reportAttributes = useReportAttributes(); - - const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY); - const [searchContext] = useOnyx(ONYXKEYS.SEARCH_CONTEXT); - const [isSelfTourViewed] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: hasSeenTourSelector}); - const [currentUserAccountID = -1] = useOnyx(ONYXKEYS.SESSION, {selector: accountIDSelector}); - const [introSelected] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED); - const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); - const [personalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST); - const [allFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER); - const [betas] = useOnyx(ONYXKEYS.BETAS); - - const [autocompleteSubstitutions, setAutocompleteSubstitutions] = useState({}); - const [textInputValue, setTextInputValue] = useState(''); - // The input text that was last used for autocomplete; needed for the SearchAutocompleteList when browsing list via arrow keys - const [autocompleteQueryValue, setAutocompleteQueryValue] = useState(''); - const [selection, setSelection] = useState({start: textInputValue.length, end: textInputValue.length}); - - const textInputRef = useRef(null); - const hasMountedRef = useRef(false); - - const {inputQuery: originalInputQuery} = queryJSON; - const taxRates = getAllTaxRates(policies); - const shouldShowQuery = searchContext?.shouldShowSearchQuery ?? false; - const queryText = buildUserReadableQueryString({ - queryJSON, - PersonalDetails: personalDetails, - reports, - taxRates, - cardList: personalAndWorkspaceCards, - cardFeeds: allFeeds, - policies, - currentUserAccountID, - autoCompleteWithSpace: true, - translate, - feedKeysWithCards, - reportAttributes, - }); - - useEffect(() => { - hasMountedRef.current = true; - }, []); - - useEffect(() => { - const substitutionsMap = buildSubstitutionsMap( - originalInputQuery, - personalDetails, - reports, - taxRates, - personalAndWorkspaceCards, - allFeeds, - policies, - currentUserAccountID, - translate, - reportAttributes, - ); - setAutocompleteSubstitutions(substitutionsMap); - }, [allFeeds, personalAndWorkspaceCards, originalInputQuery, personalDetails, reports, taxRates, policies, currentUserAccountID, translate, reportAttributes]); - - useEffect(() => { - const newValue = shouldShowQuery ? queryText : ''; - - setTextInputValue(newValue); - setAutocompleteQueryValue(newValue); - }, [queryText, shouldShowQuery]); - - function handleSearchAction(value: string) { - // Skip calling handleSearch on the initial mount - if (!hasMountedRef.current) { - return; - } - onSearch(value); - } - - function submitSearch(queryString: SearchQueryString, shouldSkipAmountConversion = false) { - const queryWithSubstitutions = getQueryWithSubstitutions(queryString, autocompleteSubstitutions, currentUserAccountID); - const queryWithContext = getKeywordQueryWithCurrentSearchContext(queryWithSubstitutions, queryJSON); - const updatedQuery = getQueryWithUpdatedValues(queryWithContext, shouldSkipAmountConversion); - - if (!updatedQuery) { - return; - } - - setSearchContext(true); - Navigation.navigate( - ROUTES.SEARCH_ROOT.getRoute({ - query: updatedQuery, - rawQuery: shouldSkipAmountConversion ? undefined : queryWithSubstitutions, - }), - ); - onSubmit(); - if (updatedQuery !== originalInputQuery) { - setTextInputValue(''); - setAutocompleteQueryValue(''); - } - } - - function handleKeyPress(e: TextInputKeyPressEvent) { - const keyEvent = e as unknown as KeyboardEvent; - - if (keyEvent.key === CONST.KEYBOARD_SHORTCUTS.ESCAPE.shortcutKey && textInputRef.current?.isFocused()) { - keyEvent.preventDefault(); - textInputRef.current.blur(); - } - } - - function onSearchQueryChange(userQuery: string) { - const singleLineUserQuery = StringUtils.lineBreaksToSpaces(userQuery, true); - const updatedUserQuery = getAutocompleteQueryWithComma(textInputValue, singleLineUserQuery); - setTextInputValue(updatedUserQuery); - setAutocompleteQueryValue(updatedUserQuery); - - const updatedSubstitutionsMap = getUpdatedSubstitutionsMap(singleLineUserQuery, autocompleteSubstitutions); - if (!deepEqual(autocompleteSubstitutions, updatedSubstitutionsMap)) { - setAutocompleteSubstitutions(updatedSubstitutionsMap); - } - } - - function onListItemPress(item: OptionData | SearchQueryItem) { - if (isSearchQueryItem(item)) { - if (!item.searchQuery) { - return; - } - - if (item.searchItemType === CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.AUTOCOMPLETE_SUGGESTION && textInputValue) { - const fieldKey = item.mapKey?.includes(':') ? item.mapKey.split(':').at(0) : item.mapKey; - const trimmedUserSearchQuery = getTrimmedUserSearchQueryPreservingComma(textInputValue, fieldKey); - const newSearchQuery = `${trimmedUserSearchQuery}${sanitizeSearchValue(item.searchQuery)}\u00A0`; - - onSearchQueryChange(newSearchQuery); - setSelection({start: newSearchQuery.length, end: newSearchQuery.length}); - - updateAutocompleteSubstitutionsForSelection({ - newSearchQuery, - fieldKey, - mapKey: item.mapKey, - searchQuery: item.searchQuery, - autocompleteID: item.autocompleteID, - substitutions: autocompleteSubstitutions, - setAutocompleteSubstitutions, - }); - } else if (item.searchItemType === CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.SEARCH) { - submitSearch(item.searchQuery, item.keyForList !== CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.FIND_ITEM); - } - return; - } - // Call onSubmit to ensure the SearchRouter closes when navigating to a report from search results. - // This prevents `isBlockingViewVisible` from remaining `true` after navigating from the SearchRouter. - Navigation.setNavigationActionToMicrotaskQueue(() => onSubmit()); - if (item?.reportID) { - Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(item?.reportID)); - } else if ('login' in item) { - navigateToAndOpenReport(item.login ? [item.login] : [], personalDetails, currentUserAccountID, introSelected, isSelfTourViewed, betas, false); - } - } - - const searchQueryItems = textInputValue?.trim() - ? [ - { - text: textInputValue, - singleIcon: expensifyIcons.MagnifyingGlass, - searchQuery: textInputValue, - itemStyle: styles.activeComponentBG, - keyForList: CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.FIND_ITEM, - searchItemType: CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.SEARCH, - }, - ] - : undefined; - - return { - allFeeds, - autocompleteSubstitutions, - autocompleteQueryValue, - personalAndWorkspaceCards, - personalDetails, - reports, - searchQueryItems, - selection, - textInputRef, - textInputValue, - handleKeyPress, - handleSearchAction, - onListItemPress, - onSearchQueryChange, - submitSearch, - }; -} - -export default useSearchPageInput; diff --git a/src/components/Search/SearchQueryProvider.tsx b/src/components/Search/SearchQueryProvider.tsx index c4ce93687c46..4734ad95b919 100644 --- a/src/components/Search/SearchQueryProvider.tsx +++ b/src/components/Search/SearchQueryProvider.tsx @@ -21,19 +21,13 @@ function selectSearchQueryParam(state: NavigationState | undefined) { return focused?.name === SCREENS.SEARCH.ROOT ? (focused.params?.q as string | undefined) : undefined; } -function selectSearchRawQueryParam(state: NavigationState | undefined) { - const focused = getDeepestFocusedScreen(state); - return focused?.name === SCREENS.SEARCH.ROOT ? (focused.params?.rawQuery as string | undefined) : undefined; -} - function SearchQueryProvider({children}: SearchQueryProviderProps) { const navigation = useNavigation(); // Extract only the primitive values we need from the focused screen to avoid // re-renders from new object references returned by getDeepestFocusedScreen. const queryParam = useRootNavigationState((state) => selectSearchQueryParam(state ?? navigation.getState())); - const rawQueryParam = useRootNavigationState((state) => selectSearchRawQueryParam(state ?? navigation.getState())); const definedQueryParam = usePreviousDefined(queryParam) ?? buildSearchQueryString(); - const currentSearchQueryJSON = buildSearchQueryJSON(definedQueryParam, rawQueryParam); + const currentSearchQueryJSON = buildSearchQueryJSON(definedQueryParam); const {defaultCardFeed} = useCardFeedsForDisplay(); const {accountID} = useCurrentUserPersonalDetails(); diff --git a/src/components/Search/SearchRouter/SearchRouter.tsx b/src/components/Search/SearchRouter/SearchRouter.tsx index db8a64bc421e..5f689defcf2a 100644 --- a/src/components/Search/SearchRouter/SearchRouter.tsx +++ b/src/components/Search/SearchRouter/SearchRouter.tsx @@ -41,7 +41,6 @@ import StringUtils from '@libs/StringUtils'; import Navigation from '@navigation/Navigation'; import variables from '@styles/variables'; import {navigateToAndOpenReport, searchInServer} from '@userActions/Report'; -import {setSearchContext} from '@userActions/Search'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; @@ -279,7 +278,6 @@ function SearchRouter({onRouterClose, shouldHideInputCaret, isSearchRouterDispla backHistory(() => { onRouterClose(); - setSearchContext(true); Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query: updatedQuery})); }); diff --git a/src/components/Search/SearchRouter/SearchRouterContext.tsx b/src/components/Search/SearchRouter/SearchRouterContext.tsx index 165c638a3475..a9ca74e21090 100644 --- a/src/components/Search/SearchRouter/SearchRouterContext.tsx +++ b/src/components/Search/SearchRouter/SearchRouterContext.tsx @@ -1,12 +1,7 @@ import React, {useContext, useEffect, useRef, useState} from 'react'; -import type {AnimatedTextInputRef} from '@components/RNTextInput'; -import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; -import {navigationRef} from '@libs/Navigation/Navigation'; import {cancelSpan, endSpan, getSpan, startSpan} from '@libs/telemetry/activeSpans'; import {close} from '@userActions/Modal'; import CONST from '@src/CONST'; -import NAVIGATORS from '@src/NAVIGATORS'; -import SCREENS from '@src/SCREENS'; import type ChildrenProps from '@src/types/utils/ChildrenProps'; import {closeSearch, openSearch} from './toggleSearch'; @@ -32,8 +27,6 @@ type SearchRouterActionsContextType = { openSearchRouter: (query?: string) => void; closeSearchRouter: () => void; toggleSearch: () => void; - registerSearchPageInput: (ref: AnimatedTextInputRef) => void; - unregisterSearchPageInput: () => void; }; type HistoryState = { @@ -44,8 +37,6 @@ const defaultSearchRouterActionsContext: SearchRouterActionsContextType = { openSearchRouter: () => {}, closeSearchRouter: () => {}, toggleSearch: () => {}, - registerSearchPageInput: () => {}, - unregisterSearchPageInput: () => {}, }; const SearchRouterStateContext = React.createContext({isSearchRouterDisplayed: false}); @@ -58,7 +49,6 @@ const canListenPopState = typeof window !== 'undefined' && typeof window.addEven function SearchRouterContextProvider({children}: ChildrenProps) { const [isSearchRouterDisplayed, setIsSearchRouterDisplayed] = useState(false); const searchRouterDisplayedRef = useRef(false); - const searchPageInputRef = useRef(undefined); useEffect(() => { if (!canListenPopState) { return; @@ -142,21 +132,8 @@ function SearchRouterContextProvider({children}: ChildrenProps) { // There are callbacks that live outside of React render-loop and interact with SearchRouter // So we need a function that is based on ref to correctly open/close it - // When user is on `/search` page we focus the Input instead of showing router const toggleSearch = () => { - const searchFullScreenRoutes = navigationRef.getRootState()?.routes.findLast((route) => route.name === NAVIGATORS.SEARCH_FULLSCREEN_NAVIGATOR); - const lastRoute = searchFullScreenRoutes?.state?.routes?.at(-1); - const isUserOnSearchPage = isSearchTopmostFullScreenRoute() && lastRoute?.name === SCREENS.SEARCH.ROOT; - - if (isUserOnSearchPage && searchPageInputRef.current) { - if (searchPageInputRef.current.isFocused()) { - searchPageInputRef.current.blur(); - } else { - startSearchRouterOpenSpan(); - startListRenderSpan(); - searchPageInputRef.current.focus(); - } - } else if (searchRouterDisplayedRef.current) { + if (searchRouterDisplayedRef.current) { closeSearchRouter(); } else { startSearchRouterOpenSpan(); @@ -164,22 +141,12 @@ function SearchRouterContextProvider({children}: ChildrenProps) { } }; - const registerSearchPageInput = (ref: AnimatedTextInputRef) => { - searchPageInputRef.current = ref; - }; - - const unregisterSearchPageInput = () => { - searchPageInputRef.current = undefined; - }; - // Because of the React Compiler we don't need to memoize it manually // eslint-disable-next-line react/jsx-no-constructed-context-values const actionsContextValue = { openSearchRouter, closeSearchRouter, toggleSearch, - registerSearchPageInput, - unregisterSearchPageInput, }; // Because of the React Compiler we don't need to memoize it manually diff --git a/src/components/Search/hooks/useUpdateFilterQuery.tsx b/src/components/Search/hooks/useUpdateFilterQuery.tsx index 10d8b6da4c19..d21cbc6b2d5f 100644 --- a/src/components/Search/hooks/useUpdateFilterQuery.tsx +++ b/src/components/Search/hooks/useUpdateFilterQuery.tsx @@ -43,7 +43,7 @@ function useUpdateFilterQuery(queryJSON: SearchQueryJSON | undefined) { return; } - Navigation.setParams({q: queryString, rawQuery: undefined}); + Navigation.setParams({q: queryString}); } function updateFilterQueryParams(values: Partial) { diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index b974e2ffb743..9e59a9cdc93f 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -1487,11 +1487,7 @@ function Search({ if (hasErrors && (currentRoute === '/' || (shouldResetSearchQuery && currentRoute === '/search'))) { // Use requestAnimationFrame to safely update navigation params without overriding the current route requestAnimationFrame(() => { - // We want to explicitly clear stale rawQuery since it’s only used for manually typed-in queries. - Navigation.setParams({ - q: buildCannedSearchQuery(), - rawQuery: undefined, - }); + Navigation.setParams({q: buildCannedSearchQuery()}); }); if (shouldResetSearchQuery) { setShouldResetSearchQuery(false); @@ -1743,7 +1739,7 @@ function Search({ sortOrder: order, }); onSortPressedCallback?.(); - navigation.setParams({q: newQuery, rawQuery: undefined}); + navigation.setParams({q: newQuery}); }, [clearSelectedTransactions, queryJSON, onSortPressedCallback, navigation], ); diff --git a/src/components/Search/types.ts b/src/components/Search/types.ts index 9c9c9a10848c..cf9823522b47 100644 --- a/src/components/Search/types.ts +++ b/src/components/Search/types.ts @@ -310,15 +310,6 @@ type QueryFilters = Array<{ filters: QueryFilter[]; }>; -type RawFilterKey = SyntaxFilterKey | ValueOf; - -type RawQueryFilter = { - key: RawFilterKey; - operator: ValueOf; - value: string | string[]; - isDefault?: boolean; -}; - type SearchQueryString = string; type SearchQueryAST = { @@ -330,7 +321,6 @@ type SearchQueryAST = { view: SearchView; filters: ASTNode; policyID?: string[]; - rawFilterList?: RawQueryFilter[]; columns?: SearchCustomColumnIds | SearchCustomColumnIds[]; limit?: number; }; @@ -343,7 +333,6 @@ type SearchQueryJSON = { /** Use similarSearchHash to test if two searchers are similar i.e. have same filters but not necessary same values */ similarSearchHash: number; flatFilters: QueryFilters; - isViewExplicitlySet?: boolean; } & SearchQueryAST; type SearchAutocompleteResult = { @@ -449,7 +438,6 @@ export type { QueryFilter, QueryFilters, SyntaxFilterKey, - RawQueryFilter, SearchFilterKey, UserFriendlyKey, SearchAutocompleteResult, diff --git a/src/libs/Navigation/types.ts b/src/libs/Navigation/types.ts index 6bd1d14f56dd..08a7c33a0337 100644 --- a/src/libs/Navigation/types.ts +++ b/src/libs/Navigation/types.ts @@ -3177,7 +3177,6 @@ type SearchReportActionsParamList = { type SearchFullscreenNavigatorParamList = { [SCREENS.SEARCH.ROOT]: { q: SearchQueryString; - rawQuery?: SearchQueryString; name?: string; groupBy?: string; }; diff --git a/src/libs/SearchParser/searchParser.js b/src/libs/SearchParser/searchParser.js index 1077a0e62310..cc60ec42ad0a 100644 --- a/src/libs/SearchParser/searchParser.js +++ b/src/libs/SearchParser/searchParser.js @@ -435,7 +435,6 @@ function peg$parse(input, options) { const allFilters = [head, ...tail.map(([_, filter]) => filter)] .filter(Boolean) .filter((filter) => filter.right); - rawFilterList = allFilters.map(createRawFilter).filter(Boolean); const filtersWithoutDefaults = allFilters.filter((filter) => !filter.isDefault); @@ -4668,7 +4667,6 @@ function peg$parse(input, options) { sortOrder: "desc", view: "table", }; - let rawFilterList = []; let userProvidedSortBy = false; let userProvidedSortOrder = false; @@ -4693,7 +4691,6 @@ function peg$parse(input, options) { return { ...defaultValues, filters, - rawFilterList, }; } @@ -4759,26 +4756,6 @@ function peg$parse(input, options) { defaultValues[field] = value; } - function createRawFilter(filter) { - if (!filter || !filter.right) { - return null; - } - - if (typeof filter.left !== "string") { - return null; - } - - const key = filter.left; - const value = Array.isArray(filter.right) ? [...filter.right] : filter.right; - - return { - key, - operator: filter.operator, - value, - isDefault: !!filter.isDefault, - }; - } - let nameOperator = false; let expectingNestedQuote = false; diff --git a/src/libs/SearchParser/searchParser.peggy b/src/libs/SearchParser/searchParser.peggy index 568189d5b0f4..9d7f9cd08182 100644 --- a/src/libs/SearchParser/searchParser.peggy +++ b/src/libs/SearchParser/searchParser.peggy @@ -65,7 +65,6 @@ sortOrder: "desc", view: "table", }; - let rawFilterList = []; let userProvidedSortBy = false; let userProvidedSortOrder = false; @@ -90,7 +89,6 @@ return { ...defaultValues, filters, - rawFilterList, }; } @@ -155,26 +153,6 @@ defaultValues[field] = value; } - - function createRawFilter(filter) { - if (!filter || !filter.right) { - return null; - } - - if (typeof filter.left !== "string") { - return null; - } - - const key = filter.left; - const value = Array.isArray(filter.right) ? [...filter.right] : filter.right; - - return { - key, - operator: filter.operator, - value, - isDefault: !!filter.isDefault, - }; - } } query = _ filters:filterList? _ { return applyDefaults(filters); } @@ -184,7 +162,6 @@ filterList const allFilters = [head, ...tail.map(([_, filter]) => filter)] .filter(Boolean) .filter((filter) => filter.right); - rawFilterList = allFilters.map(createRawFilter).filter(Boolean); const filtersWithoutDefaults = allFilters.filter((filter) => !filter.isDefault); diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index b0acef984347..57878e8c8f64 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -8,12 +8,10 @@ import type { ASTNode, QueryFilter, QueryFilters, - RawQueryFilter, ReportFieldDateKey, ReportFieldNegatedKey, ReportFieldTextKey, SearchAmountFilterKeys, - SearchAutocompleteResult, SearchDateFilterKeys, SearchDateKey, SearchDatePreset, @@ -460,14 +458,6 @@ function wasViewExplicitlySet(queryJSON?: SearchQueryJSON | Readonly filter.key === CONST.SEARCH.SYNTAX_ROOT_KEYS.VIEW)) { - return true; - } - - if (queryJSON.isViewExplicitlySet) { - return true; - } - if (queryJSON.view !== getDefaultSearchQueryJSON()?.view) { return true; } @@ -564,38 +554,16 @@ function isFilterSupported(filter: SearchAdvancedFiltersKey, type: SearchDataTyp return false; } -/** - * Parses a given search query string into a structured `SearchQueryJSON` format. - * This format of query is most commonly shared between components and also sent to backend to retrieve search results. - * - * In a way this is the reverse of buildSearchQueryString() - */ -function getRawFilterListFromQuery(rawQuery: SearchQueryString) { - try { - const rawResult = parseSearchQuery(rawQuery) as SearchQueryJSON; - const sanitizedFilters = getSanitizedRawFilters(rawResult); - return sanitizedFilters; - } catch (error) { - Log.warn('[Search] Failed to parse raw query for raw filters', {error, rawQuery}); - } - - return undefined; -} - // Cache for buildSearchQueryJSON to avoid re-running the PEG parser for identical queries. // Cached values are shallow-frozen; callers needing to change fields must spread into a new object first. // This is a pure function called from 64+ sites — many fire during the same render cycle // with identical query strings, each running the full parser from scratch. const buildSearchQueryJSONCache = new Map | undefined>(); const BUILD_SEARCH_QUERY_JSON_CACHE_MAX_SIZE = 50; -const BUILD_SEARCH_QUERY_JSON_CACHE_KEY_SEPARATOR = '\x00'; // Null byte prevents collisions if query/rawQuery contain arbitrary strings - -function getBuildSearchQueryJSONCacheKey(query: SearchQueryString, rawQuery?: SearchQueryString) { - return rawQuery ? `${query}${BUILD_SEARCH_QUERY_JSON_CACHE_KEY_SEPARATOR}${rawQuery}` : query; -} -function getCachedSearchQueryJSON(query: SearchQueryString, rawQuery?: SearchQueryString): Readonly | undefined { - const cacheKey = getBuildSearchQueryJSONCacheKey(query, rawQuery); +/** Parses {@link query} into JSON. Repeated calls share the same cached object identity for referential stability. */ +function buildSearchQueryJSON(query: SearchQueryString): Readonly | undefined { + const cacheKey = query; if (buildSearchQueryJSONCache.has(cacheKey)) { return buildSearchQueryJSONCache.get(cacheKey); } @@ -603,12 +571,10 @@ function getCachedSearchQueryJSON(query: SearchQueryString, rawQuery?: SearchQue try { const result = parseSearchQuery(query) as SearchQueryJSON; const flatFilters = getFilters(result); - const rawFilterList = rawQuery ? getRawFilterListFromQuery(rawQuery) : result.rawFilterList; // Add the full input and hash to the results result.inputQuery = query; result.flatFilters = flatFilters; - result.isViewExplicitlySet = rawFilterList?.some((filter) => filter.key === CONST.SEARCH.SYNTAX_ROOT_KEYS.VIEW) ?? false; if (result.policyID && typeof result.policyID === 'string') { // Ensure policyID is always an array for consistency @@ -626,11 +592,6 @@ function getCachedSearchQueryJSON(query: SearchQueryString, rawQuery?: SearchQue result.recentSearchHash = recentSearchHash; result.similarSearchHash = similarSearchHash; - delete result.rawFilterList; - if (rawQuery) { - result.rawFilterList = rawFilterList; - } - if (buildSearchQueryJSONCache.size >= BUILD_SEARCH_QUERY_JSON_CACHE_MAX_SIZE) { const firstKey = buildSearchQueryJSONCache.keys().next().value; if (firstKey !== undefined) { @@ -646,11 +607,6 @@ function getCachedSearchQueryJSON(query: SearchQueryString, rawQuery?: SearchQue } } -/** Parses {@link query} (and optionally {@link rawQuery}) into JSON. Repeated calls share the same cached object identity for referential stability. */ -function buildSearchQueryJSON(query: SearchQueryString, rawQuery?: SearchQueryString): Readonly | undefined { - return getCachedSearchQueryJSON(query, rawQuery); -} - /** * Formats a given `SearchQueryJSON` object into the string version of query. * This format of query is the most basic string format and is used as the query param `q` in search URLs. @@ -697,59 +653,6 @@ function buildSearchQueryString(queryJSON?: SearchQueryJSON | Readonly((accumulator, rawFilter) => { - if (!rawFilter) { - return accumulator; - } - - if (rawFilter.isDefault) { - accumulator.push(rawFilter); - return accumulator; - } - - const rawValue = rawFilter.value; - const filterKey = rawFilter.key; - const isRecognizedFilterKey = Object.values(CONST.SEARCH.SYNTAX_FILTER_KEYS).includes(filterKey as SyntaxFilterKey); - let updatedValue: string | string[] = Array.isArray(rawValue) ? rawValue.map((value) => value?.toString() ?? '') : (rawValue?.toString() ?? ''); - - if (isRecognizedFilterKey) { - updatedValue = getUpdatedFilterValue(filterKey as SyntaxFilterKey, updatedValue); - } - - accumulator.push({ - ...rawFilter, - value: updatedValue, - }); - return accumulator; - }, []); - - const seenKeys = new Set(); - - for (let index = sanitizedFilters.length - 1; index >= 0; index -= 1) { - const filter = sanitizedFilters.at(index); - - if (!filter) { - continue; - } - - const filterKey = filter.key; - - if (seenKeys.has(filterKey) && filter.isDefault) { - sanitizedFilters.splice(index, 1); - continue; - } - - seenKeys.add(filterKey); - } - - return sanitizedFilters; -} - type BuildQueryStringOptions = { sortBy?: string; sortOrder?: string; @@ -1583,62 +1486,6 @@ function getDisplayQueryFiltersForKey( })); } -function formatDefaultRawFilterSegment(rawFilter: RawQueryFilter, policies: OnyxCollection, reports?: OnyxCollection) { - const rawValues = Array.isArray(rawFilter.value) ? rawFilter.value : [rawFilter.value]; - const cleanedValues = rawValues.map((val) => (typeof val === 'string' ? val.trim() : '')).filter((val) => val.length > 0); - - if (cleanedValues.length === 0) { - return; - } - - if (rawFilter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID) { - const workspaceValues = cleanedValues.map((id) => { - const policyName = getPolicyNameWithFallback(id, policies, reports); - return sanitizeSearchValue(policyName); - }); - - if (workspaceValues.length === 0) { - return; - } - - return `${getUserFriendlyKey(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID)}:${workspaceValues.join(',')}`; - } - - if (rawFilter.key === CONST.SEARCH.SYNTAX_ROOT_KEYS.SORT_BY || rawFilter.key === CONST.SEARCH.SYNTAX_ROOT_KEYS.SORT_ORDER) { - return; - } - - let userFriendlyKey: UserFriendlyKey; - switch (rawFilter.key) { - case CONST.SEARCH.SYNTAX_ROOT_KEYS.TYPE: - userFriendlyKey = getUserFriendlyKey(CONST.SEARCH.SYNTAX_ROOT_KEYS.TYPE); - break; - case CONST.SEARCH.SYNTAX_ROOT_KEYS.STATUS: - userFriendlyKey = getUserFriendlyKey(CONST.SEARCH.SYNTAX_ROOT_KEYS.STATUS); - break; - case CONST.SEARCH.SYNTAX_ROOT_KEYS.GROUP_BY: - userFriendlyKey = getUserFriendlyKey(CONST.SEARCH.SYNTAX_ROOT_KEYS.GROUP_BY); - break; - case CONST.SEARCH.SYNTAX_ROOT_KEYS.COLUMNS: - userFriendlyKey = getUserFriendlyKey(CONST.SEARCH.SYNTAX_ROOT_KEYS.COLUMNS); - break; - case CONST.SEARCH.SYNTAX_ROOT_KEYS.LIMIT: - userFriendlyKey = getUserFriendlyKey(CONST.SEARCH.SYNTAX_ROOT_KEYS.LIMIT); - break; - default: - userFriendlyKey = getUserFriendlyKey(rawFilter.key as SearchFilterKey); - break; - } - - const formattedValues = cleanedValues.map((val) => sanitizeSearchValue(getUserFriendlyValue(val))); - - if (!formattedValues.length) { - return; - } - - return `${userFriendlyKey}:${formattedValues.join(',')}`; -} - /** * Formats a given `SearchQueryJSON` object into the human-readable string version of query. * This format of query is the one which we want to display to users. @@ -1674,67 +1521,7 @@ function buildUserReadableQueryString({ feedKeysWithCards, reportAttributes, }: BuildUserReadableQueryStringParams) { - const {type, status, groupBy, view, columns, policyID, rawFilterList, flatFilters: filters = [], limit} = queryJSON; - - if (rawFilterList && rawFilterList.length > 0) { - const segments: string[] = []; - - for (const rawFilter of rawFilterList) { - if (!rawFilter) { - continue; - } - - if (rawFilter.isDefault) { - const defaultSegment = formatDefaultRawFilterSegment(rawFilter, policies, reports); - if (defaultSegment) { - segments.push(defaultSegment); - } - continue; - } - - const rawValues = Array.isArray(rawFilter.value) ? rawFilter.value : [rawFilter.value]; - const queryFilters = rawValues - .map((val) => (val ?? '').toString()) - .filter((val) => val.length > 0) - .map((val) => ({ - operator: rawFilter.operator, - value: val, - })); - - if (!queryFilters.length) { - continue; - } - - const displayQueryFilters = getDisplayQueryFiltersForKey( - rawFilter.key, - queryFilters, - PersonalDetails, - reports, - taxRates, - cardList, - cardFeeds, - policies, - currentUserAccountID, - translate, - reportAttributes, - feedKeysWithCards, - ); - - if (!displayQueryFilters.length) { - continue; - } - - const segment = buildFilterValuesString(getUserFriendlyKey(rawFilter.key as SearchFilterKey), displayQueryFilters).trim(); - - if (segment) { - segments.push(segment); - } - } - - if (segments.length > 0) { - return segments.join(' '); - } - } + const {type, status, groupBy, view, columns, policyID, flatFilters: filters = [], limit} = queryJSON; let title = status ? `type:${getUserFriendlyValue(type)} status:${Array.isArray(status) ? status.map(getUserFriendlyValue).join(',') : getUserFriendlyValue(status)}` @@ -1880,12 +1667,6 @@ function traverseAndUpdatedQuery(queryJSON: SearchQueryJSON | Readonly): SearchQueryString { - const autocompleteRanges = (parseForAutocomplete(queryString) as SearchAutocompleteResult).ranges; - const hasOnlyKeywordSearch = queryString.trim().length > 0 && autocompleteRanges.length === 0; - if (!hasOnlyKeywordSearch) { - return queryString; - } - const currentFiltersWithoutKeywords = currentQueryJSON.flatFilters.filter((filter) => filter.key !== CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD); const currentQueryString = buildSearchQueryString({...currentQueryJSON, flatFilters: currentFiltersWithoutKeywords}); return `${currentQueryString} ${queryString}`; @@ -1905,13 +1686,6 @@ function getQueryWithUpdatedValues(query: string, shouldSkipAmountConversion = f const computeNodeValue = (left: SyntaxFilterKey, right: string | string[]) => getUpdatedFilterValue(left, right, shouldSkipAmountConversion); const standardizedQuery = traverseAndUpdatedQuery(queryJSON, computeNodeValue); - const rawFilterList = getRawFilterListFromQuery(query); - const hasInFilter = rawFilterList?.some((filter) => !filter.isDefault && filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.IN) ?? false; - const hasExplicitType = rawFilterList?.some((filter) => filter.key === CONST.SEARCH.SYNTAX_ROOT_KEYS.TYPE) ?? false; - - if (hasInFilter && !hasExplicitType) { - standardizedQuery.type = CONST.SEARCH.DATA_TYPES.CHAT; - } return buildSearchQueryString(standardizedQuery); } @@ -1937,8 +1711,8 @@ function getCurrentSearchQueryJSON() { return; } - const {q: searchParams, rawQuery} = lastSearchRoute.params as SearchFullscreenNavigatorParamList[typeof SCREENS.SEARCH.ROOT]; - const queryJSON = buildSearchQueryJSON(searchParams, rawQuery); + const {q: searchParams} = lastSearchRoute.params as SearchFullscreenNavigatorParamList[typeof SCREENS.SEARCH.ROOT]; + const queryJSON = buildSearchQueryJSON(searchParams); if (!queryJSON) { return; } @@ -2189,17 +1963,9 @@ function getDateModifierTitle(modifier: ValueOf(queryData: T): string { +function serializeQueryJSONForBackend(queryData: T): string { const normalizedFilters = queryData.filters ? applyContainsOperatorToTextFields(queryData.filters) : queryData.filters; - const normalizedRawFilterList = queryData.rawFilterList - ? queryData.rawFilterList.map((filter) => { - if (TEXT_SEARCH_FIELDS.has(filter.key) && filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO) { - return {...filter, operator: CONST.SEARCH.SYNTAX_OPERATORS.CONTAINS}; - } - return filter; - }) - : queryData.rawFilterList; - return JSON.stringify({...queryData, filters: normalizedFilters, rawFilterList: normalizedRawFilterList}); + return JSON.stringify({...queryData, filters: normalizedFilters}); } export { @@ -2212,6 +1978,7 @@ export { buildSearchQueryJSON, buildSearchQueryString, buildUserReadableQueryString, + buildFilterValuesString, getDisplayQueryFiltersForKey, getFilterDisplayValue, getPolicyNameWithFallback, diff --git a/src/libs/actions/Search.ts b/src/libs/actions/Search.ts index f5c969ebd0cd..fd6613c6269f 100644 --- a/src/libs/actions/Search.ts +++ b/src/libs/actions/Search.ts @@ -1181,7 +1181,6 @@ function rejectMoneyRequestsOnSearch( const searchParams = lastRoute.params as SearchFullscreenNavigatorParamList[typeof SCREENS.SEARCH.ROOT]; urlToNavigateBack = ROUTES.SEARCH_ROOT.getRoute({ query: searchParams.q, - ...(searchParams?.rawQuery && {rawQuery: searchParams.rawQuery}), ...(searchParams?.name && {name: searchParams.name}), }); } else { @@ -1329,13 +1328,6 @@ function updateAdvancedFilters(values: Nullable { - setSearchContext(false); Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query: item?.query ?? '', name: item?.name})); }, rightComponent: ( diff --git a/src/pages/Search/SearchAdvancedFiltersProvider.tsx b/src/pages/Search/SearchAdvancedFiltersProvider.tsx index 66e6481d7742..7c62709b569b 100644 --- a/src/pages/Search/SearchAdvancedFiltersProvider.tsx +++ b/src/pages/Search/SearchAdvancedFiltersProvider.tsx @@ -2,7 +2,6 @@ import React, {useState} from 'react'; import useUpdateFilterQuery from '@components/Search/hooks/useUpdateFilterQuery'; import {useSearchQueryContext} from '@components/Search/SearchContext'; import useOnyx from '@hooks/useOnyx'; -import {setSearchContext} from '@libs/actions/Search'; import Navigation from '@libs/Navigation/Navigation'; import {getAdvancedFiltersToReset} from '@libs/SearchQueryUtils'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -45,26 +44,14 @@ function SearchAdvancedFiltersProvider({children}: SearchAdvancedFiltersProvider const advancedFiltersToReset = searchAdvancedFiltersForm ? getAdvancedFiltersToReset(searchAdvancedFiltersForm) : undefined; const applyFilters = () => { - Navigation.dismissModal({ - afterTransition: () => { - setFilterQueryParams(values); - if (values.keyword) { - setSearchContext(true); - } - }, - }); + Navigation.dismissModal({afterTransition: () => setFilterQueryParams(values)}); }; const resetFilters = () => { if (!advancedFiltersToReset) { return; } - Navigation.dismissModal({ - afterTransition: () => { - setFilterQueryParams(advancedFiltersToReset); - setSearchContext(false); - }, - }); + Navigation.dismissModal({afterTransition: () => setFilterQueryParams(advancedFiltersToReset)}); }; const setDraftFilters = (newValues: Partial) => { diff --git a/src/pages/Search/SearchPageNarrow/StaticSearchPageInput.tsx b/src/pages/Search/SearchPageNarrow/StaticSearchPageInput.tsx index 3cce11bb2164..6dfcec3499e8 100644 --- a/src/pages/Search/SearchPageNarrow/StaticSearchPageInput.tsx +++ b/src/pages/Search/SearchPageNarrow/StaticSearchPageInput.tsx @@ -1,4 +1,4 @@ -// Static twin of SearchPageInputNarrow - used for fast perceived performance. +// Static twin of SearchPageInput for narrow layout - used for fast perceived performance. // Keep hooks and Onyx subscriptions to an absolute minimum; add new ones only // when strictly necessary. UI must stay visually identical to the interactive version. import React from 'react'; @@ -15,29 +15,21 @@ function StaticSearchPageInput() { return ( - - - - - {translate('search.searchPlaceholder')} - - - - + + {translate('search.searchPlaceholder')} + ); } diff --git a/src/pages/Search/SearchPageNarrow/Switches.tsx b/src/pages/Search/SearchPageNarrow/Switches.tsx index cdb3ff481566..266a14ece71e 100644 --- a/src/pages/Search/SearchPageNarrow/Switches.tsx +++ b/src/pages/Search/SearchPageNarrow/Switches.tsx @@ -17,8 +17,8 @@ import SearchActionsBarNarrow from '@components/Search/SearchPageHeader/SearchAc import type {SearchActionsBarNarrowProps} from '@components/Search/SearchPageHeader/SearchActionsBarNarrow'; import SearchFiltersBarNarrow from '@components/Search/SearchPageHeader/SearchFiltersBarNarrow'; import type {SearchFiltersBarNarrowProps} from '@components/Search/SearchPageHeader/SearchFiltersBarNarrow'; -import SearchPageInputNarrow from '@components/Search/SearchPageHeader/SearchPageInputNarrow'; -import type {SearchPageInputNarrowProps} from '@components/Search/SearchPageHeader/SearchPageInputNarrow'; +import SearchPageInput from '@components/Search/SearchPageHeader/SearchPageInput'; +import type {SearchPageInputProps} from '@components/Search/SearchPageHeader/SearchPageInput'; import SearchTypeMenuNarrow from '@pages/Search/SearchTypeMenuNarrow'; import type {SearchTypeMenuNarrowProps} from '@pages/Search/SearchTypeMenuNarrow'; import StaticSearchActionsBar from './StaticSearchActionsBar'; @@ -33,12 +33,12 @@ function SearchTypeMenuSwitch({showStatic, ...props}: SearchTypeMenuNarrowProps return ; } -function SearchPageInputSwitch({showStatic, ...props}: SearchPageInputNarrowProps & {showStatic: boolean}) { +function SearchPageInputSwitch({showStatic, ...props}: SearchPageInputProps & {showStatic: boolean}) { if (showStatic) { return ; } - return ; + return ; } function SearchFiltersBarSwitch({showStatic, ...props}: SearchFiltersBarNarrowProps & {showStatic: boolean}) { diff --git a/src/pages/Search/SearchPageNarrow/index.tsx b/src/pages/Search/SearchPageNarrow/index.tsx index 98a909616dab..eff2d8e19fa5 100644 --- a/src/pages/Search/SearchPageNarrow/index.tsx +++ b/src/pages/Search/SearchPageNarrow/index.tsx @@ -4,7 +4,6 @@ import {StyleSheet, View} from 'react-native'; import Animated, {clamp, useAnimatedScrollHandler, useAnimatedStyle, useSharedValue, withTiming} from 'react-native-reanimated'; import {scheduleOnRN} from 'react-native-worklets'; import FullPageNotFoundView from '@components/BlockingViews/FullPageNotFoundView'; -import {useFullScreenBlockingViewActions} from '@components/FullScreenBlockingViewContextProvider'; import HeaderWithBackButton from '@components/HeaderWithBackButton'; import NAVIGATION_TABS from '@components/Navigation/NavigationTabBar/NAVIGATION_TABS'; import TabBarBottomContent from '@components/Navigation/TabBarBottomContent'; @@ -24,7 +23,6 @@ import useEndSubmitNavigationSpans from '@hooks/useEndSubmitNavigationSpans'; import useLoadingBarVisibility from '@hooks/useLoadingBarVisibility'; import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; -import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useScrollEventEmitter from '@hooks/useScrollEventEmitter'; import useSearchLoadingState from '@hooks/useSearchLoadingState'; import useStyleUtils from '@hooks/useStyleUtils'; @@ -87,13 +85,11 @@ function SearchPageNarrow({ }: SearchPageNarrowProps) { const shouldShowLoadingSkeleton = useSearchLoadingState(queryJSON, searchResults); const {translate} = useLocalize(); - const {shouldUseNarrowLayout} = useResponsiveLayout(); const {windowHeight} = useWindowDimensions(); const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); const {clearSelectedTransactions} = useSearchSelectionActions(); const {shouldUseLiveData} = useSearchResultsContext(); - const [searchRouterListVisible, setSearchRouterListVisible] = useState(false); const {isOffline} = useNetwork(); const shouldShowLoadingBarForReports = useLoadingBarVisibility(); @@ -159,11 +155,6 @@ function SearchPageNarrow({ const handleOnBackButtonPress = () => Navigation.goBack(ROUTES.SEARCH_ROOT.getRoute({query: buildCannedSearchQuery()})); - const shouldDisplayCancelSearch = shouldUseNarrowLayout && searchRouterListVisible; - const cancelSearchCallback = useCallback(() => { - setSearchRouterListVisible(false); - }, []); - const handleSearchAction = useCallback((value: SearchParams | string) => { if (typeof value === 'string') { searchInServer(value); @@ -172,17 +163,6 @@ function SearchPageNarrow({ } }, []); - const {addRouteKey, removeRouteKey} = useFullScreenBlockingViewActions(); - useEffect(() => { - if (!searchRouterListVisible) { - return; - } - - addRouteKey(route.key); - - return () => removeRouteKey(route.key); - }, [addRouteKey, removeRouteKey, route.key, searchRouterListVisible]); - const navigation = useNavigation(); // When pre-inserted behind the RHP (not focused), always start in static rendering // mode so we stay at the lightweight static list until focus arrives. This avoids @@ -265,30 +245,21 @@ function SearchPageNarrow({ shouldEnableMaxHeight offlineIndicatorStyle={styles.mtAuto} shouldShowOfflineIndicator={!!searchResults} - bottomContent={!searchRouterListVisible && tabBarContent} + bottomContent={tabBarContent} bottomContentStyle={styles.overflowVisible} > {!isMobileSelectionModeEnabled ? ( - + - + { - setSearchRouterListVisible(false); - }} /> - + { - setSearchRouterListVisible(false); - }} - onSearchRouterFocus={() => { - topBarOffset.set(StyleUtils.searchHeaderDefaultOffset); - setSearchRouterListVisible(true); - }} - handleSearch={handleSearchAction} - skipSkeleton={useStaticRendering} + onFocus={() => topBarOffset.set(StyleUtils.searchHeaderDefaultOffset)} /> - {!searchRouterListVisible && ( - - )} - - {!searchRouterListVisible && ( - - )} + + @@ -352,81 +307,79 @@ function SearchPageNarrow({ /> )} - {!searchRouterListVisible && ( - - {useStaticRendering && ( - <> - {isInteractive && ( - - )} - {isOverlayActive && !searchOverlayContent && } - {!!searchOverlayContent && ( - - {searchOverlayContent} - - )} - - )} - {!useStaticRendering && ( - <> - {shouldShowLoadingSkeleton ? ( - 0 && !isOffline, - hasPendingResponse: searchRequestResponseStatusCode === null, - shouldUseLiveData, - }} - /> - ) : ( - - )} - {isOverlayActive && !searchOverlayContent && } - {!!searchOverlayContent && ( - - {searchOverlayContent} - - )} - - )} - - )} - {shouldShowFooter && !searchRouterListVisible && ( + + {useStaticRendering && ( + <> + {isInteractive && ( + + )} + {isOverlayActive && !searchOverlayContent && } + {!!searchOverlayContent && ( + + {searchOverlayContent} + + )} + + )} + {!useStaticRendering && ( + <> + {shouldShowLoadingSkeleton ? ( + 0 && !isOffline, + hasPendingResponse: searchRequestResponseStatusCode === null, + shouldUseLiveData, + }} + /> + ) : ( + + )} + {isOverlayActive && !searchOverlayContent && } + {!!searchOverlayContent && ( + + {searchOverlayContent} + + )} + + )} + + {shouldShowFooter && ( { @@ -219,11 +217,10 @@ function SearchTypeMenuNarrow({queryJSON, onTabPress}: SearchTypeMenuNarrowProps return; } onTabPress?.(); - setSearchContext(false); navigation.dispatch({ type: CONST.NAVIGATION.ACTION_TYPE.PUSH_PARAMS, payload: { - params: {q: searchData.query, name: searchData.name, rawQuery: undefined}, + params: {q: searchData.query, name: searchData.name}, }, }); }; diff --git a/src/pages/Search/SearchTypeMenuWide.tsx b/src/pages/Search/SearchTypeMenuWide.tsx index f20a851b5531..b2b36bae3938 100644 --- a/src/pages/Search/SearchTypeMenuWide.tsx +++ b/src/pages/Search/SearchTypeMenuWide.tsx @@ -14,7 +14,6 @@ import useOnyx from '@hooks/useOnyx'; import useSearchTypeMenuSections from '@hooks/useSearchTypeMenuSections'; import useSingleExecution from '@hooks/useSingleExecution'; import useThemeStyles from '@hooks/useThemeStyles'; -import {setSearchContext} from '@libs/actions/Search'; import Navigation from '@libs/Navigation/Navigation'; import {getItemBadgeText, getSectionBadgeText} from '@libs/SearchUIUtils'; import type {SearchTypeMenuSection} from '@libs/SearchUIUtils'; @@ -143,7 +142,6 @@ function SearchTypeMenuWide({queryJSON}: SearchTypeMenuProps) { const handleTypeMenuItemPress = singleExecution((searchQuery: string) => { clearSelectedTransactions(); - setSearchContext(false); Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query: searchQuery})); }); diff --git a/src/pages/settings/Subscription/CardSection/CardSection.tsx b/src/pages/settings/Subscription/CardSection/CardSection.tsx index 07c0d6fdb437..71e79fb26fec 100644 --- a/src/pages/settings/Subscription/CardSection/CardSection.tsx +++ b/src/pages/settings/Subscription/CardSection/CardSection.tsx @@ -113,7 +113,7 @@ function CardSection() { ], }); - Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query, rawQuery: query})); + Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query})); }; const [billingStatus, setBillingStatus] = useState(() => diff --git a/src/styles/index.ts b/src/styles/index.ts index 12141d03e835..fbce04519d3d 100644 --- a/src/styles/index.ts +++ b/src/styles/index.ts @@ -5075,13 +5075,9 @@ const staticStyles = (theme: ThemeColors) => minHeight: 28, }, - searchPageInputWideTouchableWrapper: {height: 32, width: 200}, - searchPageInputWidePlaceholder: { - // Extra 2 to account for the borders - height: 34, - width: 202, - }, - searchPageInputNarrowTouchableWrapper: {height: 44}, + // Extra 2 to account for the borders + searchPageInputWideTouchableWrapper: {height: 34, width: 202}, + searchPageInputNarrowTouchableWrapper: {height: 46}, walletStaticIllustration: { width: 262, diff --git a/tests/actions/IOU/SearchUpdateTest.ts b/tests/actions/IOU/SearchUpdateTest.ts index 99a1216878e9..e0b56e138f7c 100644 --- a/tests/actions/IOU/SearchUpdateTest.ts +++ b/tests/actions/IOU/SearchUpdateTest.ts @@ -307,14 +307,6 @@ describe('actions/IOU', () => { hash: 591785022, recentSearchHash: 714245044, similarSearchHash: 1023624110, - rawFilterList: [ - { - key: 'policyID', - operator: 'eq', - value: policyID, - isDefault: true, - }, - ], } as unknown as SearchQueryJSON; // When the IOU report has a matching policyID, it should return true diff --git a/tests/unit/NavigationFocusReturnTest.ts b/tests/unit/NavigationFocusReturnTest.ts index 29f2a1f08d5e..977752222d22 100644 --- a/tests/unit/NavigationFocusReturnTest.ts +++ b/tests/unit/NavigationFocusReturnTest.ts @@ -1627,14 +1627,6 @@ describe('compoundParamsKey', () => { expect(compoundParamsKey('search-x', {q: 'foo'})).not.toBe('search-x'); }); - it('should treat explicit-undefined fields as omitted (path rehydration parity)', () => { - expect(compoundParamsKey('search-x', {q: 'foo', rawQuery: undefined})).toBe(compoundParamsKey('search-x', {q: 'foo'})); - }); - - it('should distinguish explicit null from absent (null is a real value)', () => { - expect(compoundParamsKey('search-x', {q: 'foo', rawQuery: null})).not.toBe(compoundParamsKey('search-x', {q: 'foo'})); - }); - it('should distinguish array [undefined] from array [null] (JSON.stringify would otherwise collapse both to "null")', () => { expect(compoundParamsKey('search-x', {ids: [undefined]})).not.toBe(compoundParamsKey('search-x', {ids: [null]})); }); diff --git a/tests/unit/Search/SearchListRenderCountTest.tsx b/tests/unit/Search/SearchListRenderCountTest.tsx index 7e257b7e6ff4..420a678bbf1d 100644 --- a/tests/unit/Search/SearchListRenderCountTest.tsx +++ b/tests/unit/Search/SearchListRenderCountTest.tsx @@ -118,7 +118,6 @@ const STABLE_QUERY_JSON: SearchQueryJSON = { policyID: undefined, columns: undefined, limit: undefined, - rawFilterList: undefined, }; const STABLE_COLUMNS: SearchColumnType[] = [CONST.SEARCH.TABLE_COLUMNS.DATE, CONST.SEARCH.TABLE_COLUMNS.MERCHANT, CONST.SEARCH.TABLE_COLUMNS.TOTAL_AMOUNT, CONST.SEARCH.TABLE_COLUMNS.ACTION]; diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index 985719190b7d..c93533347770 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -179,13 +179,6 @@ describe('SearchQueryUtils', () => { const result = getQueryWithUpdatedValues(userQuery); expect(result).toEqual(`${defaultQuery} action:submit from:me`); - - const queryJSON = buildSearchQueryJSON(result ?? '', userQuery); - expect(queryJSON?.rawFilterList).toEqual([ - {key: CONST.SEARCH.SYNTAX_FILTER_KEYS.ACTION, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'submit', isDefault: false}, - {key: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'me', isDefault: false}, - {key: CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: CONST.SEARCH.DATA_TYPES.EXPENSE, isDefault: true}, - ]); }); }); @@ -683,7 +676,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to standardize query string'); } - const queryJSON = buildSearchQueryJSON(canonicalQueryString, queryString); + const queryJSON = buildSearchQueryJSON(canonicalQueryString); if (!queryJSON) { throw new Error('Failed to parse query string'); @@ -714,7 +707,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to standardize query string'); } - const queryJSON = buildSearchQueryJSON(canonicalQueryString, queryString); + const queryJSON = buildSearchQueryJSON(canonicalQueryString); if (!queryJSON) { throw new Error('Failed to parse query string'); @@ -745,7 +738,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to standardize query string'); } - const queryJSON = buildSearchQueryJSON(canonicalQueryString, queryString); + const queryJSON = buildSearchQueryJSON(canonicalQueryString); const policies: OnyxCollection = { [`${ONYXKEYS.COLLECTION.POLICY}123`]: { name: 'Team Space', @@ -773,21 +766,6 @@ describe('SearchQueryUtils', () => { expect(result).toBe('workspace:"Team Space" type:expense merchant:Starbucks'); }); - test('rawQuery overrides canonical filter values when provided', () => { - const queryString = 'type:expense merchant:Uber'; - const canonicalQueryString = getQueryWithUpdatedValues(queryString); - - if (!canonicalQueryString) { - throw new Error('Failed to standardize query string'); - } - - const overriddenRawQuery = 'type:expense merchant:Lyft'; - const queryJSON = buildSearchQueryJSON(canonicalQueryString, overriddenRawQuery); - const merchantFilter = queryJSON?.rawFilterList?.find((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.MERCHANT); - - expect(merchantFilter?.value).toBe('Lyft'); - }); - test('includes limit in readable query string when present', () => { const queryJSON = buildSearchQueryJSON('type:expense limit:25'); @@ -1623,7 +1601,7 @@ describe('SearchQueryUtils', () => { it('should return different primary hash for implicit table view and explicit view:table', () => { const queryJSONa = buildSearchQueryJSON('type:expense groupBy:category'); - const queryJSONb = buildSearchQueryJSON('type:expense groupBy:category view:table', 'type:expense groupBy:category view:table'); + const queryJSONb = buildSearchQueryJSON('type:expense groupBy:category view:table'); expect(queryJSONa?.similarSearchHash).toEqual(queryJSONb?.similarSearchHash); expect(queryJSONa?.hash).not.toEqual(queryJSONb?.hash); @@ -1986,22 +1964,6 @@ describe('SearchQueryUtils', () => { }); describe('buildSearchQueryString', () => { - test('includes view when explicitly set in rawFilterList', () => { - const queryJSON = buildSearchQueryJSON('type:expense view:line', 'type:expense view:line'); - - const result = buildSearchQueryString(queryJSON); - - expect(result).toContain('view:line'); - }); - - test('includes view when differs from default even without rawFilterList', () => { - const queryJSON = buildSearchQueryJSON('type:expense view:pie'); - - const result = buildSearchQueryString(queryJSON); - - expect(result).toContain('view:pie'); - }); - test('includes view when set to bar', () => { const queryJSON = buildSearchQueryJSON('type:expense view:bar'); @@ -2018,14 +1980,6 @@ describe('SearchQueryUtils', () => { expect(result).not.toContain('view:table'); }); - test('includes view when explicitly set to table in rawFilterList', () => { - const queryJSON = buildSearchQueryJSON('type:expense groupBy:category view:table', 'type:expense groupBy:category view:table'); - - const result = buildSearchQueryString(queryJSON); - - expect(result).toContain('view:table'); - }); - test('preserves view along with other filters', () => { const queryJSON = buildSearchQueryJSON('type:expense view:line category:travel'); @@ -2034,15 +1988,6 @@ describe('SearchQueryUtils', () => { expect(result).toContain('view:line'); expect(result).toContain('category:travel'); }); - - test('handles view with rawFilterList containing other filters', () => { - const queryJSON = buildSearchQueryJSON('type:expense view:pie merchant:Amazon', 'type:expense view:pie merchant:Amazon'); - - const result = buildSearchQueryString(queryJSON); - - expect(result).toContain('view:pie'); - expect(result).toContain('merchant:Amazon'); - }); }); describe('buildFilterQueryWithSortDefaults', () => { @@ -2276,17 +2221,6 @@ describe('SearchQueryUtils', () => { expect(Object.isFrozen(first)).toBe(true); }); - test('returns independent results for the same query with different rawQuery values', () => { - const query = 'type:expense'; - const rawQueryA = 'type:expense status:drafts'; - const rawQueryB = 'type:expense status:paid'; - - const resultA = buildSearchQueryJSON(query, rawQueryA); - const resultB = buildSearchQueryJSON(query, rawQueryB); - - expect(resultA?.rawFilterList).not.toEqual(resultB?.rawFilterList); - }); - test('does not cache a failed parse result so subsequent calls retry the parser', () => { // Force the parser to throw on the first call only, then succeed on the second. // Verifies that a failed parse is not stored in the cache. @@ -2952,18 +2886,6 @@ describe('SearchQueryUtils', () => { } expect(merchantNode.operator).toBe(CONST.SEARCH.SYNTAX_OPERATORS.CONTAINS); }); - - it('should apply contains to merchant in rawFilterList', () => { - const rawFilterList = [{key: CONST.SEARCH.SYNTAX_FILTER_KEYS.MERCHANT, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'coffee'}]; - const serialized = JSON.parse(serializeQueryJSONForBackend({filters: undefined, rawFilterList})) as {rawFilterList: typeof rawFilterList}; - expect(serialized.rawFilterList.at(0)?.operator).toBe(CONST.SEARCH.SYNTAX_OPERATORS.CONTAINS); - }); - - it('should not affect non-text fields in rawFilterList', () => { - const rawFilterList = [{key: CONST.SEARCH.SYNTAX_FILTER_KEYS.CATEGORY, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'food'}]; - const serialized = JSON.parse(serializeQueryJSONForBackend({filters: undefined, rawFilterList})) as {rawFilterList: typeof rawFilterList}; - expect(serialized.rawFilterList.at(0)?.operator).toBe(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO); - }); }); describe('getKeywordQueryWithCurrentSearchContext', () => { diff --git a/tests/unit/Search/yourSpendQueryBuildersTest.ts b/tests/unit/Search/yourSpendQueryBuildersTest.ts index 95aa2289af50..17cfc5942c29 100644 --- a/tests/unit/Search/yourSpendQueryBuildersTest.ts +++ b/tests/unit/Search/yourSpendQueryBuildersTest.ts @@ -17,9 +17,6 @@ const CARD_ID = 67890; /** * Returns the parsed filter entries for a given key from a query string. - * Uses `flatFilters` (the standard parsed-filter representation across the app) - * so the helper does not depend on `rawFilterList`, which is internal to - * SearchQueryUtils and only kept when both `query` and `rawQuery` are supplied. */ function getRawFiltersForKey(inputQuery: string, key: string): Array<{operator: string; value: string | string[]}> { const queryJSON = buildSearchQueryJSON(inputQuery); diff --git a/tests/unit/SearchParserTest.ts b/tests/unit/SearchParserTest.ts index 16f655f5a621..7008dc83c311 100644 --- a/tests/unit/SearchParserTest.ts +++ b/tests/unit/SearchParserTest.ts @@ -1376,28 +1376,28 @@ const limitTests = [ describe('search parser', () => { test.each(tests)(`parsing: $query`, ({query, expected}) => { - const {rawFilterList, ...resultWithoutRawFilters} = parse(query) as SearchQueryJSON; - expect(resultWithoutRawFilters).toEqual(expected); + const result = parse(query) as SearchQueryJSON; + expect(result).toEqual(expected); }); }); describe('Testing search parser with special characters and wrapped in quotes.', () => { test.each(keywordTests)(`parsing: $query`, ({query, expected}) => { - const {rawFilterList, ...resultWithoutRawFilters} = parse(query) as SearchQueryJSON; - expect(resultWithoutRawFilters).toEqual(expected); + const result = parse(query) as SearchQueryJSON; + expect(result).toEqual(expected); }); }); describe('search parser - view and groupBy defaults', () => { test.each(viewAndGroupByTests)(`parsing: $query`, ({query, expected}) => { - const {rawFilterList, ...resultWithoutRawFilters} = parse(query) as SearchQueryJSON; - expect(resultWithoutRawFilters).toEqual(expected); + const result = parse(query) as SearchQueryJSON; + expect(result).toEqual(expected); }); }); describe('search parser - limit filter', () => { test.each(limitTests)('$description: $query', ({query, expected}) => { - const {rawFilterList, ...resultWithoutRawFilters} = parse(query) as SearchQueryJSON; - expect(resultWithoutRawFilters).toEqual(expected); + const result = parse(query) as SearchQueryJSON; + expect(result).toEqual(expected); }); }); From 587eb7ac8e87a90d50084351da80d4846e19836c Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Sun, 14 Jun 2026 17:40:10 +0800 Subject: [PATCH 03/36] remove keyword filter when pressing clear --- .../Search/SearchPageHeader/SearchPageInput.tsx | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/components/Search/SearchPageHeader/SearchPageInput.tsx b/src/components/Search/SearchPageHeader/SearchPageInput.tsx index 05d2e993da65..f6e91c2bc235 100644 --- a/src/components/Search/SearchPageHeader/SearchPageInput.tsx +++ b/src/components/Search/SearchPageHeader/SearchPageInput.tsx @@ -30,8 +30,8 @@ function SearchPageInput({queryJSON, onFocus}: SearchPageInputProps) { const keywordFilters = queryJSON.flatFilters.find((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD)?.filters ?? []; const keywordQuery = buildFilterValuesString(CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD, keywordFilters).trim(); - function submitSearch() { - const queryWithContext = getKeywordQueryWithCurrentSearchContext(textInputValue, queryJSON); + function submitSearch(query: string) { + const queryWithContext = getKeywordQueryWithCurrentSearchContext(query, queryJSON); const updatedQuery = getQueryWithUpdatedValues(queryWithContext); if (!updatedQuery) { @@ -59,10 +59,10 @@ function SearchPageInput({queryJSON, onFocus}: SearchPageInputProps) { maxLength={CONST.SEARCH_QUERY_LIMIT} onSubmitEditing={() => { if (shouldUseNarrowLayout) { - KeyboardUtils.dismiss().then(submitSearch); + KeyboardUtils.dismiss().then(() => submitSearch(textInputValue)); return; } - submitSearch(); + submitSearch(textInputValue); }} containerStyles={[shouldUseNarrowLayout ? styles.flex1 : undefined]} textInputContainerStyles={[styles.pb0, shouldUseNarrowLayout ? styles.ph3 : styles.ph2]} @@ -72,7 +72,10 @@ function SearchPageInput({queryJSON, onFocus}: SearchPageInputProps) { placeholderTextColor={theme.textSupporting} shouldShowClearButton={!!textInputValue} shouldHideClearButton={false} - onClearInput={() => setTextInputValue('')} + onClearInput={() => { + setTextInputValue(''); + submitSearch(''); + }} onFocus={onFocus} /> ); From 4b20314c3ffb9af23580ab2d3d4dfa2d252b579d Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Sun, 14 Jun 2026 17:44:17 +0800 Subject: [PATCH 04/36] remove unused type --- src/types/onyx/index.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index de1e76f91ff6..e7b9110b1431 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -160,7 +160,6 @@ import type {SavedCSVColumnLayoutData, SavedCSVColumnLayoutList} from './SavedCS import type {SaveSearch} from './SaveSearch'; import type ScheduleCallDraft from './ScheduleCallDraft'; import type ScreenShareRequest from './ScreenShareRequest'; -import type SearchContext from './SearchContext'; import type SearchResults from './SearchResults'; import type SearchSidebar from './SearchSidebar'; import type SecurityGroup from './SecurityGroup'; @@ -373,7 +372,6 @@ export type { DomainSettings, SaveSearch, RecentSearchItem, - SearchContext, SearchSidebar, ImportedSpreadsheet, BankAccountShareDetails, From 89865db0034aaace98408628c686ecebbd980686 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Sun, 14 Jun 2026 18:17:59 +0800 Subject: [PATCH 05/36] fix test --- tests/ui/SearchPageTest.tsx | 4 +-- tests/unit/Search/SearchQueryUtilsTest.ts | 41 ++++++----------------- 2 files changed, 12 insertions(+), 33 deletions(-) diff --git a/tests/ui/SearchPageTest.tsx b/tests/ui/SearchPageTest.tsx index 2088fb0329df..c32d1fe6d035 100644 --- a/tests/ui/SearchPageTest.tsx +++ b/tests/ui/SearchPageTest.tsx @@ -133,7 +133,7 @@ describe('SearchPageNarrow', () => { expect(screen.getByTestId('SearchPageNarrow')).toBeTruthy(); - const searchAutocompleteInput = screen.getByTestId('search-autocomplete-text-input', {includeHiddenElements: true}); - expect(searchAutocompleteInput).toBeTruthy(); + const searchInput = screen.getByPlaceholderText('Search for something...', {includeHiddenElements: true}); + expect(searchInput).toBeTruthy(); }); }); diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index c93533347770..88980741964f 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -668,7 +668,7 @@ describe('SearchQueryUtils', () => { const emptyTaxRates: Record = {}; const currentUserAccountID = 0; - test('preserves manual filter order for raw queries', () => { + test('produces canonical filter order', () => { const queryString = 'type:expense date:this-month groupBy:from tag:travel'; const canonicalQueryString = getQueryWithUpdatedValues(queryString); @@ -696,10 +696,10 @@ describe('SearchQueryUtils', () => { reportAttributes: undefined, }); - expect(result).toBe('type:expense date:this-month group-by:from tag:travel'); + expect(result).toBe('type:expense group-by:from date:this-month tag:travel'); }); - test('preserves status all default value from manual query', () => { + test('drops the default status all value from the query', () => { const queryString = 'type:expense status:all merchant:Uber'; const canonicalQueryString = getQueryWithUpdatedValues(queryString); @@ -727,10 +727,10 @@ describe('SearchQueryUtils', () => { reportAttributes: undefined, }); - expect(result).toBe('type:expense status:all merchant:Uber'); + expect(result).toBe('type:expense merchant:Uber'); }); - test('maps workspace names and maintains manual order', () => { + test('maps workspace names in canonical order', () => { const queryString = 'policyID:123 type:expense merchant:Starbucks'; const canonicalQueryString = getQueryWithUpdatedValues(queryString); @@ -763,7 +763,7 @@ describe('SearchQueryUtils', () => { reportAttributes: undefined, }); - expect(result).toBe('workspace:"Team Space" type:expense merchant:Starbucks'); + expect(result).toBe('type:expense workspace:"Team Space" merchant:Starbucks'); }); test('includes limit in readable query string when present', () => { @@ -1599,14 +1599,6 @@ describe('SearchQueryUtils', () => { expect(queryJSONa?.hash).not.toEqual(queryJSONb?.hash); }); - it('should return different primary hash for implicit table view and explicit view:table', () => { - const queryJSONa = buildSearchQueryJSON('type:expense groupBy:category'); - const queryJSONb = buildSearchQueryJSON('type:expense groupBy:category view:table'); - - expect(queryJSONa?.similarSearchHash).toEqual(queryJSONb?.similarSearchHash); - expect(queryJSONa?.hash).not.toEqual(queryJSONb?.hash); - }); - it('should not include view in query string when groupBy is removed after chart drill-down', () => { const parsed = buildSearchQueryJSON('type:expense date:this-month groupBy:category view:bar'); @@ -2898,25 +2890,12 @@ describe('SearchQueryUtils', () => { expect(result).toContain('status:outstanding'); }); - it('should return query unchanged when it contains explicit filters', () => { - const currentQueryJSON = buildSearchQueryJSON('type:trip status:all'); - - const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('type:expense hello', currentQueryJSON) : ''; - expect(result).toBe('type:expense hello'); - }); - - it('should return query unchanged when it contains only explicit filters without keywords', () => { - const currentQueryJSON = buildSearchQueryJSON('type:trip status:all'); - - const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('type:expense status:open', currentQueryJSON) : ''; - expect(result).toBe('type:expense status:open'); - }); - - it('should return empty query unchanged', () => { - const currentQueryJSON = buildSearchQueryJSON('type:trip status:all'); + it('should keep the current context without keywords when input is empty', () => { + const currentQueryJSON = buildSearchQueryJSON('type:trip status:all existing'); const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('', currentQueryJSON) : ''; - expect(result).toBe(''); + expect(result).toContain('type:trip'); + expect(result).not.toContain('existing'); }); it('should strip existing keyword filters from current context before prepending', () => { From 60427c5036c284ee27e0954c26b6604cb67d2798 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Sun, 14 Jun 2026 18:19:05 +0800 Subject: [PATCH 06/36] lint --- src/components/Search/SearchPageHeader/SearchActionsBarWide.tsx | 1 - src/libs/SearchQueryUtils.ts | 1 - src/pages/Search/SearchPageWide.tsx | 1 - 3 files changed, 3 deletions(-) diff --git a/src/components/Search/SearchPageHeader/SearchActionsBarWide.tsx b/src/components/Search/SearchPageHeader/SearchActionsBarWide.tsx index ef386a8da2ba..02fcca66af9d 100644 --- a/src/components/Search/SearchPageHeader/SearchActionsBarWide.tsx +++ b/src/components/Search/SearchPageHeader/SearchActionsBarWide.tsx @@ -16,7 +16,6 @@ import SearchSaveButton from './SearchSaveButton'; type SearchActionsBarWideProps = { queryJSON: SearchQueryJSON; searchResults: OnyxEntry; - handleSearch: (value: string) => void; onSort: () => void; }; diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index 57878e8c8f64..112bb7eed142 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -47,7 +47,6 @@ import type {SearchFullscreenNavigatorParamList} from './Navigation/types'; import {getDisplayNameOrDefault, getPersonalDetailByEmail} from './PersonalDetailsUtils'; import {getCleanedTagName} from './PolicyUtils'; import {getReportName} from './ReportNameUtils'; -import {parse as parseForAutocomplete} from './SearchParser/autocompleteParser'; import {parse as parseSearchQuery} from './SearchParser/searchParser'; import StringUtils from './StringUtils'; import {hashText} from './UserUtils'; diff --git a/src/pages/Search/SearchPageWide.tsx b/src/pages/Search/SearchPageWide.tsx index e4b7e9264720..0c9f540e2f75 100644 --- a/src/pages/Search/SearchPageWide.tsx +++ b/src/pages/Search/SearchPageWide.tsx @@ -116,7 +116,6 @@ function SearchPageWide({ queryJSON={queryJSON} searchResults={searchResults} onSort={onSortPressedCallback} - handleSearch={handleSearchAction} /> {shouldShowLoadingSkeleton ? ( From 28757c1aaf6dc1b06376036f028829f98af69fc1 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Sun, 14 Jun 2026 18:23:07 +0800 Subject: [PATCH 07/36] remove unused type --- src/types/onyx/SearchContext.ts | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 src/types/onyx/SearchContext.ts diff --git a/src/types/onyx/SearchContext.ts b/src/types/onyx/SearchContext.ts deleted file mode 100644 index 5e815cd957a6..000000000000 --- a/src/types/onyx/SearchContext.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** Model of the search context */ -type SearchContext = { - /** Whether to show the search query in the input field */ - shouldShowSearchQuery: boolean; -}; - -export default SearchContext; From 720f467aa012da487f90c0b7d69e89013ca07cc9 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Sun, 14 Jun 2026 22:32:48 +0800 Subject: [PATCH 08/36] lint --- .../Search/SearchPageHeader/SearchPageInput.tsx | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/components/Search/SearchPageHeader/SearchPageInput.tsx b/src/components/Search/SearchPageHeader/SearchPageInput.tsx index f6e91c2bc235..53aef4e08ce5 100644 --- a/src/components/Search/SearchPageHeader/SearchPageInput.tsx +++ b/src/components/Search/SearchPageHeader/SearchPageInput.tsx @@ -29,6 +29,12 @@ function SearchPageInput({queryJSON, onFocus}: SearchPageInputProps) { const keywordFilters = queryJSON.flatFilters.find((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD)?.filters ?? []; const keywordQuery = buildFilterValuesString(CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD, keywordFilters).trim(); + const [prevKeywordQuery, setPrevKeywordQuery] = useState(''); + + if (keywordQuery !== prevKeywordQuery) { + setTextInputValue(keywordQuery); + setPrevKeywordQuery(keywordQuery); + } function submitSearch(query: string) { const queryWithContext = getKeywordQueryWithCurrentSearchContext(query, queryJSON); @@ -41,10 +47,6 @@ function SearchPageInput({queryJSON, onFocus}: SearchPageInputProps) { Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query: updatedQuery})); } - useEffect(() => { - setTextInputValue(keywordQuery); - }, [keywordQuery]); - return ( Date: Mon, 15 Jun 2026 10:36:01 +0800 Subject: [PATCH 09/36] remove unused import --- src/components/Search/SearchPageHeader/SearchPageInput.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/Search/SearchPageHeader/SearchPageInput.tsx b/src/components/Search/SearchPageHeader/SearchPageInput.tsx index 53aef4e08ce5..0613930dd265 100644 --- a/src/components/Search/SearchPageHeader/SearchPageInput.tsx +++ b/src/components/Search/SearchPageHeader/SearchPageInput.tsx @@ -1,7 +1,7 @@ // NOTE: This component has a static twin in SearchPageNarrow/StaticSearchPageInput.tsx // used for fast perceived performance. If you change the UI here, verify the // static version still looks visually identical. -import React, {useEffect, useState} from 'react'; +import React, {useState} from 'react'; import type {SearchQueryJSON} from '@components/Search/types'; import TextInput from '@components/TextInput'; import useLocalize from '@hooks/useLocalize'; From 92e0c53402461e28001deade58a007a42b9f17e3 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Mon, 15 Jun 2026 21:42:28 +0800 Subject: [PATCH 10/36] fix extra spacing --- src/components/Search/SearchWithNavigationDeferredMount.tsx | 2 +- src/components/Search/index.tsx | 2 +- src/pages/Search/SearchPageWide.tsx | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/components/Search/SearchWithNavigationDeferredMount.tsx b/src/components/Search/SearchWithNavigationDeferredMount.tsx index c73db4612296..d9b6db3fddc2 100644 --- a/src/components/Search/SearchWithNavigationDeferredMount.tsx +++ b/src/components/Search/SearchWithNavigationDeferredMount.tsx @@ -29,7 +29,7 @@ function handleSkeletonLayout() { function SearchWithNavigationDeferredMount(props: ComponentProps) { const styles = useThemeStyles(); const {shouldUseNarrowLayout} = useResponsiveLayout(); - const containerStyle = shouldUseNarrowLayout ? styles.searchListContentContainerStyles(!!props.hasFilterBars) : styles.mt3; + const containerStyle = shouldUseNarrowLayout ? styles.searchListContentContainerStyles(!!props.hasFilterBars) : undefined; return ( {shouldShowLoadingSkeleton ? ( Date: Mon, 15 Jun 2026 21:42:53 +0800 Subject: [PATCH 11/36] move individual style to styles --- src/components/Search/SearchPageHeader/SearchActionsBarWide.tsx | 2 +- src/styles/index.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/components/Search/SearchPageHeader/SearchActionsBarWide.tsx b/src/components/Search/SearchPageHeader/SearchActionsBarWide.tsx index 02fcca66af9d..0b020a9d7976 100644 --- a/src/components/Search/SearchPageHeader/SearchActionsBarWide.tsx +++ b/src/components/Search/SearchPageHeader/SearchActionsBarWide.tsx @@ -25,7 +25,7 @@ function SearchActionsBarWide({queryJSON, searchResults, onSort}: SearchActionsB const hasSelectedItems = selected > 0; return ( - + {hasSelectedItems ? ( diff --git a/src/styles/index.ts b/src/styles/index.ts index 151c2cd44a35..40e7b426c36b 100644 --- a/src/styles/index.ts +++ b/src/styles/index.ts @@ -5072,8 +5072,10 @@ const staticStyles = (theme: ThemeColors) => }, searchActionsBarContainer: { + marginTop: 12, marginBottom: 16, paddingHorizontal: 20, + gap: 8, flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'space-between', From 05cd75d9acc1dd8c47dce1913dac1205a4b56f98 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Mon, 15 Jun 2026 22:22:39 +0800 Subject: [PATCH 12/36] lint --- src/components/Search/index.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index c9b447cf7610..921c800e219e 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -1822,7 +1822,6 @@ function Search({ const {shouldShowYearCreated, shouldShowYearSubmitted, shouldShowYearApproved, shouldShowYearPosted, shouldShowYearExported, shouldShowYearWithdrawn} = yearIndicators; const {shouldShowAmountInWideColumn, shouldShowTaxAmountInWideColumn} = amountIndicators; const shouldShowTableHeader = isLargeScreenWidth && !isChat; - const tableHeaderVisible = canSelectMultiple || shouldShowTableHeader; const shouldShowChartView = (view === CONST.SEARCH.VIEW.BAR || view === CONST.SEARCH.VIEW.LINE || view === CONST.SEARCH.VIEW.PIE) && !!validGroupBy; From 16b91a8088675fcd8b5c04a44578576b0134eb75 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Wed, 17 Jun 2026 11:50:51 +0800 Subject: [PATCH 13/36] fix search filter bar skeleton styling --- src/components/Skeletons/SearchFiltersSkeleton.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/components/Skeletons/SearchFiltersSkeleton.tsx b/src/components/Skeletons/SearchFiltersSkeleton.tsx index 9171ebabf454..0cd68ad7fe09 100644 --- a/src/components/Skeletons/SearchFiltersSkeleton.tsx +++ b/src/components/Skeletons/SearchFiltersSkeleton.tsx @@ -31,7 +31,7 @@ function SearchFiltersSkeleton({shouldAnimate = true, itemCount = 5, width = 84, const skeletonCount = new Array(itemCount).fill(0); return ( - + From d78a38571bf17ff2572c84fd2f935329099c5a25 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Wed, 17 Jun 2026 11:58:37 +0800 Subject: [PATCH 14/36] change clear icon size to 16 --- .../Search/SearchPageHeader/SearchPageInput.tsx | 2 ++ .../BaseTextInput/implementation/index.native.tsx | 2 ++ .../TextInput/BaseTextInput/implementation/index.tsx | 2 ++ src/components/TextInput/BaseTextInput/types.ts | 3 +++ src/components/TextInput/TextInputClearButton/index.tsx | 8 +++++--- 5 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/components/Search/SearchPageHeader/SearchPageInput.tsx b/src/components/Search/SearchPageHeader/SearchPageInput.tsx index 0613930dd265..d8b167abd23b 100644 --- a/src/components/Search/SearchPageHeader/SearchPageInput.tsx +++ b/src/components/Search/SearchPageHeader/SearchPageInput.tsx @@ -10,6 +10,7 @@ import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; import Navigation from '@libs/Navigation/Navigation'; import {buildFilterValuesString, getKeywordQueryWithCurrentSearchContext, getQueryWithUpdatedValues} from '@libs/SearchQueryUtils'; +import variables from '@styles/variables'; import CONST from '@src/CONST'; import ROUTES from '@src/ROUTES'; import KeyboardUtils from '@src/utils/keyboard'; @@ -71,6 +72,7 @@ function SearchPageInput({queryJSON, onFocus}: SearchPageInputProps) { inputStyle={[styles.w100, styles.lineHeightUndefined, shouldUseNarrowLayout ? undefined : styles.fontSizeLabel]} touchableInputWrapperStyle={shouldUseNarrowLayout ? styles.searchPageInputNarrowTouchableWrapper : styles.searchPageInputWideTouchableWrapper} clearButtonStyle={shouldUseNarrowLayout ? undefined : styles.mh0} + clearButtonIconSize={shouldUseNarrowLayout ? undefined : variables.iconSizeSmall} placeholderTextColor={theme.textSupporting} shouldShowClearButton={!!textInputValue} shouldHideClearButton={false} diff --git a/src/components/TextInput/BaseTextInput/implementation/index.native.tsx b/src/components/TextInput/BaseTextInput/implementation/index.native.tsx index aa2a6d08d92b..11a0e57a60e9 100644 --- a/src/components/TextInput/BaseTextInput/implementation/index.native.tsx +++ b/src/components/TextInput/BaseTextInput/implementation/index.native.tsx @@ -84,6 +84,7 @@ function BaseTextInput({ onClearInput, iconContainerStyle, clearButtonStyle, + clearButtonIconSize, shouldUseDefaultLineHeightForPrefix = true, ref, sentryLabel, @@ -460,6 +461,7 @@ function BaseTextInput({ setValue(''); onClearInput?.(); }} + iconSize={clearButtonIconSize} style={[StyleUtils.getTextInputIconContainerStyles(hasLabel, false, verticalPaddingDiff), clearButtonStyle]} /> )} diff --git a/src/components/TextInput/BaseTextInput/implementation/index.tsx b/src/components/TextInput/BaseTextInput/implementation/index.tsx index bec4fa44a6cf..d08ef3514086 100644 --- a/src/components/TextInput/BaseTextInput/implementation/index.tsx +++ b/src/components/TextInput/BaseTextInput/implementation/index.tsx @@ -85,6 +85,7 @@ function BaseTextInput({ onClearInput, iconContainerStyle, clearButtonStyle, + clearButtonIconSize, shouldUseDefaultLineHeightForPrefix = true, ref, sentryLabel, @@ -531,6 +532,7 @@ function BaseTextInput({ setValue(''); onClearInput?.(); }} + iconSize={clearButtonIconSize} style={[StyleUtils.getTextInputIconContainerStyles(hasLabel, false, verticalPaddingDiff), clearButtonStyle]} sentryLabel={sentryLabel ? `${sentryLabel}-ClearButton` : undefined} /> diff --git a/src/components/TextInput/BaseTextInput/types.ts b/src/components/TextInput/BaseTextInput/types.ts index 36d53b612c52..4c0a55765ae3 100644 --- a/src/components/TextInput/BaseTextInput/types.ts +++ b/src/components/TextInput/BaseTextInput/types.ts @@ -174,6 +174,9 @@ type CustomBaseTextInputProps = ForwardedFSClassProps & /** Style for the clear button */ clearButtonStyle?: StyleProp; + /** The clear button icon size */ + clearButtonIconSize?: number; + /** The width of inner content */ contentWidth?: number; diff --git a/src/components/TextInput/TextInputClearButton/index.tsx b/src/components/TextInput/TextInputClearButton/index.tsx index 20c16d279295..71d76bea445b 100644 --- a/src/components/TextInput/TextInputClearButton/index.tsx +++ b/src/components/TextInput/TextInputClearButton/index.tsx @@ -7,15 +7,17 @@ import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; +import variables from '@styles/variables'; import CONST from '@src/CONST'; import type WithSentryLabel from '@src/types/utils/SentryLabel'; type TextInputClearButtonProps = WithSentryLabel & { + iconSize?: number; style?: StyleProp; onPressButton: () => void; }; -function TextInputClearButton({style, onPressButton, sentryLabel}: TextInputClearButtonProps) { +function TextInputClearButton({iconSize = variables.iconSizeNormal, style, onPressButton, sentryLabel}: TextInputClearButtonProps) { const theme = useTheme(); const styles = useThemeStyles(); const {translate} = useLocalize(); @@ -35,8 +37,8 @@ function TextInputClearButton({style, onPressButton, sentryLabel}: TextInputClea > From 0b1d2b371b6dc5111193237c3299d4c1d219bab1 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Wed, 17 Jun 2026 13:33:21 +0800 Subject: [PATCH 15/36] implement keyword escaping in search queries to prevent filter syntax interpretation --- src/libs/SearchQueryUtils.ts | 27 ++++- tests/unit/Search/SearchQueryUtilsTest.ts | 131 ++++++++++++++++++++-- 2 files changed, 144 insertions(+), 14 deletions(-) diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index 112bb7eed142..68e9e7e5ecbf 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -138,6 +138,24 @@ function sanitizeSearchValue(str: string) { return str; } +/** + * Quotes each keyword to escape query syntax. For example, `type:expense` + * becomes `"type:expense"` and is matched as a keyword instead of being + * interpreted as the `type` filter with value `expense`. + */ +function escapeKeyword(keywords: string) { + return keywords + .split(' ') + .map((q) => { + const sanitizedKeyword = sanitizeSearchValue(q); + if (sanitizedKeyword.startsWith('"') && sanitizedKeyword.endsWith('"')) { + return sanitizedKeyword; + } + return `"${q}"`; + }) + .join(' '); +} + function getRangeQueryValue(from?: string, to?: string) { if (from && to) { return `${from},${to}`; @@ -645,8 +663,8 @@ function buildSearchQueryString(queryJSON?: SearchQueryJSON | Readonly): SearchQueryString { const currentFiltersWithoutKeywords = currentQueryJSON.flatFilters.filter((filter) => filter.key !== CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD); const currentQueryString = buildSearchQueryString({...currentQueryJSON, flatFilters: currentFiltersWithoutKeywords}); - return `${currentQueryString} ${queryString}`; + return `${currentQueryString} ${escapeKeyword(queryString)}`; } /** diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index 88980741964f..291b733292a6 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/naming-convention */ // we need "dirty" object key names in these tests import type {OnyxCollection} from 'react-native-onyx'; -import type {ASTNode, SearchQueryJSON} from '@components/Search/types'; +import type {ASTNode, QueryFilter, SearchQueryJSON} from '@components/Search/types'; import {generatePolicyID} from '@libs/actions/Policy/Policy'; import type * as PersonalDetailsUtils from '@libs/PersonalDetailsUtils'; import CONST from '@src/CONST'; @@ -10,6 +10,7 @@ import { applyContainsOperatorToTextFields, buildFilterFormValuesFromQuery, buildFilterQueryWithSortDefaults, + buildFilterValuesString, buildQueryStringFromFilterFormValues, buildSearchQueryJSON, buildSearchQueryString, @@ -114,7 +115,7 @@ describe('SearchQueryUtils', () => { const result = getQueryWithUpdatedValues(userQuery); - expect(result).toEqual(`${defaultQuery} amount:2000000 foo test`); + expect(result).toEqual(`${defaultQuery} amount:2000000 "foo" "test"`); }); test('returns query with user emails substituted', () => { @@ -122,7 +123,7 @@ describe('SearchQueryUtils', () => { const result = getQueryWithUpdatedValues(userQuery); - expect(result).toEqual(`${defaultQuery} from:12345 hello`); + expect(result).toEqual(`${defaultQuery} from:12345 "hello"`); }); test('returns query with user emails substituted and preserves user ids', () => { @@ -138,7 +139,7 @@ describe('SearchQueryUtils', () => { const result = getQueryWithUpdatedValues(userQuery); - expect(result).toEqual(`${defaultQuery} from:9876,87654 to:78901 amount:15000 hello test`); + expect(result).toEqual(`${defaultQuery} from:9876,87654 to:78901 amount:15000 "hello" "test"`); }); test('returns query with updated groupBy', () => { @@ -219,7 +220,7 @@ describe('SearchQueryUtils', () => { const result = buildQueryStringFromFilterFormValues(filterValues); - expect(result).toEqual('type:expense policyID:67890 merchant:Amazon description:Electronics laptop category:electronics,gadgets'); + expect(result).toEqual('type:expense policyID:67890 merchant:Amazon description:Electronics "laptop" category:electronics,gadgets'); }); test('currencies and categories', () => { @@ -523,7 +524,7 @@ describe('SearchQueryUtils', () => { // "10 90" is not a valid positive integer, so limit is dropped entirely expect(result).not.toContain('limit'); - expect(result).toEqual('type:expense hi'); + expect(result).toEqual('type:expense "hi"'); }); test('non-numeric limit value (JSON-like) is discarded to prevent keyword contamination', () => { @@ -537,7 +538,7 @@ describe('SearchQueryUtils', () => { // JSON-like string is not a valid positive integer, so limit is dropped expect(result).not.toContain('limit'); - expect(result).toEqual('type:expense hi'); + expect(result).toEqual('type:expense "hi"'); // Round-trip: keyword must NOT be contaminated const queryJSON = buildSearchQueryJSON(result); @@ -565,7 +566,7 @@ describe('SearchQueryUtils', () => { }; const queryString = buildQueryStringFromFilterFormValues(filterValues); - expect(queryString).toEqual('type:expense hello limit:50'); + expect(queryString).toEqual('type:expense "hello" limit:50'); const queryJSON = buildSearchQueryJSON(queryString); expect(queryJSON?.limit).toBe(50); @@ -1980,6 +1981,108 @@ describe('SearchQueryUtils', () => { expect(result).toContain('view:line'); expect(result).toContain('category:travel'); }); + + test('wraps keyword values in quotes so they are not re-interpreted as filter syntax', () => { + // A quoted keyword that looks like the `type` filter should round-trip back as a quoted keyword + const queryJSON = buildSearchQueryJSON('type:expense "type:expense"'); + + const result = buildSearchQueryString(queryJSON); + + expect(result).toContain('"type:expense"'); + }); + + test('escapes each keyword individually', () => { + const queryJSON = buildSearchQueryJSON('type:expense foo bar'); + + const result = buildSearchQueryString(queryJSON); + + expect(result).toContain('"foo" "bar"'); + }); + + test('keyword escaping round-trips through the parser preserving the keyword value', () => { + const queryJSON = buildSearchQueryJSON('type:expense "status:done"'); + const result = buildSearchQueryString(queryJSON); + + // Re-parsing the built string must keep "status:done" as a keyword, not a status filter + const reparsed = buildSearchQueryJSON(result); + const keywordFilter = reparsed?.flatFilters.find((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD); + expect(keywordFilter?.filters.at(0)?.value).toBe('status:done'); + expect(reparsed?.status).toBe(CONST.SEARCH.STATUS.EXPENSE.ALL); + }); + + test('does not add quotes to non-keyword filter values', () => { + const queryJSON = buildSearchQueryJSON('type:expense merchant:Amazon'); + + const result = buildSearchQueryString(queryJSON); + + expect(result).toContain('merchant:Amazon'); + expect(result).not.toContain('"Amazon"'); + }); + }); + + describe('buildFilterValuesString', () => { + test('joins keyword values with spaces using a leading space', () => { + const queryFilters: QueryFilter[] = [ + {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'hello'}, + {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'world'}, + ]; + + const result = buildFilterValuesString(CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD, queryFilters); + + expect(result.trim()).toBe('hello world'); + }); + + test('wraps keyword values containing spaces in quotes', () => { + const queryFilters: QueryFilter[] = [{operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'hello world'}]; + + const result = buildFilterValuesString(CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD, queryFilters); + + expect(result.trim()).toBe('"hello world"'); + }); + + test('joins equal-to values for non-keyword filters with commas', () => { + const queryFilters: QueryFilter[] = [ + {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'a'}, + {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'b'}, + ]; + + const result = buildFilterValuesString(CONST.SEARCH.SYNTAX_FILTER_KEYS.CATEGORY, queryFilters); + + expect(result.trim()).toBe('category:a,b'); + }); + + test('renders not-equal-to values with a negated key prefix', () => { + const queryFilters: QueryFilter[] = [{operator: CONST.SEARCH.SYNTAX_OPERATORS.NOT_EQUAL_TO, value: 'travel'}]; + + const result = buildFilterValuesString(CONST.SEARCH.SYNTAX_FILTER_KEYS.CATEGORY, queryFilters); + + expect(result.trim()).toBe('-category:travel'); + }); + + test('expands a range operator into inclusive boundary expressions', () => { + const queryFilters: QueryFilter[] = [{operator: CONST.SEARCH.SYNTAX_OPERATORS.RANGE, value: '2025-03-01,2025-03-10'}]; + + const result = buildFilterValuesString(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, queryFilters); + + expect(result.trim()).toBe('date>=2025-03-01 date<=2025-03-10'); + }); + + test('renders comparison operators using their operator character', () => { + const queryFilters: QueryFilter[] = [ + {operator: CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN, value: '100'}, + {operator: CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN, value: '500'}, + ]; + + const result = buildFilterValuesString(CONST.SEARCH.SYNTAX_FILTER_KEYS.AMOUNT, queryFilters); + + expect(result.trim()).toBe('amount>100 amount<500'); + }); + + test('returns an empty string when there are no filters', () => { + const result = buildFilterValuesString(CONST.SEARCH.SYNTAX_FILTER_KEYS.CATEGORY, []); + + expect(result).toBe(''); + }); }); describe('buildFilterQueryWithSortDefaults', () => { @@ -2910,7 +3013,17 @@ describe('SearchQueryUtils', () => { const currentQueryJSON = buildSearchQueryJSON('type:trip status:all'); const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('hello world', currentQueryJSON) : ''; - expect(result).toContain('hello world'); + // Each word is escaped as its own quoted keyword to avoid being interpreted as filter syntax + expect(result).toContain('"hello" "world"'); + expect(result).toContain('type:trip'); + }); + + it('should escape input that looks like filter syntax so it is treated as a keyword', () => { + const currentQueryJSON = buildSearchQueryJSON('type:trip status:all'); + + const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('type:expense', currentQueryJSON) : ''; + // The user typed "type:expense" as free text, so it must be quoted instead of overriding the context type + expect(result).toContain('"type:expense"'); expect(result).toContain('type:trip'); }); }); From 0c5211292cc6ee3853c3d4f77b1c999f088378b9 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Wed, 17 Jun 2026 16:02:26 +0800 Subject: [PATCH 16/36] populate initial search router input value from the current query on the search page --- .../Search/SearchRouter/SearchRouter.tsx | 61 +++++++++++++++++-- .../Search/SearchRouter/SearchRouterUtils.ts | 10 ++- tests/unit/SearchRouterUtilsTest.ts | 52 ++++++++++++++++ 3 files changed, 114 insertions(+), 9 deletions(-) diff --git a/src/components/Search/SearchRouter/SearchRouter.tsx b/src/components/Search/SearchRouter/SearchRouter.tsx index e156624c5a86..e538aaaf9469 100644 --- a/src/components/Search/SearchRouter/SearchRouter.tsx +++ b/src/components/Search/SearchRouter/SearchRouter.tsx @@ -10,7 +10,7 @@ import {usePersonalDetails} from '@components/OnyxListItemProvider'; import type {AnimatedTextInputRef} from '@components/RNTextInput'; import DeferredAutocompleteList from '@components/Search/DeferredSearchAutocompleteList'; import type {GetAdditionalSectionsCallback} from '@components/Search/SearchAutocompleteList'; -import {useSearchQueryActions} from '@components/Search/SearchContext'; +import {useSearchQueryActions, useSearchQueryContext} from '@components/Search/SearchContext'; import SearchInputSelectionWrapper from '@components/Search/SearchInputSelectionWrapper'; import type {SearchQueryItem} from '@components/Search/SearchList/ListItem/SearchQueryListItem'; import {isSearchQueryItem} from '@components/Search/SearchList/ListItem/SearchQueryListItem'; @@ -18,10 +18,12 @@ import type {SearchQueryString} from '@components/Search/types'; import type {SelectionListWithSectionsHandle} from '@components/SelectionList/SelectionListWithSections/types'; import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails'; import useDebouncedState from '@hooks/useDebouncedState'; +import useFeedKeysWithAssignedCards from '@hooks/useFeedKeysWithAssignedCards'; import useKeyboardShortcut from '@hooks/useKeyboardShortcut'; import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useOnyx from '@hooks/useOnyx'; +import useReportAttributes from '@hooks/useReportAttributes'; import useReportOrReportDraft from '@hooks/useReportOrReportDraft'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useRootNavigationState from '@hooks/useRootNavigationState'; @@ -32,11 +34,12 @@ import backHistory from '@libs/Navigation/helpers/backHistory'; import type {SearchOption} from '@libs/OptionsListUtils'; import {createOptionFromReport} from '@libs/OptionsListUtils'; import Parser from '@libs/Parser'; +import {getAllTaxRates} from '@libs/PolicyUtils'; import {getReportAction} from '@libs/ReportActionsUtils'; import {isHiddenForCurrentUser} from '@libs/ReportUtils'; import type {OptionData} from '@libs/ReportUtils'; import {getAutocompleteQueryWithComma, getTrimmedUserSearchQueryPreservingComma} from '@libs/SearchAutocompleteUtils'; -import {getQueryWithUpdatedValues, sanitizeSearchValue} from '@libs/SearchQueryUtils'; +import {buildUserReadableQueryString, getQueryWithUpdatedValues, sanitizeSearchValue} from '@libs/SearchQueryUtils'; import StringUtils from '@libs/StringUtils'; import Navigation from '@navigation/Navigation'; import variables from '@styles/variables'; @@ -45,6 +48,7 @@ import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; import type Report from '@src/types/onyx/Report'; +import {buildSubstitutionsMap} from './buildSubstitutionsMap'; import type {SubstitutionMap} from './getQueryWithSubstitutions'; import {getQueryWithSubstitutions} from './getQueryWithSubstitutions'; import {getUpdatedSubstitutionsMap} from './getUpdatedSubstitutionsMap'; @@ -80,7 +84,54 @@ function SearchRouter({onRouterClose, shouldHideInputCaret, isSearchRouterDispla const expensifyIcons = useMemoizedLazyExpensifyIcons(['MagnifyingGlass', 'ConciergeAvatar']); const {askConcierge, shouldShowAskConcierge} = useAskConcierge(); - const initialQuery = peekPendingRouterQuery(); + const {contextualReportID, isSearchRouterScreen, isOnSearchPage} = useRootNavigationState(getContextualReportData); + const {currentSearchQueryJSON} = useSearchQueryContext(); + const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); + const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY); + const [personalAndWorkspaceCards] = useOnyx(ONYXKEYS.DERIVED.PERSONAL_AND_WORKSPACE_CARD_LIST); + const [allFeeds] = useOnyx(ONYXKEYS.COLLECTION.SHARED_NVP_PRIVATE_DOMAIN_MEMBER); + const feedKeysWithCards = useFeedKeysWithAssignedCards(); + const reportAttributes = useReportAttributes(); + + // Seed the input on open. When the SearchRouter is opened while on the search page, we build a + // user-readable query string from the current search query (showing names instead of IDs) along + // with the substitutions map needed to map those names back to IDs when submitting. + // Otherwise we fall back to the explicit pending query (e.g. from ExpenseReportSearchHandler). + // Computed once via a lazy initializer so the query string and its substitutions stay consistent. + const [[initialQuery, initialSubstitutions]] = useState<[string, SubstitutionMap]>(() => { + if (!isOnSearchPage || !currentSearchQueryJSON) { + return [peekPendingRouterQuery(), {}]; + } + + const taxRates = getAllTaxRates(policies); + const query = buildUserReadableQueryString({ + queryJSON: currentSearchQueryJSON, + PersonalDetails: personalDetails, + reports, + taxRates, + cardList: personalAndWorkspaceCards, + cardFeeds: allFeeds, + policies, + currentUserAccountID, + autoCompleteWithSpace: false, + translate, + feedKeysWithCards, + reportAttributes, + }); + const substitutions = buildSubstitutionsMap( + currentSearchQueryJSON.inputQuery, + personalDetails, + reports, + taxRates, + personalAndWorkspaceCards, + allFeeds, + policies, + currentUserAccountID, + translate, + reportAttributes, + ); + return [query, substitutions]; + }); // The actual input text that the user sees const [textInputValue, , setTextInputValue] = useDebouncedState(initialQuery, 500); @@ -91,11 +142,9 @@ function SearchRouter({onRouterClose, shouldHideInputCaret, isSearchRouterDispla useEffect(() => { clearPendingRouterQuery(); }, []); - const [autocompleteSubstitutions, setAutocompleteSubstitutions] = useState({}); + const [autocompleteSubstitutions, setAutocompleteSubstitutions] = useState(initialSubstitutions); const textInputRef = useRef(null); - const {contextualReportID, isSearchRouterScreen} = useRootNavigationState(getContextualReportData); - const contextualReport = useReportOrReportDraft(contextualReportID); const [contextualReportNVP] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${contextualReportID}`, { selector: privateIsArchivedSelector, diff --git a/src/components/Search/SearchRouter/SearchRouterUtils.ts b/src/components/Search/SearchRouter/SearchRouterUtils.ts index 6d0a857e6498..482a1397c8e6 100644 --- a/src/components/Search/SearchRouter/SearchRouterUtils.ts +++ b/src/components/Search/SearchRouter/SearchRouterUtils.ts @@ -11,6 +11,7 @@ import type * as OnyxTypes from '@src/types/onyx'; type ContextualReportData = { contextualReportID: string | undefined; isSearchRouterScreen: boolean; + isOnSearchPage: boolean; }; /** @@ -31,7 +32,7 @@ type ContextualReportData = { function getContextualReportData(state: NavigationState | undefined): ContextualReportData { // Safe handling when navigation is not yet initialized if (!state) { - return {contextualReportID: undefined, isSearchRouterScreen: false}; + return {contextualReportID: undefined, isSearchRouterScreen: false, isOnSearchPage: false}; } let maybeReportRoute = findFocusedRoute(state); const isSearchRouterScreen = maybeReportRoute?.name === SCREENS.SEARCH_ROUTER.ROOT; @@ -46,9 +47,12 @@ function getContextualReportData(state: NavigationState | undefined): Contextual if (maybeReportRoute?.name === SCREENS.REPORT || maybeReportRoute?.name === SCREENS.RIGHT_MODAL.EXPENSE_REPORT) { // We're guaranteed that the type of params is of SCREENS.REPORT - return {contextualReportID: (maybeReportRoute?.params as ReportsSplitNavigatorParamList[typeof SCREENS.REPORT]).reportID, isSearchRouterScreen}; + return {contextualReportID: (maybeReportRoute?.params as ReportsSplitNavigatorParamList[typeof SCREENS.REPORT]).reportID, isSearchRouterScreen, isOnSearchPage: false}; } - return {contextualReportID: undefined, isSearchRouterScreen}; + + // Whether the screen underneath the SearchRouter (or the focused screen when the router is an overlay) is the search page + const isOnSearchPage = maybeReportRoute?.name === SCREENS.SEARCH.ROOT; + return {contextualReportID: undefined, isSearchRouterScreen, isOnSearchPage}; } function getContextualSearchAutocompleteKey(item: SearchQueryItem, policies: OnyxCollection, reports?: OnyxCollection) { diff --git a/tests/unit/SearchRouterUtilsTest.ts b/tests/unit/SearchRouterUtilsTest.ts index 2764224b412f..75f57081b495 100644 --- a/tests/unit/SearchRouterUtilsTest.ts +++ b/tests/unit/SearchRouterUtilsTest.ts @@ -16,6 +16,7 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: undefined, isSearchRouterScreen: false, + isOnSearchPage: false, }); }); @@ -35,6 +36,7 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: '12345', isSearchRouterScreen: false, + isOnSearchPage: false, }); }); @@ -54,6 +56,7 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: '67890', isSearchRouterScreen: false, + isOnSearchPage: false, }); }); @@ -77,6 +80,7 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: '11111', isSearchRouterScreen: true, + isOnSearchPage: false, }); }); @@ -100,6 +104,7 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: undefined, isSearchRouterScreen: true, + isOnSearchPage: false, }); }); @@ -119,6 +124,7 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: undefined, isSearchRouterScreen: false, + isOnSearchPage: false, }); }); @@ -146,6 +152,7 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: '55555', isSearchRouterScreen: false, + isOnSearchPage: false, }); }); @@ -169,6 +176,51 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: '99999', isSearchRouterScreen: true, + isOnSearchPage: false, + }); + }); + + it('returns isOnSearchPage true when focused on the Search page', () => { + const state = createMockState({ + index: 0, + routes: [ + { + name: SCREENS.SEARCH.ROOT, + params: {}, + }, + ], + }); + + const result = getContextualReportData(state); + + expect(result).toEqual({ + contextualReportID: undefined, + isSearchRouterScreen: false, + isOnSearchPage: true, + }); + }); + + it('returns isOnSearchPage true when SearchRouter is open over the Search page', () => { + const state = createMockState({ + index: 1, + routes: [ + { + name: SCREENS.SEARCH.ROOT, + params: {}, + }, + { + name: SCREENS.SEARCH_ROUTER.ROOT, + params: {}, + }, + ], + }); + + const result = getContextualReportData(state); + + expect(result).toEqual({ + contextualReportID: undefined, + isSearchRouterScreen: true, + isOnSearchPage: true, }); }); }); From b3bc0c8fad4b602434ac352cd855f6508fbb35d0 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Wed, 17 Jun 2026 17:04:04 +0800 Subject: [PATCH 17/36] do the escaping on the deeper function --- .../SearchPageHeader/SearchPageInput.tsx | 4 +-- src/libs/SearchQueryUtils.ts | 22 +++++++------- tests/unit/Search/SearchQueryUtilsTest.ts | 29 +++++++------------ 3 files changed, 24 insertions(+), 31 deletions(-) diff --git a/src/components/Search/SearchPageHeader/SearchPageInput.tsx b/src/components/Search/SearchPageHeader/SearchPageInput.tsx index d8b167abd23b..e6d9ed449288 100644 --- a/src/components/Search/SearchPageHeader/SearchPageInput.tsx +++ b/src/components/Search/SearchPageHeader/SearchPageInput.tsx @@ -9,7 +9,7 @@ import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; import Navigation from '@libs/Navigation/Navigation'; -import {buildFilterValuesString, getKeywordQueryWithCurrentSearchContext, getQueryWithUpdatedValues} from '@libs/SearchQueryUtils'; +import {getKeywordQueryWithCurrentSearchContext, getQueryWithUpdatedValues} from '@libs/SearchQueryUtils'; import variables from '@styles/variables'; import CONST from '@src/CONST'; import ROUTES from '@src/ROUTES'; @@ -29,7 +29,7 @@ function SearchPageInput({queryJSON, onFocus}: SearchPageInputProps) { const [textInputValue, setTextInputValue] = useState(''); const keywordFilters = queryJSON.flatFilters.find((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD)?.filters ?? []; - const keywordQuery = buildFilterValuesString(CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD, keywordFilters).trim(); + const keywordQuery = keywordFilters.reduce((acc, keyword) => `${acc} ${keyword.value}`, '').trim(); const [prevKeywordQuery, setPrevKeywordQuery] = useState(''); if (keywordQuery !== prevKeywordQuery) { diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index 68e9e7e5ecbf..ac8f861d92f5 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -139,19 +139,21 @@ function sanitizeSearchValue(str: string) { } /** - * Quotes each keyword to escape query syntax. For example, `type:expense` - * becomes `"type:expense"` and is matched as a keyword instead of being - * interpreted as the `type` filter with value `expense`. + * Escapes each keyword that would otherwise be re-interpreted as query syntax by wrapping it in quotes. + * A keyword that looks like a filter (e.g. `type:expense`) becomes `"type:expense"` so it is matched as a + * keyword instead of being parsed as the `type` filter. Keywords containing spaces are wrapped by + * `sanitizeSearchValue`. Plain keywords (e.g. `foo`) are left untouched. */ function escapeKeyword(keywords: string) { return keywords .split(' ') .map((q) => { const sanitizedKeyword = sanitizeSearchValue(q); - if (sanitizedKeyword.startsWith('"') && sanitizedKeyword.endsWith('"')) { - return sanitizedKeyword; + if (sanitizedKeyword.match(/^\w+:\w+$/)) { + // The keyword is not escaped yet by sanitizeSearchValue, so we do it here. + return `"${q}"`; } - return `"${q}"`; + return sanitizedKeyword; }) .join(' '); } @@ -317,9 +319,9 @@ function buildFilterValuesString(filterName: string, queryFilters: QueryFilter[] const nextValueHasSameOp = allowedOps.has(queryFilter.operator) && queryFilters?.at(index + 1)?.operator === queryFilter.operator; // If the previous queryFilter has the same operator (this rule applies only to eq and neq operators) then append the current value - if (index !== 0 && (previousValueHasSameOp || nextValueHasSameOp)) { - filterValueString += `${delimiter}${sanitizeSearchValue(queryFilter.value.toString())}`; - } else if (filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD) { + if (filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD) { + filterValueString += `${delimiter}${escapeKeyword(queryFilter.value.toString())}`; + } else if (index !== 0 && (previousValueHasSameOp || nextValueHasSameOp)) { filterValueString += `${delimiter}${sanitizeSearchValue(queryFilter.value.toString())}`; } else if (queryFilter.operator === CONST.SEARCH.SYNTAX_OPERATORS.NOT_EQUAL_TO) { filterValueString += ` -${filterName}:${sanitizeSearchValue(queryFilter.value.toString())}`; @@ -664,7 +666,7 @@ function buildSearchQueryString(queryJSON?: SearchQueryJSON | Readonly { const result = getQueryWithUpdatedValues(userQuery); - expect(result).toEqual(`${defaultQuery} amount:2000000 "foo" "test"`); + expect(result).toEqual(`${defaultQuery} amount:2000000 foo test`); }); test('returns query with user emails substituted', () => { @@ -123,7 +123,7 @@ describe('SearchQueryUtils', () => { const result = getQueryWithUpdatedValues(userQuery); - expect(result).toEqual(`${defaultQuery} from:12345 "hello"`); + expect(result).toEqual(`${defaultQuery} from:12345 hello`); }); test('returns query with user emails substituted and preserves user ids', () => { @@ -139,7 +139,7 @@ describe('SearchQueryUtils', () => { const result = getQueryWithUpdatedValues(userQuery); - expect(result).toEqual(`${defaultQuery} from:9876,87654 to:78901 amount:15000 "hello" "test"`); + expect(result).toEqual(`${defaultQuery} from:9876,87654 to:78901 amount:15000 hello test`); }); test('returns query with updated groupBy', () => { @@ -220,7 +220,7 @@ describe('SearchQueryUtils', () => { const result = buildQueryStringFromFilterFormValues(filterValues); - expect(result).toEqual('type:expense policyID:67890 merchant:Amazon description:Electronics "laptop" category:electronics,gadgets'); + expect(result).toEqual('type:expense policyID:67890 merchant:Amazon description:Electronics laptop category:electronics,gadgets'); }); test('currencies and categories', () => { @@ -524,7 +524,7 @@ describe('SearchQueryUtils', () => { // "10 90" is not a valid positive integer, so limit is dropped entirely expect(result).not.toContain('limit'); - expect(result).toEqual('type:expense "hi"'); + expect(result).toEqual('type:expense hi'); }); test('non-numeric limit value (JSON-like) is discarded to prevent keyword contamination', () => { @@ -538,7 +538,7 @@ describe('SearchQueryUtils', () => { // JSON-like string is not a valid positive integer, so limit is dropped expect(result).not.toContain('limit'); - expect(result).toEqual('type:expense "hi"'); + expect(result).toEqual('type:expense hi'); // Round-trip: keyword must NOT be contaminated const queryJSON = buildSearchQueryJSON(result); @@ -566,7 +566,7 @@ describe('SearchQueryUtils', () => { }; const queryString = buildQueryStringFromFilterFormValues(filterValues); - expect(queryString).toEqual('type:expense "hello" limit:50'); + expect(queryString).toEqual('type:expense hello limit:50'); const queryJSON = buildSearchQueryJSON(queryString); expect(queryJSON?.limit).toBe(50); @@ -1991,12 +1991,12 @@ describe('SearchQueryUtils', () => { expect(result).toContain('"type:expense"'); }); - test('escapes each keyword individually', () => { + test('does not quote plain keywords that cannot be confused with filter syntax', () => { const queryJSON = buildSearchQueryJSON('type:expense foo bar'); const result = buildSearchQueryString(queryJSON); - expect(result).toContain('"foo" "bar"'); + expect(result).toContain('foo bar'); }); test('keyword escaping round-trips through the parser preserving the keyword value', () => { @@ -2032,14 +2032,6 @@ describe('SearchQueryUtils', () => { expect(result.trim()).toBe('hello world'); }); - test('wraps keyword values containing spaces in quotes', () => { - const queryFilters: QueryFilter[] = [{operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'hello world'}]; - - const result = buildFilterValuesString(CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD, queryFilters); - - expect(result.trim()).toBe('"hello world"'); - }); - test('joins equal-to values for non-keyword filters with commas', () => { const queryFilters: QueryFilter[] = [ {operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'a'}, @@ -3013,8 +3005,7 @@ describe('SearchQueryUtils', () => { const currentQueryJSON = buildSearchQueryJSON('type:trip status:all'); const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('hello world', currentQueryJSON) : ''; - // Each word is escaped as its own quoted keyword to avoid being interpreted as filter syntax - expect(result).toContain('"hello" "world"'); + expect(result).toContain('hello world'); expect(result).toContain('type:trip'); }); From e64c58f16997b7f9edf024fd440be5e9db55564d Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Wed, 17 Jun 2026 22:30:28 +0800 Subject: [PATCH 18/36] merge with main leftover --- Mobile-Expensify | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Mobile-Expensify b/Mobile-Expensify index 136c65872c06..95d29444b9d6 160000 --- a/Mobile-Expensify +++ b/Mobile-Expensify @@ -1 +1 @@ -Subproject commit 136c65872c06aa3c67ce4a0a542ca3782dcdcacc +Subproject commit 95d29444b9d6dc5452e18a4e16dbe878b2232b03 From f1f5a7c00853d530967d18ff80c6257e1d5f63d1 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Wed, 17 Jun 2026 22:47:20 +0800 Subject: [PATCH 19/36] Revert "merge with main leftover" This reverts commit e64c58f16997b7f9edf024fd440be5e9db55564d. --- Mobile-Expensify | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Mobile-Expensify b/Mobile-Expensify index 95d29444b9d6..136c65872c06 160000 --- a/Mobile-Expensify +++ b/Mobile-Expensify @@ -1 +1 @@ -Subproject commit 95d29444b9d6dc5452e18a4e16dbe878b2232b03 +Subproject commit 136c65872c06aa3c67ce4a0a542ca3782dcdcacc From de2661dc6521cca7440558e8f80bc56fdf10398d Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Wed, 17 Jun 2026 22:50:44 +0800 Subject: [PATCH 20/36] restore previous change --- Mobile-Expensify | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Mobile-Expensify b/Mobile-Expensify index 136c65872c06..86e56434bea1 160000 --- a/Mobile-Expensify +++ b/Mobile-Expensify @@ -1 +1 @@ -Subproject commit 136c65872c06aa3c67ce4a0a542ca3782dcdcacc +Subproject commit 86e56434bea180a6e84c316c24e3927430b8bff3 From b8ff0b29d193e7b5accbbcb2ab5bfc8b8bd155df Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Fri, 19 Jun 2026 11:58:25 +0800 Subject: [PATCH 21/36] add back the raw query logic --- src/ONYXKEYS.ts | 4 + src/ROUTES.ts | 5 +- .../SearchAdvancedFiltersPopup/index.tsx | 8 +- .../Search/FilterDropdowns/SortByPopup.tsx | 3 +- .../Search/FilterDropdowns/SortOrderPopup.tsx | 3 +- .../Search/SearchAutocompleteInput.tsx | 2 + .../SearchPageHeader/useSearchFiltersBar.tsx | 2 + src/components/Search/SearchQueryProvider.tsx | 8 +- .../Search/hooks/useUpdateFilterQuery.tsx | 2 +- src/components/Search/index.tsx | 8 +- src/components/Search/types.ts | 12 + src/libs/Navigation/types.ts | 1 + src/libs/SearchParser/searchParser.js | 23 ++ src/libs/SearchParser/searchParser.peggy | 23 ++ src/libs/SearchQueryUtils.ts | 243 +++++++++++++++++- src/libs/actions/Search.ts | 9 + src/pages/Search/SavedSearchList.tsx | 2 + .../Search/SearchAdvancedFiltersProvider.tsx | 17 +- src/pages/Search/SearchTypeMenuNarrow.tsx | 5 +- src/pages/Search/SearchTypeMenuWide.tsx | 2 + .../Subscription/CardSection/CardSection.tsx | 2 +- src/types/onyx/SearchContext.ts | 7 + src/types/onyx/index.ts | 2 + tests/actions/IOU/SearchUpdateTest.ts | 8 + tests/unit/NavigationFocusReturnTest.ts | 8 + .../unit/Search/SearchListRenderCountTest.tsx | 1 + tests/unit/Search/SearchQueryUtilsTest.ts | 84 +++++- .../unit/Search/yourSpendQueryBuildersTest.ts | 3 + tests/unit/SearchParserTest.ts | 16 +- 29 files changed, 481 insertions(+), 32 deletions(-) create mode 100644 src/types/onyx/SearchContext.ts diff --git a/src/ONYXKEYS.ts b/src/ONYXKEYS.ts index f08f69ab14c6..67dd60ea1de0 100755 --- a/src/ONYXKEYS.ts +++ b/src/ONYXKEYS.ts @@ -626,6 +626,9 @@ const ONYXKEYS = { /** Stores the information about the recent searches */ RECENT_SEARCHES: 'nvp_recentSearches', + /** Stores the current search page context (e.g., whether to show the search query) */ + SEARCH_CONTEXT: 'searchContext', + /** Stores recently used currencies */ RECENTLY_USED_CURRENCIES: 'nvp_recentlyUsedCurrencies', @@ -1428,6 +1431,7 @@ type OnyxValuesMapping = { [ONYXKEYS.NVP_TRY_NEW_DOT]: OnyxTypes.TryNewDot; [ONYXKEYS.RECENT_SEARCHES]: Record; [ONYXKEYS.SAVED_SEARCHES]: OnyxTypes.SaveSearch; + [ONYXKEYS.SEARCH_CONTEXT]: OnyxTypes.SearchContext; [ONYXKEYS.RECENTLY_USED_CURRENCIES]: string[]; [ONYXKEYS.ACTIVE_CLIENTS]: string[]; [ONYXKEYS.DEVICE_ID]: string; diff --git a/src/ROUTES.ts b/src/ROUTES.ts index 8e9cbaff75dc..ac8e4a090e64 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -903,8 +903,9 @@ const ROUTES = { SEARCH_ROUTER: 'search-router', SEARCH_ROOT: { route: 'search', - getRoute: ({query, name}: {query: SearchQueryString; name?: string}) => { - return `search?q=${encodeURIComponent(query)}${name ? `&name=${name}` : ''}` as const; + getRoute: ({query, rawQuery, name}: {query: SearchQueryString; rawQuery?: SearchQueryString; name?: string}) => { + const rawQuerySegment = rawQuery ? `&rawQuery=${encodeURIComponent(rawQuery)}` : ''; + return `search?q=${encodeURIComponent(query)}${name ? `&name=${name}` : ''}${rawQuerySegment}` as const; }, }, SEARCH_ROOT_VERIFY_ACCOUNT: `search/${VERIFY_ACCOUNT}`, diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 63ab10f26a4f..604adc159bbb 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -9,6 +9,7 @@ import useOnyx from '@hooks/useOnyx'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; import useWindowDimensions from '@hooks/useWindowDimensions'; +import {setSearchContext} from '@libs/actions/Search'; import type {SearchFilter} from '@libs/SearchUIUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -58,7 +59,12 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps Date: DateFilterContentPopupWrapper, ReportField: ReportFieldFilterContentPopupWrapper, }} - onChange={updateFilterQueryParams} + onChange={(values) => { + updateFilterQueryParams(values); + if (values.keyword) { + setSearchContext(true); + } + }} /> diff --git a/src/components/Search/FilterDropdowns/SortByPopup.tsx b/src/components/Search/FilterDropdowns/SortByPopup.tsx index cdbed340f194..3624b564f96d 100644 --- a/src/components/Search/FilterDropdowns/SortByPopup.tsx +++ b/src/components/Search/FilterDropdowns/SortByPopup.tsx @@ -65,8 +65,9 @@ function SortByPopup({searchResults, queryJSON, groupBy, onSort, onSortOrderPres clearSelectedTransactions(); const newQuery = buildSearchQueryString({...queryJSON, sortBy: column}); onSort(); + // We want to explicitly clear stale rawQuery since it's only used for manually typed-in queries. close(() => { - Navigation.setParams({q: newQuery}); + Navigation.setParams({q: newQuery, rawQuery: undefined}); }); }; diff --git a/src/components/Search/FilterDropdowns/SortOrderPopup.tsx b/src/components/Search/FilterDropdowns/SortOrderPopup.tsx index 65d072352c6b..33e66e4a01f6 100644 --- a/src/components/Search/FilterDropdowns/SortOrderPopup.tsx +++ b/src/components/Search/FilterDropdowns/SortOrderPopup.tsx @@ -23,8 +23,9 @@ function SortOrderPopup({queryJSON, onSort, onBackButtonPress, closeOverlay}: So clearSelectedTransactions(); const newQuery = buildSearchQueryString({...queryJSON, sortOrder}); onSort(); + // We want to explicitly clear stale rawQuery since it's only used for manually typed-in queries. close(() => { - Navigation.setParams({q: newQuery}); + Navigation.setParams({q: newQuery, rawQuery: undefined}); }); }; diff --git a/src/components/Search/SearchAutocompleteInput.tsx b/src/components/Search/SearchAutocompleteInput.tsx index 11c919a79caa..5f1f80c5d3f7 100644 --- a/src/components/Search/SearchAutocompleteInput.tsx +++ b/src/components/Search/SearchAutocompleteInput.tsx @@ -17,6 +17,7 @@ import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; +import {setSearchContext} from '@libs/actions/Search'; import scheduleOnLiveMarkdownRuntime from '@libs/scheduleOnLiveMarkdownRuntime'; import {getAutocompleteCategories, getAutocompleteTags, parseForLiveMarkdown} from '@libs/SearchAutocompleteUtils'; import {expensifyLoginsSelector} from '@libs/UserUtils'; @@ -193,6 +194,7 @@ function SearchAutocompleteInput({ const clearInput = () => { onSearchQueryChange(''); + setSearchContext(false); }; const inputWidth = isFullWidth ? styles.w100 : {width: variables.popoverWidth}; diff --git a/src/components/Search/SearchPageHeader/useSearchFiltersBar.tsx b/src/components/Search/SearchPageHeader/useSearchFiltersBar.tsx index 92e9a94d07df..e0a67471c22e 100644 --- a/src/components/Search/SearchPageHeader/useSearchFiltersBar.tsx +++ b/src/components/Search/SearchPageHeader/useSearchFiltersBar.tsx @@ -13,6 +13,7 @@ import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useOnyx from '@hooks/useOnyx'; import {close} from '@libs/actions/Modal'; +import {setSearchContext} from '@libs/actions/Search'; import {getAdvancedFiltersToReset} from '@libs/SearchQueryUtils'; import {FILTER_VIEW_MAP, isAmountFilterKey, isDateFilterKey, mapFiltersFormToLabelValueList, SKIPPED_SEARCH_FILTERS} from '@libs/SearchUIUtils'; import type {SearchFilter} from '@libs/SearchUIUtils'; @@ -182,6 +183,7 @@ function useSearchFiltersBar(queryJSON: SearchQueryJSON): UseSearchFiltersBarRes const clearFilters = () => { setFilterQueryParams(getAdvancedFiltersToReset(searchAdvancedFiltersForm ?? {})); + setSearchContext(false); }; return { diff --git a/src/components/Search/SearchQueryProvider.tsx b/src/components/Search/SearchQueryProvider.tsx index 4734ad95b919..c4ce93687c46 100644 --- a/src/components/Search/SearchQueryProvider.tsx +++ b/src/components/Search/SearchQueryProvider.tsx @@ -21,13 +21,19 @@ function selectSearchQueryParam(state: NavigationState | undefined) { return focused?.name === SCREENS.SEARCH.ROOT ? (focused.params?.q as string | undefined) : undefined; } +function selectSearchRawQueryParam(state: NavigationState | undefined) { + const focused = getDeepestFocusedScreen(state); + return focused?.name === SCREENS.SEARCH.ROOT ? (focused.params?.rawQuery as string | undefined) : undefined; +} + function SearchQueryProvider({children}: SearchQueryProviderProps) { const navigation = useNavigation(); // Extract only the primitive values we need from the focused screen to avoid // re-renders from new object references returned by getDeepestFocusedScreen. const queryParam = useRootNavigationState((state) => selectSearchQueryParam(state ?? navigation.getState())); + const rawQueryParam = useRootNavigationState((state) => selectSearchRawQueryParam(state ?? navigation.getState())); const definedQueryParam = usePreviousDefined(queryParam) ?? buildSearchQueryString(); - const currentSearchQueryJSON = buildSearchQueryJSON(definedQueryParam); + const currentSearchQueryJSON = buildSearchQueryJSON(definedQueryParam, rawQueryParam); const {defaultCardFeed} = useCardFeedsForDisplay(); const {accountID} = useCurrentUserPersonalDetails(); diff --git a/src/components/Search/hooks/useUpdateFilterQuery.tsx b/src/components/Search/hooks/useUpdateFilterQuery.tsx index d21cbc6b2d5f..10d8b6da4c19 100644 --- a/src/components/Search/hooks/useUpdateFilterQuery.tsx +++ b/src/components/Search/hooks/useUpdateFilterQuery.tsx @@ -43,7 +43,7 @@ function useUpdateFilterQuery(queryJSON: SearchQueryJSON | undefined) { return; } - Navigation.setParams({q: queryString}); + Navigation.setParams({q: queryString, rawQuery: undefined}); } function updateFilterQueryParams(values: Partial) { diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index 06f3ec508dce..591eba98b961 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -911,7 +911,11 @@ function Search({ if (hasErrors && (currentRoute === '/' || (shouldResetSearchQuery && currentRoute === '/search'))) { // Use requestAnimationFrame to safely update navigation params without overriding the current route requestAnimationFrame(() => { - Navigation.setParams({q: buildCannedSearchQuery()}); + // We want to explicitly clear stale rawQuery since it’s only used for manually typed-in queries. + Navigation.setParams({ + q: buildCannedSearchQuery(), + rawQuery: undefined, + }); }); if (shouldResetSearchQuery) { setShouldResetSearchQuery(false); @@ -1078,7 +1082,7 @@ function Search({ sortOrder: order, }); onSortPressedCallback?.(); - navigation.setParams({q: newQuery}); + navigation.setParams({q: newQuery, rawQuery: undefined}); }, [clearSelectedTransactions, queryJSON, onSortPressedCallback, navigation], ); diff --git a/src/components/Search/types.ts b/src/components/Search/types.ts index 2253ca881e8b..4c15f6153bd4 100644 --- a/src/components/Search/types.ts +++ b/src/components/Search/types.ts @@ -334,6 +334,15 @@ type QueryFilters = Array<{ filters: QueryFilter[]; }>; +type RawFilterKey = SyntaxFilterKey | ValueOf; + +type RawQueryFilter = { + key: RawFilterKey; + operator: ValueOf; + value: string | string[]; + isDefault?: boolean; +}; + type SearchQueryString = string; type SearchQueryAST = { @@ -345,6 +354,7 @@ type SearchQueryAST = { view: SearchView; filters: ASTNode; policyID?: string[]; + rawFilterList?: RawQueryFilter[]; columns?: SearchCustomColumnIds | SearchCustomColumnIds[]; limit?: number; }; @@ -357,6 +367,7 @@ type SearchQueryJSON = { /** Use similarSearchHash to test if two searchers are similar i.e. have same filters but not necessary same values */ similarSearchHash: number; flatFilters: QueryFilters; + isViewExplicitlySet?: boolean; } & SearchQueryAST; type SearchAutocompleteResult = { @@ -466,6 +477,7 @@ export type { QueryFilter, QueryFilters, SyntaxFilterKey, + RawQueryFilter, SearchFilterKey, UserFriendlyKey, SearchAutocompleteResult, diff --git a/src/libs/Navigation/types.ts b/src/libs/Navigation/types.ts index e93ef5c57752..4a4452b00f9f 100644 --- a/src/libs/Navigation/types.ts +++ b/src/libs/Navigation/types.ts @@ -3146,6 +3146,7 @@ type SearchReportActionsParamList = { type SearchFullscreenNavigatorParamList = { [SCREENS.SEARCH.ROOT]: { q: SearchQueryString; + rawQuery?: SearchQueryString; name?: string; groupBy?: string; }; diff --git a/src/libs/SearchParser/searchParser.js b/src/libs/SearchParser/searchParser.js index cc60ec42ad0a..1077a0e62310 100644 --- a/src/libs/SearchParser/searchParser.js +++ b/src/libs/SearchParser/searchParser.js @@ -435,6 +435,7 @@ function peg$parse(input, options) { const allFilters = [head, ...tail.map(([_, filter]) => filter)] .filter(Boolean) .filter((filter) => filter.right); + rawFilterList = allFilters.map(createRawFilter).filter(Boolean); const filtersWithoutDefaults = allFilters.filter((filter) => !filter.isDefault); @@ -4667,6 +4668,7 @@ function peg$parse(input, options) { sortOrder: "desc", view: "table", }; + let rawFilterList = []; let userProvidedSortBy = false; let userProvidedSortOrder = false; @@ -4691,6 +4693,7 @@ function peg$parse(input, options) { return { ...defaultValues, filters, + rawFilterList, }; } @@ -4756,6 +4759,26 @@ function peg$parse(input, options) { defaultValues[field] = value; } + function createRawFilter(filter) { + if (!filter || !filter.right) { + return null; + } + + if (typeof filter.left !== "string") { + return null; + } + + const key = filter.left; + const value = Array.isArray(filter.right) ? [...filter.right] : filter.right; + + return { + key, + operator: filter.operator, + value, + isDefault: !!filter.isDefault, + }; + } + let nameOperator = false; let expectingNestedQuote = false; diff --git a/src/libs/SearchParser/searchParser.peggy b/src/libs/SearchParser/searchParser.peggy index 9d7f9cd08182..568189d5b0f4 100644 --- a/src/libs/SearchParser/searchParser.peggy +++ b/src/libs/SearchParser/searchParser.peggy @@ -65,6 +65,7 @@ sortOrder: "desc", view: "table", }; + let rawFilterList = []; let userProvidedSortBy = false; let userProvidedSortOrder = false; @@ -89,6 +90,7 @@ return { ...defaultValues, filters, + rawFilterList, }; } @@ -153,6 +155,26 @@ defaultValues[field] = value; } + + function createRawFilter(filter) { + if (!filter || !filter.right) { + return null; + } + + if (typeof filter.left !== "string") { + return null; + } + + const key = filter.left; + const value = Array.isArray(filter.right) ? [...filter.right] : filter.right; + + return { + key, + operator: filter.operator, + value, + isDefault: !!filter.isDefault, + }; + } } query = _ filters:filterList? _ { return applyDefaults(filters); } @@ -162,6 +184,7 @@ filterList const allFilters = [head, ...tail.map(([_, filter]) => filter)] .filter(Boolean) .filter((filter) => filter.right); + rawFilterList = allFilters.map(createRawFilter).filter(Boolean); const filtersWithoutDefaults = allFilters.filter((filter) => !filter.isDefault); diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index ac8f861d92f5..b76f25428211 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -8,6 +8,7 @@ import type { ASTNode, QueryFilter, QueryFilters, + RawQueryFilter, ReportFieldDateKey, ReportFieldNegatedKey, ReportFieldTextKey, @@ -477,6 +478,14 @@ function wasViewExplicitlySet(queryJSON?: SearchQueryJSON | Readonly filter.key === CONST.SEARCH.SYNTAX_ROOT_KEYS.VIEW)) { + return true; + } + + if (queryJSON.isViewExplicitlySet) { + return true; + } + if (queryJSON.view !== getDefaultSearchQueryJSON()?.view) { return true; } @@ -573,16 +582,38 @@ function isFilterSupported(filter: SearchAdvancedFiltersKey, type: SearchDataTyp return false; } +/** + * Parses a given search query string into a structured `SearchQueryJSON` format. + * This format of query is most commonly shared between components and also sent to backend to retrieve search results. + * + * In a way this is the reverse of buildSearchQueryString() + */ +function getRawFilterListFromQuery(rawQuery: SearchQueryString) { + try { + const rawResult = parseSearchQuery(rawQuery) as SearchQueryJSON; + const sanitizedFilters = getSanitizedRawFilters(rawResult); + return sanitizedFilters; + } catch (error) { + Log.warn('[Search] Failed to parse raw query for raw filters', {error, rawQuery}); + } + + return undefined; +} + // Cache for buildSearchQueryJSON to avoid re-running the PEG parser for identical queries. // Cached values are shallow-frozen; callers needing to change fields must spread into a new object first. // This is a pure function called from 64+ sites — many fire during the same render cycle // with identical query strings, each running the full parser from scratch. const buildSearchQueryJSONCache = new Map | undefined>(); const BUILD_SEARCH_QUERY_JSON_CACHE_MAX_SIZE = 50; +const BUILD_SEARCH_QUERY_JSON_CACHE_KEY_SEPARATOR = '\x00'; // Null byte prevents collisions if query/rawQuery contain arbitrary strings + +function getBuildSearchQueryJSONCacheKey(query: SearchQueryString, rawQuery?: SearchQueryString) { + return rawQuery ? `${query}${BUILD_SEARCH_QUERY_JSON_CACHE_KEY_SEPARATOR}${rawQuery}` : query; +} -/** Parses {@link query} into JSON. Repeated calls share the same cached object identity for referential stability. */ -function buildSearchQueryJSON(query: SearchQueryString): Readonly | undefined { - const cacheKey = query; +function getCachedSearchQueryJSON(query: SearchQueryString, rawQuery?: SearchQueryString): Readonly | undefined { + const cacheKey = getBuildSearchQueryJSONCacheKey(query, rawQuery); if (buildSearchQueryJSONCache.has(cacheKey)) { return buildSearchQueryJSONCache.get(cacheKey); } @@ -590,10 +621,12 @@ function buildSearchQueryJSON(query: SearchQueryString): Readonly filter.key === CONST.SEARCH.SYNTAX_ROOT_KEYS.VIEW) ?? false; if (result.policyID && typeof result.policyID === 'string') { // Ensure policyID is always an array for consistency @@ -611,6 +644,11 @@ function buildSearchQueryJSON(query: SearchQueryString): Readonly= BUILD_SEARCH_QUERY_JSON_CACHE_MAX_SIZE) { const firstKey = buildSearchQueryJSONCache.keys().next().value; if (firstKey !== undefined) { @@ -626,6 +664,11 @@ function buildSearchQueryJSON(query: SearchQueryString): Readonly | undefined { + return getCachedSearchQueryJSON(query, rawQuery); +} + /** * Formats a given `SearchQueryJSON` object into the string version of query. * This format of query is the most basic string format and is used as the query param `q` in search URLs. @@ -672,6 +715,59 @@ function buildSearchQueryString(queryJSON?: SearchQueryJSON | Readonly((accumulator, rawFilter) => { + if (!rawFilter) { + return accumulator; + } + + if (rawFilter.isDefault) { + accumulator.push(rawFilter); + return accumulator; + } + + const rawValue = rawFilter.value; + const filterKey = rawFilter.key; + const isRecognizedFilterKey = Object.values(CONST.SEARCH.SYNTAX_FILTER_KEYS).includes(filterKey as SyntaxFilterKey); + let updatedValue: string | string[] = Array.isArray(rawValue) ? rawValue.map((value) => value?.toString() ?? '') : (rawValue?.toString() ?? ''); + + if (isRecognizedFilterKey) { + updatedValue = getUpdatedFilterValue(filterKey as SyntaxFilterKey, updatedValue); + } + + accumulator.push({ + ...rawFilter, + value: updatedValue, + }); + return accumulator; + }, []); + + const seenKeys = new Set(); + + for (let index = sanitizedFilters.length - 1; index >= 0; index -= 1) { + const filter = sanitizedFilters.at(index); + + if (!filter) { + continue; + } + + const filterKey = filter.key; + + if (seenKeys.has(filterKey) && filter.isDefault) { + sanitizedFilters.splice(index, 1); + continue; + } + + seenKeys.add(filterKey); + } + + return sanitizedFilters; +} + type BuildQueryStringOptions = { sortBy?: string; sortOrder?: string; @@ -1525,6 +1621,62 @@ type BuildUserReadableQueryStringParams = { reportAttributes: OnyxTypes.ReportAttributesDerivedValue['reports'] | undefined; }; +function formatDefaultRawFilterSegment(rawFilter: RawQueryFilter, policies: OnyxCollection, reports?: OnyxCollection) { + const rawValues = Array.isArray(rawFilter.value) ? rawFilter.value : [rawFilter.value]; + const cleanedValues = rawValues.map((val) => (typeof val === 'string' ? val.trim() : '')).filter((val) => val.length > 0); + + if (cleanedValues.length === 0) { + return; + } + + if (rawFilter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID) { + const workspaceValues = cleanedValues.map((id) => { + const policyName = getPolicyNameWithFallback(id, policies, reports); + return sanitizeSearchValue(policyName); + }); + + if (workspaceValues.length === 0) { + return; + } + + return `${getUserFriendlyKey(CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID)}:${workspaceValues.join(',')}`; + } + + if (rawFilter.key === CONST.SEARCH.SYNTAX_ROOT_KEYS.SORT_BY || rawFilter.key === CONST.SEARCH.SYNTAX_ROOT_KEYS.SORT_ORDER) { + return; + } + + let userFriendlyKey: UserFriendlyKey; + switch (rawFilter.key) { + case CONST.SEARCH.SYNTAX_ROOT_KEYS.TYPE: + userFriendlyKey = getUserFriendlyKey(CONST.SEARCH.SYNTAX_ROOT_KEYS.TYPE); + break; + case CONST.SEARCH.SYNTAX_ROOT_KEYS.STATUS: + userFriendlyKey = getUserFriendlyKey(CONST.SEARCH.SYNTAX_ROOT_KEYS.STATUS); + break; + case CONST.SEARCH.SYNTAX_ROOT_KEYS.GROUP_BY: + userFriendlyKey = getUserFriendlyKey(CONST.SEARCH.SYNTAX_ROOT_KEYS.GROUP_BY); + break; + case CONST.SEARCH.SYNTAX_ROOT_KEYS.COLUMNS: + userFriendlyKey = getUserFriendlyKey(CONST.SEARCH.SYNTAX_ROOT_KEYS.COLUMNS); + break; + case CONST.SEARCH.SYNTAX_ROOT_KEYS.LIMIT: + userFriendlyKey = getUserFriendlyKey(CONST.SEARCH.SYNTAX_ROOT_KEYS.LIMIT); + break; + default: + userFriendlyKey = getUserFriendlyKey(rawFilter.key as SearchFilterKey); + break; + } + + const formattedValues = cleanedValues.map((val) => sanitizeSearchValue(getUserFriendlyValue(val))); + + if (!formattedValues.length) { + return; + } + + return `${userFriendlyKey}:${formattedValues.join(',')}`; +} + function buildUserReadableQueryString({ queryJSON, PersonalDetails, @@ -1539,7 +1691,67 @@ function buildUserReadableQueryString({ feedKeysWithCards, reportAttributes, }: BuildUserReadableQueryStringParams) { - const {type, status, groupBy, view, columns, policyID, flatFilters: filters = [], limit} = queryJSON; + const {type, status, groupBy, view, columns, policyID, rawFilterList, flatFilters: filters = [], limit} = queryJSON; + + if (rawFilterList && rawFilterList.length > 0) { + const segments: string[] = []; + + for (const rawFilter of rawFilterList) { + if (!rawFilter) { + continue; + } + + if (rawFilter.isDefault) { + const defaultSegment = formatDefaultRawFilterSegment(rawFilter, policies, reports); + if (defaultSegment) { + segments.push(defaultSegment); + } + continue; + } + + const rawValues = Array.isArray(rawFilter.value) ? rawFilter.value : [rawFilter.value]; + const queryFilters = rawValues + .map((val) => (val ?? '').toString()) + .filter((val) => val.length > 0) + .map((val) => ({ + operator: rawFilter.operator, + value: val, + })); + + if (!queryFilters.length) { + continue; + } + + const displayQueryFilters = getDisplayQueryFiltersForKey( + rawFilter.key, + queryFilters, + PersonalDetails, + reports, + taxRates, + cardList, + cardFeeds, + policies, + currentUserAccountID, + translate, + reportAttributes, + feedKeysWithCards, + ); + + if (!displayQueryFilters.length) { + continue; + } + + const segment = buildFilterValuesString(getUserFriendlyKey(rawFilter.key as SearchFilterKey), displayQueryFilters).trim(); + + if (segment) { + segments.push(segment); + } + } + + if (segments.length > 0) { + return segments.join(' '); + } + } let title = status ? `type:${getUserFriendlyValue(type)} status:${Array.isArray(status) ? status.map(getUserFriendlyValue).join(',') : getUserFriendlyValue(status)}` @@ -1704,6 +1916,13 @@ function getQueryWithUpdatedValues(query: string, shouldSkipAmountConversion = f const computeNodeValue = (left: SyntaxFilterKey, right: string | string[]) => getUpdatedFilterValue(left, right, shouldSkipAmountConversion); const standardizedQuery = traverseAndUpdatedQuery(queryJSON, computeNodeValue); + const rawFilterList = getRawFilterListFromQuery(query); + const hasInFilter = rawFilterList?.some((filter) => !filter.isDefault && filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.IN) ?? false; + const hasExplicitType = rawFilterList?.some((filter) => filter.key === CONST.SEARCH.SYNTAX_ROOT_KEYS.TYPE) ?? false; + + if (hasInFilter && !hasExplicitType) { + standardizedQuery.type = CONST.SEARCH.DATA_TYPES.CHAT; + } return buildSearchQueryString(standardizedQuery); } @@ -1729,8 +1948,8 @@ function getCurrentSearchQueryJSON() { return; } - const {q: searchParams} = lastSearchRoute.params as SearchFullscreenNavigatorParamList[typeof SCREENS.SEARCH.ROOT]; - const queryJSON = buildSearchQueryJSON(searchParams); + const {q: searchParams, rawQuery} = lastSearchRoute.params as SearchFullscreenNavigatorParamList[typeof SCREENS.SEARCH.ROOT]; + const queryJSON = buildSearchQueryJSON(searchParams, rawQuery); if (!queryJSON) { return; } @@ -1981,9 +2200,17 @@ function getDateModifierTitle(modifier: ValueOf(queryData: T): string { +function serializeQueryJSONForBackend(queryData: T): string { const normalizedFilters = queryData.filters ? applyContainsOperatorToTextFields(queryData.filters) : queryData.filters; - return JSON.stringify({...queryData, filters: normalizedFilters}); + const normalizedRawFilterList = queryData.rawFilterList + ? queryData.rawFilterList.map((filter) => { + if (TEXT_SEARCH_FIELDS.has(filter.key) && filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO) { + return {...filter, operator: CONST.SEARCH.SYNTAX_OPERATORS.CONTAINS}; + } + return filter; + }) + : queryData.rawFilterList; + return JSON.stringify({...queryData, filters: normalizedFilters, rawFilterList: normalizedRawFilterList}); } export { diff --git a/src/libs/actions/Search.ts b/src/libs/actions/Search.ts index 71a3721db735..42f554d962b2 100644 --- a/src/libs/actions/Search.ts +++ b/src/libs/actions/Search.ts @@ -1183,6 +1183,7 @@ function rejectMoneyRequestsOnSearch( const searchParams = lastRoute.params as SearchFullscreenNavigatorParamList[typeof SCREENS.SEARCH.ROOT]; urlToNavigateBack = ROUTES.SEARCH_ROOT.getRoute({ query: searchParams.q, + ...(searchParams?.rawQuery && {rawQuery: searchParams.rawQuery}), ...(searchParams?.name && {name: searchParams.name}), }); } else { @@ -1387,6 +1388,13 @@ function updateAdvancedFilters(values: Nullable { + setSearchContext(false); Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query: item?.query ?? '', name: item?.name})); }, rightComponent: ( diff --git a/src/pages/Search/SearchAdvancedFiltersProvider.tsx b/src/pages/Search/SearchAdvancedFiltersProvider.tsx index 7c62709b569b..66e6481d7742 100644 --- a/src/pages/Search/SearchAdvancedFiltersProvider.tsx +++ b/src/pages/Search/SearchAdvancedFiltersProvider.tsx @@ -2,6 +2,7 @@ import React, {useState} from 'react'; import useUpdateFilterQuery from '@components/Search/hooks/useUpdateFilterQuery'; import {useSearchQueryContext} from '@components/Search/SearchContext'; import useOnyx from '@hooks/useOnyx'; +import {setSearchContext} from '@libs/actions/Search'; import Navigation from '@libs/Navigation/Navigation'; import {getAdvancedFiltersToReset} from '@libs/SearchQueryUtils'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -44,14 +45,26 @@ function SearchAdvancedFiltersProvider({children}: SearchAdvancedFiltersProvider const advancedFiltersToReset = searchAdvancedFiltersForm ? getAdvancedFiltersToReset(searchAdvancedFiltersForm) : undefined; const applyFilters = () => { - Navigation.dismissModal({afterTransition: () => setFilterQueryParams(values)}); + Navigation.dismissModal({ + afterTransition: () => { + setFilterQueryParams(values); + if (values.keyword) { + setSearchContext(true); + } + }, + }); }; const resetFilters = () => { if (!advancedFiltersToReset) { return; } - Navigation.dismissModal({afterTransition: () => setFilterQueryParams(advancedFiltersToReset)}); + Navigation.dismissModal({ + afterTransition: () => { + setFilterQueryParams(advancedFiltersToReset); + setSearchContext(false); + }, + }); }; const setDraftFilters = (newValues: Partial) => { diff --git a/src/pages/Search/SearchTypeMenuNarrow.tsx b/src/pages/Search/SearchTypeMenuNarrow.tsx index 11c1e2af55ba..f9cb8f7b0173 100644 --- a/src/pages/Search/SearchTypeMenuNarrow.tsx +++ b/src/pages/Search/SearchTypeMenuNarrow.tsx @@ -22,6 +22,7 @@ import useReportAttributes from '@hooks/useReportAttributes'; import useSearchTypeMenuSections from '@hooks/useSearchTypeMenuSections'; import useShareSavedSearch, {MENU_CLOSE_DELAY_MS} from '@hooks/useShareSavedSearch'; import useThemeStyles from '@hooks/useThemeStyles'; +import {setSearchContext} from '@libs/actions/Search'; import {mergeCardListWithWorkspaceFeeds} from '@libs/CardUtils'; import {getAllTaxRates} from '@libs/PolicyUtils'; import {getItemBadgeText, getOverflowMenu} from '@libs/SearchUIUtils'; @@ -209,6 +210,7 @@ function SearchTypeMenuNarrow({queryJSON, onTabPress}: SearchTypeMenuNarrowProps return; } onTabPress?.(); + setSearchContext(false); }; const handleTabPress = (tabKey: string) => { @@ -217,10 +219,11 @@ function SearchTypeMenuNarrow({queryJSON, onTabPress}: SearchTypeMenuNarrowProps return; } onTabPress?.(); + setSearchContext(false); navigation.dispatch({ type: CONST.NAVIGATION.ACTION_TYPE.PUSH_PARAMS, payload: { - params: {q: searchData.query, name: searchData.name}, + params: {q: searchData.query, name: searchData.name, rawQuery: undefined}, }, }); }; diff --git a/src/pages/Search/SearchTypeMenuWide.tsx b/src/pages/Search/SearchTypeMenuWide.tsx index a1e8e39e2cc4..4d004ae6a485 100644 --- a/src/pages/Search/SearchTypeMenuWide.tsx +++ b/src/pages/Search/SearchTypeMenuWide.tsx @@ -15,6 +15,7 @@ import useOnyx from '@hooks/useOnyx'; import useSearchTypeMenuSections from '@hooks/useSearchTypeMenuSections'; import useSingleExecution from '@hooks/useSingleExecution'; import useThemeStyles from '@hooks/useThemeStyles'; +import {setSearchContext} from '@libs/actions/Search'; import Navigation from '@libs/Navigation/Navigation'; import {getItemBadgeText, getSectionBadgeText} from '@libs/SearchUIUtils'; import type {SearchTypeMenuSection} from '@libs/SearchUIUtils'; @@ -144,6 +145,7 @@ function SearchTypeMenuWide({queryJSON}: SearchTypeMenuProps) { const handleTypeMenuItemPress = singleExecution((searchQuery: string) => { clearSelectedTransactions(); + setSearchContext(false); Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query: searchQuery})); }); diff --git a/src/pages/settings/Subscription/CardSection/CardSection.tsx b/src/pages/settings/Subscription/CardSection/CardSection.tsx index 71e79fb26fec..07c0d6fdb437 100644 --- a/src/pages/settings/Subscription/CardSection/CardSection.tsx +++ b/src/pages/settings/Subscription/CardSection/CardSection.tsx @@ -113,7 +113,7 @@ function CardSection() { ], }); - Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query})); + Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query, rawQuery: query})); }; const [billingStatus, setBillingStatus] = useState(() => diff --git a/src/types/onyx/SearchContext.ts b/src/types/onyx/SearchContext.ts new file mode 100644 index 000000000000..5e815cd957a6 --- /dev/null +++ b/src/types/onyx/SearchContext.ts @@ -0,0 +1,7 @@ +/** Model of the search context */ +type SearchContext = { + /** Whether to show the search query in the input field */ + shouldShowSearchQuery: boolean; +}; + +export default SearchContext; diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index 72a2ada5b1d4..356baf17b08a 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -160,6 +160,7 @@ import type {SavedCSVColumnLayoutData, SavedCSVColumnLayoutList} from './SavedCS import type {SaveSearch} from './SaveSearch'; import type ScheduleCallDraft from './ScheduleCallDraft'; import type ScreenShareRequest from './ScreenShareRequest'; +import type SearchContext from './SearchContext'; import type SearchResults from './SearchResults'; import type SearchSidebar from './SearchSidebar'; import type SecurityGroup from './SecurityGroup'; @@ -355,6 +356,7 @@ export type { InvitedEmailsToAccountIDs, NewGroupChatDraft, PolicyJoinMember, + SearchContext, SearchResults, ReviewDuplicates, PrivateSubscription, diff --git a/tests/actions/IOU/SearchUpdateTest.ts b/tests/actions/IOU/SearchUpdateTest.ts index e0b56e138f7c..99a1216878e9 100644 --- a/tests/actions/IOU/SearchUpdateTest.ts +++ b/tests/actions/IOU/SearchUpdateTest.ts @@ -307,6 +307,14 @@ describe('actions/IOU', () => { hash: 591785022, recentSearchHash: 714245044, similarSearchHash: 1023624110, + rawFilterList: [ + { + key: 'policyID', + operator: 'eq', + value: policyID, + isDefault: true, + }, + ], } as unknown as SearchQueryJSON; // When the IOU report has a matching policyID, it should return true diff --git a/tests/unit/NavigationFocusReturnTest.ts b/tests/unit/NavigationFocusReturnTest.ts index 977752222d22..29f2a1f08d5e 100644 --- a/tests/unit/NavigationFocusReturnTest.ts +++ b/tests/unit/NavigationFocusReturnTest.ts @@ -1627,6 +1627,14 @@ describe('compoundParamsKey', () => { expect(compoundParamsKey('search-x', {q: 'foo'})).not.toBe('search-x'); }); + it('should treat explicit-undefined fields as omitted (path rehydration parity)', () => { + expect(compoundParamsKey('search-x', {q: 'foo', rawQuery: undefined})).toBe(compoundParamsKey('search-x', {q: 'foo'})); + }); + + it('should distinguish explicit null from absent (null is a real value)', () => { + expect(compoundParamsKey('search-x', {q: 'foo', rawQuery: null})).not.toBe(compoundParamsKey('search-x', {q: 'foo'})); + }); + it('should distinguish array [undefined] from array [null] (JSON.stringify would otherwise collapse both to "null")', () => { expect(compoundParamsKey('search-x', {ids: [undefined]})).not.toBe(compoundParamsKey('search-x', {ids: [null]})); }); diff --git a/tests/unit/Search/SearchListRenderCountTest.tsx b/tests/unit/Search/SearchListRenderCountTest.tsx index a5a0d5dac185..40bbb1a49344 100644 --- a/tests/unit/Search/SearchListRenderCountTest.tsx +++ b/tests/unit/Search/SearchListRenderCountTest.tsx @@ -118,6 +118,7 @@ const STABLE_QUERY_JSON: SearchQueryJSON = { policyID: undefined, columns: undefined, limit: undefined, + rawFilterList: undefined, }; const STABLE_COLUMNS: SearchColumnType[] = [CONST.SEARCH.TABLE_COLUMNS.DATE, CONST.SEARCH.TABLE_COLUMNS.MERCHANT, CONST.SEARCH.TABLE_COLUMNS.TOTAL_AMOUNT, CONST.SEARCH.TABLE_COLUMNS.ACTION]; diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index 664a15cbdb98..e524c305574a 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -180,6 +180,13 @@ describe('SearchQueryUtils', () => { const result = getQueryWithUpdatedValues(userQuery); expect(result).toEqual(`${defaultQuery} action:submit from:me`); + + const queryJSON = buildSearchQueryJSON(result ?? '', userQuery); + expect(queryJSON?.rawFilterList).toEqual([ + {key: CONST.SEARCH.SYNTAX_FILTER_KEYS.ACTION, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'submit', isDefault: false}, + {key: CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'me', isDefault: false}, + {key: CONST.SEARCH.SYNTAX_FILTER_KEYS.TYPE, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: CONST.SEARCH.DATA_TYPES.EXPENSE, isDefault: true}, + ]); }); }); @@ -677,7 +684,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to standardize query string'); } - const queryJSON = buildSearchQueryJSON(canonicalQueryString); + const queryJSON = buildSearchQueryJSON(canonicalQueryString, queryString); if (!queryJSON) { throw new Error('Failed to parse query string'); @@ -708,7 +715,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to standardize query string'); } - const queryJSON = buildSearchQueryJSON(canonicalQueryString); + const queryJSON = buildSearchQueryJSON(canonicalQueryString, queryString); if (!queryJSON) { throw new Error('Failed to parse query string'); @@ -739,7 +746,7 @@ describe('SearchQueryUtils', () => { throw new Error('Failed to standardize query string'); } - const queryJSON = buildSearchQueryJSON(canonicalQueryString); + const queryJSON = buildSearchQueryJSON(canonicalQueryString, queryString); const policies: OnyxCollection = { [`${ONYXKEYS.COLLECTION.POLICY}123`]: { name: 'Team Space', @@ -767,6 +774,21 @@ describe('SearchQueryUtils', () => { expect(result).toBe('type:expense workspace:"Team Space" merchant:Starbucks'); }); + test('rawQuery overrides canonical filter values when provided', () => { + const queryString = 'type:expense merchant:Uber'; + const canonicalQueryString = getQueryWithUpdatedValues(queryString); + + if (!canonicalQueryString) { + throw new Error('Failed to standardize query string'); + } + + const overriddenRawQuery = 'type:expense merchant:Lyft'; + const queryJSON = buildSearchQueryJSON(canonicalQueryString, overriddenRawQuery); + const merchantFilter = queryJSON?.rawFilterList?.find((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.MERCHANT); + + expect(merchantFilter?.value).toBe('Lyft'); + }); + test('includes limit in readable query string when present', () => { const queryJSON = buildSearchQueryJSON('type:expense limit:25'); @@ -1957,6 +1979,22 @@ describe('SearchQueryUtils', () => { }); describe('buildSearchQueryString', () => { + test('includes view when explicitly set in rawFilterList', () => { + const queryJSON = buildSearchQueryJSON('type:expense view:line', 'type:expense view:line'); + + const result = buildSearchQueryString(queryJSON); + + expect(result).toContain('view:line'); + }); + + test('includes view when differs from default even without rawFilterList', () => { + const queryJSON = buildSearchQueryJSON('type:expense view:pie'); + + const result = buildSearchQueryString(queryJSON); + + expect(result).toContain('view:pie'); + }); + test('includes view when set to bar', () => { const queryJSON = buildSearchQueryJSON('type:expense view:bar'); @@ -1973,6 +2011,14 @@ describe('SearchQueryUtils', () => { expect(result).not.toContain('view:table'); }); + test('includes view when explicitly set to table in rawFilterList', () => { + const queryJSON = buildSearchQueryJSON('type:expense groupBy:category view:table', 'type:expense groupBy:category view:table'); + + const result = buildSearchQueryString(queryJSON); + + expect(result).toContain('view:table'); + }); + test('preserves view along with other filters', () => { const queryJSON = buildSearchQueryJSON('type:expense view:line category:travel'); @@ -1982,6 +2028,15 @@ describe('SearchQueryUtils', () => { expect(result).toContain('category:travel'); }); + test('handles view with rawFilterList containing other filters', () => { + const queryJSON = buildSearchQueryJSON('type:expense view:pie merchant:Amazon', 'type:expense view:pie merchant:Amazon'); + + const result = buildSearchQueryString(queryJSON); + + expect(result).toContain('view:pie'); + expect(result).toContain('merchant:Amazon'); + }); + test('wraps keyword values in quotes so they are not re-interpreted as filter syntax', () => { // A quoted keyword that looks like the `type` filter should round-trip back as a quoted keyword const queryJSON = buildSearchQueryJSON('type:expense "type:expense"'); @@ -2308,6 +2363,17 @@ describe('SearchQueryUtils', () => { expect(Object.isFrozen(first)).toBe(true); }); + test('returns independent results for the same query with different rawQuery values', () => { + const query = 'type:expense'; + const rawQueryA = 'type:expense status:drafts'; + const rawQueryB = 'type:expense status:paid'; + + const resultA = buildSearchQueryJSON(query, rawQueryA); + const resultB = buildSearchQueryJSON(query, rawQueryB); + + expect(resultA?.rawFilterList).not.toEqual(resultB?.rawFilterList); + }); + test('does not cache a failed parse result so subsequent calls retry the parser', () => { // Force the parser to throw on the first call only, then succeed on the second. // Verifies that a failed parse is not stored in the cache. @@ -2973,6 +3039,18 @@ describe('SearchQueryUtils', () => { } expect(merchantNode.operator).toBe(CONST.SEARCH.SYNTAX_OPERATORS.CONTAINS); }); + + it('should apply contains to merchant in rawFilterList', () => { + const rawFilterList = [{key: CONST.SEARCH.SYNTAX_FILTER_KEYS.MERCHANT, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'coffee'}]; + const serialized = JSON.parse(serializeQueryJSONForBackend({filters: undefined, rawFilterList})) as {rawFilterList: typeof rawFilterList}; + expect(serialized.rawFilterList.at(0)?.operator).toBe(CONST.SEARCH.SYNTAX_OPERATORS.CONTAINS); + }); + + it('should not affect non-text fields in rawFilterList', () => { + const rawFilterList = [{key: CONST.SEARCH.SYNTAX_FILTER_KEYS.CATEGORY, operator: CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO, value: 'food'}]; + const serialized = JSON.parse(serializeQueryJSONForBackend({filters: undefined, rawFilterList})) as {rawFilterList: typeof rawFilterList}; + expect(serialized.rawFilterList.at(0)?.operator).toBe(CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO); + }); }); describe('getKeywordQueryWithCurrentSearchContext', () => { diff --git a/tests/unit/Search/yourSpendQueryBuildersTest.ts b/tests/unit/Search/yourSpendQueryBuildersTest.ts index 17cfc5942c29..95aa2289af50 100644 --- a/tests/unit/Search/yourSpendQueryBuildersTest.ts +++ b/tests/unit/Search/yourSpendQueryBuildersTest.ts @@ -17,6 +17,9 @@ const CARD_ID = 67890; /** * Returns the parsed filter entries for a given key from a query string. + * Uses `flatFilters` (the standard parsed-filter representation across the app) + * so the helper does not depend on `rawFilterList`, which is internal to + * SearchQueryUtils and only kept when both `query` and `rawQuery` are supplied. */ function getRawFiltersForKey(inputQuery: string, key: string): Array<{operator: string; value: string | string[]}> { const queryJSON = buildSearchQueryJSON(inputQuery); diff --git a/tests/unit/SearchParserTest.ts b/tests/unit/SearchParserTest.ts index 7008dc83c311..16f655f5a621 100644 --- a/tests/unit/SearchParserTest.ts +++ b/tests/unit/SearchParserTest.ts @@ -1376,28 +1376,28 @@ const limitTests = [ describe('search parser', () => { test.each(tests)(`parsing: $query`, ({query, expected}) => { - const result = parse(query) as SearchQueryJSON; - expect(result).toEqual(expected); + const {rawFilterList, ...resultWithoutRawFilters} = parse(query) as SearchQueryJSON; + expect(resultWithoutRawFilters).toEqual(expected); }); }); describe('Testing search parser with special characters and wrapped in quotes.', () => { test.each(keywordTests)(`parsing: $query`, ({query, expected}) => { - const result = parse(query) as SearchQueryJSON; - expect(result).toEqual(expected); + const {rawFilterList, ...resultWithoutRawFilters} = parse(query) as SearchQueryJSON; + expect(resultWithoutRawFilters).toEqual(expected); }); }); describe('search parser - view and groupBy defaults', () => { test.each(viewAndGroupByTests)(`parsing: $query`, ({query, expected}) => { - const result = parse(query) as SearchQueryJSON; - expect(result).toEqual(expected); + const {rawFilterList, ...resultWithoutRawFilters} = parse(query) as SearchQueryJSON; + expect(resultWithoutRawFilters).toEqual(expected); }); }); describe('search parser - limit filter', () => { test.each(limitTests)('$description: $query', ({query, expected}) => { - const result = parse(query) as SearchQueryJSON; - expect(result).toEqual(expected); + const {rawFilterList, ...resultWithoutRawFilters} = parse(query) as SearchQueryJSON; + expect(resultWithoutRawFilters).toEqual(expected); }); }); From e709e9b87c8e0021cb833ddc6b23923627ef65d9 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Fri, 19 Jun 2026 12:18:24 +0800 Subject: [PATCH 22/36] change the position --- src/libs/SearchQueryUtils.ts | 42 ++++++++++++++++++------------------ src/types/onyx/index.ts | 2 +- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index b76f25428211..55518178a2bc 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -1600,27 +1600,6 @@ function getDisplayQueryFiltersForKey( })); } -/** - * Formats a given `SearchQueryJSON` object into the human-readable string version of query. - * This format of query is the one which we want to display to users. - * We try to replace every numeric id value with a display version of this value, - * So: user IDs get turned into emails, report ids into report names etc. - */ -type BuildUserReadableQueryStringParams = { - queryJSON: SearchQueryJSON; - PersonalDetails: OnyxTypes.PersonalDetailsList | undefined; - reports: OnyxCollection; - taxRates: Record; - cardList: OnyxTypes.CardList | undefined; - cardFeeds: OnyxCollection; - policies: OnyxCollection; - currentUserAccountID: number; - autoCompleteWithSpace: boolean; - translate: LocalizedTranslate; - feedKeysWithCards?: FeedKeysWithAssignedCards; - reportAttributes: OnyxTypes.ReportAttributesDerivedValue['reports'] | undefined; -}; - function formatDefaultRawFilterSegment(rawFilter: RawQueryFilter, policies: OnyxCollection, reports?: OnyxCollection) { const rawValues = Array.isArray(rawFilter.value) ? rawFilter.value : [rawFilter.value]; const cleanedValues = rawValues.map((val) => (typeof val === 'string' ? val.trim() : '')).filter((val) => val.length > 0); @@ -1677,6 +1656,27 @@ function formatDefaultRawFilterSegment(rawFilter: RawQueryFilter, policies: Onyx return `${userFriendlyKey}:${formattedValues.join(',')}`; } +/** + * Formats a given `SearchQueryJSON` object into the human-readable string version of query. + * This format of query is the one which we want to display to users. + * We try to replace every numeric id value with a display version of this value, + * So: user IDs get turned into emails, report ids into report names etc. + */ +type BuildUserReadableQueryStringParams = { + queryJSON: SearchQueryJSON; + PersonalDetails: OnyxTypes.PersonalDetailsList | undefined; + reports: OnyxCollection; + taxRates: Record; + cardList: OnyxTypes.CardList | undefined; + cardFeeds: OnyxCollection; + policies: OnyxCollection; + currentUserAccountID: number; + autoCompleteWithSpace: boolean; + translate: LocalizedTranslate; + feedKeysWithCards?: FeedKeysWithAssignedCards; + reportAttributes: OnyxTypes.ReportAttributesDerivedValue['reports'] | undefined; +}; + function buildUserReadableQueryString({ queryJSON, PersonalDetails, diff --git a/src/types/onyx/index.ts b/src/types/onyx/index.ts index 356baf17b08a..7b7f1f11f6dc 100644 --- a/src/types/onyx/index.ts +++ b/src/types/onyx/index.ts @@ -356,7 +356,6 @@ export type { InvitedEmailsToAccountIDs, NewGroupChatDraft, PolicyJoinMember, - SearchContext, SearchResults, ReviewDuplicates, PrivateSubscription, @@ -373,6 +372,7 @@ export type { DomainSettings, SaveSearch, RecentSearchItem, + SearchContext, SearchSidebar, ImportedSpreadsheet, BankAccountShareDetails, From b92c4742963d1cd9534012f08183bd5184dc8aa1 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Fri, 19 Jun 2026 13:07:56 +0800 Subject: [PATCH 23/36] show the current query on the search router --- .../Search/SearchRouter/SearchButton.tsx | 3 +- .../Search/SearchRouter/SearchRouter.tsx | 32 +++++++----- .../SearchRouter/SearchRouterContext.tsx | 15 +++--- .../Search/SearchRouter/SearchRouterUtils.ts | 10 ++-- tests/unit/SearchRouterUtilsTest.ts | 52 ------------------- 5 files changed, 34 insertions(+), 78 deletions(-) diff --git a/src/components/Search/SearchRouter/SearchButton.tsx b/src/components/Search/SearchRouter/SearchButton.tsx index dc1e92a48c74..f79beb917c32 100644 --- a/src/components/Search/SearchRouter/SearchButton.tsx +++ b/src/components/Search/SearchRouter/SearchButton.tsx @@ -7,6 +7,7 @@ import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; +import isSearchTopmostFullScreenRoute from '@libs/Navigation/helpers/isSearchTopmostFullScreenRoute'; import {startSpan} from '@libs/telemetry/activeSpans'; import {callFunctionIfActionIsAllowed} from '@userActions/Session'; import CONST from '@src/CONST'; @@ -40,7 +41,7 @@ function SearchButton({style, shouldUseAutoHitSlop = false}: SearchButtonProps) startSearchPageVisibleSpan(); - openSearchRouter(); + openSearchRouter(undefined, isSearchTopmostFullScreenRoute()); })(); }; diff --git a/src/components/Search/SearchRouter/SearchRouter.tsx b/src/components/Search/SearchRouter/SearchRouter.tsx index e538aaaf9469..bbbe9d82df43 100644 --- a/src/components/Search/SearchRouter/SearchRouter.tsx +++ b/src/components/Search/SearchRouter/SearchRouter.tsx @@ -44,6 +44,7 @@ import StringUtils from '@libs/StringUtils'; import Navigation from '@navigation/Navigation'; import variables from '@styles/variables'; import {navigateToAndOpenReport, searchInServer} from '@userActions/Report'; +import {setSearchContext} from '@userActions/Search'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import ROUTES from '@src/ROUTES'; @@ -52,7 +53,7 @@ import {buildSubstitutionsMap} from './buildSubstitutionsMap'; import type {SubstitutionMap} from './getQueryWithSubstitutions'; import {getQueryWithSubstitutions} from './getQueryWithSubstitutions'; import {getUpdatedSubstitutionsMap} from './getUpdatedSubstitutionsMap'; -import {clearPendingRouterQuery, peekPendingRouterQuery} from './SearchRouterContext'; +import {clearPendingRouterState, peekPendingRouterState} from './SearchRouterContext'; import {getContextualReportData, getContextualSearchAutocompleteKey, getContextualSearchQuery} from './SearchRouterUtils'; import updateAutocompleteSubstitutionsForSelection from './updateAutocompleteSubstitutionsForSelection'; import useAskConcierge from './useAskConcierge'; @@ -77,6 +78,7 @@ function SearchRouter({onRouterClose, shouldHideInputCaret, isSearchRouterDispla const [betas] = useOnyx(ONYXKEYS.BETAS); const [isSelfTourViewed] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {selector: hasSeenTourSelector}); const [isTrackIntentUser] = useOnyx(ONYXKEYS.NVP_INTRO_SELECTED, {selector: isTrackIntentUserSelector}); + const [searchContext] = useOnyx(ONYXKEYS.SEARCH_CONTEXT); const personalDetails = usePersonalDetails(); const sortedActions = useSortedActions(); const {shouldUseNarrowLayout} = useResponsiveLayout(); @@ -84,7 +86,7 @@ function SearchRouter({onRouterClose, shouldHideInputCaret, isSearchRouterDispla const expensifyIcons = useMemoizedLazyExpensifyIcons(['MagnifyingGlass', 'ConciergeAvatar']); const {askConcierge, shouldShowAskConcierge} = useAskConcierge(); - const {contextualReportID, isSearchRouterScreen, isOnSearchPage} = useRootNavigationState(getContextualReportData); + const {query: pendingInitialQuery, isFromSearchPageSearchButton} = peekPendingRouterState(); const {currentSearchQueryJSON} = useSearchQueryContext(); const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY); @@ -93,14 +95,15 @@ function SearchRouter({onRouterClose, shouldHideInputCaret, isSearchRouterDispla const feedKeysWithCards = useFeedKeysWithAssignedCards(); const reportAttributes = useReportAttributes(); - // Seed the input on open. When the SearchRouter is opened while on the search page, we build a - // user-readable query string from the current search query (showing names instead of IDs) along - // with the substitutions map needed to map those names back to IDs when submitting. - // Otherwise we fall back to the explicit pending query (e.g. from ExpenseReportSearchHandler). - // Computed once via a lazy initializer so the query string and its substitutions stay consistent. + // Seed the input on open. When the SearchRouter is opened from the search button on the search page + // and `shouldShowSearchQuery` is true, we build a user-readable query string from the current search + // query (showing names instead of IDs) along with the substitutions map needed to map those names + // back to IDs when submitting. Otherwise we fall back to the explicit pending query (e.g. from + // ExpenseReportSearchHandler). Computed once via a lazy initializer so the query string and its + // substitutions stay consistent. const [[initialQuery, initialSubstitutions]] = useState<[string, SubstitutionMap]>(() => { - if (!isOnSearchPage || !currentSearchQueryJSON) { - return [peekPendingRouterQuery(), {}]; + if (!currentSearchQueryJSON || !isFromSearchPageSearchButton || !searchContext?.shouldShowSearchQuery) { + return [pendingInitialQuery, {}]; } const taxRates = getAllTaxRates(policies); @@ -140,11 +143,13 @@ function SearchRouter({onRouterClose, shouldHideInputCaret, isSearchRouterDispla const [selection, setSelection] = useState({start: initialQuery.length, end: initialQuery.length}); useEffect(() => { - clearPendingRouterQuery(); + clearPendingRouterState(); }, []); const [autocompleteSubstitutions, setAutocompleteSubstitutions] = useState(initialSubstitutions); const textInputRef = useRef(null); + const {contextualReportID, isSearchRouterScreen} = useRootNavigationState(getContextualReportData); + const contextualReport = useReportOrReportDraft(contextualReportID); const [contextualReportNVP] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${contextualReportID}`, { selector: privateIsArchivedSelector, @@ -340,13 +345,16 @@ function SearchRouter({onRouterClose, shouldHideInputCaret, isSearchRouterDispla backHistory(() => { onRouterClose(); - Navigation.navigate(ROUTES.SEARCH_ROOT.getRoute({query: updatedQuery})); + setSearchContext(true); + Navigation.navigate( + ROUTES.SEARCH_ROOT.getRoute({query: updatedQuery, rawQuery: shouldSkipAmountConversion || !isFromSearchPageSearchButton ? undefined : queryWithSubstitutions}), + ); }); setTextInputValue(''); setAutocompleteQueryValue(''); }, - [autocompleteSubstitutions, currentUserAccountID, onRouterClose, setTextInputValue, setShouldResetSearchQuery], + [autocompleteSubstitutions, currentUserAccountID, onRouterClose, setTextInputValue, setShouldResetSearchQuery, isFromSearchPageSearchButton], ); const onListItemPress = useCallback( diff --git a/src/components/Search/SearchRouter/SearchRouterContext.tsx b/src/components/Search/SearchRouter/SearchRouterContext.tsx index a9ca74e21090..0454ef1fc6dd 100644 --- a/src/components/Search/SearchRouter/SearchRouterContext.tsx +++ b/src/components/Search/SearchRouter/SearchRouterContext.tsx @@ -8,23 +8,25 @@ import {closeSearch, openSearch} from './toggleSearch'; // Module-level pending query used to seed the SearchRouter input on open. // Set before opening, peeked during SearchRouter render, cleared on mount. let pendingRouterQuery = ''; +let pendingIsFromSearchPageSearchButton = false; -function peekPendingRouterQuery(): string { - return pendingRouterQuery; +function peekPendingRouterState() { + return {query: pendingRouterQuery, isFromSearchPageSearchButton: pendingIsFromSearchPageSearchButton}; } -function clearPendingRouterQuery() { +function clearPendingRouterState() { pendingRouterQuery = ''; + pendingIsFromSearchPageSearchButton = false; } -export {peekPendingRouterQuery, clearPendingRouterQuery}; +export {peekPendingRouterState, clearPendingRouterState}; type SearchRouterStateContextType = { isSearchRouterDisplayed: boolean; }; type SearchRouterActionsContextType = { - openSearchRouter: (query?: string) => void; + openSearchRouter: (query?: string, isFromSearchPage?: boolean) => void; closeSearchRouter: () => void; toggleSearch: () => void; }; @@ -85,8 +87,9 @@ function SearchRouterContextProvider({children}: ChildrenProps) { }); }; - const openSearchRouter = (query?: string) => { + const openSearchRouter = (query?: string, isFromSearchPageSearchButton?: boolean) => { pendingRouterQuery = query ?? ''; + pendingIsFromSearchPageSearchButton = isFromSearchPageSearchButton ?? false; if (isBrowserWithHistory) { window.history.pushState({isSearchModalOpen: true} satisfies HistoryState, ''); } diff --git a/src/components/Search/SearchRouter/SearchRouterUtils.ts b/src/components/Search/SearchRouter/SearchRouterUtils.ts index 482a1397c8e6..6d0a857e6498 100644 --- a/src/components/Search/SearchRouter/SearchRouterUtils.ts +++ b/src/components/Search/SearchRouter/SearchRouterUtils.ts @@ -11,7 +11,6 @@ import type * as OnyxTypes from '@src/types/onyx'; type ContextualReportData = { contextualReportID: string | undefined; isSearchRouterScreen: boolean; - isOnSearchPage: boolean; }; /** @@ -32,7 +31,7 @@ type ContextualReportData = { function getContextualReportData(state: NavigationState | undefined): ContextualReportData { // Safe handling when navigation is not yet initialized if (!state) { - return {contextualReportID: undefined, isSearchRouterScreen: false, isOnSearchPage: false}; + return {contextualReportID: undefined, isSearchRouterScreen: false}; } let maybeReportRoute = findFocusedRoute(state); const isSearchRouterScreen = maybeReportRoute?.name === SCREENS.SEARCH_ROUTER.ROOT; @@ -47,12 +46,9 @@ function getContextualReportData(state: NavigationState | undefined): Contextual if (maybeReportRoute?.name === SCREENS.REPORT || maybeReportRoute?.name === SCREENS.RIGHT_MODAL.EXPENSE_REPORT) { // We're guaranteed that the type of params is of SCREENS.REPORT - return {contextualReportID: (maybeReportRoute?.params as ReportsSplitNavigatorParamList[typeof SCREENS.REPORT]).reportID, isSearchRouterScreen, isOnSearchPage: false}; + return {contextualReportID: (maybeReportRoute?.params as ReportsSplitNavigatorParamList[typeof SCREENS.REPORT]).reportID, isSearchRouterScreen}; } - - // Whether the screen underneath the SearchRouter (or the focused screen when the router is an overlay) is the search page - const isOnSearchPage = maybeReportRoute?.name === SCREENS.SEARCH.ROOT; - return {contextualReportID: undefined, isSearchRouterScreen, isOnSearchPage}; + return {contextualReportID: undefined, isSearchRouterScreen}; } function getContextualSearchAutocompleteKey(item: SearchQueryItem, policies: OnyxCollection, reports?: OnyxCollection) { diff --git a/tests/unit/SearchRouterUtilsTest.ts b/tests/unit/SearchRouterUtilsTest.ts index 75f57081b495..2764224b412f 100644 --- a/tests/unit/SearchRouterUtilsTest.ts +++ b/tests/unit/SearchRouterUtilsTest.ts @@ -16,7 +16,6 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: undefined, isSearchRouterScreen: false, - isOnSearchPage: false, }); }); @@ -36,7 +35,6 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: '12345', isSearchRouterScreen: false, - isOnSearchPage: false, }); }); @@ -56,7 +54,6 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: '67890', isSearchRouterScreen: false, - isOnSearchPage: false, }); }); @@ -80,7 +77,6 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: '11111', isSearchRouterScreen: true, - isOnSearchPage: false, }); }); @@ -104,7 +100,6 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: undefined, isSearchRouterScreen: true, - isOnSearchPage: false, }); }); @@ -124,7 +119,6 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: undefined, isSearchRouterScreen: false, - isOnSearchPage: false, }); }); @@ -152,7 +146,6 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: '55555', isSearchRouterScreen: false, - isOnSearchPage: false, }); }); @@ -176,51 +169,6 @@ describe('SearchRouterUtils', () => { expect(result).toEqual({ contextualReportID: '99999', isSearchRouterScreen: true, - isOnSearchPage: false, - }); - }); - - it('returns isOnSearchPage true when focused on the Search page', () => { - const state = createMockState({ - index: 0, - routes: [ - { - name: SCREENS.SEARCH.ROOT, - params: {}, - }, - ], - }); - - const result = getContextualReportData(state); - - expect(result).toEqual({ - contextualReportID: undefined, - isSearchRouterScreen: false, - isOnSearchPage: true, - }); - }); - - it('returns isOnSearchPage true when SearchRouter is open over the Search page', () => { - const state = createMockState({ - index: 1, - routes: [ - { - name: SCREENS.SEARCH.ROOT, - params: {}, - }, - { - name: SCREENS.SEARCH_ROUTER.ROOT, - params: {}, - }, - ], - }); - - const result = getContextualReportData(state); - - expect(result).toEqual({ - contextualReportID: undefined, - isSearchRouterScreen: true, - isOnSearchPage: true, }); }); }); From 7cc73c84ca3b3523bc4e49e9287e925fc1cfba48 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Fri, 19 Jun 2026 13:13:47 +0800 Subject: [PATCH 24/36] fix test --- tests/unit/Search/SearchQueryUtilsTest.ts | 26 +++++++++++++++-------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index e524c305574a..76bea5b97571 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -676,7 +676,7 @@ describe('SearchQueryUtils', () => { const emptyTaxRates: Record = {}; const currentUserAccountID = 0; - test('produces canonical filter order', () => { + test('preserves manual filter order for raw queries', () => { const queryString = 'type:expense date:this-month groupBy:from tag:travel'; const canonicalQueryString = getQueryWithUpdatedValues(queryString); @@ -704,10 +704,10 @@ describe('SearchQueryUtils', () => { reportAttributes: undefined, }); - expect(result).toBe('type:expense group-by:from date:this-month tag:travel'); + expect(result).toBe('type:expense date:this-month group-by:from tag:travel'); }); - test('drops the default status all value from the query', () => { + test('preserves status all default value from manual query', () => { const queryString = 'type:expense status:all merchant:Uber'; const canonicalQueryString = getQueryWithUpdatedValues(queryString); @@ -735,10 +735,10 @@ describe('SearchQueryUtils', () => { reportAttributes: undefined, }); - expect(result).toBe('type:expense merchant:Uber'); + expect(result).toBe('type:expense status:all merchant:Uber'); }); - test('maps workspace names in canonical order', () => { + test('maps workspace names and maintains manual order', () => { const queryString = 'policyID:123 type:expense merchant:Starbucks'; const canonicalQueryString = getQueryWithUpdatedValues(queryString); @@ -771,7 +771,7 @@ describe('SearchQueryUtils', () => { reportAttributes: undefined, }); - expect(result).toBe('type:expense workspace:"Team Space" merchant:Starbucks'); + expect(result).toBe('workspace:"Team Space" type:expense merchant:Starbucks'); }); test('rawQuery overrides canonical filter values when provided', () => { @@ -1622,6 +1622,14 @@ describe('SearchQueryUtils', () => { expect(queryJSONa?.hash).not.toEqual(queryJSONb?.hash); }); + it('should return different primary hash for implicit table view and explicit view:table', () => { + const queryJSONa = buildSearchQueryJSON('type:expense groupBy:category'); + const queryJSONb = buildSearchQueryJSON('type:expense groupBy:category view:table', 'type:expense groupBy:category view:table'); + + expect(queryJSONa?.similarSearchHash).toEqual(queryJSONb?.similarSearchHash); + expect(queryJSONa?.hash).not.toEqual(queryJSONb?.hash); + }); + it('should not include view in query string when groupBy is removed after chart drill-down', () => { const parsed = buildSearchQueryJSON('type:expense date:this-month groupBy:category view:bar'); @@ -2059,10 +2067,10 @@ describe('SearchQueryUtils', () => { const result = buildSearchQueryString(queryJSON); // Re-parsing the built string must keep "status:done" as a keyword, not a status filter - const reparsed = buildSearchQueryJSON(result); - const keywordFilter = reparsed?.flatFilters.find((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD); + const newQueryJSON = buildSearchQueryJSON(result); + const keywordFilter = newQueryJSON?.flatFilters.find((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD); expect(keywordFilter?.filters.at(0)?.value).toBe('status:done'); - expect(reparsed?.status).toBe(CONST.SEARCH.STATUS.EXPENSE.ALL); + expect(newQueryJSON?.status).toBe(CONST.SEARCH.STATUS.EXPENSE.ALL); }); test('does not add quotes to non-keyword filter values', () => { From 6765f1987430ffcfe8f2a1034e9a9b9db9928da3 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Sat, 20 Jun 2026 15:23:12 +0800 Subject: [PATCH 25/36] restore previous change --- Mobile-Expensify | 2 +- ...gin+0.1.17+001+fix-loader-sourcemaps.patch | 22 +++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Mobile-Expensify b/Mobile-Expensify index 57a8e824e41d..aa5daf5ee204 160000 --- a/Mobile-Expensify +++ b/Mobile-Expensify @@ -1 +1 @@ -Subproject commit 57a8e824e41d5a88a1ebdaee4426c21bd5f3c42d +Subproject commit aa5daf5ee204593442c55b3e07446020d6ef03fe diff --git a/patches/time-analytics-webpack-plugin/time-analytics-webpack-plugin+0.1.17+001+fix-loader-sourcemaps.patch b/patches/time-analytics-webpack-plugin/time-analytics-webpack-plugin+0.1.17+001+fix-loader-sourcemaps.patch index d34429170950..6b4bb4c829ef 100644 --- a/patches/time-analytics-webpack-plugin/time-analytics-webpack-plugin+0.1.17+001+fix-loader-sourcemaps.patch +++ b/patches/time-analytics-webpack-plugin/time-analytics-webpack-plugin+0.1.17+001+fix-loader-sourcemaps.patch @@ -3,14 +3,14 @@ index 7a40d29..2a35893 100644 --- a/node_modules/time-analytics-webpack-plugin/dist/loader.js +++ b/node_modules/time-analytics-webpack-plugin/dist/loader.js @@ -57,9 +57,9 @@ function hackWrapLoaderModule(loaderPaths, wrapLoaderModuleCallback) { - // TODO: check whether thread-loader works for this case or not - Module.prototype.require = wrapRequire(originModuleRequire); - } --const loader = function timeAnalyticHackLoader(source) { -+const loader = function timeAnalyticHackLoader(source, sourceMap, meta) { - // console.log('Time analytics plugin: normal loader is executed'); -- return source; -+ this.callback(null, source, sourceMap, meta); - }; - /** - * Override `require` method, so that we could return a wrapped loader function. + // TODO: check whether thread-loader works for this case or not + Module.prototype.require = wrapRequire(originModuleRequire); + } +-const loader = function timeAnalyticHackLoader(source) { ++const loader = function timeAnalyticHackLoader(source, sourceMap, meta) { + // console.log('Time analytics plugin: normal loader is executed'); +- return source; ++ this.callback(null, source, sourceMap, meta); + }; + /** + * Override `require` method, so that we could return a wrapped loader function. From 87b484cc71add0526fade10ddd7b640a809d3093 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Thu, 25 Jun 2026 14:42:36 +0800 Subject: [PATCH 26/36] update comment --- src/pages/Search/SearchPageNarrow/Switches.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/Search/SearchPageNarrow/Switches.tsx b/src/pages/Search/SearchPageNarrow/Switches.tsx index 266a14ece71e..eefef654c902 100644 --- a/src/pages/Search/SearchPageNarrow/Switches.tsx +++ b/src/pages/Search/SearchPageNarrow/Switches.tsx @@ -7,7 +7,7 @@ * * IMPORTANT - keeping visual parity: * • If you change the UI of an interactive component (SearchTypeMenuNarrow, - * SearchPageInputNarrow, SearchActionsBarNarrow), verify the matching Static* version + * SearchPageInput, SearchActionsBarNarrow), verify the matching Static* version * still looks visually identical. * • Static components intentionally avoid expensive hooks and Onyx reads. * Do NOT add new subscriptions unless absolutely necessary for correctness. From c4ea58082f9fb4d2ccc905d4f5086461e6039051 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Thu, 25 Jun 2026 15:30:45 +0800 Subject: [PATCH 27/36] improve the syntax regex --- src/libs/SearchQueryUtils.ts | 3 ++- tests/unit/Search/SearchQueryUtilsTest.ts | 33 +++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index ba7063b32f09..de51f5281ee0 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -151,6 +151,7 @@ function sanitizeSearchValue(str: string) { return str; } +const syntaxRegex = new RegExp(`^-?(${Object.values(CONST.SEARCH.SYNTAX_FILTER_KEYS).join('|')}|report-?field(-.)+)[:><=].+$`); /** * Escapes each keyword that would otherwise be re-interpreted as query syntax by wrapping it in quotes. * A keyword that looks like a filter (e.g. `type:expense`) becomes `"type:expense"` so it is matched as a @@ -162,7 +163,7 @@ function escapeKeyword(keywords: string) { .split(' ') .map((q) => { const sanitizedKeyword = sanitizeSearchValue(q); - if (sanitizedKeyword.match(/^\w+:\w+$/)) { + if (sanitizedKeyword.toLowerCase().match(syntaxRegex)) { // The keyword is not escaped yet by sanitizeSearchValue, so we do it here. return `"${q}"`; } diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index 4c555e001b3d..0b6276f67e47 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -3281,6 +3281,39 @@ describe('SearchQueryUtils', () => { expect(result).toContain('"type:expense"'); expect(result).toContain('type:trip'); }); + + it('should escape input that uses a comparison operator with a filter key', () => { + const currentQueryJSON = buildSearchQueryJSON('type:trip status:all'); + + const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('amount>100 amount=100 amount<100 amount<=100 amount>=100', currentQueryJSON) : ''; + // "amount>100" matches real filter syntax, so it must be quoted to be treated as a keyword + expect(result).toContain('"amount>100"'); + }); + + it('should escape input that looks like filter syntax regardless of case', () => { + const currentQueryJSON = buildSearchQueryJSON('type:trip status:all'); + + const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('TYPE:expense', currentQueryJSON) : ''; + // The filter key is matched case-insensitively, so the original-case input is still quoted + expect(result).toContain('"TYPE:expense"'); + }); + + it('should escape negated input that looks like filter syntax', () => { + const currentQueryJSON = buildSearchQueryJSON('type:trip status:all'); + + const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('-type:expense', currentQueryJSON) : ''; + // A negated filter like "-type:expense" must also be quoted when typed as free text + expect(result).toContain('"-type:expense"'); + }); + + it('should not escape input that is not a real filter key', () => { + const currentQueryJSON = buildSearchQueryJSON('type:trip status:all'); + + const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('foo:bar', currentQueryJSON) : ''; + // "foo" is not a filter key, so it is kept as a plain keyword and not quoted + expect(result).toContain('foo:bar'); + expect(result).not.toContain('"foo:bar"'); + }); }); describe('getAdvancedFiltersToReset', () => { From eeae3d907774868a2d5f5e7c06173ab78f580b4d Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Thu, 25 Jun 2026 15:32:06 +0800 Subject: [PATCH 28/36] update test --- tests/unit/Search/SearchQueryUtilsTest.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index 0b6276f67e47..fff2fbb6c9ab 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -3287,7 +3287,7 @@ describe('SearchQueryUtils', () => { const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('amount>100 amount=100 amount<100 amount<=100 amount>=100', currentQueryJSON) : ''; // "amount>100" matches real filter syntax, so it must be quoted to be treated as a keyword - expect(result).toContain('"amount>100"'); + expect(result).toContain('"amount>100" "amount=100" "amount<100" "amount<=100" "amount>=100"'); }); it('should escape input that looks like filter syntax regardless of case', () => { From 6260b743db3806b3da8ff9243b68833cf5b13549 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Thu, 25 Jun 2026 16:41:32 +0800 Subject: [PATCH 29/36] fix single keyword wrapped with quote is separated into 2 keywords --- .../SearchPageHeader/SearchPageInput.tsx | 4 +-- src/libs/SearchQueryUtils.ts | 27 +++++++++---------- tests/unit/Search/SearchQueryUtilsTest.ts | 18 +++++++++++++ 3 files changed, 33 insertions(+), 16 deletions(-) diff --git a/src/components/Search/SearchPageHeader/SearchPageInput.tsx b/src/components/Search/SearchPageHeader/SearchPageInput.tsx index e6d9ed449288..e030109505a4 100644 --- a/src/components/Search/SearchPageHeader/SearchPageInput.tsx +++ b/src/components/Search/SearchPageHeader/SearchPageInput.tsx @@ -9,7 +9,7 @@ import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; import Navigation from '@libs/Navigation/Navigation'; -import {getKeywordQueryWithCurrentSearchContext, getQueryWithUpdatedValues} from '@libs/SearchQueryUtils'; +import {getKeywordQueryWithCurrentSearchContext, getQueryWithUpdatedValues, sanitizeSearchValue} from '@libs/SearchQueryUtils'; import variables from '@styles/variables'; import CONST from '@src/CONST'; import ROUTES from '@src/ROUTES'; @@ -29,7 +29,7 @@ function SearchPageInput({queryJSON, onFocus}: SearchPageInputProps) { const [textInputValue, setTextInputValue] = useState(''); const keywordFilters = queryJSON.flatFilters.find((filter) => filter.key === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD)?.filters ?? []; - const keywordQuery = keywordFilters.reduce((acc, keyword) => `${acc} ${keyword.value}`, '').trim(); + const keywordQuery = keywordFilters.reduce((acc, keyword) => `${acc} ${sanitizeSearchValue(keyword.value.toString())}`, '').trim(); const [prevKeywordQuery, setPrevKeywordQuery] = useState(''); if (keywordQuery !== prevKeywordQuery) { diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index de51f5281ee0..51d9ea8d10b8 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -155,21 +155,20 @@ const syntaxRegex = new RegExp(`^-?(${Object.values(CONST.SEARCH.SYNTAX_FILTER_K /** * Escapes each keyword that would otherwise be re-interpreted as query syntax by wrapping it in quotes. * A keyword that looks like a filter (e.g. `type:expense`) becomes `"type:expense"` so it is matched as a - * keyword instead of being parsed as the `type` filter. Keywords containing spaces are wrapped by - * `sanitizeSearchValue`. Plain keywords (e.g. `foo`) are left untouched. + * keyword instead of being parsed as the `type` filter. Plain keywords (e.g. `foo`) are left untouched. */ function escapeKeyword(keywords: string) { - return keywords - .split(' ') - .map((q) => { - const sanitizedKeyword = sanitizeSearchValue(q); - if (sanitizedKeyword.toLowerCase().match(syntaxRegex)) { - // The keyword is not escaped yet by sanitizeSearchValue, so we do it here. - return `"${q}"`; - } - return sanitizedKeyword; - }) - .join(' '); + return ( + keywords + .match(/"([^"]*)"|(\S+)/g) + ?.map((q) => { + if (q.toLowerCase().match(syntaxRegex)) { + return `"${q}"`; + } + return q; + }) + .join(' ') ?? '' + ); } function getRangeQueryValue(from?: string, to?: string) { @@ -334,7 +333,7 @@ function buildFilterValuesString(filterName: string, queryFilters: QueryFilter[] // If the previous queryFilter has the same operator (this rule applies only to eq and neq operators) then append the current value if (filterName === CONST.SEARCH.SYNTAX_FILTER_KEYS.KEYWORD) { - filterValueString += `${delimiter}${escapeKeyword(queryFilter.value.toString())}`; + filterValueString += `${delimiter}${escapeKeyword(sanitizeSearchValue(queryFilter.value.toString()))}`; } else if (index !== 0 && (previousValueHasSameOp || nextValueHasSameOp)) { filterValueString += `${delimiter}${sanitizeSearchValue(queryFilter.value.toString())}`; } else if (queryFilter.operator === CONST.SEARCH.SYNTAX_OPERATORS.NOT_EQUAL_TO) { diff --git a/tests/unit/Search/SearchQueryUtilsTest.ts b/tests/unit/Search/SearchQueryUtilsTest.ts index fff2fbb6c9ab..c484965f1521 100644 --- a/tests/unit/Search/SearchQueryUtilsTest.ts +++ b/tests/unit/Search/SearchQueryUtilsTest.ts @@ -3314,6 +3314,24 @@ describe('SearchQueryUtils', () => { expect(result).toContain('foo:bar'); expect(result).not.toContain('"foo:bar"'); }); + + it('should keep an already-quoted phrase as a single token without re-escaping it', () => { + const currentQueryJSON = buildSearchQueryJSON('type:trip status:all'); + + const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('"type:expense"', currentQueryJSON) : ''; + // The phrase is already quoted, so it must not be wrapped in another set of quotes + expect(result).toContain('"type:expense"'); + expect(result).not.toContain('""type:expense""'); + }); + + it('should not split a quoted multi-word phrase when escaping', () => { + const currentQueryJSON = buildSearchQueryJSON('type:trip status:all'); + + const result = currentQueryJSON ? getKeywordQueryWithCurrentSearchContext('"hello world" type:expense', currentQueryJSON) : ''; + // The quoted phrase stays intact and the filter-like keyword is escaped separately + expect(result).toContain('"hello world"'); + expect(result).toContain('"type:expense"'); + }); }); describe('getAdvancedFiltersToReset', () => { From d8c8b66e80428768fcbe261a61bbf0f05b625e6a Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Thu, 25 Jun 2026 20:14:50 +0800 Subject: [PATCH 30/36] remove unused prop --- .../Search/SearchPageHeader/SearchPageHeaderNarrow.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/components/Search/SearchPageHeader/SearchPageHeaderNarrow.tsx b/src/components/Search/SearchPageHeader/SearchPageHeaderNarrow.tsx index 7187c1580672..74080deb4d75 100644 --- a/src/components/Search/SearchPageHeader/SearchPageHeaderNarrow.tsx +++ b/src/components/Search/SearchPageHeader/SearchPageHeaderNarrow.tsx @@ -8,7 +8,6 @@ type SearchPageHeaderNarrowProps = { queryJSON: SearchQueryJSON; shouldShowLoadingBar: boolean; isMobileSelectionModeEnabled: boolean; - cancelSearch?: () => void; }; function SearchPageHeaderNarrow({queryJSON, shouldShowLoadingBar = false, isMobileSelectionModeEnabled, cancelSearch}: SearchPageHeaderNarrowProps) { @@ -23,7 +22,6 @@ function SearchPageHeaderNarrow({queryJSON, shouldShowLoadingBar = false, isMobi shouldShowLoadingBar={shouldShowLoadingBar} breadcrumbLabel={translate('common.spend')} shouldDisplayHelpButton - cancelSearch={cancelSearch} /> ); } From 84745b40959d6cb869a36c883c1d82d5cea32fa3 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Thu, 25 Jun 2026 20:15:58 +0800 Subject: [PATCH 31/36] readd removed var --- src/components/Search/index.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx index a7a9281051c3..f439bfa2cef5 100644 --- a/src/components/Search/index.tsx +++ b/src/components/Search/index.tsx @@ -952,6 +952,7 @@ function Search({ const {shouldShowYearCreated, shouldShowYearSubmitted, shouldShowYearApproved, shouldShowYearPosted, shouldShowYearExported, shouldShowYearWithdrawn} = yearIndicators; const {shouldShowAmountInWideColumn, shouldShowTaxAmountInWideColumn} = amountIndicators; const shouldShowTableHeader = isLargeScreenWidth && !isChat; + const tableHeaderVisible = canSelectMultiple || shouldShowTableHeader; const shouldShowChartView = (view === CONST.SEARCH.VIEW.BAR || view === CONST.SEARCH.VIEW.LINE || view === CONST.SEARCH.VIEW.PIE) && !!validGroupBy; From 78fcf5c30f9371d1f003d1791d7afe03c95260f1 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Thu, 25 Jun 2026 20:16:30 +0800 Subject: [PATCH 32/36] update regex --- src/libs/SearchQueryUtils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/SearchQueryUtils.ts b/src/libs/SearchQueryUtils.ts index 51d9ea8d10b8..a2f77ea743be 100644 --- a/src/libs/SearchQueryUtils.ts +++ b/src/libs/SearchQueryUtils.ts @@ -151,7 +151,7 @@ function sanitizeSearchValue(str: string) { return str; } -const syntaxRegex = new RegExp(`^-?(${Object.values(CONST.SEARCH.SYNTAX_FILTER_KEYS).join('|')}|report-?field(-.)+)[:><=].+$`); +const syntaxRegex = new RegExp(`^-?(${Object.values(CONST.SEARCH.SEARCH_USER_FRIENDLY_KEYS).join('|')}|report-?field(-.+)+)[:><=].+$`); /** * Escapes each keyword that would otherwise be re-interpreted as query syntax by wrapping it in quotes. * A keyword that looks like a filter (e.g. `type:expense`) becomes `"type:expense"` so it is matched as a From c186140d317e44cf1b20ce3714158d16c899a39d Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Thu, 25 Jun 2026 20:18:41 +0800 Subject: [PATCH 33/36] don't show query in search input when apply keyword --- .../FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx | 8 +------- src/pages/Search/SearchAdvancedFiltersProvider.tsx | 9 +-------- 2 files changed, 2 insertions(+), 15 deletions(-) diff --git a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx index 604adc159bbb..63ab10f26a4f 100644 --- a/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx +++ b/src/components/Search/FilterDropdowns/SearchAdvancedFiltersPopup/index.tsx @@ -9,7 +9,6 @@ import useOnyx from '@hooks/useOnyx'; import useStyleUtils from '@hooks/useStyleUtils'; import useThemeStyles from '@hooks/useThemeStyles'; import useWindowDimensions from '@hooks/useWindowDimensions'; -import {setSearchContext} from '@libs/actions/Search'; import type {SearchFilter} from '@libs/SearchUIUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; @@ -59,12 +58,7 @@ function SearchAdvancedFiltersPopup({queryJSON}: SearchAdvancedFiltersPopupProps Date: DateFilterContentPopupWrapper, ReportField: ReportFieldFilterContentPopupWrapper, }} - onChange={(values) => { - updateFilterQueryParams(values); - if (values.keyword) { - setSearchContext(true); - } - }} + onChange={updateFilterQueryParams} /> diff --git a/src/pages/Search/SearchAdvancedFiltersProvider.tsx b/src/pages/Search/SearchAdvancedFiltersProvider.tsx index 66e6481d7742..b7610584da4a 100644 --- a/src/pages/Search/SearchAdvancedFiltersProvider.tsx +++ b/src/pages/Search/SearchAdvancedFiltersProvider.tsx @@ -45,14 +45,7 @@ function SearchAdvancedFiltersProvider({children}: SearchAdvancedFiltersProvider const advancedFiltersToReset = searchAdvancedFiltersForm ? getAdvancedFiltersToReset(searchAdvancedFiltersForm) : undefined; const applyFilters = () => { - Navigation.dismissModal({ - afterTransition: () => { - setFilterQueryParams(values); - if (values.keyword) { - setSearchContext(true); - } - }, - }); + Navigation.dismissModal({afterTransition: () => setFilterQueryParams(values)}); }; const resetFilters = () => { From aaacc4d9638e4a62f4a6a990ec99cd6f57443272 Mon Sep 17 00:00:00 2001 From: Bernhard Owen Josephus Date: Thu, 25 Jun 2026 21:38:24 +0800 Subject: [PATCH 34/36] Merge branch 'main' into feat/92924-rework-search-input --- Mobile-Expensify | 2 +- android/app/build.gradle | 4 +- config/eslint/eslint.seatbelt.tsv | 5 +- ios/NewExpensify/Info.plist | 2 +- ios/NotificationServiceExtension/Info.plist | 2 +- ios/ShareViewController/Info.plist | 2 +- package-lock.json | 4 +- package.json | 2 +- src/ROUTES.ts | 162 ++-------- src/SCREENS.ts | 12 +- src/components/Button/index.tsx | 12 +- .../MoneyRequestConfirmationList.tsx | 14 +- .../sections/AttendeeField.tsx | 5 +- .../sections/CategoryField.tsx | 24 +- .../sections/RateField.tsx | 22 +- .../sections/TaxFields.tsx | 7 +- .../MoneyRequestHeaderSecondaryActions.tsx | 19 +- .../QuickCreationActionsBar/index.tsx | 19 +- .../ReportActionItem/MoneyRequestView.tsx | 99 +++--- .../ListFilterViewWrapper.tsx | 6 +- .../Search/FilterComponents/SingleSelect.tsx | 3 - .../Search/FilterDropdowns/CurrencyPopup.tsx | 57 ---- .../Search/FilterDropdowns/DisplayPopup.tsx | 7 +- .../FilterDropdowns/GroupCurrencyPopup.tsx | 45 +++ .../FilterDropdowns/SingleSelectPopup.tsx | 5 - src/components/Search/SearchPageFooter.tsx | 137 ++------- .../Search/SearchPageFooterSkeleton.tsx | 51 ---- .../SearchActionsBarCreateButton.tsx | 16 +- .../Search/SearchSelectionFooter.tsx | 282 ++---------------- src/components/Search/types.ts | 1 - src/hooks/useCreateReport.tsx | 16 +- src/hooks/useParticipantSubmission.ts | 10 +- .../ModalStackNavigators/index.tsx | 12 +- src/libs/Navigation/linkingConfig/config.ts | 12 +- src/libs/Navigation/types.ts | 26 +- src/libs/ReportUtils.ts | 32 +- src/libs/SearchQueryUtils.ts | 39 --- src/libs/actions/Search.ts | 3 - .../Search/SearchTransactionsChangeReport.tsx | 32 +- src/pages/iou/MoneyRequestAmountForm.tsx | 3 +- src/pages/iou/SplitExpenseEditPage.tsx | 49 ++- ...tPage.tsx => IOURequestStepAccountant.tsx} | 18 +- ...esPage.tsx => IOURequestStepAttendees.tsx} | 28 +- ...oryPage.tsx => IOURequestStepCategory.tsx} | 44 +-- .../step/IOURequestStepCategoryCreate.tsx | 9 +- ...ge.tsx => IOURequestStepTaxAmountPage.tsx} | 30 +- ...Page.tsx => IOURequestStepTaxRatePage.tsx} | 17 +- ...radePage.tsx => IOURequestStepUpgrade.tsx} | 33 +- .../step/withFullTransactionOrNotFound.tsx | 6 +- .../step/withWritableReportOrNotFound.tsx | 12 +- .../PolicyCommuterExclusionsPage.tsx | 1 + tests/unit/ReportUtilsTest.ts | 77 ++--- .../Search/searchTotalsLoadingDataTest.ts | 143 +-------- 53 files changed, 461 insertions(+), 1219 deletions(-) delete mode 100644 src/components/Search/FilterDropdowns/CurrencyPopup.tsx create mode 100644 src/components/Search/FilterDropdowns/GroupCurrencyPopup.tsx delete mode 100644 src/components/Search/SearchPageFooterSkeleton.tsx rename src/pages/iou/request/step/{DynamicIOURequestStepAccountantPage.tsx => IOURequestStepAccountant.tsx} (82%) rename src/pages/iou/request/step/{DynamicIOURequestStepAttendeesPage.tsx => IOURequestStepAttendees.tsx} (82%) rename src/pages/iou/request/step/{DynamicIOURequestStepCategoryPage.tsx => IOURequestStepCategory.tsx} (90%) rename src/pages/iou/request/step/{DynamicIOURequestStepTaxAmountPage.tsx => IOURequestStepTaxAmountPage.tsx} (88%) rename src/pages/iou/request/step/{DynamicIOURequestStepTaxRatePage.tsx => IOURequestStepTaxRatePage.tsx} (90%) rename src/pages/iou/request/step/{DynamicIOURequestStepUpgradePage.tsx => IOURequestStepUpgrade.tsx} (93%) diff --git a/Mobile-Expensify b/Mobile-Expensify index 08be844985dc..81df53c398be 160000 --- a/Mobile-Expensify +++ b/Mobile-Expensify @@ -1 +1 @@ -Subproject commit 08be844985dcf73ca3a60a03c624ca4646610e84 +Subproject commit 81df53c398befa32ba3c204e63949ba59cd2651a diff --git a/android/app/build.gradle b/android/app/build.gradle index ca1ce7ebdfca..26ab4e336fd5 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -111,8 +111,8 @@ android { minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion multiDexEnabled rootProject.ext.multiDexEnabled - versionCode 1009041901 - versionName "9.4.19-1" + versionCode 1009041903 + versionName "9.4.19-3" // Supported language variants must be declared here to avoid from being removed during the compilation. // This also helps us to not include unnecessary language variants in the APK. resConfigs "en", "es" diff --git a/config/eslint/eslint.seatbelt.tsv b/config/eslint/eslint.seatbelt.tsv index 45ddf8c2acd9..35444f319997 100644 --- a/config/eslint/eslint.seatbelt.tsv +++ b/config/eslint/eslint.seatbelt.tsv @@ -68,7 +68,7 @@ "../../src/Expensify.tsx" "react-hooks/set-state-in-effect" 1 "../../src/GlobalModals.tsx" "no-restricted-syntax" 2 "../../src/ONYXKEYS.ts" "no-restricted-syntax" 2 -"../../src/ROUTES.ts" "@typescript-eslint/no-deprecated/getUrlWithBackToParam" 120 +"../../src/ROUTES.ts" "@typescript-eslint/no-deprecated/getUrlWithBackToParam" 123 "../../src/ROUTES.ts" "@typescript-eslint/no-unsafe-type-assertion" 3 "../../src/TIMEZONES.ts" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/components/AccountingConnectionConfirmationModal.tsx" "@typescript-eslint/no-deprecated/ConfirmModal" 1 @@ -1164,6 +1164,7 @@ "../../src/pages/iou/request/step/IOURequestEditReportCommon.tsx" "@typescript-eslint/no-deprecated/ConfirmModal" 1 "../../src/pages/iou/request/step/IOURequestEditReportCommon.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/pages/iou/request/step/IOURequestStepAmount.tsx" "react-hooks/set-state-in-effect" 1 +"../../src/pages/iou/request/step/IOURequestStepCategory.tsx" "@typescript-eslint/no-deprecated/InteractionManager.runAfterInteractions" 1 "../../src/pages/iou/request/step/IOURequestStepConfirmation.tsx" "@typescript-eslint/no-unsafe-type-assertion" 3 "../../src/pages/iou/request/step/IOURequestStepConfirmation.tsx" "react-hooks/preserve-manual-memoization" 1 "../../src/pages/iou/request/step/IOURequestStepDestination.tsx" "@typescript-eslint/no-deprecated/InteractionManager.runAfterInteractions" 1 @@ -1188,6 +1189,8 @@ "../../src/pages/iou/request/step/IOURequestStepScan/utils/getFileSource.ts" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/pages/iou/request/step/IOURequestStepSubrate.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/pages/iou/request/step/IOURequestStepSubrate.tsx" "react-hooks/set-state-in-effect" 1 +"../../src/pages/iou/request/step/IOURequestStepUpgrade.tsx" "@typescript-eslint/no-deprecated/ConfirmModal" 1 +"../../src/pages/iou/request/step/IOURequestStepUpgrade.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/pages/iou/request/step/IOURequestStepWaypoint.tsx" "@typescript-eslint/no-unsafe-type-assertion" 2 "../../src/pages/iou/request/step/StepScreenWrapper.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 "../../src/pages/iou/request/step/withFullTransactionOrNotFound.tsx" "@typescript-eslint/no-unsafe-type-assertion" 1 diff --git a/ios/NewExpensify/Info.plist b/ios/NewExpensify/Info.plist index 1c1934640b23..0aba2ffb11fe 100644 --- a/ios/NewExpensify/Info.plist +++ b/ios/NewExpensify/Info.plist @@ -44,7 +44,7 @@ CFBundleVersion - 9.4.19.1 + 9.4.19.3 FullStory OrgId diff --git a/ios/NotificationServiceExtension/Info.plist b/ios/NotificationServiceExtension/Info.plist index ae1d64de33aa..f4a4d920b287 100644 --- a/ios/NotificationServiceExtension/Info.plist +++ b/ios/NotificationServiceExtension/Info.plist @@ -13,7 +13,7 @@ CFBundleShortVersionString 9.4.19 CFBundleVersion - 9.4.19.1 + 9.4.19.3 NSExtension NSExtensionPointIdentifier diff --git a/ios/ShareViewController/Info.plist b/ios/ShareViewController/Info.plist index 6ef1cd803bb3..118bc6feccf4 100644 --- a/ios/ShareViewController/Info.plist +++ b/ios/ShareViewController/Info.plist @@ -13,7 +13,7 @@ CFBundleShortVersionString 9.4.19 CFBundleVersion - 9.4.19.1 + 9.4.19.3 NSExtension NSExtensionAttributes diff --git a/package-lock.json b/package-lock.json index 60424dbf78b4..c4b6f119d716 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "new.expensify", - "version": "9.4.19-1", + "version": "9.4.19-3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "new.expensify", - "version": "9.4.19-1", + "version": "9.4.19-3", "hasInstallScript": true, "license": "MIT", "workspaces": [ diff --git a/package.json b/package.json index bea3ba044b09..3b3417c05e11 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "new.expensify", - "version": "9.4.19-1", + "version": "9.4.19-3", "author": "Expensify, Inc.", "homepage": "https://new.expensify.com", "description": "New Expensify is the next generation of Expensify: a reimagination of payments based atop a foundation of chat.", diff --git a/src/ROUTES.ts b/src/ROUTES.ts index cf19054b2d2a..ad3fcc28e61b 100644 --- a/src/ROUTES.ts +++ b/src/ROUTES.ts @@ -196,138 +196,6 @@ const DYNAMIC_ROUTES = { entryScreens: ['*'], getRoute: (accountID: number) => `avatar/${accountID}` as const, }, - MONEY_REQUEST_STEP_TAX_RATE: { - path: 'money-request/tax-rate/:action/:iouType/:transactionID/:reportID?', - entryScreens: [ - SCREENS.MONEY_REQUEST.STEP_CONFIRMATION, - SCREENS.REPORT, - SCREENS.RIGHT_MODAL.EXPENSE_REPORT, - SCREENS.RIGHT_MODAL.SEARCH_REPORT, - SCREENS.RIGHT_MODAL.SEARCH_REPORT_ACTIONS, - SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT, - SCREENS.SHARE.SUBMIT_DETAILS, - SCREENS.MONEY_REQUEST.CREATE, - ], - getRoute: (action: IOUAction, iouType: IOUType, transactionID: string | undefined, reportID?: string) => { - if (!transactionID || !reportID) { - Log.warn('Invalid transactionID or reportID is used to build the MONEY_REQUEST_STEP_TAX_RATE dynamic route'); - } - - return `money-request/tax-rate/${action as string}/${iouType as string}/${transactionID}${reportID ? `/${reportID}` : ''}` as const; - }, - }, - MONEY_REQUEST_STEP_TAX_AMOUNT: { - path: 'money-request/tax-amount/:action/:iouType/:transactionID/:reportID?', - entryScreens: [ - SCREENS.MONEY_REQUEST.STEP_CONFIRMATION, - SCREENS.REPORT, - SCREENS.RIGHT_MODAL.EXPENSE_REPORT, - SCREENS.RIGHT_MODAL.SEARCH_REPORT, - SCREENS.RIGHT_MODAL.SEARCH_REPORT_ACTIONS, - SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT, - SCREENS.SHARE.SUBMIT_DETAILS, - SCREENS.MONEY_REQUEST.CREATE, - ], - getRoute: (action: IOUAction, iouType: IOUType, transactionID: string | undefined, reportID?: string) => { - if (!transactionID || !reportID) { - Log.warn('Invalid transactionID or reportID is used to build the MONEY_REQUEST_STEP_TAX_AMOUNT dynamic route'); - } - - return `money-request/tax-amount/${action as string}/${iouType as string}/${transactionID}${reportID ? `/${reportID}` : ''}` as const; - }, - }, - MONEY_REQUEST_STEP_CATEGORY: { - path: 'money-request/category/:action/:iouType/:transactionID/:reportID/:reportActionID?', - entryScreens: [ - SCREENS.MONEY_REQUEST.STEP_CONFIRMATION, - SCREENS.MONEY_REQUEST.SPLIT_EXPENSE_EDIT, - SCREENS.REPORT, - SCREENS.RIGHT_MODAL.EXPENSE_REPORT, - SCREENS.RIGHT_MODAL.SEARCH_REPORT, - SCREENS.RIGHT_MODAL.SEARCH_REPORT_ACTIONS, - SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT, - SCREENS.SHARE.SUBMIT_DETAILS, - SCREENS.MONEY_REQUEST.CREATE, - ], - getRoute: (action: IOUAction, iouType: IOUType, transactionID: string | undefined, reportID: string | undefined, reportActionID?: string) => { - if (!transactionID || !reportID) { - Log.warn('Invalid transactionID or reportID is used to build the MONEY_REQUEST_STEP_CATEGORY dynamic route'); - } - - return `money-request/category/${action as string}/${iouType as string}/${transactionID}/${reportID}${reportActionID ? `/${reportActionID}` : ''}` as const; - }, - }, - MONEY_REQUEST_ATTENDEE: { - path: 'money-request/attendees/:action/:iouType/:transactionID/:reportID', - entryScreens: [ - SCREENS.MONEY_REQUEST.STEP_CONFIRMATION, - SCREENS.REPORT, - SCREENS.RIGHT_MODAL.EXPENSE_REPORT, - SCREENS.RIGHT_MODAL.SEARCH_REPORT, - SCREENS.RIGHT_MODAL.SEARCH_REPORT_ACTIONS, - SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT, - SCREENS.SHARE.SUBMIT_DETAILS, - SCREENS.MONEY_REQUEST.CREATE, - ], - getRoute: (action: IOUAction, iouType: IOUType, transactionID: string | undefined, reportID: string | undefined) => { - if (!transactionID || !reportID) { - Log.warn('Invalid transactionID or reportID is used to build the MONEY_REQUEST_ATTENDEE dynamic route'); - } - - return `money-request/attendees/${action as string}/${iouType as string}/${transactionID}/${reportID}` as const; - }, - }, - MONEY_REQUEST_ACCOUNTANT: { - path: 'money-request/accountant/:action/:iouType/:transactionID/:reportID', - entryScreens: [ - SCREENS.MONEY_REQUEST.STEP_CONFIRMATION, - SCREENS.REPORT, - SCREENS.REPORT_DETAILS.DYNAMIC_ROOT, - SCREENS.RIGHT_MODAL.EXPENSE_REPORT, - SCREENS.RIGHT_MODAL.SEARCH_REPORT, - SCREENS.RIGHT_MODAL.SEARCH_REPORT_ACTIONS, - SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT, - SCREENS.SHARE.SUBMIT_DETAILS, - SCREENS.MONEY_REQUEST.CREATE, - ], - getRoute: (action: IOUAction, iouType: IOUType, transactionID: string | undefined, reportID: string | undefined) => { - if (!transactionID || !reportID) { - Log.warn('Invalid transactionID or reportID is used to build the MONEY_REQUEST_ACCOUNTANT dynamic route'); - } - - return `money-request/accountant/${action as string}/${iouType as string}/${transactionID}/${reportID}` as const; - }, - }, - MONEY_REQUEST_UPGRADE: { - path: 'money-request/upgrade/:action/:iouType/:transactionID/:reportID/:upgradePath?', - entryScreens: [ - SCREENS.MONEY_REQUEST.STEP_CONFIRMATION, - SCREENS.MONEY_REQUEST.SPLIT_EXPENSE_EDIT, - SCREENS.HOME, - SCREENS.INBOX, - SCREENS.REPORT, - SCREENS.RIGHT_MODAL.EXPENSE_REPORT, - SCREENS.RIGHT_MODAL.SEARCH_REPORT, - SCREENS.RIGHT_MODAL.SEARCH_REPORT_ACTIONS, - SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT, - SCREENS.SEARCH.ROOT, - SCREENS.SEARCH.TRANSACTIONS_CHANGE_REPORT_SEARCH_RHP, - SCREENS.SHARE.SUBMIT_DETAILS, - SCREENS.MONEY_REQUEST.CREATE, - ], - getRoute: (params: {action: IOUAction; iouType: IOUType; transactionID: string; reportID: string; upgradePath?: string; shouldSubmitExpense?: boolean}) => { - const {action, iouType, transactionID, reportID, upgradePath, shouldSubmitExpense} = params; - const upgradePathParam = upgradePath ? `/${upgradePath}` : ''; - const basePath = `money-request/upgrade/${action as string}/${iouType as string}/${transactionID}/${reportID}${upgradePathParam}` as const; - - if (shouldSubmitExpense) { - return `${basePath}?shouldSubmitExpense=true` as const; - } - - return basePath; - }, - queryParams: ['shouldSubmitExpense'], - }, NEW_REPORT_WORKSPACE_SELECTION: { path: 'new-report-workspace-selection', entryScreens: ['*'], @@ -1802,6 +1670,26 @@ const ROUTES = { return getUrlWithBackToParam(`${action as string}/${iouType as string}/amount/${transactionID}/${reportID}/${reportActionID ? `${reportActionID}/` : ''}${pageIndex}`, backTo); }, }, + MONEY_REQUEST_STEP_TAX_RATE: { + route: ':action/:iouType/taxRate/:transactionID/:reportID?', + getRoute: (action: IOUAction, iouType: IOUType, transactionID: string | undefined, reportID: string | undefined, backTo = '') => { + if (!transactionID || !reportID) { + Log.warn('Invalid transactionID or reportID is used to build the MONEY_REQUEST_STEP_TAX_RATE route'); + } + + return getUrlWithBackToParam(`${action as string}/${iouType as string}/taxRate/${transactionID}/${reportID}`, backTo); + }, + }, + MONEY_REQUEST_STEP_TAX_AMOUNT: { + route: ':action/:iouType/taxAmount/:transactionID/:reportID?', + getRoute: (action: IOUAction, iouType: IOUType, transactionID: string | undefined, reportID: string | undefined, backTo = '') => { + if (!transactionID || !reportID) { + Log.warn('Invalid transactionID or reportID is used to build the MONEY_REQUEST_STEP_TAX_AMOUNT route'); + } + + return getUrlWithBackToParam(`${action as string}/${iouType as string}/taxAmount/${transactionID}/${reportID}`, backTo); + }, + }, MONEY_REQUEST_STEP_CATEGORY_CREATE: { route: ':action/:iouType/category/new/:transactionID/:reportID/:reportActionID?', getRoute: (action: IOUAction, iouType: IOUType, transactionID: string | undefined, reportID: string | undefined, reportActionID?: string, backTo = '') => { @@ -1812,6 +1700,16 @@ const ROUTES = { return getUrlWithBackToParam(`${action as string}/${iouType as string}/category/new/${transactionID}/${reportID}${reportActionID ? `/${reportActionID}` : ''}`, backTo); }, }, + MONEY_REQUEST_STEP_CATEGORY: { + route: ':action/:iouType/category/:transactionID/:reportID/:reportActionID?', + getRoute: (action: IOUAction, iouType: IOUType, transactionID: string | undefined, reportID: string | undefined, backTo = '', reportActionID?: string) => { + if (!transactionID || !reportID) { + Log.warn('Invalid transactionID or reportID is used to build the MONEY_REQUEST_STEP_CATEGORY route'); + } + + return getUrlWithBackToParam(`${action as string}/${iouType as string}/category/${transactionID}/${reportID}${reportActionID ? `/${reportActionID}` : ''}`, backTo); + }, + }, MONEY_REQUEST_ATTENDEE: { route: ':action/:iouType/attendees/:transactionID/:reportID', getRoute: (action: IOUAction, iouType: IOUType, transactionID: string | undefined, reportID: string | undefined, backTo = '') => { diff --git a/src/SCREENS.ts b/src/SCREENS.ts index cb445ab688ec..a62b7f4c0baa 100644 --- a/src/SCREENS.ts +++ b/src/SCREENS.ts @@ -369,9 +369,9 @@ const SCREENS = { STEP_CONFIRMATION: 'Money_Request_Step_Confirmation', STEP_CONFIRMATION_VERIFY_ACCOUNT: 'Money_Request_Step_Confirmation_Verify_Account', START: 'Money_Request_Start', - DYNAMIC_STEP_UPGRADE: 'Dynamic_Money_Request_Step_Upgrade', + STEP_UPGRADE: 'Money_Request_Step_Upgrade', STEP_AMOUNT: 'Money_Request_Step_Amount', - DYNAMIC_STEP_CATEGORY: 'Dynamic_Money_Request_Step_Category', + STEP_CATEGORY: 'Money_Request_Step_Category', STEP_CATEGORY_CREATE: 'Money_Request_Step_Category_Create', STEP_DATE: 'Money_Request_Step_Date', STEP_DESCRIPTION: 'Money_Request_Step_Description', @@ -382,9 +382,9 @@ const SCREENS = { STEP_SCAN: 'Money_Request_Step_Scan', STEP_TAG: 'Money_Request_Step_Tag', STEP_WAYPOINT: 'Money_Request_Step_Waypoint', + STEP_TAX_AMOUNT: 'Money_Request_Step_Tax_Amount', + STEP_TAX_RATE: 'Money_Request_Step_Tax_Rate', STEP_VENDOR: 'Money_Request_Step_Vendor', - DYNAMIC_STEP_TAX_AMOUNT: 'Dynamic_Money_Request_Step_Tax_Amount', - DYNAMIC_STEP_TAX_RATE: 'Dynamic_Money_Request_Step_Tax_Rate', RECEIPT_VIEW: 'Money_Request_Receipt_View', STEP_SEND_FROM: 'Money_Request_Step_Send_From', STEP_COMPANY_INFO: 'Money_Request_Step_Company_Info', @@ -393,8 +393,8 @@ const SCREENS = { EDIT_WAYPOINT: 'Money_Request_Edit_Waypoint', RECEIPT: 'Money_Request_Receipt', STATE_SELECTOR: 'Money_Request_State_Selector', - DYNAMIC_STEP_ATTENDEES: 'Dynamic_Money_Request_Attendee', - DYNAMIC_STEP_ACCOUNTANT: 'Dynamic_Money_Request_Step_Accountant', + STEP_ATTENDEES: 'Money_Request_Attendee', + STEP_ACCOUNTANT: 'Money_Request_Accountant', STEP_DESTINATION: 'Money_Request_Destination', STEP_TIME: 'Money_Request_Time', STEP_SUBRATE: 'Money_Request_SubRate', diff --git a/src/components/Button/index.tsx b/src/components/Button/index.tsx index a8111367277c..c889db03185f 100644 --- a/src/components/Button/index.tsx +++ b/src/components/Button/index.tsx @@ -1,7 +1,7 @@ import {useIsFocused} from '@react-navigation/native'; import type {ForwardedRef} from 'react'; import React, {useCallback, useMemo, useState} from 'react'; -import type {AccessibilityState, GestureResponderEvent, LayoutChangeEvent, NativeSyntheticEvent, StyleProp, TargetedEvent, TextStyle, ViewStyle} from 'react-native'; +import type {AccessibilityState, GestureResponderEvent, LayoutChangeEvent, StyleProp, TextStyle, ViewStyle} from 'react-native'; import {StyleSheet, View} from 'react-native'; import ActivityIndicator from '@components/ActivityIndicator'; import Icon from '@components/Icon'; @@ -96,12 +96,6 @@ type ButtonProps = Partial & /** Callback that is called when mousedown is triggered. */ onMouseDown?: (e: React.MouseEvent) => void; - /** A function that is called when the button receives focus */ - onFocus?: (event: NativeSyntheticEvent) => void; - - /** A function that is called when the button loses focus */ - onBlur?: (event: NativeSyntheticEvent) => void; - /** Call the onPress function when Enter key is pressed */ pressOnEnter?: boolean; @@ -270,8 +264,6 @@ function Button({ onPressIn = () => {}, onPressOut = () => {}, onMouseDown = undefined, - onFocus = undefined, - onBlur = undefined, pressOnEnter = false, enterKeyEventListenerPriority = 0, @@ -535,8 +527,6 @@ function Button({ onPressIn={onPressIn} onPressOut={onPressOut} onMouseDown={onMouseDown} - onFocus={onFocus} - onBlur={onBlur} shouldBlendOpacity={shouldBlendOpacity} disabled={isLoading || isDisabled} wrapperStyle={[ diff --git a/src/components/MoneyRequestConfirmationList.tsx b/src/components/MoneyRequestConfirmationList.tsx index f2bfe1000b3c..9f4e07ff110e 100644 --- a/src/components/MoneyRequestConfirmationList.tsx +++ b/src/components/MoneyRequestConfirmationList.tsx @@ -623,7 +623,8 @@ function MoneyRequestConfirmationList({ isMovingTransactionFromTrackExpense={isMovingTransactionFromTrackExpense} /> - + + sections={sections} ListItem={BareUserListItem} onSelectRow={navigateToParticipantPage} @@ -631,11 +632,18 @@ function MoneyRequestConfirmationList({ shouldSingleExecuteRowSelect shouldPreventDefaultFocusOnSelectRow shouldShowListEmptyContent={false} - footerContent={footerContent} - listFooterContent={listFooterContent} + // footerContent={footerContent} + // listFooterContent={listFooterContent} style={selectionListStyle} disableKeyboardShortcuts /> + + + + {listFooterContent} + {footerContent} + + ); diff --git a/src/components/MoneyRequestConfirmationList/sections/AttendeeField.tsx b/src/components/MoneyRequestConfirmationList/sections/AttendeeField.tsx index 90d4d5cd27a3..2252f0df716f 100644 --- a/src/components/MoneyRequestConfirmationList/sections/AttendeeField.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/AttendeeField.tsx @@ -7,13 +7,12 @@ import useAttendees from '@hooks/useAttendees'; import useLocalize from '@hooks/useLocalize'; import useThemeStyles from '@hooks/useThemeStyles'; import {enrichAndSortAttendees} from '@libs/AttendeeUtils'; -import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import Navigation from '@libs/Navigation/Navigation'; import {getAttendeesListDisplayString} from '@libs/TransactionUtils'; import CONST from '@src/CONST'; import type {IOUAction, IOUType} from '@src/CONST'; import type {TranslationPaths} from '@src/languages/types'; -import {DYNAMIC_ROUTES} from '@src/ROUTES'; +import ROUTES from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; import {attendeeSliceSelector} from './selectors'; import useTransactionSelector from './useTransactionSelector'; @@ -68,7 +67,7 @@ function AttendeeField({formattedAmountPerAttendee, isReadOnly, transactionID, a return; } - Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.MONEY_REQUEST_ATTENDEE.getRoute(action, iouType, transactionID, reportID))); + Navigation.navigate(ROUTES.MONEY_REQUEST_ATTENDEE.getRoute(action, iouType, transactionID, reportID, Navigation.getActiveRoute())); }} interactive={!isReadOnly} brickRoadIndicator={shouldDisplayAttendeesError ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined} diff --git a/src/components/MoneyRequestConfirmationList/sections/CategoryField.tsx b/src/components/MoneyRequestConfirmationList/sections/CategoryField.tsx index 4f70942ac203..098a4d5225f7 100644 --- a/src/components/MoneyRequestConfirmationList/sections/CategoryField.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/CategoryField.tsx @@ -5,12 +5,11 @@ import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useThemeStyles from '@hooks/useThemeStyles'; import {getDecodedLeafCategoryName} from '@libs/CategoryUtils'; -import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import Navigation from '@libs/Navigation/Navigation'; import CONST from '@src/CONST'; import type {IOUAction, IOUType} from '@src/CONST'; import type {TranslationPaths} from '@src/languages/types'; -import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES'; +import ROUTES from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; import {categoryStateSelector} from './selectors'; import useTransactionSelector from './useTransactionSelector'; @@ -79,24 +78,23 @@ function CategoryField({ if (shouldNavigateToUpgradePath) { Navigation.navigate( - createDynamicRoute( - DYNAMIC_ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ - action, - iouType, - transactionID, - reportID, - upgradePath: CONST.UPGRADE_PATHS.CATEGORIES, - }), - ), + ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ + action, + iouType, + transactionID, + reportID, + backTo: ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute(action, iouType, transactionID, reportID, Navigation.getActiveRoute(), reportActionID), + upgradePath: CONST.UPGRADE_PATHS.CATEGORIES, + }), ); } else if (!policy && shouldSelectPolicy) { Navigation.navigate( ROUTES.SET_DEFAULT_WORKSPACE.getRoute( - createDynamicRoute(DYNAMIC_ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute(action, iouType, transactionID, reportID, reportActionID)), + ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute(action, iouType, transactionID, reportID, Navigation.getActiveRoute(), reportActionID), ), ); } else { - Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute(action, iouType, transactionID, reportID, reportActionID))); + Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute(action, iouType, transactionID, reportID, Navigation.getActiveRoute(), reportActionID)); } }} style={[styles.moneyRequestMenuItem]} diff --git a/src/components/MoneyRequestConfirmationList/sections/RateField.tsx b/src/components/MoneyRequestConfirmationList/sections/RateField.tsx index 3ea42ee730ad..3e42b63c714f 100644 --- a/src/components/MoneyRequestConfirmationList/sections/RateField.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/RateField.tsx @@ -8,12 +8,11 @@ import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useThemeStyles from '@hooks/useThemeStyles'; import DistanceRequestUtils from '@libs/DistanceRequestUtils'; -import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import Navigation from '@libs/Navigation/Navigation'; import variables from '@styles/variables'; import CONST from '@src/CONST'; import type {IOUAction, IOUType} from '@src/CONST'; -import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES'; +import ROUTES from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; import type {Unit} from '@src/types/onyx/Policy'; @@ -88,16 +87,15 @@ function RateField({ if ((!isPolicyExpenseChat && !isTrackExpense) || (shouldNavigateToUpgradePath && isTrackExpense)) { Navigation.navigate( - createDynamicRoute( - DYNAMIC_ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ - action, - iouType, - transactionID, - reportID, - upgradePath: CONST.UPGRADE_PATHS.DISTANCE_RATES, - shouldSubmitExpense: !isTrackExpense, - }), - ), + ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ + action, + iouType, + transactionID, + reportID, + upgradePath: CONST.UPGRADE_PATHS.DISTANCE_RATES, + backTo: Navigation.getActiveRoute(), + shouldSubmitExpense: !isTrackExpense, + }), ); } else if (!policy && shouldSelectPolicy && isTrackExpense) { Navigation.navigate( diff --git a/src/components/MoneyRequestConfirmationList/sections/TaxFields.tsx b/src/components/MoneyRequestConfirmationList/sections/TaxFields.tsx index fdc67c1ce3c8..c1a23e52decb 100644 --- a/src/components/MoneyRequestConfirmationList/sections/TaxFields.tsx +++ b/src/components/MoneyRequestConfirmationList/sections/TaxFields.tsx @@ -12,7 +12,6 @@ import useThemeStyles from '@hooks/useThemeStyles'; import {setMoneyRequestTaxAmount} from '@libs/actions/IOU/MoneyRequest'; import {convertToBackendAmount, convertToFrontendAmountAsString, getLocalizedCurrencySymbol} from '@libs/CurrencyUtils'; import {isMovingTransactionFromTrackExpense} from '@libs/IOUUtils'; -import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import Navigation from '@libs/Navigation/Navigation'; import {getCalculatedTaxAmount, getTaxAmount, getTaxRateTitle} from '@libs/TransactionUtils'; import {setDraftSplitTransaction} from '@userActions/IOU/Split'; @@ -20,7 +19,7 @@ import CONST from '@src/CONST'; import type {IOUAction, IOUType} from '@src/CONST'; import type {TranslationPaths} from '@src/languages/types'; import ONYXKEYS from '@src/ONYXKEYS'; -import {DYNAMIC_ROUTES} from '@src/ROUTES'; +import ROUTES from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; import {taxSliceSelector} from './selectors'; import useTransactionSelector from './useTransactionSelector'; @@ -118,7 +117,7 @@ function TaxFields({policy, policyForMovingExpenses, iouCurrencyCode, canModifyT return; } - Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.MONEY_REQUEST_STEP_TAX_RATE.getRoute(action, iouType, transactionID, reportID))); + Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_TAX_RATE.getRoute(action, iouType, transactionID, reportID, Navigation.getActiveRoute())); }} disabled={didConfirm} interactive={canModifyTaxFields} @@ -157,7 +156,7 @@ function TaxFields({policy, policyForMovingExpenses, iouCurrencyCode, canModifyT return; } - Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.MONEY_REQUEST_STEP_TAX_AMOUNT.getRoute(action, iouType, transactionID, reportID))); + Navigation.navigate(ROUTES.MONEY_REQUEST_STEP_TAX_AMOUNT.getRoute(action, iouType, transactionID, reportID, Navigation.getActiveRoute())); }} disabled={didConfirm} interactive={canModifyTaxFields} diff --git a/src/components/MoneyRequestHeaderSecondaryActions.tsx b/src/components/MoneyRequestHeaderSecondaryActions.tsx index f7bcae5c1ce9..4344a67f75f4 100644 --- a/src/components/MoneyRequestHeaderSecondaryActions.tsx +++ b/src/components/MoneyRequestHeaderSecondaryActions.tsx @@ -35,7 +35,6 @@ import initSplitExpense from '@libs/actions/SplitExpenses'; import {setNameValuePair} from '@libs/actions/User'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {getExistingTransactionID} from '@libs/IOUUtils'; -import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import Navigation from '@libs/Navigation/Navigation'; import type {PlatformStackRouteProp} from '@libs/Navigation/PlatformStackNavigation/types'; import type {ReportsSplitNavigatorParamList, RightModalNavigatorParamList} from '@libs/Navigation/types'; @@ -67,7 +66,7 @@ import {dismissRejectUseExplanation} from '@userActions/IOU/RejectMoneyRequest'; import {setDeleteTransactionNavigateBackUrl} from '@userActions/Report'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES'; +import ROUTES from '@src/ROUTES'; import SCREENS from '@src/SCREENS'; import type {Transaction} from '@src/types/onyx'; import ButtonWithDropdownMenu from './ButtonWithDropdownMenu'; @@ -531,15 +530,13 @@ function MoneyRequestHeaderSecondaryActions({reportID, onBackButtonPress}: Money const iouType = isExpenseReport(parentReport) ? CONST.IOU.TYPE.SUBMIT : CONST.IOU.TYPE.TRACK; if (shouldNavigateToUpgradePath && reportID) { Navigation.navigate( - createDynamicRoute( - DYNAMIC_ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ - action: CONST.IOU.ACTION.EDIT, - iouType, - transactionID: transaction.transactionID, - reportID, - upgradePath: CONST.UPGRADE_PATHS.REPORTS, - }), - ), + ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ + action: CONST.IOU.ACTION.EDIT, + iouType, + transactionID: transaction.transactionID, + reportID, + upgradePath: CONST.UPGRADE_PATHS.REPORTS, + }), ); return; } diff --git a/src/components/Navigation/QuickCreationActionsBar/index.tsx b/src/components/Navigation/QuickCreationActionsBar/index.tsx index 10ee065bd6fd..7b57025a2b28 100644 --- a/src/components/Navigation/QuickCreationActionsBar/index.tsx +++ b/src/components/Navigation/QuickCreationActionsBar/index.tsx @@ -17,7 +17,6 @@ import useThemeStyles from '@hooks/useThemeStyles'; import {startDistanceRequest, startMoneyRequest} from '@libs/actions/IOU/MoneyRequest'; import {createNewReport} from '@libs/actions/Report'; import interceptAnonymousUser from '@libs/interceptAnonymousUser'; -import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import getCreateReportRoute, {getReportsRootRoute, navigateToCreateReportWorkspaceSelection} from '@libs/Navigation/helpers/getCreateReportRoute'; import Navigation from '@libs/Navigation/Navigation'; import {openTravelDotLink} from '@libs/openTravelDotLink'; @@ -27,7 +26,7 @@ import {generateReportID, hasViolations as hasViolationsReportUtils} from '@libs import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils'; import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; -import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES'; +import ROUTES from '@src/ROUTES'; import {primaryLoginSelector} from '@src/selectors/Account'; import type * as OnyxTypes from '@src/types/onyx'; @@ -132,15 +131,13 @@ function QuickCreationActionsBar() { const freshReportID = generateReportID(); const freshTransactionID = generateReportID(); Navigation.navigate( - createDynamicRoute( - DYNAMIC_ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ - action: CONST.IOU.ACTION.CREATE, - iouType: CONST.IOU.TYPE.CREATE, - transactionID: freshTransactionID, - reportID: freshReportID, - upgradePath: CONST.UPGRADE_PATHS.REPORTS, - }), - ), + ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ + action: CONST.IOU.ACTION.CREATE, + iouType: CONST.IOU.TYPE.CREATE, + transactionID: freshTransactionID, + reportID: freshReportID, + upgradePath: CONST.UPGRADE_PATHS.REPORTS, + }), ); return; } diff --git a/src/components/ReportActionItem/MoneyRequestView.tsx b/src/components/ReportActionItem/MoneyRequestView.tsx index 24050e9d857a..7dbfc194e101 100644 --- a/src/components/ReportActionItem/MoneyRequestView.tsx +++ b/src/components/ReportActionItem/MoneyRequestView.tsx @@ -61,7 +61,6 @@ import DistanceRequestUtils from '@libs/DistanceRequestUtils'; import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID'; import {getRateFromMerchant} from '@libs/MergeTransactionUtils'; import {isBillableEnabledOnPolicy, isSingleTransactionReport} from '@libs/MoneyRequestReportUtils'; -import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute'; import {hasEnabledOptions} from '@libs/OptionsListUtils'; import Parser from '@libs/Parser'; import { @@ -139,7 +138,7 @@ import variables from '@styles/variables'; import CONST from '@src/CONST'; import type {TranslationPaths} from '@src/languages/types'; import ONYXKEYS from '@src/ONYXKEYS'; -import ROUTES, {DYNAMIC_ROUTES} from '@src/ROUTES'; +import ROUTES from '@src/ROUTES'; import type * as OnyxTypes from '@src/types/onyx'; import type {TransactionPendingFieldsKey} from '@src/types/onyx/Transaction'; import {isEmptyObject} from '@src/types/utils/EmptyObject'; @@ -933,15 +932,13 @@ function MoneyRequestView({ if (isTrackExpense) { if (shouldNavigateToUpgradePath && transactionThreadReport) { Navigation.navigate( - createDynamicRoute( - DYNAMIC_ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ - action: CONST.IOU.ACTION.EDIT, - iouType, - transactionID: transaction.transactionID, - reportID: transactionThreadReport?.reportID, - upgradePath: CONST.UPGRADE_PATHS.DISTANCE_RATES, - }), - ), + ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ + action: CONST.IOU.ACTION.EDIT, + iouType, + transactionID: transaction.transactionID, + reportID: transactionThreadReport?.reportID, + upgradePath: CONST.UPGRADE_PATHS.DISTANCE_RATES, + }), ); return; } @@ -1249,33 +1246,41 @@ function MoneyRequestView({ if (shouldNavigateToUpgradePath && transactionThreadReport) { Navigation.navigate( - createDynamicRoute( - DYNAMIC_ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ - action: CONST.IOU.ACTION.EDIT, + ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ + action: CONST.IOU.ACTION.EDIT, + iouType, + transactionID: transaction.transactionID, + reportID: transactionThreadReport?.reportID, + upgradePath: CONST.UPGRADE_PATHS.CATEGORIES, + backTo: ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute( + CONST.IOU.ACTION.EDIT, iouType, - transactionID: transaction.transactionID, - reportID: transactionThreadReport?.reportID, - upgradePath: CONST.UPGRADE_PATHS.CATEGORIES, - }), - ), + transaction.transactionID, + transactionThreadReport?.reportID, + Navigation.getActiveRoute(), + ), + }), ); } else if (!policy && shouldSelectPolicy) { Navigation.navigate( ROUTES.SET_DEFAULT_WORKSPACE.getRoute( - createDynamicRoute( - DYNAMIC_ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute( - CONST.IOU.ACTION.EDIT, - iouType, - transaction.transactionID, - transactionThreadReport?.reportID, - ), + ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute( + CONST.IOU.ACTION.EDIT, + iouType, + transaction.transactionID, + transactionThreadReport?.reportID, + Navigation.getActiveRoute(), ), ), ); } else { Navigation.navigate( - createDynamicRoute( - DYNAMIC_ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction.transactionID, transactionThreadReport?.reportID), + ROUTES.MONEY_REQUEST_STEP_CATEGORY.getRoute( + CONST.IOU.ACTION.EDIT, + iouType, + transaction.transactionID, + transactionThreadReport?.reportID, + Navigation.getActiveRoute(), ), ); } @@ -1337,8 +1342,12 @@ function MoneyRequestView({ } Navigation.navigate( - createDynamicRoute( - DYNAMIC_ROUTES.MONEY_REQUEST_STEP_TAX_RATE.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction.transactionID, transactionThreadReport?.reportID), + ROUTES.MONEY_REQUEST_STEP_TAX_RATE.getRoute( + CONST.IOU.ACTION.EDIT, + iouType, + transaction.transactionID, + transactionThreadReport?.reportID, + getReportRHPActiveRoute(), ), ); }} @@ -1365,8 +1374,12 @@ function MoneyRequestView({ } Navigation.navigate( - createDynamicRoute( - DYNAMIC_ROUTES.MONEY_REQUEST_STEP_TAX_AMOUNT.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction.transactionID, transactionThreadReport?.reportID), + ROUTES.MONEY_REQUEST_STEP_TAX_AMOUNT.getRoute( + CONST.IOU.ACTION.EDIT, + iouType, + transaction.transactionID, + transactionThreadReport?.reportID, + getReportRHPActiveRoute(), ), ); }} @@ -1402,11 +1415,7 @@ function MoneyRequestView({ style={[styles.moneyRequestMenuItem]} titleStyle={styles.flex1} onPress={() => { - Navigation.navigate( - createDynamicRoute( - DYNAMIC_ROUTES.MONEY_REQUEST_ATTENDEE.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction.transactionID, transactionThreadReport?.reportID), - ), - ); + Navigation.navigate(ROUTES.MONEY_REQUEST_ATTENDEE.getRoute(CONST.IOU.ACTION.EDIT, iouType, transaction.transactionID, transactionThreadReport?.reportID)); }} brickRoadIndicator={getErrorForField('attendees') ? CONST.BRICK_ROAD_INDICATOR_STATUS.ERROR : undefined} errorText={getErrorForField('attendees')} @@ -1487,15 +1496,13 @@ function MoneyRequestView({ } if (shouldNavigateToUpgradePath) { Navigation.navigate( - createDynamicRoute( - DYNAMIC_ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ - iouType, - action: CONST.IOU.ACTION.EDIT, - transactionID: transaction?.transactionID, - reportID: transactionThreadReport?.reportID, - upgradePath: CONST.UPGRADE_PATHS.REPORTS, - }), - ), + ROUTES.MONEY_REQUEST_UPGRADE.getRoute({ + iouType, + action: CONST.IOU.ACTION.EDIT, + transactionID: transaction?.transactionID, + reportID: transactionThreadReport?.reportID, + upgradePath: CONST.UPGRADE_PATHS.REPORTS, + }), ); return; } diff --git a/src/components/Search/FilterComponents/ListFilterViewWrapper.tsx b/src/components/Search/FilterComponents/ListFilterViewWrapper.tsx index 5b7fe6670a0d..e4a04a300361 100644 --- a/src/components/Search/FilterComponents/ListFilterViewWrapper.tsx +++ b/src/components/Search/FilterComponents/ListFilterViewWrapper.tsx @@ -13,21 +13,19 @@ type ListFilterWrapperProps = { hasHeader?: boolean; isSearchable?: boolean; extraHeight?: number; - shouldUseFixedPopoverHeight?: boolean; }; -function ListFilterView({children, itemCount, itemHeight, hasTitle = true, hasHeader, isSearchable, extraHeight, shouldUseFixedPopoverHeight}: ListFilterWrapperProps) { +function ListFilterView({children, itemCount, itemHeight, hasTitle = true, hasHeader, isSearchable, extraHeight}: ListFilterWrapperProps) { const styles = useThemeStyles(); const {windowHeight} = useWindowDimensions(); // eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth const {isSmallScreenWidth, isInLandscapeMode} = useResponsiveLayout(); - const heightItemCount = shouldUseFixedPopoverHeight ? Number.MAX_SAFE_INTEGER : itemCount || 1; return ( = SearchFilterCommonProps | undefi /** Custom height for each item in the list */ itemHeight?: number; - shouldUseFixedPopoverHeight?: boolean; allowDeselect?: boolean; hasTitle?: boolean; hasHeader?: boolean; @@ -48,7 +47,6 @@ function SingleSelect({ hasTitle, hasHeader, itemHeight, - shouldUseFixedPopoverHeight, footer, allowDeselect, onChange, @@ -123,7 +121,6 @@ function SingleSelect({ hasTitle={hasTitle} isSearchable={isSearchable} itemHeight={itemHeight ?? variables.optionRowHeight} - shouldUseFixedPopoverHeight={shouldUseFixedPopoverHeight} > void; - - /** Function to call to close the overlay */ - closeOverlay: () => void; - - /** Function to call when a currency is selected */ - onChange: (item: SingleSelectItem | undefined) => void; - - /** The currently selected currency code */ - value?: string; - - /** The currency code to select when reset is clicked */ - defaultValue?: string; - - /** Search input placeholder */ - searchPlaceholder?: string; - - /** Whether the currency list should be visible */ - shouldShowList?: boolean; -}; - -function CurrencyPopup({label, onBackButtonPress, onChange, closeOverlay, value, defaultValue, searchPlaceholder, shouldShowList}: CurrencyPopupProps) { - const {currencyList} = useCurrencyListState(); - const {getCurrencySymbol} = useCurrencyListActions(); - - const currencyOptions = getCurrencyOptions(currencyList, getCurrencySymbol); - const currencyValue = currencyOptions.find((option) => option.value === value); - - return ( - - ); -} - -export default CurrencyPopup; diff --git a/src/components/Search/FilterDropdowns/DisplayPopup.tsx b/src/components/Search/FilterDropdowns/DisplayPopup.tsx index ed2e083a79eb..2ba5a61e2b6e 100644 --- a/src/components/Search/FilterDropdowns/DisplayPopup.tsx +++ b/src/components/Search/FilterDropdowns/DisplayPopup.tsx @@ -20,8 +20,8 @@ import ROUTES from '@src/ROUTES'; import type {SearchAdvancedFiltersForm} from '@src/types/form'; import type {SearchResults} from '@src/types/onyx'; import {getEmptyObject} from '@src/types/utils/EmptyObject'; -import CurrencyPopup from './CurrencyPopup'; import GroupByPopup from './GroupByPopup'; +import GroupCurrencyPopup from './GroupCurrencyPopup'; import SingleSelectPopup from './SingleSelectPopup'; import SortByPopup from './SortByPopup'; import SortOrderPopup from './SortOrderPopup'; @@ -187,13 +187,10 @@ function DisplayPopup({queryJSON, searchResults, closeOverlay, onSort}: DisplayP ); case CONST.SEARCH.SYNTAX_FILTER_KEYS.GROUP_CURRENCY: return ( - updateFilterForm({groupCurrency: item?.value})} - label={translate('common.groupCurrency')} onBackButtonPress={goBack} closeOverlay={closeOverlay} - searchPlaceholder={translate('common.groupCurrency')} /> ); case CONST.SEARCH.SYNTAX_ROOT_KEYS.VIEW: diff --git a/src/components/Search/FilterDropdowns/GroupCurrencyPopup.tsx b/src/components/Search/FilterDropdowns/GroupCurrencyPopup.tsx new file mode 100644 index 000000000000..bddcbc6084fb --- /dev/null +++ b/src/components/Search/FilterDropdowns/GroupCurrencyPopup.tsx @@ -0,0 +1,45 @@ +import React from 'react'; +import type {OnyxEntry} from 'react-native-onyx'; +import {useCurrencyListActions, useCurrencyListState} from '@components/CurrencyListContextProvider'; +import type {SingleSelectItem} from '@components/Search/FilterComponents/SingleSelect'; +import useLocalize from '@hooks/useLocalize'; +import useOnyx from '@hooks/useOnyx'; +import {getCurrencyOptions} from '@libs/SearchUIUtils'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {SearchAdvancedFiltersForm} from '@src/types/form'; +import SingleSelectPopup from './SingleSelectPopup'; + +type GroupCurrencyPopupProps = { + onBackButtonPress: () => void; + closeOverlay: () => void; + onChange: (item: SingleSelectItem | undefined) => void; +}; + +function filterGroupCurrencySelector(searchAdvancedFiltersForm: OnyxEntry) { + return searchAdvancedFiltersForm?.groupCurrency; +} + +function GroupCurrencyPopup({onBackButtonPress, onChange, closeOverlay}: GroupCurrencyPopupProps) { + const {translate} = useLocalize(); + const {currencyList} = useCurrencyListState(); + const {getCurrencySymbol} = useCurrencyListActions(); + const groupCurrencyOptions = getCurrencyOptions(currencyList, getCurrencySymbol); + const [groupCurrency] = useOnyx(ONYXKEYS.FORMS.SEARCH_ADVANCED_FILTERS_FORM, {selector: filterGroupCurrencySelector}); + + const groupCurrencyValue = groupCurrencyOptions.find((option) => option.value === groupCurrency); + + return ( + + ); +} + +export default GroupCurrencyPopup; diff --git a/src/components/Search/FilterDropdowns/SingleSelectPopup.tsx b/src/components/Search/FilterDropdowns/SingleSelectPopup.tsx index 2e3e0b2894a6..abc9fb660b64 100644 --- a/src/components/Search/FilterDropdowns/SingleSelectPopup.tsx +++ b/src/components/Search/FilterDropdowns/SingleSelectPopup.tsx @@ -44,9 +44,6 @@ type SingleSelectPopupProps = { /** Whether SelectionList of popup should stay mounted when popup is not visible. */ shouldShowList?: boolean; - - /** Whether the popover should keep a fixed height while filtering results. */ - shouldUseFixedPopoverHeight?: boolean; }; function SingleSelectPopup({ @@ -63,7 +60,6 @@ function SingleSelectPopup({ selectionListStyle, itemHeight, shouldShowList = true, - shouldUseFixedPopoverHeight, }: SingleSelectPopupProps) { const [selectedItem, setSelectedItem] = useState(value); @@ -99,7 +95,6 @@ function SingleSelectPopup({ selectionListStyle={selectionListStyle} shouldShowList={shouldShowList} itemHeight={itemHeight} - shouldUseFixedPopoverHeight={shouldUseFixedPopoverHeight} /> diff --git a/src/components/Search/SearchPageFooter.tsx b/src/components/Search/SearchPageFooter.tsx index d341d59c0812..5582042ab6d6 100644 --- a/src/components/Search/SearchPageFooter.tsx +++ b/src/components/Search/SearchPageFooter.tsx @@ -1,147 +1,52 @@ -import React, {useMemo, useState} from 'react'; -import {StyleSheet, View} from 'react-native'; -import Button from '@components/Button'; +import React, {useMemo} from 'react'; +import {View} from 'react-native'; import Text from '@components/Text'; import {useCurrencyListActions} from '@hooks/useCurrencyList'; -import useKeyboardShortcut from '@hooks/useKeyboardShortcut'; -import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset'; import useLocalize from '@hooks/useLocalize'; import useNetwork from '@hooks/useNetwork'; import useResponsiveLayout from '@hooks/useResponsiveLayout'; import useStyleUtils from '@hooks/useStyleUtils'; import useTheme from '@hooks/useTheme'; import useThemeStyles from '@hooks/useThemeStyles'; -import CONST from '@src/CONST'; -import type {SingleSelectItem} from './FilterComponents/SingleSelect'; -import CurrencyPopup from './FilterDropdowns/CurrencyPopup'; -import FilterPopupButton from './FilterDropdowns/FilterPopupButton'; -import type {ButtonComponentProps, FilterPopupButtonProps} from './FilterDropdowns/FilterPopupButton'; -import SearchPageFooterSkeleton from './SearchPageFooterSkeleton'; type SearchPageFooterProps = { - /** Number of expenses represented by the footer total */ count: number | undefined; - - /** Total amount to display in the footer */ total: number | undefined; - - /** Currency code for the displayed total */ currency: string | undefined; - - /** Currency code used when the footer currency is reset */ - defaultCurrency: string | undefined; - - /** Whether the footer total is currently refreshing */ - isTotalLoading: boolean; - - /** Function to call when the footer currency changes */ - onCurrencyChange: (currency: string | undefined) => void; - - /** Whether the footer currency picker should be available */ - shouldAllowCurrencyChange: boolean; }; -function SearchPageFooter({count, total, currency, defaultCurrency, isTotalLoading, onCurrencyChange, shouldAllowCurrencyChange}: SearchPageFooterProps) { +function SearchPageFooter({count, total, currency}: SearchPageFooterProps) { const theme = useTheme(); const styles = useThemeStyles(); const StyleUtils = useStyleUtils(); const {translate} = useLocalize(); const {convertToDisplayString} = useCurrencyListActions(); const {isOffline} = useNetwork(); - const icons = useMemoizedLazyExpensifyIcons(['DownArrow']); const {shouldUseNarrowLayout} = useResponsiveLayout(); - const [isTotalButtonFocused, setIsTotalButtonFocused] = useState(false); - const valueTextStyle = useMemo(() => (isOffline ? [styles.textLabelSupporting, styles.labelStrong] : [styles.labelStrong]), [isOffline, styles]); - // The SearchList registers a global Enter shortcut that opens the focused expense. While the total button is focused, - // claim Enter at top priority without bubbling so Enter only opens the currency popover instead of also opening the expense. - useKeyboardShortcut(CONST.KEYBOARD_SHORTCUTS.ENTER, () => {}, {isActive: isTotalButtonFocused, shouldBubble: false, shouldPreventDefault: false}); - - const handleCurrencyChange = (item: SingleSelectItem | undefined) => { - if (isOffline) { - return; - } - - const nextCurrency = item?.value ?? defaultCurrency; - if (!nextCurrency) { - return; - } - onCurrencyChange(nextCurrency === defaultCurrency ? undefined : nextCurrency); - }; - - const renderCurrencyPopup: FilterPopupButtonProps['PopoverComponent'] = ({closeOverlay, isExpanded}) => ( - - ); - - const totalButton = (props: ButtonComponentProps) => ( -