-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
AttachmentModal.js
executable file
·556 lines (504 loc) · 22.5 KB
/
AttachmentModal.js
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
import Str from 'expensify-common/lib/str';
import lodashExtend from 'lodash/extend';
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
import React, {useCallback, useEffect, useMemo, useState} from 'react';
import {Animated, Keyboard, View} from 'react-native';
import {GestureHandlerRootView} from 'react-native-gesture-handler';
import {withOnyx} from 'react-native-onyx';
import _ from 'underscore';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import useWindowDimensions from '@hooks/useWindowDimensions';
import addEncryptedAuthTokenToURL from '@libs/addEncryptedAuthTokenToURL';
import compose from '@libs/compose';
import fileDownload from '@libs/fileDownload';
import * as FileUtils from '@libs/fileDownload/FileUtils';
import Navigation from '@libs/Navigation/Navigation';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as ReportUtils from '@libs/ReportUtils';
import * as TransactionUtils from '@libs/TransactionUtils';
import useNativeDriver from '@libs/useNativeDriver';
import reportPropTypes from '@pages/reportPropTypes';
import * as IOU from '@userActions/IOU';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';
import AttachmentCarousel from './Attachments/AttachmentCarousel';
import AttachmentView from './Attachments/AttachmentView';
import Button from './Button';
import ConfirmModal from './ConfirmModal';
import HeaderGap from './HeaderGap';
import HeaderWithBackButton from './HeaderWithBackButton';
import * as Expensicons from './Icon/Expensicons';
import Modal from './Modal';
import SafeAreaConsumer from './SafeAreaConsumer';
import transactionPropTypes from './transactionPropTypes';
import withLocalize, {withLocalizePropTypes} from './withLocalize';
import withWindowDimensions, {windowDimensionsPropTypes} from './withWindowDimensions';
/**
* Modal render prop component that exposes modal launching triggers that can be used
* to display a full size image or PDF modally with optional confirmation button.
*/
const propTypes = {
/** Optional source (URL, SVG function) for the image shown. If not passed in via props must be specified when modal is opened. */
source: PropTypes.oneOfType([PropTypes.string, PropTypes.func, PropTypes.number]),
/** Optional callback to fire when we want to preview an image and approve it for use. */
onConfirm: PropTypes.func,
/** Whether the modal should be open by default */
defaultOpen: PropTypes.bool,
/** Optional callback to fire when we want to do something after modal show. */
onModalShow: PropTypes.func,
/** Optional callback to fire when we want to do something after modal hide. */
onModalHide: PropTypes.func,
/** Optional callback to fire when we want to do something after attachment carousel changes. */
onCarouselAttachmentChange: PropTypes.func,
/** Optional original filename when uploading */
originalFileName: PropTypes.string,
/** A function as a child to pass modal launching methods to */
children: PropTypes.func,
/** Whether source url requires authentication */
isAuthTokenRequired: PropTypes.bool,
/** Determines if download Button should be shown or not */
allowDownload: PropTypes.bool,
/** Title shown in the header of the modal */
headerTitle: PropTypes.string,
/** The report that has this attachment */
report: reportPropTypes,
/** The transaction associated with the receipt attachment, if any */
transaction: transactionPropTypes,
...withLocalizePropTypes,
...windowDimensionsPropTypes,
/** Denotes whether it is a workspace avatar or not */
isWorkspaceAvatar: PropTypes.bool,
/** Whether it is a receipt attachment or not */
isReceiptAttachment: PropTypes.bool,
};
const defaultProps = {
source: '',
onConfirm: null,
defaultOpen: false,
originalFileName: '',
children: null,
isAuthTokenRequired: false,
allowDownload: false,
headerTitle: null,
report: {},
transaction: {},
onModalShow: () => {},
onModalHide: () => {},
onCarouselAttachmentChange: () => {},
isWorkspaceAvatar: false,
isReceiptAttachment: false,
};
function AttachmentModal(props) {
const theme = useTheme();
const styles = useThemeStyles();
const StyleUtils = useStyleUtils();
const [isModalOpen, setIsModalOpen] = useState(props.defaultOpen);
const [shouldLoadAttachment, setShouldLoadAttachment] = useState(false);
const [isAttachmentInvalid, setIsAttachmentInvalid] = useState(false);
const [isDeleteReceiptConfirmModalVisible, setIsDeleteReceiptConfirmModalVisible] = useState(false);
const [isAuthTokenRequired, setIsAuthTokenRequired] = useState(props.isAuthTokenRequired);
const [attachmentInvalidReasonTitle, setAttachmentInvalidReasonTitle] = useState('');
const [attachmentInvalidReason, setAttachmentInvalidReason] = useState(null);
const [source, setSource] = useState(props.source);
const [modalType, setModalType] = useState(CONST.MODAL.MODAL_TYPE.CENTERED_UNSWIPEABLE);
const [isConfirmButtonDisabled, setIsConfirmButtonDisabled] = useState(false);
const [confirmButtonFadeAnimation] = useState(() => new Animated.Value(1));
const [isDownloadButtonReadyToBeShown, setIsDownloadButtonReadyToBeShown] = React.useState(true);
const {windowWidth} = useWindowDimensions();
const isOverlayModalVisible = (props.isReceiptAttachment && isDeleteReceiptConfirmModalVisible) || (!props.isReceiptAttachment && isAttachmentInvalid);
const [file, setFile] = useState(
props.originalFileName
? {
name: props.originalFileName,
}
: undefined,
);
const {translate} = useLocalize();
const {isOffline} = useNetwork();
useEffect(() => {
setFile(props.originalFileName ? {name: props.originalFileName} : undefined);
}, [props.originalFileName]);
const onCarouselAttachmentChange = props.onCarouselAttachmentChange;
/**
* Keeps the attachment source in sync with the attachment displayed currently in the carousel.
* @param {{ source: String, isAuthTokenRequired: Boolean, file: { name: string }, isReceipt: Boolean }} attachment
*/
const onNavigate = useCallback(
(attachment) => {
setSource(attachment.source);
setFile(attachment.file);
setIsAuthTokenRequired(attachment.isAuthTokenRequired);
onCarouselAttachmentChange(attachment);
},
[onCarouselAttachmentChange],
);
/**
* If our attachment is a PDF, return the unswipeable Modal type.
* @param {String} sourceURL
* @param {Object} _file
* @returns {String}
*/
const getModalType = useCallback(
(sourceURL, _file) =>
sourceURL && (Str.isPDF(sourceURL) || (_file && Str.isPDF(_file.name || translate('attachmentView.unknownFilename'))))
? CONST.MODAL.MODAL_TYPE.CENTERED_UNSWIPEABLE
: CONST.MODAL.MODAL_TYPE.CENTERED,
[translate],
);
const setDownloadButtonVisibility = useCallback(
(isButtonVisible) => {
if (isDownloadButtonReadyToBeShown === isButtonVisible) {
return;
}
setIsDownloadButtonReadyToBeShown(isButtonVisible);
},
[isDownloadButtonReadyToBeShown],
);
/**
* Download the currently viewed attachment.
*/
const downloadAttachment = useCallback(() => {
let sourceURL = source;
if (isAuthTokenRequired) {
sourceURL = addEncryptedAuthTokenToURL(sourceURL);
}
fileDownload(sourceURL, lodashGet(file, 'name', ''));
// At ios, if the keyboard is open while opening the attachment, then after downloading
// the attachment keyboard will show up. So, to fix it we need to dismiss the keyboard.
Keyboard.dismiss();
}, [isAuthTokenRequired, source, file]);
/**
* Execute the onConfirm callback and close the modal.
*/
const submitAndClose = useCallback(() => {
// If the modal has already been closed or the confirm button is disabled
// do not submit.
if (!isModalOpen || isConfirmButtonDisabled) {
return;
}
if (props.onConfirm) {
props.onConfirm(lodashExtend(file, {source}));
}
setIsModalOpen(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isModalOpen, isConfirmButtonDisabled, props.onConfirm, file, source]);
/**
* Close the confirm modals.
*/
const closeConfirmModal = useCallback(() => {
setIsAttachmentInvalid(false);
setIsDeleteReceiptConfirmModalVisible(false);
}, []);
/**
* Detach the receipt and close the modal.
*/
const deleteAndCloseModal = useCallback(() => {
IOU.detachReceipt(props.transaction.transactionID, props.report.reportID);
setIsDeleteReceiptConfirmModalVisible(false);
Navigation.dismissModal(props.report.reportID);
}, [props.transaction, props.report]);
/**
* @param {Object} _file
* @returns {Boolean}
*/
const isValidFile = useCallback((_file) => {
if (lodashGet(_file, 'size', 0) > CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE) {
setIsAttachmentInvalid(true);
setAttachmentInvalidReasonTitle('attachmentPicker.attachmentTooLarge');
setAttachmentInvalidReason('attachmentPicker.sizeExceeded');
return false;
}
if (lodashGet(_file, 'size', 0) < CONST.API_ATTACHMENT_VALIDATIONS.MIN_SIZE) {
setIsAttachmentInvalid(true);
setAttachmentInvalidReasonTitle('attachmentPicker.attachmentTooSmall');
setAttachmentInvalidReason('attachmentPicker.sizeNotMet');
return false;
}
return true;
}, []);
/**
* @param {Object} _data
* @returns {Boolean}
*/
const isDirectoryCheck = useCallback((_data) => {
if (typeof _data.webkitGetAsEntry === 'function' && _data.webkitGetAsEntry().isDirectory) {
setIsAttachmentInvalid(true);
setAttachmentInvalidReasonTitle('attachmentPicker.attachmentError');
setAttachmentInvalidReason('attachmentPicker.folderNotAllowedMessage');
return false;
}
return true;
}, []);
/**
* @param {Object} _data
*/
const validateAndDisplayFileToUpload = useCallback(
(_data) => {
if (!isDirectoryCheck(_data)) {
return;
}
let fileObject = _data;
if (typeof _data.getAsFile === 'function') {
fileObject = _data.getAsFile();
}
if (!fileObject) {
return;
}
if (!isValidFile(fileObject)) {
return;
}
if (fileObject instanceof File) {
/**
* Cleaning file name, done here so that it covers all cases:
* upload, drag and drop, copy-paste
*/
let updatedFile = fileObject;
const cleanName = FileUtils.cleanFileName(updatedFile.name);
if (updatedFile.name !== cleanName) {
updatedFile = new File([updatedFile], cleanName, {type: updatedFile.type});
}
const inputSource = URL.createObjectURL(updatedFile);
const inputModalType = getModalType(inputSource, updatedFile);
setIsModalOpen(true);
setSource(inputSource);
setFile(updatedFile);
setModalType(inputModalType);
} else {
const inputModalType = getModalType(fileObject.uri, fileObject);
setIsModalOpen(true);
setSource(fileObject.uri);
setFile(fileObject);
setModalType(inputModalType);
}
},
[isValidFile, getModalType, isDirectoryCheck],
);
/**
* In order to gracefully hide/show the confirm button when the keyboard
* opens/closes, apply an animation to fade the confirm button out/in. And since
* we're only updating the opacity of the confirm button, we must also conditionally
* disable it.
*
* @param {Boolean} shouldFadeOut If true, fade out confirm button. Otherwise fade in.
*/
const updateConfirmButtonVisibility = useCallback(
(shouldFadeOut) => {
setIsConfirmButtonDisabled(shouldFadeOut);
const toValue = shouldFadeOut ? 0 : 1;
Animated.timing(confirmButtonFadeAnimation, {
toValue,
duration: 100,
useNativeDriver,
}).start();
},
[confirmButtonFadeAnimation],
);
/**
* close the modal
*/
const closeModal = useCallback(() => {
setIsModalOpen(false);
}, []);
/**
* open the modal
*/
const openModal = useCallback(() => {
setIsModalOpen(true);
}, []);
const sourceForAttachmentView = props.source || source;
const threeDotsMenuItems = useMemo(() => {
if (!props.isReceiptAttachment || !props.parentReport || !props.parentReportActions) {
return [];
}
const menuItems = [];
const parentReportAction = props.parentReportActions[props.report.parentReportActionID];
const canEdit =
ReportUtils.canEditFieldOfMoneyRequest(parentReportAction, props.parentReport.reportID, CONST.EDIT_REQUEST_FIELD.RECEIPT) &&
!TransactionUtils.isDistanceRequest(props.transaction);
if (canEdit) {
menuItems.push({
icon: Expensicons.Camera,
text: props.translate('common.replace'),
onSelected: () => {
closeModal();
Navigation.navigate(ROUTES.EDIT_REQUEST.getRoute(props.report.reportID, CONST.EDIT_REQUEST_FIELD.RECEIPT));
},
});
}
menuItems.push({
icon: Expensicons.Download,
text: props.translate('common.download'),
onSelected: () => downloadAttachment(source),
});
if (TransactionUtils.hasReceipt(props.transaction) && !TransactionUtils.isReceiptBeingScanned(props.transaction) && canEdit) {
menuItems.push({
icon: Expensicons.Trashcan,
text: props.translate('receipt.deleteReceipt'),
onSelected: () => {
setIsDeleteReceiptConfirmModalVisible(true);
},
});
}
return menuItems;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.isReceiptAttachment, props.parentReport, props.parentReportActions, props.policy, props.transaction, file]);
// There are a few things that shouldn't be set until we absolutely know if the file is a receipt or an attachment.
// props.isReceiptAttachment will be null until its certain what the file is, in which case it will then be true|false.
let headerTitle = props.headerTitle;
let shouldShowDownloadButton = false;
let shouldShowThreeDotsButton = false;
if (!_.isEmpty(props.report)) {
headerTitle = translate(props.isReceiptAttachment ? 'common.receipt' : 'common.attachment');
shouldShowDownloadButton = props.allowDownload && isDownloadButtonReadyToBeShown && !props.isReceiptAttachment && !isOffline;
shouldShowThreeDotsButton = props.isReceiptAttachment && isModalOpen;
}
return (
<>
<Modal
type={modalType}
onSubmit={submitAndClose}
onClose={isOverlayModalVisible ? closeConfirmModal : closeModal}
isVisible={isModalOpen}
backgroundColor={theme.componentBG}
onModalShow={() => {
props.onModalShow();
setShouldLoadAttachment(true);
}}
onModalHide={(e) => {
props.onModalHide(e);
setShouldLoadAttachment(false);
}}
propagateSwipe
>
<GestureHandlerRootView style={styles.flex1}>
{props.isSmallScreenWidth && <HeaderGap />}
<HeaderWithBackButton
title={headerTitle}
shouldShowBorderBottom
shouldShowDownloadButton={shouldShowDownloadButton}
onDownloadButtonPress={() => downloadAttachment(source)}
shouldShowCloseButton={!props.isSmallScreenWidth}
shouldShowBackButton={props.isSmallScreenWidth}
onBackButtonPress={closeModal}
onCloseButtonPress={closeModal}
shouldShowThreeDotsButton={shouldShowThreeDotsButton}
threeDotsAnchorPosition={styles.threeDotsPopoverOffsetAttachmentModal(windowWidth)}
threeDotsMenuItems={threeDotsMenuItems}
shouldOverlay
/>
<View style={styles.imageModalImageCenterContainer}>
{!_.isEmpty(props.report) && !props.isReceiptAttachment ? (
<AttachmentCarousel
report={props.report}
onNavigate={onNavigate}
source={props.source}
onClose={closeModal}
onToggleKeyboard={updateConfirmButtonVisibility}
setDownloadButtonVisibility={setDownloadButtonVisibility}
/>
) : (
Boolean(sourceForAttachmentView) &&
shouldLoadAttachment && (
<AttachmentView
containerStyles={[styles.mh5]}
source={sourceForAttachmentView}
isAuthTokenRequired={isAuthTokenRequired}
file={file}
onToggleKeyboard={updateConfirmButtonVisibility}
isWorkspaceAvatar={props.isWorkspaceAvatar}
fallbackSource={props.fallbackSource}
isUsedInAttachmentModal
transactionID={props.transaction.transactionID}
/>
)
)}
</View>
{/* If we have an onConfirm method show a confirmation button */}
{Boolean(props.onConfirm) && (
<SafeAreaConsumer>
{({safeAreaPaddingBottomStyle}) => (
<Animated.View style={[StyleUtils.fade(confirmButtonFadeAnimation), safeAreaPaddingBottomStyle]}>
<Button
success
style={[styles.buttonConfirm, props.isSmallScreenWidth ? {} : styles.attachmentButtonBigScreen]}
textStyles={[styles.buttonConfirmText]}
text={translate('common.send')}
onPress={submitAndClose}
disabled={isConfirmButtonDisabled}
pressOnEnter
/>
</Animated.View>
)}
</SafeAreaConsumer>
)}
{props.isReceiptAttachment && (
<ConfirmModal
title={translate('receipt.deleteReceipt')}
isVisible={isDeleteReceiptConfirmModalVisible}
onConfirm={deleteAndCloseModal}
onCancel={closeConfirmModal}
prompt={translate('receipt.deleteConfirmation')}
confirmText={translate('common.delete')}
cancelText={translate('common.cancel')}
danger
/>
)}
</GestureHandlerRootView>
</Modal>
{!props.isReceiptAttachment && (
<ConfirmModal
title={attachmentInvalidReasonTitle ? translate(attachmentInvalidReasonTitle) : ''}
onConfirm={closeConfirmModal}
onCancel={closeConfirmModal}
isVisible={isAttachmentInvalid}
prompt={attachmentInvalidReason ? translate(attachmentInvalidReason) : ''}
confirmText={translate('common.close')}
shouldShowCancelButton={false}
/>
)}
{props.children &&
props.children({
displayFileInModal: validateAndDisplayFileToUpload,
show: openModal,
})}
</>
);
}
AttachmentModal.propTypes = propTypes;
AttachmentModal.defaultProps = defaultProps;
AttachmentModal.displayName = 'AttachmentModal';
export default compose(
withWindowDimensions,
withLocalize,
withOnyx({
transaction: {
key: ({report}) => {
if (!report) {
return undefined;
}
const parentReportAction = ReportActionsUtils.getReportAction(report.parentReportID, report.parentReportActionID);
const transactionID = lodashGet(parentReportAction, ['originalMessage', 'IOUTransactionID'], 0);
return `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`;
},
},
parentReport: {
key: ({report}) => `${ONYXKEYS.COLLECTION.REPORT}${report ? report.parentReportID : '0'}`,
},
policy: {
key: ({report}) => `${ONYXKEYS.COLLECTION.POLICY}${report ? report.policyID : '0'}`,
},
parentReportActions: {
key: ({report}) => `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report ? report.parentReportID : '0'}`,
canEvict: false,
},
session: {
key: ONYXKEYS.SESSION,
},
}),
)(AttachmentModal);