All files BarcodeDetectorPolyfill.js

22.95% Statements 14/61
9.67% Branches 3/31
25% Functions 3/12
22.95% Lines 14/61

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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          1x   1x                                         1x   1x   22x 22x 22x 22x 22x                                                                                                                                                                                                                                                                         1x 1x                                                 1x     1x       1x  
/**
 * Copied from https://github.com/lekoala/barcode-detector-zbar
 *
 */
 
import { scanImageData } from 'zbar.wasm';
 
const SUPPORTED_FORMATS_MAP = {
  ZBAR_EAN2: 'ean_2',
  ZBAR_EAN5: 'ean_5',
  ZBAR_EAN8: 'ean_8',
  ZBAR_UPCE: 'upc_e',
  ZBAR_ISBN10: 'isbn_10',
  ZBAR_UPCA: 'upc_a',
  ZBAR_EAN13: 'ean_13',
  ZBAR_ISBN13: 'isbn_13',
  ZBAR_COMPOSITE: 'composite',
  ZBAR_I25: 'itf',
  ZBAR_DATABAR: 'databar',
  ZBAR_DATABAR_EXP: 'databar_exp',
  ZBAR_CODABAR: 'codabar',
  ZBAR_CODE39: 'code_39',
  ZBAR_CODE93: 'code_93',
  ZBAR_CODE128: 'code_128',
  ZBAR_PDF417: 'pdf417',
  ZBAR_QRCODE: 'qr_code',
  ZBAR_SQCODE: 'sq_code',
};
const CANVAS_SIZE = 480;
 
class BarcodeDetectorPolyfill {
  constructor(options = {}) {
    this.canvas = document.createElement('canvas');
    this.canvas.width = CANVAS_SIZE;
    this.canvas.height = CANVAS_SIZE;
    this.ctx = this.canvas.getContext('2d');
    this.formats = options.formats || Object.values(SUPPORTED_FORMATS_MAP);
  }
 
  /**
   * Returns a Promise which fulfills with an Array of supported barcode format types.
   * @returns {Promise}
   */
  static getSupportedFormats() {
    return new Promise((resolve, reject) => {
      resolve(Object.values(SUPPORTED_FORMATS_MAP));
    });
  }
 
  /**
   * Returns a Promise which fulfills with an array of detectedBarcode objects with the following properties:
   * - boundingBox: A DOMRectReadOnly, which returns the dimensions of a rectangle representing the extent
   *   of a detected barcode, aligned with the image.
   * - cornerPoints: The x and y co-ordinates of the four corner points of the detected barcode relative
   *   to the image, starting with the top left and working clockwise. This may not be square due
   *   to perspective distortions within the image.
   * - format: The detected barcode format. (For a full list of formats see the [landing page])
   * - rawValue: A String decoded from the barcode data.
   * @param {ImageBitmapSource} image This can be an element, a Blob of type image or an ImageData object.
   * @returns {Promise}
   */
  detect(image) {
    return new Promise(async (resolve, reject) => {
      let canvas_width, canvas_height;
 
      if (
        Object.prototype.toString.call(image) === '[object HTMLVideoElement]'
      ) {
        canvas_width = image.videoWidth;
        canvas_height = image.videoHeight;
      } else if (
        Object.prototype.toString.call(image) === '[object ImageData]'
      ) {
        canvas_width = image.width;
        canvas_height = image.height;
      } else {
        canvas_width = image.width;
        canvas_height = image.height;
      }
 
      if (!canvas_width || !canvas_height) {
        reject('No width or height');
        return;
      }
 
      // Use full area to scan
      if (
        this.canvas.width != canvas_width ||
        this.canvas.height != canvas_height
      ) {
        this.canvas.width = canvas_width;
        this.canvas.height = canvas_height;
        this.ctx = this.canvas.getContext('2d');
      }
 
      if (Object.prototype.toString.call(image) === '[object ImageData]') {
        this.ctx.putImageData(image, 0, 0);
      } else {
        this.ctx.drawImage(image, 0, 0, this.canvas.width, this.canvas.height);
      }
 
      let imageData = this.ctx.getImageData(0, 0, canvas_width, canvas_height);
      const zbarResults = await scanImageData(imageData);
 
      // Convert zbar data to match expected results
      const results = zbarResults
        .filter((res) => {
          // Make sure we have a bounding box
          if (res.points.length < 2) {
            return false;
          }
          // Make sure it's a supported format
          if (!this.formats.includes(SUPPORTED_FORMATS_MAP[res.typeName])) {
            return false;
          }
          return true;
        })
        .map((res) => {
          const nativeFormat = SUPPORTED_FORMATS_MAP[res.typeName];
          let bounds = {
            minX: Infinity,
            maxX: -Infinity,
            minY: Infinity,
            maxY: -Infinity,
          };
          let cornerPoints;
 
          if (res.points.length !== 4) {
            res.points.forEach((point) => {
              bounds.minX = Math.min(bounds.minX, point.x);
              bounds.maxX = Math.max(bounds.maxX, point.x);
              bounds.minY = Math.min(bounds.minY, point.y);
              bounds.maxY = Math.max(bounds.maxY, point.y);
            });
 
            cornerPoints = [
              { x: bounds.minX, y: bounds.minY },
              { x: bounds.maxX, y: bounds.minY },
              { x: bounds.maxX, y: bounds.maxY },
              { x: bounds.minX, y: bounds.maxY },
            ];
          } else {
            cornerPoints = res.points;
          }
 
          return {
            boundingBox: DOMRectReadOnly.fromRect({
              x: bounds.minX,
              y: bounds.minY,
              width: bounds.maxX - bounds.minX,
              height: bounds.maxY - bounds.minY,
            }),
            cornerPoints: cornerPoints,
            format: nativeFormat,
            rawValue: res.decode(),
            quality: res.quality,
          };
        });
      resolve(results);
    });
  }
 
  // Additional helpers below, not part of the actual interface
 
  /**
   * Basically, it's only supported on mobile android (2021)
   * @returns {bool}
   */
  static checkBarcodeDetectorSupport() {
    Eif (!('BarcodeDetector' in window)) {
      return false;
    }
    return true;
  }
 
  /**
   * If the current document isn't loaded securely, navigator.mediaDevices will be undefined
   * @returns {bool}
   */
  static checkWebcamSupport() {
    if (navigator.mediaDevices && !!navigator.mediaDevices.enumerateDevices) {
      return true;
    }
    return false;
  }
 
  /**
   * Use this the check secure context if needed
   * @returns {bool}
   */
  static checkSecureContext() {
    return !!window.isSecureContext;
  }
 
  static setupPolyfill() {
    Iif (BarcodeDetectorPolyfill.checkBarcodeDetectorSupport()) {
      return;
    }
    window['BarcodeDetector'] = BarcodeDetectorPolyfill;
  }
}
 
export default BarcodeDetectorPolyfill;