@mui/material 5.16.1 → 5.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/Autocomplete/Autocomplete.d.ts +6 -7
  2. package/Autocomplete/Autocomplete.js +1 -1
  3. package/Badge/Badge.d.ts +1 -1
  4. package/Badge/Badge.js +2 -2
  5. package/Badge/useBadge.d.ts +13 -0
  6. package/Badge/useBadge.js +41 -0
  7. package/Badge/useBadge.types.d.ts +40 -0
  8. package/Badge/useBadge.types.js +1 -0
  9. package/Breadcrumbs/Breadcrumbs.d.ts +1 -1
  10. package/Breadcrumbs/Breadcrumbs.js +1 -1
  11. package/CHANGELOG.md +18 -0
  12. package/ClickAwayListener/ClickAwayListener.d.ts +47 -0
  13. package/ClickAwayListener/ClickAwayListener.js +178 -0
  14. package/ClickAwayListener/index.d.ts +2 -2
  15. package/ClickAwayListener/index.js +1 -1
  16. package/InputBase/InputBase.js +2 -2
  17. package/ListItem/ListItem.js +1 -1
  18. package/Menu/Menu.js +1 -1
  19. package/Modal/Modal.d.ts +1 -1
  20. package/Modal/Modal.js +2 -2
  21. package/Modal/ModalManager.d.ts +25 -0
  22. package/Modal/ModalManager.js +213 -0
  23. package/Modal/index.d.ts +1 -1
  24. package/Modal/index.js +1 -1
  25. package/Modal/useModal.d.ts +13 -0
  26. package/Modal/useModal.js +195 -0
  27. package/Modal/useModal.types.d.ts +115 -0
  28. package/Modal/useModal.types.js +1 -0
  29. package/NoSsr/NoSsr.d.ts +25 -0
  30. package/NoSsr/NoSsr.js +73 -0
  31. package/NoSsr/NoSsr.types.d.ts +18 -0
  32. package/NoSsr/NoSsr.types.js +1 -0
  33. package/NoSsr/index.d.ts +3 -2
  34. package/NoSsr/index.js +1 -1
  35. package/Popover/Popover.js +2 -1
  36. package/Popper/BasePopper.d.ts +7 -0
  37. package/Popper/BasePopper.js +372 -0
  38. package/Popper/BasePopper.types.d.ts +130 -0
  39. package/Popper/BasePopper.types.js +1 -0
  40. package/Popper/Popper.d.ts +1 -1
  41. package/Popper/Popper.js +1 -1
  42. package/Popper/index.d.ts +2 -1
  43. package/Popper/index.js +2 -1
  44. package/Popper/popperClasses.d.ts +8 -0
  45. package/Popper/popperClasses.js +7 -0
  46. package/Portal/Portal.d.ts +16 -0
  47. package/Portal/Portal.js +92 -0
  48. package/Portal/Portal.types.d.ts +23 -0
  49. package/Portal/Portal.types.js +1 -0
  50. package/Portal/index.d.ts +3 -2
  51. package/Portal/index.js +1 -1
  52. package/Slider/Slider.d.ts +2 -2
  53. package/Slider/Slider.js +3 -2
  54. package/Slider/useSlider.d.ts +14 -0
  55. package/Slider/useSlider.js +655 -0
  56. package/Slider/useSlider.types.d.ts +228 -0
  57. package/Slider/useSlider.types.js +1 -0
  58. package/Snackbar/Snackbar.d.ts +1 -1
  59. package/Snackbar/Snackbar.js +4 -5
  60. package/Snackbar/useSnackbar.d.ts +14 -0
  61. package/Snackbar/useSnackbar.js +131 -0
  62. package/Snackbar/useSnackbar.types.d.ts +60 -0
  63. package/Snackbar/useSnackbar.types.js +1 -0
  64. package/SwipeableDrawer/SwipeableDrawer.js +1 -1
  65. package/TabScrollButton/TabScrollButton.d.ts +1 -1
  66. package/TabScrollButton/TabScrollButton.js +1 -1
  67. package/TablePagination/TablePagination.js +1 -1
  68. package/Tabs/Tabs.d.ts +1 -1
  69. package/Tabs/Tabs.js +1 -1
  70. package/TextareaAutosize/TextareaAutosize.d.ts +14 -0
  71. package/TextareaAutosize/TextareaAutosize.js +223 -0
  72. package/TextareaAutosize/TextareaAutosize.types.d.ts +13 -0
  73. package/TextareaAutosize/TextareaAutosize.types.js +1 -0
  74. package/TextareaAutosize/index.d.ts +3 -2
  75. package/TextareaAutosize/index.js +1 -1
  76. package/Tooltip/Tooltip.js +2 -3
  77. package/Unstable_TrapFocus/FocusTrap.d.ts +10 -0
  78. package/Unstable_TrapFocus/FocusTrap.js +332 -0
  79. package/Unstable_TrapFocus/FocusTrap.types.d.ts +51 -0
  80. package/Unstable_TrapFocus/FocusTrap.types.js +1 -0
  81. package/Unstable_TrapFocus/index.d.ts +2 -2
  82. package/Unstable_TrapFocus/index.js +1 -1
  83. package/index.d.ts +1 -1
  84. package/index.js +2 -2
  85. package/legacy/Autocomplete/Autocomplete.js +1 -1
  86. package/legacy/Badge/Badge.js +2 -2
  87. package/legacy/Badge/useBadge.js +42 -0
  88. package/legacy/Badge/useBadge.types.js +1 -0
  89. package/legacy/Breadcrumbs/Breadcrumbs.js +1 -1
  90. package/legacy/ClickAwayListener/ClickAwayListener.js +181 -0
  91. package/legacy/ClickAwayListener/index.js +1 -1
  92. package/legacy/InputBase/InputBase.js +2 -2
  93. package/legacy/ListItem/ListItem.js +1 -1
  94. package/legacy/Menu/Menu.js +1 -1
  95. package/legacy/Modal/Modal.js +2 -2
  96. package/legacy/Modal/ModalManager.js +233 -0
  97. package/legacy/Modal/index.js +1 -1
  98. package/legacy/Modal/useModal.js +206 -0
  99. package/legacy/Modal/useModal.types.js +1 -0
  100. package/legacy/NoSsr/NoSsr.js +75 -0
  101. package/legacy/NoSsr/NoSsr.types.js +1 -0
  102. package/legacy/NoSsr/index.js +1 -1
  103. package/legacy/Popover/Popover.js +2 -1
  104. package/legacy/Popper/BasePopper.js +380 -0
  105. package/legacy/Popper/BasePopper.types.js +1 -0
  106. package/legacy/Popper/Popper.js +1 -1
  107. package/legacy/Popper/index.js +2 -1
  108. package/legacy/Popper/popperClasses.js +7 -0
  109. package/legacy/Portal/Portal.js +92 -0
  110. package/legacy/Portal/Portal.types.js +1 -0
  111. package/legacy/Portal/index.js +1 -1
  112. package/legacy/Slider/Slider.js +3 -2
  113. package/legacy/Slider/useSlider.js +701 -0
  114. package/legacy/Slider/useSlider.types.js +1 -0
  115. package/legacy/Snackbar/Snackbar.js +4 -5
  116. package/legacy/Snackbar/useSnackbar.js +141 -0
  117. package/legacy/Snackbar/useSnackbar.types.js +1 -0
  118. package/legacy/SwipeableDrawer/SwipeableDrawer.js +1 -1
  119. package/legacy/TabScrollButton/TabScrollButton.js +1 -1
  120. package/legacy/TablePagination/TablePagination.js +1 -1
  121. package/legacy/Tabs/Tabs.js +1 -1
  122. package/legacy/TextareaAutosize/TextareaAutosize.js +220 -0
  123. package/legacy/TextareaAutosize/TextareaAutosize.types.js +1 -0
  124. package/legacy/TextareaAutosize/index.js +1 -1
  125. package/legacy/Tooltip/Tooltip.js +2 -3
  126. package/legacy/Unstable_TrapFocus/FocusTrap.js +341 -0
  127. package/legacy/Unstable_TrapFocus/FocusTrap.types.js +1 -0
  128. package/legacy/Unstable_TrapFocus/index.js +1 -1
  129. package/legacy/index.js +2 -2
  130. package/legacy/useAutocomplete/useAutocomplete.js +1078 -2
  131. package/legacy/utils/PolymorphicComponent.js +1 -0
  132. package/legacy/utils/areArraysEqual.js +9 -0
  133. package/legacy/utils/index.js +1 -1
  134. package/legacy/utils/shouldSpreadAdditionalProps.js +1 -1
  135. package/legacy/utils/useSlot.js +3 -1
  136. package/modern/Autocomplete/Autocomplete.js +1 -1
  137. package/modern/Badge/Badge.js +2 -2
  138. package/modern/Badge/useBadge.js +41 -0
  139. package/modern/Badge/useBadge.types.js +1 -0
  140. package/modern/Breadcrumbs/Breadcrumbs.js +1 -1
  141. package/modern/ClickAwayListener/ClickAwayListener.js +178 -0
  142. package/modern/ClickAwayListener/index.js +1 -1
  143. package/modern/InputBase/InputBase.js +2 -2
  144. package/modern/ListItem/ListItem.js +1 -1
  145. package/modern/Menu/Menu.js +1 -1
  146. package/modern/Modal/Modal.js +2 -2
  147. package/modern/Modal/ModalManager.js +213 -0
  148. package/modern/Modal/index.js +1 -1
  149. package/modern/Modal/useModal.js +193 -0
  150. package/modern/Modal/useModal.types.js +1 -0
  151. package/modern/NoSsr/NoSsr.js +73 -0
  152. package/modern/NoSsr/NoSsr.types.js +1 -0
  153. package/modern/NoSsr/index.js +1 -1
  154. package/modern/Popover/Popover.js +2 -1
  155. package/modern/Popper/BasePopper.js +371 -0
  156. package/modern/Popper/BasePopper.types.js +1 -0
  157. package/modern/Popper/Popper.js +1 -1
  158. package/modern/Popper/index.js +2 -1
  159. package/modern/Popper/popperClasses.js +7 -0
  160. package/modern/Portal/Portal.js +92 -0
  161. package/modern/Portal/Portal.types.js +1 -0
  162. package/modern/Portal/index.js +1 -1
  163. package/modern/Slider/Slider.js +3 -2
  164. package/modern/Slider/useSlider.js +643 -0
  165. package/modern/Slider/useSlider.types.js +1 -0
  166. package/modern/Snackbar/Snackbar.js +4 -5
  167. package/modern/Snackbar/useSnackbar.js +131 -0
  168. package/modern/Snackbar/useSnackbar.types.js +1 -0
  169. package/modern/SwipeableDrawer/SwipeableDrawer.js +1 -1
  170. package/modern/TabScrollButton/TabScrollButton.js +1 -1
  171. package/modern/TablePagination/TablePagination.js +1 -1
  172. package/modern/Tabs/Tabs.js +1 -1
  173. package/modern/TextareaAutosize/TextareaAutosize.js +223 -0
  174. package/modern/TextareaAutosize/TextareaAutosize.types.js +1 -0
  175. package/modern/TextareaAutosize/index.js +1 -1
  176. package/modern/Tooltip/Tooltip.js +2 -3
  177. package/modern/Unstable_TrapFocus/FocusTrap.js +331 -0
  178. package/modern/Unstable_TrapFocus/FocusTrap.types.js +1 -0
  179. package/modern/Unstable_TrapFocus/index.js +1 -1
  180. package/modern/index.js +2 -2
  181. package/modern/useAutocomplete/useAutocomplete.js +987 -2
  182. package/modern/utils/PolymorphicComponent.js +1 -0
  183. package/modern/utils/areArraysEqual.js +4 -0
  184. package/modern/utils/index.js +1 -1
  185. package/modern/utils/shouldSpreadAdditionalProps.js +1 -1
  186. package/modern/utils/useSlot.js +3 -1
  187. package/node/Autocomplete/Autocomplete.js +3 -3
  188. package/node/Badge/Badge.js +5 -5
  189. package/node/Badge/useBadge.js +46 -0
  190. package/node/Badge/useBadge.types.js +5 -0
  191. package/node/Breadcrumbs/Breadcrumbs.js +2 -2
  192. package/node/ClickAwayListener/ClickAwayListener.js +184 -0
  193. package/node/ClickAwayListener/index.js +1 -1
  194. package/node/InputBase/InputBase.js +7 -7
  195. package/node/ListItem/ListItem.js +3 -3
  196. package/node/Menu/Menu.js +3 -3
  197. package/node/Modal/Modal.js +5 -5
  198. package/node/Modal/ModalManager.js +221 -0
  199. package/node/Modal/index.js +2 -2
  200. package/node/Modal/useModal.js +203 -0
  201. package/node/Modal/useModal.types.js +5 -0
  202. package/node/NoSsr/NoSsr.js +81 -0
  203. package/node/NoSsr/NoSsr.types.js +5 -0
  204. package/node/NoSsr/index.js +3 -2
  205. package/node/Popover/Popover.js +5 -4
  206. package/node/Popper/BasePopper.js +380 -0
  207. package/node/Popper/BasePopper.types.js +5 -0
  208. package/node/Popper/Popper.js +2 -2
  209. package/node/Popper/index.js +14 -1
  210. package/node/Popper/popperClasses.js +15 -0
  211. package/node/Portal/Portal.js +100 -0
  212. package/node/Portal/Portal.types.js +5 -0
  213. package/node/Portal/index.js +3 -2
  214. package/node/Slider/Slider.js +14 -13
  215. package/node/Slider/useSlider.js +666 -0
  216. package/node/Slider/useSlider.types.js +5 -0
  217. package/node/Snackbar/Snackbar.js +9 -10
  218. package/node/Snackbar/useSnackbar.js +139 -0
  219. package/node/Snackbar/useSnackbar.types.js +5 -0
  220. package/node/SwipeableDrawer/SwipeableDrawer.js +2 -2
  221. package/node/TabScrollButton/TabScrollButton.js +3 -3
  222. package/node/TablePagination/TablePagination.js +2 -2
  223. package/node/Tabs/Tabs.js +3 -3
  224. package/node/TextareaAutosize/TextareaAutosize.js +230 -0
  225. package/node/TextareaAutosize/TextareaAutosize.types.js +5 -0
  226. package/node/TextareaAutosize/index.js +3 -2
  227. package/node/Tooltip/Tooltip.js +10 -11
  228. package/node/Unstable_TrapFocus/FocusTrap.js +339 -0
  229. package/node/Unstable_TrapFocus/FocusTrap.types.js +5 -0
  230. package/node/Unstable_TrapFocus/index.js +3 -2
  231. package/node/index.js +3 -3
  232. package/node/useAutocomplete/useAutocomplete.js +997 -18
  233. package/node/utils/PolymorphicComponent.js +5 -0
  234. package/node/utils/areArraysEqual.js +10 -0
  235. package/node/utils/index.js +2 -2
  236. package/node/utils/shouldSpreadAdditionalProps.js +3 -2
  237. package/node/utils/useSlot.js +6 -4
  238. package/package.json +4 -5
  239. package/styles/overrides.d.ts +1 -1
  240. package/umd/material-ui.development.js +9190 -9248
  241. package/umd/material-ui.production.min.js +3 -3
  242. package/useAutocomplete/useAutocomplete.d.ts +460 -2
  243. package/useAutocomplete/useAutocomplete.js +994 -2
  244. package/utils/PolymorphicComponent.d.ts +17 -0
  245. package/utils/PolymorphicComponent.js +1 -0
  246. package/utils/areArraysEqual.d.ts +3 -0
  247. package/utils/areArraysEqual.js +4 -0
  248. package/utils/index.d.ts +2 -1
  249. package/utils/index.js +1 -1
  250. package/utils/shouldSpreadAdditionalProps.js +1 -1
  251. package/utils/types.d.ts +2 -1
  252. package/utils/useSlot.js +3 -1
