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 15 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
5 changes: 5 additions & 0 deletions src/CONST.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5730,6 +5730,11 @@ const CONST = {
IN: 'in',
},
EMPTY_VALUE: 'none',
SEARCH_ROUTER_ITEM_TYPE: {
CONTEXTUAL_SUGGESTION: 'contextualSuggestion',
AUTOCOMPLETE_SUGGESTION: 'autocompleteSuggestion',
SEARCH: 'searchItem',
},
},

REFERRER: {
Expand Down
3 changes: 1 addition & 2 deletions src/components/Search/SearchPageHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,8 @@ function HeaderWrapper({icon, children, text, value, isCannedQuery, onSubmit, se
<View style={styles.pr5}>
<SearchRouterInput
value={value}
setValue={setValue}
onSubmit={onSubmit}
updateSearch={() => {}}
updateSearch={setValue}
autoFocus={false}
isFullWidth
wrapperStyle={[styles.searchRouterInputResults, styles.br2]}
Expand Down
222 changes: 184 additions & 38 deletions src/components/Search/SearchRouter/SearchRouter.tsx

Large diffs are not rendered by default.

5 changes: 0 additions & 5 deletions src/components/Search/SearchRouter/SearchRouterInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@ type SearchRouterInputProps = {
/** Value of TextInput */
value: string;

/** Setter to TextInput value */
setValue: (searchTerm: string) => void;

/** Callback to update search in SearchRouter */
updateSearch: (searchTerm: string) => void;

Expand Down Expand Up @@ -58,7 +55,6 @@ type SearchRouterInputProps = {

function SearchRouterInput({
value,
setValue,
updateSearch,
onSubmit = () => {},
routerListRef,
Expand All @@ -79,7 +75,6 @@ function SearchRouterInput({
const offlineMessage: string = isOffline && shouldShowOfflineMessage ? `${translate('common.youAppearToBeOffline')} ${translate('search.resultsAreLimited')}` : '';

const onChangeText = (text: string) => {
setValue(text);
updateSearch(text);
};

Expand Down
72 changes: 54 additions & 18 deletions src/components/Search/SearchRouter/SearchRouterList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,27 +25,32 @@ import ROUTES from '@src/ROUTES';

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

type SearchRouterListProps = {
/** currentQuery value computed coming from parsed TextInput value */
currentQuery: SearchQueryJSON | undefined;
/** value of TextInput */
textInputValue: string;

/** Callback to update text input when selecting contextual or autocomplete suggestion */
setTextInputValue: (newSearchQuery: string) => void;

/** Recent searches */
recentSearches: Array<ItemWithQuery & {timestamp: string}> | undefined;

/** Recent reports */
recentReports: OptionData[];

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

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

/** Context present when opening SearchRouter from a report, invoice or workspace page */
reportForContextualSearch?: OptionData;

/** Callback to update search query when selecting contextual suggestion */
updateUserSearchQuery: (newSearchQuery: string) => void;

/** Callback to close and clear SearchRouter */
closeAndClearRouter: () => void;
};
Expand Down Expand Up @@ -91,7 +96,16 @@ function SearchRouterItem(props: UserListItemProps<OptionData> | SearchQueryList
}

function SearchRouterList(
{currentQuery, reportForContextualSearch, recentSearches, recentReports, onSearchSubmit, updateUserSearchQuery, closeAndClearRouter}: SearchRouterListProps,
{
textInputValue,
setTextInputValue: updateTextInputValue,
reportForContextualSearch,
recentSearches,
autocompleteItems,
recentReports,
onSearchSubmit,
closeAndClearRouter,
}: SearchRouterListProps,
ref: ForwardedRef<SelectionListHandle>,
) {
const styles = useThemeStyles();
Expand All @@ -104,21 +118,22 @@ function SearchRouterList(
const [cardList = {}] = useOnyx(ONYXKEYS.CARD_LIST);
const sections: Array<SectionListDataType<OptionData | SearchQueryItem>> = [];

if (currentQuery?.inputQuery) {
if (textInputValue) {
sections.push({
data: [
{
text: currentQuery?.inputQuery,
text: textInputValue,
singleIcon: Expensicons.MagnifyingGlass,
query: currentQuery?.inputQuery,
query: textInputValue,
itemStyle: styles.activeComponentBG,
keyForList: 'findItem',
searchItemType: CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.SEARCH,
},
],
});
}

if (reportForContextualSearch && !currentQuery?.inputQuery) {
if (reportForContextualSearch && !textInputValue) {
sections.push({
data: [
{
Expand All @@ -128,22 +143,38 @@ function SearchRouterList(
itemStyle: styles.activeComponentBG,
keyForList: 'contextualSearch',
isContextualSearchItem: true,
searchItemType: CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.CONTEXTUAL_SUGGESTION,
},
],
});
}

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

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 {
text: searchQueryJSON ? SearchQueryUtils.buildUserReadableQueryString(searchQueryJSON, personalDetails, cardList, reports, taxRates) : query,
singleIcon: Expensicons.History,
query,
keyForList: timestamp,
searchItemType: CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.SEARCH,
};
});

if (!currentQuery?.inputQuery && recentSearchesData && recentSearchesData.length > 0) {
if (!textInputValue && recentSearchesData && recentSearchesData.length > 0) {
sections.push({title: translate('search.recentSearches'), data: recentSearchesData});
}

Expand All @@ -153,16 +184,21 @@ function SearchRouterList(
const onSelectRow = useCallback(
(item: OptionData | SearchQueryItem) => {
if (isSearchQueryItem(item)) {
if (item.isContextualSearchItem) {
// Handle selection of "Contextual search suggestion"
updateUserSearchQuery(`${item?.query} ${currentQuery?.inputQuery ?? ''}`);
if (!item?.query) {
return;
}

// Handle selection of "Recent search"
if (!item?.query) {
if (item.searchItemType === CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.CONTEXTUAL_SUGGESTION) {
updateTextInputValue(`${item?.query} `);
return;
}
if (item.searchItemType === CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.AUTOCOMPLETE_SUGGESTION && textInputValue) {
const lastColonIndex = textInputValue.lastIndexOf(':');
const lastCommaIndex = textInputValue.lastIndexOf(',');
const trimmedUserSearchQuery = lastColonIndex > lastCommaIndex ? textInputValue.slice(0, lastColonIndex + 1) : textInputValue.slice(0, lastCommaIndex + 1);
updateTextInputValue(`${trimmedUserSearchQuery}${item?.query} `);
return;
}

onSearchSubmit(SearchQueryUtils.buildSearchQueryJSON(item?.query));
}

Expand All @@ -174,7 +210,7 @@ function SearchRouterList(
Report.navigateToAndOpenReport(item.login ? [item.login] : [], false);
}
},
[closeAndClearRouter, onSearchSubmit, currentQuery, updateUserSearchQuery],
[closeAndClearRouter, textInputValue, onSearchSubmit, updateTextInputValue],
);

return (
Expand Down
14 changes: 14 additions & 0 deletions src/components/Search/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,18 @@ type SearchQueryJSON = {
flatFilters: QueryFilters;
} & SearchQueryAST;

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

type SearchAutocompleteResult = {
autocomplete: AutocompleteRange;
ranges: AutocompleteRange[];
};

export type {
SelectedTransactionInfo,
SelectedTransactions,
Expand All @@ -97,4 +109,6 @@ export type {
InvoiceSearchStatus,
TripSearchStatus,
ChatSearchStatus,
SearchAutocompleteResult,
AutocompleteRange,
};
3 changes: 3 additions & 0 deletions src/components/SelectionList/Search/SearchQueryListItem.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
import React from 'react';
import {View} from 'react-native';
import type {ValueOf} from 'type-fest';
import Icon from '@components/Icon';
import BaseListItem from '@components/SelectionList/BaseListItem';
import type {ListItem} from '@components/SelectionList/types';
import TextWithTooltip from '@components/TextWithTooltip';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import type CONST from '@src/CONST';
import type IconAsset from '@src/types/utils/IconAsset';

type SearchQueryItem = ListItem & {
singleIcon?: IconAsset;
query?: string;
isContextualSearchItem?: boolean;
searchItemType: ValueOf<typeof CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE>;
};

type SearchQueryListItemProps = {
Expand Down
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};
3 changes: 2 additions & 1 deletion src/libs/SearchParser/autocompleteParser.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,9 @@ function peg$parse(input, options) {
...value[value.length - 1],
};

return value.map(({ start, length }) => ({
return value.map(({ start, value, length }) => ({
key,
value,
start,
length,
}));
Expand Down
3 changes: 2 additions & 1 deletion src/libs/SearchParser/autocompleteParser.peggy
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@ defaultFilter
...value[value.length - 1],
};

return value.map(({ start, length }) => ({
return value.map(({ start, value, length }) => ({
key,
value,
start,
length,
}));
Expand Down
Loading