-
-
Notifications
You must be signed in to change notification settings - Fork 31.9k
/
Menu.js
596 lines (523 loc) · 17.6 KB
/
Menu.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import shallowEqual from 'recompose/shallowEqual';
import ClickAwayListener from '../internal/ClickAwayListener';
import keycode from 'keycode';
import propTypes from '../utils/propTypes';
import List from '../List/List';
import {HotKeyHolder} from './menuUtils';
function getStyles(props, context) {
const {
desktop,
maxHeight,
width,
} = props;
const {muiTheme} = context;
const styles = {
root: {
// Nested div because the List scales x faster than it scales y
zIndex: muiTheme.zIndex.menu,
maxHeight: maxHeight,
overflowY: maxHeight ? 'auto' : null,
},
divider: {
marginTop: 7,
marginBottom: 8,
},
list: {
display: 'table-cell',
paddingBottom: desktop ? 16 : 8,
paddingTop: desktop ? 16 : 8,
userSelect: 'none',
width: width,
},
selectedMenuItem: {
color: muiTheme.menuItem.selectedTextColor,
},
};
return styles;
}
class Menu extends Component {
static propTypes = {
/**
* If true, the width of the menu will be set automatically
* according to the widths of its children,
* using proper keyline increments (64px for desktop,
* 56px otherwise).
*/
autoWidth: PropTypes.bool,
/**
* The content of the menu. This is usually used to pass `MenuItem`
* elements.
*/
children: PropTypes.node,
/**
* If true, the menu item will render with compact desktop styles.
*/
desktop: PropTypes.bool,
/**
* If true, the menu will not be auto-focused.
*/
disableAutoFocus: PropTypes.bool,
/**
* If true, the menu will be keyboard-focused initially.
*/
initiallyKeyboardFocused: PropTypes.bool,
/**
* Override the inline-styles of the underlying `List` element.
*/
listStyle: PropTypes.object,
/**
* The maximum height of the menu in pixels. If specified,
* the menu will be scrollable if it is taller than the provided
* height.
*/
maxHeight: PropTypes.number,
/**
* Override the inline-styles of menu items.
*/
menuItemStyle: PropTypes.object,
/**
* If true, `value` must be an array and the menu will support
* multiple selections.
*/
multiple: PropTypes.bool,
/**
* Callback function fired when a menu item with `value` not
* equal to the current `value` of the menu is touch-tapped.
*
* @param {object} event TouchTap event targeting the menu item.
* @param {any} value If `multiple` is true, the menu's `value`
* array with either the menu item's `value` added (if
* it wasn't already selected) or omitted (if it was already selected).
* Otherwise, the `value` of the menu item.
*/
onChange: PropTypes.func,
/**
* Callback function fired when the menu is focused and the *Esc* key
* is pressed.
*
* @param {object} event `keydown` event targeting the menu.
*/
onEscKeyDown: PropTypes.func,
/**
* Callback function fired when a menu item is touch-tapped.
*
* @param {object} event TouchTap event targeting the menu item.
* @param {object} menuItem The menu item.
* @param {number} index The index of the menu item.
*/
onItemTouchTap: PropTypes.func,
/** @ignore */
onKeyDown: PropTypes.func,
/**
* Callback function fired when the focus on a `MenuItem` is changed.
* There will be some "duplicate" changes reported if two different
* focusing event happen, for example if a `MenuItem` is focused via
* the keyboard and then it is clicked on.
*
* @param {object} event The event that triggered the focus change.
* The event can be null since the focus can be changed for non-event
* reasons such as prop changes.
* @param {number} newFocusIndex The index of the newly focused
* `MenuItem` or `-1` if focus was lost.
*/
onMenuItemFocusChange: PropTypes.func,
/**
* Override the inline-styles of selected menu items.
*/
selectedMenuItemStyle: PropTypes.object,
/**
* Override the inline-styles of the root element.
*/
style: PropTypes.object,
/**
* If `multiple` is true, an array of the `value`s of the selected
* menu items. Otherwise, the `value` of the selected menu item.
* If provided, the menu will be a controlled component.
* This component also supports valueLink.
*/
value: PropTypes.any,
/**
* ValueLink for the menu's `value`.
*/
valueLink: PropTypes.object,
/**
* The width of the menu. If not specified, the menu's width
* will be set according to the widths of its children, using
* proper keyline increments (64px for desktop, 56px otherwise).
*/
width: propTypes.stringOrNumber,
};
static defaultProps = {
autoWidth: true,
desktop: false,
disableAutoFocus: false,
initiallyKeyboardFocused: false,
maxHeight: null,
multiple: false,
onChange: () => {},
onEscKeyDown: () => {},
onItemTouchTap: () => {},
onKeyDown: () => {},
};
static contextTypes = {
muiTheme: PropTypes.object.isRequired,
};
constructor(props, context) {
super(props, context);
const filteredChildren = this.getFilteredChildren(props.children);
const selectedIndex = this.getLastSelectedIndex(props, filteredChildren);
const newFocusIndex = props.disableAutoFocus ? -1 : selectedIndex >= 0 ? selectedIndex : 0;
if (newFocusIndex !== -1 && props.onMenuItemFocusChange) {
props.onMenuItemFocusChange(null, newFocusIndex);
}
this.state = {
focusIndex: newFocusIndex,
isKeyboardFocused: props.initiallyKeyboardFocused,
keyWidth: props.desktop ? 64 : 56,
};
this.hotKeyHolder = new HotKeyHolder();
}
componentDidMount() {
if (this.props.autoWidth) {
this.setWidth();
}
this.setScollPosition();
}
componentWillReceiveProps(nextProps) {
let selectedIndex;
const filteredChildren = this.getFilteredChildren(nextProps.children);
if (this.props.multiple !== true) {
selectedIndex = this.getLastSelectedIndex(nextProps, filteredChildren);
} else {
selectedIndex = this.state.focusIndex;
}
const newFocusIndex = nextProps.disableAutoFocus ? -1 : selectedIndex >= 0 ? selectedIndex : 0;
if (newFocusIndex !== this.state.focusIndex && this.props.onMenuItemFocusChange) {
this.props.onMenuItemFocusChange(null, newFocusIndex);
}
this.setState({
focusIndex: newFocusIndex,
keyWidth: nextProps.desktop ? 64 : 56,
});
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
return (
!shallowEqual(this.props, nextProps) ||
!shallowEqual(this.state, nextState) ||
!shallowEqual(this.context, nextContext)
);
}
componentDidUpdate() {
if (this.props.autoWidth) this.setWidth();
}
handleClickAway = (event) => {
if (event.defaultPrevented) {
return;
}
const {focusIndex} = this.state;
if (focusIndex < 0) {
return;
}
const filteredChildren = this.getFilteredChildren(this.props.children);
const focusedItem = filteredChildren[focusIndex];
if (focusedItem.props.menuItems && focusedItem.props.menuItems.length > 0) {
return;
}
this.setFocusIndex(event, -1, false);
};
// Do not use outside of this component, it will be removed once valueLink is deprecated
getValueLink(props) {
return props.valueLink || {
value: props.value,
requestChange: props.onChange,
};
}
setKeyboardFocused(keyboardFocused) {
this.setState({
isKeyboardFocused: keyboardFocused,
});
}
getFilteredChildren(children) {
const filteredChildren = [];
React.Children.forEach(children, (child) => {
if (child) {
filteredChildren.push(child);
}
});
return filteredChildren;
}
cloneMenuItem(child, childIndex, styles, index) {
const childIsDisabled = child.props.disabled;
const selectedChildStyles = {};
if (!childIsDisabled) {
const selected = this.isChildSelected(child, this.props);
if (selected) {
Object.assign(selectedChildStyles, styles.selectedMenuItem, this.props.selectedMenuItemStyle);
}
}
const mergedChildStyles = Object.assign({}, child.props.style, this.props.menuItemStyle, selectedChildStyles);
const extraProps = {
desktop: this.props.desktop,
style: mergedChildStyles,
};
if (!childIsDisabled) {
const isFocused = childIndex === this.state.focusIndex;
let focusState = 'none';
if (isFocused) {
focusState = this.state.isKeyboardFocused ?
'keyboard-focused' : 'focused';
}
Object.assign(extraProps, {
focusState: focusState,
onClick: (event) => {
this.handleMenuItemTouchTap(event, child, index);
if (child.props.onClick) child.props.onClick(event);
},
ref: isFocused ? 'focusedMenuItem' : null,
});
}
return React.cloneElement(child, extraProps);
}
decrementKeyboardFocusIndex(event) {
let index = this.state.focusIndex;
index--;
if (index < 0) index = 0;
this.setFocusIndex(event, index, true);
}
getMenuItemCount(filteredChildren) {
let menuItemCount = 0;
filteredChildren.forEach((child) => {
const childIsADivider = child.type && child.type.muiName === 'Divider';
const childIsDisabled = child.props.disabled;
if (!childIsADivider && !childIsDisabled) menuItemCount++;
});
return menuItemCount;
}
getLastSelectedIndex(props, filteredChildren) {
let selectedIndex = -1;
let menuItemIndex = 0;
filteredChildren.forEach((child) => {
const childIsADivider = child.type && child.type.muiName === 'Divider';
if (this.isChildSelected(child, props)) selectedIndex = menuItemIndex;
if (!childIsADivider) menuItemIndex++;
});
return selectedIndex;
}
handleKeyDown = (event) => {
const filteredChildren = this.getFilteredChildren(this.props.children);
const key = keycode(event);
switch (key) {
case 'down':
event.preventDefault();
this.incrementKeyboardFocusIndex(event, filteredChildren);
break;
case 'esc':
this.props.onEscKeyDown(event);
break;
case 'tab':
event.preventDefault();
if (event.shiftKey) {
this.decrementKeyboardFocusIndex(event);
} else {
this.incrementKeyboardFocusIndex(event, filteredChildren);
}
break;
case 'up':
event.preventDefault();
this.decrementKeyboardFocusIndex(event);
break;
default:
if (key && key.length === 1) {
const hotKeys = this.hotKeyHolder.append(key);
if (this.setFocusIndexStartsWith(event, hotKeys)) {
event.preventDefault();
}
}
}
this.props.onKeyDown(event);
};
setFocusIndexStartsWith(event, keys) {
let foundIndex = -1;
React.Children.forEach(this.props.children, (child, index) => {
if (foundIndex >= 0) {
return;
}
const {primaryText} = child.props;
if (typeof primaryText === 'string' && primaryText.substr(0, keys.length).toLowerCase() === keys.toLowerCase()) {
foundIndex = index;
}
});
if (foundIndex >= 0) {
this.setFocusIndex(event, foundIndex, true);
return true;
}
return false;
}
handleMenuItemTouchTap(event, item, index) {
const children = this.props.children;
const multiple = this.props.multiple;
const valueLink = this.getValueLink(this.props);
let menuValue = valueLink.value;
const itemValue = item.props.value;
const focusIndex = React.isValidElement(children) ? 0 : children.indexOf(item);
this.setFocusIndex(event, focusIndex, false);
if (multiple) {
menuValue = menuValue || [];
const itemIndex = menuValue.indexOf(itemValue);
const [...newMenuValue] = menuValue;
if (itemIndex === -1) {
newMenuValue.push(itemValue);
} else {
newMenuValue.splice(itemIndex, 1);
}
valueLink.requestChange(event, newMenuValue);
} else if (!multiple && itemValue !== menuValue) {
valueLink.requestChange(event, itemValue);
}
this.props.onItemTouchTap(event, item, index);
}
incrementKeyboardFocusIndex(event, filteredChildren) {
let index = this.state.focusIndex;
const maxIndex = this.getMenuItemCount(filteredChildren) - 1;
index++;
if (index > maxIndex) index = maxIndex;
this.setFocusIndex(event, index, true);
}
isChildSelected(child, props) {
const menuValue = this.getValueLink(props).value;
const childValue = child.props.value;
if (props.multiple) {
return menuValue && menuValue.length && menuValue.indexOf(childValue) !== -1;
} else {
return child.props.hasOwnProperty('value') && menuValue === childValue;
}
}
setFocusIndex(event, newIndex, isKeyboardFocused) {
if (this.props.onMenuItemFocusChange) {
// Do this even if `newIndex === this.state.focusIndex` to allow users
// to detect up-arrow on the first MenuItem or down-arrow on the last.
this.props.onMenuItemFocusChange(event, newIndex);
}
this.setState({
focusIndex: newIndex,
isKeyboardFocused: isKeyboardFocused,
});
}
setScollPosition() {
const desktop = this.props.desktop;
const focusedMenuItem = this.refs.focusedMenuItem;
const menuItemHeight = desktop ? 32 : 48;
if (focusedMenuItem) {
const selectedOffSet = ReactDOM.findDOMNode(focusedMenuItem).offsetTop;
// Make the focused item be the 2nd item in the list the user sees
let scrollTop = selectedOffSet - menuItemHeight;
if (scrollTop < menuItemHeight) scrollTop = 0;
ReactDOM.findDOMNode(this.refs.scrollContainer).scrollTop = scrollTop;
}
}
cancelScrollEvent(event) {
event.stopPropagation();
event.preventDefault();
return false;
}
handleOnWheel = (event) => {
const scrollContainer = this.refs.scrollContainer;
// Only scroll lock if the the Menu is scrollable.
if (scrollContainer.scrollHeight <= scrollContainer.clientHeight) return;
const {scrollTop, scrollHeight, clientHeight} = scrollContainer;
const wheelDelta = event.deltaY;
const isDeltaPositive = wheelDelta > 0;
if (isDeltaPositive && wheelDelta > scrollHeight - clientHeight - scrollTop) {
scrollContainer.scrollTop = scrollHeight;
return this.cancelScrollEvent(event);
} else if (!isDeltaPositive && -wheelDelta > scrollTop) {
scrollContainer.scrollTop = 0;
return this.cancelScrollEvent(event);
}
}
setWidth() {
const el = ReactDOM.findDOMNode(this);
const listEl = ReactDOM.findDOMNode(this.refs.list);
const elWidth = el.offsetWidth;
const keyWidth = this.state.keyWidth;
const minWidth = keyWidth * 1.5;
let keyIncrements = elWidth / keyWidth;
let newWidth;
keyIncrements = keyIncrements <= 1.5 ? 1.5 : Math.ceil(keyIncrements);
newWidth = keyIncrements * keyWidth;
if (newWidth < minWidth) newWidth = minWidth;
el.style.width = `${newWidth}px`;
listEl.style.width = `${newWidth}px`;
}
render() {
const {
autoWidth, // eslint-disable-line no-unused-vars
children,
desktop, // eslint-disable-line no-unused-vars
disableAutoFocus, // eslint-disable-line no-unused-vars
initiallyKeyboardFocused, // eslint-disable-line no-unused-vars
listStyle,
maxHeight, // eslint-disable-line no-unused-vars
multiple, // eslint-disable-line no-unused-vars
onItemTouchTap, // eslint-disable-line no-unused-vars
onEscKeyDown, // eslint-disable-line no-unused-vars
onMenuItemFocusChange, // eslint-disable-line no-unused-vars
selectedMenuItemStyle, // eslint-disable-line no-unused-vars
menuItemStyle, // eslint-disable-line no-unused-vars
style,
value, // eslint-disable-line no-unused-vars
valueLink, // eslint-disable-line no-unused-vars
width, // eslint-disable-line no-unused-vars
...other
} = this.props;
const {prepareStyles} = this.context.muiTheme;
const styles = getStyles(this.props, this.context);
const mergedRootStyles = Object.assign(styles.root, style);
const mergedListStyles = Object.assign(styles.list, listStyle);
const filteredChildren = this.getFilteredChildren(children);
let menuItemIndex = 0;
const newChildren = React.Children.map(filteredChildren, (child, index) => {
const childIsDisabled = child.props.disabled;
const childName = child.type ? child.type.muiName : '';
let newChild = child;
switch (childName) {
case 'MenuItem':
newChild = this.cloneMenuItem(child, menuItemIndex, styles, index);
break;
case 'Divider':
newChild = React.cloneElement(child, {
style: Object.assign({}, styles.divider, child.props.style),
});
break;
}
if (childName === 'MenuItem' && !childIsDisabled) {
menuItemIndex++;
}
return newChild;
});
return (
<ClickAwayListener onClickAway={this.handleClickAway}>
<div
onKeyDown={this.handleKeyDown}
onWheel={this.handleOnWheel}
style={prepareStyles(mergedRootStyles)}
ref="scrollContainer"
role="presentation"
>
<List
{...other}
ref="list"
style={mergedListStyles}
role="menu"
>
{newChildren}
</List>
</div>
</ClickAwayListener>
);
}
}
export default Menu;