@mui/material 5.16.1 → 5.16.3

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