forked from mui/material-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Autocomplete.js
776 lines (758 loc) · 22 KB
/
Autocomplete.js
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { withStyles } from '@material-ui/core/styles';
import Popper from '@material-ui/core/Popper';
import ListSubheader from '@material-ui/core/ListSubheader';
import Paper from '@material-ui/core/Paper';
import IconButton from '@material-ui/core/IconButton';
import Chip from '@material-ui/core/Chip';
import CloseIcon from '../internal/svg-icons/Close';
import ArrowDropDownIcon from '../internal/svg-icons/ArrowDropDown';
import useAutocomplete, { createFilterOptions } from '../useAutocomplete';
export { createFilterOptions };
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
'&:hover $clearIndicatorDirty, &$focused $clearIndicatorDirty': {
visibility: 'visible',
},
},
/* Pseudo-class applied to the root element if focused. */
focused: {},
/* Styles applied to the tag elements, e.g. the chips. */
tag: {
margin: 3,
maxWidth: 'calc(100% - 6px)',
},
/* Styles applied to the tag elements, e.g. the chips if `size="small"`. */
tagSizeSmall: {
margin: 2,
maxWidth: 'calc(100% - 4px)',
},
/* Styles applied when the popup icon is rendered. */
hasPopupIcon: {},
/* Styles applied when the clear icon is rendered. */
hasClearIcon: {},
/* Styles applied to the Input element. */
inputRoot: {
flexWrap: 'wrap',
'$hasPopupIcon &, $hasClearIcon &': {
paddingRight: 26 + 4,
},
'$hasPopupIcon$hasClearIcon &': {
paddingRight: 52 + 4,
},
'& $input': {
width: 0,
minWidth: 30,
},
'&[class*="MuiInput-root"]': {
paddingBottom: 1,
'& $input': {
padding: 4,
},
'& $input:first-child': {
padding: '6px 0',
},
},
'&[class*="MuiInput-root"][class*="MuiInput-marginDense"]': {
'& $input': {
padding: '4px 4px 5px',
},
'& $input:first-child': {
padding: '3px 0 6px',
},
},
'&[class*="MuiOutlinedInput-root"]': {
padding: 9,
'$hasPopupIcon &, $hasClearIcon &': {
paddingRight: 26 + 4 + 9,
},
'$hasPopupIcon$hasClearIcon &': {
paddingRight: 52 + 4 + 9,
},
'& $input': {
padding: '9.5px 4px',
},
'& $input:first-child': {
paddingLeft: 6,
},
'& $endAdornment': {
right: 9,
},
},
'&[class*="MuiOutlinedInput-root"][class*="MuiOutlinedInput-marginDense"]': {
padding: 6,
'& $input': {
padding: '4.5px 4px',
},
},
'&[class*="MuiFilledInput-root"]': {
paddingTop: 19,
paddingLeft: 8,
'$hasPopupIcon &, $hasClearIcon &': {
paddingRight: 26 + 4 + 9,
},
'$hasPopupIcon$hasClearIcon &': {
paddingRight: 52 + 4 + 9,
},
'& $input': {
padding: '9px 4px',
},
'& $endAdornment': {
right: 9,
},
},
'&[class*="MuiFilledInput-root"][class*="MuiFilledInput-marginDense"]': {
paddingBottom: 1,
'& $input': {
padding: '4.5px 4px',
},
},
},
/* Styles applied to the input element. */
input: {
flexGrow: 1,
textOverflow: 'ellipsis',
opacity: 0,
},
/* Styles applied to the input element if tag focused. */
inputFocused: {
opacity: 1,
},
/* Styles applied to the endAdornment element. */
endAdornment: {
// We use a position absolute to support wrapping tags.
position: 'absolute',
right: 0,
top: 'calc(50% - 14px)', // Center vertically
},
/* Styles applied to the clear indicator. */
clearIndicator: {
marginRight: -2,
padding: 4,
color: theme.palette.action.active,
visibility: 'hidden',
},
/* Styles applied to the clear indicator if the input is dirty. */
clearIndicatorDirty: {},
/* Styles applied to the popup indicator. */
popupIndicator: {
padding: 2,
marginRight: -2,
color: theme.palette.action.active,
},
/* Styles applied to the popup indicator if the popup is open. */
popupIndicatorOpen: {
transform: 'rotate(180deg)',
},
/* Styles applied to the popper element. */
popper: {
zIndex: theme.zIndex.modal,
},
/* Styles applied to the popper element if `disablePortal={true}`. */
popperDisablePortal: {
position: 'absolute',
},
/* Styles applied to the `Paper` component. */
paper: {
...theme.typography.body1,
overflow: 'hidden',
margin: '4px 0',
'& > ul': {
maxHeight: '40vh',
overflow: 'auto',
},
},
/* Styles applied to the `listbox` component. */
listbox: {
listStyle: 'none',
margin: 0,
padding: '8px 0px',
position: 'relative',
},
/* Styles applied to the loading wrapper. */
loading: {
color: theme.palette.text.secondary,
padding: '14px 16px',
},
/* Styles applied to the no option wrapper. */
noOptions: {
color: theme.palette.text.secondary,
padding: '14px 16px',
},
/* Styles applied to the option elements. */
option: {
minHeight: 48,
display: 'flex',
justifyContent: 'flex-start',
alignItems: 'center',
cursor: 'pointer',
paddingTop: 6,
boxSizing: 'border-box',
outline: '0',
WebkitTapHighlightColor: 'transparent',
paddingBottom: 6,
paddingLeft: 16,
paddingRight: 16,
[theme.breakpoints.up('sm')]: {
minHeight: 'auto',
},
'&[aria-selected="true"]': {
backgroundColor: theme.palette.action.selected,
},
'&[data-focus="true"]': {
backgroundColor: theme.palette.action.hover,
},
'&[aria-disabled="true"]': {
opacity: 0.5,
pointerEvents: 'none',
},
'&:active': {
backgroundColor: theme.palette.action.selected,
},
},
/* Styles applied to the group's label elements. */
groupLabel: {
backgroundColor: theme.palette.background.paper,
top: -8,
},
/* Styles applied to the group's ul elements. */
groupUl: {
padding: 0,
},
});
function DisablePortal(props) {
// eslint-disable-next-line react/prop-types
const { anchorEl, open, ...other } = props;
return <div {...other} />;
}
const Autocomplete = React.forwardRef(function Autocomplete(props, ref) {
/* eslint-disable no-unused-vars */
const {
autoComplete = false,
autoHighlight = false,
autoSelect = false,
blurOnSelect = false,
ChipProps,
classes,
className,
clearOnEscape = false,
clearText = 'Clear',
closeIcon = <CloseIcon fontSize="small" />,
closeText = 'Close',
debug = false,
defaultValue = props.multiple ? [] : null,
disableClearable = false,
disableCloseOnSelect = false,
disabled = false,
disableListWrap = false,
disableOpenOnFocus = false,
disablePortal = false,
filterOptions,
filterSelectedOptions = false,
forcePopupIcon = 'auto',
freeSolo = false,
getOptionDisabled,
getOptionLabel = x => x,
getOptionSelected,
groupBy,
id: idProp,
includeInputInList = false,
inputValue: inputValueProp,
ListboxComponent = 'ul',
ListboxProps,
loading = false,
loadingText = 'Loading…',
multiple = false,
noOptionsText = 'No options',
onNoOptionsSelected,
onChange,
onClose,
onInputChange,
onOpen,
open,
openText = 'Open',
options = [],
PaperComponent = Paper,
PopperComponent: PopperComponentProp = Popper,
popupIcon = <ArrowDropDownIcon />,
renderGroup: renderGroupProp,
renderInput,
renderOption: renderOptionProp,
renderTags,
selectOnFocus = !props.freeSolo,
size = 'medium',
value: valueProp,
...other
} = props;
/* eslint-enable no-unused-vars */
const PopperComponent = disablePortal ? DisablePortal : PopperComponentProp;
const {
getRootProps,
getInputProps,
getInputLabelProps,
getPopupIndicatorProps,
getClearProps,
getTagProps,
getListboxProps,
getNoOptionsSelectedProps,
getOptionProps,
value,
dirty,
id,
popupOpen,
focused,
focusedTag,
anchorEl,
setAnchorEl,
inputValue,
groupedOptions,
} = useAutocomplete({ ...props, componentName: 'Autocomplete' });
let startAdornment;
if (multiple && value.length > 0) {
const getCustomizedTagProps = params => ({
className: clsx(classes.tag, {
[classes.tagSizeSmall]: size === 'small',
}),
disabled,
...getTagProps(params),
});
if (renderTags) {
startAdornment = renderTags(value, getCustomizedTagProps);
} else {
startAdornment = value.map((option, index) => (
<Chip
label={getOptionLabel(option)}
size={size}
{...getCustomizedTagProps({ index })}
{...ChipProps}
/>
));
}
}
const defaultRenderGroup = params => (
<li key={params.key}>
<ListSubheader className={classes.groupLabel} component="div">
{params.key}
</ListSubheader>
<ul className={classes.groupUl}>{params.children}</ul>
</li>
);
const renderGroup = renderGroupProp || defaultRenderGroup;
const renderOption = renderOptionProp || getOptionLabel;
const renderListOption = (option, index) => {
const optionProps = getOptionProps({ option, index });
return (
<li {...optionProps} className={classes.option}>
{renderOption(option, {
selected: optionProps['aria-selected'],
inputValue,
})}
</li>
);
};
const hasClearIcon = !disableClearable && !disabled;
const hasPopupIcon = (!freeSolo || forcePopupIcon === true) && forcePopupIcon !== false;
return (
<React.Fragment>
<div
ref={ref}
className={clsx(
classes.root,
{
[classes.focused]: focused,
[classes.hasClearIcon]: hasClearIcon,
[classes.hasPopupIcon]: hasPopupIcon,
},
className,
)}
{...getRootProps(other)}
>
{renderInput({
id,
disabled,
size: size === 'small' ? 'small' : undefined,
InputLabelProps: getInputLabelProps(),
InputProps: {
ref: setAnchorEl,
className: classes.inputRoot,
startAdornment,
endAdornment: (
<div className={classes.endAdornment}>
{hasClearIcon ? (
<IconButton
{...getClearProps()}
aria-label={clearText}
title={clearText}
className={clsx(classes.clearIndicator, {
[classes.clearIndicatorDirty]: dirty,
})}
>
{closeIcon}
</IconButton>
) : null}
{hasPopupIcon ? (
<IconButton
{...getPopupIndicatorProps()}
disabled={disabled}
aria-label={popupOpen ? closeText : openText}
title={popupOpen ? closeText : openText}
className={clsx(classes.popupIndicator, {
[classes.popupIndicatorOpen]: popupOpen,
})}
>
{popupIcon}
</IconButton>
) : null}
</div>
),
},
inputProps: {
className: clsx(classes.input, {
[classes.inputFocused]: focusedTag === -1,
}),
disabled,
...getInputProps(),
},
})}
</div>
{popupOpen && anchorEl ? (
<PopperComponent
className={clsx(classes.popper, {
[classes.popperDisablePortal]: disablePortal,
})}
style={{
width: anchorEl ? anchorEl.clientWidth : null,
}}
role="presentation"
anchorEl={anchorEl}
open
>
<PaperComponent className={classes.paper}>
{loading && groupedOptions.length === 0 ? (
<div className={classes.loading}>{loadingText}</div>
) : null}
{groupedOptions.length === 0 && !onNoOptionsSelected && !freeSolo && !loading ? (
<div className={classes.noOptions}>{noOptionsText}</div>
) : null}
{(groupedOptions.length > 0 || (groupedOptions.length === 0 && onNoOptionsSelected)) ? (
<ListboxComponent
className={classes.listbox}
{...getListboxProps()}
{...ListboxProps}
>
{groupedOptions.length === 0 && onNoOptionsSelected ?
<li className={classes.option} {...getNoOptionsSelectedProps()}>
{noOptionsText}
</li> : null
}
{groupedOptions.length > 0 ? groupedOptions.map((option, index) => {
if (groupBy) {
return renderGroup({
key: option.key,
children: option.options.map((option2, index2) =>
renderListOption(option2, option.index + index2),
),
});
}
return renderListOption(option, index);
}) : null}
</ListboxComponent>
) : null}
</PaperComponent>
</PopperComponent>
) : null}
</React.Fragment>
);
});
Autocomplete.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* If `true`, the portion of the selected suggestion that has not been typed by the user,
* known as the completion string, appears inline after the input cursor in the textbox.
* The inline completion string is visually highlighted and has a selected state.
*/
autoComplete: PropTypes.bool,
/**
* If `true`, the first option is automatically highlighted.
*/
autoHighlight: PropTypes.bool,
/**
* If `true`, the selected option becomes the value of the input
* when the Autocomplete loses focus unless the user chooses
* a different option or changes the character string in the input.
*/
autoSelect: PropTypes.bool,
/**
* Control if the input should be blurred when an option is selected:
*
* - `false` the input is not blurred.
* - `true` the input is always blurred.
* - `touch` the input is blurred after a touch event.
* - `mouse` the input is blurred after a mouse event.
*/
blurOnSelect: PropTypes.oneOfType([PropTypes.oneOf(['mouse', 'touch']), PropTypes.bool]),
/**
* Props applied to the [`Chip`](/api/chip/) element.
*/
ChipProps: PropTypes.object,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, clear all values when the user presses escape and the popup is closed.
*/
clearOnEscape: PropTypes.bool,
/**
* Override the default text for the *clear* icon button.
*
* For localization purposes, you can use the provided [translations](/guides/localization/).
*/
clearText: PropTypes.string,
/**
* The icon to display in place of the default close icon.
*/
closeIcon: PropTypes.node,
/**
* Override the default text for the *close popup* icon button.
*
* For localization purposes, you can use the provided [translations](/guides/localization/).
*/
closeText: PropTypes.string,
/**
* If `true`, the popup will ignore the blur event if the input if filled.
* You can inspect the popup markup with your browser tools.
* Consider this option when you need to customize the component.
*/
debug: PropTypes.bool,
/**
* The default input value. Use when the component is not controlled.
*/
defaultValue: PropTypes.oneOfType([PropTypes.any, PropTypes.array]),
/**
* If `true`, the input can't be cleared.
*/
disableClearable: PropTypes.bool,
/**
* If `true`, the popup won't close when a value is selected.
*/
disableCloseOnSelect: PropTypes.bool,
/**
* If `true`, the input will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the list box in the popup will not wrap focus.
*/
disableListWrap: PropTypes.bool,
/**
* If `true`, the popup won't open on input focus.
*/
disableOpenOnFocus: PropTypes.bool,
/**
* Disable the portal behavior.
* The children stay within it's parent DOM hierarchy.
*/
disablePortal: PropTypes.bool,
/**
* A filter function that determines the options that are eligible.
*
* @param {T[]} options The options to render.
* @param {object} state The state of the component.
* @returns {T[]}
*/
filterOptions: PropTypes.func,
/**
* If `true`, hide the selected options from the list box.
*/
filterSelectedOptions: PropTypes.bool,
/**
* Force the visibility display of the popup icon.
*/
forcePopupIcon: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.bool]),
/**
* If `true`, the Autocomplete is free solo, meaning that the user input is not bound to provided options.
*/
freeSolo: PropTypes.bool,
/**
* Used to determine the disabled state for a given option.
*/
getOptionDisabled: PropTypes.func,
/**
* Used to determine the string value for a given option.
* It's used to fill the input (and the list box options if `renderOption` is not provided).
*/
getOptionLabel: PropTypes.func,
/**
* Used to determine if an option is selected.
* Uses strict equality by default.
*/
getOptionSelected: PropTypes.func,
/**
* If provided, the options will be grouped under the returned string.
* The groupBy value is also used as the text for group headings when `renderGroup` is not provided.
*
* @param {T} options The option to group.
* @returns {string}
*/
groupBy: PropTypes.func,
/**
* This prop is used to help implement the accessibility logic.
* If you don't provide this prop. It falls back to a randomly generated id.
*/
id: PropTypes.string,
/**
* If `true`, the highlight can move to the input.
*/
includeInputInList: PropTypes.bool,
/**
* The input value.
*/
inputValue: PropTypes.string,
/**
* The component used to render the listbox.
*/
ListboxComponent: PropTypes.elementType,
/**
* Props applied to the Listbox element.
*/
ListboxProps: PropTypes.object,
/**
* If `true`, the component is in a loading state.
*/
loading: PropTypes.bool,
/**
* Text to display when in a loading state.
*
* For localization purposes, you can use the provided [translations](/guides/localization/).
*/
loadingText: PropTypes.node,
/**
* If `true`, `value` must be an array and the menu will support multiple selections.
*/
multiple: PropTypes.bool,
/**
* Text to display when there are no options.
*
* For localization purposes, you can use the provided [translations](/guides/localization/).
*/
noOptionsText: PropTypes.node,
/**
* Callback fired when the value changes.
*
* @param {object} event The event source of the callback.
* @param {T} value
*/
onChange: PropTypes.func,
/**
* Callback fired when the popup requests to be closed.
* Use in controlled mode (see open).
*
* @param {object} event The event source of the callback.
*/
onClose: PropTypes.func,
/**
* Callback fired when the input value changes.
*
* @param {object} event The event source of the callback.
* @param {string} value The new value of the text input.
* @param {string} reason Can be: `"input"` (user input), `"reset"` (programmatic change), `"clear"`.
*/
onInputChange: PropTypes.func,
/**
* Text to display when there are no options.
*
* For localization purposes, you can use the provided [translations](/guides/localization/).
*/
onNoOptionsSelected: PropTypes.elementType,
/**
* Callback fired when the popup requests to be opened.
* Use in controlled mode (see open).
*
* @param {object} event The event source of the callback.
*/
onOpen: PropTypes.func,
/**
* Control the popup` open state.
*/
open: PropTypes.bool,
/**
* Override the default text for the *open popup* icon button.
*
* For localization purposes, you can use the provided [translations](/guides/localization/).
*/
openText: PropTypes.string,
/**
* Array of options.
*/
options: PropTypes.array,
/**
* The component used to render the body of the popup.
*/
PaperComponent: PropTypes.elementType,
/**
* The component used to position the popup.
*/
PopperComponent: PropTypes.elementType,
/**
* The icon to display in place of the default popup icon.
*/
popupIcon: PropTypes.node,
/**
* Render the group.
*
* @param {any} option The group to render.
* @returns {ReactNode}
*/
renderGroup: PropTypes.func,
/**
* Render the input.
*
* @param {object} params
* @returns {ReactNode}
*/
renderInput: PropTypes.func.isRequired,
/**
* Render the option, use `getOptionLabel` by default.
*
* @param {T} option The option to render.
* @param {object} state The state of the component.
* @returns {ReactNode}
*/
renderOption: PropTypes.func,
/**
* Render the selected value.
*
* @param {T[]} value The `value` provided to the component.
* @param {function} getTagProps A tag props getter.
* @returns {ReactNode}
*/
renderTags: PropTypes.func,
/**
* If `true`, the input's text will be selected on focus.
*/
selectOnFocus: PropTypes.bool,
/**
* The size of the autocomplete.
*/
size: PropTypes.oneOf(['medium', 'small']),
/**
* The value of the autocomplete.
*
* The value must have reference equality with the option in order to be selected.
* You can customize the equality behavior with the `getOptionSelected` prop.
*/
value: PropTypes.oneOfType([PropTypes.any, PropTypes.array]),
};
export default withStyles(styles, { name: 'MuiAutocomplete' })(Autocomplete);