UNPKG

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