/
Menu.tsx
519 lines (441 loc) · 13.9 KB
/
Menu.tsx
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
/**
* Copyright IBM Corp. 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 cx from 'classnames';
import PropTypes from 'prop-types';
import React, {
forwardRef,
ReactNode,
useContext,
useEffect,
useMemo,
useReducer,
useRef,
useState,
RefObject,
} from 'react';
import { createPortal } from 'react-dom';
import { keys, match } from '../../internal/keyboard';
import { useMergedRefs } from '../../internal/useMergedRefs';
import { usePrefix } from '../../internal/usePrefix';
import { warning } from '../../internal/warning.js';
import { MenuContext, menuReducer } from './MenuContext';
import { useLayoutDirection } from '../LayoutDirection';
const spacing = 8; // distance to keep to window edges, in px
interface MenuProps extends React.HTMLAttributes<HTMLUListElement> {
/**
* The ref of the containing element, used for positioning and alignment of the menu
*/
containerRef?: RefObject<HTMLDivElement>;
/**
* A collection of MenuItems to be rendered within this Menu.
*/
children?: ReactNode;
/**
* Additional CSS class names.
*/
className?: string;
/**
* A label describing the Menu.
*/
label: string;
/**
* Specify how the menu should align with the button element
*/
menuAlignment?: string;
/**
* The mode of this menu. Defaults to full.
* `full` supports nesting and selectable menu items, but no icons.
* `basic` supports icons but no nesting or selectable menu items.
*
* **This prop is not intended for use and will be set by the respective implementation (like useContextMenu, MenuButton, and ComboButton).**
*/
mode?: 'full' | 'basic';
/**
* Provide an optional function to be called when the Menu should be closed.
*/
onClose?: () => void;
/**
* Provide an optional function to be called when the Menu is opened.
*/
onOpen?: () => void;
/**
* Whether the Menu is open or not.
*/
open?: boolean;
/**
* Specify the size of the Menu.
*/
size?: 'xs' | 'sm' | 'md' | 'lg';
/**
* Specify a DOM node where the Menu should be rendered in. Defaults to document.body.
*/
target?: HTMLElement;
/**
* Specify the x position of the Menu. Either pass a single number or an array with two numbers describing your activator's boundaries ([x1, x2])
*/
x?: number | [number, number];
/**
* Specify the y position of the Menu. Either pass a single number or an array with two numbers describing your activator's boundaries ([y1, y2])
*/
y?: number | [number, number];
}
const Menu = forwardRef<HTMLUListElement, MenuProps>(function Menu(
{
children,
className,
containerRef,
label,
menuAlignment,
mode = 'full',
onClose,
onOpen,
open,
size = 'sm',
// TODO: #16004
// eslint-disable-next-line ssr-friendly/no-dom-globals-in-react-fc
target = document.body,
x = 0,
y = 0,
...rest
},
forwardRef
) {
const prefix = usePrefix();
const focusReturn = useRef<HTMLElement | null>(null);
const context = useContext(MenuContext);
const isRoot = context.state.isRoot;
if (context.state.mode === 'basic' && !isRoot) {
warning(
false,
'Nested menus are not supported when the menu is in "basic" mode.'
);
}
const menuSize = isRoot ? size : context.state.size;
const [childState, childDispatch] = useReducer(menuReducer, {
...context.state,
isRoot: false,
mode,
size,
requestCloseRoot: isRoot ? handleClose : context.state.requestCloseRoot,
});
const childContext = useMemo(() => {
return {
state: childState,
dispatch: childDispatch,
};
}, [childState, childDispatch]);
const menu = useRef<HTMLUListElement>(null);
const ref = useMergedRefs<HTMLUListElement>([forwardRef, menu]);
const [position, setPosition] = useState([-1, -1]);
const focusableItems = childContext.state.items.filter(
(item) => !item.disabled && item.ref.current
);
// Getting the width from the parent container element - controlled
let actionButtonWidth: number;
if (containerRef?.current) {
const { width: w } = containerRef.current.getBoundingClientRect();
actionButtonWidth = w;
}
// Set RTL based on the document direction or `LayoutDirection`
const { direction } = useLayoutDirection();
function returnFocus() {
if (focusReturn.current) {
focusReturn.current.focus();
}
}
function handleOpen() {
if (menu.current) {
focusReturn.current = document.activeElement as HTMLElement;
const pos = calculatePosition();
if (
(document?.dir === 'rtl' || direction === 'rtl') &&
!rest?.id?.includes('MenuButton')
) {
menu.current.style.insetInlineStart = `initial`;
menu.current.style.insetInlineEnd = `${pos[0]}px`;
} else {
menu.current.style.insetInlineStart = `${pos[0]}px`;
menu.current.style.insetInlineEnd = `initial`;
}
menu.current.style.insetBlockStart = `${pos[1]}px`;
setPosition(pos);
menu.current.focus();
if (onOpen) {
onOpen();
}
}
}
function handleClose(e: Pick<React.KeyboardEvent<HTMLUListElement>, 'type'>) {
if (/^key/.test(e.type)) {
window.addEventListener('keyup', returnFocus, { once: true });
} else if (e.type === 'click' && menu.current) {
menu.current.addEventListener('focusout', returnFocus, { once: true });
} else {
returnFocus();
}
if (onClose) {
onClose();
}
}
function handleKeyDown(e: React.KeyboardEvent<HTMLUListElement>) {
e.stopPropagation();
// if the user presses escape or this is a submenu
// and the user presses ArrowLeft, close it
if (
(match(e, keys.Escape) || (!isRoot && match(e, keys.ArrowLeft))) &&
onClose
) {
handleClose(e);
} else {
focusItem(e);
}
}
function focusItem(e?: React.KeyboardEvent<HTMLUListElement>) {
const currentItem = focusableItems.findIndex((item) =>
item.ref.current.contains(document.activeElement)
);
let indexToFocus = currentItem;
// if currentItem is -1, no menu item is focused yet.
// in this case, the first item should receive focus.
if (currentItem === -1) {
indexToFocus = 0;
} else if (e) {
if (match(e, keys.ArrowUp)) {
indexToFocus = indexToFocus - 1;
}
if (match(e, keys.ArrowDown)) {
indexToFocus = indexToFocus + 1;
}
}
if (indexToFocus < 0) {
indexToFocus = focusableItems.length - 1;
}
if (indexToFocus >= focusableItems.length) {
indexToFocus = 0;
}
if (indexToFocus !== currentItem) {
const nodeToFocus = focusableItems[indexToFocus];
nodeToFocus.ref.current.focus();
}
}
function handleBlur(e: React.FocusEvent<HTMLUListElement>) {
if (open && onClose && isRoot && !menu.current?.contains(e.relatedTarget)) {
handleClose(e);
}
}
function fitValue(range: number[], axis: 'x' | 'y') {
if (!menu.current) {
return;
}
const { width, height } = menu.current.getBoundingClientRect();
const alignment = isRoot ? 'vertical' : 'horizontal';
const axes = {
x: {
max: window.innerWidth,
size: width,
anchor: alignment === 'horizontal' ? range[1] : range[0],
reversedAnchor: alignment === 'horizontal' ? range[0] : range[1],
offset: 0,
},
y: {
max: window.innerHeight,
size: height,
anchor: alignment === 'horizontal' ? range[0] : range[1],
reversedAnchor: alignment === 'horizontal' ? range[1] : range[0],
offset: isRoot ? 0 : 4, // top padding in menu, used to align the menu items
},
};
// Avoid that the Menu render incorrectly when the postion is set in the right side of the screen
if (
actionButtonWidth &&
actionButtonWidth < axes.x.size &&
(menuAlignment === 'bottom' || menuAlignment === 'top')
) {
axes.x.size = actionButtonWidth;
}
// if 'axes.x.anchor' is lower than 87px dynamically switch render side
if (
actionButtonWidth &&
(menuAlignment === 'bottom-end' || menuAlignment === 'top-end') &&
axes.x.anchor >= 87 &&
actionButtonWidth < axes.x.size
) {
const diff = axes.x.anchor + axes.x.reversedAnchor;
axes.x.anchor = axes.x.anchor + diff;
}
const { max, size, anchor, reversedAnchor, offset } = axes[axis];
// get values for different scenarios, set to false if they don't work
const options = [
// towards max (preferred)
max - spacing - size - anchor >= 0 ? anchor - offset : false,
// towards min / reversed (first fallback)
reversedAnchor - size >= 0 ? reversedAnchor - size + offset : false,
// align at max (second fallback)
max - spacing - size,
];
const topAlignment =
menuAlignment === 'top' ||
menuAlignment === 'top-end' ||
menuAlignment === 'top-start';
// If the tooltip is not visible in the top, switch to the bototm
if (
typeof options[0] === 'number' &&
topAlignment &&
options[0] >= 0 &&
!options[1] &&
axis === 'y'
) {
menu.current.style.transform = 'translate(0)';
} else if (topAlignment && !options[0] && axis === 'y') {
options[0] = anchor - offset;
}
// Previous array `options`, has at least one item that is a number (the last one - second fallback).
// That guarantees that the return of `find()` will always be a number
// and we can safely add the numeric casting `as number`.
const bestOption = options.find((option) => option !== false) as number;
return bestOption >= spacing ? bestOption : spacing;
}
function notEmpty<TValue>(value: TValue | null | undefined): value is TValue {
return value !== null && value !== undefined;
}
function getPosition(x: number | (number | null | undefined)[]) {
if (Array.isArray(x)) {
// has to be of length 2
const filtered = x.filter(notEmpty);
if (filtered.length === 2) {
return filtered;
} else {
return;
}
} else {
return [x, x];
}
}
function calculatePosition() {
const ranges = {
x: getPosition(x),
y: getPosition(y),
};
if (!ranges.x || !ranges.y) {
return [-1, -1];
}
return [fitValue(ranges.x, 'x') ?? -1, fitValue(ranges.y, 'y') ?? -1];
}
useEffect(() => {
if (open && focusableItems.length > 0) {
focusItem();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, focusableItems]);
useEffect(() => {
if (open) {
handleOpen();
} else {
// reset position when menu is closed in order for the --shown
// modifier to be applied correctly
setPosition([-1, -1]);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
const classNames = cx(
className,
`${prefix}--menu`,
`${prefix}--menu--${menuSize}`,
{
// --open sets visibility and --shown sets opacity.
// visibility is needed for focusing elements.
// opacity is only set once the position has been set correctly
// to avoid a flicker effect when opening.
[`${prefix}--menu--box-shadow-top`]:
menuAlignment && menuAlignment.slice(0, 3) === 'top',
[`${prefix}--menu--open`]: open,
[`${prefix}--menu--shown`]: position[0] >= 0 && position[1] >= 0,
[`${prefix}--menu--with-icons`]: childContext.state.hasIcons,
}
);
const rendered = (
<MenuContext.Provider value={childContext}>
<ul
{...rest}
className={classNames}
role="menu"
ref={ref}
aria-label={label}
tabIndex={-1}
onKeyDown={handleKeyDown}
onBlur={handleBlur}>
{children}
</ul>
</MenuContext.Provider>
);
return isRoot ? (open && createPortal(rendered, target)) || null : rendered;
});
Menu.propTypes = {
/**
* A collection of MenuItems to be rendered within this Menu.
*/
children: PropTypes.node,
/**
* Additional CSS class names.
*/
className: PropTypes.string,
/**
* A label describing the Menu.
*/
// @ts-ignore-next-line -- avoid spurious (?) TS2322 error
label: PropTypes.string,
/**
* Specify how the menu should align with the button element
*/
menuAlignment: PropTypes.string,
/**
* The mode of this menu. Defaults to full.
* `full` supports nesting and selectable menu items, but no icons.
* `basic` supports icons but no nesting or selectable menu items.
*
* **This prop is not intended for use and will be set by the respective implementation (like useContextMenu, MenuButton, and ComboButton).**
*/
mode: PropTypes.oneOf(['full', 'basic']),
/**
* Provide an optional function to be called when the Menu should be closed.
*/
onClose: PropTypes.func,
/**
* Provide an optional function to be called when the Menu is opened.
*/
onOpen: PropTypes.func,
/**
* Whether the Menu is open or not.
*/
open: PropTypes.bool,
/**
* Specify the size of the Menu.
*/
size: PropTypes.oneOf(['xs', 'sm', 'md', 'lg']),
/**
* Specify a DOM node where the Menu should be rendered in. Defaults to document.body.
*/
// @ts-ignore-next-line -- avoid spurious (?) TS2322 error
target: PropTypes.object,
/**
* Specify the x position of the Menu. Either pass a single number or an array with two numbers describing your activator's boundaries ([x1, x2])
*/
// @ts-ignore-next-line -- avoid spurious (?) TS2322 error
x: PropTypes.oneOfType([
PropTypes.number,
PropTypes.arrayOf(PropTypes.number),
]),
/**
* Specify the y position of the Menu. Either pass a single number or an array with two numbers describing your activator's boundaries ([y1, y2])
*/
// @ts-ignore-next-line -- avoid spurious (?) TS2322 error
y: PropTypes.oneOfType([
PropTypes.number,
PropTypes.arrayOf(PropTypes.number),
]),
};
export { Menu };