-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
OverflowMenu.js
601 lines (536 loc) · 15.7 KB
/
OverflowMenu.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
597
598
599
600
601
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import invariant from 'invariant';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import classNames from 'classnames';
import ClickListener from '../../internal/ClickListener';
import FloatingMenu, {
DIRECTION_TOP,
DIRECTION_BOTTOM,
} from '../../internal/FloatingMenu';
import { OverflowMenuVertical } from '@carbon/icons-react';
import { keys, matches as keyCodeMatches } from '../../internal/keyboard';
import mergeRefs from '../../tools/mergeRefs';
import { PrefixContext } from '../../internal/usePrefix';
import deprecate from '../../prop-types/deprecate';
import { IconButton } from '../IconButton';
import setupGetInstanceId from '../../tools/setupGetInstanceId';
import { noopFn } from '../../internal/noopFn';
const getInstanceId = setupGetInstanceId();
const on = (element, ...args) => {
element.addEventListener(...args);
return {
release() {
element.removeEventListener(...args);
return null;
},
};
};
/**
* The CSS property names of the arrow keyed by the floating menu direction.
* @type {[key: string]: string}
*/
const triggerButtonPositionProps = {
[DIRECTION_TOP]: 'bottom',
[DIRECTION_BOTTOM]: 'top',
};
/**
* Determines how the position of arrow should affect the floating menu position.
* @type {[key: string]: number}
*/
const triggerButtonPositionFactors = {
[DIRECTION_TOP]: -2,
[DIRECTION_BOTTOM]: -1,
};
/**
* @param {Element} menuBody The menu body with the menu arrow.
* @param {string} direction The floating menu direction.
* @returns {FloatingMenu~offset} The adjustment of the floating menu position, upon the position of the menu arrow.
* @private
*/
export const getMenuOffset = (menuBody, direction, trigger, flip) => {
const triggerButtonPositionProp = triggerButtonPositionProps[direction];
const triggerButtonPositionFactor = triggerButtonPositionFactors[direction];
if (__DEV__) {
invariant(
triggerButtonPositionProp && triggerButtonPositionFactor,
'[OverflowMenu] wrong floating menu direction: `%s`',
direction
);
}
const { offsetWidth: menuWidth, offsetHeight: menuHeight } = menuBody;
switch (triggerButtonPositionProp) {
case 'top':
case 'bottom': {
// TODO: Ensure `trigger` is there for `<OverflowMenu open>`
const triggerWidth = !trigger ? 0 : trigger.offsetWidth;
return {
left: (!flip ? 1 : -1) * (menuWidth / 2 - triggerWidth / 2),
top: 0,
};
}
case 'left':
case 'right': {
// TODO: Ensure `trigger` is there for `<OverflowMenu open>`
const triggerHeight = !trigger ? 0 : trigger.offsetHeight;
return {
left: 0,
top: (!flip ? 1 : -1) * (menuHeight / 2 - triggerHeight / 2),
};
}
default:
break;
}
};
class OverflowMenu extends Component {
state = {};
instanceId = getInstanceId();
static propTypes = {
/**
* Specify a label to be read by screen readers on the container node
*/
['aria-label']: PropTypes.string,
/**
* Deprecated, please use `aria-label` instead.
* Specify a label to be read by screen readers on the container note.
*/
ariaLabel: deprecate(
PropTypes.string,
'This prop syntax has been deprecated. Please use the new `aria-label`.'
),
/**
* The child nodes.
*/
children: PropTypes.node,
/**
* The CSS class names.
*/
className: PropTypes.string,
/**
* The menu direction.
*/
direction: PropTypes.oneOf([DIRECTION_TOP, DIRECTION_BOTTOM]),
/**
* `true` if the menu alignment should be flipped.
*/
flipped: PropTypes.bool,
/**
* Enable or disable focus trap behavior
*/
focusTrap: PropTypes.bool,
/**
* The CSS class for the icon.
*/
iconClass: PropTypes.string,
/**
* The icon description.
*/
iconDescription: PropTypes.string,
/**
* The element ID.
*/
id: PropTypes.string,
/**
* `true` to use the light version. For use on $ui-01 backgrounds only.
* Don't use this to make OverflowMenu background color same as container background color.
*/
light: deprecate(
PropTypes.bool,
'The `light` prop for `OverflowMenu` is no longer needed and has been deprecated. It will be removed in the next major release. Use the Layer component instead.'
),
/**
* The adjustment in position applied to the floating menu.
*/
menuOffset: PropTypes.oneOfType([
PropTypes.shape({
top: PropTypes.number,
left: PropTypes.number,
}),
PropTypes.func,
]),
/**
* The adjustment in position applied to the floating menu.
*/
menuOffsetFlip: PropTypes.oneOfType([
PropTypes.shape({
top: PropTypes.number,
left: PropTypes.number,
}),
PropTypes.func,
]),
/**
* The class to apply to the menu options
*/
menuOptionsClass: PropTypes.string,
/**
* The event handler for the `click` event.
*/
onClick: PropTypes.func,
/**
* Function called when menu is closed
*/
onClose: PropTypes.func,
/**
* The event handler for the `focus` event.
*/
onFocus: PropTypes.func,
/**
* The event handler for the `keydown` event.
*/
onKeyDown: PropTypes.func,
/**
* Function called when menu is opened
*/
onOpen: PropTypes.func,
/**
* `true` if the menu should be open.
*/
open: PropTypes.bool,
/**
* Function called to override icon rendering.
*/
renderIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
/**
* Specify a CSS selector that matches the DOM element that should
* be focused when the OverflowMenu opens
*/
selectorPrimaryFocus: PropTypes.string,
/**
* Specify the size of the OverflowMenu. Currently supports either `sm`, 'md' (default) or 'lg` as an option.
*/
size: PropTypes.oneOf(['sm', 'md', 'lg']),
};
static contextType = PrefixContext;
/**
* The handle of `onfocusin` or `focus` event handler.
* @private
*/
_hFocusIn = null;
/**
* The timeout handle for handling `blur` event.
* @private
*/
_hBlurTimeout;
/**
* The element ref of the tooltip's trigger button.
* @type {React.RefObject<Element>}
* @private
*/
_triggerRef = React.createRef();
componentDidUpdate(_, prevState) {
const { onClose = noopFn } = this.props;
if (!this.state.open && prevState.open) {
onClose();
}
}
componentDidMount() {
// ensure that if open=true on first render, we wait
// to render the floating menu until the trigger ref is not null
if (this._triggerRef.current) {
this.setState({ hasMountedTrigger: true });
}
}
static getDerivedStateFromProps({ open }, state) {
const { prevOpen } = state;
return prevOpen === open
? null
: {
open,
prevOpen: open,
};
}
componentWillUnmount() {
if (typeof this._hBlurTimeout === 'number') {
clearTimeout(this._hBlurTimeout);
this._hBlurTimeout = undefined;
}
}
handleClick = (evt) => {
const { onClick = noopFn } = this.props;
this.setState({ click: true });
evt.stopPropagation();
if (!this._menuBody || !this._menuBody.contains(evt.target)) {
this.setState({ open: !this.state.open });
onClick(evt);
}
};
closeMenuAndFocus = () => {
let wasClicked = this.state.click;
let wasOpen = this.state.open;
this.closeMenu(() => {
if (wasOpen && !wasClicked) {
this.focusMenuEl();
}
});
};
closeMenuOnEscape = () => {
let wasOpen = this.state.open;
this.closeMenu(() => {
if (wasOpen) {
this.focusMenuEl();
}
});
};
handleKeyPress = (evt) => {
if (
this.state.open &&
keyCodeMatches(evt, [
keys.ArrowUp,
keys.ArrowRight,
keys.ArrowDown,
keys.ArrowLeft,
])
) {
evt.preventDefault();
}
// Close the overflow menu on escape
if (keyCodeMatches(evt, [keys.Escape])) {
this.closeMenuOnEscape();
// Stop the esc keypress from bubbling out and closing something it shouldn't
evt.stopPropagation();
}
};
handleClickOutside = (evt) => {
if (
this.state.open &&
(!this._menuBody || !this._menuBody.contains(evt.target))
) {
this.closeMenu();
}
};
closeMenu = (onCloseMenu) => {
const { onClose = noopFn } = this.props;
this.setState({ open: false }, () => {
// Optional callback to be executed after the state as been set to close
if (onCloseMenu) {
onCloseMenu();
}
onClose();
});
};
focusMenuEl = () => {
const { current: triggerEl } = this._triggerRef;
if (triggerEl) {
triggerEl.focus();
}
};
/**
* Focuses the next enabled overflow menu item given the currently focused
* item index and direction to move
* @param {object} params
* @param {number} params.currentIndex - the index of the currently focused
* overflow menu item in the list of overflow menu items
* @param {number} params.direction - number denoting the direction to move
* focus (1 for forwards, -1 for backwards)
*/
handleOverflowMenuItemFocus = ({ currentIndex, direction }) => {
const enabledIndices = React.Children.toArray(this.props.children).reduce(
(acc, curr, i) => {
if (!curr.props.disabled) {
acc.push(i);
}
return acc;
},
[]
);
const nextValidIndex = (() => {
const nextIndex = enabledIndices.indexOf(currentIndex) + direction;
switch (nextIndex) {
case -1:
return enabledIndices.length - 1;
case enabledIndices.length:
return 0;
default:
return nextIndex;
}
})();
const overflowMenuItem =
this[`overflowMenuItem${enabledIndices[nextValidIndex]}`];
overflowMenuItem?.focus();
};
/**
* Handles the floating menu being unmounted or non-floating menu being
* mounted or unmounted.
* @param {Element} menuBody The DOM element of the menu body.
* @private
*/
_bindMenuBody = (menuBody) => {
if (!menuBody) {
this._menuBody = menuBody;
}
if (!menuBody && this._hFocusIn) {
this._hFocusIn = this._hFocusIn.release();
}
};
/**
* Handles the floating menu being placed.
* @param {Element} menuBody The DOM element of the menu body.
* @private
*/
_handlePlace = (menuBody) => {
const { onOpen = noopFn } = this.props;
if (menuBody) {
this._menuBody = menuBody;
const hasFocusin = 'onfocusin' in window;
const focusinEventName = hasFocusin ? 'focusin' : 'focus';
this._hFocusIn = on(
menuBody.ownerDocument,
focusinEventName,
(event) => {
const target = ClickListener.getEventTarget(event);
const { current: triggerEl } = this._triggerRef;
if (typeof target.matches === 'function') {
if (
!menuBody.contains(target) &&
triggerEl &&
!target.matches(
`.${this.context}--overflow-menu:first-child,.${this.context}--overflow-menu-options:first-child`
)
) {
this.closeMenuAndFocus();
}
}
},
!hasFocusin
);
onOpen();
}
};
/**
* @returns {Element} The DOM element where the floating menu is placed in.
*/
_getTarget = () => {
const { current: triggerEl } = this._triggerRef;
return (
(triggerEl && triggerEl.closest('[data-floating-menu-container]')) ||
document.body
);
};
render() {
const prefix = this.context;
const {
id,
['aria-label']: ariaLabel = null,
ariaLabel: deprecatedAriaLabel,
children,
iconDescription = 'Options',
direction = DIRECTION_BOTTOM,
flipped = false,
focusTrap = true,
menuOffset = getMenuOffset,
menuOffsetFlip = getMenuOffset,
iconClass,
onClick = noopFn, // eslint-disable-line
onOpen = noopFn, // eslint-disable-line
selectorPrimaryFocus = '[data-floating-menu-primary-focus]', // eslint-disable-line
renderIcon: IconElement = OverflowMenuVertical,
// eslint-disable-next-line react/prop-types
innerRef: ref,
menuOptionsClass,
light,
size = 'md',
...other
} = this.props;
const { open = false } = this.state;
const overflowMenuClasses = classNames(
this.props.className,
`${prefix}--overflow-menu`,
{
[`${prefix}--overflow-menu--open`]: open,
[`${prefix}--overflow-menu--light`]: light,
[`${prefix}--overflow-menu--${size}`]: size,
}
);
const overflowMenuOptionsClasses = classNames(
menuOptionsClass,
`${prefix}--overflow-menu-options`,
{
[`${prefix}--overflow-menu--flip`]: this.props.flipped,
[`${prefix}--overflow-menu-options--open`]: open,
[`${prefix}--overflow-menu-options--light`]: light,
[`${prefix}--overflow-menu-options--${size}`]: size,
}
);
const overflowMenuIconClasses = classNames(
`${prefix}--overflow-menu__icon`,
iconClass
);
const childrenWithProps = React.Children.toArray(children).map(
(child, index) =>
React.cloneElement(child, {
closeMenu: child?.props?.closeMenu || this.closeMenuAndFocus,
handleOverflowMenuItemFocus: this.handleOverflowMenuItemFocus,
ref: (e) => {
this[`overflowMenuItem${index}`] = e;
},
index,
})
);
const menuBodyId = `overflow-menu-${this.instanceId}__menu-body`;
const menuBody = (
<ul
className={overflowMenuOptionsClasses}
tabIndex="-1"
role="menu"
aria-label={ariaLabel || deprecatedAriaLabel}
onKeyDown={this.handleKeyPress}
id={menuBodyId}>
{childrenWithProps}
</ul>
);
const wrappedMenuBody = (
<FloatingMenu
focusTrap={focusTrap}
triggerRef={this._triggerRef}
menuDirection={direction}
menuOffset={flipped ? menuOffsetFlip : menuOffset}
menuRef={this._bindMenuBody}
flipped={this.props.flipped}
target={this._getTarget}
onPlace={this._handlePlace}
selectorPrimaryFocus={this.props.selectorPrimaryFocus}>
{React.cloneElement(menuBody, {
'data-floating-menu-direction': direction,
})}
</FloatingMenu>
);
const iconProps = {
className: overflowMenuIconClasses,
'aria-label': iconDescription,
};
return (
<ClickListener onClickOutside={this.handleClickOutside}>
<span
className={`${prefix}--overflow-menu__wrapper`}
aria-owns={open ? menuBodyId : null}>
<IconButton
{...other}
type="button"
aria-haspopup
aria-expanded={open}
aria-controls={open ? menuBodyId : null}
className={overflowMenuClasses}
onClick={this.handleClick}
id={id}
ref={mergeRefs(this._triggerRef, ref)}
size={size}
label={iconDescription}>
<IconElement {...iconProps} />
</IconButton>
{open && this.state.hasMountedTrigger && wrappedMenuBody}
</span>
</ClickListener>
);
}
}
export { OverflowMenu };
export default (() => {
const forwardRef = (props, ref) => <OverflowMenu {...props} innerRef={ref} />;
forwardRef.displayName = 'OverflowMenu';
return React.forwardRef(forwardRef);
})();