UNPKG

2.24 kBJavaScriptView Raw
1import React, { PropTypes } from 'react';
2import {
3 NativeModules,
4 Platform,
5 StyleSheet,
6 requireNativeComponent,
7 View,
8} from 'react-native';
9
10const BarCodeScannerManager = (
11 NativeModules.ExponentBarCodeScannerManager ||
12 NativeModules.ExponentBarCodeScannerModule
13);
14
15function convertNativeProps(props) {
16 const newProps = { ...props };
17 if (typeof props.torchMode === 'string') {
18 newProps.torchMode = BarCodeScanner.Constants.TorchMode[props.torchMode];
19 }
20
21 if (typeof props.type === 'string') {
22 newProps.type = BarCodeScanner.Constants.Type[props.type];
23 }
24
25 return newProps;
26}
27
28const EventThrottleMs = 500;
29
30export default class BarCodeScanner extends React.Component {
31 static Constants = {
32 BarCodeType: BarCodeScannerManager.BarCodeType,
33 Type: BarCodeScannerManager.Type,
34 TorchMode: BarCodeScannerManager.TorchMode
35 };
36
37 static propTypes = {
38 ...View.propTypes,
39 onBarCodeRead: PropTypes.func,
40 barCodeTypes: PropTypes.array,
41 torchMode: PropTypes.oneOfType([
42 PropTypes.string,
43 PropTypes.number
44 ]),
45 type: PropTypes.oneOfType([
46 PropTypes.string,
47 PropTypes.number
48 ])
49 };
50
51 static defaultProps = {
52 type: BarCodeScannerManager.Type.back,
53 torchMode: BarCodeScannerManager.TorchMode.off,
54 barCodeTypes: Object.values(BarCodeScannerManager.BarCodeType),
55 };
56
57 setNativeProps(props) {
58 this.refs[CAMERA_REF].setNativeProps(props);
59 }
60
61 render() {
62 const nativeProps = convertNativeProps(this.props);
63
64 return (
65 <ExponentBarCodeScanner
66 {...nativeProps}
67 onBarCodeRead={this._onBarCodeRead}
68 />
69 );
70 }
71
72 _onBarCodeRead = ({nativeEvent}) => {
73 if (this._lastEvent &&
74 JSON.stringify(nativeEvent) === this._lastEvent &&
75 (new Date() - this._lastEventTime) < EventThrottleMs) {
76 return;
77 }
78
79 if (this.props.onBarCodeRead) {
80 this.props.onBarCodeRead(nativeEvent)
81 this._lastEvent = JSON.stringify(nativeEvent);
82 this._lastEventTime = new Date();
83 }
84 };
85}
86
87export const Constants = BarCodeScanner.Constants;
88
89const ExponentBarCodeScanner = requireNativeComponent('ExponentBarCodeScanner', BarCodeScanner, {
90 nativeOnly: {
91 onBarCodeRead: true,
92 },
93});