-
Notifications
You must be signed in to change notification settings - Fork 3k
/
SearchRouterList.tsx
322 lines (283 loc) · 13.3 KB
/
SearchRouterList.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import React, {forwardRef, useCallback} from 'react';
import type {ForwardedRef} from 'react';
import {useOnyx} from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import * as Expensicons from '@components/Icon/Expensicons';
import {usePersonalDetails} from '@components/OnyxProvider';
import type {SearchFilterKey, SearchQueryString} from '@components/Search/types';
import SelectionList from '@components/SelectionList';
import SearchQueryListItem from '@components/SelectionList/Search/SearchQueryListItem';
import type {SearchQueryItem, SearchQueryListItemProps} from '@components/SelectionList/Search/SearchQueryListItem';
import type {SectionListDataType, SelectionListHandle, UserListItemProps} from '@components/SelectionList/types';
import UserListItem from '@components/SelectionList/UserListItem';
import useLocalize from '@hooks/useLocalize';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useThemeStyles from '@hooks/useThemeStyles';
import Navigation from '@libs/Navigation/Navigation';
import type {SearchOption} from '@libs/OptionsListUtils';
import Performance from '@libs/Performance';
import {getAllTaxRates} from '@libs/PolicyUtils';
import type {OptionData} from '@libs/ReportUtils';
import {getQueryWithoutAutocompletedPart} from '@libs/SearchAutocompleteUtils';
import * as SearchQueryUtils from '@libs/SearchQueryUtils';
import * as ReportUserActions from '@userActions/Report';
import Timing from '@userActions/Timing';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import type Report from '@src/types/onyx/Report';
import {getSubstitutionMapKey} from './getQueryWithSubstitutions';
type SearchQueryItemData = {
query: string;
text?: string;
};
type AutocompleteItemData = {
filterKey: SearchFilterKey;
text: string;
autocompleteID?: string;
};
type SearchRouterListProps = {
/** value of TextInput */
textInputValue: string;
/** Callback to update text input value along with autocomplete suggestions */
updateSearchValue: (newValue: string) => void;
/** Callback to update text input value */
setTextInputValue: (text: string) => void;
/** Recent searches */
recentSearches: Array<SearchQueryItemData & {timestamp: string}> | undefined;
/** Recent reports */
recentReports: OptionData[];
/** Autocomplete items */
autocompleteSuggestions: AutocompleteItemData[] | undefined;
/** Callback to submit query when selecting a list item */
onSearchSubmit: (query: SearchQueryString) => void;
/** Context present when opening SearchRouter from a report, invoice or workspace page */
reportForContextualSearch?: OptionData;
/** Callback to run when user clicks a suggestion item that contains autocomplete data */
onAutocompleteSuggestionClick: (autocompleteKey: string, autocompleteID: string) => void;
/** Callback to close and clear SearchRouter */
closeRouter: () => void;
};
const setPerformanceTimersEnd = () => {
Timing.end(CONST.TIMING.OPEN_SEARCH);
Performance.markEnd(CONST.TIMING.OPEN_SEARCH);
};
function getContextualSearchQuery(item: SearchQueryItem) {
const baseQuery = `${CONST.SEARCH.SYNTAX_ROOT_KEYS.TYPE}:${item.roomType}`;
let additionalQuery = '';
switch (item.roomType) {
case CONST.SEARCH.DATA_TYPES.EXPENSE:
case CONST.SEARCH.DATA_TYPES.INVOICE:
additionalQuery += ` ${CONST.SEARCH.SYNTAX_ROOT_KEYS.POLICY_ID}:${item.policyID}`;
if (item.roomType === CONST.SEARCH.DATA_TYPES.INVOICE && item.autocompleteID) {
additionalQuery += ` ${CONST.SEARCH.SYNTAX_FILTER_KEYS.TO}:${SearchQueryUtils.sanitizeSearchValue(item.searchQuery ?? '')}`;
}
break;
case CONST.SEARCH.DATA_TYPES.CHAT:
default:
additionalQuery = ` ${CONST.SEARCH.SYNTAX_FILTER_KEYS.IN}:${SearchQueryUtils.sanitizeSearchValue(item.searchQuery ?? '')}`;
break;
}
return baseQuery + additionalQuery;
}
function isSearchQueryItem(item: OptionData | SearchQueryItem): item is SearchQueryItem {
return 'searchItemType' in item;
}
function isSearchQueryListItem(listItem: UserListItemProps<OptionData> | SearchQueryListItemProps): listItem is SearchQueryListItemProps {
return isSearchQueryItem(listItem.item);
}
function getItemHeight(item: OptionData | SearchQueryItem) {
if (isSearchQueryItem(item)) {
return 44;
}
return 64;
}
function SearchRouterItem(props: UserListItemProps<OptionData> | SearchQueryListItemProps) {
const styles = useThemeStyles();
if (isSearchQueryListItem(props)) {
return (
<SearchQueryListItem
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
/>
);
}
return (
<UserListItem
pressableStyle={[styles.br2]}
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
/>
);
}
function SearchRouterList(
{
textInputValue,
updateSearchValue,
setTextInputValue,
reportForContextualSearch,
recentSearches,
autocompleteSuggestions,
recentReports,
onSearchSubmit,
onAutocompleteSuggestionClick,
closeRouter,
}: SearchRouterListProps,
ref: ForwardedRef<SelectionListHandle>,
) {
const styles = useThemeStyles();
const {translate} = useLocalize();
const {shouldUseNarrowLayout} = useResponsiveLayout();
const personalDetails = usePersonalDetails();
const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
const taxRates = getAllTaxRates();
const [cardList = {}] = useOnyx(ONYXKEYS.CARD_LIST);
const sections: Array<SectionListDataType<OptionData | SearchQueryItem>> = [];
if (textInputValue) {
sections.push({
data: [
{
text: textInputValue,
singleIcon: Expensicons.MagnifyingGlass,
searchQuery: textInputValue,
itemStyle: styles.activeComponentBG,
keyForList: 'findItem',
searchItemType: CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.SEARCH,
},
],
});
}
if (reportForContextualSearch && !textInputValue) {
const reportQueryValue = reportForContextualSearch.text ?? reportForContextualSearch.alternateText ?? reportForContextualSearch.reportID;
let roomType: ValueOf<typeof CONST.SEARCH.DATA_TYPES> = CONST.SEARCH.DATA_TYPES.CHAT;
let autocompleteID = reportForContextualSearch.reportID;
if (reportForContextualSearch.isInvoiceRoom) {
roomType = CONST.SEARCH.DATA_TYPES.INVOICE;
const report = reportForContextualSearch as SearchOption<Report>;
if (report.item && report.item?.invoiceReceiver && report.item.invoiceReceiver?.type === CONST.REPORT.INVOICE_RECEIVER_TYPE.INDIVIDUAL) {
autocompleteID = report.item.invoiceReceiver.accountID.toString();
} else {
autocompleteID = '';
}
}
if (reportForContextualSearch.isPolicyExpenseChat) {
roomType = CONST.SEARCH.DATA_TYPES.EXPENSE;
autocompleteID = reportForContextualSearch.policyID ?? '';
}
sections.push({
data: [
{
text: `${translate('search.searchIn')} ${reportForContextualSearch.text ?? reportForContextualSearch.alternateText}`,
singleIcon: Expensicons.MagnifyingGlass,
searchQuery: reportQueryValue,
autocompleteID,
itemStyle: styles.activeComponentBG,
keyForList: 'contextualSearch',
searchItemType: CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.CONTEXTUAL_SUGGESTION,
roomType,
policyID: reportForContextualSearch.policyID,
},
],
});
}
const autocompleteData = autocompleteSuggestions?.map(({filterKey, text, autocompleteID}) => {
return {
text: getSubstitutionMapKey(filterKey, text),
singleIcon: Expensicons.MagnifyingGlass,
searchQuery: text,
autocompleteID,
keyForList: autocompleteID ?? text, // in case we have a unique identifier then use it because text might not be unique
searchItemType: CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.AUTOCOMPLETE_SUGGESTION,
};
});
if (autocompleteData && autocompleteData.length > 0) {
sections.push({title: translate('search.suggestions'), data: autocompleteData});
}
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,
searchQuery: query,
keyForList: timestamp,
searchItemType: CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.SEARCH,
};
});
if (!textInputValue && recentSearchesData && recentSearchesData.length > 0) {
sections.push({title: translate('search.recentSearches'), data: recentSearchesData});
}
const styledRecentReports = recentReports.map((item) => ({...item, pressableStyle: styles.br2, wrapperStyle: [styles.pr3, styles.pl3]}));
sections.push({title: translate('search.recentChats'), data: styledRecentReports});
const onSelectRow = useCallback(
(item: OptionData | SearchQueryItem) => {
if (isSearchQueryItem(item)) {
if (!item.searchQuery) {
return;
}
if (item.searchItemType === CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.CONTEXTUAL_SUGGESTION) {
const searchQuery = getContextualSearchQuery(item);
updateSearchValue(`${searchQuery} `);
if (item.roomType === CONST.SEARCH.DATA_TYPES.INVOICE && item.autocompleteID) {
const autocompleteKey = `${CONST.SEARCH.SYNTAX_FILTER_KEYS.TO}:${item.searchQuery}`;
onAutocompleteSuggestionClick(autocompleteKey, item.autocompleteID);
}
if (item.roomType === CONST.SEARCH.DATA_TYPES.CHAT && item.autocompleteID) {
const autocompleteKey = `${CONST.SEARCH.SYNTAX_FILTER_KEYS.IN}:${item.searchQuery}`;
onAutocompleteSuggestionClick(autocompleteKey, item.autocompleteID);
}
return;
}
if (item.searchItemType === CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.AUTOCOMPLETE_SUGGESTION && textInputValue) {
const trimmedUserSearchQuery = getQueryWithoutAutocompletedPart(textInputValue);
updateSearchValue(`${trimmedUserSearchQuery}${SearchQueryUtils.sanitizeSearchValue(item.searchQuery)} `);
if (item.autocompleteID && item.text) {
onAutocompleteSuggestionClick(item.text, item.autocompleteID);
}
return;
}
onSearchSubmit(item.searchQuery);
}
// Handle selection of "Recent chat"
closeRouter();
if ('reportID' in item && item?.reportID) {
Navigation.navigate(ROUTES.REPORT_WITH_ID.getRoute(item?.reportID));
} else if ('login' in item) {
ReportUserActions.navigateToAndOpenReport(item.login ? [item.login] : [], false);
}
},
[closeRouter, textInputValue, onSearchSubmit, updateSearchValue, onAutocompleteSuggestionClick],
);
const onArrowFocus = useCallback(
(focusedItem: OptionData | SearchQueryItem) => {
if (!isSearchQueryItem(focusedItem) || focusedItem?.searchItemType !== CONST.SEARCH.SEARCH_ROUTER_ITEM_TYPE.AUTOCOMPLETE_SUGGESTION || !focusedItem.searchQuery) {
return;
}
const trimmedUserSearchQuery = getQueryWithoutAutocompletedPart(textInputValue);
setTextInputValue(`${trimmedUserSearchQuery}${SearchQueryUtils.sanitizeSearchValue(focusedItem.searchQuery)} `);
if (focusedItem.autocompleteID && focusedItem.text) {
onAutocompleteSuggestionClick(focusedItem.text, focusedItem.autocompleteID);
}
},
[setTextInputValue, textInputValue, onAutocompleteSuggestionClick],
);
return (
<SelectionList<OptionData | SearchQueryItem>
sections={sections}
onSelectRow={onSelectRow}
ListItem={SearchRouterItem}
containerStyle={[styles.mh100]}
sectionListStyle={[shouldUseNarrowLayout ? styles.ph5 : styles.ph2, styles.pb2]}
listItemWrapperStyle={[styles.pr3, styles.pl3]}
getItemHeight={getItemHeight}
onLayout={setPerformanceTimersEnd}
ref={ref}
showScrollIndicator={!shouldUseNarrowLayout}
sectionTitleStyles={styles.mhn2}
shouldSingleExecuteRowSelect
onArrowFocus={onArrowFocus}
/>
);
}
export default forwardRef(SearchRouterList);
export {SearchRouterItem};
export type {AutocompleteItemData};