-
Notifications
You must be signed in to change notification settings - Fork 23
/
Swipe.js
89 lines (76 loc) · 2.09 KB
/
Swipe.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
import React, { Component, PropTypes } from 'react';
import {
Easing,
StyleSheet,
Text,
View,
Animated,
PanResponder
} from 'react-native';
const swipeDirections = {
SWIPE_LEFT: 'SWIPE_LEFT',
SWIPE_RIGHT: 'SWIPE_RIGHT'
};
function isValidSwipe(velocity, velocityThreshold, directionalOffset, directionalOffsetThreshold) {
return Math.abs(velocity) >= velocityThreshold &&
Math.abs(directionalOffset) < directionalOffsetThreshold;
}
class Swipe extends Component {
constructor(props) {
super(props);
this.swipeConfig = {
velocityThreshold: 0.3,
directionalOffsetThreshold: 80
};
}
componentWillMount() {
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderRelease: (evt, gestureState) => {
const swipeDirection = this._getSwipeDirection(gestureState);
this._triggerSwipeHandlers(swipeDirection, gestureState);
}
});
}
_triggerSwipeHandlers(swipeDirection, gestureState) {
const {SWIPE_LEFT, SWIPE_RIGHT} = swipeDirections;
switch (swipeDirection) {
case SWIPE_LEFT:
this.props.onSwipeLeft(gestureState);
break;
case SWIPE_RIGHT:
this.props.onSwipeRight(gestureState);
break;
}
}
_getSwipeDirection(gestureState) {
const {SWIPE_LEFT, SWIPE_RIGHT} = swipeDirections;
const {dx, dy} = gestureState;
if (this._isValidHorizontalSwipe(gestureState)) {
return (dx > 0) ? SWIPE_RIGHT : SWIPE_LEFT;
}
}
_isValidHorizontalSwipe(gestureState) {
const {vx, dy} = gestureState;
const {velocityThreshold, directionalOffsetThreshold} = this.swipeConfig;
return isValidSwipe(vx, velocityThreshold, dy, directionalOffsetThreshold);
}
render() {
return (
<Animated.View style={this.props.style}
{...this.panResponder.panHandlers}
>
{this.props.children}
</Animated.View>
);
}
}
Swipe.propTypes = {
onSwipeLeft: PropTypes.func,
onSwipeRight: PropTypes.func,
}
Swipe.defaultProps = {
onSwipeLeft: () => {},
onSwipeRight: () => {}
}
export default Swipe;