-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
AttachmentModal.js
executable file
·334 lines (297 loc) · 12.6 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
import React, {PureComponent} 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 './AttachmentView';
import AttachmentCarousel from './AttachmentCarousel';
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 HeaderWithCloseButton from './HeaderWithCloseButton';
import fileDownload from '../libs/fileDownload';
import withLocalize, {withLocalizePropTypes} from './withLocalize';
import ConfirmModal from './ConfirmModal';
import HeaderGap from './HeaderGap';
import SafeAreaConsumer from './SafeAreaConsumer';
/**
* 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,
/** Optional callback to fire when we want to do something after modal hide. */
onModalHide: PropTypes.func,
/** Optional original filename when uploading */
originalFileName: PropTypes.string,
/** A function as a child to pass modal launching methods to */
children: PropTypes.func.isRequired,
/** 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 ID of the report that has this attachment */
reportID: PropTypes.string,
...withLocalizePropTypes,
...windowDimensionsPropTypes,
};
const defaultProps = {
source: '',
onConfirm: null,
originalFileName: '',
isAuthTokenRequired: false,
allowDownload: false,
headerTitle: null,
reportID: '',
onModalHide: () => {},
};
class AttachmentModal extends PureComponent {
constructor(props) {
super(props);
this.state = {
isModalOpen: false,
shouldLoadAttachment: false,
isAttachmentInvalid: false,
attachmentInvalidReasonTitle: null,
attachmentInvalidReason: null,
source: props.source,
modalType: CONST.MODAL.MODAL_TYPE.CENTERED_UNSWIPEABLE,
isConfirmButtonDisabled: false,
confirmButtonFadeAnimation: new Animated.Value(1),
};
this.submitAndClose = this.submitAndClose.bind(this);
this.closeConfirmModal = this.closeConfirmModal.bind(this);
this.onNavigate = this.onNavigate.bind(this);
this.validateAndDisplayFileToUpload = this.validateAndDisplayFileToUpload.bind(this);
this.updateConfirmButtonVisibility = this.updateConfirmButtonVisibility.bind(this);
}
/**
* Helps to navigate between next/previous attachments
* by setting sourceURL and file in state
* @param {Object} attachmentData
*/
onNavigate(attachmentData) {
this.setState(attachmentData);
}
/**
* If our attachment is a PDF, return the unswipeable Modal type.
* @param {String} sourceURL
* @param {Object} file
* @returns {String}
*/
getModalType(sourceURL, file) {
return (
sourceURL
&& (
Str.isPDF(sourceURL)
|| (
file
&& Str.isPDF(file.name || this.props.translate('attachmentView.unknownFilename'))
)
)
)
? CONST.MODAL.MODAL_TYPE.CENTERED_UNSWIPEABLE
: CONST.MODAL.MODAL_TYPE.CENTERED;
}
/**
* @param {String} sourceURL
*/
downloadAttachment(sourceURL) {
const originalFileName = lodashGet(this.state, 'file.name') || this.props.originalFileName;
fileDownload(sourceURL, originalFileName);
// 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();
}
/**
* Execute the onConfirm callback and close the modal.
*/
submitAndClose() {
// If the modal has already been closed or the confirm button is disabled
// do not submit.
if (!this.state.isModalOpen || this.state.isConfirmButtonDisabled) {
return;
}
if (this.props.onConfirm) {
this.props.onConfirm(lodashExtend(this.state.file, {source: this.state.source}));
}
this.setState({isModalOpen: false});
}
/**
* Close the confirm modal.
*/
closeConfirmModal() {
this.setState({isAttachmentInvalid: false});
}
/**
* @param {Object} file
* @returns {Boolean}
*/
isValidFile(file) {
const {fileExtension} = FileUtils.splitExtensionFromFileName(lodashGet(file, 'name', ''));
if (!_.contains(CONST.API_ATTACHMENT_VALIDATIONS.ALLOWED_EXTENSIONS, fileExtension.toLowerCase())) {
const invalidReason = `${this.props.translate('attachmentPicker.notAllowedExtension')} ${CONST.API_ATTACHMENT_VALIDATIONS.ALLOWED_EXTENSIONS.join(', ')}`;
this.setState({
isAttachmentInvalid: true,
attachmentInvalidReasonTitle: this.props.translate('attachmentPicker.wrongFileType'),
attachmentInvalidReason: invalidReason,
});
return false;
}
if (lodashGet(file, 'size', 0) > CONST.API_ATTACHMENT_VALIDATIONS.MAX_SIZE) {
this.setState({
isAttachmentInvalid: true,
attachmentInvalidReasonTitle: this.props.translate('attachmentPicker.attachmentTooLarge'),
attachmentInvalidReason: this.props.translate('attachmentPicker.sizeExceeded'),
});
return false;
}
if (lodashGet(file, 'size', 0) < CONST.API_ATTACHMENT_VALIDATIONS.MIN_SIZE) {
this.setState({
isAttachmentInvalid: true,
attachmentInvalidReasonTitle: this.props.translate('attachmentPicker.attachmentTooSmall'),
attachmentInvalidReason: this.props.translate('attachmentPicker.sizeNotMet'),
});
return false;
}
return true;
}
/**
* @param {Object} file
*/
validateAndDisplayFileToUpload(file) {
if (!file) {
return;
}
if (!this.isValidFile(file)) {
return;
}
if (file instanceof File) {
const source = URL.createObjectURL(file);
const modalType = this.getModalType(source, file);
this.setState({
isModalOpen: true, source, file, modalType,
});
} else {
const modalType = this.getModalType(file.uri, file);
this.setState({
isModalOpen: true, source: file.uri, file, modalType,
});
}
}
/**
* 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.
*/
updateConfirmButtonVisibility(shouldFadeOut) {
this.setState({isConfirmButtonDisabled: shouldFadeOut});
const toValue = shouldFadeOut ? 0 : 1;
Animated.timing(this.state.confirmButtonFadeAnimation, {
toValue,
duration: 100,
useNativeDriver: true,
}).start();
}
render() {
const source = this.state.source;
return (
<>
<Modal
type={this.state.modalType}
onSubmit={this.submitAndClose}
onClose={() => this.setState({isModalOpen: false})}
isVisible={this.state.isModalOpen}
backgroundColor={themeColors.componentBG}
onModalShow={() => this.setState({shouldLoadAttachment: true})}
onModalHide={(e) => {
this.props.onModalHide(e);
this.setState({shouldLoadAttachment: false});
}}
propagateSwipe
>
{this.props.isSmallScreenWidth && <HeaderGap />}
<HeaderWithCloseButton
title={this.props.headerTitle || this.props.translate('common.attachment')}
shouldShowBorderBottom
shouldShowDownloadButton={this.props.allowDownload}
onDownloadButtonPress={() => this.downloadAttachment(source)}
onCloseButtonPress={() => this.setState({isModalOpen: false})}
/>
<View style={styles.imageModalImageCenterContainer}>
{this.props.reportID ? (
<AttachmentCarousel
reportID={this.props.reportID}
onNavigate={this.onNavigate}
source={this.props.source}
onToggleKeyboard={this.updateConfirmButtonVisibility}
/>
) : Boolean(this.state.source) && this.state.shouldLoadAttachment && (
<AttachmentView
source={source}
isAuthTokenRequired={this.props.isAuthTokenRequired}
file={this.state.file}
onToggleKeyboard={this.updateConfirmButtonVisibility}
/>
)}
</View>
{/* If we have an onConfirm method show a confirmation button */}
{Boolean(this.props.onConfirm) && (
<SafeAreaConsumer>
{({safeAreaPaddingBottomStyle}) => (
<Animated.View style={[StyleUtils.fade(this.state.confirmButtonFadeAnimation), safeAreaPaddingBottomStyle]}>
<Button
success
style={[styles.buttonConfirm, this.props.isSmallScreenWidth ? {} : styles.attachmentButtonBigScreen]}
textStyles={[styles.buttonConfirmText]}
text={this.props.translate('common.send')}
onPress={this.submitAndClose}
disabled={this.state.isConfirmButtonDisabled}
pressOnEnter
/>
</Animated.View>
)}
</SafeAreaConsumer>
)}
</Modal>
<ConfirmModal
title={this.state.attachmentInvalidReasonTitle}
onConfirm={this.closeConfirmModal}
onCancel={this.closeConfirmModal}
isVisible={this.state.isAttachmentInvalid}
prompt={this.state.attachmentInvalidReason}
confirmText={this.props.translate('common.close')}
shouldShowCancelButton={false}
/>
{this.props.children({
displayFileInModal: this.validateAndDisplayFileToUpload,
show: () => {
this.setState({isModalOpen: true});
},
})}
</>
);
}
}
AttachmentModal.propTypes = propTypes;
AttachmentModal.defaultProps = defaultProps;
export default compose(
withWindowDimensions,
withLocalize,
)(AttachmentModal);