-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
index.native.tsx
438 lines (401 loc) · 17.3 KB
/
index.native.tsx
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
import {Str} from 'expensify-common';
import {manipulateAsync, SaveFormat} from 'expo-image-manipulator';
import React, {useCallback, useMemo, useRef, useState} from 'react';
import {Alert, View} from 'react-native';
import RNFetchBlob from 'react-native-blob-util';
import RNDocumentPicker from 'react-native-document-picker';
import type {DocumentPickerOptions, DocumentPickerResponse} from 'react-native-document-picker';
import {launchImageLibrary} from 'react-native-image-picker';
import type {Asset, Callback, CameraOptions, ImageLibraryOptions, ImagePickerResponse} from 'react-native-image-picker';
import ImageSize from 'react-native-image-size';
import type {FileObject, ImagePickerResponse as FileResponse} from '@components/AttachmentModal';
import * as Expensicons from '@components/Icon/Expensicons';
import MenuItem from '@components/MenuItem';
import Popover from '@components/Popover';
import useArrowKeyFocusManager from '@hooks/useArrowKeyFocusManager';
import useKeyboardShortcut from '@hooks/useKeyboardShortcut';
import useLocalize from '@hooks/useLocalize';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useThemeStyles from '@hooks/useThemeStyles';
import * as FileUtils from '@libs/fileDownload/FileUtils';
import CONST from '@src/CONST';
import type {TranslationPaths} from '@src/languages/types';
import type IconAsset from '@src/types/utils/IconAsset';
import launchCamera from './launchCamera/launchCamera';
import type BaseAttachmentPickerProps from './types';
type AttachmentPickerProps = BaseAttachmentPickerProps & {
/** If this value is true, then we exclude Camera option. */
shouldHideCameraOption?: boolean;
};
type Item = {
/** The icon associated with the item. */
icon: IconAsset;
/** The key in the translations file to use for the title */
textTranslationKey: TranslationPaths;
/** Function to call when the user clicks the item */
pickAttachment: () => Promise<Asset[] | void | DocumentPickerResponse[]>;
};
/**
* See https://github.com/react-native-image-picker/react-native-image-picker/#options
* for ImagePicker configuration options
*/
const imagePickerOptions: Partial<CameraOptions | ImageLibraryOptions> = {
includeBase64: false,
saveToPhotos: false,
selectionLimit: 1,
includeExtra: false,
assetRepresentationMode: 'current',
};
/**
* Return imagePickerOptions based on the type
*/
const getImagePickerOptions = (type: string): CameraOptions => {
// mediaType property is one of the ImagePicker configuration to restrict types'
const mediaType = type === CONST.ATTACHMENT_PICKER_TYPE.IMAGE ? 'photo' : 'mixed';
return {
mediaType,
...imagePickerOptions,
};
};
/**
* Return documentPickerOptions based on the type
* @param {String} type
* @returns {Object}
*/
const getDocumentPickerOptions = (type: string): DocumentPickerOptions => {
if (type === CONST.ATTACHMENT_PICKER_TYPE.IMAGE) {
return {
type: [RNDocumentPicker.types.images],
copyTo: 'cachesDirectory',
};
}
return {
type: [RNDocumentPicker.types.allFiles],
copyTo: 'cachesDirectory',
};
};
/**
* The data returned from `show` is different on web and mobile, so use this function to ensure the data we
* send to the xhr will be handled properly.
*/
const getDataForUpload = (fileData: FileResponse): Promise<FileObject> => {
const fileName = fileData.name || 'chat_attachment';
const fileResult: FileObject = {
name: FileUtils.cleanFileName(fileName),
type: fileData.type,
width: fileData.width,
height: fileData.height,
uri: fileData.uri,
size: fileData.size,
};
if (fileResult.size) {
return Promise.resolve(fileResult);
}
return RNFetchBlob.fs.stat(fileData.uri.replace('file://', '')).then((stats) => {
fileResult.size = stats.size;
return fileResult;
});
};
/**
* This component renders a function as a child and
* returns a "show attachment picker" method that takes
* a callback. This is the ios/android implementation
* opening a modal with attachment options
*/
function AttachmentPicker({type = CONST.ATTACHMENT_PICKER_TYPE.FILE, children, shouldHideCameraOption = false, shouldValidateImage = true}: AttachmentPickerProps) {
const styles = useThemeStyles();
const [isVisible, setIsVisible] = useState(false);
const completeAttachmentSelection = useRef<(data: FileObject) => void>(() => {});
const onModalHide = useRef<() => void>();
const onCanceled = useRef<() => void>(() => {});
const popoverRef = useRef(null);
const {translate} = useLocalize();
const {shouldUseNarrowLayout} = useResponsiveLayout();
/**
* A generic handling when we don't know the exact reason for an error
*/
const showGeneralAlert = useCallback(
(message = translate('attachmentPicker.errorWhileSelectingAttachment')) => {
Alert.alert(translate('attachmentPicker.attachmentError'), message);
},
[translate],
);
/**
* Common image picker handling
*
* @param {function} imagePickerFunc - RNImagePicker.launchCamera or RNImagePicker.launchImageLibrary
*/
const showImagePicker = useCallback(
(imagePickerFunc: (options: CameraOptions, callback: Callback) => Promise<ImagePickerResponse>): Promise<Asset[] | void> =>
new Promise((resolve, reject) => {
imagePickerFunc(getImagePickerOptions(type), (response: ImagePickerResponse) => {
if (response.didCancel) {
// When the user cancelled resolve with no attachment
return resolve();
}
if (response.errorCode) {
switch (response.errorCode) {
case 'permission':
FileUtils.showCameraPermissionsAlert();
return resolve();
default:
showGeneralAlert();
break;
}
return reject(new Error(`Error during attachment selection: ${response.errorMessage}`));
}
const targetAsset = response.assets?.[0];
const targetAssetUri = targetAsset?.uri;
if (!targetAssetUri) {
return resolve();
}
if (targetAsset?.type?.startsWith('image')) {
FileUtils.verifyFileFormat({fileUri: targetAssetUri, formatSignatures: CONST.HEIC_SIGNATURES})
.then((isHEIC) => {
// react-native-image-picker incorrectly changes file extension without transcoding the HEIC file, so we are doing it manually if we detect HEIC signature
if (isHEIC && targetAssetUri) {
manipulateAsync(targetAssetUri, [], {format: SaveFormat.JPEG})
.then((manipResult) => {
const uri = manipResult.uri;
const convertedAsset = {
uri,
name: uri
.substring(uri.lastIndexOf('/') + 1)
.split('?')
.at(0),
type: 'image/jpeg',
width: manipResult.width,
height: manipResult.height,
};
return resolve([convertedAsset]);
})
.catch((err) => reject(err));
} else {
return resolve(response.assets);
}
})
.catch((err) => reject(err));
} else {
return resolve(response.assets);
}
});
}),
[showGeneralAlert, type],
);
/**
* Launch the DocumentPicker. Results are in the same format as ImagePicker
*
* @returns {Promise<DocumentPickerResponse[] | void>}
*/
const showDocumentPicker = useCallback(
(): Promise<DocumentPickerResponse[] | void> =>
RNDocumentPicker.pick(getDocumentPickerOptions(type)).catch((error: Error) => {
if (RNDocumentPicker.isCancel(error)) {
return;
}
showGeneralAlert(error.message);
throw error;
}),
[showGeneralAlert, type],
);
const menuItemData: Item[] = useMemo(() => {
const data: Item[] = [
{
icon: Expensicons.Gallery,
textTranslationKey: 'attachmentPicker.chooseFromGallery',
pickAttachment: () => showImagePicker(launchImageLibrary),
},
{
icon: Expensicons.Paperclip,
textTranslationKey: 'attachmentPicker.chooseDocument',
pickAttachment: showDocumentPicker,
},
];
if (!shouldHideCameraOption) {
data.unshift({
icon: Expensicons.Camera,
textTranslationKey: 'attachmentPicker.takePhoto',
pickAttachment: () => showImagePicker(launchCamera),
});
}
return data;
}, [showDocumentPicker, showImagePicker, shouldHideCameraOption]);
const [focusedIndex, setFocusedIndex] = useArrowKeyFocusManager({initialFocusedIndex: -1, maxIndex: menuItemData.length - 1, isActive: isVisible});
/**
* An attachment error dialog when user selected malformed images
*/
const showImageCorruptionAlert = useCallback(() => {
Alert.alert(translate('attachmentPicker.attachmentError'), translate('attachmentPicker.errorWhileSelectingCorruptedAttachment'));
}, [translate]);
/**
* Opens the attachment modal
*
* @param onPickedHandler A callback that will be called with the selected attachment
* @param onCanceledHandler A callback that will be called without a selected attachment
*/
const open = (onPickedHandler: (file: FileObject) => void, onCanceledHandler: () => void = () => {}) => {
// eslint-disable-next-line react-compiler/react-compiler
completeAttachmentSelection.current = onPickedHandler;
onCanceled.current = onCanceledHandler;
setIsVisible(true);
};
/**
* Closes the attachment modal
*/
const close = () => {
setIsVisible(false);
};
const validateAndCompleteAttachmentSelection = useCallback(
(fileData: FileResponse) => {
// Check if the file dimensions indicate corruption
// The width/height for a corrupted file is -1 on android native and 0 on ios native
// We must check only numeric values because the width/height can be undefined for non-image files
if ((typeof fileData.width === 'number' && fileData.width <= 0) || (typeof fileData.height === 'number' && fileData.height <= 0)) {
showImageCorruptionAlert();
return Promise.resolve();
}
return getDataForUpload(fileData)
.then((result) => {
completeAttachmentSelection.current(result);
})
.catch((error: Error) => {
showGeneralAlert(error.message);
throw error;
});
},
[showGeneralAlert, showImageCorruptionAlert],
);
/**
* Handles the image/document picker result and
* sends the selected attachment to the caller (parent component)
*/
const pickAttachment = useCallback(
(attachments: Asset[] | DocumentPickerResponse[] | void = []): Promise<void> | undefined => {
if (!attachments || attachments.length === 0) {
onCanceled.current();
return Promise.resolve();
}
const fileData = attachments[0];
if (!fileData) {
onCanceled.current();
return Promise.resolve();
}
/* eslint-disable @typescript-eslint/prefer-nullish-coalescing */
const fileDataName = ('fileName' in fileData && fileData.fileName) || ('name' in fileData && fileData.name) || '';
const fileDataUri = ('fileCopyUri' in fileData && fileData.fileCopyUri) || ('uri' in fileData && fileData.uri) || '';
const fileDataObject: FileResponse = {
name: fileDataName ?? '',
uri: fileDataUri,
size: ('size' in fileData && fileData.size) || ('fileSize' in fileData && fileData.fileSize) || null,
type: fileData.type ?? '',
width: ('width' in fileData && fileData.width) || undefined,
height: ('height' in fileData && fileData.height) || undefined,
};
if (!shouldValidateImage && fileDataName && Str.isImage(fileDataName)) {
ImageSize.getSize(fileDataUri)
.then(({width, height}) => {
fileDataObject.width = width;
fileDataObject.height = height;
return fileDataObject;
})
.then((file) => {
getDataForUpload(file)
.then((result) => {
completeAttachmentSelection.current(result);
})
.catch((error: Error) => {
showGeneralAlert(error.message);
throw error;
});
});
return;
}
/* eslint-enable @typescript-eslint/prefer-nullish-coalescing */
if (fileDataName && Str.isImage(fileDataName)) {
ImageSize.getSize(fileDataUri)
.then(({width, height}) => {
fileDataObject.width = width;
fileDataObject.height = height;
validateAndCompleteAttachmentSelection(fileDataObject);
})
.catch(() => showImageCorruptionAlert());
} else {
return validateAndCompleteAttachmentSelection(fileDataObject);
}
},
[validateAndCompleteAttachmentSelection, showImageCorruptionAlert, shouldValidateImage, showGeneralAlert],
);
/**
* Setup native attachment selection to start after this popover closes
*
* @param {Object} item - an item from this.menuItemData
* @param {Function} item.pickAttachment
*/
const selectItem = useCallback(
(item: Item) => {
/* setTimeout delays execution to the frame after the modal closes
* without this on iOS closing the modal closes the gallery/camera as well */
onModalHide.current = () => {
setTimeout(() => {
item.pickAttachment()
.then((result) => pickAttachment(result))
.catch(console.error)
.finally(() => delete onModalHide.current);
}, 200);
};
close();
},
[pickAttachment],
);
useKeyboardShortcut(
CONST.KEYBOARD_SHORTCUTS.ENTER,
() => {
if (focusedIndex === -1) {
return;
}
const item = menuItemData.at(focusedIndex);
if (item) {
selectItem(item);
setFocusedIndex(-1); // Reset the focusedIndex on selecting any menu
}
},
{
isActive: isVisible,
},
);
/**
* Call the `children` renderProp with the interface defined in propTypes
*/
const renderChildren = (): React.ReactNode =>
children({
openPicker: ({onPicked, onCanceled: newOnCanceled}) => open(onPicked, newOnCanceled),
});
return (
<>
<Popover
onClose={() => {
close();
onCanceled.current();
}}
isVisible={isVisible}
anchorRef={popoverRef}
onModalHide={onModalHide.current}
>
<View style={!shouldUseNarrowLayout && styles.createMenuContainer}>
{menuItemData.map((item, menuIndex) => (
<MenuItem
key={item.textTranslationKey}
icon={item.icon}
title={translate(item.textTranslationKey)}
onPress={() => selectItem(item)}
focused={focusedIndex === menuIndex}
/>
))}
</View>
</Popover>
{renderChildren()}
</>
);
}
AttachmentPicker.displayName = 'AttachmentPicker';
export default AttachmentPicker;