Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide autocomplete suggestions in SearchRouterList #51237

Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
433ec49
autocomplete POC
SzymczakJ Oct 14, 2024
6578dde
Merge branch 'main' into @szymczak/autocomplete-search-router
SzymczakJ Oct 21, 2024
9fd9ead
Merge branch 'main' into @szymczak/autocomplete-search-router
SzymczakJ Oct 22, 2024
2b63c0e
remove previously added parser
SzymczakJ Oct 22, 2024
3f748b5
remove autocomplete list behaviour
SzymczakJ Oct 22, 2024
c58aa27
remove unused CONST values
SzymczakJ Oct 22, 2024
a354bdc
Merge branch 'main' into @szymczak/autocomplete-search-router
SzymczakJ Oct 23, 2024
157c3e1
move autocomplete functions to autocompleteUtils
SzymczakJ Oct 23, 2024
ffd2995
autosuggest recent categories and currencies when textinput is empty
SzymczakJ Oct 23, 2024
fb4359b
fix pr comments
SzymczakJ Oct 23, 2024
00d61c6
autosuggest tags
SzymczakJ Oct 23, 2024
dc8f993
put autocomplete suggestions into input
SzymczakJ Oct 24, 2024
8cf4690
ignore already autocompleted values
SzymczakJ Oct 24, 2024
3354af2
autocomplete "in:" key
SzymczakJ Oct 24, 2024
3ec1802
fix SearchRouterInput bug
SzymczakJ Oct 24, 2024
94c259f
fix PR comments
SzymczakJ Oct 24, 2024
4002093
add arrowSelectionAutocomplete logic
SzymczakJ Oct 25, 2024
0dc345c
sort autocomplete values
SzymczakJ Oct 25, 2024
11ee9da
clean up code
SzymczakJ Oct 25, 2024
affe34f
Merge branch 'main' into @szymczak/autocomplete-search-router
SzymczakJ Oct 25, 2024
0d6f2ce
fix type errors
SzymczakJ Oct 25, 2024
ae7a667
Merge branch 'main' into @szymczak/autocomplete-search-router
SzymczakJ Oct 25, 2024
d834b70
Merge branch 'main' into @szymczak/autocomplete-search-router
SzymczakJ Oct 28, 2024
c1e1bc5
make autocomplete suggestions insensitive
SzymczakJ Oct 28, 2024
d7b51bb
sanitize search query in search router
SzymczakJ Oct 28, 2024
cf4eb14
fix PR comments
SzymczakJ Oct 29, 2024
73ecc8f
Merge branch 'main' into @szymczak/autocomplete-search-router
SzymczakJ Oct 29, 2024
f66dfee
trim space to allow for autocomplete sugggestion after comma
SzymczakJ Oct 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 156 additions & 3 deletions src/components/Search/SearchRouter/SearchRouter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,31 @@ import debounce from 'lodash/debounce';
import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {View} from 'react-native';
import {useOnyx} from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
import {usePersonalDetails} from '@components/OnyxProvider';
import {useOptionsList} from '@components/OptionListContextProvider';
import type {SearchQueryJSON} from '@components/Search/types';
import type {SelectionListHandle} from '@components/SelectionList/types';
import useActiveWorkspaceFromNavigationState from '@hooks/useActiveWorkspaceFromNavigationState';
import useDebouncedState from '@hooks/useDebouncedState';
import useKeyboardShortcut from '@hooks/useKeyboardShortcut';
import useLocalize from '@hooks/useLocalize';
import usePolicy from '@hooks/usePolicy';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useThemeStyles from '@hooks/useThemeStyles';
import Log from '@libs/Log';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import {getAllTaxRates} from '@libs/PolicyUtils';
import type {OptionData} from '@libs/ReportUtils';
import {
getAutocompleteCategories,
getAutocompleteRecentCategories,
getAutocompleteRecentTags,
getAutocompleteTags,
getAutocompleteTaxList,
parseForAutocomplete,
} from '@libs/SearchAutocompleteUtils';
import * as SearchQueryUtils from '@libs/SearchQueryUtils';
import Navigation from '@navigation/Navigation';
import variables from '@styles/variables';
Expand All @@ -26,9 +38,9 @@ import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import SearchRouterInput from './SearchRouterInput';
import SearchRouterList from './SearchRouterList';
import type {ItemWithQuery} from './SearchRouterList';

