-
Notifications
You must be signed in to change notification settings - Fork 0
/
Search.tsx
425 lines (405 loc) · 15 KB
/
Search.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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import Fuse from 'fuse.js';
import {
Button,
ButtonProps,
debounce,
Dialog,
Divider,
Grid,
IconButton,
Stack,
useMediaQuery,
useTheme,
} from '@mui/material';
import { QuickFill } from './QuickFill';
import { FilteredSearch } from './FilteredSearch';
import { SearchInput } from './SearchInput';
import { SearchButton } from './SearchButton';
import { RecentSearches } from './RecentSearches';
import { addRecent, clearRecents, getRecents } from './helpers';
import { PaddedIcon } from './PaddedIcon';
import CloseIcon from '@mui/icons-material/Close';
import SearchIcon from '@mui/icons-material/Search';
const RSD_SEARCH_INPUT_ID = 'rsd-search-input';
const RSD_POPOVER_ID = 'rsd-popover';
// TODO: implement variable row heights using this enum to support react-window's itemSize() function
/**
* List item height preset values
*/
export enum ItemHeightPreset {
SMALL = 24,
MEDIUM = 32,
LARGE = 40,
XLARGE = 48,
}
/**
* Type that describes the height of each search / recent list item
*/
export type ItemHeight = ItemHeightPreset | number;
/**
* Type that every item passed into the `items` prop must extend
*/
export type SearchItemRequirements = { label: string } | string;
/**
* Arguments passed into the `renderResult` and `renderRecent` functions
*/
export type RenderItemArgs<T> = {
item: T;
smallDisplay: boolean;
closeDialog: () => void;
addToRecents: () => void;
};
export type SearchProps<T> = {
/**
* List of items to search through.
*
* **NOTE: Each item must have a `label` property or be a string!**
*
* This constraint is enforced for two main reasons:
* 1. So that the search engine has a property it can depend on being present to
* use when searching
* 2. When using the default `renderResult` function, it can assume that is the
* item isn't a string, that is can use the `label` property to display the item
* @see SearchItemRequirements
*/
items: T[];
/**
* Props passed to the search button that opens main search dialog
* @see ButtonProps
* @link https://mui.com/api/button/
*/
buttonProps?: ButtonProps | ((isSmallScreen: boolean) => ButtonProps);
/**
* Search engine options passed to Fuse.js.
*
* **NOTE: `label` is preserved as an attribute in the search key array.**
*/
fuseOptions?: Fuse.IFuseOptions<T>;
/**
* Place holder displayed in the search input when empty
* @default 'Search'
*/
placeholder?: string;
/**
* Title for the Quick Fill section of the search dialog
* @default 'Quick Fill'
*/
quickFillTitle?: string;
/**
* Height of each search result item
* @default ItemHeightPreset.LARGE
* @see ItemHeight
*/
itemHeight?: ItemHeight;
/**
* List of items to display in the quick fill section of the search dialog
*/
quickFillItems?: T[];
/**
* Maximum height of the search dialog
*/
maxHeight?: React.CSSProperties['maxHeight'];
/**
* Maximum width of the search dialog
*/
maxWidth?: React.CSSProperties['maxWidth'];
/**
* Whether or not to show recent searches
*/
noHistory?: boolean;
/**
* Callback function that is called when a search result item is selected
*
* **NOTE: If not using `renderResult`, this prop is required! If using `renderResult`,
* this prop does nothing.**
* @param item The item that was selected
*/
onItemSelect?: (item: T) => void;
/**
* Function that renders each search result item
* @param result The item to render
* @param smallDisplay Whether or not the search dialog is in small display mode
* @param closeDialog Function to call to close the search dialog
* @param addToRecents Callback function that should be called when the item is selected
* @returns JSX.Element
*/
renderResult?: ({
item,
smallDisplay,
closeDialog,
addToRecents,
}: RenderItemArgs<T>) => JSX.Element;
/**
* Function that renders each recent search item
* @param recent The item to render
* @param smallDisplay Whether or not the search dialog is in small display mode
* @param closeDialog Function to call to close the search dialog
* @param addToRecents Callback function that should be called when the item is selected
* @returns JSX.Element
*/
renderRecent?: ({
item,
smallDisplay,
closeDialog,
addToRecents,
}: RenderItemArgs<T>) => JSX.Element;
};
/**
* All in one search dialog component!
*
* **Required props:**
* - `items` - List of items to search through. Each item must have a `label` property or be a string
* - `onItemSelect` - Callback function that is fired when a search result item is selected
*
* **Conditionally required props:**
* - `onItemSelect` - Required if not using `renderResult` prop. Prop is required in this case so that
* each search result item has an onClick handler
*
* **Recommended optional props:**
* - `renderResult` - Function that renders each search result item
* - `renderRecent` - Function that renders each recent search item
* - `quickFillItems` - List of items to display in the quick fill section of the search dialog
* - `itemHeight` - Height of each search result / recent search item
*
* @see SearchProps
* @returns JSX.Element
*/
export const Search = <T extends SearchItemRequirements>({
items,
buttonProps,
fuseOptions,
placeholder,
quickFillTitle,
itemHeight = ItemHeightPreset.LARGE,
quickFillItems,
maxHeight,
maxWidth,
noHistory = false,
onItemSelect,
renderResult,
renderRecent,
}: SearchProps<T>) => {
const theme = useTheme();
const [open, setOpen] = useState(false);
const [recentSearches, setRecentSearches] = useState<T[]>([]);
const [searchText, setSearchText] = useState('');
const [searchResults, setSearchResults] = useState<T[]>([]);
const [searchEngine, setSearchEngine] = useState<Fuse<T>>();
const rsdInputRef = useRef<HTMLInputElement | null>(null);
const smallDisplay = useMediaQuery(theme.breakpoints.down('sm'));
useEffect(() => {
setRecentSearches(getRecents<T>());
}, []);
/**
* Monitors the `renderResult` and `onItemSelect` props to ensure that at least one of them is provided
*/
useEffect(() => {
if (renderResult === undefined && onItemSelect == undefined) {
throw Error(
'If not providing the `renderResult` prop, the `onItemSelect` prop is required for item click functionality.'
);
}
}, [renderResult, onItemSelect]);
/**
* Instantiates the search engine and keeps the collections of items to search through up to date
*/
useEffect(() => {
if (!searchEngine) {
const mergedFuseOptions = { threshold: 0.3, ...fuseOptions };
if (typeof items?.at(0) !== 'string') {
mergedFuseOptions.keys = ['label', ...(fuseOptions?.keys ?? [])];
}
setSearchEngine(new Fuse(items, mergedFuseOptions));
}
searchEngine?.setCollection(items);
}, [fuseOptions, items, searchEngine]);
/**
* Updates the search results state when the search text changes.
* When search text is empty, all items are displayed (useful when the noHistory prop is evoked)
*/
useEffect(() => {
if (searchText === '') {
setSearchResults(items);
} else {
setSearchResults(searchEngine?.search(searchText).map((res) => res.item) ?? items);
}
}, [searchText, items, searchEngine]);
/**
* Setups up and tears down the keydown event listeners that:
* - Opens the search dialog when the user presses ctrl + k
* - Close the search dialog when the user presses escape
* @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
*/
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
switch (e.key) {
case 'Escape':
setOpen(false);
break;
case 'ArrowDown':
if (rsdInputRef.current !== null) {
rsdInputRef.current.blur();
}
break;
case 'k':
if (e.ctrlKey) {
e.preventDefault();
setOpen(true);
}
break;
default:
break;
}
};
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, []);
/**
* Handles the click event on a quick fill item by updating the search text and
* input value to the item's label if item is an object or value otherwise
*/
const onQuickFillItemClick = useCallback(
(item: T) => {
if (rsdInputRef.current !== null) {
const newSearchText = typeof item === 'string' ? item : item.label;
setSearchText(newSearchText);
rsdInputRef.current.value = newSearchText;
} else {
throw Error('Could not find react-search-dialog search input element to update value');
}
},
[setSearchText]
);
/**
* Handles the click event on a search result item by calling the onItemSelect callback
* and adding the item to the recent searches list if the noHistory prop is not evoked
*/
const getAddToRecentsFunc = useCallback(
(item: T) => {
return () => {
if (!noHistory) {
const newRecents = addRecent(item);
setRecentSearches(newRecents);
}
};
},
[noHistory]
);
/**
* Handles closing the search dialog and resetting the search text
*/
const closeAndReset = useCallback(() => {
setOpen(false);
setSearchText('');
}, []);
const evaluatedButtonProps = useMemo(() => {
if (typeof buttonProps === 'function') {
return buttonProps(smallDisplay);
} else {
return buttonProps;
}
}, [buttonProps, smallDisplay]);
return (
<>
<SearchButton
buttonProps={{
...evaluatedButtonProps,
onClick: () => {
setOpen(true);
},
}}
mobile={smallDisplay}
/>
<Dialog
id={RSD_POPOVER_ID}
open={open}
onClose={closeAndReset}
sx={{ '& .MuiDialog-container': { backdropFilter: 'blur(4px)' } }}
PaperProps={{
sx: {
width: '100%',
height: '100%',
maxWidth: smallDisplay ? 'unset' : maxWidth ?? theme.breakpoints.values.md,
maxHeight: smallDisplay ? 'unset' : maxHeight ?? theme.breakpoints.values.sm,
},
}}
fullScreen={smallDisplay}
>
<Stack direction="column" height="100%">
<Stack direction="row">
<PaddedIcon icon={<SearchIcon />} />
<SearchInput
id={RSD_SEARCH_INPUT_ID}
ref={rsdInputRef}
placeholder={placeholder !== undefined ? placeholder : 'Search'}
inputProps={{ 'aria-label': 'search' }}
onClick={() => {
setOpen(true);
}}
onChange={debounce((e) => {
setSearchText(e.target.value);
}, 400)}
fullWidth
autoFocus
/>
<Divider orientation="vertical" />
<IconButton onClick={closeAndReset} sx={{ borderRadius: 'unset' }}>
<CloseIcon />
</IconButton>
</Stack>
<Divider />
<Grid container sx={{ height: '100%' }}>
{quickFillItems && !smallDisplay && (
<Grid item xs={3}>
<div style={{ display: 'flex', flexDirection: 'row', height: '100%' }}>
<QuickFill
quickFillTitle={quickFillTitle}
quickFillItems={quickFillItems}
onQuickItemClick={onQuickFillItemClick}
/>
<Divider orientation="vertical" />
</div>
</Grid>
)}
<Grid item xs={true}>
{(searchResults.length > 0 && searchText.length > 0) || noHistory ? (
<FilteredSearch
searchResults={searchResults}
itemHeight={itemHeight}
smallDisplay={smallDisplay}
onItemSelect={onItemSelect}
getAddToRecentsFunc={getAddToRecentsFunc}
renderResult={renderResult}
closeDialog={closeAndReset}
/>
) : (
<RecentSearches
recents={recentSearches}
itemHeight={itemHeight}
smallDisplay={smallDisplay}
onItemSelect={onItemSelect}
getAddToRecentsFunc={getAddToRecentsFunc}
renderRecent={renderRecent}
closeDialog={closeAndReset}
toolbarElements={
<Button
onClick={() => {
clearRecents();
setRecentSearches([]);
}}
>
Clear Recents
</Button>
}
/>
)}
</Grid>
</Grid>
</Stack>
</Dialog>
</>
);
};