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