-
Notifications
You must be signed in to change notification settings - Fork 375
Expand file tree
/
Copy pathImageGallery.tsx
More file actions
677 lines (614 loc) · 21.1 KB
/
ImageGallery.tsx
File metadata and controls
677 lines (614 loc) · 21.1 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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
import React, { RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Image, ImageStyle, Keyboard, StyleSheet, ViewStyle } from 'react-native';
import { Gesture, GestureDetector } from 'react-native-gesture-handler';
import Animated, {
Easing,
runOnJS,
runOnUI,
SharedValue,
useAnimatedStyle,
useDerivedValue,
useSharedValue,
withTiming,
} from 'react-native-reanimated';
import { BottomSheetModal as BottomSheetModalOriginal } from '@gorhom/bottom-sheet';
import type { UserResponse } from 'stream-chat';
import { AnimatedGalleryImage } from './components/AnimatedGalleryImage';
import { AnimatedGalleryVideo } from './components/AnimatedGalleryVideo';
import {
ImageGalleryFooter,
ImageGalleryFooterCustomComponentProps,
} from './components/ImageGalleryFooter';
import {
ImageGalleryHeader,
ImageGalleryHeaderCustomComponentProps,
} from './components/ImageGalleryHeader';
import { ImageGalleryOverlay } from './components/ImageGalleryOverlay';
import { ImageGalleryGridImageComponents, ImageGrid } from './components/ImageGrid';
import {
ImageGalleryGridHandleCustomComponentProps,
ImageGridHandle,
} from './components/ImageGridHandle';
import { useImageGalleryGestures } from './hooks/useImageGalleryGestures';
import { useChatConfigContext } from '../../contexts/chatConfigContext/ChatConfigContext';
import { useImageGalleryContext } from '../../contexts/imageGalleryContext/ImageGalleryContext';
import { OverlayProviderProps } from '../../contexts/overlayContext/OverlayContext';
import { useTheme } from '../../contexts/themeContext/ThemeContext';
import { useViewport } from '../../hooks/useViewport';
import { isVideoPlayerAvailable, VideoType } from '../../native';
import { FileTypes } from '../../types/types';
import { getResizedImageUrl } from '../../utils/getResizedImageUrl';
import { getUrlOfImageAttachment } from '../../utils/getUrlOfImageAttachment';
import { getGiphyMimeType } from '../Attachment/utils/getGiphyMimeType';
import {
BottomSheetModal,
BottomSheetModalProvider,
} from '../BottomSheetCompatibility/BottomSheetModal';
const MARGIN = 32;
export enum HasPinched {
FALSE = 0,
TRUE,
}
export enum IsSwiping {
UNDETERMINED = 0,
TRUE,
FALSE,
}
export type ImageGalleryCustomComponents = {
/**
* Override props for following UI components, which are part of [image gallery](https://github.com/GetStream/stream-chat-react-native/wiki/Cookbook-v3.0#gallery-components).
*
* - [ImageGalleryFooter](#ImageGalleryFooter)
*
* - [ImageGrid](#ImageGrid)
*
* - [ImageGridHandle](#ImageGridHandle)
*
* - [ImageGalleryHeader](#ImageGalleryHeader)
*
* e.g.,
*
* ```js
* {
* footer: {
* ShareIcon: CustomShareIconComponent
* },
* grid: {
* avatarComponent: CustomAvatarComponent
* },
* gridHandle: {
* centerComponent: CustomCenterComponent
* },
* header: {
* CloseIcon: CustomCloseButtonComponent
* },
* }
* ```
* @overrideType object
*/
imageGalleryCustomComponents?: {
footer?: ImageGalleryFooterCustomComponentProps;
grid?: ImageGalleryGridImageComponents;
gridHandle?: ImageGalleryGridHandleCustomComponentProps;
header?: ImageGalleryHeaderCustomComponentProps;
};
};
type Props = ImageGalleryCustomComponents & {
overlayOpacity: SharedValue<number>;
} & Pick<
OverlayProviderProps,
| 'giphyVersion'
| 'imageGalleryGridSnapPoints'
| 'imageGalleryGridHandleHeight'
| 'numberOfImageGalleryGridColumns'
| 'autoPlayVideo'
>;
export const ImageGallery = (props: Props) => {
const {
autoPlayVideo = false,
giphyVersion = 'fixed_height',
imageGalleryCustomComponents,
imageGalleryGridHandleHeight = 40,
imageGalleryGridSnapPoints,
numberOfImageGalleryGridColumns,
overlayOpacity,
} = props;
const { resizableCDNHosts } = useChatConfigContext();
const {
theme: {
colors: { white_snow },
imageGallery: { backgroundColor, pager, slide },
},
} = useTheme();
const [gridPhotos, setGridPhotos] = useState<Photo[]>([]);
const { messages, selectedMessage, setSelectedMessage } = useImageGalleryContext();
const { vh, vw } = useViewport();
const fullWindowHeight = vh(100);
const fullWindowWidth = vw(100);
const halfScreenWidth = fullWindowWidth / 2;
const halfScreenHeight = fullWindowHeight / 2;
const quarterScreenHeight = fullWindowHeight / 4;
const snapPoints = React.useMemo(
() => [(fullWindowHeight * 3) / 4, fullWindowHeight - imageGalleryGridHandleHeight],
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
/**
* BottomSheetModal ref
*/
const bottomSheetModalRef = useRef<BottomSheetModalOriginal>(null);
/**
* BottomSheetModal state
*/
const [currentBottomSheetIndex, setCurrentBottomSheetIndex] = useState(0);
const animatedBottomSheetIndex = useSharedValue(0);
/**
* Fade animation for screen, it is always rendered with pointerEvents
* set to none for fast opening
*/
const screenTranslateY = useSharedValue(fullWindowHeight);
const showScreen = () => {
'worklet';
screenTranslateY.value = withTiming(0, {
duration: 250,
easing: Easing.out(Easing.ease),
});
};
/**
* Run the fade animation on visible change
*/
useEffect(() => {
Keyboard.dismiss();
showScreen();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
/**
* Image height from URL or default to full screen height
*/
const [currentImageHeight, setCurrentImageHeight] = useState<number>(fullWindowHeight);
/**
* Header visible value for animating in out
*/
const headerFooterVisible = useSharedValue(1);
/**
* Shared values for movement
*/
const translateX = useSharedValue(0);
const translateY = useSharedValue(0);
const offsetScale = useSharedValue(1);
const scale = useSharedValue(1);
const translationX = useSharedValue(0);
/**
* Photos array created from all currently available
* photo attachments
*/
const photos = useMemo(
() =>
messages.reduce((acc: Photo[], cur) => {
const attachmentImages =
cur.attachments
?.filter(
(attachment) =>
(attachment.type === FileTypes.Giphy &&
(attachment.giphy?.[giphyVersion]?.url ||
attachment.thumb_url ||
attachment.image_url)) ||
(attachment.type === FileTypes.Image &&
!attachment.title_link &&
!attachment.og_scrape_url &&
getUrlOfImageAttachment(attachment)) ||
(isVideoPlayerAvailable() && attachment.type === FileTypes.Video),
)
.reverse() || [];
const attachmentPhotos = attachmentImages.map((a) => {
const imageUrl = getUrlOfImageAttachment(a) as string;
const giphyURL = a.giphy?.[giphyVersion]?.url || a.thumb_url || a.image_url;
const isInitiallyPaused = !autoPlayVideo;
return {
channelId: cur.cid,
created_at: cur.created_at,
duration: 0,
id: `photoId-${cur.id}-${imageUrl}`,
messageId: cur.id,
mime_type: a.type === 'giphy' ? getGiphyMimeType(giphyURL ?? '') : a.mime_type,
original_height: a.original_height,
original_width: a.original_width,
paused: isInitiallyPaused,
progress: 0,
thumb_url: a.thumb_url,
type: a.type,
uri:
a.type === 'giphy'
? giphyURL
: getResizedImageUrl({
height: fullWindowHeight,
resizableCDNHosts,
url: imageUrl,
width: fullWindowWidth,
}),
user: cur.user,
user_id: cur.user_id,
};
});
return [...attachmentPhotos, ...acc] as Photo[];
}, []),
[autoPlayVideo, fullWindowHeight, fullWindowWidth, giphyVersion, messages, resizableCDNHosts],
);
/**
* The URL for the images may differ because of dimensions passed as
* part of the query.
*/
const stripQueryFromUrl = (url: string) => url.split('?')[0];
const photoSelectedIndex = useMemo(() => {
const idx = photos.findIndex(
(photo) =>
photo.messageId === selectedMessage?.messageId &&
stripQueryFromUrl(photo.uri) === stripQueryFromUrl(selectedMessage?.url || ''),
);
return idx === -1 ? 0 : idx;
}, [photos, selectedMessage]);
/**
* JS and UI index values, the JS follows the UI but is needed
* for rendering the virtualized image list
*/
const [selectedIndex, setSelectedIndex] = useState(photoSelectedIndex);
const index = useSharedValue(photoSelectedIndex);
const [imageGalleryAttachments, setImageGalleryAttachments] = useState<Photo[]>(photos);
/**
* Photos length needs to be kept as a const here so if the length
* changes it causes the pan gesture handler function to refresh. This
* does not work if the calculation for the length of the array is left
* inside the gesture handler as it will have an array as a dependency
*/
const photoLength = photos.length;
/**
* Set selected photo when changed via pressing in the message list
*/
useEffect(() => {
const updatePosition = (newIndex: number) => {
'worklet';
if (newIndex > -1) {
index.value = newIndex;
translationX.value = -(fullWindowWidth + MARGIN) * newIndex;
runOnJS(setSelectedIndex)(newIndex);
}
};
runOnUI(updatePosition)(photoSelectedIndex);
}, [fullWindowWidth, index, photoSelectedIndex, translationX]);
/**
* Image heights are not provided and therefore need to be calculated.
* We start by allowing the image to be the full height then reduce it
* to the proper scaled height based on the width being restricted to the
* screen width when the dimensions are received.
*/
const uriForCurrentImage = imageGalleryAttachments[selectedIndex]?.uri;
useEffect(() => {
let currentImageHeight = fullWindowHeight;
const photo = imageGalleryAttachments[index.value];
const height = photo?.original_height;
const width = photo?.original_width;
if (height && width) {
const imageHeight = Math.floor(height * (fullWindowWidth / width));
currentImageHeight = imageHeight > fullWindowHeight ? fullWindowHeight : imageHeight;
} else if (photo?.uri) {
if (photo.type === FileTypes.Image) {
Image.getSize(photo.uri, (width, height) => {
const imageHeight = Math.floor(height * (fullWindowWidth / width));
currentImageHeight = imageHeight > fullWindowHeight ? fullWindowHeight : imageHeight;
});
}
}
setCurrentImageHeight(currentImageHeight);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [uriForCurrentImage]);
const { doubleTap, pan, pinch, singleTap } = useImageGalleryGestures({
currentImageHeight,
halfScreenHeight,
halfScreenWidth,
headerFooterVisible,
offsetScale,
overlayOpacity,
photoLength,
scale,
screenHeight: fullWindowHeight,
screenWidth: fullWindowWidth,
selectedIndex,
setSelectedIndex,
translateX,
translateY,
translationX,
});
/**
* If the header is visible we scale down the opacity of it as the
* image is swiped downward
*/
const headerFooterOpacity = useDerivedValue(
() =>
currentImageHeight * scale.value < fullWindowHeight && translateY.value > 0
? 1 - translateY.value / quarterScreenHeight
: currentImageHeight * scale.value > fullWindowHeight &&
translateY.value > (currentImageHeight / 2) * scale.value - halfScreenHeight
? 1 -
(translateY.value - ((currentImageHeight / 2) * scale.value - halfScreenHeight)) /
quarterScreenHeight
: 1,
[currentImageHeight],
);
/**
* This transition and scaleX reverse lets use scroll right
*/
const pagerStyle = useAnimatedStyle<ImageStyle>(
() => ({
transform: [
{ scaleX: 1 },
{
translateX: translationX.value,
},
],
}),
[],
);
/**
* Simple background color animation on Y movement
*/
const containerBackground = useAnimatedStyle<ViewStyle>(
() => ({
backgroundColor: backgroundColor || white_snow,
opacity: headerFooterOpacity.value,
}),
[headerFooterOpacity],
);
/**
* Show screen style as component is always rendered we hide it
* down and up and set opacity to 0 for good measure
*/
const showScreenStyle = useAnimatedStyle<ViewStyle>(
() => ({
transform: [
{
translateY: screenTranslateY.value,
},
],
}),
[],
);
/**
* Functions toclose BottomSheetModal with image grid
*/
const closeGridView = () => {
if (bottomSheetModalRef.current?.close) {
bottomSheetModalRef.current.close();
setGridPhotos([]);
}
};
/**
* Function to open BottomSheetModal with image grid
*/
const openGridView = () => {
if (bottomSheetModalRef.current?.present) {
bottomSheetModalRef.current.present();
setGridPhotos(imageGalleryAttachments);
}
};
const handleEnd = () => {
handlePlayPause(imageGalleryAttachments[selectedIndex].id, true);
handleProgress(imageGalleryAttachments[selectedIndex].id, 1, true);
};
const videoRef = useRef<VideoType>(null);
const handleLoad = (index: string, duration: number) => {
setImageGalleryAttachments((prevImageGalleryAttachment) =>
prevImageGalleryAttachment.map((imageGalleryAttachment) => ({
...imageGalleryAttachment,
duration: imageGalleryAttachment.id === index ? duration : imageGalleryAttachment.duration,
})),
);
};
const handleProgress = (index: string, progress: number, hasEnd?: boolean) => {
setImageGalleryAttachments((prevImageGalleryAttachments) =>
prevImageGalleryAttachments.map((imageGalleryAttachment) => ({
...imageGalleryAttachment,
progress:
imageGalleryAttachment.id === index
? hasEnd
? 1
: progress
: imageGalleryAttachment.progress,
})),
);
};
const handlePlayPause = (index: string, pausedStatus?: boolean) => {
if (pausedStatus === false) {
// If the status is false we set the audio with the index as playing and the others as paused.
setImageGalleryAttachments((prevImageGalleryAttachment) =>
prevImageGalleryAttachment.map((imageGalleryAttachment) => ({
...imageGalleryAttachment,
paused: imageGalleryAttachment.id === index ? false : true,
})),
);
if (videoRef.current?.play) {
videoRef.current.play();
}
} else {
// If the status is true we simply set all the audio's paused state as true.
setImageGalleryAttachments((prevImageGalleryAttachment) =>
prevImageGalleryAttachment.map((imageGalleryAttachment) => ({
...imageGalleryAttachment,
paused: true,
})),
);
if (videoRef.current?.pause) {
videoRef.current.pause();
}
}
};
const onPlayPause = (status?: boolean) => {
if (status === undefined) {
if (imageGalleryAttachments[selectedIndex].paused) {
handlePlayPause(imageGalleryAttachments[selectedIndex].id, false);
} else {
handlePlayPause(imageGalleryAttachments[selectedIndex].id, true);
}
} else {
handlePlayPause(imageGalleryAttachments[selectedIndex].id, status);
}
};
const MemoizedImageGridHandle = useCallback(
() => (
<ImageGridHandle
closeGridView={closeGridView}
{...imageGalleryCustomComponents?.gridHandle}
/>
),
[imageGalleryCustomComponents?.gridHandle],
);
return (
<Animated.View
accessibilityLabel='Image Gallery'
pointerEvents={'auto'}
style={[StyleSheet.absoluteFillObject, showScreenStyle]}
>
<Animated.View style={[StyleSheet.absoluteFillObject, containerBackground]} />
<GestureDetector gesture={Gesture.Simultaneous(singleTap, doubleTap, pinch, pan)}>
<Animated.View style={StyleSheet.absoluteFillObject}>
<Animated.View style={[styles.animatedContainer, pagerStyle, pager]}>
{imageGalleryAttachments.map((photo, i) =>
photo.type === FileTypes.Video ? (
<AnimatedGalleryVideo
attachmentId={photo.id}
handleEnd={handleEnd}
handleLoad={handleLoad}
handleProgress={handleProgress}
index={i}
key={`${photo.uri}-${i}`}
offsetScale={offsetScale}
paused={photo.paused || false}
previous={selectedIndex > i}
repeat={true}
scale={scale}
screenHeight={fullWindowHeight}
selected={selectedIndex === i}
shouldRender={Math.abs(selectedIndex - i) < 4}
source={{ uri: photo.uri }}
style={[
{
height: fullWindowHeight * 8,
marginRight: MARGIN,
width: fullWindowWidth * 8,
},
slide,
]}
translateX={translateX}
translateY={translateY}
videoRef={videoRef as RefObject<VideoType>}
/>
) : (
<AnimatedGalleryImage
accessibilityLabel={'Image Item'}
index={i}
key={`${photo.uri}-${i}`}
offsetScale={offsetScale}
photo={photo}
previous={selectedIndex > i}
scale={scale}
screenHeight={fullWindowHeight}
selected={selectedIndex === i}
shouldRender={Math.abs(selectedIndex - i) < 4}
style={[
{
height: fullWindowHeight * 8,
marginRight: MARGIN,
width: fullWindowWidth * 8,
},
slide,
]}
translateX={translateX}
translateY={translateY}
/>
),
)}
</Animated.View>
</Animated.View>
</GestureDetector>
<ImageGalleryHeader
opacity={headerFooterOpacity}
photo={imageGalleryAttachments[selectedIndex]}
visible={headerFooterVisible}
{...imageGalleryCustomComponents?.header}
/>
{imageGalleryAttachments[selectedIndex] && (
<ImageGalleryFooter
accessibilityLabel={'Image Gallery Footer'}
duration={imageGalleryAttachments[selectedIndex].duration || 0}
onPlayPause={onPlayPause}
opacity={headerFooterOpacity}
openGridView={openGridView}
paused={imageGalleryAttachments[selectedIndex].paused || false}
photo={imageGalleryAttachments[selectedIndex]}
photoLength={imageGalleryAttachments.length}
progress={imageGalleryAttachments[selectedIndex].progress || 0}
selectedIndex={selectedIndex}
videoRef={videoRef as RefObject<VideoType>}
visible={headerFooterVisible}
{...imageGalleryCustomComponents?.footer}
/>
)}
<ImageGalleryOverlay
animatedBottomSheetIndex={animatedBottomSheetIndex}
closeGridView={closeGridView}
currentBottomSheetIndex={currentBottomSheetIndex}
/>
<BottomSheetModalProvider>
<BottomSheetModal
animatedIndex={animatedBottomSheetIndex}
enablePanDownToClose={true}
handleComponent={MemoizedImageGridHandle}
// @ts-ignore
handleHeight={imageGalleryGridHandleHeight}
index={0}
onChange={(index: number) => setCurrentBottomSheetIndex(index)}
ref={bottomSheetModalRef}
snapPoints={imageGalleryGridSnapPoints || snapPoints}
>
<ImageGrid
closeGridView={closeGridView}
numberOfImageGalleryGridColumns={numberOfImageGalleryGridColumns}
photos={gridPhotos}
setSelectedMessage={setSelectedMessage}
{...imageGalleryCustomComponents?.grid}
/>
</BottomSheetModal>
</BottomSheetModalProvider>
</Animated.View>
);
};
/**
* Clamping worklet to clamp the scaling
*/
export const clamp = (value: number, lowerBound: number, upperBound: number) => {
'worklet';
return Math.min(Math.max(lowerBound, value), upperBound);
};
const styles = StyleSheet.create({
animatedContainer: {
alignItems: 'center',
flexDirection: 'row',
},
});
export type Photo = {
id: string;
uri: string;
channelId?: string;
created_at?: string | Date;
duration?: number;
messageId?: string;
mime_type?: string;
original_height?: number;
original_width?: number;
paused?: boolean;
progress?: number;
thumb_url?: string;
type?: string;
user?: UserResponse | null;
user_id?: string;
};
ImageGallery.displayName = 'ImageGallery{imageGallery}';