UNPKG

@thewirv/react-barcode-scanner

Version:

A React component for scanning QR codes and other barcodes via webcam

142 lines (130 loc) 6.53 kB
'use strict'; var jsxRuntime = require('react/jsx-runtime'); var react = require('react'); var fi = require('react-icons/fi'); var browser = require('@zxing/browser'); var library = require('@zxing/library'); const styles = { barcodeScannerError: { border: '8px #eee solid', borderRadius: '10px', padding: '2rem', }, barcodeScannerErrorSvg: { width: '75%', height: '75%', display: 'block', opacity: 0.2, margin: '0 auto', }, container: { width: '100%', paddingTop: '100%', overflow: 'hidden', position: 'relative', display: 'none', }, barcodeScannerVisible: { display: 'block', }, video: { top: 0, left: 0, width: '100%', height: '100%', display: 'block', overflow: 'hidden', position: 'absolute', transform: undefined, }, }; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; function decodeBarcodeFromConstraints(codeReader_1, videoElement_1, _a) { return __awaiter(this, arguments, void 0, function* (codeReader, videoElement, { constraints, onSuccess, onError }) { if (!videoElement.current) return; try { const result = yield codeReader.decodeOnceFromConstraints({ audio: false, video: constraints, preferCurrentTab: true }, videoElement.current); onSuccess(result.getText()); } catch (error) { if (error && !(error instanceof library.NotFoundException || error instanceof library.ChecksumException || error instanceof library.FormatException)) { onError(error); } } }); } function BarcodeScanner({ doScan = true, constraints = { facingMode: 'environment' }, onSuccess, onError, onLoad, Viewfinder, containerStyle, videoContainerStyle, videoStyle, videoProps: passedVideoProps, }) { const [isCameraInitialized, setIsCameraInitialized] = react.useState(false); const codeReader = react.useMemo(() => new browser.BrowserMultiFormatReader(), []); const videoElement = react.useRef(null); const isShowingDisabledImage = !isCameraInitialized || !doScan; react.useEffect(() => { if (!doScan) return; if (!(navigator === null || navigator === void 0 ? void 0 : navigator.mediaDevices)) { const message = 'Your browser has no support for the MediaDevices API. You could fix this by running "npm i webrtc-adapter"'; console.warn(`[ReactBarcodeScanner]: ${message}`); onError(new Error(message)); return; } void decodeBarcodeFromConstraints(codeReader, videoElement, { constraints, onSuccess, onError, }); }, [onSuccess, onError, doScan, codeReader, constraints]); const videoProps = react.useMemo(() => { var _a; const onLoadedData = ({ nativeEvent }) => { const eventTarget = nativeEvent.target; if (!(eventTarget === null || eventTarget === void 0 ? void 0 : eventTarget.readyState)) return; if (eventTarget.readyState === eventTarget.HAVE_ENOUGH_DATA) { setIsCameraInitialized(true); onLoad === null || onLoad === void 0 ? void 0 : onLoad(); } }; const defaultVideoProps = { playsInline: true, disablePictureInPicture: true, muted: true, onLoadedData, style: Object.assign(Object.assign(Object.assign({}, styles.video), videoStyle), { transform: `${(_a = videoStyle === null || videoStyle === void 0 ? void 0 : videoStyle.transform) !== null && _a !== void 0 ? _a : ''} ${constraints.facingMode === 'user' ? 'scaleX(-1)' : ''}` }), }; if (!passedVideoProps) return defaultVideoProps; if (typeof passedVideoProps !== 'function') return passedVideoProps; return passedVideoProps(defaultVideoProps); }, [constraints.facingMode, onLoad, passedVideoProps, videoStyle]); return (jsxRuntime.jsxs("section", { style: containerStyle, children: [isShowingDisabledImage && (jsxRuntime.jsx("div", { style: styles.barcodeScannerError, children: jsxRuntime.jsx(fi.FiCameraOff, { size: 300, style: styles.barcodeScannerErrorSvg }) })), jsxRuntime.jsxs("div", { style: Object.assign(Object.assign(Object.assign({}, styles.container), (!isShowingDisabledImage ? styles.barcodeScannerVisible : {})), videoContainerStyle), children: [jsxRuntime.jsx("video", Object.assign({ ref: videoElement }, videoProps)), !!Viewfinder && jsxRuntime.jsx(Viewfinder, {})] })] })); } BarcodeScanner.displayName = 'BarcodeScanner'; exports.BarcodeScanner = BarcodeScanner;