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 => listboxRef.current !== null && listboxRef.current.parentElement?.contains(document.activeElement);
|
61 | export function useAutocomplete(props) {
|
62 | const {
|
63 |
|
64 | unstable_isActiveElementInListbox = defaultIsActiveElementInListbox,
|
65 |
|
66 | unstable_classNamePrefix = 'Mui',
|
67 | autoComplete = false,
|
68 | autoHighlight = false,
|
69 | autoSelect = false,
|
70 | blurOnSelect = false,
|
71 | clearOnBlur = !props.freeSolo,
|
72 | clearOnEscape = false,
|
73 | componentName = 'useAutocomplete',
|
74 | defaultValue = props.multiple ? [] : null,
|
75 | disableClearable = false,
|
76 | disableCloseOnSelect = false,
|
77 | disabled: disabledProp,
|
78 | disabledItemsFocusable = false,
|
79 | disableListWrap = false,
|
80 | filterOptions = defaultFilterOptions,
|
81 | filterSelectedOptions = false,
|
82 | freeSolo = false,
|
83 | getOptionDisabled,
|
84 | getOptionKey,
|
85 | getOptionLabel: getOptionLabelProp = option => option.label ?? option,
|
86 | groupBy,
|
87 | handleHomeEndKeys = !props.freeSolo,
|
88 | id: idProp,
|
89 | includeInputInList = false,
|
90 | inputValue: inputValueProp,
|
91 | isOptionEqualToValue = (option, value) => option === value,
|
92 | multiple = false,
|
93 | onChange,
|
94 | onClose,
|
95 | onHighlightChange,
|
96 | onInputChange,
|
97 | onOpen,
|
98 | open: openProp,
|
99 | openOnFocus = false,
|
100 | options,
|
101 | readOnly = false,
|
102 | selectOnFocus = !props.freeSolo,
|
103 | value: valueProp
|
104 | } = props;
|
105 | const id = useId(idProp);
|
106 | let getOptionLabel = getOptionLabelProp;
|
107 | getOptionLabel = option => {
|
108 | const optionLabel = getOptionLabelProp(option);
|
109 | if (typeof optionLabel !== 'string') {
|
110 | if (process.env.NODE_ENV !== 'production') {
|
111 | const erroneousReturn = optionLabel === undefined ? 'undefined' : `${typeof optionLabel} (${optionLabel})`;
|
112 | console.error(`MUI: The \`getOptionLabel\` method of ${componentName} returned ${erroneousReturn} instead of a string for ${JSON.stringify(option)}.`);
|
113 | }
|
114 | return String(optionLabel);
|
115 | }
|
116 | return optionLabel;
|
117 | };
|
118 | const ignoreFocus = React.useRef(false);
|
119 | const firstFocus = React.useRef(true);
|
120 | const inputRef = React.useRef(null);
|
121 | const listboxRef = React.useRef(null);
|
122 | const [anchorEl, setAnchorEl] = React.useState(null);
|
123 | const [focusedTag, setFocusedTag] = React.useState(-1);
|
124 | const defaultHighlighted = autoHighlight ? 0 : -1;
|
125 | const highlightedIndexRef = React.useRef(defaultHighlighted);
|
126 | const [value, setValueState] = useControlled({
|
127 | controlled: valueProp,
|
128 | default: defaultValue,
|
129 | name: componentName
|
130 | });
|
131 | const [inputValue, setInputValueState] = useControlled({
|
132 | controlled: inputValueProp,
|
133 | default: '',
|
134 | name: componentName,
|
135 | state: 'inputValue'
|
136 | });
|
137 | const [focused, setFocused] = React.useState(false);
|
138 | const resetInputValue = React.useCallback((event, newValue) => {
|
139 |
|
140 |
|
141 | const isOptionSelected = multiple ? value.length < newValue.length : newValue !== null;
|
142 | if (!isOptionSelected && !clearOnBlur) {
|
143 | return;
|
144 | }
|
145 | let newInputValue;
|
146 | if (multiple) {
|
147 | newInputValue = '';
|
148 | } else if (newValue == null) {
|
149 | newInputValue = '';
|
150 | } else {
|
151 | const optionLabel = getOptionLabel(newValue);
|
152 | newInputValue = typeof optionLabel === 'string' ? optionLabel : '';
|
153 | }
|
154 | if (inputValue === newInputValue) {
|
155 | return;
|
156 | }
|
157 | setInputValueState(newInputValue);
|
158 | if (onInputChange) {
|
159 | onInputChange(event, newInputValue, 'reset');
|
160 | }
|
161 | }, [getOptionLabel, inputValue, multiple, onInputChange, setInputValueState, clearOnBlur, value]);
|
162 | const [open, setOpenState] = useControlled({
|
163 | controlled: openProp,
|
164 | default: false,
|
165 | name: componentName,
|
166 | state: 'open'
|
167 | });
|
168 | const [inputPristine, setInputPristine] = React.useState(true);
|
169 | const inputValueIsSelectedValue = !multiple && value != null && inputValue === getOptionLabel(value);
|
170 | const popupOpen = open && !readOnly;
|
171 | const filteredOptions = popupOpen ? filterOptions(options.filter(option => {
|
172 | if (filterSelectedOptions && (multiple ? value : [value]).some(value2 => value2 !== null && isOptionEqualToValue(option, value2))) {
|
173 | return false;
|
174 | }
|
175 | return true;
|
176 | }),
|
177 |
|
178 |
|
179 | {
|
180 | inputValue: inputValueIsSelectedValue && inputPristine ? '' : inputValue,
|
181 | getOptionLabel
|
182 | }) : [];
|
183 | const previousProps = usePreviousProps({
|
184 | filteredOptions,
|
185 | value,
|
186 | inputValue
|
187 | });
|
188 | React.useEffect(() => {
|
189 | const valueChange = value !== previousProps.value;
|
190 | if (focused && !valueChange) {
|
191 | return;
|
192 | }
|
193 |
|
194 |
|
195 | if (freeSolo && !valueChange) {
|
196 | return;
|
197 | }
|
198 | resetInputValue(null, value);
|
199 | }, [value, resetInputValue, focused, previousProps.value, freeSolo]);
|
200 | const listboxAvailable = open && filteredOptions.length > 0 && !readOnly;
|
201 | if (process.env.NODE_ENV !== 'production') {
|
202 | if (value !== null && !freeSolo && options.length > 0) {
|
203 | const missingValue = (multiple ? value : [value]).filter(value2 => !options.some(option => isOptionEqualToValue(option, value2)));
|
204 | if (missingValue.length > 0) {
|
205 | 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'));
|
206 | }
|
207 | }
|
208 | }
|
209 | const focusTag = useEventCallback(tagToFocus => {
|
210 | if (tagToFocus === -1) {
|
211 | inputRef.current.focus();
|
212 | } else {
|
213 | anchorEl.querySelector(`[data-tag-index="${tagToFocus}"]`).focus();
|
214 | }
|
215 | });
|
216 |
|
217 |
|
218 | React.useEffect(() => {
|
219 | if (multiple && focusedTag > value.length - 1) {
|
220 | setFocusedTag(-1);
|
221 | focusTag(-1);
|
222 | }
|
223 | }, [value, multiple, focusedTag, focusTag]);
|
224 | function validOptionIndex(index, direction) {
|
225 | if (!listboxRef.current || index < 0 || index >= filteredOptions.length) {
|
226 | return -1;
|
227 | }
|
228 | let nextFocus = index;
|
229 | while (true) {
|
230 | const option = listboxRef.current.querySelector(`[data-option-index="${nextFocus}"]`);
|
231 |
|
232 |
|
233 | const nextFocusDisabled = disabledItemsFocusable ? false : !option || option.disabled || option.getAttribute('aria-disabled') === 'true';
|
234 | if (option && option.hasAttribute('tabindex') && !nextFocusDisabled) {
|
235 |
|
236 | return nextFocus;
|
237 | }
|
238 |
|
239 |
|
240 |
|
241 | if (direction === 'next') {
|
242 | nextFocus = (nextFocus + 1) % filteredOptions.length;
|
243 | } else {
|
244 | nextFocus = (nextFocus - 1 + filteredOptions.length) % filteredOptions.length;
|
245 | }
|
246 |
|
247 |
|
248 |
|
249 | if (nextFocus === index) {
|
250 | return -1;
|
251 | }
|
252 | }
|
253 | }
|
254 | const setHighlightedIndex = useEventCallback(({
|
255 | event,
|
256 | index,
|
257 | reason = 'auto'
|
258 | }) => {
|
259 | highlightedIndexRef.current = index;
|
260 |
|
261 |
|
262 | if (index === -1) {
|
263 | inputRef.current.removeAttribute('aria-activedescendant');
|
264 | } else {
|
265 | inputRef.current.setAttribute('aria-activedescendant', `${id}-option-${index}`);
|
266 | }
|
267 | if (onHighlightChange) {
|
268 | onHighlightChange(event, index === -1 ? null : filteredOptions[index], reason);
|
269 | }
|
270 | if (!listboxRef.current) {
|
271 | return;
|
272 | }
|
273 | const prev = listboxRef.current.querySelector(`[role="option"].${unstable_classNamePrefix}-focused`);
|
274 | if (prev) {
|
275 | prev.classList.remove(`${unstable_classNamePrefix}-focused`);
|
276 | prev.classList.remove(`${unstable_classNamePrefix}-focusVisible`);
|
277 | }
|
278 | let listboxNode = listboxRef.current;
|
279 | if (listboxRef.current.getAttribute('role') !== 'listbox') {
|
280 | listboxNode = listboxRef.current.parentElement.querySelector('[role="listbox"]');
|
281 | }
|
282 |
|
283 |
|
284 | if (!listboxNode) {
|
285 | return;
|
286 | }
|
287 | if (index === -1) {
|
288 | listboxNode.scrollTop = 0;
|
289 | return;
|
290 | }
|
291 | const option = listboxRef.current.querySelector(`[data-option-index="${index}"]`);
|
292 | if (!option) {
|
293 | return;
|
294 | }
|
295 | option.classList.add(`${unstable_classNamePrefix}-focused`);
|
296 | if (reason === 'keyboard') {
|
297 | option.classList.add(`${unstable_classNamePrefix}-focusVisible`);
|
298 | }
|
299 |
|
300 |
|
301 |
|
302 |
|
303 |
|
304 |
|
305 | if (listboxNode.scrollHeight > listboxNode.clientHeight && reason !== 'mouse' && reason !== 'touch') {
|
306 | const element = option;
|
307 | const scrollBottom = listboxNode.clientHeight + listboxNode.scrollTop;
|
308 | const elementBottom = element.offsetTop + element.offsetHeight;
|
309 | if (elementBottom > scrollBottom) {
|
310 | listboxNode.scrollTop = elementBottom - listboxNode.clientHeight;
|
311 | } else if (element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0) < listboxNode.scrollTop) {
|
312 | listboxNode.scrollTop = element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0);
|
313 | }
|
314 | }
|
315 | });
|
316 | const changeHighlightedIndex = useEventCallback(({
|
317 | event,
|
318 | diff,
|
319 | direction = 'next',
|
320 | reason = 'auto'
|
321 | }) => {
|
322 | if (!popupOpen) {
|
323 | return;
|
324 | }
|
325 | const getNextIndex = () => {
|
326 | const maxIndex = filteredOptions.length - 1;
|
327 | if (diff === 'reset') {
|
328 | return defaultHighlighted;
|
329 | }
|
330 | if (diff === 'start') {
|
331 | return 0;
|
332 | }
|
333 | if (diff === 'end') {
|
334 | return maxIndex;
|
335 | }
|
336 | const newIndex = highlightedIndexRef.current + diff;
|
337 | if (newIndex < 0) {
|
338 | if (newIndex === -1 && includeInputInList) {
|
339 | return -1;
|
340 | }
|
341 | if (disableListWrap && highlightedIndexRef.current !== -1 || Math.abs(diff) > 1) {
|
342 | return 0;
|
343 | }
|
344 | return maxIndex;
|
345 | }
|
346 | if (newIndex > maxIndex) {
|
347 | if (newIndex === maxIndex + 1 && includeInputInList) {
|
348 | return -1;
|
349 | }
|
350 | if (disableListWrap || Math.abs(diff) > 1) {
|
351 | return maxIndex;
|
352 | }
|
353 | return 0;
|
354 | }
|
355 | return newIndex;
|
356 | };
|
357 | const nextIndex = validOptionIndex(getNextIndex(), direction);
|
358 | setHighlightedIndex({
|
359 | index: nextIndex,
|
360 | reason,
|
361 | event
|
362 | });
|
363 |
|
364 |
|
365 | if (autoComplete && diff !== 'reset') {
|
366 | if (nextIndex === -1) {
|
367 | inputRef.current.value = inputValue;
|
368 | } else {
|
369 | const option = getOptionLabel(filteredOptions[nextIndex]);
|
370 | inputRef.current.value = option;
|
371 |
|
372 |
|
373 |
|
374 | const index = option.toLowerCase().indexOf(inputValue.toLowerCase());
|
375 | if (index === 0 && inputValue.length > 0) {
|
376 | inputRef.current.setSelectionRange(inputValue.length, option.length);
|
377 | }
|
378 | }
|
379 | }
|
380 | });
|
381 | const getPreviousHighlightedOptionIndex = () => {
|
382 | const isSameValue = (value1, value2) => {
|
383 | const label1 = value1 ? getOptionLabel(value1) : '';
|
384 | const label2 = value2 ? getOptionLabel(value2) : '';
|
385 | return label1 === label2;
|
386 | };
|
387 | 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))) {
|
388 | const previousHighlightedOption = previousProps.filteredOptions[highlightedIndexRef.current];
|
389 | if (previousHighlightedOption) {
|
390 | return findIndex(filteredOptions, option => {
|
391 | return getOptionLabel(option) === getOptionLabel(previousHighlightedOption);
|
392 | });
|
393 | }
|
394 | }
|
395 | return -1;
|
396 | };
|
397 | const syncHighlightedIndex = React.useCallback(() => {
|
398 | if (!popupOpen) {
|
399 | return;
|
400 | }
|
401 |
|
402 |
|
403 |
|
404 | const previousHighlightedOptionIndex = getPreviousHighlightedOptionIndex();
|
405 | if (previousHighlightedOptionIndex !== -1) {
|
406 | highlightedIndexRef.current = previousHighlightedOptionIndex;
|
407 | return;
|
408 | }
|
409 | const valueItem = multiple ? value[0] : value;
|
410 |
|
411 |
|
412 | if (filteredOptions.length === 0 || valueItem == null) {
|
413 | changeHighlightedIndex({
|
414 | diff: 'reset'
|
415 | });
|
416 | return;
|
417 | }
|
418 | if (!listboxRef.current) {
|
419 | return;
|
420 | }
|
421 |
|
422 |
|
423 | if (valueItem != null) {
|
424 | const currentOption = filteredOptions[highlightedIndexRef.current];
|
425 |
|
426 |
|
427 | if (multiple && currentOption && findIndex(value, val => isOptionEqualToValue(currentOption, val)) !== -1) {
|
428 | return;
|
429 | }
|
430 | const itemIndex = findIndex(filteredOptions, optionItem => isOptionEqualToValue(optionItem, valueItem));
|
431 | if (itemIndex === -1) {
|
432 | changeHighlightedIndex({
|
433 | diff: 'reset'
|
434 | });
|
435 | } else {
|
436 | setHighlightedIndex({
|
437 | index: itemIndex
|
438 | });
|
439 | }
|
440 | return;
|
441 | }
|
442 |
|
443 |
|
444 | if (highlightedIndexRef.current >= filteredOptions.length - 1) {
|
445 | setHighlightedIndex({
|
446 | index: filteredOptions.length - 1
|
447 | });
|
448 | return;
|
449 | }
|
450 |
|
451 |
|
452 | setHighlightedIndex({
|
453 | index: highlightedIndexRef.current
|
454 | });
|
455 |
|
456 |
|
457 | }, [
|
458 |
|
459 | filteredOptions.length,
|
460 |
|
461 |
|
462 | multiple ? false : value, filterSelectedOptions, changeHighlightedIndex, setHighlightedIndex, popupOpen, inputValue, multiple]);
|
463 | const handleListboxRef = useEventCallback(node => {
|
464 | setRef(listboxRef, node);
|
465 | if (!node) {
|
466 | return;
|
467 | }
|
468 | syncHighlightedIndex();
|
469 | });
|
470 | if (process.env.NODE_ENV !== 'production') {
|
471 |
|
472 | React.useEffect(() => {
|
473 | if (!inputRef.current || inputRef.current.nodeName !== 'INPUT') {
|
474 | if (inputRef.current && inputRef.current.nodeName === 'TEXTAREA') {
|
475 | 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'));
|
476 | } else {
|
477 | 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'));
|
478 | }
|
479 | }
|
480 | }, [componentName]);
|
481 | }
|
482 | React.useEffect(() => {
|
483 | syncHighlightedIndex();
|
484 | }, [syncHighlightedIndex]);
|
485 | const handleOpen = event => {
|
486 | if (open) {
|
487 | return;
|
488 | }
|
489 | setOpenState(true);
|
490 | setInputPristine(true);
|
491 | if (onOpen) {
|
492 | onOpen(event);
|
493 | }
|
494 | };
|
495 | const handleClose = (event, reason) => {
|
496 | if (!open) {
|
497 | return;
|
498 | }
|
499 | setOpenState(false);
|
500 | if (onClose) {
|
501 | onClose(event, reason);
|
502 | }
|
503 | };
|
504 | const handleValue = (event, newValue, reason, details) => {
|
505 | if (multiple) {
|
506 | if (value.length === newValue.length && value.every((val, i) => val === newValue[i])) {
|
507 | return;
|
508 | }
|
509 | } else if (value === newValue) {
|
510 | return;
|
511 | }
|
512 | if (onChange) {
|
513 | onChange(event, newValue, reason, details);
|
514 | }
|
515 | setValueState(newValue);
|
516 | };
|
517 | const isTouch = React.useRef(false);
|
518 | const selectNewValue = (event, option, reasonProp = 'selectOption', origin = 'options') => {
|
519 | let reason = reasonProp;
|
520 | let newValue = option;
|
521 | if (multiple) {
|
522 | newValue = Array.isArray(value) ? value.slice() : [];
|
523 | if (process.env.NODE_ENV !== 'production') {
|
524 | const matches = newValue.filter(val => isOptionEqualToValue(option, val));
|
525 | if (matches.length > 1) {
|
526 | 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'));
|
527 | }
|
528 | }
|
529 | const itemIndex = findIndex(newValue, valueItem => isOptionEqualToValue(option, valueItem));
|
530 | if (itemIndex === -1) {
|
531 | newValue.push(option);
|
532 | } else if (origin !== 'freeSolo') {
|
533 | newValue.splice(itemIndex, 1);
|
534 | reason = 'removeOption';
|
535 | }
|
536 | }
|
537 | resetInputValue(event, newValue);
|
538 | handleValue(event, newValue, reason, {
|
539 | option
|
540 | });
|
541 | if (!disableCloseOnSelect && (!event || !event.ctrlKey && !event.metaKey)) {
|
542 | handleClose(event, reason);
|
543 | }
|
544 | if (blurOnSelect === true || blurOnSelect === 'touch' && isTouch.current || blurOnSelect === 'mouse' && !isTouch.current) {
|
545 | inputRef.current.blur();
|
546 | }
|
547 | };
|
548 | function validTagIndex(index, direction) {
|
549 | if (index === -1) {
|
550 | return -1;
|
551 | }
|
552 | let nextFocus = index;
|
553 | while (true) {
|
554 |
|
555 | if (direction === 'next' && nextFocus === value.length || direction === 'previous' && nextFocus === -1) {
|
556 | return -1;
|
557 | }
|
558 | const option = anchorEl.querySelector(`[data-tag-index="${nextFocus}"]`);
|
559 |
|
560 |
|
561 | if (!option || !option.hasAttribute('tabindex') || option.disabled || option.getAttribute('aria-disabled') === 'true') {
|
562 | nextFocus += direction === 'next' ? 1 : -1;
|
563 | } else {
|
564 | return nextFocus;
|
565 | }
|
566 | }
|
567 | }
|
568 | const handleFocusTag = (event, direction) => {
|
569 | if (!multiple) {
|
570 | return;
|
571 | }
|
572 | if (inputValue === '') {
|
573 | handleClose(event, 'toggleInput');
|
574 | }
|
575 | let nextTag = focusedTag;
|
576 | if (focusedTag === -1) {
|
577 | if (inputValue === '' && direction === 'previous') {
|
578 | nextTag = value.length - 1;
|
579 | }
|
580 | } else {
|
581 | nextTag += direction === 'next' ? 1 : -1;
|
582 | if (nextTag < 0) {
|
583 | nextTag = 0;
|
584 | }
|
585 | if (nextTag === value.length) {
|
586 | nextTag = -1;
|
587 | }
|
588 | }
|
589 | nextTag = validTagIndex(nextTag, direction);
|
590 | setFocusedTag(nextTag);
|
591 | focusTag(nextTag);
|
592 | };
|
593 | const handleClear = event => {
|
594 | ignoreFocus.current = true;
|
595 | setInputValueState('');
|
596 | if (onInputChange) {
|
597 | onInputChange(event, '', 'clear');
|
598 | }
|
599 | handleValue(event, multiple ? [] : null, 'clear');
|
600 | };
|
601 | const handleKeyDown = other => event => {
|
602 | if (other.onKeyDown) {
|
603 | other.onKeyDown(event);
|
604 | }
|
605 | if (event.defaultMuiPrevented) {
|
606 | return;
|
607 | }
|
608 | if (focusedTag !== -1 && ['ArrowLeft', 'ArrowRight'].indexOf(event.key) === -1) {
|
609 | setFocusedTag(-1);
|
610 | focusTag(-1);
|
611 | }
|
612 |
|
613 |
|
614 | if (event.which !== 229) {
|
615 | switch (event.key) {
|
616 | case 'Home':
|
617 | if (popupOpen && handleHomeEndKeys) {
|
618 |
|
619 | event.preventDefault();
|
620 | changeHighlightedIndex({
|
621 | diff: 'start',
|
622 | direction: 'next',
|
623 | reason: 'keyboard',
|
624 | event
|
625 | });
|
626 | }
|
627 | break;
|
628 | case 'End':
|
629 | if (popupOpen && handleHomeEndKeys) {
|
630 |
|
631 | event.preventDefault();
|
632 | changeHighlightedIndex({
|
633 | diff: 'end',
|
634 | direction: 'previous',
|
635 | reason: 'keyboard',
|
636 | event
|
637 | });
|
638 | }
|
639 | break;
|
640 | case 'PageUp':
|
641 |
|
642 | event.preventDefault();
|
643 | changeHighlightedIndex({
|
644 | diff: -pageSize,
|
645 | direction: 'previous',
|
646 | reason: 'keyboard',
|
647 | event
|
648 | });
|
649 | handleOpen(event);
|
650 | break;
|
651 | case 'PageDown':
|
652 |
|
653 | event.preventDefault();
|
654 | changeHighlightedIndex({
|
655 | diff: pageSize,
|
656 | direction: 'next',
|
657 | reason: 'keyboard',
|
658 | event
|
659 | });
|
660 | handleOpen(event);
|
661 | break;
|
662 | case 'ArrowDown':
|
663 |
|
664 | event.preventDefault();
|
665 | changeHighlightedIndex({
|
666 | diff: 1,
|
667 | direction: 'next',
|
668 | reason: 'keyboard',
|
669 | event
|
670 | });
|
671 | handleOpen(event);
|
672 | break;
|
673 | case 'ArrowUp':
|
674 |
|
675 | event.preventDefault();
|
676 | changeHighlightedIndex({
|
677 | diff: -1,
|
678 | direction: 'previous',
|
679 | reason: 'keyboard',
|
680 | event
|
681 | });
|
682 | handleOpen(event);
|
683 | break;
|
684 | case 'ArrowLeft':
|
685 | handleFocusTag(event, 'previous');
|
686 | break;
|
687 | case 'ArrowRight':
|
688 | handleFocusTag(event, 'next');
|
689 | break;
|
690 | case 'Enter':
|
691 | if (highlightedIndexRef.current !== -1 && popupOpen) {
|
692 | const option = filteredOptions[highlightedIndexRef.current];
|
693 | const disabled = getOptionDisabled ? getOptionDisabled(option) : false;
|
694 |
|
695 |
|
696 | event.preventDefault();
|
697 | if (disabled) {
|
698 | return;
|
699 | }
|
700 | selectNewValue(event, option, 'selectOption');
|
701 |
|
702 |
|
703 | if (autoComplete) {
|
704 | inputRef.current.setSelectionRange(inputRef.current.value.length, inputRef.current.value.length);
|
705 | }
|
706 | } else if (freeSolo && inputValue !== '' && inputValueIsSelectedValue === false) {
|
707 | if (multiple) {
|
708 |
|
709 | event.preventDefault();
|
710 | }
|
711 | selectNewValue(event, inputValue, 'createOption', 'freeSolo');
|
712 | }
|
713 | break;
|
714 | case 'Escape':
|
715 | if (popupOpen) {
|
716 |
|
717 | event.preventDefault();
|
718 |
|
719 | event.stopPropagation();
|
720 | handleClose(event, 'escape');
|
721 | } else if (clearOnEscape && (inputValue !== '' || multiple && value.length > 0)) {
|
722 |
|
723 | event.preventDefault();
|
724 |
|
725 | event.stopPropagation();
|
726 | handleClear(event);
|
727 | }
|
728 | break;
|
729 | case 'Backspace':
|
730 |
|
731 | if (multiple && !readOnly && inputValue === '' && value.length > 0) {
|
732 | const index = focusedTag === -1 ? value.length - 1 : focusedTag;
|
733 | const newValue = value.slice();
|
734 | newValue.splice(index, 1);
|
735 | handleValue(event, newValue, 'removeOption', {
|
736 | option: value[index]
|
737 | });
|
738 | }
|
739 | break;
|
740 | case 'Delete':
|
741 |
|
742 | if (multiple && !readOnly && inputValue === '' && value.length > 0 && focusedTag !== -1) {
|
743 | const index = focusedTag;
|
744 | const newValue = value.slice();
|
745 | newValue.splice(index, 1);
|
746 | handleValue(event, newValue, 'removeOption', {
|
747 | option: value[index]
|
748 | });
|
749 | }
|
750 | break;
|
751 | default:
|
752 | }
|
753 | }
|
754 | };
|
755 | const handleFocus = event => {
|
756 | setFocused(true);
|
757 | if (openOnFocus && !ignoreFocus.current) {
|
758 | handleOpen(event);
|
759 | }
|
760 | };
|
761 | const handleBlur = event => {
|
762 |
|
763 | if (unstable_isActiveElementInListbox(listboxRef)) {
|
764 | inputRef.current.focus();
|
765 | return;
|
766 | }
|
767 | setFocused(false);
|
768 | firstFocus.current = true;
|
769 | ignoreFocus.current = false;
|
770 | if (autoSelect && highlightedIndexRef.current !== -1 && popupOpen) {
|
771 | selectNewValue(event, filteredOptions[highlightedIndexRef.current], 'blur');
|
772 | } else if (autoSelect && freeSolo && inputValue !== '') {
|
773 | selectNewValue(event, inputValue, 'blur', 'freeSolo');
|
774 | } else if (clearOnBlur) {
|
775 | resetInputValue(event, value);
|
776 | }
|
777 | handleClose(event, 'blur');
|
778 | };
|
779 | const handleInputChange = event => {
|
780 | const newValue = event.target.value;
|
781 | if (inputValue !== newValue) {
|
782 | setInputValueState(newValue);
|
783 | setInputPristine(false);
|
784 | if (onInputChange) {
|
785 | onInputChange(event, newValue, 'input');
|
786 | }
|
787 | }
|
788 | if (newValue === '') {
|
789 | if (!disableClearable && !multiple) {
|
790 | handleValue(event, null, 'clear');
|
791 | }
|
792 | } else {
|
793 | handleOpen(event);
|
794 | }
|
795 | };
|
796 | const handleOptionMouseMove = event => {
|
797 | const index = Number(event.currentTarget.getAttribute('data-option-index'));
|
798 | if (highlightedIndexRef.current !== index) {
|
799 | setHighlightedIndex({
|
800 | event,
|
801 | index,
|
802 | reason: 'mouse'
|
803 | });
|
804 | }
|
805 | };
|
806 | const handleOptionTouchStart = event => {
|
807 | setHighlightedIndex({
|
808 | event,
|
809 | index: Number(event.currentTarget.getAttribute('data-option-index')),
|
810 | reason: 'touch'
|
811 | });
|
812 | isTouch.current = true;
|
813 | };
|
814 | const handleOptionClick = event => {
|
815 | const index = Number(event.currentTarget.getAttribute('data-option-index'));
|
816 | selectNewValue(event, filteredOptions[index], 'selectOption');
|
817 | isTouch.current = false;
|
818 | };
|
819 | const handleTagDelete = index => event => {
|
820 | const newValue = value.slice();
|
821 | newValue.splice(index, 1);
|
822 | handleValue(event, newValue, 'removeOption', {
|
823 | option: value[index]
|
824 | });
|
825 | };
|
826 | const handlePopupIndicator = event => {
|
827 | if (open) {
|
828 | handleClose(event, 'toggleInput');
|
829 | } else {
|
830 | handleOpen(event);
|
831 | }
|
832 | };
|
833 |
|
834 |
|
835 | const handleMouseDown = event => {
|
836 |
|
837 | if (!event.currentTarget.contains(event.target)) {
|
838 | return;
|
839 | }
|
840 | if (event.target.getAttribute('id') !== id) {
|
841 | event.preventDefault();
|
842 | }
|
843 | };
|
844 |
|
845 |
|
846 | const handleClick = event => {
|
847 |
|
848 | if (!event.currentTarget.contains(event.target)) {
|
849 | return;
|
850 | }
|
851 | inputRef.current.focus();
|
852 | if (selectOnFocus && firstFocus.current && inputRef.current.selectionEnd - inputRef.current.selectionStart === 0) {
|
853 | inputRef.current.select();
|
854 | }
|
855 | firstFocus.current = false;
|
856 | };
|
857 | const handleInputMouseDown = event => {
|
858 | if (!disabledProp && (inputValue === '' || !open)) {
|
859 | handlePopupIndicator(event);
|
860 | }
|
861 | };
|
862 | let dirty = freeSolo && inputValue.length > 0;
|
863 | dirty = dirty || (multiple ? value.length > 0 : value !== null);
|
864 | let groupedOptions = filteredOptions;
|
865 | if (groupBy) {
|
866 |
|
867 | const indexBy = new Map();
|
868 | let warn = false;
|
869 | groupedOptions = filteredOptions.reduce((acc, option, index) => {
|
870 | const group = groupBy(option);
|
871 | if (acc.length > 0 && acc[acc.length - 1].group === group) {
|
872 | acc[acc.length - 1].options.push(option);
|
873 | } else {
|
874 | if (process.env.NODE_ENV !== 'production') {
|
875 | if (indexBy.get(group) && !warn) {
|
876 | 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`.');
|
877 | warn = true;
|
878 | }
|
879 | indexBy.set(group, true);
|
880 | }
|
881 | acc.push({
|
882 | key: index,
|
883 | index,
|
884 | group,
|
885 | options: [option]
|
886 | });
|
887 | }
|
888 | return acc;
|
889 | }, []);
|
890 | }
|
891 | if (disabledProp && focused) {
|
892 | handleBlur();
|
893 | }
|
894 | return {
|
895 | getRootProps: (other = {}) => _extends({
|
896 | 'aria-owns': listboxAvailable ? `${id}-listbox` : null
|
897 | }, other, {
|
898 | onKeyDown: handleKeyDown(other),
|
899 | onMouseDown: handleMouseDown,
|
900 | onClick: handleClick
|
901 | }),
|
902 | getInputLabelProps: () => ({
|
903 | id: `${id}-label`,
|
904 | htmlFor: id
|
905 | }),
|
906 | getInputProps: () => ({
|
907 | id,
|
908 | value: inputValue,
|
909 | onBlur: handleBlur,
|
910 | onFocus: handleFocus,
|
911 | onChange: handleInputChange,
|
912 | onMouseDown: handleInputMouseDown,
|
913 |
|
914 |
|
915 | 'aria-activedescendant': popupOpen ? '' : null,
|
916 | 'aria-autocomplete': autoComplete ? 'both' : 'list',
|
917 | 'aria-controls': listboxAvailable ? `${id}-listbox` : undefined,
|
918 | 'aria-expanded': listboxAvailable,
|
919 |
|
920 |
|
921 | autoComplete: 'off',
|
922 | ref: inputRef,
|
923 | autoCapitalize: 'none',
|
924 | spellCheck: 'false',
|
925 | role: 'combobox',
|
926 | disabled: disabledProp
|
927 | }),
|
928 | getClearProps: () => ({
|
929 | tabIndex: -1,
|
930 | type: 'button',
|
931 | onClick: handleClear
|
932 | }),
|
933 | getPopupIndicatorProps: () => ({
|
934 | tabIndex: -1,
|
935 | type: 'button',
|
936 | onClick: handlePopupIndicator
|
937 | }),
|
938 | getTagProps: ({
|
939 | index
|
940 | }) => _extends({
|
941 | key: index,
|
942 | 'data-tag-index': index,
|
943 | tabIndex: -1
|
944 | }, !readOnly && {
|
945 | onDelete: handleTagDelete(index)
|
946 | }),
|
947 | getListboxProps: () => ({
|
948 | role: 'listbox',
|
949 | id: `${id}-listbox`,
|
950 | 'aria-labelledby': `${id}-label`,
|
951 | ref: handleListboxRef,
|
952 | onMouseDown: event => {
|
953 |
|
954 | event.preventDefault();
|
955 | }
|
956 | }),
|
957 | getOptionProps: ({
|
958 | index,
|
959 | option
|
960 | }) => {
|
961 | const selected = (multiple ? value : [value]).some(value2 => value2 != null && isOptionEqualToValue(option, value2));
|
962 | const disabled = getOptionDisabled ? getOptionDisabled(option) : false;
|
963 | return {
|
964 | key: getOptionKey?.(option) ?? getOptionLabel(option),
|
965 | tabIndex: -1,
|
966 | role: 'option',
|
967 | id: `${id}-option-${index}`,
|
968 | onMouseMove: handleOptionMouseMove,
|
969 | onClick: handleOptionClick,
|
970 | onTouchStart: handleOptionTouchStart,
|
971 | 'data-option-index': index,
|
972 | 'aria-disabled': disabled,
|
973 | 'aria-selected': selected
|
974 | };
|
975 | },
|
976 | id,
|
977 | inputValue,
|
978 | value,
|
979 | dirty,
|
980 | expanded: popupOpen && anchorEl,
|
981 | popupOpen,
|
982 | focused: focused || focusedTag !== -1,
|
983 | anchorEl,
|
984 | setAnchorEl,
|
985 | focusedTag,
|
986 | groupedOptions
|
987 | };
|
988 | } |
\ | No newline at end of file |