UNPKG

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