-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathDrawer.js
More file actions
393 lines (362 loc) · 12.4 KB
/
Drawer.js
File metadata and controls
393 lines (362 loc) · 12.4 KB
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
import React, { Component, PropTypes } from 'react';
import {
Animated,
Dimensions,
PanResponder,
Platform,
ScrollView,
StyleSheet,
StatusBar,
Text,
TouchableWithoutFeedback,
View
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
// Get screen dimensions
const { width, height } = Dimensions.get('window');
export default class Drawer extends Component {
// Define prop types
static propTypes = {
// Pass messages to show as children
children: PropTypes.any,
// Whether the window is open or not
isOpen: PropTypes.bool,
// Header that shows up on top the screen when opened
header: PropTypes.string,
// Header height
headerHeight: PropTypes.number,
// Height of the visible teaser area at the bottom of the screen
teaserHeight: PropTypes.number,
};
// Set default prop values
static defaultProps = {
isOpen: false,
header: 'Messages',
headerHeight: 70,
teaserHeight: 75,
};
// Define state
state = {
// Whether it's open or not
open: false,
// Whether the window is being pulled up/down or not
pulling: false,
// Zero means user haven't scrolled the content yet
scrollOffset: 0,
};
// Configure animations
config = {
// Window position
position: {
// maximum possible value - the bottom edge of the screen
max: height,
// starting value - teaserHeight higher than the bottom of the screen
start: height - this.props.teaserHeight,
// end value - headerHeight lower than the top of the screen
end: this.props.headerHeight,
// minimal possible value - a bit lower the top of the screen
min: this.props.headerHeight,
// When animated triggers these value updates
animates: [
() => this._animatedOpacity,
() => this._animatedWidth
]
},
// Window width
width: {
end: width, // takes full with once opened
start: width - 20, // slightly narrower than screen when closed
},
// Window backdrop opacity
opacity: {
start: 0, // fully transparent when closed
end: 1 // not transparent once opened
},
};
// Pan responder to handle gestures
_panResponder = {};
// Animates backdrop opacity
_animatedOpacity = new Animated.Value(this.config.opacity.start);
// Animates window width
_animatedWidth = new Animated.Value(this.config.width.start);
// Animates window position
_animatedPosition = new Animated.Value(this.props.isOpen
? this.config.position.end
: this.config.position.start);
componentWillMount() {
// Set current position
this._currentPosition = this._animatedPosition._value;
// Listen for this._animatedPosition changes
this._animatedPosition.addListener((value) => {
// Update _currentPosition
this._currentPosition = value.value;
// Animate depending values
this.config.position.animates.map(item => {
item().setValue(value.value);
})
});
// Reset value once listener is registered to update depending animations
this._animatedPosition.setValue(this._animatedPosition._value);
// Initialize PanResponder to handle gestures
this._panResponder = PanResponder.create({
onStartShouldSetPanResponder: this._grantPanResponder,
onStartShouldSetPanResponderCapture: this._grantPanResponder,
onMoveShouldSetPanResponder: this._grantPanResponder,
onMoveShouldSetPanResponderCapture: this._grantPanResponder,
onPanResponderGrant: this._handlePanResponderGrant,
onPanResponderMove: this._handlePanResponderMove,
onPanResponderTerminationRequest: (evt, gestureState) => true,
onPanResponderRelease: this._handlePanResponderEnd,
onPanResponderTerminate: this._handlePanResponderEnd,
onShouldBlockNativeResponder: (evt, gestureState) => true,
});
}
// Handle isOpen prop changes to either open or close the window
componentWillReceiveProps(nextProps) {
// isOpen prop changed to true from false
if (!this.props.isOpen && nextProps.isOpen) {
this.open();
}
// isOpen prop changed to false from true
else if (this.props.isOpen && !nextProps.isOpen) {
this.close();
}
}
render() {
const { children, header } = this.props,
// Interpolate position value into opacity value
animatedOpacity = this._animatedOpacity.interpolate({
inputRange: [this.config.position.end, this.config.position.start],
outputRange: [this.config.opacity.end, this.config.opacity.start],
}),
// Interpolate position value into width value
animatedWidth = this._animatedWidth.interpolate({
inputRange: [this.config.position.min,// top of the screen
this.config.position.start - 50, // 50 pixels higher than next point
this.config.position.start, // a bit higher than the bottom of the screen
this.config.position.max // the bottom of the screen
],
outputRange: [this.config.width.end, // keep max width after next point
this.config.width.end, // end: max width at 50 pixel higher
this.config.width.start, // start: min width at the bottom
this.config.width.start // keep min width before previous point
],
});
return (
<Animated.View style={[styles.container, this.getContainerStyle()]}>
{/* Use light status bar because we have dark background */}
<StatusBar barStyle={"light-content"} />
{/* Backdrop with animated opacity */}
<Animated.View style={[styles.backdrop, { opacity: animatedOpacity }]}>
{/* Close window when tapped on header */}
<TouchableWithoutFeedback onPress={this.close}>
<View style={[styles.header, this.getHeaderStyle()]}>
{/* Icon */}
<View style={styles.headerIcon}>
<Icon name="md-arrow-up" size={24} color="white" />
</View>
{/* Header */}
<View style={styles.headerTitle}>
<Text style={styles.headerText}>{header}</Text>
</View>
</View>
</TouchableWithoutFeedback>
</Animated.View>
{/* Content container */}
<Animated.View
style={[styles.content, {
// Add padding at the bottom to fit all content on the screen
paddingBottom: this.props.headerHeight,
// Animate width
width: animatedWidth,
// Animate position on the screen
transform: [{ translateY: this._animatedPosition }, { translateX: 0 }]
}]}
// Handle gestures
{...this._panResponder.panHandlers}
>
{/* Put all content in a scrollable container */}
<ScrollView
ref={(scrollView) => { this._scrollView = scrollView; }}
// Enable scrolling only when the window is open
scrollEnabled={this.state.open}
// Hide all scrolling indicators
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
// Trigger onScroll often
scrollEventThrottle={16}
onScroll={this._handleScroll}
>
{/* Render children components */}
{children}
</ScrollView>
</Animated.View>
</Animated.View>
);
}
// Either allow or deny gesture handler
_grantPanResponder = (evt, gestureState) => {
// Allow if is not open
if (!this.state.open) {
return true;
}
// Allow if user haven't scroll the content yet
else if (this.pulledDown(gestureState) && this.state.scrollOffset <= 0) {
return true;
}
// Allow if pulled down rapidly
else if (this.pulledDown(gestureState) && this.pulledFast(gestureState)) {
return true;
}
// Deny otherwise
return false;
};
// Called when granted
_handlePanResponderGrant = (evt, gestureState) => {
// Update the state so we know we're in the middle of pulling it
this.setState({ pulling: true });
// Set offset and initialize with 0 so we update it
// with relative values from gesture handler
this._animatedPosition.setOffset(this._currentPosition);
this._animatedPosition.setValue(0);
};
// Called when being pulled
_handlePanResponderMove = (evt, gestureState) => {
// Update position unless we go outside of allowed range
if (this.insideAllowedRange()) {
this._animatedPosition.setValue(gestureState.dy);
}
};
// Called when gesture ended
_handlePanResponderEnd = (evt, gestureState) => {
// Reset offset
this._animatedPosition.flattenOffset();
// Reset pulling state
this.setState({ pulling: false });
// Pulled down and far enough to trigger close
if (this.pulledDown(gestureState) && this.pulledFar(gestureState)) {
return this.close();
}
// Pulled up and far enough to trigger open
else if (this.pulledUp(gestureState) && this.pulledFar(gestureState)) {
return this.open();
}
// Toggle if tapped
else if (this.tapped(gestureState)) {
return this.toggle();
}
// Restore back to appropriate position otherwise
else {
this.restore();
}
};
// Handle content scrolling
_handleScroll = event => {
const { y } = event.nativeEvent.contentOffset;
this.setState({ scrollOffset: y });
};
// Check if gesture was a tap
tapped = (gestureState) => gestureState.dx === 0 && gestureState.dy === 0;
// Check if pulled up
pulledUp = (gestureState) => gestureState.dy < 0;
// Check if pulled down
pulledDown = (gestureState) => gestureState.dy > 0;
// Check if pulled rapidly
pulledFast = (gestureState) => Math.abs(gestureState.vy) > 0.75;
// Check if pulled far
pulledFar = (gestureState) => Math.abs(gestureState.dy) > 50;
// Check if current position is inside allowed range
insideAllowedRange = () =>
this._currentPosition >= this.config.position.min
&& this._currentPosition <= this.config.position.max;
// Open up the window on full screen
open = () => {
this.setState({ open: true }, () => {
Animated.timing(this._animatedPosition, {
toValue: this.config.position.end,
duration: 400,
}).start();
});
};
// Minimize window and keep a teaser at the bottom
close = () => {
this._scrollView.scrollTo({ y: 0 });
Animated.timing(this._animatedPosition, {
toValue: this.config.position.start,
duration: 400,
}).start(() => this.setState({
open: false,
}));
};
// Toggle window state between opened and closed
toggle = () => {
if (!this.state.open) {
this.open();
}
else {
this.close();
}
};
// Either open or close depending on the state
restore = () => {
if (this.state.open) {
this.open();
}
else {
this.close();
}
};
// Get header style
getHeaderStyle = () => ({
height: Platform.OS === 'ios'
? this.props.headerHeight
: this.props.headerHeight - 40, // compensate for the status bar
});
// Get container style
getContainerStyle = () => ({
// Move the view below others if not open or moving
// to not block gesture handlers on other views
//zIndex: this.state.pulling || this.state.open ? 1 : -1,
zIndex: 9999999
});
}
const styles = StyleSheet.create({
// Main container
container: {
...StyleSheet.absoluteFillObject, // fill up all screen
alignItems: 'center', // center children
justifyContent: 'flex-end', // align popup at the bottom
backgroundColor: 'transparent', // transparent background
},
// Semi-transparent background below popup
backdrop: {
...StyleSheet.absoluteFillObject, // fill up all screen
alignItems: 'center', // center children
justifyContent: 'flex-start', // align popup at the bottom
backgroundColor: 'black',
},
// Body
content: {
backgroundColor: 'black',
height: height,
},
// Header
header: {
flexDirection: 'row', // arrange children in a row
alignItems: 'center', // center vertically
paddingTop: 20,
paddingHorizontal: 20,
},
headerIcon: {
marginRight: 10,
},
headerTitle: {
flex: 1, // take up all available space
},
headerText: {
color: 'white',
fontFamily: 'Avenir',
fontWeight: '600',
fontSize: 16,
},
});