-
Notifications
You must be signed in to change notification settings - Fork 375
Expand file tree
/
Copy pathAttachmentPicker.tsx
More file actions
326 lines (294 loc) · 11.6 KB
/
AttachmentPicker.tsx
File metadata and controls
326 lines (294 loc) · 11.6 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
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { BackHandler, Keyboard, Platform, StyleSheet } from 'react-native';
import BottomSheetOriginal from '@gorhom/bottom-sheet';
import type { BottomSheetHandleProps } from '@gorhom/bottom-sheet';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import type { AttachmentPickerErrorProps } from './components/AttachmentPickerError';
import { renderAttachmentPickerItem } from './components/AttachmentPickerItem';
import {
AttachmentPickerContextValue,
useAttachmentPickerContext,
} from '../../contexts/attachmentPickerContext/AttachmentPickerContext';
import { useTheme } from '../../contexts/themeContext/ThemeContext';
import { useScreenDimensions } from '../../hooks/useScreenDimensions';
import { NativeHandlers } from '../../native';
import type { Asset } from '../../types/types';
import { BottomSheet } from '../BottomSheetCompatibility/BottomSheet';
import { BottomSheetFlatList } from '../BottomSheetCompatibility/BottomSheetFlatList';
dayjs.extend(duration);
const styles = StyleSheet.create({
container: {
flexGrow: 1,
},
});
export type AttachmentPickerProps = Pick<
AttachmentPickerContextValue,
| 'AttachmentPickerBottomSheetHandle'
| 'attachmentPickerBottomSheetHandleHeight'
| 'attachmentSelectionBarHeight'
| 'attachmentPickerBottomSheetHeight'
> & {
/**
* Custom UI component to render error component while opening attachment picker.
*
* **Default** [AttachmentPickerError](https://github.com/GetStream/stream-chat-react-native/blob/main/package/src/components/AttachmentPicker/components/AttachmentPickerError.tsx)
*/
AttachmentPickerError: React.ComponentType<AttachmentPickerErrorProps>;
/**
* Custom UI component to render error image for attachment picker
*
* **Default** [AttachmentPickerErrorImage](https://github.com/GetStream/stream-chat-react-native/blob/main/package/src/components/AttachmentPicker/components/AttachmentPickerErrorImage.tsx)
*/
AttachmentPickerErrorImage: React.ComponentType;
/**
* Custom UI Component to render select more photos for selected gallery access in iOS.
*/
AttachmentPickerIOSSelectMorePhotos: React.ComponentType;
/**
* Custom UI component to render overlay component, that shows up on top of [selected image](https://github.com/GetStream/stream-chat-react-native/blob/main/screenshots/docs/1.png) (with tick mark)
*
* **Default** [ImageOverlaySelectedComponent](https://github.com/GetStream/stream-chat-react-native/blob/main/package/src/components/AttachmentPicker/components/ImageOverlaySelectedComponent.tsx)
*/
ImageOverlaySelectedComponent: React.ComponentType;
attachmentPickerErrorButtonText?: string;
attachmentPickerErrorText?: string;
numberOfAttachmentImagesToLoadPerCall?: number;
numberOfAttachmentPickerImageColumns?: number;
};
export const AttachmentPicker = React.forwardRef(
(props: AttachmentPickerProps, ref: React.ForwardedRef<BottomSheetOriginal>) => {
const {
AttachmentPickerBottomSheetHandle,
attachmentPickerBottomSheetHandleHeight,
attachmentPickerBottomSheetHeight,
AttachmentPickerError,
attachmentPickerErrorButtonText,
AttachmentPickerErrorImage,
attachmentPickerErrorText,
AttachmentPickerIOSSelectMorePhotos,
ImageOverlaySelectedComponent,
numberOfAttachmentImagesToLoadPerCall,
numberOfAttachmentPickerImageColumns,
} = props;
const {
theme: {
attachmentPicker: { bottomSheetContentContainer },
colors: { white },
},
} = useTheme();
const {
closePicker,
maxNumberOfFiles,
selectedFiles,
selectedImages,
selectedPicker,
setSelectedFiles,
setSelectedImages,
setSelectedPicker,
topInset,
} = useAttachmentPickerContext();
const { vh: screenVh } = useScreenDimensions();
const fullScreenHeight = screenVh(100);
const [currentIndex, setCurrentIndex] = useState(-1);
const endCursorRef = useRef<string>(undefined);
const [photoError, setPhotoError] = useState(false);
const [iOSLimited, setIosLimited] = useState(false);
const hasNextPageRef = useRef(true);
const [loadingPhotos, setLoadingPhotos] = useState(false);
const [photos, setPhotos] = useState<Asset[]>([]);
const attemptedToLoadPhotosOnOpenRef = useRef(false);
const getMorePhotos = useCallback(async () => {
if (
hasNextPageRef.current &&
!loadingPhotos &&
currentIndex > -1 &&
selectedPicker === 'images'
) {
setPhotoError(false);
setLoadingPhotos(true);
const endCursor = endCursorRef.current;
try {
if (!NativeHandlers.getPhotos) {
setPhotos([]);
setIosLimited(false);
return;
}
const results = await NativeHandlers.getPhotos({
after: endCursor,
first: numberOfAttachmentImagesToLoadPerCall ?? 60,
});
endCursorRef.current = results.endCursor;
setPhotos((prevPhotos) =>
endCursor ? [...prevPhotos, ...results.assets] : results.assets,
);
setIosLimited(results.iOSLimited);
hasNextPageRef.current = !!results.hasNextPage;
} catch (error) {
setPhotoError(true);
}
setLoadingPhotos(false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentIndex, selectedPicker, loadingPhotos]);
// we need to use ref here to avoid running effect when getMorePhotos changes
const getMorePhotosRef = useRef(getMorePhotos);
getMorePhotosRef.current = getMorePhotos;
useEffect(() => {
if (selectedPicker !== 'images') {
return;
}
if (!NativeHandlers.oniOS14GalleryLibrarySelectionChange) {
return;
}
// ios 14 library selection change event is fired when user reselects the images that are permitted to be readable by the app
const { unsubscribe } = NativeHandlers.oniOS14GalleryLibrarySelectionChange(() => {
// we reset the cursor and has next page to true to facilitate fetching of the first page of photos again
hasNextPageRef.current = true;
endCursorRef.current = undefined;
// fetch the first page of photos again
getMorePhotosRef.current();
});
return unsubscribe;
}, [selectedPicker]);
useEffect(() => {
const backAction = () => {
if (selectedPicker) {
setSelectedPicker(undefined);
closePicker();
return true;
}
return false;
};
const backHandler = BackHandler.addEventListener('hardwareBackPress', backAction);
return () => backHandler.remove();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedPicker, closePicker]);
useEffect(() => {
const onKeyboardOpenHandler = () => {
if (selectedPicker) {
setSelectedPicker(undefined);
}
closePicker();
};
const keyboardShowEvent = Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow';
const keyboardSubscription = Keyboard.addListener(keyboardShowEvent, onKeyboardOpenHandler);
return () => {
// Following if-else condition to avoid deprecated warning coming RN 0.65
if (keyboardSubscription?.remove) {
keyboardSubscription.remove();
return;
}
// @ts-ignore
else if (Keyboard.removeListener) {
// @ts-ignore
Keyboard.removeListener(keyboardShowEvent, onKeyboardOpenHandler);
}
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [closePicker, selectedPicker]);
useEffect(() => {
if (currentIndex < 0) {
setSelectedPicker(undefined);
if (!loadingPhotos) {
endCursorRef.current = undefined;
hasNextPageRef.current = true;
attemptedToLoadPhotosOnOpenRef.current = false;
setPhotoError(false);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentIndex, loadingPhotos]);
useEffect(() => {
if (
!attemptedToLoadPhotosOnOpenRef.current &&
selectedPicker === 'images' &&
endCursorRef.current === undefined &&
currentIndex > -1 &&
!loadingPhotos
) {
getMorePhotos();
// we do this only once on open for avoiding to request permissions in rationale dialog again and again on Android
attemptedToLoadPhotosOnOpenRef.current = true;
}
}, [currentIndex, selectedPicker, getMorePhotos, loadingPhotos]);
const selectedPhotos = photos.map((asset) => ({
asset,
ImageOverlaySelectedComponent,
maxNumberOfFiles,
numberOfAttachmentPickerImageColumns,
numberOfUploads: selectedFiles.length + selectedImages.length,
// `id` is available for Expo MediaLibrary while Cameraroll doesn't share id therefore we use `uri`
selected:
selectedImages.some((image) =>
image.id
? image.id === asset.id
: image.uri === asset.uri || image.originalUri === asset.uri,
) ||
selectedFiles.some((file) =>
file.id ? file.id === asset.id : file.uri === asset.uri || file.originalUri === asset.uri,
),
selectedFiles,
selectedImages,
setSelectedFiles,
setSelectedImages,
}));
const handleHeight = attachmentPickerBottomSheetHandleHeight;
const initialSnapPoint = attachmentPickerBottomSheetHeight;
const finalSnapPoint = fullScreenHeight - topInset;
/**
* Snap points changing cause a rerender of the position,
* this is an issue if you are calling close on the bottom sheet.
*/
const snapPoints = [initialSnapPoint, finalSnapPoint];
const MemoizedAttachmentPickerBottomSheetHandle = useCallback(
(props: BottomSheetHandleProps) =>
/**
* using `null` here instead of `style={{ opacity: photoError ? 0 : 1 }}`
* as opacity is not an allowed style
*/
!photoError && AttachmentPickerBottomSheetHandle ? (
<AttachmentPickerBottomSheetHandle {...props} />
) : null,
[AttachmentPickerBottomSheetHandle, photoError],
);
return (
<>
<BottomSheet
enablePanDownToClose={true}
handleComponent={MemoizedAttachmentPickerBottomSheetHandle}
// @ts-ignore
handleHeight={handleHeight}
index={-1}
onChange={setCurrentIndex}
ref={ref}
snapPoints={snapPoints}
>
{iOSLimited && <AttachmentPickerIOSSelectMorePhotos />}
<BottomSheetFlatList
contentContainerStyle={[
styles.container,
{ backgroundColor: white },
bottomSheetContentContainer,
{ opacity: photoError ? 0 : 1 },
]}
data={selectedPhotos}
keyExtractor={(item) => item.asset.uri}
numColumns={numberOfAttachmentPickerImageColumns ?? 3}
onEndReached={photoError ? undefined : getMorePhotos}
renderItem={renderAttachmentPickerItem}
/>
</BottomSheet>
{selectedPicker === 'images' && photoError && (
<AttachmentPickerError
attachmentPickerBottomSheetHeight={attachmentPickerBottomSheetHeight}
attachmentPickerErrorButtonText={attachmentPickerErrorButtonText}
AttachmentPickerErrorImage={AttachmentPickerErrorImage}
attachmentPickerErrorText={attachmentPickerErrorText}
/>
)}
</>
);
},
);
AttachmentPicker.displayName = 'AttachmentPicker';