@@ -1,4 +1,989 @@
1
1
  'use client';
2
2
 
3
- export { useAutocomplete as default } from '@mui/base/useAutocomplete';
4
- export * from '@mui/base/useAutocomplete';
3
+ /* eslint-disable no-constant-condition */
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
+ // https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
9
+ // Give up on IE11 support for this feature
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
+ // To replace with .findIndex() once we stop IE11 support.
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
+ // Number of options to jump in list box when `Page Up` and `Page Down` keys are used.
59
+ const pageSize = 5;
60
+ const defaultIsActiveElementInListbox = listboxRef => listboxRef.current !== null && listboxRef.current.parentElement?.contains(document.activeElement);
61
+ function useAutocomplete(props) {
62
+ const {
63
+ // eslint-disable-next-line @typescript-eslint/naming-convention
64
+ unstable_isActiveElementInListbox = defaultIsActiveElementInListbox,
65
+ // eslint-disable-next-line @typescript-eslint/naming-convention
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
+ // retain current `inputValue` if new option isn't selected and `clearOnBlur` is false
140
+ // When `multiple` is enabled, `newValue` is an array of all selected items including the newly selected item
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
+ // we use the empty string to manipulate `filterOptions` to not filter any options
178
+ // i.e. the filter predicate always returns true
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
+ // Only reset the input's value when freeSolo if the component's value changes.
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
+ // Ensure the focusedTag is never inconsistent
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
+ // Same logic as MenuList.js
233
+ const nextFocusDisabled = disabledItemsFocusable ? false : !option || option.disabled || option.getAttribute('aria-disabled') === 'true';
234
+ if (option && option.hasAttribute('tabindex') && !nextFocusDisabled) {
235
+ // The next option is available
236
+ return nextFocus;
237
+ }
238
+
239
+ // The next option is disabled, move to the next element.
240
+ // with looped index
241
+ if (direction === 'next') {
242
+ nextFocus = (nextFocus + 1) % filteredOptions.length;
243
+ } else {
244
+ nextFocus = (nextFocus - 1 + filteredOptions.length) % filteredOptions.length;
245
+ }
246
+
247
+ // We end up with initial index, that means we don't have available options.
248
+ // All of them are disabled
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
+ // does the index exist?
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
+ // "No results"
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
+ // Scroll active descendant into view.
301
+ // Logic copied from https://www.w3.org/WAI/content-assets/wai-aria-practices/patterns/combobox/examples/js/select-only.js
302
+ // In case of mouse clicks and touch (in mobile devices) we avoid scrolling the element and keep both behaviors same.
303
+ // Consider this API instead once it has a better browser support:
304
+ // .scrollIntoView({ scrollMode: 'if-needed', block: 'nearest' });
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
+ // Sync the content of the input with the highlighted option.
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
+ // The portion of the selected suggestion that has not been typed by the user,
373
+ // a completion string, appears inline after the input cursor in the textbox.
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
+ // Check if the previously highlighted option still exists in the updated filtered options list and if the value and inputValue haven't changed
403
+ // If it exists and the value and the inputValue haven't changed, just update its index, otherwise continue execution
404
+ const previousHighlightedOptionIndex = getPreviousHighlightedOptionIndex();
405
+ if (previousHighlightedOptionIndex !== -1) {
406
+ highlightedIndexRef.current = previousHighlightedOptionIndex;
407
+ return;
408
+ }
409
+ const valueItem = multiple ? value[0] : value;
410
+
411
+ // The popup is empty, reset
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
+ // Synchronize the value with the highlighted index
423
+ if (valueItem != null) {
424
+ const currentOption = filteredOptions[highlightedIndexRef.current];
425
+
426
+ // Keep the current highlighted index if possible
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
+ // Prevent the highlighted index to leak outside the boundaries.
444
+ if (highlightedIndexRef.current >= filteredOptions.length - 1) {
445
+ setHighlightedIndex({
446
+ index: filteredOptions.length - 1
447
+ });
448
+ return;
449
+ }
450
+
451
+ // Restore the focus to the previous index.
452
+ setHighlightedIndex({
453
+ index: highlightedIndexRef.current
454
+ });
455
+ // Ignore filteredOptions (and options, isOptionEqualToValue, getOptionLabel) not to break the scroll position
456
+ // eslint-disable-next-line react-hooks/exhaustive-deps
457
+ }, [
458
+ // Only sync the highlighted index when the option switch between empty and not
459
+ filteredOptions.length,
460
+ // Don't sync the highlighted index with the value when multiple
461
+ // eslint-disable-next-line react-hooks/exhaustive-deps
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
+ // eslint-disable-next-line react-hooks/rules-of-hooks
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
+ // Out of range
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
+ // Same logic as MenuList.js
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
+ // Wait until IME is settled.
614
+ if (event.which !== 229) {
615
+ switch (event.key) {
616
+ case 'Home':
617
+ if (popupOpen && handleHomeEndKeys) {
618
+ // Prevent scroll of the page
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
+ // Prevent scroll of the page
631
+ event.preventDefault();
632
+ changeHighlightedIndex({
633
+ diff: 'end',
634
+ direction: 'previous',
635
+ reason: 'keyboard',
636
+ event
637
+ });
638
+ }
639
+ break;
640
+ case 'PageUp':
641
+ // Prevent scroll of the page
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
+ // Prevent scroll of the page
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
+ // Prevent cursor move
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
+ // Prevent cursor move
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
+ // Avoid early form validation, let the end-users continue filling the form.
696
+ event.preventDefault();
697
+ if (disabled) {
698
+ return;
699
+ }
700
+ selectNewValue(event, option, 'selectOption');
701
+
702
+ // Move the selection to the end.
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
+ // Allow people to add new values before they submit the form.
709
+ event.preventDefault();
710
+ }
711
+ selectNewValue(event, inputValue, 'createOption', 'freeSolo');
712
+ }
713
+ break;
714
+ case 'Escape':
715
+ if (popupOpen) {
716
+ // Avoid Opera to exit fullscreen mode.
717
+ event.preventDefault();
718
+ // Avoid the Modal to handle the event.
719
+ event.stopPropagation();
720
+ handleClose(event, 'escape');
721
+ } else if (clearOnEscape && (inputValue !== '' || multiple && value.length > 0)) {
722
+ // Avoid Opera to exit fullscreen mode.
723
+ event.preventDefault();
724
+ // Avoid the Modal to handle the event.
725
+ event.stopPropagation();
726
+ handleClear(event);
727
+ }
728
+ break;
729
+ case 'Backspace':
730
+ // Remove the value on the left of the "cursor"
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
+ // Remove the value on the right of the "cursor"
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
+ // Ignore the event when using the scrollbar with IE11
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
+ // Prevent input blur when interacting with the combobox
835
+ const handleMouseDown = event => {
836
+ // Prevent focusing the input if click is anywhere outside the Autocomplete
837
+ if (!event.currentTarget.contains(event.target)) {
838
+ return;
839
+ }
840
+ if (event.target.getAttribute('id') !== id) {
841
+ event.preventDefault();
842
+ }
843
+ };
844
+
845
+ // Focus the input when interacting with the combobox
846
+ const handleClick = event => {
847
+ // Prevent focusing the input if click is anywhere outside the Autocomplete
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
+ // used to keep track of key and indexes in the result array
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
+ // if open then this is handled imperatively so don't let react override
914
+ // only have an opinion about this when closed
915
+ 'aria-activedescendant': popupOpen ? '' : null,
916
+ 'aria-autocomplete': autoComplete ? 'both' : 'list',
917
+ 'aria-controls': listboxAvailable ? `${id}-listbox` : undefined,
918
+ 'aria-expanded': listboxAvailable,
919
+ // Disable browser's suggestion that might overlap with the popup.
920
+ // Handle autocomplete but not autofill.
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
+ // Prevent blur
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
+ }
989
+ export default useAutocomplete;