-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSwipeCard.ts
More file actions
77 lines (68 loc) · 2.06 KB
/
useSwipeCard.ts
File metadata and controls
77 lines (68 loc) · 2.06 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
import {
interpolate,
useAnimatedStyle,
useSharedValue,
withTiming,
} from 'react-native-reanimated';
import {Gesture} from 'react-native-gesture-handler';
import {snapPoint} from 'react-native-redash';
import {
CARD_OPACITY_OUTPUT,
CARD_ROTATION_DEG,
CARD_ROTATION_OUTPUT,
CARD_SNAP_POINTS,
CARD_START_X_POSITION,
CARD_START_Y_POSITION,
} from '~config/cards';
function useSwipeCard() {
const translateX = useSharedValue(CARD_START_X_POSITION);
const translateY = useSharedValue(CARD_START_Y_POSITION);
const rotateZ = useSharedValue((Math.random() - 0.5) * CARD_ROTATION_DEG);
const opacity = useSharedValue(1);
const context = useSharedValue({x: 0, y: 0});
const gesture = Gesture.Pan()
.onStart(() => {
context.value = {x: translateX.value, y: translateY.value};
})
.onUpdate(event => {
const {translationX, translationY} = event;
const nextX = translationX + context.value.x;
const nextY = translationY + context.value.y;
translateX.value = nextX;
translateY.value = nextY;
rotateZ.value = interpolate(
translationX,
CARD_SNAP_POINTS,
CARD_ROTATION_OUTPUT,
);
opacity.value = interpolate(
translationX,
CARD_SNAP_POINTS,
CARD_OPACITY_OUTPUT,
);
})
.onEnd(event => {
const {translationX, velocityX} = event;
const nextX = translationX + context.value.x;
const snap = snapPoint(nextX, velocityX, CARD_SNAP_POINTS);
const isSwipeLeft = snap < 0;
const isSwipeRight = snap > 0;
if (isSwipeLeft || isSwipeRight) {
translateX.value = withTiming(snap);
} else {
translateX.value = withTiming(CARD_START_X_POSITION);
rotateZ.value = withTiming(0);
opacity.value = withTiming(1);
}
});
const style = useAnimatedStyle(() => ({
opacity: opacity.value,
transform: [
{translateX: translateX.value},
{translateY: translateY.value},
{rotateZ: `${rotateZ.value}deg`},
],
}));
return {gesture, style};
}
export default useSwipeCard;