-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
index.native.js
318 lines (291 loc) · 12.2 KB
/
index.native.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
import {ActivityIndicator, Alert, AppState, Linking, Text, View} from 'react-native';
import React, {useCallback, useEffect, useRef, useState} from 'react';
import {useCameraDevices} from 'react-native-vision-camera';
import lodashGet from 'lodash/get';
import PropTypes from 'prop-types';
import {launchImageLibrary} from 'react-native-image-picker';
import {withOnyx} from 'react-native-onyx';
import {RESULTS} from 'react-native-permissions';
import PressableWithFeedback from '../../../components/Pressable/PressableWithFeedback';
import Icon from '../../../components/Icon';
import * as Expensicons from '../../../components/Icon/Expensicons';
import styles from '../../../styles/styles';
import Shutter from '../../../../assets/images/shutter.svg';
import Hand from '../../../../assets/images/hand.svg';
import * as IOU from '../../../libs/actions/IOU';
import themeColors from '../../../styles/themes/default';
import reportPropTypes from '../../reportPropTypes';
import CONST from '../../../CONST';
import Button from '../../../components/Button';
import useLocalize from '../../../hooks/useLocalize';
import ONYXKEYS from '../../../ONYXKEYS';
import Log from '../../../libs/Log';
import * as CameraPermission from './CameraPermission';
import {iouPropTypes, iouDefaultProps} from '../propTypes';
import NavigationAwareCamera from './NavigationAwareCamera';
const propTypes = {
/** React Navigation route */
route: PropTypes.shape({
/** Params from the route */
params: PropTypes.shape({
/** The type of IOU report, i.e. bill, request, send */
iouType: PropTypes.string,
/** The report ID of the IOU */
reportID: PropTypes.string,
}),
}).isRequired,
/** The report on which the request is initiated on */
report: reportPropTypes,
/** Holds data related to Money Request view state, rather than the underlying Money Request data. */
iou: iouPropTypes,
};
const defaultProps = {
report: {},
iou: iouDefaultProps,
};
/**
* See https://github.com/react-native-image-picker/react-native-image-picker/#options
* for ImagePicker configuration options
*/
const imagePickerOptions = {
includeBase64: false,
saveToPhotos: false,
selectionLimit: 1,
includeExtra: false,
};
/**
* Return imagePickerOptions based on the type
* @param {String} type
* @returns {Object}
*/
function getImagePickerOptions(type) {
// mediaType property is one of the ImagePicker configuration to restrict types'
const mediaType = type === CONST.ATTACHMENT_PICKER_TYPE.IMAGE ? 'photo' : 'mixed';
return {
mediaType,
...imagePickerOptions,
};
}
function ReceiptSelector(props) {
const devices = useCameraDevices('wide-angle-camera');
const device = devices.back;
const camera = useRef(null);
const [flash, setFlash] = useState(false);
const [permissions, setPermissions] = useState('granted');
const isAndroidBlockedPermissionRef = useRef(false);
const appState = useRef(AppState.currentState);
const iouType = lodashGet(props.route, 'params.iouType', '');
const reportID = lodashGet(props.route, 'params.reportID', '');
const pageIndex = lodashGet(props.route, 'params.pageIndex', 1);
const {translate} = useLocalize();
// We want to listen to if the app has come back from background and refresh the permissions status to show camera when permissions were granted
useEffect(() => {
const subscription = AppState.addEventListener('change', (nextAppState) => {
if (appState.current.match(/inactive|background/) && nextAppState === 'active') {
CameraPermission.getCameraPermissionStatus().then((permissionStatus) => {
setPermissions(permissionStatus);
});
}
appState.current = nextAppState;
});
return () => {
subscription.remove();
};
}, []);
/**
* Inform the users when they need to grant camera access and guide them to settings
*/
const showPermissionsAlert = () => {
Alert.alert(
translate('attachmentPicker.cameraPermissionRequired'),
translate('attachmentPicker.expensifyDoesntHaveAccessToCamera'),
[
{
text: translate('common.cancel'),
style: 'cancel',
},
{
text: translate('common.settings'),
onPress: () => Linking.openSettings(),
},
],
{cancelable: false},
);
};
/**
* A generic handling when we don't know the exact reason for an error
*
*/
const showGeneralAlert = () => {
Alert.alert(translate('attachmentPicker.attachmentError'), translate('attachmentPicker.errorWhileSelectingAttachment'));
};
const askForPermissions = () => {
// There's no way we can check for the BLOCKED status without requesting the permission first
// https://github.com/zoontek/react-native-permissions/blob/a836e114ce3a180b2b23916292c79841a267d828/README.md?plain=1#L670
if (permissions === RESULTS.BLOCKED || isAndroidBlockedPermissionRef.current) {
Linking.openSettings();
} else if (permissions === RESULTS.DENIED) {
CameraPermission.requestCameraPermission().then((permissionStatus) => {
setPermissions(permissionStatus);
isAndroidBlockedPermissionRef.current = permissionStatus === RESULTS.BLOCKED;
});
}
};
/**
* Common image picker handling
*
* @param {function} imagePickerFunc - RNImagePicker.launchCamera or RNImagePicker.launchImageLibrary
* @returns {Promise}
*/
const showImagePicker = (imagePickerFunc) =>
new Promise((resolve, reject) => {
imagePickerFunc(getImagePickerOptions(CONST.ATTACHMENT_PICKER_TYPE.IMAGE), (response) => {
if (response.didCancel) {
// When the user cancelled resolve with no attachment
return resolve();
}
if (response.errorCode) {
switch (response.errorCode) {
case 'permission':
showPermissionsAlert();
return resolve();
default:
showGeneralAlert();
break;
}
return reject(new Error(`Error during attachment selection: ${response.errorMessage}`));
}
return resolve(response.assets);
});
});
const takePhoto = useCallback(() => {
const showCameraAlert = () => {
Alert.alert(translate('receipt.cameraErrorTitle'), translate('receipt.cameraErrorMessage'));
};
if (!camera.current) {
showCameraAlert();
return;
}
camera.current
.takePhoto({
qualityPrioritization: 'speed',
flash: flash ? 'on' : 'off',
})
.then((photo) => {
IOU.setMoneyRequestReceipt(`file://${photo.path}`, photo.path);
IOU.navigateToNextPage(props.iou, iouType, reportID, props.report);
})
.catch((error) => {
showCameraAlert();
Log.warn('Error taking photo', error);
});
}, [flash, iouType, props.iou, props.report, reportID, translate]);
CameraPermission.getCameraPermissionStatus().then((permissionStatus) => {
setPermissions(permissionStatus);
});
return (
<View style={styles.flex1}>
{permissions !== RESULTS.GRANTED && (
<View style={[styles.cameraView, styles.permissionView]}>
<Hand
width={CONST.RECEIPT.HAND_ICON_WIDTH}
height={CONST.RECEIPT.HAND_ICON_HEIGHT}
style={[styles.pb5]}
/>
<Text style={[styles.textReceiptUpload]}>{translate('receipt.takePhoto')}</Text>
<Text style={[styles.subTextReceiptUpload]}>{translate('receipt.cameraAccess')}</Text>
<PressableWithFeedback
accessibilityLabel={translate('receipt.givePermission')}
accessibilityRole={CONST.ACCESSIBILITY_ROLE.BUTTON}
>
<Button
medium
success
text={translate('receipt.givePermission')}
style={[styles.p9, styles.pt5]}
onPress={askForPermissions}
/>
</PressableWithFeedback>
</View>
)}
{permissions === RESULTS.GRANTED && device == null && (
<View style={[styles.cameraView]}>
<ActivityIndicator
size={CONST.ACTIVITY_INDICATOR_SIZE.LARGE}
style={[styles.flex1]}
color={themeColors.textSupporting}
/>
</View>
)}
{permissions === RESULTS.GRANTED && device != null && (
<NavigationAwareCamera
ref={camera}
device={device}
style={[styles.cameraView]}
zoom={device.neutralZoom}
photo
cameraTabIndex={pageIndex}
/>
)}
<View style={[styles.flexRow, styles.justifyContentAround, styles.alignItemsCenter, styles.pv3]}>
<PressableWithFeedback
accessibilityRole={CONST.ACCESSIBILITY_ROLE.BUTTON}
accessibilityLabel={translate('receipt.gallery')}
style={[styles.alignItemsStart]}
onPress={() => {
showImagePicker(launchImageLibrary)
.then((receiptImage) => {
IOU.setMoneyRequestReceipt(receiptImage[0].uri, receiptImage[0].fileName);
IOU.navigateToNextPage(props.iou, iouType, reportID, props.report);
})
.catch(() => {
Log.info('User did not select an image from gallery');
});
}}
>
<Icon
height={32}
width={32}
src={Expensicons.Gallery}
fill={themeColors.textSupporting}
/>
</PressableWithFeedback>
<PressableWithFeedback
accessibilityRole={CONST.ACCESSIBILITY_ROLE.BUTTON}
accessibilityLabel={translate('receipt.shutter')}
style={[styles.alignItemsCenter]}
onPress={takePhoto}
>
<Shutter
width={CONST.RECEIPT.SHUTTER_SIZE}
height={CONST.RECEIPT.SHUTTER_SIZE}
/>
</PressableWithFeedback>
<PressableWithFeedback
accessibilityRole={CONST.ACCESSIBILITY_ROLE.BUTTON}
accessibilityLabel={translate('receipt.flash')}
style={[styles.alignItemsEnd]}
onPress={() => setFlash((prevFlash) => !prevFlash)}
>
<Icon
height={32}
width={32}
src={Expensicons.Bolt}
fill={flash ? themeColors.iconHovered : themeColors.textSupporting}
/>
</PressableWithFeedback>
</View>
</View>
);
}
ReceiptSelector.defaultProps = defaultProps;
ReceiptSelector.propTypes = propTypes;
ReceiptSelector.displayName = 'ReceiptSelector';
export default withOnyx({
iou: {
key: ONYXKEYS.IOU,
},
report: {
key: ({route}) => `${ONYXKEYS.COLLECTION.REPORT}${lodashGet(route, 'params.reportID', '')}`,
},
})(ReceiptSelector);