-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
AutocompleteArrayInput.tsx
526 lines (496 loc) · 17.8 KB
/
AutocompleteArrayInput.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
import React, {
useCallback,
useEffect,
useRef,
FunctionComponent,
useMemo,
isValidElement,
} from 'react';
import Downshift, { DownshiftProps } from 'downshift';
import classNames from 'classnames';
import get from 'lodash/get';
import { makeStyles, TextField, Chip } from '@material-ui/core';
import { TextFieldProps } from '@material-ui/core/TextField';
import {
useInput,
FieldTitle,
InputProps,
useSuggestions,
warning,
} from 'ra-core';
import InputHelperText from './InputHelperText';
import AutocompleteSuggestionList from './AutocompleteSuggestionList';
import AutocompleteSuggestionItem from './AutocompleteSuggestionItem';
interface Options {
suggestionsContainerProps?: any;
labelProps?: any;
}
/**
* An Input component for an autocomplete field, using an array of objects for the options
*
* Pass possible options as an array of objects in the 'choices' attribute.
*
* By default, the options are built from:
* - the 'id' property as the option value,
* - the 'name' property an the option text
* @example
* const choices = [
* { id: 'M', name: 'Male' },
* { id: 'F', name: 'Female' },
* ];
* <AutocompleteArrayInput source="gender" choices={choices} />
*
* You can also customize the properties to use for the option name and value,
* thanks to the 'optionText' and 'optionValue' attributes.
* @example
* const choices = [
* { _id: 123, full_name: 'Leo Tolstoi', sex: 'M' },
* { _id: 456, full_name: 'Jane Austen', sex: 'F' },
* ];
* <AutocompleteArrayInput source="author_id" choices={choices} optionText="full_name" optionValue="_id" />
*
* `optionText` also accepts a function, so you can shape the option text at will:
* @example
* const choices = [
* { id: 123, first_name: 'Leo', last_name: 'Tolstoi' },
* { id: 456, first_name: 'Jane', last_name: 'Austen' },
* ];
* const optionRenderer = choice => `${choice.first_name} ${choice.last_name}`;
* <AutocompleteArrayInput source="author_id" choices={choices} optionText={optionRenderer} />
*
* `optionText` also accepts a React Element, that will be cloned and receive
* the related choice as the `record` prop. You can use Field components there.
* Note that you must also specify the `matchSuggestion` prop
* @example
* const choices = [
* { id: 123, first_name: 'Leo', last_name: 'Tolstoi' },
* { id: 456, first_name: 'Jane', last_name: 'Austen' },
* ];
* const matchSuggestion = (filterValue, choice) => choice.first_name.match(filterValue) || choice.last_name.match(filterValue);
* const FullNameField = ({ record }) => <span>{record.first_name} {record.last_name}</span>;
* <SelectInput source="gender" choices={choices} optionText={<FullNameField />} matchSuggestion={matchSuggestion} />
*
* The choices are translated by default, so you can use translation identifiers as choices:
* @example
* const choices = [
* { id: 'M', name: 'myroot.gender.male' },
* { id: 'F', name: 'myroot.gender.female' },
* ];
*
* However, in some cases (e.g. inside a `<ReferenceInput>`), you may not want
* the choice to be translated. In that case, set the `translateChoice` prop to false.
* @example
* <AutocompleteArrayInput source="gender" choices={choices} translateChoice={false}/>
*
* The object passed as `options` props is passed to the material-ui <TextField> component
*
* @example
* <AutocompleteArrayInput source="author_id" options={{ color: 'secondary' }} />
*/
const AutocompleteArrayInput: FunctionComponent<
InputProps<TextFieldProps & Options> & DownshiftProps<any>
> = ({
allowDuplicates,
allowEmpty,
classes: classesOverride,
choices = [],
emptyText,
emptyValue,
format,
fullWidth,
helperText,
id: idOverride,
input: inputOverride,
isRequired: isRequiredOverride,
label,
limitChoicesToValue,
margin,
matchSuggestion,
meta: metaOverride,
onBlur,
onChange,
onFocus,
options: {
suggestionsContainerProps,
labelProps,
InputProps,
...options
} = {},
optionText = 'name',
optionValue = 'id',
parse,
resource,
setFilter,
shouldRenderSuggestions: shouldRenderSuggestionsOverride,
source,
suggestionLimit,
translateChoice = true,
validate,
variant = 'filled',
...rest
}) => {
warning(
isValidElement(optionText) && !matchSuggestion,
`If the optionText prop is a React element, you must also specify the matchSuggestion prop:
<AutocompleteInput
matchSuggestion={(filterValue, suggestion) => true}
/>
`
);
const classes = useStyles({ classes: classesOverride });
let inputEl = useRef<HTMLInputElement>();
let anchorEl = useRef<any>();
const {
id,
input,
isRequired,
meta: { touched, error },
} = useInput({
format,
id: idOverride,
input: inputOverride,
meta: metaOverride,
onBlur,
onChange,
onFocus,
parse,
resource,
source,
validate,
...rest,
});
const [filterValue, setFilterValue] = React.useState('');
const getSuggestionFromValue = useCallback(
value => choices.find(choice => get(choice, optionValue) === value),
[choices, optionValue]
);
const selectedItems = useMemo(
() => (input.value || []).map(getSuggestionFromValue),
[input.value, getSuggestionFromValue]
);
const { getChoiceText, getChoiceValue, getSuggestions } = useSuggestions({
allowDuplicates,
allowEmpty,
choices,
emptyText,
emptyValue,
limitChoicesToValue,
matchSuggestion,
optionText,
optionValue,
selectedItem: selectedItems,
suggestionLimit,
translateChoice,
});
const handleFilterChange = useCallback(
(eventOrValue: React.ChangeEvent<{ value: string }> | string) => {
const event = eventOrValue as React.ChangeEvent<{ value: string }>;
const value = event.target
? event.target.value
: (eventOrValue as string);
setFilterValue(value);
if (setFilter) {
setFilter(value);
}
},
[setFilter, setFilterValue]
);
// We must reset the filter every time the value changes to ensure we
// display at least some choices even if the input has a value.
// Otherwise, it would only display the currently selected one and the user
// would have to first clear the input before seeing any other choices
useEffect(() => {
handleFilterChange('');
}, [input.value, handleFilterChange]);
const handleKeyDown = useCallback(
(event: React.KeyboardEvent) => {
// Remove latest item from array when user hits backspace with no text
if (
selectedItems.length &&
!filterValue.length &&
event.key === 'Backspace'
) {
const newSelectedItems = selectedItems.slice(
0,
selectedItems.length - 1
);
input.onChange(newSelectedItems.map(getChoiceValue));
}
},
[filterValue.length, getChoiceValue, input, selectedItems]
);
const handleChange = useCallback(
(item: any) => {
let newSelectedItems =
!allowDuplicates && selectedItems.includes(item)
? [...selectedItems]
: [...selectedItems, item];
setFilterValue('');
input.onChange(newSelectedItems.map(getChoiceValue));
},
[allowDuplicates, getChoiceValue, input, selectedItems, setFilterValue]
);
const handleDelete = useCallback(
item => () => {
const newSelectedItems = [...selectedItems];
newSelectedItems.splice(newSelectedItems.indexOf(item), 1);
input.onChange(newSelectedItems.map(getChoiceValue));
},
[input, selectedItems, getChoiceValue]
);
// This function ensures that the suggestion list stay aligned to the
// input element even if it moves (because user scrolled for example)
const updateAnchorEl = () => {
if (!inputEl.current) {
return;
}
const inputPosition = inputEl.current.getBoundingClientRect() as DOMRect;
// It works by implementing a mock element providing the only method used
// by the PopOver component, getBoundingClientRect, which will return a
// position based on the input position
if (!anchorEl.current) {
anchorEl.current = { getBoundingClientRect: () => inputPosition };
} else {
const anchorPosition = anchorEl.current.getBoundingClientRect();
if (
anchorPosition.x !== inputPosition.x ||
anchorPosition.y !== inputPosition.y
) {
anchorEl.current = {
getBoundingClientRect: () => inputPosition,
};
}
}
};
const storeInputRef = input => {
inputEl.current = input;
updateAnchorEl();
};
const handleBlur = useCallback(
event => {
setFilterValue('');
handleFilterChange('');
input.onBlur(event);
},
[handleFilterChange, input, setFilterValue]
);
const handleFocus = useCallback(
openMenu => event => {
openMenu(event);
input.onFocus(event);
},
[input]
);
const handleClick = useCallback(
openMenu => event => {
if (event.target === inputEl.current) {
openMenu(event);
}
},
[]
);
const shouldRenderSuggestions = val => {
if (
shouldRenderSuggestionsOverride !== undefined &&
typeof shouldRenderSuggestionsOverride === 'function'
) {
return shouldRenderSuggestionsOverride(val);
}
return true;
};
return (
<Downshift
inputValue={filterValue}
onChange={handleChange}
selectedItem={selectedItems}
itemToString={item => getChoiceValue(item)}
{...rest}
>
{({
getInputProps,
getItemProps,
getLabelProps,
getMenuProps,
isOpen,
inputValue: suggestionFilter,
highlightedIndex,
openMenu,
}) => {
const isMenuOpen =
isOpen && shouldRenderSuggestions(suggestionFilter);
const {
id: idFromDownshift,
onBlur,
onChange,
onFocus,
ref,
color,
size,
...inputProps
} = getInputProps({
onBlur: handleBlur,
onFocus: handleFocus(openMenu),
onClick: handleClick(openMenu),
onKeyDown: handleKeyDown,
});
return (
<div className={classes.container}>
<TextField
id={id}
fullWidth={fullWidth}
InputProps={{
inputRef: storeInputRef,
classes: {
root: classNames(classes.inputRoot, {
[classes.inputRootFilled]:
variant === 'filled',
}),
input: classes.inputInput,
},
startAdornment: (
<div
className={classNames({
[classes.chipContainerFilled]:
variant === 'filled',
})}
>
{selectedItems.map((item, index) => (
<Chip
key={index}
tabIndex={-1}
label={getChoiceText(item)}
className={classes.chip}
onDelete={handleDelete(item)}
/>
))}
</div>
),
onBlur,
onChange: event => {
handleFilterChange(event);
onChange!(event as React.ChangeEvent<
HTMLInputElement
>);
},
onFocus,
}}
error={!!(touched && error)}
label={
<FieldTitle
label={label}
{...labelProps}
source={source}
resource={resource}
isRequired={
typeof isRequiredOverride !==
'undefined'
? isRequiredOverride
: isRequired
}
/>
}
InputLabelProps={getLabelProps({
htmlFor: id,
})}
helperText={
<InputHelperText
touched={touched}
error={error}
helperText={helperText}
/>
}
variant={variant}
margin={margin}
color={color as any}
size={size as any}
{...inputProps}
{...options}
/>
<AutocompleteSuggestionList
isOpen={isMenuOpen}
menuProps={getMenuProps(
{},
// https://github.com/downshift-js/downshift/issues/235
{ suppressRefError: true }
)}
inputEl={inputEl.current}
suggestionsContainerProps={
suggestionsContainerProps
}
>
{getSuggestions(suggestionFilter).map(
(suggestion, index) => (
<AutocompleteSuggestionItem
key={getChoiceValue(suggestion)}
suggestion={suggestion}
index={index}
highlightedIndex={highlightedIndex}
isSelected={selectedItems
.map(getChoiceValue)
.includes(
getChoiceValue(suggestion)
)}
filterValue={filterValue}
getSuggestionText={getChoiceText}
{...getItemProps({
item: suggestion,
})}
/>
)
)}
</AutocompleteSuggestionList>
</div>
);
}}
</Downshift>
);
};
const useStyles = makeStyles(
theme => {
const chipBackgroundColor =
theme.palette.type === 'light'
? 'rgba(0, 0, 0, 0.09)'
: 'rgba(255, 255, 255, 0.09)';
return {
root: {
flexGrow: 1,
height: 250,
},
container: {
flexGrow: 1,
position: 'relative',
},
paper: {
position: 'absolute',
zIndex: 1,
marginTop: theme.spacing(1),
left: 0,
right: 0,
},
chip: {
margin: theme.spacing(0.5, 0.5, 0.5, 0),
},
chipContainerFilled: {
margin: '27px 12px 10px 0',
},
inputRoot: {
flexWrap: 'wrap',
},
inputRootFilled: {
flexWrap: 'wrap',
'& $chip': {
backgroundColor: chipBackgroundColor,
},
},
inputInput: {
width: 'auto',
flexGrow: 1,
},
divider: {
height: theme.spacing(2),
},
};
},
{ name: 'RaAutocompleteArrayInput' }
);
export default AutocompleteArrayInput;