UNPKG

33.6 kBJavaScriptView Raw
1import _extends from "@babel/runtime/helpers/esm/extends";
2/* eslint-disable no-constant-condition */
3import * as React from 'react';
4import { unstable_setRef as setRef, unstable_useEventCallback as useEventCallback, unstable_useControlled as useControlled, unstable_useId as useId, usePreviousProps } from '@mui/utils';
5
6// https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
7// Give up on IE11 support for this feature
8function stripDiacritics(string) {
9 return typeof string.normalize !== 'undefined' ? string.normalize('NFD').replace(/[\u0300-\u036f]/g, '') : string;
10}
11export function createFilterOptions(config = {}) {
12 const {
13 ignoreAccents = true,
14 ignoreCase = true,
15 limit,
16 matchFrom = 'any',
17 stringify,
18 trim = false
19 } = config;
20 return (options, {
21 inputValue,
22 getOptionLabel
23 }) => {
24 let input = trim ? inputValue.trim() : inputValue;
25 if (ignoreCase) {
26 input = input.toLowerCase();
27 }
28 if (ignoreAccents) {
29 input = stripDiacritics(input);
30 }
31 const filteredOptions = !input ? options : options.filter(option => {
32 let candidate = (stringify || getOptionLabel)(option);
33 if (ignoreCase) {
34 candidate = candidate.toLowerCase();
35 }
36 if (ignoreAccents) {
37 candidate = stripDiacritics(candidate);
38 }
39 return matchFrom === 'start' ? candidate.indexOf(input) === 0 : candidate.indexOf(input) > -1;
40 });
41 return typeof limit === 'number' ? filteredOptions.slice(0, limit) : filteredOptions;
42 };
43}
44
45// To replace with .findIndex() once we stop IE11 support.
46function findIndex(array, comp) {
47 for (let i = 0; i < array.length; i += 1) {
48 if (comp(array[i])) {
49 return i;
50 }
51 }
52 return -1;
53}
54const defaultFilterOptions = createFilterOptions();
55
56// Number of options to jump in list box when `Page Up` and `Page Down` keys are used.
57const pageSize = 5;
58const defaultIsActiveElementInListbox = listboxRef => listboxRef.current !== null && listboxRef.current.parentElement?.contains(document.activeElement);
59export default function useAutocomplete(props) {
60 const {
61 // eslint-disable-next-line @typescript-eslint/naming-convention
62 unstable_isActiveElementInListbox = defaultIsActiveElementInListbox,
63 // eslint-disable-next-line @typescript-eslint/naming-convention
64 unstable_classNamePrefix = 'Mui',
65 autoComplete = false,
66 autoHighlight = false,
67 autoSelect = false,
68 blurOnSelect = false,
69 clearOnBlur = !props.freeSolo,
70 clearOnEscape = false,
71 componentName = 'useAutocomplete',
72 defaultValue = props.multiple ? [] : null,
73 disableClearable = false,
74 disableCloseOnSelect = false,
75 disabled: disabledProp,
76 disabledItemsFocusable = false,
77 disableListWrap = false,
78 filterOptions = defaultFilterOptions,
79 filterSelectedOptions = false,
80 freeSolo = false,
81 getOptionDisabled,
82 getOptionLabel: getOptionLabelProp = option => option.label ?? option,
83 groupBy,
84 handleHomeEndKeys = !props.freeSolo,
85 id: idProp,
86 includeInputInList = false,
87 inputValue: inputValueProp,
88 isOptionEqualToValue = (option, value) => option === value,
89 multiple = false,
90 onChange,
91 onClose,
92 onHighlightChange,
93 onInputChange,
94 onOpen,
95 open: openProp,
96 openOnFocus = false,
97 options,
98 readOnly = false,
99 selectOnFocus = !props.freeSolo,
100 value: valueProp
101 } = props;
102 const id = useId(idProp);
103 let getOptionLabel = getOptionLabelProp;
104 getOptionLabel = option => {
105 const optionLabel = getOptionLabelProp(option);
106 if (typeof optionLabel !== 'string') {
107 if (process.env.NODE_ENV !== 'production') {
108 const erroneousReturn = optionLabel === undefined ? 'undefined' : `${typeof optionLabel} (${optionLabel})`;
109 console.error(`MUI: The \`getOptionLabel\` method of ${componentName} returned ${erroneousReturn} instead of a string for ${JSON.stringify(option)}.`);
110 }
111 return String(optionLabel);
112 }
113 return optionLabel;
114 };
115 const ignoreFocus = React.useRef(false);
116 const firstFocus = React.useRef(true);
117 const inputRef = React.useRef(null);
118 const listboxRef = React.useRef(null);
119 const [anchorEl, setAnchorEl] = React.useState(null);
120 const [focusedTag, setFocusedTag] = React.useState(-1);
121 const defaultHighlighted = autoHighlight ? 0 : -1;
122 const highlightedIndexRef = React.useRef(defaultHighlighted);
123 const [value, setValueState] = useControlled({
124 controlled: valueProp,
125 default: defaultValue,
126 name: componentName
127 });
128 const [inputValue, setInputValueState] = useControlled({
129 controlled: inputValueProp,
130 default: '',
131 name: componentName,
132 state: 'inputValue'
133 });
134 const [focused, setFocused] = React.useState(false);
135 const resetInputValue = React.useCallback((event, newValue) => {
136 // retain current `inputValue` if new option isn't selected and `clearOnBlur` is false
137 // When `multiple` is enabled, `newValue` is an array of all selected items including the newly selected item
138 const isOptionSelected = multiple ? value.length < newValue.length : newValue !== null;
139 if (!isOptionSelected && !clearOnBlur) {
140 return;
141 }
142 let newInputValue;
143 if (multiple) {
144 newInputValue = '';
145 } else if (newValue == null) {
146 newInputValue = '';
147 } else {
148 const optionLabel = getOptionLabel(newValue);
149 newInputValue = typeof optionLabel === 'string' ? optionLabel : '';
150 }
151 if (inputValue === newInputValue) {
152 return;
153 }
154 setInputValueState(newInputValue);
155 if (onInputChange) {
156 onInputChange(event, newInputValue, 'reset');
157 }
158 }, [getOptionLabel, inputValue, multiple, onInputChange, setInputValueState, clearOnBlur, value]);
159 const [open, setOpenState] = useControlled({
160 controlled: openProp,
161 default: false,
162 name: componentName,
163 state: 'open'
164 });
165 const [inputPristine, setInputPristine] = React.useState(true);
166 const inputValueIsSelectedValue = !multiple && value != null && inputValue === getOptionLabel(value);
167 const popupOpen = open && !readOnly;
168 const filteredOptions = popupOpen ? filterOptions(options.filter(option => {
169 if (filterSelectedOptions && (multiple ? value : [value]).some(value2 => value2 !== null && isOptionEqualToValue(option, value2))) {
170 return false;
171 }
172 return true;
173 }),
174 // we use the empty string to manipulate `filterOptions` to not filter any options
175 // i.e. the filter predicate always returns true
176 {
177 inputValue: inputValueIsSelectedValue && inputPristine ? '' : inputValue,
178 getOptionLabel
179 }) : [];
180 const previousProps = usePreviousProps({
181 filteredOptions,
182 value
183 });
184 React.useEffect(() => {
185 const valueChange = value !== previousProps.value;
186 if (focused && !valueChange) {
187 return;
188 }
189
190 // Only reset the input's value when freeSolo if the component's value changes.
191 if (freeSolo && !valueChange) {
192 return;
193 }
194 resetInputValue(null, value);
195 }, [value, resetInputValue, focused, previousProps.value, freeSolo]);
196 const listboxAvailable = open && filteredOptions.length > 0 && !readOnly;
197 if (process.env.NODE_ENV !== 'production') {
198 if (value !== null && !freeSolo && options.length > 0) {
199 const missingValue = (multiple ? value : [value]).filter(value2 => !options.some(option => isOptionEqualToValue(option, value2)));
200 if (missingValue.length > 0) {
201 console.warn([`MUI: The value provided to ${componentName} is invalid.`, `None of the options match with \`${missingValue.length > 1 ? JSON.stringify(missingValue) : JSON.stringify(missingValue[0])}\`.`, 'You can use the `isOptionEqualToValue` prop to customize the equality test.'].join('\n'));
202 }
203 }
204 }
205 const focusTag = useEventCallback(tagToFocus => {
206 if (tagToFocus === -1) {
207 inputRef.current.focus();
208 } else {
209 anchorEl.querySelector(`[data-tag-index="${tagToFocus}"]`).focus();
210 }
211 });
212
213 // Ensure the focusedTag is never inconsistent
214 React.useEffect(() => {
215 if (multiple && focusedTag > value.length - 1) {
216 setFocusedTag(-1);
217 focusTag(-1);
218 }
219 }, [value, multiple, focusedTag, focusTag]);
220 function validOptionIndex(index, direction) {
221 if (!listboxRef.current || index === -1) {
222 return -1;
223 }
224 let nextFocus = index;
225 while (true) {
226 // Out of range
227 if (direction === 'next' && nextFocus === filteredOptions.length || direction === 'previous' && nextFocus === -1) {
228 return -1;
229 }
230 const option = listboxRef.current.querySelector(`[data-option-index="${nextFocus}"]`);
231
232 // Same logic as MenuList.js
233 const nextFocusDisabled = disabledItemsFocusable ? false : !option || option.disabled || option.getAttribute('aria-disabled') === 'true';
234 if (option && !option.hasAttribute('tabindex') || nextFocusDisabled) {
235 // Move to the next element.
236 nextFocus += direction === 'next' ? 1 : -1;
237 } else {
238 return nextFocus;
239 }
240 }
241 }
242 const setHighlightedIndex = useEventCallback(({
243 event,
244 index,
245 reason = 'auto'
246 }) => {
247 highlightedIndexRef.current = index;
248
249 // does the index exist?
250 if (index === -1) {
251 inputRef.current.removeAttribute('aria-activedescendant');
252 } else {
253 inputRef.current.setAttribute('aria-activedescendant', `${id}-option-${index}`);
254 }
255 if (onHighlightChange) {
256 onHighlightChange(event, index === -1 ? null : filteredOptions[index], reason);
257 }
258 if (!listboxRef.current) {
259 return;
260 }
261 const prev = listboxRef.current.querySelector(`[role="option"].${unstable_classNamePrefix}-focused`);
262 if (prev) {
263 prev.classList.remove(`${unstable_classNamePrefix}-focused`);
264 prev.classList.remove(`${unstable_classNamePrefix}-focusVisible`);
265 }
266 let listboxNode = listboxRef.current;
267 if (listboxRef.current.getAttribute('role') !== 'listbox') {
268 listboxNode = listboxRef.current.parentElement.querySelector('[role="listbox"]');
269 }
270
271 // "No results"
272 if (!listboxNode) {
273 return;
274 }
275 if (index === -1) {
276 listboxNode.scrollTop = 0;
277 return;
278 }
279 const option = listboxRef.current.querySelector(`[data-option-index="${index}"]`);
280 if (!option) {
281 return;
282 }
283 option.classList.add(`${unstable_classNamePrefix}-focused`);
284 if (reason === 'keyboard') {
285 option.classList.add(`${unstable_classNamePrefix}-focusVisible`);
286 }
287
288 // Scroll active descendant into view.
289 // Logic copied from https://www.w3.org/WAI/content-assets/wai-aria-practices/patterns/combobox/examples/js/select-only.js
290 //
291 // Consider this API instead once it has a better browser support:
292 // .scrollIntoView({ scrollMode: 'if-needed', block: 'nearest' });
293 if (listboxNode.scrollHeight > listboxNode.clientHeight && reason !== 'mouse') {
294 const element = option;
295 const scrollBottom = listboxNode.clientHeight + listboxNode.scrollTop;
296 const elementBottom = element.offsetTop + element.offsetHeight;
297 if (elementBottom > scrollBottom) {
298 listboxNode.scrollTop = elementBottom - listboxNode.clientHeight;
299 } else if (element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0) < listboxNode.scrollTop) {
300 listboxNode.scrollTop = element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0);
301 }
302 }
303 });
304 const changeHighlightedIndex = useEventCallback(({
305 event,
306 diff,
307 direction = 'next',
308 reason = 'auto'
309 }) => {
310 if (!popupOpen) {
311 return;
312 }
313 const getNextIndex = () => {
314 const maxIndex = filteredOptions.length - 1;
315 if (diff === 'reset') {
316 return defaultHighlighted;
317 }
318 if (diff === 'start') {
319 return 0;
320 }
321 if (diff === 'end') {
322 return maxIndex;
323 }
324 const newIndex = highlightedIndexRef.current + diff;
325 if (newIndex < 0) {
326 if (newIndex === -1 && includeInputInList) {
327 return -1;
328 }
329 if (disableListWrap && highlightedIndexRef.current !== -1 || Math.abs(diff) > 1) {
330 return 0;
331 }
332 return maxIndex;
333 }
334 if (newIndex > maxIndex) {
335 if (newIndex === maxIndex + 1 && includeInputInList) {
336 return -1;
337 }
338 if (disableListWrap || Math.abs(diff) > 1) {
339 return maxIndex;
340 }
341 return 0;
342 }
343 return newIndex;
344 };
345 const nextIndex = validOptionIndex(getNextIndex(), direction);
346 setHighlightedIndex({
347 index: nextIndex,
348 reason,
349 event
350 });
351
352 // Sync the content of the input with the highlighted option.
353 if (autoComplete && diff !== 'reset') {
354 if (nextIndex === -1) {
355 inputRef.current.value = inputValue;
356 } else {
357 const option = getOptionLabel(filteredOptions[nextIndex]);
358 inputRef.current.value = option;
359
360 // The portion of the selected suggestion that has not been typed by the user,
361 // a completion string, appears inline after the input cursor in the textbox.
362 const index = option.toLowerCase().indexOf(inputValue.toLowerCase());
363 if (index === 0 && inputValue.length > 0) {
364 inputRef.current.setSelectionRange(inputValue.length, option.length);
365 }
366 }
367 }
368 });
369 const checkHighlightedOptionExists = () => {
370 const isSameValue = (value1, value2) => {
371 const label1 = value1 ? getOptionLabel(value1) : '';
372 const label2 = value2 ? getOptionLabel(value2) : '';
373 return label1 === label2;
374 };
375 if (highlightedIndexRef.current !== -1 && previousProps.filteredOptions && previousProps.filteredOptions.length !== filteredOptions.length && (multiple ? value.length === previousProps.value.length && previousProps.value.every((val, i) => getOptionLabel(value[i]) === getOptionLabel(val)) : isSameValue(previousProps.value, value))) {
376 const previousHighlightedOption = previousProps.filteredOptions[highlightedIndexRef.current];
377 if (previousHighlightedOption) {
378 const previousHighlightedOptionExists = filteredOptions.some(option => {
379 return getOptionLabel(option) === getOptionLabel(previousHighlightedOption);
380 });
381 if (previousHighlightedOptionExists) {
382 return true;
383 }
384 }
385 }
386 return false;
387 };
388 const syncHighlightedIndex = React.useCallback(() => {
389 if (!popupOpen) {
390 return;
391 }
392
393 // Check if the previously highlighted option still exists in the updated filtered options list and if the value hasn't changed
394 // If it exists and the value hasn't changed, return, otherwise continue execution
395 if (checkHighlightedOptionExists()) {
396 return;
397 }
398 const valueItem = multiple ? value[0] : value;
399
400 // The popup is empty, reset
401 if (filteredOptions.length === 0 || valueItem == null) {
402 changeHighlightedIndex({
403 diff: 'reset'
404 });
405 return;
406 }
407 if (!listboxRef.current) {
408 return;
409 }
410
411 // Synchronize the value with the highlighted index
412 if (valueItem != null) {
413 const currentOption = filteredOptions[highlightedIndexRef.current];
414
415 // Keep the current highlighted index if possible
416 if (multiple && currentOption && findIndex(value, val => isOptionEqualToValue(currentOption, val)) !== -1) {
417 return;
418 }
419 const itemIndex = findIndex(filteredOptions, optionItem => isOptionEqualToValue(optionItem, valueItem));
420 if (itemIndex === -1) {
421 changeHighlightedIndex({
422 diff: 'reset'
423 });
424 } else {
425 setHighlightedIndex({
426 index: itemIndex
427 });
428 }
429 return;
430 }
431
432 // Prevent the highlighted index to leak outside the boundaries.
433 if (highlightedIndexRef.current >= filteredOptions.length - 1) {
434 setHighlightedIndex({
435 index: filteredOptions.length - 1
436 });
437 return;
438 }
439
440 // Restore the focus to the previous index.
441 setHighlightedIndex({
442 index: highlightedIndexRef.current
443 });
444 // Ignore filteredOptions (and options, isOptionEqualToValue, getOptionLabel) not to break the scroll position
445 // eslint-disable-next-line react-hooks/exhaustive-deps
446 }, [
447 // Only sync the highlighted index when the option switch between empty and not
448 filteredOptions.length,
449 // Don't sync the highlighted index with the value when multiple
450 // eslint-disable-next-line react-hooks/exhaustive-deps
451 multiple ? false : value, filterSelectedOptions, changeHighlightedIndex, setHighlightedIndex, popupOpen, inputValue, multiple]);
452 const handleListboxRef = useEventCallback(node => {
453 setRef(listboxRef, node);
454 if (!node) {
455 return;
456 }
457 syncHighlightedIndex();
458 });
459 if (process.env.NODE_ENV !== 'production') {
460 // eslint-disable-next-line react-hooks/rules-of-hooks
461 React.useEffect(() => {
462 if (!inputRef.current || inputRef.current.nodeName !== 'INPUT') {
463 if (inputRef.current && inputRef.current.nodeName === 'TEXTAREA') {
464 console.warn([`A textarea element was provided to ${componentName} where input was expected.`, `This is not a supported scenario but it may work under certain conditions.`, `A textarea keyboard navigation may conflict with Autocomplete controls (e.g. enter and arrow keys).`, `Make sure to test keyboard navigation and add custom event handlers if necessary.`].join('\n'));
465 } else {
466 console.error([`MUI: Unable to find the input element. It was resolved to ${inputRef.current} while an HTMLInputElement was expected.`, `Instead, ${componentName} expects an input element.`, '', componentName === 'useAutocomplete' ? 'Make sure you have bound getInputProps correctly and that the normal ref/effect resolutions order is guaranteed.' : 'Make sure you have customized the input component correctly.'].join('\n'));
467 }
468 }
469 }, [componentName]);
470 }
471 React.useEffect(() => {
472 syncHighlightedIndex();
473 }, [syncHighlightedIndex]);
474 const handleOpen = event => {
475 if (open) {
476 return;
477 }
478 setOpenState(true);
479 setInputPristine(true);
480 if (onOpen) {
481 onOpen(event);
482 }
483 };
484 const handleClose = (event, reason) => {
485 if (!open) {
486 return;
487 }
488 setOpenState(false);
489 if (onClose) {
490 onClose(event, reason);
491 }
492 };
493 const handleValue = (event, newValue, reason, details) => {
494 if (multiple) {
495 if (value.length === newValue.length && value.every((val, i) => val === newValue[i])) {
496 return;
497 }
498 } else if (value === newValue) {
499 return;
500 }
501 if (onChange) {
502 onChange(event, newValue, reason, details);
503 }
504 setValueState(newValue);
505 };
506 const isTouch = React.useRef(false);
507 const selectNewValue = (event, option, reasonProp = 'selectOption', origin = 'options') => {
508 let reason = reasonProp;
509 let newValue = option;
510 if (multiple) {
511 newValue = Array.isArray(value) ? value.slice() : [];
512 if (process.env.NODE_ENV !== 'production') {
513 const matches = newValue.filter(val => isOptionEqualToValue(option, val));
514 if (matches.length > 1) {
515 console.error([`MUI: The \`isOptionEqualToValue\` method of ${componentName} does not handle the arguments correctly.`, `The component expects a single value to match a given option but found ${matches.length} matches.`].join('\n'));
516 }
517 }
518 const itemIndex = findIndex(newValue, valueItem => isOptionEqualToValue(option, valueItem));
519 if (itemIndex === -1) {
520 newValue.push(option);
521 } else if (origin !== 'freeSolo') {
522 newValue.splice(itemIndex, 1);
523 reason = 'removeOption';
524 }
525 }
526 resetInputValue(event, newValue);
527 handleValue(event, newValue, reason, {
528 option
529 });
530 if (!disableCloseOnSelect && (!event || !event.ctrlKey && !event.metaKey)) {
531 handleClose(event, reason);
532 }
533 if (blurOnSelect === true || blurOnSelect === 'touch' && isTouch.current || blurOnSelect === 'mouse' && !isTouch.current) {
534 inputRef.current.blur();
535 }
536 };
537 function validTagIndex(index, direction) {
538 if (index === -1) {
539 return -1;
540 }
541 let nextFocus = index;
542 while (true) {
543 // Out of range
544 if (direction === 'next' && nextFocus === value.length || direction === 'previous' && nextFocus === -1) {
545 return -1;
546 }
547 const option = anchorEl.querySelector(`[data-tag-index="${nextFocus}"]`);
548
549 // Same logic as MenuList.js
550 if (!option || !option.hasAttribute('tabindex') || option.disabled || option.getAttribute('aria-disabled') === 'true') {
551 nextFocus += direction === 'next' ? 1 : -1;
552 } else {
553 return nextFocus;
554 }
555 }
556 }
557 const handleFocusTag = (event, direction) => {
558 if (!multiple) {
559 return;
560 }
561 if (inputValue === '') {
562 handleClose(event, 'toggleInput');
563 }
564 let nextTag = focusedTag;
565 if (focusedTag === -1) {
566 if (inputValue === '' && direction === 'previous') {
567 nextTag = value.length - 1;
568 }
569 } else {
570 nextTag += direction === 'next' ? 1 : -1;
571 if (nextTag < 0) {
572 nextTag = 0;
573 }
574 if (nextTag === value.length) {
575 nextTag = -1;
576 }
577 }
578 nextTag = validTagIndex(nextTag, direction);
579 setFocusedTag(nextTag);
580 focusTag(nextTag);
581 };
582 const handleClear = event => {
583 ignoreFocus.current = true;
584 setInputValueState('');
585 if (onInputChange) {
586 onInputChange(event, '', 'clear');
587 }
588 handleValue(event, multiple ? [] : null, 'clear');
589 };
590 const handleKeyDown = other => event => {
591 if (other.onKeyDown) {
592 other.onKeyDown(event);
593 }
594 if (event.defaultMuiPrevented) {
595 return;
596 }
597 if (focusedTag !== -1 && ['ArrowLeft', 'ArrowRight'].indexOf(event.key) === -1) {
598 setFocusedTag(-1);
599 focusTag(-1);
600 }
601
602 // Wait until IME is settled.
603 if (event.which !== 229) {
604 switch (event.key) {
605 case 'Home':
606 if (popupOpen && handleHomeEndKeys) {
607 // Prevent scroll of the page
608 event.preventDefault();
609 changeHighlightedIndex({
610 diff: 'start',
611 direction: 'next',
612 reason: 'keyboard',
613 event
614 });
615 }
616 break;
617 case 'End':
618 if (popupOpen && handleHomeEndKeys) {
619 // Prevent scroll of the page
620 event.preventDefault();
621 changeHighlightedIndex({
622 diff: 'end',
623 direction: 'previous',
624 reason: 'keyboard',
625 event
626 });
627 }
628 break;
629 case 'PageUp':
630 // Prevent scroll of the page
631 event.preventDefault();
632 changeHighlightedIndex({
633 diff: -pageSize,
634 direction: 'previous',
635 reason: 'keyboard',
636 event
637 });
638 handleOpen(event);
639 break;
640 case 'PageDown':
641 // Prevent scroll of the page
642 event.preventDefault();
643 changeHighlightedIndex({
644 diff: pageSize,
645 direction: 'next',
646 reason: 'keyboard',
647 event
648 });
649 handleOpen(event);
650 break;
651 case 'ArrowDown':
652 // Prevent cursor move
653 event.preventDefault();
654 changeHighlightedIndex({
655 diff: 1,
656 direction: 'next',
657 reason: 'keyboard',
658 event
659 });
660 handleOpen(event);
661 break;
662 case 'ArrowUp':
663 // Prevent cursor move
664 event.preventDefault();
665 changeHighlightedIndex({
666 diff: -1,
667 direction: 'previous',
668 reason: 'keyboard',
669 event
670 });
671 handleOpen(event);
672 break;
673 case 'ArrowLeft':
674 handleFocusTag(event, 'previous');
675 break;
676 case 'ArrowRight':
677 handleFocusTag(event, 'next');
678 break;
679 case 'Enter':
680 if (highlightedIndexRef.current !== -1 && popupOpen) {
681 const option = filteredOptions[highlightedIndexRef.current];
682 const disabled = getOptionDisabled ? getOptionDisabled(option) : false;
683
684 // Avoid early form validation, let the end-users continue filling the form.
685 event.preventDefault();
686 if (disabled) {
687 return;
688 }
689 selectNewValue(event, option, 'selectOption');
690
691 // Move the selection to the end.
692 if (autoComplete) {
693 inputRef.current.setSelectionRange(inputRef.current.value.length, inputRef.current.value.length);
694 }
695 } else if (freeSolo && inputValue !== '' && inputValueIsSelectedValue === false) {
696 if (multiple) {
697 // Allow people to add new values before they submit the form.
698 event.preventDefault();
699 }
700 selectNewValue(event, inputValue, 'createOption', 'freeSolo');
701 }
702 break;
703 case 'Escape':
704 if (popupOpen) {
705 // Avoid Opera to exit fullscreen mode.
706 event.preventDefault();
707 // Avoid the Modal to handle the event.
708 event.stopPropagation();
709 handleClose(event, 'escape');
710 } else if (clearOnEscape && (inputValue !== '' || multiple && value.length > 0)) {
711 // Avoid Opera to exit fullscreen mode.
712 event.preventDefault();
713 // Avoid the Modal to handle the event.
714 event.stopPropagation();
715 handleClear(event);
716 }
717 break;
718 case 'Backspace':
719 if (multiple && !readOnly && inputValue === '' && value.length > 0) {
720 const index = focusedTag === -1 ? value.length - 1 : focusedTag;
721 const newValue = value.slice();
722 newValue.splice(index, 1);
723 handleValue(event, newValue, 'removeOption', {
724 option: value[index]
725 });
726 }
727 break;
728 case 'Delete':
729 if (multiple && !readOnly && inputValue === '' && value.length > 0 && focusedTag !== -1) {
730 const index = focusedTag;
731 const newValue = value.slice();
732 newValue.splice(index, 1);
733 handleValue(event, newValue, 'removeOption', {
734 option: value[index]
735 });
736 }
737 break;
738 default:
739 }
740 }
741 };
742 const handleFocus = event => {
743 setFocused(true);
744 if (openOnFocus && !ignoreFocus.current) {
745 handleOpen(event);
746 }
747 };
748 const handleBlur = event => {
749 // Ignore the event when using the scrollbar with IE11
750 if (unstable_isActiveElementInListbox(listboxRef)) {
751 inputRef.current.focus();
752 return;
753 }
754 setFocused(false);
755 firstFocus.current = true;
756 ignoreFocus.current = false;
757 if (autoSelect && highlightedIndexRef.current !== -1 && popupOpen) {
758 selectNewValue(event, filteredOptions[highlightedIndexRef.current], 'blur');
759 } else if (autoSelect && freeSolo && inputValue !== '') {
760 selectNewValue(event, inputValue, 'blur', 'freeSolo');
761 } else if (clearOnBlur) {
762 resetInputValue(event, value);
763 }
764 handleClose(event, 'blur');
765 };
766 const handleInputChange = event => {
767 const newValue = event.target.value;
768 if (inputValue !== newValue) {
769 setInputValueState(newValue);
770 setInputPristine(false);
771 if (onInputChange) {
772 onInputChange(event, newValue, 'input');
773 }
774 }
775 if (newValue === '') {
776 if (!disableClearable && !multiple) {
777 handleValue(event, null, 'clear');
778 }
779 } else {
780 handleOpen(event);
781 }
782 };
783 const handleOptionMouseMove = event => {
784 const index = Number(event.currentTarget.getAttribute('data-option-index'));
785 if (highlightedIndexRef.current !== index) {
786 setHighlightedIndex({
787 event,
788 index,
789 reason: 'mouse'
790 });
791 }
792 };
793 const handleOptionTouchStart = event => {
794 setHighlightedIndex({
795 event,
796 index: Number(event.currentTarget.getAttribute('data-option-index')),
797 reason: 'touch'
798 });
799 isTouch.current = true;
800 };
801 const handleOptionClick = event => {
802 const index = Number(event.currentTarget.getAttribute('data-option-index'));
803 selectNewValue(event, filteredOptions[index], 'selectOption');
804 isTouch.current = false;
805 };
806 const handleTagDelete = index => event => {
807 const newValue = value.slice();
808 newValue.splice(index, 1);
809 handleValue(event, newValue, 'removeOption', {
810 option: value[index]
811 });
812 };
813 const handlePopupIndicator = event => {
814 if (open) {
815 handleClose(event, 'toggleInput');
816 } else {
817 handleOpen(event);
818 }
819 };
820
821 // Prevent input blur when interacting with the combobox
822 const handleMouseDown = event => {
823 // Prevent focusing the input if click is anywhere outside the Autocomplete
824 if (!event.currentTarget.contains(event.target)) {
825 return;
826 }
827 if (event.target.getAttribute('id') !== id) {
828 event.preventDefault();
829 }
830 };
831
832 // Focus the input when interacting with the combobox
833 const handleClick = event => {
834 // Prevent focusing the input if click is anywhere outside the Autocomplete
835 if (!event.currentTarget.contains(event.target)) {
836 return;
837 }
838 inputRef.current.focus();
839 if (selectOnFocus && firstFocus.current && inputRef.current.selectionEnd - inputRef.current.selectionStart === 0) {
840 inputRef.current.select();
841 }
842 firstFocus.current = false;
843 };
844 const handleInputMouseDown = event => {
845 if (inputValue === '' || !open) {
846 handlePopupIndicator(event);
847 }
848 };
849 let dirty = freeSolo && inputValue.length > 0;
850 dirty = dirty || (multiple ? value.length > 0 : value !== null);
851 let groupedOptions = filteredOptions;
852 if (groupBy) {
853 // used to keep track of key and indexes in the result array
854 const indexBy = new Map();
855 let warn = false;
856 groupedOptions = filteredOptions.reduce((acc, option, index) => {
857 const group = groupBy(option);
858 if (acc.length > 0 && acc[acc.length - 1].group === group) {
859 acc[acc.length - 1].options.push(option);
860 } else {
861 if (process.env.NODE_ENV !== 'production') {
862 if (indexBy.get(group) && !warn) {
863 console.warn(`MUI: The options provided combined with the \`groupBy\` method of ${componentName} returns duplicated headers.`, 'You can solve the issue by sorting the options with the output of `groupBy`.');
864 warn = true;
865 }
866 indexBy.set(group, true);
867 }
868 acc.push({
869 key: index,
870 index,
871 group,
872 options: [option]
873 });
874 }
875 return acc;
876 }, []);
877 }
878 if (disabledProp && focused) {
879 handleBlur();
880 }
881 return {
882 getRootProps: (other = {}) => _extends({
883 'aria-owns': listboxAvailable ? `${id}-listbox` : null
884 }, other, {
885 onKeyDown: handleKeyDown(other),
886 onMouseDown: handleMouseDown,
887 onClick: handleClick
888 }),
889 getInputLabelProps: () => ({
890 id: `${id}-label`,
891 htmlFor: id
892 }),
893 getInputProps: () => ({
894 id,
895 value: inputValue,
896 onBlur: handleBlur,
897 onFocus: handleFocus,
898 onChange: handleInputChange,
899 onMouseDown: handleInputMouseDown,
900 // if open then this is handled imperatively so don't let react override
901 // only have an opinion about this when closed
902 'aria-activedescendant': popupOpen ? '' : null,
903 'aria-autocomplete': autoComplete ? 'both' : 'list',
904 'aria-controls': listboxAvailable ? `${id}-listbox` : undefined,
905 'aria-expanded': listboxAvailable,
906 // Disable browser's suggestion that might overlap with the popup.
907 // Handle autocomplete but not autofill.
908 autoComplete: 'off',
909 ref: inputRef,
910 autoCapitalize: 'none',
911 spellCheck: 'false',
912 role: 'combobox',
913 disabled: disabledProp
914 }),
915 getClearProps: () => ({
916 tabIndex: -1,
917 onClick: handleClear
918 }),
919 getPopupIndicatorProps: () => ({
920 tabIndex: -1,
921 onClick: handlePopupIndicator
922 }),
923 getTagProps: ({
924 index
925 }) => _extends({
926 key: index,
927 'data-tag-index': index,
928 tabIndex: -1
929 }, !readOnly && {
930 onDelete: handleTagDelete(index)
931 }),
932 getListboxProps: () => ({
933 role: 'listbox',
934 id: `${id}-listbox`,
935 'aria-labelledby': `${id}-label`,
936 ref: handleListboxRef,
937 onMouseDown: event => {
938 // Prevent blur
939 event.preventDefault();
940 }
941 }),
942 getOptionProps: ({
943 index,
944 option
945 }) => {
946 const selected = (multiple ? value : [value]).some(value2 => value2 != null && isOptionEqualToValue(option, value2));
947 const disabled = getOptionDisabled ? getOptionDisabled(option) : false;
948 return {
949 key: getOptionLabel(option),
950 tabIndex: -1,
951 role: 'option',
952 id: `${id}-option-${index}`,
953 onMouseMove: handleOptionMouseMove,
954 onClick: handleOptionClick,
955 onTouchStart: handleOptionTouchStart,
956 'data-option-index': index,
957 'aria-disabled': disabled,
958 'aria-selected': selected
959 };
960 },
961 id,
962 inputValue,
963 value,
964 dirty,
965 expanded: popupOpen && anchorEl,
966 popupOpen,
967 focused: focused || focusedTag !== -1,
968 anchorEl,
969 setAnchorEl,
970 focusedTag,
971 groupedOptions
972 };
973}
\No newline at end of file