UNPKG

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