const SEARCH_DEBOUNCE_DELAY = 150;

type SearchRouterProps = {
onRouterClose: () => void;
};
Expand All @@ -39,18 +51,54 @@ function SearchRouter({onRouterClose}: SearchRouterProps) {
const [betas] = useOnyx(ONYXKEYS.BETAS);
const [recentSearches] = useOnyx(ONYXKEYS.RECENT_SEARCHES);
const [isSearchingForReports] = useOnyx(ONYXKEYS.IS_SEARCHING_FOR_REPORTS, {initWithStoredValues: false});
const [autocompleteSuggestions, setAutocompleteSuggestions] = useState<ItemWithQuery[] | undefined>([]);

const {shouldUseNarrowLayout} = useResponsiveLayout();
const listRef = useRef<SelectionListHandle>(null);

const taxRates = getAllTaxRates();
const [cardList = {}] = useOnyx(ONYXKEYS.CARD_LIST);

const [textInputValue, debouncedInputValue, setTextInputValue] = useDebouncedState('', 500);
const [userSearchQuery, setUserSearchQuery] = useState<SearchQueryJSON | undefined>(undefined);
const contextualReportID = useNavigationState<Record<string, {reportID: string}>, string | undefined>((state) => {
return state?.routes.at(-1)?.params?.reportID;
});

const activeWorkspaceID = useActiveWorkspaceFromNavigationState();
const policy = usePolicy(activeWorkspaceID);
const typesAutocompleteList = Object.values(CONST.SEARCH.DATA_TYPES);
const statusesAutocompleteList = Object.values({...CONST.SEARCH.STATUS.TRIP, ...CONST.SEARCH.STATUS.INVOICE, ...CONST.SEARCH.STATUS.CHAT, ...CONST.SEARCH.STATUS.TRIP});
SzymczakJ marked this conversation as resolved.
Show resolved Hide resolved
const expenseTypes = Object.values(CONST.SEARCH.TRANSACTION_TYPE);
const allTaxRates = getAllTaxRates();
SzymczakJ marked this conversation as resolved.
Show resolved Hide resolved
const taxAutocompleteList = useMemo(() => getAutocompleteTaxList(allTaxRates, policy), [policy, allTaxRates]);
const [cardList = {}] = useOnyx(ONYXKEYS.CARD_LIST);
const cardsAutocompleteList = Object.values(cardList ?? {}).map((card) => card.bank);
const personalDetails = usePersonalDetails();
const participantsAutocompleteList = Object.values(personalDetails)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good job, but still:
image

😆 but seriously NAB and if we need all this data then we need it

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea, I'm not sure there's a way around it. Maybe we can create a custom hook, useAutocomplete so the logic lives outside the component?

.filter((details) => details && details?.login)
// eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style
.map((details) => details?.login as string);

const [allPolicyCategories] = useOnyx(ONYXKEYS.COLLECTION.POLICY_CATEGORIES);
const [allRecentCategories] = useOnyx(ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_CATEGORIES);
const categoryAutocompleteList = useMemo(() => {
return getAutocompleteCategories(allPolicyCategories, activeWorkspaceID);
}, [activeWorkspaceID, allPolicyCategories]);
const recentCategoriesAutocompleteList = useMemo(() => {
return getAutocompleteRecentCategories(allRecentCategories, activeWorkspaceID);
}, [activeWorkspaceID, allRecentCategories]);

const [currencyList] = useOnyx(ONYXKEYS.CURRENCY_LIST);
const currencyAutocompleteList = Object.keys(currencyList ?? {});
const [recentCurrencyAutocompleteList] = useOnyx(ONYXKEYS.RECENTLY_USED_CURRENCIES);

const [allPoliciesTags] = useOnyx(ONYXKEYS.COLLECTION.POLICY_TAGS);
const [allRecentTags] = useOnyx(ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS);
const tagAutocompleteList = useMemo(() => {
return getAutocompleteTags(allPoliciesTags, activeWorkspaceID);
}, [activeWorkspaceID, allPoliciesTags]);
const recentTagsAutocompleteList = getAutocompleteRecentTags(allRecentTags, activeWorkspaceID);

const sortedRecentSearches = useMemo(() => {
return Object.values(recentSearches ?? {}).sort((a, b) => b.timestamp.localeCompare(a.timestamp));
}, [recentSearches]);
Expand Down Expand Up @@ -106,6 +154,107 @@ function SearchRouter({onRouterClose}: SearchRouterProps) {
setUserSearchQuery(undefined);
};

const updateAutocomplete = useCallback(
(autocompleteValue: string, autocompleteType?: ValueOf<typeof CONST.SEARCH.SYNTAX_ROOT_KEYS & typeof CONST.SEARCH.SYNTAX_FILTER_KEYS>) => {
switch (autocompleteType) {
case 'tag': {
const autocompleteList = autocompleteValue ? tagAutocompleteList : recentTagsAutocompleteList ?? [];
const filteredTags = autocompleteList.filter((tag) => tag?.includes(autocompleteValue));
setAutocompleteSuggestions(
filteredTags.map((tagName) => ({
text: `tag:${tagName}`,
query: `${tagName}`,
})),
);
return;
}
case 'category': {
const autocompleteList = autocompleteValue ? categoryAutocompleteList : recentCategoriesAutocompleteList;
const filteredCategories = autocompleteList.filter((category) => category?.includes(autocompleteValue));
setAutocompleteSuggestions(
filteredCategories.map((categoryName) => ({
text: `category:${categoryName}`,
query: `${categoryName}`,
})),
);
return;
}
case 'currency': {
const autocompleteList = autocompleteValue ? currencyAutocompleteList : recentCurrencyAutocompleteList ?? [];
const filteredCurrencies = autocompleteList.filter((currency) => currency?.includes(autocompleteValue));
setAutocompleteSuggestions(
filteredCurrencies.map((currencyName) => ({
text: `currency:${currencyName}`,
query: `${currencyName}`,
})),
);
return;
}
case 'taxRate': {
const filteredTaxRates = taxAutocompleteList.filter((tax) => tax.includes(autocompleteValue));
setAutocompleteSuggestions(filteredTaxRates.map((tax) => ({text: `type:${tax}`, query: `${tax}`})));
return;
}
case 'from': {
const filteredParticipants = participantsAutocompleteList.filter((participant) => participant.includes(autocompleteValue));
setAutocompleteSuggestions(filteredParticipants.map((participant) => ({text: `from:${participant}`, query: `${participant}`})));
return;
}
case 'to': {
const filteredParticipants = participantsAutocompleteList.filter((participant) => participant.includes(autocompleteValue));
setAutocompleteSuggestions(filteredParticipants.map((participant) => ({text: `to:${participant}`, query: `${participant}`})));
return;
}
case 'type': {
const filteredTypes = typesAutocompleteList.filter((type) => type.includes(autocompleteValue));
setAutocompleteSuggestions(filteredTypes.map((type) => ({text: `type:${type}`, query: `${type}`})));
return;
}
case 'status': {
const filteredStatuses = statusesAutocompleteList.filter((status) => status.includes(autocompleteValue));
setAutocompleteSuggestions(filteredStatuses.map((status) => ({text: `status:${status}`, query: `${status}`})));
return;
}
case 'expenseType': {
const filteredExpenseTypes = expenseTypes.filter((expenseType) => expenseType.includes(autocompleteValue));
setAutocompleteSuggestions(
filteredExpenseTypes.map((expenseType) => ({
text: `expenseType:${expenseType}`,
query: `${expenseType}`,
})),
);
return;
}
case 'cardID': {
const filteredCards = cardsAutocompleteList.filter((card) => card.includes(autocompleteValue));
setAutocompleteSuggestions(
filteredCards.map((card) => ({
text: `expenseType:${card}`,
query: `${card}`,
})),
);
return;
}
default:
setAutocompleteSuggestions(undefined);
}
},
[
tagAutocompleteList,
recentTagsAutocompleteList,
categoryAutocompleteList,
recentCategoriesAutocompleteList,
currencyAutocompleteList,
recentCurrencyAutocompleteList,
taxAutocompleteList,
participantsAutocompleteList,
typesAutocompleteList,
statusesAutocompleteList,
expenseTypes,
cardsAutocompleteList,
],
);

const onSearchChange = useMemo(
// eslint-disable-next-line react-compiler/react-compiler
() =>
Expand All @@ -115,6 +264,9 @@ function SearchRouter({onRouterClose}: SearchRouterProps) {
listRef.current?.updateAndScrollToFocusedIndex(-1);
return;
}
const autocompleteParsedQuery = parseForAutocomplete(userQuery);
updateAutocomplete(autocompleteParsedQuery?.autocomplete?.value ?? '', autocompleteParsedQuery?.autocomplete?.key);

listRef.current?.updateAndScrollToFocusedIndex(0);
const queryJSON = SearchQueryUtils.buildSearchQueryJSON(userQuery);

Expand All @@ -126,7 +278,7 @@ function SearchRouter({onRouterClose}: SearchRouterProps) {
}, SEARCH_DEBOUNCE_DELAY),
// eslint-disable-next-line react-compiler/react-compiler
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
[updateAutocomplete],
);

