-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
AutocompleteInput.tsx
744 lines (692 loc) · 23.9 KB
/
AutocompleteInput.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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
import * as React from 'react';
import {
isValidElement,
useCallback,
useEffect,
useMemo,
useRef,
useState,
ReactNode,
} from 'react';
import debounce from 'lodash/debounce';
import get from 'lodash/get';
import isEqual from 'lodash/isEqual';
import clsx from 'clsx';
import {
Autocomplete,
AutocompleteProps,
Chip,
TextField,
TextFieldProps,
createFilterOptions,
} from '@mui/material';
import { styled } from '@mui/material/styles';
import {
ChoicesProps,
FieldTitle,
RaRecord,
useChoicesContext,
useInput,
useSuggestions,
UseSuggestionsOptions,
useTimeout,
useTranslate,
warning,
useGetRecordRepresentation,
} from 'ra-core';
import {
SupportCreateSuggestionOptions,
useSupportCreateSuggestion,
} from './useSupportCreateSuggestion';
import { CommonInputProps } from './CommonInputProps';
import { InputHelperText } from './InputHelperText';
import { sanitizeInputRestProps } from './sanitizeInputRestProps';
const defaultFilterOptions = createFilterOptions();
/**
* 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 as the option text
* @example
* const choices = [
* { id: 'M', name: 'Male' },
* { id: 'F', name: 'Female' },
* ];
* <AutocompleteInput 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' },
* ];
* <AutocompleteInput 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}`;
* <AutocompleteInput source="author_id" choices={choices} optionText={optionRenderer} />
*
* `optionText` also accepts a React Element, that can access
* the related choice through the `useRecordContext` hook. You can use Field components there.
* Note that you must also specify the `matchSuggestion` and `inputText` props
* @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 inputText = (record) => `${record.fullName} (${record.language})`;
*
* const FullNameField = () => {
* const record = useRecordContext();
* return <span>{record.first_name} {record.last_name}</span>;
* }
* <AutocompleteInput source="author" choices={choices} optionText={<FullNameField />} matchSuggestion={matchSuggestion} inputText={inputText} />
*
* 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
* <AutocompleteInput source="gender" choices={choices} translateChoice={false}/>
*
* The object passed as `options` props is passed to the MUI <TextField> component
*
* @example
* <AutocompleteInput source="author_id" options={{ color: 'secondary', InputLabelProps: { shrink: true } }} />
*/
export const AutocompleteInput = <
OptionType extends RaRecord = RaRecord,
Multiple extends boolean | undefined = false,
DisableClearable extends boolean | undefined = false,
SupportCreate extends boolean | undefined = false
>(
props: AutocompleteInputProps<
OptionType,
Multiple,
DisableClearable,
SupportCreate
>
) => {
const {
choices: choicesProp,
className,
clearOnBlur = true,
clearText = 'ra.action.clear_input_value',
closeText = 'ra.action.close',
create,
createLabel,
createItemLabel,
createValue,
debounce: debounceDelay = 250,
defaultValue,
emptyText,
emptyValue = '',
field: fieldOverride,
format,
helperText,
id: idOverride,
inputText,
isFetching: isFetchingProp,
isLoading: isLoadingProp,
isRequired: isRequiredOverride,
label,
limitChoicesToValue,
matchSuggestion,
margin,
fieldState: fieldStateOverride,
filterToQuery = DefaultFilterToQuery,
formState: formStateOverride,
multiple = false,
noOptionsText,
onBlur,
onChange,
onCreate,
openText = 'ra.action.open',
optionText,
optionValue,
parse,
resource: resourceProp,
shouldRenderSuggestions,
setFilter,
size,
source: sourceProp,
suggestionLimit = Infinity,
TextFieldProps,
translateChoice,
validate,
variant,
...rest
} = props;
const {
allChoices,
isLoading,
error: fetchError,
resource,
source,
setFilters,
isFromReference,
} = useChoicesContext({
choices: choicesProp,
isFetching: isFetchingProp,
isLoading: isLoadingProp,
resource: resourceProp,
source: sourceProp,
});
const translate = useTranslate();
const finalEmptyText = emptyText ?? '';
const {
id,
field,
isRequired,
fieldState: { error, invalid, isTouched },
formState: { isSubmitted },
} = useInput({
defaultValue,
id: idOverride,
field: fieldOverride,
fieldState: fieldStateOverride,
formState: formStateOverride,
isRequired: isRequiredOverride,
onBlur,
onChange,
parse,
format,
resource,
source,
validate,
...rest,
});
const finalChoices = useMemo(
() =>
isRequired || multiple
? allChoices
: [
{
[optionValue || 'id']: emptyValue,
[typeof optionText === 'string'
? optionText
: 'name']: translate(finalEmptyText, {
_: finalEmptyText,
}),
},
].concat(allChoices),
[
allChoices,
emptyValue,
finalEmptyText,
isRequired,
multiple,
optionText,
optionValue,
translate,
]
);
const selectedChoice = useSelectedChoice<
OptionType,
Multiple,
DisableClearable,
SupportCreate
>(field.value, {
choices: finalChoices,
// @ts-ignore
multiple,
optionValue,
});
useEffect(() => {
// eslint-disable-next-line eqeqeq
if (emptyValue == null) {
throw new Error(
`emptyValue being set to null or undefined is not supported. Use parse to turn the empty string into null.`
);
}
}, [emptyValue]);
useEffect(() => {
// eslint-disable-next-line eqeqeq
if (isValidElement(optionText) && emptyText != undefined) {
throw new Error(
`optionText of type React element is not supported when setting emptyText`
);
}
// eslint-disable-next-line eqeqeq
if (isValidElement(optionText) && inputText == undefined) {
throw new Error(`
If you provided a React element for the optionText prop, you must also provide the inputText prop (used for the text input)`);
}
// eslint-disable-next-line eqeqeq
if (isValidElement(optionText) && matchSuggestion == undefined) {
throw new Error(`
If you provided a React element for the optionText prop, you must also provide the matchSuggestion prop (used to match the user input with a choice)`);
}
}, [optionText, inputText, matchSuggestion, emptyText]);
useEffect(() => {
warning(
/* eslint-disable eqeqeq */
shouldRenderSuggestions != undefined && noOptionsText == undefined,
`When providing a shouldRenderSuggestions function, we recommend you also provide the noOptionsText prop and set it to a text explaining users why no options are displayed. It supports translation keys.`
);
/* eslint-enable eqeqeq */
}, [shouldRenderSuggestions, noOptionsText]);
const getRecordRepresentation = useGetRecordRepresentation(resource);
const { getChoiceText, getChoiceValue, getSuggestions } = useSuggestions({
choices: finalChoices,
limitChoicesToValue,
matchSuggestion,
optionText:
optionText ??
(isFromReference ? getRecordRepresentation : undefined),
optionValue,
selectedItem: selectedChoice,
suggestionLimit,
translateChoice,
});
const [filterValue, setFilterValue] = useState('');
const handleChange = (newValue: any) => {
if (multiple) {
if (Array.isArray(newValue)) {
field.onChange(newValue.map(getChoiceValue));
} else {
field.onChange([
...(field.value ?? []),
getChoiceValue(newValue),
]);
}
} else {
field.onChange(getChoiceValue(newValue) ?? emptyValue);
}
};
// eslint-disable-next-line
const debouncedSetFilter = useCallback(
debounce(filter => {
if (setFilter) {
return setFilter(filter);
}
if (choicesProp) {
return;
}
setFilters(filterToQuery(filter), undefined, true);
}, debounceDelay),
[debounceDelay, setFilters, setFilter]
);
// 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
const currentValue = useRef(field.value);
useEffect(() => {
if (!isEqual(currentValue.current, field.value)) {
currentValue.current = field.value;
debouncedSetFilter('');
}
}, [field.value]); // eslint-disable-line
const {
getCreateItem,
handleChange: handleChangeWithCreateSupport,
createElement,
createId,
} = useSupportCreateSuggestion({
create,
createLabel,
createItemLabel,
createValue,
handleChange,
filter: filterValue,
onCreate,
optionText,
});
const getOptionLabel = useCallback(
(option: any, isListItem: boolean = false) => {
// eslint-disable-next-line eqeqeq
if (option == undefined) {
return '';
}
// Value selected with enter, right from the input
if (typeof option === 'string') {
return option;
}
if (option?.id === createId) {
return option?.name;
}
if (!isListItem && option[optionValue || 'id'] === emptyValue) {
return option[
typeof optionText === 'string' ? optionText : 'name'
];
}
if (!isListItem && inputText !== undefined) {
return inputText(option);
}
return getChoiceText(option);
},
[
getChoiceText,
inputText,
createId,
optionText,
optionValue,
emptyValue,
]
);
const finalOnBlur = useCallback((): void => {
if (clearOnBlur) {
const optionLabel = getOptionLabel(selectedChoice);
setFilterValue(optionLabel);
}
field.onBlur();
}, [clearOnBlur, field, selectedChoice, getOptionLabel]);
useEffect(() => {
if (!multiple) {
const optionLabel = getOptionLabel(selectedChoice);
if (typeof optionLabel === 'string') {
setFilterValue(optionLabel);
} else {
throw new Error(
'When optionText returns a React element, you must also provide the inputText prop'
);
}
}
}, [getOptionLabel, multiple, selectedChoice]);
const handleInputChange = (
event: any,
newInputValue: string,
reason: string
) => {
if (
event?.type === 'change' ||
!doesQueryMatchSelection(newInputValue)
) {
setFilterValue(newInputValue);
debouncedSetFilter(newInputValue);
}
};
const doesQueryMatchSelection = useCallback(
(filter: string) => {
let selectedItemTexts;
if (multiple) {
selectedItemTexts = selectedChoice.map(item =>
getOptionLabel(item)
);
} else {
selectedItemTexts = [getOptionLabel(selectedChoice)];
}
return selectedItemTexts.includes(filter);
},
[getOptionLabel, multiple, selectedChoice]
);
const doesQueryMatchSuggestion = useCallback(
filter => {
const hasOption = !!finalChoices
? finalChoices.some(choice => getOptionLabel(choice) === filter)
: false;
return doesQueryMatchSelection(filter) || hasOption;
},
[finalChoices, getOptionLabel, doesQueryMatchSelection]
);
const filterOptions = (options, params) => {
let filteredOptions =
isFromReference || // When used inside a reference, AutocompleteInput shouldn't do the filtering as it's done by the reference input
matchSuggestion || // When using element as optionText (and matchSuggestion), options are filtered by getSuggestions, so they shouldn't be filtered here
limitChoicesToValue // When limiting choices to values (why? it's legacy!), options are also filtered by getSuggestions, so they shouldn't be filtered here
? options
: defaultFilterOptions(options, params); // Otherwise, we let MUI's Autocomplete do the filtering
// add create option if necessary
const { inputValue } = params;
if (
(onCreate || create) &&
inputValue !== '' &&
!doesQueryMatchSuggestion(filterValue)
) {
filteredOptions = filteredOptions.concat(getCreateItem(inputValue));
}
return filteredOptions;
};
const handleAutocompleteChange = (
event: any,
newValue: any,
reason: string
) => {
handleChangeWithCreateSupport(newValue != null ? newValue : emptyValue);
};
const oneSecondHasPassed = useTimeout(1000, filterValue);
const suggestions = useMemo(() => {
if (matchSuggestion || limitChoicesToValue) {
return getSuggestions(filterValue);
}
return finalChoices?.slice(0, suggestionLimit) || [];
}, [
finalChoices,
filterValue,
getSuggestions,
limitChoicesToValue,
matchSuggestion,
suggestionLimit,
]);
const isOptionEqualToValue = (option, value) => {
return getChoiceValue(option) === getChoiceValue(value);
};
return (
<>
<StyledAutocomplete
blurOnSelect
className={clsx('ra-input', `ra-input-${source}`, className)}
clearText={translate(clearText, { _: clearText })}
closeText={translate(closeText, { _: closeText })}
openOnFocus
openText={translate(openText, { _: openText })}
id={id}
isOptionEqualToValue={isOptionEqualToValue}
filterSelectedOptions
renderInput={params => (
<TextField
name={field.name}
label={
<FieldTitle
label={label}
source={source}
resource={resourceProp}
isRequired={
typeof isRequiredOverride !== 'undefined'
? isRequiredOverride
: isRequired
}
/>
}
error={
!!fetchError ||
((isTouched || isSubmitted) && invalid)
}
helperText={
<InputHelperText
touched={isTouched || isSubmitted || fetchError}
error={error?.message || fetchError?.message}
helperText={helperText}
/>
}
margin={margin}
variant={variant}
className={AutocompleteInputClasses.textField}
{...TextFieldProps}
{...params}
size={size}
/>
)}
multiple={multiple}
renderTags={(value, getTagProps) =>
value.map((option, index) => (
<Chip
label={
isValidElement(optionText)
? inputText(option)
: getChoiceText(option)
}
sx={{
'.MuiSvgIcon-root': {
// FIXME: Workaround to allow choices deletion
// Maybe related to storybook and mui using different versions of emotion
zIndex: 100,
},
}}
size="small"
{...getTagProps({ index })}
/>
))
}
noOptionsText={
typeof noOptionsText === 'string'
? translate(noOptionsText, { _: noOptionsText })
: noOptionsText
}
selectOnFocus
clearOnBlur={clearOnBlur}
{...sanitizeInputRestProps(rest)}
freeSolo={!!create || !!onCreate}
handleHomeEndKeys={!!create || !!onCreate}
filterOptions={filterOptions}
options={
shouldRenderSuggestions == undefined || // eslint-disable-line eqeqeq
shouldRenderSuggestions(filterValue)
? suggestions
: []
}
getOptionLabel={getOptionLabel}
inputValue={filterValue}
loading={
isLoading &&
(!finalChoices || finalChoices.length === 0) &&
oneSecondHasPassed
}
value={selectedChoice}
onChange={handleAutocompleteChange}
onBlur={finalOnBlur}
onInputChange={handleInputChange}
renderOption={(props, record: RaRecord) => {
(props as {
key: string;
}).key = getChoiceValue(record);
const optionLabel = getOptionLabel(record, true);
return (
<li {...props}>
{optionLabel === '' ? ' ' : optionLabel}
</li>
);
}}
/>
{createElement}
</>
);
};
const PREFIX = 'RaAutocompleteInput';
export const AutocompleteInputClasses = {
textField: `${PREFIX}-textField`,
};
const StyledAutocomplete = styled(Autocomplete, {
name: PREFIX,
overridesResolver: (props, styles) => styles.root,
})(({ theme }) => ({
[`& .${AutocompleteInputClasses.textField}`]: {
minWidth: theme.spacing(20),
},
}));
// @ts-ignore
export interface AutocompleteInputProps<
OptionType extends any = RaRecord,
Multiple extends boolean | undefined = false,
DisableClearable extends boolean | undefined = false,
SupportCreate extends boolean | undefined = false
> extends Omit<CommonInputProps, 'source'>,
ChoicesProps,
UseSuggestionsOptions,
Omit<SupportCreateSuggestionOptions, 'handleChange' | 'optionText'>,
Omit<
AutocompleteProps<
OptionType,
Multiple,
DisableClearable,
SupportCreate
>,
'onChange' | 'options' | 'renderInput'
> {
children?: ReactNode;
debounce?: number;
emptyText?: string;
emptyValue?: any;
filterToQuery?: (searchText: string) => any;
inputText?: (option: any) => string;
setFilter?: (value: string) => void;
shouldRenderSuggestions?: any;
// Source is optional as AutocompleteInput can be used inside a ReferenceInput that already defines the source
source?: string;
TextFieldProps?: TextFieldProps;
}
/**
* Returns the selected choice (or choices if multiple) by matching the input value with the choices.
*/
const useSelectedChoice = <
OptionType extends any = RaRecord,
Multiple extends boolean | undefined = false,
DisableClearable extends boolean | undefined = false,
SupportCreate extends boolean | undefined = false
>(
value: any,
{
choices,
multiple,
optionValue,
}: AutocompleteInputProps<
OptionType,
Multiple,
DisableClearable,
SupportCreate
>
) => {
const selectedChoiceRef = useRef(
getSelectedItems(choices, value, optionValue, multiple)
);
const [selectedChoice, setSelectedChoice] = useState<RaRecord | RaRecord[]>(
() => getSelectedItems(choices, value, optionValue, multiple)
);
// As the selected choices are objects, we want to ensure we pass the same
// reference to the Autocomplete as it would reset its filter value otherwise.
useEffect(() => {
const newSelectedItems = getSelectedItems(
choices,
value,
optionValue,
multiple
);
if (!isEqual(selectedChoiceRef.current, newSelectedItems)) {
selectedChoiceRef.current = newSelectedItems;
setSelectedChoice(newSelectedItems);
}
}, [choices, value, multiple, optionValue]);
return selectedChoice || null;
};
const getSelectedItems = (
choices = [],
value,
optionValue = 'id',
multiple
) => {
if (multiple) {
return (value || [])
.map(item =>
choices.find(choice => item === get(choice, optionValue))
)
.filter(item => !!item);
}
return choices.find(choice => get(choice, optionValue) === value) || '';
};
const DefaultFilterToQuery = searchText => ({ q: searchText });