-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
Copy pathMenu.js
525 lines (462 loc) · 14 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
// @flow
import React, {
Component,
type Element as ReactElement,
type ElementRef,
type Node,
} from 'react';
import { css } from 'emotion';
import { createPortal } from 'react-dom';
import PropTypes from 'prop-types';
import {
animatedScrollTo,
getBoundingClientObj,
type RectType,
getScrollParent,
getScrollTop,
scrollTo,
} from '../utils';
import type {
InnerRef,
MenuPlacement,
MenuPosition,
CommonProps,
} from '../types';
import type { Theme } from '../types';
// ==============================
// Menu
// ==============================
// Get Menu Placement
// ------------------------------
type MenuState = {
placement: 'bottom' | 'top' | null,
maxHeight: number,
};
type PlacementArgs = {
maxHeight: number,
menuEl: ElementRef<*>,
minHeight: number,
placement: 'bottom' | 'top' | 'auto',
shouldScroll: boolean,
isFixedPosition: boolean,
theme: Theme,
};
export function getMenuPlacement({
maxHeight,
menuEl,
minHeight,
placement,
shouldScroll,
isFixedPosition,
theme,
}: PlacementArgs): MenuState {
const { spacing } = theme;
const scrollParent = getScrollParent(menuEl);
const defaultState = { placement: 'bottom', maxHeight };
// something went wrong, return default state
if (!menuEl || !menuEl.offsetParent) return defaultState;
// we can't trust `scrollParent.scrollHeight` --> it may increase when
// the menu is rendered
const { height: scrollHeight } = scrollParent.getBoundingClientRect();
const {
bottom: menuBottom,
height: menuHeight,
top: menuTop,
} = menuEl.getBoundingClientRect();
const { top: containerTop } = menuEl.offsetParent.getBoundingClientRect();
const viewHeight = window.innerHeight;
const scrollTop = getScrollTop(scrollParent);
const marginBottom = parseInt(getComputedStyle(menuEl).marginBottom, 10);
const marginTop = parseInt(getComputedStyle(menuEl).marginTop, 10);
const viewSpaceAbove = containerTop - marginTop;
const viewSpaceBelow = viewHeight - menuTop;
const scrollSpaceAbove = viewSpaceAbove + scrollTop;
const scrollSpaceBelow = scrollHeight - scrollTop - menuTop;
const scrollDown = menuBottom - viewHeight + scrollTop + marginBottom;
const scrollUp = scrollTop + menuTop - marginTop;
const scrollDuration = 160;
switch (placement) {
case 'auto':
case 'bottom':
// 1: the menu will fit, do nothing
if (viewSpaceBelow >= menuHeight) {
return { placement: 'bottom', maxHeight };
}
// 2: the menu will fit, if scrolled
if (scrollSpaceBelow >= menuHeight && !isFixedPosition) {
if (shouldScroll) {
animatedScrollTo(scrollParent, scrollDown, scrollDuration);
}
return { placement: 'bottom', maxHeight };
}
// 3: the menu will fit, if constrained
if (
(!isFixedPosition && scrollSpaceBelow >= minHeight) ||
(isFixedPosition && viewSpaceBelow >= minHeight)
) {
if (shouldScroll) {
animatedScrollTo(scrollParent, scrollDown, scrollDuration);
}
// we want to provide as much of the menu as possible to the user,
// so give them whatever is available below rather than the minHeight.
const constrainedHeight = isFixedPosition
? viewSpaceBelow - marginBottom
: scrollSpaceBelow - marginBottom;
return {
placement: 'bottom',
maxHeight: constrainedHeight,
};
}
// 4. Forked beviour when there isn't enough space below
// AUTO: flip the menu, render above
if (placement === 'auto' || isFixedPosition) {
// may need to be constrained after flipping
let constrainedHeight = maxHeight;
const spaceAbove = isFixedPosition ? viewSpaceAbove : scrollSpaceAbove;
if (spaceAbove >= minHeight) {
constrainedHeight = Math.min(
spaceAbove - marginBottom - spacing.controlHeight,
maxHeight
);
}
return { placement: 'top', maxHeight: constrainedHeight };
}
// BOTTOM: allow browser to increase scrollable area and immediately set scroll
if (placement === 'bottom') {
scrollTo(scrollParent, scrollDown);
return { placement: 'bottom', maxHeight };
}
break;
case 'top':
// 1: the menu will fit, do nothing
if (viewSpaceAbove >= menuHeight) {
return { placement: 'top', maxHeight };
}
// 2: the menu will fit, if scrolled
if (scrollSpaceAbove >= menuHeight && !isFixedPosition) {
if (shouldScroll) {
animatedScrollTo(scrollParent, scrollUp, scrollDuration);
}
return { placement: 'top', maxHeight };
}
// 3: the menu will fit, if constrained
if (
(!isFixedPosition && scrollSpaceAbove >= minHeight) ||
(isFixedPosition && viewSpaceAbove >= minHeight)
) {
let constrainedHeight = maxHeight;
// we want to provide as much of the menu as possible to the user,
// so give them whatever is available below rather than the minHeight.
if (
(!isFixedPosition && scrollSpaceAbove >= minHeight) ||
(isFixedPosition && viewSpaceAbove >= minHeight)
) {
constrainedHeight = isFixedPosition
? viewSpaceAbove - marginTop
: scrollSpaceAbove - marginTop;
}
if (shouldScroll) {
animatedScrollTo(scrollParent, scrollUp, scrollDuration);
}
return {
placement: 'top',
maxHeight: constrainedHeight,
};
}
// 4. not enough space, the browser WILL NOT increase scrollable area when
// absolutely positioned element rendered above the viewport (only below).
// Flip the menu, render below
return { placement: 'bottom', maxHeight };
default:
throw new Error(`Invalid placement provided "${placement}".`);
}
// fulfil contract with flow: implicit return value of undefined
return defaultState;
}
// Menu Component
// ------------------------------
export type MenuAndPlacerCommon = CommonProps & {
/** Callback to update the portal after possible flip. */
getPortalPlacement: MenuState => void,
/** Props to be passed to the menu wrapper. */
innerProps: {},
/** Set the maximum height of the menu. */
maxMenuHeight: number,
/** Set whether the menu should be at the top, at the bottom. The auto options sets it to bottom. */
menuPlacement: MenuPlacement,
/* The CSS position value of the menu, when "fixed" extra layout management is required */
menuPosition: MenuPosition,
/** Set the minimum height of the menu. */
minMenuHeight: number,
/** Set whether the page should scroll to show the menu. */
menuShouldScrollIntoView: boolean,
};
export type MenuProps = MenuAndPlacerCommon & {
/** Reference to the internal element, consumed by the MenuPlacer component */
innerRef: ElementRef<*>,
/** The children to be rendered. */
children: ReactElement<*>,
};
export type MenuPlacerProps = MenuAndPlacerCommon & {
/** The children to be rendered. */
children: ({ }) => Node,
};
function alignToControl(placement) {
const placementToCSSProp = { bottom: 'top', top: 'bottom' };
return placement ? placementToCSSProp[placement] : 'bottom';
}
const coercePlacement = p => (p === 'auto' ? 'bottom' : p);
type MenuStateWithProps = MenuState & MenuProps;
export const menuCSS = ({
placement,
theme: { borderRadius, spacing, colors },
}: MenuStateWithProps) => ({
[alignToControl(placement)]: '100%',
backgroundColor: colors.neutral0,
borderRadius: borderRadius,
boxShadow: '0 0 0 1px hsla(0, 0%, 0%, 0.1), 0 4px 11px hsla(0, 0%, 0%, 0.1)',
marginBottom: spacing.menuGutter,
marginTop: spacing.menuGutter,
position: 'absolute',
width: '100%',
zIndex: 1,
});
// NOTE: internal only
export class MenuPlacer extends Component<MenuPlacerProps, MenuState> {
state = {
maxHeight: this.props.maxMenuHeight,
placement: null,
};
static contextTypes = {
getPortalPlacement: PropTypes.func,
};
getPlacement = (ref: ElementRef<*>) => {
const {
minMenuHeight,
maxMenuHeight,
menuPlacement,
menuPosition,
menuShouldScrollIntoView,
theme,
} = this.props;
const { getPortalPlacement } = this.context;
if (!ref) return;
// DO NOT scroll if position is fixed
const isFixedPosition = menuPosition === 'fixed';
const shouldScroll = menuShouldScrollIntoView && !isFixedPosition;
const state = getMenuPlacement({
maxHeight: maxMenuHeight,
menuEl: ref,
minHeight: minMenuHeight,
placement: menuPlacement,
shouldScroll,
isFixedPosition,
theme,
});
if (getPortalPlacement) getPortalPlacement(state);
this.setState(state);
};
getUpdatedProps = () => {
const { menuPlacement } = this.props;
const placement = this.state.placement || coercePlacement(menuPlacement);
return { ...this.props, placement, maxHeight: this.state.maxHeight };
};
render() {
const { children } = this.props;
return children({
ref: this.getPlacement,
placerProps: this.getUpdatedProps(),
});
}
}
const Menu = (props: MenuProps) => {
const { children, className, cx, getStyles, innerRef, innerProps } = props;
const cn = cx(css(getStyles('menu', props)), { menu: true }, className);
return (
<div className={cn} {...innerProps} ref={innerRef}>
{children}
</div>
);
};
export default Menu;
// ==============================
// Menu List
// ==============================
type MenuListState = {
/** Set classname for isMulti */
isMulti: boolean,
/* Set the max height of the Menu component */
maxHeight: number,
};
export type MenuListProps = {
/** The children to be rendered. */
children: Node,
/** Inner ref to DOM Node */
innerRef: InnerRef,
};
export type MenuListComponentProps = CommonProps &
MenuListProps &
MenuListState;
export const menuListCSS = ({
maxHeight,
theme: {
spacing: { baseUnit },
},
}: MenuListComponentProps) => ({
maxHeight,
overflowY: 'auto',
paddingBottom: baseUnit,
paddingTop: baseUnit,
position: 'relative', // required for offset[Height, Top] > keyboard scroll
WebkitOverflowScrolling: 'touch',
});
export const MenuList = (props: MenuListComponentProps) => {
const { children, className, cx, getStyles, isMulti, innerRef } = props;
return (
<div
className={cx(
css(getStyles('menuList', props)),
{
'menu-list': true,
'menu-list--is-multi': isMulti,
},
className
)}
ref={innerRef}
>
{children}
</div>
);
};
// ==============================
// Menu Notices
// ==============================
const noticeCSS = ({
theme: {
spacing: { baseUnit },
colors,
},
}: NoticeProps) => ({
color: colors.neutral40,
padding: `${baseUnit * 2}px ${baseUnit * 3}px`,
textAlign: 'center',
});
export const noOptionsMessageCSS = noticeCSS;
export const loadingMessageCSS = noticeCSS;
export type NoticeProps = CommonProps & {
/** The children to be rendered. */
children: Node,
/** Props to be passed on to the wrapper. */
innerProps: {},
};
export const NoOptionsMessage = (props: NoticeProps) => {
const { children, className, cx, getStyles, innerProps } = props;
return (
<div
className={cx(
css(getStyles('noOptionsMessage', props)),
{
'menu-notice': true,
'menu-notice--no-options': true,
},
className
)}
{...innerProps}
>
{children}
</div>
);
};
NoOptionsMessage.defaultProps = {
children: 'No options',
};
export const LoadingMessage = (props: NoticeProps) => {
const { children, className, cx, getStyles, innerProps } = props;
return (
<div
className={cx(
css(getStyles('loadingMessage', props)),
{
'menu-notice': true,
'menu-notice--loading': true,
},
className
)}
{...innerProps}
>
{children}
</div>
);
};
LoadingMessage.defaultProps = {
children: 'Loading...',
};
// ==============================
// Menu Portal
// ==============================
export type MenuPortalProps = CommonProps & {
appendTo: HTMLElement,
children: Node, // ideally Menu<MenuProps>
controlElement: HTMLElement,
menuPlacement: MenuPlacement,
menuPosition: MenuPosition,
};
type MenuPortalState = {
placement: 'bottom' | 'top' | null,
};
type PortalStyleArgs = {
offset: number,
position: MenuPosition,
rect: RectType,
};
export const menuPortalCSS = ({ rect, offset, position }: PortalStyleArgs) => ({
left: rect.left,
position: position,
top: offset,
width: rect.width,
zIndex: 1,
});
export class MenuPortal extends Component<MenuPortalProps, MenuPortalState> {
state = { placement: null };
static childContextTypes = {
getPortalPlacement: PropTypes.func,
};
getChildContext() {
return {
getPortalPlacement: this.getPortalPlacement,
};
}
// callback for occassions where the menu must "flip"
getPortalPlacement = ({ placement }: MenuState) => {
const initialPlacement = coercePlacement(this.props.menuPlacement);
// avoid re-renders if the placement has not changed
if (placement !== initialPlacement) {
this.setState({ placement });
}
};
render() {
const {
appendTo,
children,
controlElement,
menuPlacement,
menuPosition: position,
getStyles,
} = this.props;
const isFixed = position === 'fixed';
// bail early if required elements aren't present
if ((!appendTo && !isFixed) || !controlElement) {
return null;
}
const placement = this.state.placement || coercePlacement(menuPlacement);
const rect = getBoundingClientObj(controlElement);
const scrollDistance = isFixed ? 0 : window.pageYOffset;
const offset = rect[placement] + scrollDistance;
const state = { offset, position, rect };
// same wrapper element whether fixed or portalled
const menuWrapper = (
<div className={css(getStyles('menuPortal', state))}>{children}</div>
);
return appendTo ? createPortal(menuWrapper, appendTo) : menuWrapper;
}
}