-
Notifications
You must be signed in to change notification settings - Fork 110
/
index.native.js
227 lines (206 loc) · 7.58 KB
/
index.native.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
const React = require('react')
const { View, PanResponder, Dimensions } = require('react-native')
const { useSpring, animated } = require('@react-spring/native')
const { height, width } = Dimensions.get('window')
const settings = {
maxTilt: 25, // in deg
rotationPower: 50,
swipeThreshold: 1 // need to update this threshold for RN (1.5 seems reasonable...?)
}
// physical properties of the spring
const physics = {
touchResponsive: {
friction: 50,
tension: 2000
},
animateOut: {
friction: 30,
tension: 400
},
animateBack: {
friction: 10,
tension: 200
}
}
const pythagoras = (x, y) => {
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2))
}
const normalize = (vector) => {
const length = Math.sqrt(Math.pow(vector.x, 2) + Math.pow(vector.y, 2))
return { x: vector.x / length, y: vector.y / length }
}
const animateOut = async (gesture, setSpringTarget) => {
const diagonal = pythagoras(height, width)
const velocity = pythagoras(gesture.x, gesture.y)
const finalX = diagonal * gesture.x
const finalY = diagonal * gesture.y
const finalRotation = gesture.x * 45
const duration = diagonal / velocity
setSpringTarget.current[0].start({
x: finalX,
y: finalY,
rot: finalRotation, // set final rotation value based on gesture.vx
config: { duration: duration }
})
// for now animate back
return await new Promise((resolve) =>
setTimeout(() => {
resolve()
}, duration)
)
}
const animateBack = (setSpringTarget) => {
// translate back to the initial position
return new Promise((resolve) => {
setSpringTarget.current[0].start({ x: 0, y: 0, rot: 0, config: physics.animateBack, onRest: resolve })
})
}
const getSwipeDirection = (property) => {
if (Math.abs(property.x) > Math.abs(property.y)) {
if (property.x > settings.swipeThreshold) {
return 'right'
} else if (property.x < -settings.swipeThreshold) {
return 'left'
}
} else {
if (property.y > settings.swipeThreshold) {
return 'down'
} else if (property.y < -settings.swipeThreshold) {
return 'up'
}
}
return 'none'
}
// must be created outside of the TinderCard forwardRef
const AnimatedView = animated(View)
const TinderCard = React.forwardRef(
(
{ flickOnSwipe = true, children, onSwipe, onCardLeftScreen, className, preventSwipe = [], swipeRequirementType = 'velocity', swipeThreshold = settings.swipeThreshold, onSwipeRequirementFulfilled, onSwipeRequirementUnfulfilled },
ref
) => {
const [{ x, y, rot }, setSpringTarget] = useSpring(() => ({
x: 0,
y: 0,
rot: 0,
config: physics.touchResponsive
}))
settings.swipeThreshold = swipeThreshold
React.useImperativeHandle(ref, () => ({
async swipe (dir = 'right') {
if (onSwipe) onSwipe(dir)
const power = 1.3
const disturbance = (Math.random() - 0.5) / 2
if (dir === 'right') {
await animateOut({ x: power, y: disturbance }, setSpringTarget)
} else if (dir === 'left') {
await animateOut({ x: -power, y: disturbance }, setSpringTarget)
} else if (dir === 'up') {
await animateOut({ x: disturbance, y: -power }, setSpringTarget)
} else if (dir === 'down') {
await animateOut({ x: disturbance, y: power }, setSpringTarget)
}
if (onCardLeftScreen) onCardLeftScreen(dir)
},
async restoreCard () {
await animateBack(setSpringTarget)
}
}))
const handleSwipeReleased = React.useCallback(
async (setSpringTarget, gesture) => {
// Check if this is a swipe
const dir = getSwipeDirection({
x: swipeRequirementType === 'velocity' ? gesture.vx : gesture.dx,
y: swipeRequirementType === 'velocity' ? gesture.vy : gesture.dy
})
if (dir !== 'none') {
if (flickOnSwipe) {
if (!preventSwipe.includes(dir)) {
if (onSwipe) onSwipe(dir)
await animateOut(swipeRequirementType === 'velocity' ? ({
x: gesture.vx,
y: gesture.vy
}) : (
normalize({ x: gesture.dx, y: gesture.dy }) // Normalize to avoid flicking the card away with super fast speed only direction is wanted here
), setSpringTarget, swipeRequirementType)
if (onCardLeftScreen) onCardLeftScreen(dir)
return
}
}
}
// Card was not flicked away, animate back to start
animateBack(setSpringTarget)
},
[flickOnSwipe, onSwipe, onCardLeftScreen, preventSwipe]
)
let swipeThresholdFulfilledDirection = 'none'
const panResponder = React.useMemo(
() =>
PanResponder.create({
// Ask to be the responder:
onStartShouldSetPanResponder: (evt, gestureState) => false,
onStartShouldSetPanResponderCapture: (evt, gestureState) => false,
onMoveShouldSetPanResponder: (evt, gestureState) => {
const { dx, dy } = gestureState
return (dx > 2 || dx < -2 || dy > 2 || dy < -2)
},
onMoveShouldSetPanResponderCapture: (evt, gestureState) => {
const { dx, dy } = gestureState
return (dx > 2 || dx < -2 || dy > 2 || dy < -2)
},
onPanResponderGrant: (evt, gestureState) => {
// The gesture has started.
// Probably wont need this anymore as postion i relative to swipe!
setSpringTarget.current[0].start({ x: gestureState.dx, y: gestureState.dy, rot: 0, config: physics.touchResponsive })
},
onPanResponderMove: (evt, gestureState) => {
// Check fulfillment
if (onSwipeRequirementFulfilled || onSwipeRequirementUnfulfilled) {
const dir = getSwipeDirection({
x: swipeRequirementType === 'velocity' ? gestureState.vx : gestureState.dx,
y: swipeRequirementType === 'velocity' ? gestureState.vy : gestureState.dy
})
if (dir !== swipeThresholdFulfilledDirection) {
swipeThresholdFulfilledDirection = dir
if (swipeThresholdFulfilledDirection === 'none') {
if (onSwipeRequirementUnfulfilled) onSwipeRequirementUnfulfilled()
} else {
if (onSwipeRequirementFulfilled) onSwipeRequirementFulfilled(dir)
}
}
}
// use guestureState.vx / guestureState.vy for velocity calculations
// translate element
let rot = ((300 * gestureState.vx) / width) * 15// Magic number 300 different on different devices? Run on physical device!
rot = Math.max(Math.min(rot, settings.maxTilt), -settings.maxTilt)
setSpringTarget.current[0].start({ x: gestureState.dx, y: gestureState.dy, rot, config: physics.touchResponsive })
},
onPanResponderTerminationRequest: (evt, gestureState) => {
return true
},
onPanResponderRelease: (evt, gestureState) => {
// The user has released all touches while this view is the
// responder. This typically means a gesture has succeeded
// enable
handleSwipeReleased(setSpringTarget, gestureState)
}
}),
[]
)
return (
<AnimatedView
{...panResponder.panHandlers}
style={{
transform: [
{ translateX: x },
{ translateY: y },
{ rotate: rot.to((rot) => `${rot}deg`) }
]
}}
className={className}
>
{children}
</AnimatedView>
)
}
)
module.exports = TinderCard