-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
AttachmentModal.js
executable file
·415 lines (371 loc) · 15.8 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
import React, {useState, useCallback} from 'react';
import PropTypes from 'prop-types';
import {View, Animated, Keyboard} from 'react-native';
import Str from 'expensify-common/lib/str';
import lodashGet from 'lodash/get';
import lodashExtend from 'lodash/extend';
import _ from 'underscore';
import CONST from '../CONST';
import Modal from './Modal';
import AttachmentView from './Attachments/AttachmentView';
import AttachmentCarousel from './Attachments/AttachmentCarousel';
import useLocalize from '../hooks/useLocalize';
import styles from '../styles/styles';
import * as StyleUtils from '../styles/StyleUtils';
import * as FileUtils from '../libs/fileDownload/FileUtils';
import themeColors from '../styles/themes/default';
import compose from '../libs/compose';
import withWindowDimensions, {windowDimensionsPropTypes} from './withWindowDimensions';
import Button from './Button';
import HeaderWithBackButton from './HeaderWithBackButton';
import fileDownload from '../libs/fileDownload';
import withLocalize, {withLocalizePropTypes} from './withLocalize';
import ConfirmModal from './ConfirmModal';
import HeaderGap from './HeaderGap';
import SafeAreaConsumer from './SafeAreaConsumer';
import addEncryptedAuthTokenToURL from '../libs/addEncryptedAuthTokenToURL';
import reportPropTypes from '../pages/reportPropTypes';
import tryResolveUrlFromApiRoot from '../libs/tryResolveUrlFromApiRoot';
/**
* 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]),
/** 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,
...withLocalizePropTypes,
...windowDimensionsPropTypes,
/** Denotes whether it is a workspace avatar or not */
isWorkspaceAvatar: PropTypes.bool,
};
const defaultProps = {
source: '',
onConfirm: null,
defaultOpen: false,
originalFileName: '',
children: null,
isAuthTokenRequired: false,
allowDownload: false,
headerTitle: null,
report: {},
onModalShow: () => {},
onModalHide: () => {},
onCarouselAttachmentChange: () => {},
isWorkspaceAvatar: false,
};
function AttachmentModal(props) {
const [isModalOpen, setIsModalOpen] = useState(props.defaultOpen);
const [shouldLoadAttachment, setShouldLoadAttachment] = useState(false);
const [isAttachmentInvalid, setIsAttachmentInvalid] = useState(false);
const [isAuthTokenRequired, setIsAuthTokenRequired] = useState(props.isAuthTokenRequired);
const [isAttachmentReceipt, setIsAttachmentReceipt] = useState(false);
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 [shouldShowDownloadButton, setShouldShowDownloadButton] = React.useState(true);
const [file, setFile] = useState(
props.originalFileName
? {
name: props.originalFileName,
}
: undefined,
);
const {translate} = useLocalize();
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);
setIsAttachmentReceipt(attachment.isReceipt);
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(
(shouldShowButton) => {
if (shouldShowDownloadButton === shouldShowButton) {
return;
}
setShouldShowDownloadButton(shouldShowButton);
},
[shouldShowDownloadButton],
);
/**
* Download the currently viewed attachment.
*/
const downloadAttachment = useCallback(() => {
let sourceURL = source;
if (isAuthTokenRequired) {
sourceURL = addEncryptedAuthTokenToURL(sourceURL);
}
fileDownload(sourceURL, 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 modal.
*/
const closeConfirmModal = useCallback(() => {
setIsAttachmentInvalid(false);
}, []);
/**
* @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: true,
}).start();
},
[confirmButtonFadeAnimation],
);
/**
* close the modal
*/
const closeModal = useCallback(() => {
setIsModalOpen(false);
}, []);
/**
* open the modal
*/
const openModal = useCallback(() => {
setIsModalOpen(true);
}, []);
const sourceForAttachmentView = props.source || source;
return (
<>
<Modal
type={modalType}
onSubmit={submitAndClose}
onClose={closeModal}
isVisible={isModalOpen}
backgroundColor={themeColors.componentBG}
onModalShow={() => {
props.onModalShow();
setShouldLoadAttachment(true);
}}
onModalHide={(e) => {
props.onModalHide(e);
setShouldLoadAttachment(false);
}}
propagateSwipe
>
{props.isSmallScreenWidth && <HeaderGap />}
<HeaderWithBackButton
title={props.headerTitle || translate(isAttachmentReceipt ? 'common.receipt' : 'common.attachment')}
shouldShowBorderBottom
shouldShowDownloadButton={props.allowDownload && shouldShowDownloadButton}
onDownloadButtonPress={() => downloadAttachment(source)}
shouldShowCloseButton={!props.isSmallScreenWidth}
shouldShowBackButton={props.isSmallScreenWidth}
onBackButtonPress={closeModal}
onCloseButtonPress={closeModal}
/>
<View style={styles.imageModalImageCenterContainer}>
{!_.isEmpty(props.report) ? (
<AttachmentCarousel
report={props.report}
onNavigate={onNavigate}
source={tryResolveUrlFromApiRoot(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}
/>
)
)}
</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>
)}
</Modal>
<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)(AttachmentModal);