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