-
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
dropdownMenu.tsx
447 lines (378 loc) · 12 KB
/
dropdownMenu.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
import PropTypes from 'prop-types';
import React from 'react';
import * as Sentry from '@sentry/react';
import {MENU_CLOSE_DELAY} from 'app/constants';
type GetActorArgs = {
onClick?: (e: React.MouseEvent<Element>) => void;
onMouseEnter?: (e: React.MouseEvent<Element>) => void;
onMouseLeave?: (e: React.MouseEvent<Element>) => void;
onKeyDown?: (e: React.KeyboardEvent<Element>) => void;
style?: React.CSSProperties;
className?: string;
};
type GetMenuArgs = {
onClick?: (e: React.MouseEvent<Element>) => void;
onMouseEnter?: (e: React.MouseEvent<Element>) => void;
onMouseLeave?: (e: React.MouseEvent<Element>) => void;
className?: string;
};
// Props for the "actor" element of `<DropdownMenu>`
// This is the element that handles visibility of the dropdown menu
type ActorProps = {
onClick: (e: React.MouseEvent<Element>) => void;
onMouseEnter: (e: React.MouseEvent<Element>) => void;
onMouseLeave: (e: React.MouseEvent<Element>) => void;
onKeyDown: (e: React.KeyboardEvent<Element>) => void;
};
type MenuProps = {
onClick: (e: React.MouseEvent<Element>) => void;
onMouseEnter: (e: React.MouseEvent<Element>) => void;
onMouseLeave: (e: React.MouseEvent<Element>) => void;
};
export type GetActorPropsFn = (opts?: GetActorArgs) => ActorProps;
type GetMenuPropsFn = (opts?: GetMenuArgs) => MenuProps;
type RenderProps = {
isOpen: boolean;
getRootProps: Function;
getActorProps: GetActorPropsFn;
getMenuProps: GetMenuPropsFn;
actions: {
open: Function;
close: Function;
};
};
type DefaultProps = {
/**
* Keeps dropdown menu open when menu is clicked
*/
keepMenuOpen: boolean;
/**
* closes menu on "Esc" keypress
*/
closeOnEscape: boolean;
};
type Props = DefaultProps & {
onOpen?: Function;
onClose?: Function;
/**
* Callback for when we get a click outside of dropdown menus.
* Useful for when menu is controlled.
*/
onClickOutside?: Function;
/**
* Callback function to check if we should ignore click outside to
* hide dropdown menu
*/
shouldIgnoreClickOutside?: (event: MouseEvent) => boolean;
/**
* If this is set, then this will become a "controlled" component.
* It will no longer set local state and dropdown visibility will
* only follow `isOpen`.
*/
isOpen?: boolean;
/**
* Compatibility for <DropdownLink>
* This will change where we attach event handlers
*/
alwaysRenderMenu?: boolean;
/**
* If this is set to true, the dropdown behaves as a "nested dropdown" and is
* triggered on mouse enter and mouse leave
*/
isNestedDropdown?: boolean;
/**
* Render function
*/
children: (renderProps: RenderProps) => React.ReactNode;
};
type State = {
isOpen: boolean;
};
class DropdownMenu extends React.Component<Props, State> {
static propTypes = {
onOpen: PropTypes.func,
onClose: PropTypes.func,
onClickOutside: PropTypes.func,
shouldIgnoreClickOutside: PropTypes.func,
isOpen: PropTypes.bool,
keepMenuOpen: PropTypes.bool,
alwaysRenderMenu: PropTypes.bool,
closeOnEscape: PropTypes.bool,
isNestedDropdown: PropTypes.bool,
};
static defaultProps: DefaultProps = {
keepMenuOpen: false,
closeOnEscape: true,
};
state: State = {
isOpen: false,
};
componentWillUnmount() {
document.removeEventListener('click', this.checkClickOutside, true);
}
dropdownMenu: Element | null = null;
dropdownActor: Element | null = null;
mouseLeaveId: number | null = null;
mouseEnterId: number | null = null;
// Gets open state from props or local state when appropriate
isOpen = () => {
const {isOpen} = this.props;
const isControlled = typeof isOpen !== 'undefined';
return (isControlled && isOpen) || this.state.isOpen;
};
// Checks if click happens inside of dropdown menu (or its button)
// Closes dropdownmenu if it is "outside"
checkClickOutside = async (e: MouseEvent) => {
const {onClickOutside, shouldIgnoreClickOutside} = this.props;
if (!this.dropdownMenu) {
return;
}
if (!(e.target instanceof Element)) {
return;
}
// Dropdown menu itself
if (this.dropdownMenu.contains(e.target)) {
return;
}
if (!this.dropdownActor) {
// Log an error, should be lower priority
Sentry.withScope(scope => {
scope.setLevel(Sentry.Severity.Warning);
Sentry.captureException(new Error('DropdownMenu does not have "Actor" attached'));
});
}
// Button that controls visibility of dropdown menu
if (this.dropdownActor && this.dropdownActor.contains(e.target)) {
return;
}
if (typeof shouldIgnoreClickOutside === 'function' && shouldIgnoreClickOutside(e)) {
return;
}
if (typeof onClickOutside === 'function') {
onClickOutside(e);
}
// Wait until the current macrotask completes, in the case that the click
// happened on a hovercard or some other element rendered outside of the
// dropdown, but controlled by the existence of the dropdown, we need to
// ensure any click handlers are run.
await new Promise(resolve => setTimeout(resolve));
this.handleClose(null);
};
// Opens dropdown menu
handleOpen = (e: React.MouseEvent<Element>) => {
const {onOpen, isOpen, alwaysRenderMenu} = this.props;
const isControlled = typeof isOpen !== 'undefined';
if (!isControlled) {
this.setState({
isOpen: true,
});
}
if (this.mouseLeaveId) {
window.clearTimeout(this.mouseLeaveId);
}
// If we always render menu (e.g. DropdownLink), then add the check click outside handlers when we open the menu
// instead of when the menu component mounts. Otherwise we will have many click handlers attached on initial load.
if (alwaysRenderMenu) {
document.addEventListener('click', this.checkClickOutside, true);
}
if (typeof onOpen === 'function') {
onOpen(e);
}
};
// Decide whether dropdown should be closed when mouse leaves element
// Only for nested dropdowns
handleMouseLeave = (e: React.MouseEvent<Element>) => {
const {isNestedDropdown} = this.props;
if (!isNestedDropdown) {
return;
}
const toElement = e.relatedTarget;
try {
if (
this.dropdownMenu &&
(!(toElement instanceof Element) || !this.dropdownMenu.contains(toElement))
) {
this.mouseLeaveId = window.setTimeout(() => {
this.handleClose(e);
}, MENU_CLOSE_DELAY);
}
} catch (err) {
Sentry.withScope(scope => {
scope.setExtra('event', e);
scope.setExtra('relatedTarget', e.relatedTarget);
Sentry.captureException(err);
});
}
};
// Closes dropdown menu
handleClose = (e: React.KeyboardEvent<Element> | React.MouseEvent<Element> | null) => {
const {onClose, isOpen, alwaysRenderMenu} = this.props;
const isControlled = typeof isOpen !== 'undefined';
if (!isControlled) {
this.setState({isOpen: false});
}
// Clean up click handlers when the menu is closed for menus that are always rendered,
// otherwise the click handlers get cleaned up when menu is unmounted
if (alwaysRenderMenu) {
document.removeEventListener('click', this.checkClickOutside, true);
}
if (typeof onClose === 'function') {
onClose(e);
}
};
// When dropdown menu is displayed and mounted to DOM,
// bind a click handler to `document` to listen for clicks outside of
// this component and close menu if so
handleMenuMount = (ref: Element | null) => {
if (ref && !(ref instanceof Element)) {
return;
}
const {alwaysRenderMenu} = this.props;
this.dropdownMenu = ref;
// Don't add document event listeners here if we are always rendering menu
// Instead add when menu is opened
if (alwaysRenderMenu) {
return;
}
if (this.dropdownMenu) {
// 3rd arg = useCapture = so event capturing vs event bubbling
document.addEventListener('click', this.checkClickOutside, true);
} else {
document.removeEventListener('click', this.checkClickOutside, true);
}
};
handleActorMount = (ref: Element | null) => {
if (ref && !(ref instanceof Element)) {
return;
}
this.dropdownActor = ref;
};
handleToggle = (e: React.MouseEvent<Element>) => {
if (this.isOpen()) {
this.handleClose(e);
} else {
this.handleOpen(e);
}
};
// Control whether we should hide dropdown menu when it is clicked
handleDropdownMenuClick = (e: React.MouseEvent<Element>) => {
if (this.props.keepMenuOpen) {
return;
}
this.handleClose(e);
};
getRootProps<T>(props: T): T {
return props;
}
// Actor is the component that will open the dropdown menu
getActorProps: GetActorPropsFn = ({
onClick,
onMouseEnter,
onMouseLeave,
onKeyDown,
style = {},
...props
}: GetActorArgs = {}) => {
const {isNestedDropdown, closeOnEscape} = this.props;
const refProps = {ref: this.handleActorMount};
// Props that the actor needs to have <DropdownMenu> work
return {
...props,
...refProps,
style: {...style, outline: 'none'},
onKeyDown: (e: React.KeyboardEvent<Element>) => {
if (typeof onKeyDown === 'function') {
onKeyDown(e);
}
if (e.key === 'Escape' && closeOnEscape) {
this.handleClose(e);
}
},
onMouseEnter: (e: React.MouseEvent<Element>) => {
if (typeof onMouseEnter === 'function') {
onMouseEnter(e);
}
// Only handle mouse enter for nested dropdowns
if (!isNestedDropdown) {
return;
}
if (this.mouseLeaveId) {
window.clearTimeout(this.mouseLeaveId);
}
this.mouseEnterId = window.setTimeout(() => {
this.handleOpen(e);
}, MENU_CLOSE_DELAY);
},
onMouseLeave: (e: React.MouseEvent<Element>) => {
if (typeof onMouseLeave === 'function') {
onMouseLeave(e);
}
if (this.mouseEnterId) {
window.clearTimeout(this.mouseEnterId);
}
this.handleMouseLeave(e);
},
onClick: (e: React.MouseEvent<Element>) => {
// Note: clicking on an actor that has a nested menu will close the dropdown menus
// This is because we currently do not try to find the deepest non-nested dropdown menu
this.handleToggle(e);
if (typeof onClick === 'function') {
onClick(e);
}
},
};
};
// Menu is the menu component that <DropdownMenu> will control
getMenuProps: GetMenuPropsFn = ({
onClick,
onMouseLeave,
onMouseEnter,
...props
}: GetMenuArgs = {}): MenuProps => {
const refProps = {ref: this.handleMenuMount};
// Props that the menu needs to have <DropdownMenu> work
return {
...props,
...refProps,
onMouseEnter: (e: React.MouseEvent<Element>) => {
if (typeof onMouseEnter === 'function') {
onMouseEnter(e);
}
// There is a delay before closing a menu on mouse leave, cancel this action if mouse enters menu again
if (this.mouseLeaveId) {
window.clearTimeout(this.mouseLeaveId);
}
},
onMouseLeave: (e: React.MouseEvent<Element>) => {
if (typeof onMouseLeave === 'function') {
onMouseLeave(e);
}
this.handleMouseLeave(e);
},
onClick: (e: React.MouseEvent<Element>) => {
// Note: clicking on an actor that has a nested menu will close the dropdown menus
// This is because we currently do not try to find the deepest non-nested dropdown menu
this.handleDropdownMenuClick(e);
if (typeof onClick === 'function') {
onClick(e);
}
},
};
};
render() {
const {children} = this.props;
// Default anchor = left
const shouldShowDropdown = this.isOpen();
return children({
isOpen: shouldShowDropdown,
getRootProps: this.getRootProps,
getActorProps: this.getActorProps,
getMenuProps: this.getMenuProps,
actions: {
open: this.handleOpen,
close: this.handleClose,
},
});
}
}
export default DropdownMenu;