-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathusePanGesture.ts
258 lines (221 loc) · 10 KB
/
usePanGesture.ts
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
/* eslint-disable no-param-reassign */
import {useCallback} from 'react';
import {Dimensions} from 'react-native';
import type {PanGesture} from 'react-native-gesture-handler';
import {Gesture} from 'react-native-gesture-handler';
import {runOnJS, useDerivedValue, useSharedValue, withDecay, withSpring} from 'react-native-reanimated';
import * as Browser from '@libs/Browser';
import {SPRING_CONFIG} from './constants';
import type {MultiGestureCanvasVariables} from './types';
import * as MultiGestureCanvasUtils from './utils';
// This value determines how fast the pan animation should phase out
// We're using a "withDecay" animation to smoothly phase out the pan animation
// https://docs.swmansion.com/react-native-reanimated/docs/animations/withDecay/
const PAN_DECAY_DECELARATION = 0.9915;
const SCREEN_HEIGHT = Dimensions.get('screen').height;
const SNAP_POINT = SCREEN_HEIGHT / 4;
const SNAP_POINT_HIDDEN = SCREEN_HEIGHT / 1.2;
type UsePanGestureProps = Pick<
MultiGestureCanvasVariables,
| 'canvasSize'
| 'contentSize'
| 'zoomScale'
| 'totalScale'
| 'offsetX'
| 'offsetY'
| 'panTranslateX'
| 'panTranslateY'
| 'shouldDisableTransformationGestures'
| 'stopAnimation'
| 'onSwipeDown'
| 'isSwipingDownToClose'
>;
const usePanGesture = ({
canvasSize,
contentSize,
zoomScale,
totalScale,
offsetX,
offsetY,
panTranslateX,
panTranslateY,
shouldDisableTransformationGestures,
stopAnimation,
isSwipingDownToClose,
onSwipeDown,
}: UsePanGestureProps): PanGesture => {
// The content size after fitting it to the canvas and zooming
const zoomedContentWidth = useDerivedValue(() => contentSize.width * totalScale.get(), [contentSize.width]);
const zoomedContentHeight = useDerivedValue(() => contentSize.height * totalScale.get(), [contentSize.height]);
// Used to track previous touch position for the "swipe down to close" gesture
const previousTouch = useSharedValue<{x: number; y: number} | null>(null);
// Velocity of the pan gesture
// We need to keep track of the velocity to properly phase out/decay the pan animation
const panVelocityX = useSharedValue(0);
const panVelocityY = useSharedValue(0);
const isMobileBrowser = Browser.isMobile();
// Disable "swipe down to close" gesture when content is bigger than the canvas
const enableSwipeDownToClose = useDerivedValue(() => canvasSize.height < zoomedContentHeight.get(), [canvasSize.height]);
// Calculates bounds of the scaled content
// Can we pan left/right/up/down
// Can be used to limit gesture or implementing tension effect
const getBounds = useCallback(() => {
'worklet';
let horizontalBoundary = 0;
let verticalBoundary = 0;
if (canvasSize.width < zoomedContentWidth.get()) {
horizontalBoundary = Math.abs(canvasSize.width - zoomedContentWidth.get()) / 2;
}
if (canvasSize.height < zoomedContentHeight.get()) {
verticalBoundary = Math.abs(zoomedContentHeight.get() - canvasSize.height) / 2;
}
const horizontalBoundaries = {min: -horizontalBoundary, max: horizontalBoundary};
const verticalBoundaries = {min: -verticalBoundary, max: verticalBoundary};
const clampedOffset = {
x: MultiGestureCanvasUtils.clamp(offsetX.get(), horizontalBoundaries.min, horizontalBoundaries.max),
y: MultiGestureCanvasUtils.clamp(offsetY.get(), verticalBoundaries.min, verticalBoundaries.max),
};
// If the horizontal/vertical offset is the same after clamping to the min/max boundaries, the content is within the boundaries
const isInHorizontalBoundary = clampedOffset.x === offsetX.get();
const isInVerticalBoundary = clampedOffset.y === offsetY.get();
return {
horizontalBoundaries,
verticalBoundaries,
clampedOffset,
isInHorizontalBoundary,
isInVerticalBoundary,
};
}, [canvasSize.width, canvasSize.height, zoomedContentWidth, zoomedContentHeight, offsetX, offsetY]);
// We want to smoothly decay/end the gesture by phasing out the pan animation
// In case the content is outside of the boundaries of the canvas,
// we need to move the content back into the boundaries
const finishPanGesture = useCallback(() => {
'worklet';
// If the content is centered within the canvas, we don't need to run any animations
if (offsetX.get() === 0 && offsetY.get() === 0 && panTranslateX.get() === 0 && panTranslateY.get() === 0) {
return;
}
const {clampedOffset, isInHorizontalBoundary, isInVerticalBoundary, horizontalBoundaries, verticalBoundaries} = getBounds();
// If the content is within the horizontal/vertical boundaries of the canvas, we can smoothly phase out the animation
// If not, we need to snap back to the boundaries
if (isInHorizontalBoundary) {
// If the (absolute) velocity is 0, we don't need to run an animation
if (Math.abs(panVelocityX.get()) !== 0) {
// Phase out the pan animation
// eslint-disable-next-line react-compiler/react-compiler
offsetX.set(
withDecay({
velocity: panVelocityX.get(),
clamp: [horizontalBoundaries.min, horizontalBoundaries.max],
deceleration: PAN_DECAY_DECELARATION,
rubberBandEffect: false,
}),
);
}
} else {
// Animated back to the boundary
offsetX.set(withSpring(clampedOffset.x, SPRING_CONFIG));
}
if (isInVerticalBoundary) {
// If the (absolute) velocity is 0, we don't need to run an animation
if (Math.abs(panVelocityY.get()) !== 0) {
// Phase out the pan animation
offsetY.set(
withDecay({
velocity: panVelocityY.get(),
clamp: [verticalBoundaries.min, verticalBoundaries.max],
deceleration: PAN_DECAY_DECELARATION,
}),
);
}
} else {
const finalTranslateY = offsetY.get() + panVelocityY.get() * 0.2;
if (finalTranslateY > SNAP_POINT && zoomScale.get() <= 1) {
offsetY.set(
withSpring(SNAP_POINT_HIDDEN, SPRING_CONFIG, () => {
isSwipingDownToClose.set(false);
if (onSwipeDown) {
runOnJS(onSwipeDown)();
}
}),
);
} else {
// Animated back to the boundary
offsetY.set(
withSpring(clampedOffset.y, SPRING_CONFIG, () => {
isSwipingDownToClose.set(false);
}),
);
}
}
// Reset velocity variables after we finished the pan gesture
panVelocityX.set(0);
panVelocityY.set(0);
}, [getBounds, isSwipingDownToClose, offsetX, offsetY, onSwipeDown, panTranslateX, panTranslateY, panVelocityX, panVelocityY, zoomScale]);
const panGesture = Gesture.Pan()
.manualActivation(true)
.averageTouches(true)
.onTouchesUp(() => {
previousTouch.set(null);
})
.onTouchesMove((evt, state) => {
// We only allow panning when the content is zoomed in
if (zoomScale.get() > 1 && !shouldDisableTransformationGestures.get()) {
state.activate();
}
// TODO: this needs tuning to work properly
const previousTouchValue = previousTouch.get();
if (!shouldDisableTransformationGestures.get() && zoomScale.get() === 1 && previousTouchValue !== null) {
const velocityX = Math.abs((evt.allTouches.at(0)?.x ?? 0) - previousTouchValue.x);
const velocityY = (evt.allTouches.at(0)?.y ?? 0) - previousTouchValue.y;
if (Math.abs(velocityY) > velocityX && velocityY > 20) {
state.activate();
isSwipingDownToClose.set(true);
previousTouch.set(null);
return;
}
}
if (previousTouch.get() === null) {
previousTouch.set({
x: evt.allTouches.at(0)?.x ?? 0,
y: evt.allTouches.at(0)?.y ?? 0,
});
}
})
.onStart(() => {
stopAnimation();
})
.onChange((evt) => {
// Since we're running both pinch and pan gesture handlers simultaneously,
// we need to make sure that we don't pan when we pinch since we track it as pinch focal gesture.
if (evt.numberOfPointers > 1) {
return;
}
panVelocityX.set(evt.velocityX);
panVelocityY.set(evt.velocityY);
if (!isSwipingDownToClose.get()) {
if (!isMobileBrowser || (isMobileBrowser && zoomScale.get() !== 1)) {
panTranslateX.set((value) => value + evt.changeX);
}
}
if (enableSwipeDownToClose.get() || isSwipingDownToClose.get()) {
panTranslateY.set((value) => value + evt.changeY);
}
})
.onEnd(() => {
// Add pan translation to total offset and reset gesture variables
offsetX.set((value) => value + panTranslateX.get());
offsetY.set((value) => value + panTranslateY.get());
// Reset pan gesture variables
panTranslateX.set(0);
panTranslateY.set(0);
previousTouch.set(null);
// If we are swiping (in the pager), we don't want to return to boundaries
if (shouldDisableTransformationGestures.get()) {
return;
}
finishPanGesture();
});
return panGesture;
};
export default usePanGesture;