UNPKG

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