@cometchat/chat-uikit-react-native 4.3.1 → 4.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/android/src/main/AndroidManifest.xml +3 -4
  2. package/android/src/main/java/com/reactnativecometchatuikit/CometchatUiKitPackage.java +0 -1
  3. package/android/src/main/java/com/reactnativecometchatuikit/FileManager.java +125 -7
  4. package/android/src/main/java/com/reactnativecometchatuikit/ImageManager.java +1 -1
  5. package/package.json +1 -1
  6. package/src/CometChatConversations/CometChatConversations.tsx +51 -28
  7. package/src/CometChatConversations/style.ts +5 -1
  8. package/src/CometChatMessageComposer/CometChatMessageComposer.tsx +53 -20
  9. package/src/CometChatMessageList/CometChatMessageList.tsx +15 -15
  10. package/src/CometChatMessageList/MessageListConfiguration.ts +5 -5
  11. package/src/CometChatThreadedMessages/CometChatThreadedMessages.tsx +35 -2
  12. package/src/extensions/LinkPreview/LinkPreviewBubble.tsx +51 -15
  13. package/src/index.ts +8 -8
  14. package/src/shared/CometChatContext.tsx +5 -1
  15. package/src/shared/CometChatUiKit/CometChatUIKit.ts +1 -4
  16. package/src/shared/index.ts +8 -8
  17. package/src/shared/libs/ImageZoom/ReactNativeZoomableView.tsx +1040 -0
  18. package/src/shared/libs/ImageZoom/ReactNativeZoomableViewWithGestures.tsx +223 -0
  19. package/src/shared/libs/ImageZoom/helper.ts +144 -0
  20. package/src/shared/libs/ImageZoom/index.tsx +13 -0
  21. package/src/shared/libs/ImageZoom/types/index.ts +186 -0
  22. package/src/shared/libs/VideoPlayer/Video.js +0 -24
  23. package/src/shared/libs/VideoPlayerControls/assets/img/back.png +0 -0
  24. package/src/shared/libs/VideoPlayerControls/components/Back/Back.tsx +1 -1
  25. package/src/shared/resources/CometChatLocalize/CometChatLocalize.ts +1 -1
  26. package/src/shared/utils/NetworkUtils.tsx +5 -0
  27. package/src/shared/views/CometChatActionSheet/CometChatActionSheet.tsx +1 -0
  28. package/src/shared/views/CometChatDate/CometChatDate.tsx +1 -1
  29. package/src/shared/views/CometChatImageBubble/CometChatImageBubble.tsx +64 -18
  30. package/src/shared/views/CometChatImageBubble/assets/index.ts +5 -0
  31. package/src/shared/views/CometChatImageBubble/assets/spineer.png +0 -0
  32. package/src/shared/views/CometChatImageViewerModal/ImageViewerModal.tsx +106 -0
  33. package/src/shared/views/CometChatImageViewerModal/index.tsx +1 -0
  34. package/src/shared/views/CometChatImageViewerModal/resources/Back.png +0 -0
  35. package/src/shared/views/CometChatImageViewerModal/resources/index.ts +5 -0
  36. package/src/shared/views/CometChatList/CometChatList.tsx +10 -1
  37. package/src/shared/views/{CometChatReactionsList/CometChatReactionsList.tsx → CometChatReactionList/CometChatReactionList.tsx} +17 -17
  38. package/src/shared/views/CometChatReactionList/ReactionListConfiguration.tsx +14 -0
  39. package/src/shared/views/CometChatReactionList/index.ts +12 -0
  40. package/src/shared/views/CometChatVideoBubble/CometChatVideoBubble.tsx +1 -1
  41. package/src/shared/views/index.ts +5 -5
  42. package/android/src/main/java/com/reactnativecometchatuikit/VideoManager.java +0 -40
  43. package/src/shared/libs/VideoPlayerControls/assets/img/back@2x.png +0 -0
  44. package/src/shared/libs/VideoPlayerControls/assets/img/back@3x.png +0 -0
  45. package/src/shared/views/CometChatReactionsList/ReactionsListConfiguration.tsx +0 -14
  46. package/src/shared/views/CometChatReactionsList/index.ts +0 -12
  47. /package/src/shared/views/{CometChatReactionsList/ReactionsListStyle.tsx → CometChatReactionList/ReactionListStyle.tsx} +0 -0
  48. /package/src/shared/views/{CometChatReactionsList → CometChatReactionList}/resources/Spineer.png +0 -0
  49. /package/src/shared/views/{CometChatReactionsList → CometChatReactionList}/resources/index.ts +0 -0