const updateUserSearchQuery = (newSearchQuery: string) => {
Expand Down Expand Up @@ -194,6 +346,7 @@ function SearchRouter({onRouterClose}: SearchRouterProps) {
reportForContextualSearch={contextualReportData}
recentSearches={sortedRecentSearches?.slice(0, 5)}
recentReports={recentReports}
autocompleteItems={autocompleteSuggestions}
onSearchSubmit={onSearchSubmit}
updateUserSearchQuery={updateUserSearchQuery}
closeAndClearRouter={closeAndClearRouter}
Expand Down
19 changes: 18 additions & 1 deletion src/components/Search/SearchRouter/SearchRouterList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import ROUTES from '@src/ROUTES';

type ItemWithQuery = {
query: string;
text?: string;
};

type SearchRouterListProps = {
Expand All @@ -37,6 +38,9 @@ type SearchRouterListProps = {
/** Recent reports */
recentReports: OptionData[];

/** Autocomplete items */
autocompleteItems: ItemWithQuery[] | undefined;

/** Callback to submit query when selecting a list item */
onSearchSubmit: (query: SearchQueryJSON | undefined) => void;

Expand Down Expand Up @@ -91,7 +95,7 @@ function SearchRouterItem(props: UserListItemProps<OptionData> | SearchQueryList
}

function SearchRouterList(
{currentQuery, reportForContextualSearch, recentSearches, recentReports, onSearchSubmit, updateUserSearchQuery, closeAndClearRouter}: SearchRouterListProps,
{currentQuery, reportForContextualSearch, recentSearches, autocompleteItems, recentReports, onSearchSubmit, updateUserSearchQuery, closeAndClearRouter}: SearchRouterListProps,
ref: ForwardedRef<SelectionListHandle>,
) {
const styles = useThemeStyles();
Expand Down Expand Up @@ -133,6 +137,19 @@ function SearchRouterList(
});
}

const autocompleteData = autocompleteItems?.map(({text, query}) => {
return {
text,
singleIcon: Expensicons.MagnifyingGlass,
query,
keyForList: query,
};
});

if (autocompleteData && autocompleteData.length > 0) {
sections.push({title: 'Autocomplete', data: autocompleteData});
SzymczakJ marked this conversation as resolved.
Show resolved Hide resolved
}

const recentSearchesData = recentSearches?.map(({query, timestamp}) => {
const searchQueryJSON = SearchQueryUtils.buildSearchQueryJSON(query);
return {
Expand Down
10 changes: 10 additions & 0 deletions src/components/Search/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,15 @@ type SearchQueryJSON = {
flatFilters: QueryFilters;
} & SearchQueryAST;

type SearchAutocompleteResult = {
autocomplete: {
key: ValueOf<typeof CONST.SEARCH.SYNTAX_FILTER_KEYS>;
length: number;
start: number;
value: string;
};
};

export type {
SelectedTransactionInfo,
SelectedTransactions,
Expand All @@ -97,4 +106,5 @@ export type {
InvoiceSearchStatus,
TripSearchStatus,
ChatSearchStatus,
SearchAutocompleteResult,
};
71 changes: 71 additions & 0 deletions src/libs/SearchAutocompleteUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import type {SearchAutocompleteResult} from '@components/Search/types';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Policy, PolicyCategories, PolicyTagLists, RecentlyUsedCategories, RecentlyUsedTags} from '@src/types/onyx';
import {getTagNamesFromTagsLists} from './PolicyUtils';
import * as autocompleteParser from './SearchParser/autocompleteParser';

function parseForAutocomplete(text: string) {
try {
const parsedAutocomplete = autocompleteParser.parse(text) as SearchAutocompleteResult;
return parsedAutocomplete;
} catch (e) {
console.error(`Error when parsing autocopmlete query}"`, e);
SzymczakJ marked this conversation as resolved.
Show resolved Hide resolved
}
}

function getAutocompleteTags(allPoliciesTagsLists: OnyxCollection<PolicyTagLists>, policyID?: string) {
const singlePolicyTagsList: PolicyTagLists | undefined = allPoliciesTagsLists?.[`${ONYXKEYS.COLLECTION.POLICY_TAGS}${policyID}`];
if (!singlePolicyTagsList) {
const uniqueTagNames = new Set<string>();
const tagListsUnpacked = Object.values(allPoliciesTagsLists ?? {}).filter((item) => !!item) as PolicyTagLists[];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is possible to use default argument instead, and do

getAutoCompleteTagsList(allPoliciesTagsLists: OnyxCollection<PolicyTagLists> = {}, policyID?: string)

?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe our hands are tied by OnyxCollection which can be undefined.

tagListsUnpacked
.map(getTagNamesFromTagsLists)
.flat()
.forEach((tag) => uniqueTagNames.add(tag));
return Array.from(uniqueTagNames);
}
return getTagNamesFromTagsLists(singlePolicyTagsList);
}

function getAutocompleteRecentTags(allRecentTags: OnyxCollection<RecentlyUsedTags>, policyID?: string) {
const singlePolicyRecentTags: RecentlyUsedTags | undefined = allRecentTags?.[`${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_TAGS}${policyID}`];
if (!singlePolicyRecentTags) {
const uniqueTagNames = new Set<string>();
Object.values(allRecentTags ?? {})
.map((testVar) => Object.values(testVar ?? {}))
SzymczakJ marked this conversation as resolved.
Show resolved Hide resolved
.flat(2)
.forEach((tag) => uniqueTagNames.add(tag));
return Array.from(uniqueTagNames);
}
return Object.values(singlePolicyRecentTags ?? {}).flat(2);
}

function getAutocompleteCategories(allPolicyCategories: OnyxCollection<PolicyCategories>, policyID?: string) {
const singlePolicyCategories = allPolicyCategories?.[`${ONYXKEYS.COLLECTION.POLICY_CATEGORIES}${policyID}`];
if (!singlePolicyCategories) {
const uniqueCategoryNames = new Set<string>();
Object.values(allPolicyCategories ?? {}).map((policyCategories) => Object.values(policyCategories ?? {}).forEach((category) => uniqueCategoryNames.add(category.name)));
return Array.from(uniqueCategoryNames);
}
return Object.values(singlePolicyCategories ?? {}).map((category) => category.name);
}

function getAutocompleteRecentCategories(allRecentCategories: OnyxCollection<RecentlyUsedCategories>, policyID?: string) {
const singlePolicyRecentCategories = allRecentCategories?.[`${ONYXKEYS.COLLECTION.POLICY_RECENTLY_USED_CATEGORIES}${policyID}`];
if (!singlePolicyRecentCategories) {
const uniqueCategoryNames = new Set<string>();
Object.values(allRecentCategories ?? {}).map((policyCategories) => Object.values(policyCategories ?? {}).forEach((category) => uniqueCategoryNames.add(category)));
return Array.from(uniqueCategoryNames);
}
return Object.values(singlePolicyRecentCategories ?? {}).map((category) => category);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NAB maybe we could DRY the logic in some of these functions too since the logic is 95% identical

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as in #51237 (comment)


function getAutocompleteTaxList(allTaxRates: Record<string, string[]>, policy?: OnyxEntry<Policy>) {
if (policy) {
return Object.keys(policy?.taxRates?.taxes ?? {}).map((taxRateName) => taxRateName);
}
return Object.keys(allTaxRates).map((taxRateName) => taxRateName);
}

export {parseForAutocomplete, getAutocompleteTags, getAutocompleteRecentTags, getAutocompleteCategories, getAutocompleteRecentCategories, getAutocompleteTaxList};
Loading