forked from react-navigation/react-navigation
/
Drawer.tsx
672 lines (606 loc) · 20.9 KB
/
Drawer.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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
import * as React from 'react';
import {
I18nManager,
InteractionManager,
Keyboard,
LayoutChangeEvent,
Platform,
StatusBar,
StyleSheet,
View,
} from 'react-native';
import Animated from 'react-native-reanimated';
import type { DrawerProps } from '../../types';
import DrawerProgressContext from '../../utils/DrawerProgressContext';
import { GestureState, PanGestureHandler } from '../GestureHandler';
import Overlay from './Overlay';
const {
Clock,
Value,
onChange,
clockRunning,
startClock,
stopClock,
spring,
abs,
add,
and,
block,
call,
cond,
divide,
eq,
event,
greaterThan,
lessThan,
max,
min,
multiply,
neq,
or,
set,
sub,
} = Animated;
const TRUE = 1;
const FALSE = 0;
const NOOP = 0;
const UNSET = -1;
const DIRECTION_LEFT = 1;
const DIRECTION_RIGHT = -1;
const SWIPE_DISTANCE_MINIMUM = 5;
const DEFAULT_DRAWER_WIDTH = '80%';
const SPRING_CONFIG = {
stiffness: 1000,
damping: 500,
mass: 3,
overshootClamping: true,
restDisplacementThreshold: 0.01,
restSpeedThreshold: 0.01,
};
const ANIMATED_ZERO = new Animated.Value(0);
const ANIMATED_ONE = new Animated.Value(1);
type Binary = 0 | 1;
export default class DrawerView extends React.Component<DrawerProps> {
componentDidUpdate(prevProps: DrawerProps) {
const {
open,
drawerPosition,
drawerType,
swipeDistanceThreshold,
swipeVelocityThreshold,
hideStatusBarOnOpen: hideStatusBar,
} = this.props;
if (
// If we're not in the middle of a transition, sync the drawer's open state
typeof this.pendingOpenValue !== 'boolean' ||
open !== this.pendingOpenValue
) {
this.toggleDrawer(open);
}
this.pendingOpenValue = undefined;
if (open !== prevProps.open && hideStatusBar) {
this.toggleStatusBar(open);
}
if (prevProps.drawerPosition !== drawerPosition) {
this.drawerPosition.setValue(
drawerPosition === 'right' ? DIRECTION_RIGHT : DIRECTION_LEFT
);
}
if (prevProps.drawerType !== drawerType) {
this.isDrawerTypeFront.setValue(drawerType === 'front' ? TRUE : FALSE);
}
if (prevProps.swipeDistanceThreshold !== swipeDistanceThreshold) {
this.swipeDistanceThreshold.setValue(swipeDistanceThreshold);
}
if (prevProps.swipeVelocityThreshold !== swipeVelocityThreshold) {
this.swipeVelocityThreshold.setValue(swipeVelocityThreshold);
}
}
componentWillUnmount() {
this.toggleStatusBar(false);
this.handleEndInteraction();
}
private handleEndInteraction = () => {
if (this.interactionHandle !== undefined) {
InteractionManager.clearInteractionHandle(this.interactionHandle);
this.interactionHandle = undefined;
}
};
private handleStartInteraction = () => {
if (this.interactionHandle === undefined) {
this.interactionHandle = InteractionManager.createInteractionHandle();
}
};
private getDrawerWidth = (): number => {
const { drawerStyle, dimensions } = this.props;
const { width = DEFAULT_DRAWER_WIDTH } =
StyleSheet.flatten(drawerStyle) || {};
if (typeof width === 'string' && width.endsWith('%')) {
// Try to calculate width if a percentage is given
const percentage = Number(width.replace(/%$/, ''));
if (Number.isFinite(percentage)) {
return dimensions.width * (percentage / 100);
}
}
return typeof width === 'number' ? width : 0;
};
private clock = new Clock();
private interactionHandle: number | undefined;
private isDrawerTypeFront = new Value<Binary>(
this.props.drawerType === 'front' ? TRUE : FALSE
);
private isOpen = new Value<Binary>(this.props.open ? TRUE : FALSE);
private nextIsOpen = new Value<Binary | -1>(UNSET);
private isSwiping = new Value<Binary>(FALSE);
private initialDrawerWidth = this.getDrawerWidth();
private gestureState = new Value<number>(GestureState.UNDETERMINED);
private touchX = new Value<number>(0);
private velocityX = new Value<number>(0);
private gestureX = new Value<number>(0);
private offsetX = new Value<number>(0);
private position = new Value<number>(
this.props.open
? this.initialDrawerWidth *
(this.props.drawerPosition === 'right'
? DIRECTION_RIGHT
: DIRECTION_LEFT)
: 0
);
private containerWidth = new Value<number>(this.props.dimensions.width);
private drawerWidth = new Value<number>(this.initialDrawerWidth);
private drawerOpacity = new Value<number>(
this.props.drawerType === 'permanent' ? 1 : 0
);
private drawerPosition = new Value<number>(
this.props.drawerPosition === 'right' ? DIRECTION_RIGHT : DIRECTION_LEFT
);
// Comment stolen from react-native-gesture-handler/DrawerLayout
//
// While closing the drawer when user starts gesture outside of its area (in greyed
// out part of the window), we want the drawer to follow only once finger reaches the
// edge of the drawer.
// E.g. on the diagram below drawer is illustrate by X signs and the greyed out area by
// dots. The touch gesture starts at '*' and moves left, touch path is indicated by
// an arrow pointing left
// 1) +---------------+ 2) +---------------+ 3) +---------------+ 4) +---------------+
// |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|
// |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|
// |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|
// |XXXXXXXX|......| |XXXXXXXX|.<-*..| |XXXXXXXX|<--*..| |XXXXX|<-----*..|
// |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|
// |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|
// |XXXXXXXX|......| |XXXXXXXX|......| |XXXXXXXX|......| |XXXXX|.........|
// +---------------+ +---------------+ +---------------+ +---------------+
//
// For the above to work properly we define animated value that will keep start position
// of the gesture. Then we use that value to calculate how much we need to subtract from
// the dragX. If the gesture started on the greyed out area we take the distance from the
// edge of the drawer to the start position. Otherwise we don't subtract at all and the
// drawer be pulled back as soon as you start the pan.
//
// This is used only when drawerType is "front"
private touchDistanceFromDrawer = cond(
this.isDrawerTypeFront,
cond(
eq(this.drawerPosition, DIRECTION_LEFT),
max(
// Distance of touch start from left screen edge - Drawer width
sub(sub(this.touchX, this.gestureX), this.drawerWidth),
0
),
min(
multiply(
// Distance of drawer from left screen edge - Touch start point
sub(
sub(this.containerWidth, this.drawerWidth),
sub(this.touchX, this.gestureX)
),
DIRECTION_RIGHT
),
0
)
),
0
);
private swipeDistanceThreshold = new Value<number>(
this.props.swipeDistanceThreshold
);
private swipeVelocityThreshold = new Value<number>(
this.props.swipeVelocityThreshold
);
private currentOpenValue: boolean = this.props.open;
private pendingOpenValue: boolean | undefined;
private isStatusBarHidden: boolean = false;
private manuallyTriggerSpring = new Value<Binary>(FALSE);
private transitionTo = (isOpen: number | Animated.Node<number>) => {
const toValue = new Value(0);
const frameTime = new Value(0);
const state = {
position: this.position,
time: new Value(0),
finished: new Value(FALSE),
velocity: new Value(0),
};
return block([
cond(clockRunning(this.clock), NOOP, [
// Animation wasn't running before
// Set the initial values and start the clock
set(toValue, multiply(isOpen, this.drawerWidth, this.drawerPosition)),
set(frameTime, 0),
set(state.time, 0),
set(state.finished, FALSE),
set(state.velocity, this.velocityX),
set(this.isOpen, isOpen),
startClock(this.clock),
call([], this.handleStartInteraction),
set(this.manuallyTriggerSpring, FALSE),
]),
spring(this.clock, state, { ...SPRING_CONFIG, toValue }),
cond(state.finished, [
// Reset gesture and velocity from previous gesture
set(this.touchX, 0),
set(this.gestureX, 0),
set(this.velocityX, 0),
set(this.offsetX, 0),
// When the animation finishes, stop the clock
stopClock(this.clock),
call([this.isOpen], ([value]: readonly Binary[]) => {
const open = Boolean(value);
this.handleEndInteraction();
if (open !== this.props.open) {
// Sync drawer's state after animation finished
// This shouldn't be necessary, but there seems to be an issue on iOS
this.toggleDrawer(this.props.open);
}
}),
]),
]);
};
private dragX = block([
onChange(
this.isOpen,
call([this.isOpen], ([value]: readonly Binary[]) => {
const open = Boolean(value);
this.currentOpenValue = open;
// Without this check, the drawer can go to an infinite update <-> animate loop for sync updates
if (open !== this.props.open) {
// If the mode changed, update state
if (open) {
this.props.onOpen();
} else {
this.props.onClose();
}
this.pendingOpenValue = open;
// Force componentDidUpdate to fire, whether user does a setState or not
// This allows us to detect when the user drops the update and revert back
// It's necessary to make sure that the state stays in sync
this.forceUpdate();
}
})
),
onChange(
this.nextIsOpen,
cond(neq(this.nextIsOpen, UNSET), [
// Stop any running animations
cond(clockRunning(this.clock), stopClock(this.clock)),
// Update the open value to trigger the transition
set(this.isOpen, this.nextIsOpen),
set(this.gestureX, 0),
set(this.nextIsOpen, UNSET),
])
),
// This block must be after the this.isOpen listener since we check for current value
onChange(
this.isSwiping,
// Listen to updates for this value only when it changes
// Without `onChange`, this will fire even if the value didn't change
// We don't want to call the listeners if the value didn't change
call([this.isSwiping], ([value]: readonly Binary[]) => {
const { keyboardDismissMode } = this.props;
if (value === TRUE) {
if (keyboardDismissMode === 'on-drag') {
Keyboard.dismiss();
}
this.toggleStatusBar(true);
} else {
this.toggleStatusBar(this.currentOpenValue);
}
})
),
onChange(
this.gestureState,
cond(
eq(this.gestureState, GestureState.ACTIVE),
call([], this.handleStartInteraction)
)
),
cond(
eq(this.gestureState, GestureState.ACTIVE),
[
cond(this.isSwiping, NOOP, [
// We weren't dragging before, set it to true
set(this.isSwiping, TRUE),
// Also update the drag offset to the last position
set(this.offsetX, this.position),
]),
// Update position with previous offset + gesture distance
set(
this.position,
add(this.offsetX, this.gestureX, this.touchDistanceFromDrawer)
),
// Stop animations while we're dragging
stopClock(this.clock),
],
[
set(this.isSwiping, FALSE),
set(this.touchX, 0),
this.transitionTo(
cond(
this.manuallyTriggerSpring,
this.isOpen,
cond(
or(
and(
greaterThan(abs(this.gestureX), SWIPE_DISTANCE_MINIMUM),
greaterThan(abs(this.velocityX), this.swipeVelocityThreshold)
),
greaterThan(abs(this.gestureX), this.swipeDistanceThreshold)
),
cond(
eq(this.drawerPosition, DIRECTION_LEFT),
// If swiped to right, open the drawer, otherwise close it
greaterThan(
cond(eq(this.velocityX, 0), this.gestureX, this.velocityX),
0
),
// If swiped to left, open the drawer, otherwise close it
lessThan(
cond(eq(this.velocityX, 0), this.gestureX, this.velocityX),
0
)
),
this.isOpen
)
)
),
]
),
this.position,
]);
private translateX = cond(
eq(this.drawerPosition, DIRECTION_RIGHT),
min(max(multiply(this.drawerWidth, -1), this.dragX), 0),
max(min(this.drawerWidth, this.dragX), 0)
);
private progress = cond(
// Check if the drawer width is available to avoid division by zero
eq(this.drawerWidth, 0),
0,
abs(divide(this.translateX, this.drawerWidth))
);
private handleGestureEvent = event([
{
nativeEvent: {
x: this.touchX,
translationX: this.gestureX,
velocityX: this.velocityX,
},
},
]);
private handleGestureStateChange = event([
{
nativeEvent: {
state: (s: Animated.Value<number>) => set(this.gestureState, s),
},
},
]);
private handleContainerLayout = (e: LayoutChangeEvent) =>
this.containerWidth.setValue(e.nativeEvent.layout.width);
private handleDrawerLayout = (e: LayoutChangeEvent) => {
this.drawerWidth.setValue(e.nativeEvent.layout.width);
this.toggleDrawer(this.props.open);
// Until layout is available, drawer is hidden with opacity: 0 by default
// Show it in the next frame when layout is available
// If we don't delay it until the next frame, there's a visible flicker
requestAnimationFrame(() =>
requestAnimationFrame(() => this.drawerOpacity.setValue(1))
);
};
private toggleDrawer = (open: boolean) => {
if (this.currentOpenValue !== open) {
this.nextIsOpen.setValue(open ? TRUE : FALSE);
// This value will also be set shortly after as changing this.nextIsOpen changes this.isOpen
// However, there's a race condition on Android, so we need to set a bit earlier
this.currentOpenValue = open;
}
};
private toggleStatusBar = (hidden: boolean) => {
const { hideStatusBarOnOpen: hideStatusBar, statusBarAnimation } =
this.props;
if (hideStatusBar && this.isStatusBarHidden !== hidden) {
this.isStatusBarHidden = hidden;
StatusBar.setHidden(hidden, statusBarAnimation);
}
};
render() {
const {
open,
swipeEnabled,
drawerPosition,
drawerType,
swipeEdgeWidth,
drawerStyle,
overlayStyle,
renderDrawerContent,
renderSceneContent,
gestureHandlerProps,
overlayAccessibilityLabel,
} = this.props;
const isOpen = drawerType === 'permanent' ? true : open;
const isRight = drawerPosition === 'right';
const contentTranslateX =
drawerType === 'front' ? ANIMATED_ZERO : this.translateX;
const drawerTranslateX =
drawerType === 'back'
? I18nManager.getConstants().isRTL
? multiply(
sub(this.containerWidth, this.drawerWidth),
isRight ? 1 : -1
)
: ANIMATED_ZERO
: this.translateX;
const offset =
drawerType === 'back'
? 0
: I18nManager.getConstants().isRTL
? '100%'
: multiply(this.drawerWidth, -1);
// FIXME: Currently hitSlop is broken when on Android when drawer is on right
// https://github.com/software-mansion/react-native-gesture-handler/issues/569
const hitSlop = isRight
? // Extend hitSlop to the side of the screen when drawer is closed
// This lets the user drag the drawer from the side of the screen
{ right: 0, width: isOpen ? undefined : swipeEdgeWidth }
: { left: 0, width: isOpen ? undefined : swipeEdgeWidth };
const progress = drawerType === 'permanent' ? ANIMATED_ONE : this.progress;
return (
<DrawerProgressContext.Provider value={progress}>
<PanGestureHandler
activeOffsetX={[-SWIPE_DISTANCE_MINIMUM, SWIPE_DISTANCE_MINIMUM]}
failOffsetY={[-SWIPE_DISTANCE_MINIMUM, SWIPE_DISTANCE_MINIMUM]}
onGestureEvent={this.handleGestureEvent}
onHandlerStateChange={this.handleGestureStateChange}
hitSlop={hitSlop}
enabled={drawerType !== 'permanent' && swipeEnabled}
{...gestureHandlerProps}
>
<Animated.View
onLayout={this.handleContainerLayout}
style={[
styles.main,
{
flexDirection:
drawerType === 'permanent' && !isRight
? 'row-reverse'
: 'row',
},
]}
>
<Animated.View
style={[
styles.content,
{
transform:
drawerType === 'permanent'
? // Reanimated needs the property to be present, but it results in Browser bug
// https://bugs.chromium.org/p/chromium/issues/detail?id=20574
[]
: [{ translateX: contentTranslateX }],
},
]}
>
<View
accessibilityElementsHidden={
isOpen && drawerType !== 'permanent'
}
importantForAccessibility={
isOpen && drawerType !== 'permanent'
? 'no-hide-descendants'
: 'auto'
}
style={styles.content}
>
{renderSceneContent()}
</View>
{
// Disable overlay if sidebar is permanent
drawerType === 'permanent' ? null : (
<Overlay
progress={progress}
onPress={() => this.toggleDrawer(false)}
accessibilityLabel={overlayAccessibilityLabel}
style={overlayStyle as any}
accessibilityElementsHidden={!isOpen}
importantForAccessibility={
isOpen ? 'auto' : 'no-hide-descendants'
}
/>
)
}
</Animated.View>
<Animated.Code
// This is needed to make sure that container width updates with `setValue`
// Without this, it won't update when not used in styles
exec={this.containerWidth}
/>
{drawerType === 'permanent' ? null : (
<Animated.Code
exec={block([
onChange(this.manuallyTriggerSpring, [
cond(eq(this.manuallyTriggerSpring, TRUE), [
set(this.nextIsOpen, FALSE),
call([], () => (this.currentOpenValue = false)),
]),
]),
])}
/>
)}
<Animated.View
removeClippedSubviews={Platform.OS !== 'ios'}
onLayout={this.handleDrawerLayout}
style={[
styles.container,
{
transform:
drawerType === 'permanent'
? // Reanimated needs the property to be present, but it results in Browser bug
// https://bugs.chromium.org/p/chromium/issues/detail?id=20574
[]
: [{ translateX: drawerTranslateX }],
opacity: this.drawerOpacity,
},
drawerType === 'permanent'
? // Without this, the `left`/`right` values don't get reset
isRight
? { right: 0 }
: { left: 0 }
: [
styles.nonPermanent,
isRight ? { right: offset } : { left: offset },
{ zIndex: drawerType === 'back' ? -1 : 0 },
],
drawerStyle as any,
]}
>
{renderDrawerContent()}
</Animated.View>
</Animated.View>
</PanGestureHandler>
</DrawerProgressContext.Provider>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
maxWidth: '100%',
},
nonPermanent: {
position: 'absolute',
top: 0,
bottom: 0,
width: DEFAULT_DRAWER_WIDTH,
},
content: {
flex: 1,
},
main: {
flex: 1,
...Platform.select({
// FIXME: We need to hide `overflowX` on Web so the translated content doesn't show offscreen.
// But adding `overflowX: 'hidden'` prevents content from collapsing the URL bar.
web: null,
default: { overflow: 'hidden' },
}),
},
});