-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathMenu.tsx
614 lines (558 loc) · 17.1 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
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
602
603
604
605
606
607
608
609
610
611
612
613
614
import * as React from 'react';
import {
Platform,
StyleSheet,
Animated,
BackHandler,
Dimensions,
Easing,
I18nManager,
TouchableWithoutFeedback,
View,
ScrollView,
findNodeHandle,
ViewStyle,
type EmitterSubscription,
} from 'react-native';
import type { NativeEventSubscription } from 'react-native/types';
type LayoutRectangle = { x: number; y: number; width: number; height: number };
// NOTE this is ignored in our case bcs of this.isAnchorCoord() condition
const APPROX_STATUSBAR_HEIGHT = 25;
type Props = {
/**
* Whether the Menu is currently visible.
*/
visible: boolean;
/**
* The anchor to open the menu from. In most cases, it will be a button that opens the menu.
*/
anchor: React.ReactNode | { x: number; y: number };
/**
* Extra margin to add at the top of the menu to account for translucent status bar on Android.
* If you are using Expo, we assume translucent status bar and set a height for status bar automatically.
* Pass `0` or a custom value to and customize it.
* This is automatically handled on iOS.
*/
statusBarHeight?: number;
/**
* Callback called when Menu is dismissed. The `visible` prop needs to be updated when this is called.
*/
onDismiss: () => void;
/**
* Accessibility label for the overlay. This is read by the screen reader when the user taps outside the menu.
*/
overlayAccessibilityLabel?: string;
/**
* Content of the `Menu`.
*/
children: React.ReactNode;
/**
* Style of menu's inner content.
*/
contentStyle?: ViewStyle;
style?: ViewStyle;
};
type Layout = { width: number; height: number };
type State = {
rendered: boolean;
top: number;
left: number;
menuLayout: Layout;
anchorLayout: Layout;
opacityAnimation: Animated.Value;
scaleAnimation: Animated.ValueXY;
};
// Minimum padding between the edge of the screen and the menu
const SCREEN_INDENT = 8;
// From https://material.io/design/motion/speed.html#duration
const ANIMATION_DURATION = 250;
// From the 'Standard easing' section of https://material.io/design/motion/speed.html#easing
const EASING = Easing.bezier(0.4, 0, 0.2, 1);
/**
* Menus display a list of choices on temporary elevated surfaces. Their placement varies based on the element that opens them.
*
* <div class="screenshots">
* <img class="medium" src="screenshots/menu-1.png" />
* <img class="medium" src="screenshots/menu-2.png" />
* </div>
*
* ## Usage
* ```js
* import * as React from 'react';
* import { View } from 'react-native';
* import { Button, Paragraph, Menu, Divider, Provider } from 'react-native-paper';
*
* export default class MyComponent extends React.Component {
* state = {
* visible: false,
* };
*
* _openMenu = () => this.setState({ visible: true });
*
* _closeMenu = () => this.setState({ visible: false });
*
* render() {
* return (
* <Provider>
* <View
* style={{
* paddingTop: 50,
* flexDirection: 'row',
* justifyContent: 'center'
* }}>
* <Menu
* visible={this.state.visible}
* onDismiss={this._closeMenu}
* anchor={
* <Button onPress={this._openMenu}>Show menu</Button>
* }
* >
* <Menu.Item onPress={() => {}} title="Item 1" />
* <Menu.Item onPress={() => {}} title="Item 2" />
* <Divider />
* <Menu.Item onPress={() => {}} title="Item 3" />
* </Menu>
* </View>
* </Provider>
* );
* }
* }
* ```
*/
export class Menu extends React.Component<Props, State> {
// @component ./MenuItem.tsx
// static Item = MenuItem;
static defaultProps = {
statusBarHeight: APPROX_STATUSBAR_HEIGHT,
overlayAccessibilityLabel: 'Close menu',
};
private backPressListener: NativeEventSubscription | undefined;
private dimensionChangeListener: EmitterSubscription | undefined;
static getDerivedStateFromProps(nextProps: Props, prevState: State) {
if (nextProps.visible && !prevState.rendered) {
return { rendered: true };
}
return null;
}
state = {
rendered: this.props.visible,
top: 0,
left: 0,
menuLayout: { width: 0, height: 0 },
anchorLayout: { width: 0, height: 0 },
opacityAnimation: new Animated.Value(0),
scaleAnimation: new Animated.ValueXY({ x: 0, y: 0 }),
};
componentDidUpdate(prevProps: Props) {
if (prevProps.visible !== this.props.visible) {
this.updateVisibility();
}
}
componentWillUnmount() {
this.removeListeners();
}
anchor: View | null = null;
menu: View | null = null;
isAnchorCoord = () => !React.isValidElement(this.props.anchor);
measureMenuLayout = () =>
new Promise<LayoutRectangle>((resolve) => {
if (this.menu) {
// $FlowFixMe
this.menu.measureInWindow((x, y, width, height) => {
resolve({ x, y, width, height });
});
}
});
measureAnchorLayout = () =>
new Promise<LayoutRectangle>((resolve) => {
const { anchor } = this.props;
if (this.isAnchorCoord()) {
// @ts-ignore
resolve({ x: anchor.x, y: anchor.y, width: 0, height: 0 });
return;
}
if (this.anchor) {
// $FlowFixMe
this.anchor.measureInWindow((x, y, width, height) => {
resolve({ x, y, width, height });
});
}
});
updateVisibility = async () => {
// Menu is rendered in Portal, which updates items asynchronously
// We need to do the same here so that the ref is up-to-date
await Promise.resolve();
if (this.props.visible) {
this.show();
} else {
this.hide();
}
};
isBrowser = () => Platform.OS === 'web' && 'document' in global;
focusFirstDOMNode = (el: View | null | typeof undefined) => {
if (el && this.isBrowser()) {
// When in the browser, we want to focus the first focusable item on toggle
// For example, when menu is shown, focus the first item in the menu
// And when menu is dismissed, send focus back to the button to resume tabbing
const node: any = findNodeHandle(el);
const focusableNode = node.querySelector(
// This is a rough list of selectors that can be focused
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
// $FlowFixMe
focusableNode?.focus();
}
};
handleDismiss = () => {
if (this.props.visible) {
this.props.onDismiss();
}
return true;
};
handleKeypress = (e: KeyboardEvent) => {
// @ts-ignore
if (e.key === 'Escape') {
this.props.onDismiss();
}
};
attachListeners = () => {
this.backPressListener = BackHandler.addEventListener(
'hardwareBackPress',
this.handleDismiss
);
this.dimensionChangeListener = Dimensions.addEventListener(
'change',
this.handleDismiss
);
this.isBrowser() && document.addEventListener('keyup', this.handleKeypress);
};
removeListeners = () => {
this?.backPressListener?.remove();
this?.dimensionChangeListener?.remove();
this.isBrowser() &&
document.removeEventListener('keyup', this.handleKeypress);
};
show = async () => {
const windowLayout = Dimensions.get('window');
const [menuLayout, anchorLayout] = await Promise.all([
this.measureMenuLayout(),
this.measureAnchorLayout(),
]);
// When visible is true for first render
// native views can be still not rendered and
// measureMenuLayout/measureAnchorLayout functions
// return wrong values e.g { x:0, y: 0, width: 0, height: 0 }
// so we have to wait until views are ready
// and rerun this function to show menu
if (
!windowLayout.width ||
!windowLayout.height ||
!menuLayout.width ||
!menuLayout.height ||
(!anchorLayout.width && !this.isAnchorCoord()) ||
(!anchorLayout.height && !this.isAnchorCoord())
) {
// $FlowFixMe
requestAnimationFrame(this.show);
return;
}
this.setState(
() => ({
left: anchorLayout.x,
top: anchorLayout.y,
anchorLayout: {
height: anchorLayout.height,
width: anchorLayout.width,
},
menuLayout: {
width: menuLayout.width,
height: menuLayout.height,
},
}),
() => {
this.attachListeners();
const { animation } = {
animation: {
scale: 1.0,
},
};
Animated.parallel([
Animated.timing(this.state.scaleAnimation, {
toValue: { x: menuLayout.width, y: menuLayout.height },
duration: ANIMATION_DURATION * animation.scale,
easing: EASING,
useNativeDriver: true,
}),
Animated.timing(this.state.opacityAnimation, {
toValue: 1,
duration: ANIMATION_DURATION * animation.scale,
easing: EASING,
useNativeDriver: true,
}),
]).start(({ finished }) => {
if (finished) {
this.focusFirstDOMNode(this.menu);
}
});
}
);
};
hide = () => {
this.removeListeners();
const { animation } = {
animation: {
scale: 1.0,
},
};
Animated.timing(this.state.opacityAnimation, {
toValue: 0,
duration: ANIMATION_DURATION * animation.scale,
easing: EASING,
useNativeDriver: true,
}).start(({ finished }) => {
if (finished) {
this.setState({ menuLayout: { width: 0, height: 0 }, rendered: false });
this.state.scaleAnimation.setValue({ x: 0, y: 0 });
this.focusFirstDOMNode(this.anchor);
}
});
};
render() {
const {
visible,
contentStyle,
style,
children,
statusBarHeight,
onDismiss,
overlayAccessibilityLabel,
} = this.props;
const {
rendered,
menuLayout,
anchorLayout,
opacityAnimation,
scaleAnimation,
} = this.state;
let { left, top } = this.state;
// I don't know why but on Android measure function is wrong by 24
const additionalVerticalValue = Platform.select({
android: statusBarHeight,
default: 0,
});
const scaleTransforms = [
{
scaleX: scaleAnimation.x.interpolate({
inputRange: [0, menuLayout.width],
// $FlowFixMe
outputRange: [0, 1],
}),
},
{
scaleY: scaleAnimation.y.interpolate({
inputRange: [0, menuLayout.height],
// $FlowFixMe
outputRange: [0, 1],
}),
},
];
const windowLayout = Dimensions.get('window');
// We need to translate menu while animating scale to imitate transform origin for scale animation
const positionTransforms = [];
// Check if menu fits horizontally and if not align it to right.
if (left <= windowLayout.width - menuLayout.width - SCREEN_INDENT) {
positionTransforms.push({
translateX: scaleAnimation.x.interpolate({
inputRange: [0, menuLayout.width],
// $FlowFixMe
outputRange: [-(menuLayout.width / 2), 0],
}),
});
// Check if menu position has enough space from left side
if (left < SCREEN_INDENT) {
left = SCREEN_INDENT;
}
} else {
positionTransforms.push({
translateX: scaleAnimation.x.interpolate({
inputRange: [0, menuLayout.width],
// $FlowFixMe
outputRange: [menuLayout.width / 2, 0],
}),
});
left += anchorLayout.width - menuLayout.width;
const right = left + menuLayout.width;
// Check if menu position has enough space from right side
if (right > windowLayout.width - SCREEN_INDENT) {
left = windowLayout.width - SCREEN_INDENT - menuLayout.width;
}
}
// If the menu is larger than available vertical space,
// calculate the height of scrollable view
let scrollableMenuHeight = 0;
// Check if the menu should be scrollable
if (
// Check if the menu overflows from bottom side
top >=
windowLayout.height -
menuLayout.height -
SCREEN_INDENT -
additionalVerticalValue &&
// And bottom side of the screen has more space than top side
top <= windowLayout.height - top
) {
// Scrollable menu should be below the anchor (expands downwards)
scrollableMenuHeight =
windowLayout.height - top - SCREEN_INDENT - additionalVerticalValue;
} else if (
// Check if the menu overflows from bottom side
top >=
windowLayout.height -
menuLayout.height -
SCREEN_INDENT -
additionalVerticalValue &&
// And top side of the screen has more space than bottom side
top >= windowLayout.height - top &&
// And menu overflows from top side
top <=
menuLayout.height -
anchorLayout.height +
SCREEN_INDENT -
additionalVerticalValue
) {
// Scrollable menu should be above the anchor (expands upwards)
scrollableMenuHeight =
top + anchorLayout.height - SCREEN_INDENT + additionalVerticalValue;
}
// Scrollable menu max height
scrollableMenuHeight =
scrollableMenuHeight > windowLayout.height - 2 * SCREEN_INDENT
? windowLayout.height - 2 * SCREEN_INDENT
: scrollableMenuHeight;
// Menu is typically positioned below the element that generates it
// So first check if it fits below the anchor (expands downwards)
if (
// Check if menu fits vertically
top <=
windowLayout.height -
menuLayout.height -
SCREEN_INDENT -
additionalVerticalValue ||
// Or if the menu overflows from bottom side
(top >=
windowLayout.height -
menuLayout.height -
SCREEN_INDENT -
additionalVerticalValue &&
// And bottom side of the screen has more space than top side
top <= windowLayout.height - top)
) {
positionTransforms.push({
translateY: scaleAnimation.y.interpolate({
inputRange: [0, menuLayout.height],
// $FlowFixMe
outputRange: [-((scrollableMenuHeight || menuLayout.height) / 2), 0],
}),
});
// Check if menu position has enough space from top side
if (top < SCREEN_INDENT) {
top = SCREEN_INDENT;
}
} else {
positionTransforms.push({
translateY: scaleAnimation.y.interpolate({
inputRange: [0, menuLayout.height],
// $FlowFixMe
outputRange: [(scrollableMenuHeight || menuLayout.height) / 2, 0],
}),
});
top += anchorLayout.height - (scrollableMenuHeight || menuLayout.height);
const bottom =
top +
(scrollableMenuHeight || menuLayout.height) +
additionalVerticalValue;
// Check if menu position has enough space from bottom side
if (bottom > windowLayout.height - SCREEN_INDENT) {
top =
scrollableMenuHeight === windowLayout.height - 2 * SCREEN_INDENT
? -SCREEN_INDENT * 2
: windowLayout.height -
menuLayout.height -
SCREEN_INDENT -
additionalVerticalValue;
}
}
const shadowMenuContainerStyle = {
opacity: opacityAnimation,
transform: scaleTransforms,
borderRadius: 5,
...(scrollableMenuHeight ? { height: scrollableMenuHeight } : {}),
};
const positionStyle = {
top: this.isAnchorCoord() ? top : top + additionalVerticalValue,
...(I18nManager.isRTL ? { right: left } : { left }),
};
return rendered ? (
<View style={StyleSheet.absoluteFill} collapsable={false}>
<TouchableWithoutFeedback
accessibilityLabel={overlayAccessibilityLabel}
accessibilityRole="button"
onPress={onDismiss}
>
<View style={StyleSheet.absoluteFill} />
</TouchableWithoutFeedback>
<View
ref={(ref) => {
this.menu = ref;
}}
collapsable={false}
accessibilityViewIsModal={visible}
style={[styles.wrapper, positionStyle, style]}
pointerEvents={visible ? 'box-none' : 'none'}
onAccessibilityEscape={onDismiss}
>
<Animated.View style={{ transform: positionTransforms }}>
<Animated.View
style={[
styles.shadowMenuContainer,
styles.surface,
shadowMenuContainerStyle,
contentStyle,
]}
>
{(scrollableMenuHeight && (
<ScrollView>{children}</ScrollView>
)) || <React.Fragment>{children}</React.Fragment>}
</Animated.View>
</Animated.View>
</View>
</View>
) : null;
}
}
const styles = StyleSheet.create({
wrapper: {
position: 'absolute',
},
shadowMenuContainer: {
opacity: 0,
paddingVertical: 8,
...Platform.select({
android: {
elevation: 8,
},
default: {
shadowColor: 'black',
shadowOffset: {
width: 0,
height: 7,
},
shadowOpacity: 0.24,
shadowRadius: 8,
},
}),
},
surface: {
backgroundColor: 'white',
},
});