1 | 'use client';
|
2 |
|
3 |
|
4 | import _extends from "@babel/runtime/helpers/esm/extends";
|
5 | import * as React from 'react';
|
6 | import { unstable_setRef as setRef, unstable_useEventCallback as useEventCallback, unstable_useControlled as useControlled, unstable_useId as useId, usePreviousProps } from '@mui/utils';
|
7 |
|
8 |
|
9 |
|
10 | function stripDiacritics(string) {
|
11 | return typeof string.normalize !== 'undefined' ? string.normalize('NFD').replace(/[\u0300-\u036f]/g, '') : string;
|
12 | }
|
13 | export 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 |
|
48 | function 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 | }
|
56 | const defaultFilterOptions = createFilterOptions();
|
57 |
|
58 |
|
59 | const pageSize = 5;
|
60 | const 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 | };
|
64 | export function useAutocomplete(props) {
|
65 | const {
|
66 |
|
67 | unstable_isActiveElementInListbox = defaultIsActiveElementInListbox,
|
68 |
|
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 |
|
146 |
|
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 |
|
184 |
|
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 |
|
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 |
|
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 |
|
239 | const nextFocusDisabled = disabledItemsFocusable ? false : !option || option.disabled || option.getAttribute('aria-disabled') === 'true';
|
240 | if (option && option.hasAttribute('tabindex') && !nextFocusDisabled) {
|
241 |
|
242 | return nextFocus;
|
243 | }
|
244 |
|
245 |
|
246 |
|
247 | if (direction === 'next') {
|
248 | nextFocus = (nextFocus + 1) % filteredOptions.length;
|
249 | } else {
|
250 | nextFocus = (nextFocus - 1 + filteredOptions.length) % filteredOptions.length;
|
251 | }
|
252 |
|
253 |
|
254 |
|
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 |
|
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 |
|
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 |
|
307 |
|
308 |
|
309 |
|
310 |
|
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 |
|
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 |
|
379 |
|
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 |
|
409 |
|
410 | const previousHighlightedOptionIndex = getPreviousHighlightedOptionIndex();
|
411 | if (previousHighlightedOptionIndex !== -1) {
|
412 | highlightedIndexRef.current = previousHighlightedOptionIndex;
|
413 | return;
|
414 | }
|
415 | const valueItem = multiple ? value[0] : value;
|
416 |
|
417 |
|
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 |
|
429 | if (valueItem != null) {
|
430 | const currentOption = filteredOptions[highlightedIndexRef.current];
|
431 |
|
432 |
|
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 |
|
450 | if (highlightedIndexRef.current >= filteredOptions.length - 1) {
|
451 | setHighlightedIndex({
|
452 | index: filteredOptions.length - 1
|
453 | });
|
454 | return;
|
455 | }
|
456 |
|
457 |
|
458 | setHighlightedIndex({
|
459 | index: highlightedIndexRef.current
|
460 | });
|
461 |
|
462 |
|
463 | }, [
|
464 |
|
465 | filteredOptions.length,
|
466 |
|
467 |
|
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 |
|
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 |
|
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 |
|
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 |
|
620 | if (event.which !== 229) {
|
621 | switch (event.key) {
|
622 | case 'Home':
|
623 | if (popupOpen && handleHomeEndKeys) {
|
624 |
|
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 |
|
637 | event.preventDefault();
|
638 | changeHighlightedIndex({
|
639 | diff: 'end',
|
640 | direction: 'previous',
|
641 | reason: 'keyboard',
|
642 | event
|
643 | });
|
644 | }
|
645 | break;
|
646 | case 'PageUp':
|
647 |
|
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 |
|
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 |
|
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 |
|
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 |
|
702 | event.preventDefault();
|
703 | if (disabled) {
|
704 | return;
|
705 | }
|
706 | selectNewValue(event, option, 'selectOption');
|
707 |
|
708 |
|
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 |
|
715 | event.preventDefault();
|
716 | }
|
717 | selectNewValue(event, inputValue, 'createOption', 'freeSolo');
|
718 | }
|
719 | break;
|
720 | case 'Escape':
|
721 | if (popupOpen) {
|
722 |
|
723 | event.preventDefault();
|
724 |
|
725 | event.stopPropagation();
|
726 | handleClose(event, 'escape');
|
727 | } else if (clearOnEscape && (inputValue !== '' || multiple && value.length > 0)) {
|
728 |
|
729 | event.preventDefault();
|
730 |
|
731 | event.stopPropagation();
|
732 | handleClear(event);
|
733 | }
|
734 | break;
|
735 | case 'Backspace':
|
736 |
|
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 |
|
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 |
|
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 |
|
841 | const handleMouseDown = event => {
|
842 |
|
843 | if (!event.currentTarget.contains(event.target)) {
|
844 | return;
|
845 | }
|
846 | if (event.target.getAttribute('id') !== id) {
|
847 | event.preventDefault();
|
848 | }
|
849 | };
|
850 |
|
851 |
|
852 | const handleClick = event => {
|
853 |
|
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 |
|
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 |
|
920 |
|
921 | 'aria-activedescendant': popupOpen ? '' : null,
|
922 | 'aria-autocomplete': autoComplete ? 'both' : 'list',
|
923 | 'aria-controls': listboxAvailable ? `${id}-listbox` : undefined,
|
924 | 'aria-expanded': listboxAvailable,
|
925 |
|
926 |
|
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 |
|
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 |