forked from processing/p5.js-web-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDropdownMenu.jsx
97 lines (85 loc) · 2.48 KB
/
DropdownMenu.jsx
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
import PropTypes from 'prop-types';
import React, { forwardRef, useCallback, useRef, useState } from 'react';
import useModalClose from '../../common/useModalClose';
import DownArrowIcon from '../../images/down-filled-triangle.svg';
import { DropdownWrapper } from '../Dropdown';
// TODO: enable arrow keys to navigate options from list
const DropdownMenu = forwardRef(
(
{ children, anchor, 'aria-label': ariaLabel, align, className, classes },
ref
) => {
// Note: need to use a ref instead of a state to avoid stale closures.
const focusedRef = useRef(false);
const [isOpen, setIsOpen] = useState(false);
const close = useCallback(() => setIsOpen(false), [setIsOpen]);
const anchorRef = useModalClose(close, ref);
const toggle = useCallback(() => {
setIsOpen((prevState) => !prevState);
}, [setIsOpen]);
const handleFocus = () => {
focusedRef.current = true;
};
const handleBlur = () => {
focusedRef.current = false;
setTimeout(() => {
if (!focusedRef.current) {
close();
}
}, 200);
};
return (
<div ref={anchorRef} className={className} aria-haspopup="menu">
<button
className={classes.button}
aria-label={ariaLabel}
tabIndex="0"
onClick={toggle}
onBlur={handleBlur}
onFocus={handleFocus}
>
{anchor ?? <DownArrowIcon focusable="false" aria-hidden="true" />}
</button>
{isOpen && (
<DropdownWrapper
role="menu"
className={classes.list}
align={align}
onMouseUp={() => {
setTimeout(close, 0);
}}
onBlur={handleBlur}
onFocus={handleFocus}
>
{children}
</DropdownWrapper>
)}
</div>
);
}
);
DropdownMenu.propTypes = {
/**
* Provide <MenuItem> elements as children to control the contents of the menu.
*/
children: PropTypes.node.isRequired,
/**
* Can optionally override the contents of the button which opens the menu.
* Defaults to <DownArrowIcon>
*/
anchor: PropTypes.node,
'aria-label': PropTypes.string.isRequired,
align: PropTypes.oneOf(['left', 'right']),
className: PropTypes.string,
classes: PropTypes.shape({
button: PropTypes.string,
list: PropTypes.string
})
};
DropdownMenu.defaultProps = {
anchor: null,
align: 'right',
className: '',
classes: {}
};
export default DropdownMenu;