-
-
Notifications
You must be signed in to change notification settings - Fork 32.5k
/
Copy pathMenuList.js
344 lines (316 loc) · 10.2 KB
/
MenuList.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
'use client';
import * as React from 'react';
import { isFragment } from 'react-is';
import PropTypes from 'prop-types';
import ownerDocument from '../utils/ownerDocument';
import List from '../List';
import getScrollbarSize from '../utils/getScrollbarSize';
import useForkRef from '../utils/useForkRef';
import useEnhancedEffect from '../utils/useEnhancedEffect';
import { ownerWindow } from '../utils';
function nextItem(list, item, disableListWrap) {
if (list === item) {
return list.firstChild;
}
if (item && item.nextElementSibling) {
return item.nextElementSibling;
}
return disableListWrap ? null : list.firstChild;
}
function previousItem(list, item, disableListWrap) {
if (list === item) {
return disableListWrap ? list.firstChild : list.lastChild;
}
if (item && item.previousElementSibling) {
return item.previousElementSibling;
}
return disableListWrap ? null : list.lastChild;
}
function textCriteriaMatches(nextFocus, textCriteria) {
if (textCriteria === undefined) {
return true;
}
let text = nextFocus.innerText;
if (text === undefined) {
// jsdom doesn't support innerText
text = nextFocus.textContent;
}
text = text.trim().toLowerCase();
if (text.length === 0) {
return false;
}
if (textCriteria.repeating) {
return text[0] === textCriteria.keys[0];
}
return text.startsWith(textCriteria.keys.join(''));
}
function moveFocus(
list,
currentFocus,
disableListWrap,
disabledItemsFocusable,
traversalFunction,
textCriteria,
) {
let wrappedOnce = false;
let nextFocus = traversalFunction(list, currentFocus, currentFocus ? disableListWrap : false);
while (nextFocus) {
// Prevent infinite loop.
if (nextFocus === list.firstChild) {
if (wrappedOnce) {
return false;
}
wrappedOnce = true;
}
// Same logic as useAutocomplete.js
const nextFocusDisabled = disabledItemsFocusable
? false
: nextFocus.disabled || nextFocus.getAttribute('aria-disabled') === 'true';
if (
!nextFocus.hasAttribute('tabindex') ||
!textCriteriaMatches(nextFocus, textCriteria) ||
nextFocusDisabled
) {
// Move to the next element.
nextFocus = traversalFunction(list, nextFocus, disableListWrap);
} else {
nextFocus.focus();
return true;
}
}
return false;
}
/**
* A permanently displayed menu following https://www.w3.org/WAI/ARIA/apg/patterns/menu-button/.
* It's exposed to help customization of the [`Menu`](/material-ui/api/menu/) component if you
* use it separately you need to move focus into the component manually. Once
* the focus is placed inside the component it is fully keyboard accessible.
*/
const MenuList = React.forwardRef(function MenuList(props, ref) {
const {
// private
// eslint-disable-next-line react/prop-types
actions,
autoFocus = false,
autoFocusItem = false,
children,
className,
disabledItemsFocusable = false,
disableListWrap = false,
onKeyDown,
variant = 'selectedMenu',
...other
} = props;
const listRef = React.useRef(null);
const textCriteriaRef = React.useRef({
keys: [],
repeating: true,
previousKeyMatched: true,
lastTime: null,
});
useEnhancedEffect(() => {
if (autoFocus) {
listRef.current.focus();
}
}, [autoFocus]);
React.useImperativeHandle(
actions,
() => ({
adjustStyleForScrollbar: (containerElement, { direction }) => {
// Let's ignore that piece of logic if users are already overriding the width
// of the menu.
const noExplicitWidth = !listRef.current.style.width;
if (containerElement.clientHeight < listRef.current.clientHeight && noExplicitWidth) {
const scrollbarSize = `${getScrollbarSize(ownerWindow(containerElement))}px`;
listRef.current.style[direction === 'rtl' ? 'paddingLeft' : 'paddingRight'] =
scrollbarSize;
listRef.current.style.width = `calc(100% + ${scrollbarSize})`;
}
return listRef.current;
},
}),
[],
);
const handleKeyDown = (event) => {
const list = listRef.current;
const key = event.key;
const isModifierKeyPressed = event.ctrlKey || event.metaKey || event.altKey;
if (isModifierKeyPressed) {
if (onKeyDown) {
onKeyDown(event);
}
return;
}
/**
* @type {Element} - will always be defined since we are in a keydown handler
* attached to an element. A keydown event is either dispatched to the activeElement
* or document.body or document.documentElement. Only the first case will
* trigger this specific handler.
*/
const currentFocus = ownerDocument(list).activeElement;
if (key === 'ArrowDown') {
// Prevent scroll of the page
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, nextItem);
} else if (key === 'ArrowUp') {
event.preventDefault();
moveFocus(list, currentFocus, disableListWrap, disabledItemsFocusable, previousItem);
} else if (key === 'Home') {
event.preventDefault();
moveFocus(list, null, disableListWrap, disabledItemsFocusable, nextItem);
} else if (key === 'End') {
event.preventDefault();
moveFocus(list, null, disableListWrap, disabledItemsFocusable, previousItem);
} else if (key.length === 1) {
const criteria = textCriteriaRef.current;
const lowerKey = key.toLowerCase();
const currTime = performance.now();
if (criteria.keys.length > 0) {
// Reset
if (currTime - criteria.lastTime > 500) {
criteria.keys = [];
criteria.repeating = true;
criteria.previousKeyMatched = true;
} else if (criteria.repeating && lowerKey !== criteria.keys[0]) {
criteria.repeating = false;
}
}
criteria.lastTime = currTime;
criteria.keys.push(lowerKey);
const keepFocusOnCurrent =
currentFocus && !criteria.repeating && textCriteriaMatches(currentFocus, criteria);
if (
criteria.previousKeyMatched &&
(keepFocusOnCurrent ||
moveFocus(list, currentFocus, false, disabledItemsFocusable, nextItem, criteria))
) {
event.preventDefault();
} else {
criteria.previousKeyMatched = false;
}
}
if (onKeyDown) {
onKeyDown(event);
}
};
const handleRef = useForkRef(listRef, ref);
/**
* the index of the item should receive focus
* in a `variant="selectedMenu"` it's the first `selected` item
* otherwise it's the very first item.
*/
let activeItemIndex = -1;
// since we inject focus related props into children we have to do a lookahead
// to check if there is a `selected` item. We're looking for the last `selected`
// item and use the first valid item as a fallback
React.Children.forEach(children, (child, index) => {
if (!React.isValidElement(child)) {
if (activeItemIndex === index) {
activeItemIndex += 1;
if (activeItemIndex >= children.length) {
// there are no focusable items within the list.
activeItemIndex = -1;
}
}
return;
}
if (process.env.NODE_ENV !== 'production') {
if (isFragment(child)) {
console.error(
[
"MUI: The Menu component doesn't accept a Fragment as a child.",
'Consider providing an array instead.',
].join('\n'),
);
}
}
if (!child.props.disabled) {
if (variant === 'selectedMenu' && child.props.selected) {
activeItemIndex = index;
} else if (activeItemIndex === -1) {
activeItemIndex = index;
}
}
if (
activeItemIndex === index &&
(child.props.disabled || child.props.muiSkipListHighlight || child.type.muiSkipListHighlight)
) {
activeItemIndex += 1;
if (activeItemIndex >= children.length) {
// there are no focusable items within the list.
activeItemIndex = -1;
}
}
});
const items = React.Children.map(children, (child, index) => {
if (index === activeItemIndex) {
const newChildProps = {};
if (autoFocusItem) {
newChildProps.autoFocus = true;
}
if (child.props.tabIndex === undefined && variant === 'selectedMenu') {
newChildProps.tabIndex = 0;
}
return React.cloneElement(child, newChildProps);
}
return child;
});
return (
<List
role="menu"
ref={handleRef}
className={className}
onKeyDown={handleKeyDown}
tabIndex={autoFocus ? 0 : -1}
{...other}
>
{items}
</List>
);
});
MenuList.propTypes /* remove-proptypes */ = {
// ┌────────────────────────────── Warning ──────────────────────────────┐
// │ These PropTypes are generated from the TypeScript type definitions. │
// │ To update them, edit the d.ts file and run `pnpm proptypes`. │
// └─────────────────────────────────────────────────────────────────────┘
/**
* If `true`, will focus the `[role="menu"]` container and move into tab order.
* @default false
*/
autoFocus: PropTypes.bool,
/**
* If `true`, will focus the first menuitem if `variant="menu"` or selected item
* if `variant="selectedMenu"`.
* @default false
*/
autoFocusItem: PropTypes.bool,
/**
* MenuList contents, normally `MenuItem`s.
*/
children: PropTypes.node,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, will allow focus on disabled items.
* @default false
*/
disabledItemsFocusable: PropTypes.bool,
/**
* If `true`, the menu items will not wrap focus.
* @default false
*/
disableListWrap: PropTypes.bool,
/**
* @ignore
*/
onKeyDown: PropTypes.func,
/**
* The variant to use. Use `menu` to prevent selected items from impacting the initial focus
* and the vertical alignment relative to the anchor element.
* @default 'selectedMenu'
*/
variant: PropTypes.oneOf(['menu', 'selectedMenu']),
};
export default MenuList;