@@ -0,0 +1,1040 @@
1
+ import React, { Component, createRef, RefObject } from 'react';
2
+ import {
3
+ Animated,
4
+ Easing,
5
+ GestureResponderEvent,
6
+ InteractionManager,
7
+ PanResponder,
8
+ PanResponderGestureState,
9
+ StyleSheet,
10
+ View,
11
+ } from 'react-native';
12
+
13
+ import {
14
+ Vec2D,
15
+ ReactNativeZoomableViewProps,
16
+ ReactNativeZoomableViewState,
17
+ TouchPoint,
18
+ ZoomableViewEvent,
19
+ } from './types';
20
+ import { applyPanBoundariesToOffset, calcGestureTouchDistance, calcNewScaledOffsetForZoomCentering, getBoundaryCrossedAnim, getPanMomentumDecayAnim, getZoomToAnimation } from './helper';
21
+
22
+
23
+ const initialState = {
24
+ originalWidth: null,
25
+ originalHeight: null,
26
+ originalPageX: null,
27
+ originalPageY: null,
28
+ } as ReactNativeZoomableViewState;
29
+ function calcGestureCenterPoint(
30
+ e: GestureResponderEvent,
31
+ gestureState: PanResponderGestureState
32
+ ): Vec2D | null {
33
+ const touches = e?.nativeEvent?.touches;
34
+ if (!touches[0]) return null;
35
+
36
+ if (gestureState.numberActiveTouches === 2) {
37
+ if (!touches[1]) return null;
38
+ return {
39
+ x: (touches[0].pageX + touches[1].pageX) / 2,
40
+ y: (touches[0].pageY + touches[1].pageY) / 2,
41
+ };
42
+ }
43
+ if (gestureState.numberActiveTouches === 1) {
44
+ return {
45
+ x: touches[0].pageX,
46
+ y: touches[0].pageY,
47
+ };
48
+ }
49
+
50
+ return null;
51
+ }
52
+
53
+ class ReactNativeZoomableView extends Component<
54
+ ReactNativeZoomableViewProps,
55
+ ReactNativeZoomableViewState
56
+ > {
57
+ zoomSubjectWrapperRef: RefObject<View>;
58
+ gestureHandlers: any;
59
+ doubleTapFirstTapReleaseTimestamp: number;
60
+
61
+ static defaultProps = {
62
+ zoomEnabled: true,
63
+ panEnabled: true,
64
+ initialZoom: 1,
65
+ initialOffsetX: 0,
66
+ initialOffsetY: 0,
67
+ maxZoom: 3.5,
68
+ minZoom: 1,
69
+ pinchToZoomInSensitivity: 1,
70
+ pinchToZoomOutSensitivity: 1,
71
+ movementSensibility: 1,
72
+ doubleTapDelay: 300,
73
+ bindToBorders: true,
74
+ zoomStep: 0.5,
75
+ onLongPress: null,
76
+ longPressDuration: 700,
77
+ contentWidth: undefined,
78
+ contentHeight: undefined,
79
+ panBoundaryPadding: 0,
80
+ disablePanOnInitialZoom: false,
81
+ };
82
+
83
+ private panAnim = new Animated.ValueXY({ x: 0, y: 0 });
84
+ private zoomAnim = new Animated.Value(1);
85
+
86
+ private __offsets = {
87
+ x: {
88
+ value: 0,
89
+ boundaryCrossedAnimInEffect: false,
90
+ },
91
+ y: {
92
+ value: 0,
93
+ boundaryCrossedAnimInEffect: false,
94
+ },
95
+ };
96
+
97
+ private zoomLevel = 1;
98
+ private lastGestureCenterPosition: { x: number; y: number } = null;
99
+ private lastGestureTouchDistance: number;
100
+ private gestureType: 'pinch' | 'shift' | 'null';
101
+ private gestureStarted = false;
102
+
103
+ /**
104
+ * Last press time (used to evaluate whether user double tapped)
105
+ * @type {number}
106
+ */
107
+ private longPressTimeout: NodeJS.Timeout = null;
108
+ private onTransformInvocationInitialized: boolean;
109
+ private singleTapTimeoutId: NodeJS.Timeout;
110
+ private touches: TouchPoint[] = [];
111
+ private doubleTapFirstTap: TouchPoint;
112
+ private measureZoomSubjectInterval: NodeJS.Timer;
113
+
114
+ constructor(props) {
115
+ super(props);
116
+
117
+ this.gestureHandlers = PanResponder.create({
118
+ onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder,
119
+ onPanResponderGrant: this._handlePanResponderGrant,
120
+ onPanResponderMove: this._handlePanResponderMove,
121
+ onPanResponderRelease: this._handlePanResponderEnd,
122
+ onPanResponderTerminate: (evt, gestureState) => {
123
+ // We should also call _handlePanResponderEnd
124
+ // to properly perform cleanups when the gesture is terminated
125
+ // (aka gesture handling responsibility is taken over by another component).
126
+ // This also fixes a weird issue where
127
+ // on real device, sometimes onPanResponderRelease is not called when you lift 2 fingers up,
128
+ // but onPanResponderTerminate is called instead for no apparent reason.
129
+ this._handlePanResponderEnd(evt, gestureState);
130
+ this.props.onPanResponderTerminate?.(
131
+ evt,
132
+ gestureState,
133
+ this._getZoomableViewEventObject()
134
+ );
135
+ },
136
+ onPanResponderTerminationRequest: (evt, gestureState) =>
137
+ !!this.props.onPanResponderTerminationRequest?.(
138
+ evt,
139
+ gestureState,
140
+ this._getZoomableViewEventObject()
141
+ ),
142
+ // Defaults to true to prevent parent components, such as React Navigation's tab view, from taking over as responder.
143
+ onShouldBlockNativeResponder: (evt, gestureState) =>
144
+ this.props.onShouldBlockNativeResponder?.(
145
+ evt,
146
+ gestureState,
147
+ this._getZoomableViewEventObject()
148
+ ) ?? true,
149
+ onStartShouldSetPanResponderCapture: (evt, gestureState) =>
150
+ this.props.onStartShouldSetPanResponderCapture?.(evt, gestureState),
151
+ onMoveShouldSetPanResponderCapture: (evt, gestureState) =>
152
+ this.props.onMoveShouldSetPanResponderCapture?.(evt, gestureState),
153
+ });
154
+
155
+ this.zoomSubjectWrapperRef = createRef<View>();
156
+
157
+ if (this.props.zoomAnimatedValue)
158
+ this.zoomAnim = this.props.zoomAnimatedValue;
159
+ if (this.props.panAnimatedValueXY)
160
+ this.panAnim = this.props.panAnimatedValueXY;
161
+
162
+ this.zoomLevel = props.initialZoom;
163
+ this.offsetX = props.initialOffsetX;
164
+ this.offsetY = props.initialOffsetY;
165
+
166
+ this.panAnim.setValue({ x: this.offsetX, y: this.offsetY });
167
+ this.zoomAnim.setValue(this.zoomLevel);
168
+ this.panAnim.addListener(({ x, y }) => {
169
+ this.offsetX = x;
170
+ this.offsetY = y;
171
+ });
172
+ this.zoomAnim.addListener(({ value }) => {
173
+ this.zoomLevel = value;
174
+ });
175
+
176
+ this.state = {
177
+ ...initialState,
178
+ };
179
+
180
+ this.lastGestureTouchDistance = 150;
181
+
182
+ this.gestureType = null;
183
+ }
184
+
185
+ private set offsetX(x: number) {
186
+ this.__setOffset('x', x);
187
+ }
188
+ private set offsetY(y: number) {
189
+ this.__setOffset('y', y);
190
+ }
191
+ private get offsetX() {
192
+ return this.__getOffset('x');
193
+ }
194
+ private get offsetY() {
195
+ return this.__getOffset('y');
196
+ }
197
+ private __setOffset(axis: 'x' | 'y', offset) {
198
+ const offsetState = this.__offsets[axis];
199
+ const animValue = this.panAnim?.[axis];
200
+
201
+ if (this.props.bindToBorders) {
202
+ const containerSize =
203
+ axis === 'x' ? this.state?.originalWidth : this.state?.originalHeight;
204
+ const contentSize =
205
+ axis === 'x'
206
+ ? this.props.contentWidth || this.state?.originalWidth
207
+ : this.props.contentHeight || this.state?.originalHeight;
208
+
209
+ const boundOffset =
210
+ contentSize && containerSize
211
+ ? applyPanBoundariesToOffset(
212
+ offset,
213
+ containerSize,
214
+ contentSize,
215
+ this.zoomLevel,
216
+ this.props.panBoundaryPadding
217
+ )
218
+ : offset;
219
+
220
+ if (
221
+ animValue &&
222
+ !this.gestureType &&
223
+ !offsetState.boundaryCrossedAnimInEffect
224
+ ) {
225
+ const boundariesApplied =
226
+ boundOffset !== offset &&
227
+ boundOffset.toFixed(3) !== offset.toFixed(3);
228
+ if (boundariesApplied) {
229
+ offsetState.boundaryCrossedAnimInEffect = true;
230
+ getBoundaryCrossedAnim(this.panAnim[axis], boundOffset).start(() => {
231
+ offsetState.boundaryCrossedAnimInEffect = false;
232
+ });
233
+ return;
234
+ }
235
+ }
236
+ }
237
+
238
+ offsetState.value = offset;
239
+ }
240
+ private __getOffset(axis: 'x' | 'y') {
241
+ return this.__offsets[axis].value;
242
+ }
243
+
244
+ componentDidUpdate(
245
+ prevProps: ReactNativeZoomableViewProps,
246
+ prevState: ReactNativeZoomableViewState
247
+ ) {
248
+ const { zoomEnabled, initialZoom } = this.props;
249
+ if (prevProps.zoomEnabled && !zoomEnabled) {
250
+ this.zoomLevel = initialZoom;
251
+ this.zoomAnim.setValue(this.zoomLevel);
252
+ }
253
+ if (
254
+ !this.onTransformInvocationInitialized &&
255
+ this._invokeOnTransform().successful
256
+ ) {
257
+ this.panAnim.addListener(() => this._invokeOnTransform());
258
+ this.zoomAnim.addListener(() => this._invokeOnTransform());
259
+ this.onTransformInvocationInitialized = true;
260
+ }
261
+
262
+ const currState = this.state;
263
+ const originalMeasurementsChanged =
264
+ currState.originalHeight !== prevState.originalHeight ||
265
+ currState.originalWidth !== prevState.originalWidth ||
266
+ currState.originalPageX !== prevState.originalPageX ||
267
+ currState.originalPageY !== prevState.originalPageY;
268
+
269
+ if (this.onTransformInvocationInitialized && originalMeasurementsChanged) {
270
+ this._invokeOnTransform();
271
+ }
272
+ }
273
+
274
+ componentDidMount() {
275
+ this.grabZoomSubjectOriginalMeasurements();
276
+ // We've already run `grabZoomSubjectOriginalMeasurements` at various events
277
+ // to make sure the measurements are promptly updated.
278
+ // However, there might be cases we haven't accounted for, especially when
279
+ // native processes are involved. To account for those cases,
280
+ // we'll use an interval here to ensure we're always up-to-date.
281
+ // The `setState` in `grabZoomSubjectOriginalMeasurements` won't trigger a rerender
282
+ // if the values given haven't changed, so we're not running performance risk here.
283
+ this.measureZoomSubjectInterval = setInterval(
284
+ this.grabZoomSubjectOriginalMeasurements,
285
+ 1e3
286
+ );
287
+ }
288
+
289
+ componentWillUnmount() {
290
+ clearInterval(this.measureZoomSubjectInterval);
291
+ }
292
+
293
+ /**
294
+ * try to invoke onTransform
295
+ * @private
296
+ */
297
+ _invokeOnTransform() {
298
+ const zoomableViewEvent = this._getZoomableViewEventObject();
299
+
300
+ if (!zoomableViewEvent.originalWidth || !zoomableViewEvent.originalHeight)
301
+ return { successful: false };
302
+
303
+ this.props.onTransform?.(zoomableViewEvent);
304
+
305
+ return { successful: true };
306
+ }
307
+
308
+ /**
309
+ * Returns additional information about components current state for external event hooks
310
+ *
311
+ * @returns {{}}
312
+ * @private
313
+ */
314
+ _getZoomableViewEventObject(overwriteObj = {}): ZoomableViewEvent {
315
+ return {
316
+ zoomLevel: this.zoomLevel,
317
+ offsetX: this.offsetX,
318
+ offsetY: this.offsetY,
319
+ originalHeight: this.state.originalHeight,
320
+ originalWidth: this.state.originalWidth,
321
+ originalPageX: this.state.originalPageX,
322
+ originalPageY: this.state.originalPageY,
323
+ ...overwriteObj,
324
+ } as ZoomableViewEvent;
325
+ }
326
+
327
+ /**
328
+ * Get the original box dimensions and save them for later use.
329
+ * (They will be used to calculate boxBorders)
330
+ *
331
+ * @private
332
+ */
333
+ private grabZoomSubjectOriginalMeasurements = () => {
334
+ // make sure we measure after animations are complete
335
+ InteractionManager.runAfterInteractions(() => {
336
+ // this setTimeout is here to fix a weird issue on iOS where the measurements are all `0`
337
+ // when navigating back (react-navigation stack) from another view
338
+ // while closing the keyboard at the same time
339
+ setTimeout(() => {
340
+ // In normal conditions, we're supposed to measure zoomSubject instead of its wrapper.
341
+ // However, our zoomSubject may have been transformed by an initial zoomLevel or offset,
342
+ // in which case these measurements will not represent the true "original" measurements.
343
+ // We just need to make sure the zoomSubjectWrapper perfectly aligns with the zoomSubject
344
+ // (no border, space, or anything between them)
345
+ const zoomSubjectWrapperRef = this.zoomSubjectWrapperRef;
346
+ // we don't wanna measure when zoomSubjectWrapperRef is not yet available or has been unmounted
347
+ zoomSubjectWrapperRef.current?.measureInWindow(
348
+ (x, y, width, height) => {
349
+ this.setState({
350
+ originalWidth: width,
351
+ originalHeight: height,
352
+ originalPageX: x,
353
+ originalPageY: y,
354
+ });
355
+ }
356
+ );
357
+ });
358
+ });
359
+ };
360
+
361
+ /**
362
+ * Handles the start of touch events and checks for taps
363
+ *
364
+ * @param e
365
+ * @param gestureState
366
+ * @returns {boolean}
367
+ *
368
+ * @private
369
+ */
370
+ _handleStartShouldSetPanResponder = (
371
+ e: GestureResponderEvent,
372
+ gestureState: PanResponderGestureState
373
+ ) => {
374
+ if (this.props.onStartShouldSetPanResponder) {
375
+ this.props.onStartShouldSetPanResponder(
376
+ e,
377
+ gestureState,
378
+ this._getZoomableViewEventObject(),
379
+ false
380
+ );
381
+ }
382
+
383
+ // Always set pan responder on start
384
+ // of gesture so we can handle tap.
385
+ // "Pan threshold validation" will be handled
386
+ // in `onPanResponderMove` instead of in `onMoveShouldSetPanResponder`
387
+ return true;
388
+ };
389
+
390
+ /**
391
+ * Calculates pinch distance
392
+ *
393
+ * @param e
394
+ * @param gestureState
395
+ * @private
396
+ */
397
+ _handlePanResponderGrant = (e, gestureState) => {
398
+ if (this.props.onLongPress) {
399
+ this.longPressTimeout = setTimeout(() => {
400
+ this.props.onLongPress?.(
401
+ e,
402
+ gestureState,
403
+ this._getZoomableViewEventObject()
404
+ );
405
+ this.longPressTimeout = null;
406
+ }, this.props.longPressDuration);
407
+ }
408
+
409
+ this.props.onPanResponderGrant?.(
410
+ e,
411
+ gestureState,
412
+ this._getZoomableViewEventObject()
413
+ );
414
+
415
+ this.panAnim.stopAnimation();
416
+ this.zoomAnim.stopAnimation();
417
+ this.gestureStarted = true;
418
+ };
419
+
420
+ /**
421
+ * Handles the end of touch events
422
+ *
423
+ * @param e
424
+ * @param gestureState
425
+ *
426
+ * @private
427
+ */
428
+ _handlePanResponderEnd = (e, gestureState) => {
429
+ if (!this.gestureType) {
430
+ this._resolveAndHandleTap(e);
431
+ }
432
+
433
+
434
+ this.lastGestureCenterPosition = null;
435
+
436
+ // Trigger final shift animation unless panEnabled is false or disablePanOnInitialZoom is true and we're on the initial zoom level
437
+ if (
438
+ this.props.panEnabled &&
439
+ !(
440
+ this.gestureType === 'shift' &&
441
+ this.props.disablePanOnInitialZoom &&
442
+ this.zoomLevel === this.props.initialZoom
443
+ )
444
+ ) {
445
+ getPanMomentumDecayAnim(this.panAnim, {
446
+ x: gestureState.vx / this.zoomLevel,
447
+ y: gestureState.vy / this.zoomLevel,
448
+ }).start();
449
+ }
450
+
451
+ if (this.longPressTimeout) {
452
+ clearTimeout(this.longPressTimeout);
453
+ this.longPressTimeout = null;
454
+ }
455
+
456
+ this.props.onPanResponderEnd?.(
457
+ e,
458
+ gestureState,
459
+ this._getZoomableViewEventObject()
460
+ );
461
+
462
+ if (this.gestureType === 'pinch') {
463
+ this.props.onZoomEnd?.(
464
+ e,
465
+ gestureState,
466
+ this._getZoomableViewEventObject()
467
+ );
468
+ } else if (this.gestureType === 'shift') {
469
+ this.props.onShiftingEnd?.(
470
+ e,
471
+ gestureState,
472
+ this._getZoomableViewEventObject()
473
+ );
474
+ }
475
+
476
+ this.gestureType = null;
477
+ this.gestureStarted = false;
478
+ };
479
+
480
+ /**
481
+ * Handles the actual movement of our pan responder
482
+ *
483
+ * @param e
484
+ * @param gestureState
485
+ *
486
+ * @private
487
+ */
488
+ _handlePanResponderMove = (
489
+ e: GestureResponderEvent,
490
+ gestureState: PanResponderGestureState
491
+ ) => {
492
+ if (this.props.onPanResponderMove) {
493
+ if (
494
+ this.props.onPanResponderMove(
495
+ e,
496
+ gestureState,
497
+ this._getZoomableViewEventObject()
498
+ )
499
+ ) {
500
+ return false;
501
+ }
502
+ }
503
+
504
+ // Only supports 2 touches and below,
505
+ // any invalid number will cause the gesture to end.
506
+ if (gestureState.numberActiveTouches <= 2) {
507
+ if (!this.gestureStarted) {
508
+ this._handlePanResponderGrant(e, gestureState);
509
+ }
510
+ } else {
511
+ if (this.gestureStarted) {
512
+ this._handlePanResponderEnd(e, gestureState);
513
+ }
514
+ return true;
515
+ }
516
+
517
+ if (gestureState.numberActiveTouches === 2) {
518
+ if (this.longPressTimeout) {
519
+ clearTimeout(this.longPressTimeout);
520
+ this.longPressTimeout = null;
521
+ }
522
+
523
+ // change some measurement states when switching gesture to ensure a smooth transition
524
+ if (this.gestureType !== 'pinch') {
525
+ this.lastGestureCenterPosition = calcGestureCenterPoint(
526
+ e,
527
+ gestureState
528
+ );
529
+ this.lastGestureTouchDistance = calcGestureTouchDistance(
530
+ e,
531
+ gestureState
532
+ );
533
+ }
534
+ this.gestureType = 'pinch';
535
+ this._handlePinching(e, gestureState);
536
+ } else if (gestureState.numberActiveTouches === 1) {
537
+ if (
538
+ this.longPressTimeout &&
539
+ (Math.abs(gestureState.dx) > 5 || Math.abs(gestureState.dy) > 5)
540
+ ) {
541
+ clearTimeout(this.longPressTimeout);
542
+ this.longPressTimeout = null;
543
+ }
544
+ // change some measurement states when switching gesture to ensure a smooth transition
545
+ if (this.gestureType !== 'shift') {
546
+ this.lastGestureCenterPosition = calcGestureCenterPoint(
547
+ e,
548
+ gestureState
549
+ );
550
+ }
551
+
552
+ const { dx, dy } = gestureState;
553
+ const isShiftGesture = Math.abs(dx) > 2 || Math.abs(dy) > 2;
554
+ if (isShiftGesture) {
555
+ this.gestureType = 'shift';
556
+ this._handleShifting(gestureState);
557
+ }
558
+ }
559
+ };
560
+
561
+ /**
562
+ * Handles the pinch movement and zooming
563
+ *
564
+ * @param e
565
+ * @param gestureState
566
+ *
567
+ * @private
568
+ */
569
+ _handlePinching(
570
+ e: GestureResponderEvent,
571
+ gestureState: PanResponderGestureState
572
+ ) {
573
+ if (!this.props.zoomEnabled) return;
574
+
575
+ const {
576
+ maxZoom,
577
+ minZoom,
578
+ pinchToZoomInSensitivity,
579
+ pinchToZoomOutSensitivity,
580
+ } = this.props;
581
+
582
+ const distance = calcGestureTouchDistance(e, gestureState);
583
+
584
+ if (
585
+ this.props.onZoomBefore &&
586
+ this.props.onZoomBefore(
587
+ e,
588
+ gestureState,
589
+ this._getZoomableViewEventObject()
590
+ )
591
+ ) {
592
+ return;
593
+ }
594
+
595
+ // define the new zoom level and take zoom level sensitivity into consideration
596
+ const zoomGrowthFromLastGestureState =
597
+ distance / this.lastGestureTouchDistance;
598
+ this.lastGestureTouchDistance = distance;
599
+
600
+ const pinchToZoomSensitivity =
601
+ zoomGrowthFromLastGestureState < 1
602
+ ? pinchToZoomOutSensitivity
603
+ : pinchToZoomInSensitivity;
604
+
605
+ const deltaGrowth = zoomGrowthFromLastGestureState - 1;
606
+ // 0 - no resistance
607
+ // 10 - 90% resistance
608
+ const deltaGrowthAdjustedBySensitivity =
609
+ deltaGrowth * (1 - (pinchToZoomSensitivity * 9) / 100);
610
+
611
+ let newZoomLevel = this.zoomLevel * (1 + deltaGrowthAdjustedBySensitivity);
612
+
613
+ // make sure max and min zoom levels are respected
614
+ if (maxZoom !== null && newZoomLevel > maxZoom) {
615
+ newZoomLevel = maxZoom;
616
+ }
617
+
618
+ if (newZoomLevel < minZoom) {
619
+ newZoomLevel = minZoom;
620
+ }
621
+
622
+ const gestureCenterPoint = calcGestureCenterPoint(e, gestureState);
623
+
624
+ if (!gestureCenterPoint) return;
625
+
626
+ const zoomCenter = {
627
+ x: gestureCenterPoint.x - this.state.originalPageX,
628
+ y: gestureCenterPoint.y - this.state.originalPageY,
629
+ };
630
+
631
+ const { originalHeight, originalWidth } = this.state;
632
+
633
+ const oldOffsetX = this.offsetX;
634
+ const oldOffsetY = this.offsetY;
635
+ const oldScale = this.zoomLevel;
636
+ const newScale = newZoomLevel;
637
+
638
+ let offsetY = calcNewScaledOffsetForZoomCentering(
639
+ oldOffsetY,
640
+ originalHeight,
641
+ oldScale,
642
+ newScale,
643
+ zoomCenter.y
644
+ );
645
+ let offsetX = calcNewScaledOffsetForZoomCentering(
646
+ oldOffsetX,
647
+ originalWidth,
648
+ oldScale,
649
+ newScale,
650
+ zoomCenter.x
651
+ );
652
+
653
+ const offsetShift =
654
+ this._calcOffsetShiftSinceLastGestureState(gestureCenterPoint);
655
+ if (offsetShift) {
656
+ offsetX += offsetShift.x;
657
+ offsetY += offsetShift.y;
658
+ }
659
+
660
+ this.offsetX = offsetX;
661
+ this.offsetY = offsetY;
662
+ this.zoomLevel = newScale;
663
+
664
+ this.panAnim.setValue({ x: this.offsetX, y: this.offsetY });
665
+ this.zoomAnim.setValue(this.zoomLevel);
666
+
667
+ this.props.onZoomAfter?.(
668
+ e,
669
+ gestureState,
670
+ this._getZoomableViewEventObject()
671
+ );
672
+ }
673
+
674
+
675
+ /**
676
+ * Calculates the amount the offset should shift since the last position during panning
677
+ *
678
+ * @param {Vec2D} gestureCenterPoint
679
+ *
680
+ * @private
681
+ */
682
+ _calcOffsetShiftSinceLastGestureState(gestureCenterPoint: Vec2D) {
683
+ const { movementSensibility } = this.props;
684
+
685
+ let shift = null;
686
+
687
+ if (this.lastGestureCenterPosition) {
688
+ const dx = gestureCenterPoint.x - this.lastGestureCenterPosition.x;
689
+ const dy = gestureCenterPoint.y - this.lastGestureCenterPosition.y;
690
+
691
+ const shiftX = dx / this.zoomLevel / movementSensibility;
692
+ const shiftY = dy / this.zoomLevel / movementSensibility;
693
+
694
+ shift = {
695
+ x: shiftX,
696
+ y: shiftY,
697
+ };
698
+ }
699
+
700
+ this.lastGestureCenterPosition = gestureCenterPoint;
701
+
702
+ return shift;
703
+ }
704
+
705
+ /**
706
+ * Handles movement by tap and move
707
+ *
708
+ * @param gestureState
709
+ *
710
+ * @private
711
+ */
712
+ _handleShifting(gestureState: PanResponderGestureState) {
713
+ // Skips shifting if panEnabled is false or disablePanOnInitialZoom is true and we're on the initial zoom level
714
+ if (
715
+ !this.props.panEnabled ||
716
+ (this.props.disablePanOnInitialZoom &&
717
+ this.zoomLevel === this.props.initialZoom)
718
+ ) {
719
+ return;
720
+ }
721
+ const shift = this._calcOffsetShiftSinceLastGestureState({
722
+ x: gestureState.moveX,
723
+ y: gestureState.moveY,
724
+ });
725
+ if (!shift) return;
726
+
727
+ const offsetX = this.offsetX + shift.x;
728
+ const offsetY = this.offsetY + shift.y;
729
+
730
+
731
+ this._setNewOffsetPosition(offsetX, offsetY);
732
+ }
733
+
734
+ /**
735
+ * Set the state to offset moved
736
+ *
737
+ * @param {number} newOffsetX
738
+ * @param {number} newOffsetY
739
+ * @returns
740
+ */
741
+ async _setNewOffsetPosition(newOffsetX: number, newOffsetY: number) {
742
+ const { onShiftingBefore, onShiftingAfter } = this.props;
743
+
744
+ if (onShiftingBefore?.(null, null, this._getZoomableViewEventObject())) {
745
+ return;
746
+ }
747
+
748
+ this.offsetX = newOffsetX;
749
+ this.offsetY = newOffsetY;
750
+
751
+ this.panAnim.setValue({ x: this.offsetX, y: this.offsetY });
752
+ this.zoomAnim.setValue(this.zoomLevel);
753
+
754
+ onShiftingAfter?.(null, null, this._getZoomableViewEventObject());
755
+ }
756
+
757
+ /**
758
+ * Check whether the press event is double tap
759
+ * or single tap and handle the event accordingly
760
+ *
761
+ * @param e
762
+ *
763
+ * @private
764
+ */
765
+ private _resolveAndHandleTap = (e: GestureResponderEvent) => {
766
+ const now = Date.now();
767
+ if (
768
+ this.doubleTapFirstTapReleaseTimestamp &&
769
+ now - this.doubleTapFirstTapReleaseTimestamp < this.props.doubleTapDelay
770
+ ) {
771
+ this._addTouch({
772
+ ...this.doubleTapFirstTap,
773
+ id: now.toString(),
774
+ isSecondTap: true,
775
+ });
776
+ clearTimeout(this.singleTapTimeoutId);
777
+ delete this.doubleTapFirstTapReleaseTimestamp;
778
+ delete this.singleTapTimeoutId;
779
+ delete this.doubleTapFirstTap;
780
+ this._handleDoubleTap(e);
781
+ } else {
782
+ this.doubleTapFirstTapReleaseTimestamp = now;
783
+ this.doubleTapFirstTap = {
784
+ id: now.toString(),
785
+ x: e.nativeEvent.pageX - this.state.originalPageX,
786
+ y: e.nativeEvent.pageY - this.state.originalPageY,
787
+ };
788
+ this._addTouch(this.doubleTapFirstTap);
789
+
790
+ // persist event so e.nativeEvent is preserved after a timeout delay
791
+ e.persist();
792
+ this.singleTapTimeoutId = setTimeout(() => {
793
+ delete this.doubleTapFirstTapReleaseTimestamp;
794
+ delete this.singleTapTimeoutId;
795
+ this.props.onSingleTap?.(e, this._getZoomableViewEventObject());
796
+ }, this.props.doubleTapDelay);
797
+ }
798
+ };
799
+
800
+ private _addTouch(touch: TouchPoint) {
801
+ this.touches.push(touch);
802
+ this.setState({ touches: [...this.touches] });
803
+ }
804
+
805
+ private _removeTouch(touch: TouchPoint) {
806
+ this.touches.splice(this.touches.indexOf(touch), 1);
807
+ this.setState({ touches: [...this.touches] });
808
+ }
809
+
810
+ /**
811
+ * Handles the double tap event
812
+ *
813
+ * @param e
814
+ *
815
+ * @private
816
+ */
817
+ _handleDoubleTap(e: GestureResponderEvent) {
818
+ const { onDoubleTapBefore, onDoubleTapAfter, doubleTapZoomToCenter } =
819
+ this.props;
820
+
821
+ onDoubleTapBefore?.(e, this._getZoomableViewEventObject());
822
+
823
+ const nextZoomStep = this._getNextZoomStep();
824
+ const { originalPageX, originalPageY } = this.state;
825
+
826
+ // define new zoom position coordinates
827
+ const zoomPositionCoordinates = {
828
+ x: e.nativeEvent.pageX - originalPageX,
829
+ y: e.nativeEvent.pageY - originalPageY,
830
+ };
831
+
832
+ // if doubleTapZoomToCenter enabled -> always zoom to center instead
833
+ if (doubleTapZoomToCenter) {
834
+ zoomPositionCoordinates.x = 0;
835
+ zoomPositionCoordinates.y = 0;
836
+ }
837
+
838
+ this._zoomToLocation(
839
+ zoomPositionCoordinates.x,
840
+ zoomPositionCoordinates.y,
841
+ nextZoomStep
842
+ ).then(() => {
843
+ onDoubleTapAfter?.(
844
+ e,
845
+ this._getZoomableViewEventObject({ zoomLevel: nextZoomStep })
846
+ );
847
+ });
848
+ }
849
+
850
+ /**
851
+ * Returns the next zoom step based on current step and zoomStep property.
852
+ * If we are zoomed all the way in -> return to initialzoom
853
+ *
854
+ * @returns {*}
855
+ */
856
+ _getNextZoomStep() {
857
+ const { zoomStep, maxZoom, initialZoom } = this.props;
858
+ const { zoomLevel } = this;
859
+
860
+ if (zoomLevel.toFixed(2) === maxZoom.toFixed(2)) {
861
+ return initialZoom;
862
+ }
863
+
864
+ const nextZoomStep = zoomLevel * (1 + zoomStep);
865
+ if (nextZoomStep > maxZoom) {
866
+ return maxZoom;
867
+ }
868
+
869
+ return nextZoomStep;
870
+ }
871
+
872
+ /**
873
+ * Zooms to a specific location in our view
874
+ *
875
+ * @param x
876
+ * @param y
877
+ * @param newZoomLevel
878
+ *
879
+ * @private
880
+ */
881
+ async _zoomToLocation(x: number, y: number, newZoomLevel: number) {
882
+ if (!this.props.zoomEnabled) return;
883
+
884
+ this.props.onZoomBefore?.(null, null, this._getZoomableViewEventObject());
885
+
886
+ // == Perform Zoom Animation ==
887
+ // Calculates panAnim values based on changes in zoomAnim.
888
+ let prevScale = this.zoomLevel;
889
+ // Since zoomAnim is calculated in native driver,
890
+ // it will jitter panAnim once in a while,
891
+ // because here panAnim is being calculated in js.
892
+ // However the jittering should mostly occur in simulator.
893
+ const listenerId = this.zoomAnim.addListener(({ value: newScale }) => {
894
+ this.panAnim.setValue({
895
+ x: calcNewScaledOffsetForZoomCentering(
896
+ this.offsetX,
897
+ this.state.originalWidth,
898
+ prevScale,
899
+ newScale,
900
+ x
901
+ ),
902
+ y: calcNewScaledOffsetForZoomCentering(
903
+ this.offsetY,
904
+ this.state.originalHeight,
905
+ prevScale,
906
+ newScale,
907
+ y
908
+ ),
909
+ });
910
+ prevScale = newScale;
911
+ });
912
+ getZoomToAnimation(this.zoomAnim, newZoomLevel).start(() => {
913
+ this.zoomAnim.removeListener(listenerId);
914
+ });
915
+ // == Zoom Animation Ends ==
916
+
917
+ this.props.onZoomAfter?.(null, null, this._getZoomableViewEventObject());
918
+ }
919
+
920
+ /**
921
+ * Zooms to a specificied zoom level.
922
+ * Returns a promise if everything was updated and a boolean, whether it could be updated or if it exceeded the min/max zoom limits.
923
+ *
924
+ * @param {number} newZoomLevel
925
+ *
926
+ * @return {Promise<bool>}
927
+ */
928
+ async zoomTo(newZoomLevel: number): Promise<boolean> {
929
+ if (
930
+ // if we would go out of our min/max limits -> abort
931
+ newZoomLevel > this.props.maxZoom ||
932
+ newZoomLevel < this.props.minZoom
933
+ )
934
+ return false;
935
+
936
+ await this._zoomToLocation(0, 0, newZoomLevel);
937
+ return true;
938
+ }
939
+
940
+ /**
941
+ * Zooms in or out by a specified change level
942
+ * Use a positive number for `zoomLevelChange` to zoom in
943
+ * Use a negative number for `zoomLevelChange` to zoom out
944
+ *
945
+ * Returns a promise if everything was updated and a boolean, whether it could be updated or if it exceeded the min/max zoom limits.
946
+ *
947
+ * @param {number | null} zoomLevelChange
948
+ *
949
+ * @return {Promise<bool>}
950
+ */
951
+ zoomBy(zoomLevelChange: number = null): Promise<boolean> {
952
+ // if no zoom level Change given -> just use zoom step
953
+ if (!zoomLevelChange) {
954
+ zoomLevelChange = this.props.zoomStep;
955
+ }
956
+
957
+ return this.zoomTo(this.zoomLevel + zoomLevelChange);
958
+ }
959
+
960
+ /**
961
+ * Moves the zoomed view to a specified position
962
+ * Returns a promise when finished
963
+ *
964
+ * @param {number} newOffsetX the new position we want to move it to (x-axis)
965
+ * @param {number} newOffsetY the new position we want to move it to (y-axis)
966
+ *
967
+ * @return {Promise<bool>}
968
+ */
969
+ moveTo(newOffsetX: number, newOffsetY: number): Promise<void> {
970
+ const { originalWidth, originalHeight } = this.state;
971
+
972
+ const offsetX = (newOffsetX - originalWidth / 2) / this.zoomLevel;
973
+ const offsetY = (newOffsetY - originalHeight / 2) / this.zoomLevel;
974
+
975
+ return this._setNewOffsetPosition(-offsetX, -offsetY);
976
+ }
977
+
978
+ /**
979
+ * Moves the zoomed view by a certain amount.
980
+ *
981
+ * Returns a promise when finished
982
+ *
983
+ * @param {number} offsetChangeX the amount we want to move the offset by (x-axis)
984
+ * @param {number} offsetChangeY the amount we want to move the offset by (y-axis)
985
+ *
986
+ * @return {Promise<bool>}
987
+ */
988
+ moveBy(offsetChangeX: number, offsetChangeY: number): Promise<void> {
989
+ const offsetX =
990
+ (this.offsetX * this.zoomLevel - offsetChangeX) / this.zoomLevel;
991
+ const offsetY =
992
+ (this.offsetY * this.zoomLevel - offsetChangeY) / this.zoomLevel;
993
+
994
+ return this._setNewOffsetPosition(offsetX, offsetY);
995
+ }
996
+
997
+ render() {
998
+ return (
999
+ <View
1000
+ style={styles.container}
1001
+ {...this.gestureHandlers.panHandlers}
1002
+ ref={this.zoomSubjectWrapperRef}
1003
+ onLayout={this.grabZoomSubjectOriginalMeasurements}
1004
+ >
1005
+ <Animated.View
1006
+ style={[
1007
+ styles.zoomSubject,
1008
+ this.props.style,
1009
+ {
1010
+ transform: [
1011
+ { scale: this.zoomAnim },
1012
+ ...this.panAnim.getTranslateTransform(),
1013
+ ],
1014
+ },
1015
+ ]}
1016
+ >
1017
+ {this.props.children}
1018
+ </Animated.View>
1019
+ </View>
1020
+ );
1021
+ }
1022
+ }
1023
+
1024
+ const styles = StyleSheet.create({
1025
+ zoomSubject: {
1026
+ flex: 1,
1027
+ width: '100%',
1028
+ justifyContent: 'center',
1029
+ alignItems: 'center',
1030
+ },
1031
+ container: {
1032
+ flex: 1,
1033
+ justifyContent: 'center',
1034
+ alignItems: 'center',
1035
+ position: 'relative',
1036
+ overflow: 'hidden',
1037
+ },
1038
+ });
1039
+
1040
+ export default ReactNativeZoomableView;