forked from expo/expo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Camera.tsx
310 lines (254 loc) · 8.92 KB
/
Camera.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
import { UnavailabilityError } from '@unimodules/core';
import mapValues from 'lodash/mapValues';
import PropTypes from 'prop-types';
import React from 'react';
import { findNodeHandle, Platform, ViewPropTypes } from 'react-native';
import {
CapturedPicture,
NativeProps,
PictureOptions,
Props,
RecordingOptions,
PermissionResponse,
} from './Camera.types';
import ExponentCamera from './ExponentCamera';
import _CameraManager from './ExponentCameraManager';
// TODO: Bacon: Fix multiplatform
const CameraManager = _CameraManager as any;
const EventThrottleMs = 500;
const _PICTURE_SAVED_CALLBACKS = {};
let _GLOBAL_PICTURE_ID = 1;
function ensurePictureOptions(options?: PictureOptions): PictureOptions {
let pictureOptions = options || {};
if (!pictureOptions || typeof pictureOptions !== 'object') {
pictureOptions = {};
}
if (!pictureOptions.quality) {
pictureOptions.quality = 1;
}
if (pictureOptions.onPictureSaved) {
const id = _GLOBAL_PICTURE_ID++;
_PICTURE_SAVED_CALLBACKS[id] = pictureOptions.onPictureSaved;
pictureOptions.id = id;
pictureOptions.fastMode = true;
}
return pictureOptions;
}
function ensureRecordingOptions(options?: RecordingOptions): RecordingOptions {
let recordingOptions = options || {};
if (!recordingOptions || typeof recordingOptions !== 'object') {
recordingOptions = {};
} else if (typeof recordingOptions.quality === 'string') {
recordingOptions.quality = Camera.Constants.VideoQuality[recordingOptions.quality];
}
return recordingOptions;
}
function ensureNativeProps(options?: Props): NativeProps {
let props = options || {};
if (!props || typeof props !== 'object') {
props = {};
}
const newProps: NativeProps = mapValues(props, convertProp);
const propsKeys = Object.keys(newProps);
// barCodeTypes is deprecated
if (!propsKeys.includes('barCodeScannerSettings') && propsKeys.includes('barCodeTypes')) {
console.warn(
`The "barCodeTypes" prop for Camera is deprecated and will be removed in SDK 34. Use "barCodeScannerSettings" instead.`
);
newProps.barCodeScannerSettings = {
// @ts-ignore
barCodeTypes: newProps.barCodeTypes,
};
}
if (props.onBarCodeScanned) {
newProps.barCodeScannerEnabled = true;
}
if (props.onFacesDetected) {
newProps.faceDetectorEnabled = true;
}
if (Platform.OS !== 'android') {
delete newProps.ratio;
delete newProps.useCamera2Api;
}
return newProps;
}
function convertProp(value: any, key: string): any {
if (typeof value === 'string' && Camera.ConversionTables[key]) {
return Camera.ConversionTables[key][value];
}
return value;
}
function _onPictureSaved({ nativeEvent }: { nativeEvent: { data: CapturedPicture; id: number } }) {
const { id, data } = nativeEvent;
const callback = _PICTURE_SAVED_CALLBACKS[id];
if (callback) {
callback(data);
delete _PICTURE_SAVED_CALLBACKS[id];
}
}
export default class Camera extends React.Component<Props> {
static async isAvailableAsync(): Promise<boolean> {
if (!CameraManager.isAvailableAsync) {
throw new UnavailabilityError('expo-camera', 'isAvailableAsync');
}
return await CameraManager.isAvailableAsync();
}
static async getAvailableCameraTypesAsync(): Promise<('front' | 'back')[]> {
if (!CameraManager.getAvailableCameraTypesAsync) {
throw new UnavailabilityError('expo-camera', 'getAvailableCameraTypesAsync');
}
return await CameraManager.getAvailableCameraTypesAsync();
}
static Constants = {
Type: CameraManager.Type,
FlashMode: CameraManager.FlashMode,
AutoFocus: CameraManager.AutoFocus,
WhiteBalance: CameraManager.WhiteBalance,
VideoQuality: CameraManager.VideoQuality,
VideoStabilization: CameraManager.VideoStabilization || {},
};
// Values under keys from this object will be transformed to native options
static ConversionTables = {
type: CameraManager.Type,
flashMode: CameraManager.FlashMode,
autoFocus: CameraManager.AutoFocus,
whiteBalance: CameraManager.WhiteBalance,
};
static propTypes = {
...ViewPropTypes,
zoom: PropTypes.number,
ratio: PropTypes.string,
focusDepth: PropTypes.number,
onMountError: PropTypes.func,
pictureSize: PropTypes.string,
onCameraReady: PropTypes.func,
useCamera2Api: PropTypes.bool,
onBarCodeScanned: PropTypes.func,
barCodeScannerSettings: PropTypes.object,
onFacesDetected: PropTypes.func,
faceDetectorSettings: PropTypes.object,
type: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
flashMode: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
videoStabilizationMode: PropTypes.number,
whiteBalance: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
autoFocus: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.bool]),
};
static defaultProps: Props = {
zoom: 0,
ratio: '4:3',
focusDepth: 0,
faceDetectorSettings: {},
type: CameraManager.Type.back,
autoFocus: CameraManager.AutoFocus.on,
flashMode: CameraManager.FlashMode.off,
whiteBalance: CameraManager.WhiteBalance.auto,
};
static async getPermissionsAsync(): Promise<PermissionResponse> {
return CameraManager.getPermissionsAsync();
}
static async requestPermissionsAsync(): Promise<PermissionResponse> {
return CameraManager.requestPermissionsAsync();
}
_cameraHandle?: number | null;
_cameraRef?: React.Component | null;
_lastEvents: { [eventName: string]: string } = {};
_lastEventsTimes: { [eventName: string]: Date } = {};
async takePictureAsync(options?: PictureOptions): Promise<CapturedPicture> {
const pictureOptions = ensurePictureOptions(options);
return await CameraManager.takePicture(pictureOptions, this._cameraHandle);
}
async getSupportedRatiosAsync(): Promise<string[]> {
if (!CameraManager.getSupportedRatios) {
throw new UnavailabilityError('Camera', 'getSupportedRatiosAsync');
}
return await CameraManager.getSupportedRatios(this._cameraHandle);
}
async getAvailablePictureSizesAsync(ratio?: string): Promise<string[]> {
if (!CameraManager.getAvailablePictureSizes) {
throw new UnavailabilityError('Camera', 'getAvailablePictureSizesAsync');
}
return await CameraManager.getAvailablePictureSizes(ratio, this._cameraHandle);
}
async recordAsync(options?: RecordingOptions): Promise<{ uri: string }> {
if (!CameraManager.record) {
throw new UnavailabilityError('Camera', 'recordAsync');
}
const recordingOptions = ensureRecordingOptions(options);
return await CameraManager.record(recordingOptions, this._cameraHandle);
}
stopRecording() {
if (!CameraManager.stopRecording) {
throw new UnavailabilityError('Camera', 'stopRecording');
}
CameraManager.stopRecording(this._cameraHandle);
}
pausePreview() {
if (!CameraManager.pausePreview) {
throw new UnavailabilityError('Camera', 'pausePreview');
}
CameraManager.pausePreview(this._cameraHandle);
}
resumePreview() {
if (!CameraManager.resumePreview) {
throw new UnavailabilityError('Camera', 'resumePreview');
}
CameraManager.resumePreview(this._cameraHandle);
}
_onCameraReady = () => {
if (this.props.onCameraReady) {
this.props.onCameraReady();
}
};
_onMountError = ({ nativeEvent }: { nativeEvent: { message: string } }) => {
if (this.props.onMountError) {
this.props.onMountError(nativeEvent);
}
};
_onObjectDetected = (callback?: Function) => ({ nativeEvent }: { nativeEvent: any }) => {
const { type } = nativeEvent;
if (
this._lastEvents[type] &&
this._lastEventsTimes[type] &&
JSON.stringify(nativeEvent) === this._lastEvents[type] &&
new Date().getTime() - this._lastEventsTimes[type].getTime() < EventThrottleMs
) {
return;
}
if (callback) {
callback(nativeEvent);
this._lastEventsTimes[type] = new Date();
this._lastEvents[type] = JSON.stringify(nativeEvent);
}
};
_setReference = (ref?: React.Component) => {
if (ref) {
this._cameraRef = ref;
// TODO: Bacon: Unify these
if (Platform.OS === 'web') {
this._cameraHandle = ref as any;
} else {
this._cameraHandle = findNodeHandle(ref);
}
} else {
this._cameraRef = null;
this._cameraHandle = null;
}
};
render() {
const nativeProps = ensureNativeProps(this.props);
const onBarCodeScanned = this._onObjectDetected(this.props.onBarCodeScanned);
const onFacesDetected = this._onObjectDetected(this.props.onFacesDetected);
return (
<ExponentCamera
{...nativeProps}
ref={this._setReference}
onCameraReady={this._onCameraReady}
onMountError={this._onMountError}
onBarCodeScanned={onBarCodeScanned}
onFacesDetected={onFacesDetected}
onPictureSaved={_onPictureSaved}
/>
);
}
}
export const { Constants, getPermissionsAsync, requestPermissionsAsync } = Camera;