@leelexuan/react-qr-scanner
Version:
An enhanced React library for QR code scanning with API interaction capabilities and support for mouse-click detection on bounding boxes.
3 lines (2 loc) • 23.7 kB
JavaScript
;var e=require("react"),t=require("react-usestateref"),n=require("webrtc-adapter/dist/chrome/getusermedia"),o=require("webrtc-adapter/dist/firefox/getusermedia"),r=require("webrtc-adapter/dist/safari/safari_shim"),a=require("webrtc-adapter/dist/utils"),i=require("barcode-detector"),s=require("@techstark/opencv-js");function l(t){const{onClick:n,disabled:o,className:r}=t,a={cursor:o?"default":"pointer",stroke:o?"grey":"yellow",strokeLineJoin:"round",strokeLineCap:"round",strokeWidth:1.5,...t.style};return e.createElement("svg",{onClick:o?void 0:n,className:r,style:a,width:"28px",height:"28px",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},e.createElement("path",{d:"M3 3L6.00007 6.00007M21 21L19.8455 19.8221M9.74194 4.06811C9.83646 4.04279 9.93334 4.02428 10.0319 4.01299C10.1453 4 10.2683 4 10.5141 4H13.5327C13.7786 4 13.9015 4 14.015 4.01299C14.6068 4.08078 15.1375 4.40882 15.4628 4.90782C15.5252 5.00345 15.5802 5.11345 15.6901 5.33333C15.7451 5.44329 15.7726 5.49827 15.8037 5.54609C15.9664 5.79559 16.2318 5.95961 16.5277 5.9935C16.5844 6 16.6459 6 16.7688 6H17.8234C18.9435 6 19.5036 6 19.9314 6.21799C20.3077 6.40973 20.6137 6.71569 20.8055 7.09202C21.0234 7.51984 21.0234 8.0799 21.0234 9.2V15.3496M19.8455 19.8221C19.4278 20 18.8702 20 17.8234 20H6.22344C5.10333 20 4.54328 20 4.11546 19.782C3.73913 19.5903 3.43317 19.2843 3.24142 18.908C3.02344 18.4802 3.02344 17.9201 3.02344 16.8V9.2C3.02344 8.0799 3.02344 7.51984 3.24142 7.09202C3.43317 6.71569 3.73913 6.40973 4.11546 6.21799C4.51385 6.015 5.0269 6.00103 6.00007 6.00007M19.8455 19.8221L14.5619 14.5619M14.5619 14.5619C14.0349 15.4243 13.0847 16 12 16C10.3431 16 9 14.6569 9 13C9 11.9153 9.57566 10.9651 10.4381 10.4381M14.5619 14.5619L10.4381 10.4381M10.4381 10.4381L6.00007 6.00007"}))}function c(t){const{onClick:n,disabled:o,className:r}=t,a={cursor:o?"default":"pointer",stroke:o?"grey":"yellow",strokeLineJoin:"round",strokeLineCap:"round",strokeWidth:1.5,...t.style};return e.createElement("svg",{onClick:o?void 0:n,className:r,style:a,width:"28px",height:"28px",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg"},e.createElement("path",{d:"M12 16C13.6569 16 15 14.6569 15 13C15 11.3431 13.6569 10 12 10C10.3431 10 9 11.3431 9 13C9 14.6569 10.3431 16 12 16Z"}),e.createElement("path",{d:"M3 16.8V9.2C3 8.0799 3 7.51984 3.21799 7.09202C3.40973 6.71569 3.71569 6.40973 4.09202 6.21799C4.51984 6 5.0799 6 6.2 6H7.25464C7.37758 6 7.43905 6 7.49576 5.9935C7.79166 5.95961 8.05705 5.79559 8.21969 5.54609C8.25086 5.49827 8.27836 5.44328 8.33333 5.33333C8.44329 5.11342 8.49827 5.00346 8.56062 4.90782C8.8859 4.40882 9.41668 4.08078 10.0085 4.01299C10.1219 4 10.2448 4 10.4907 4H13.5093C13.7552 4 13.8781 4 13.9915 4.01299C14.5833 4.08078 15.1141 4.40882 15.4394 4.90782C15.5017 5.00345 15.5567 5.11345 15.6667 5.33333C15.7216 5.44329 15.7491 5.49827 15.7803 5.54609C15.943 5.79559 16.2083 5.95961 16.5042 5.9935C16.561 6 16.6224 6 16.7454 6H17.8C18.9201 6 19.4802 6 19.908 6.21799C20.2843 6.40973 20.5903 6.71569 20.782 7.09202C21 7.51984 21 8.0799 21 9.2V16.8C21 17.9201 21 18.4802 20.782 18.908C20.5903 19.2843 20.2843 19.5903 19.908 19.782C19.4802 20 18.9201 20 17.8 20H6.2C5.0799 20 4.51984 20 4.09202 19.782C3.71569 19.5903 3.40973 19.2843 3.21799 18.908C3 18.4802 3 17.9201 3 16.8Z"}))}function d(t){const{scanning:n,startScanning:o,stopScanning:r}=t,[a,i]=e.useState(!1);function s(){i(!0),n?r():o(),setTimeout((()=>i(!1)),1e3)}return e.createElement("div",{style:{bottom:85,right:3,position:"absolute",zIndex:2,cursor:a?"default":"pointer"}},n?e.createElement(l,{disabled:a,onClick:s}):e.createElement(c,{disabled:a,onClick:s}))}function u(t){const{onClick:n,className:o,style:r}=t;return e.createElement("svg",{onClick:n,width:"30px",height:"30px",viewBox:"0 0 24 24",className:o,style:r,xmlns:"http://www.w3.org/2000/svg"},e.createElement("path",{strokeWidth:.2,stroke:"yellow",fill:"yellow",d:"M13.225 9l5.025-7h-7.972l-3.3 11h5.359l-2.452 8.648.75.364L20.374 9zm.438 3H8.322l2.7-9H16.3l-5.025 7h7.101l-6.7 8.953z"}))}function h(t){const{onClick:n,className:o,style:r}=t;return e.createElement("svg",{onClick:n,width:"30px",height:"30px",viewBox:"0 0 24 24",className:o,style:r,xmlns:"http://www.w3.org/2000/svg"},e.createElement("path",{strokeWidth:.2,stroke:"yellow",fill:"yellow",d:"M14.516 15.158l.714.714-4.595 6.14-.75-.364L12.337 13H6.978L8.22 8.861l.803.803L8.322 12h3.036l1.793 1.792-1.475 5.16zm5.984 4.05L4.793 3.5l.707-.707 3.492 3.492L10.278 2h7.972l-5.025 7h7.149l-3.71 4.957 4.543 4.543zM12.707 10l3.243 3.243L18.376 10zM9.795 7.088l2.079 2.079L16.3 3h-5.278z"}))}function w(t){const{status:n,scanning:o,torchToggle:r}=t;function a(e){r(e)}return o&&r?e.createElement("div",{style:{bottom:35,right:3,position:"absolute",zIndex:2,cursor:"pointer"}},n?e.createElement(h,{onClick:()=>a(!1)}):e.createElement(u,{onClick:()=>a(!0)})):null}function m(t){const{onClick:n,className:o,disabled:r=!1}=t,a={cursor:r?"default":"pointer",stroke:r?"grey":"yellow",fill:r?"grey":"yellow",...t.style};return e.createElement("svg",{onClick:r?void 0:n,width:"30px",height:"30px",viewBox:"0 0 24 24",className:o,style:a,xmlns:"http://www.w3.org/2000/svg"},e.createElement("path",{strokeWidth:.3,d:"M16.279,17.039c-1.396,1.209 -3.216,1.941 -5.206,1.941c-4.393,0 -7.96,-3.567 -7.96,-7.96c-0,-4.393 3.567,-7.96 7.96,-7.96c4.393,0 7.96,3.567 7.96,7.96c-0,2.044 -0.772,3.909 -2.04,5.319l0.165,0.165c1.194,1.194 2.388,2.388 3.583,3.582c0.455,0.456 -0.252,1.163 -0.707,0.708l-3.755,-3.755Zm1.754,-6.019c-0,-3.841 -3.119,-6.96 -6.96,-6.96c-3.842,0 -6.96,3.119 -6.96,6.96c-0,3.841 3.118,6.96 6.96,6.96c3.841,0 6.96,-3.119 6.96,-6.96Zm-7.46,0.5l-1.5,0c-0.645,0 -0.643,-1 -0,-1l1.5,0l-0,-1.5c-0,-0.645 1,-0.643 1,0l-0,1.5l1.5,0c0.645,0 0.643,1 -0,1l-1.5,0l-0,1.5c-0,0.645 -1,0.643 -1,0l-0,-1.5Z"}))}function f(t){const{onClick:n,className:o,disabled:r=!1}=t,a={cursor:r?"default":"pointer",stroke:r?"grey":"yellow",fill:r?"grey":"yellow",...t.style};return e.createElement("svg",{onClick:r?void 0:n,width:"30px",height:"30px",viewBox:"0 0 24 24",className:o,style:a,xmlns:"http://www.w3.org/2000/svg"},e.createElement("path",{strokeWidth:.3,d:"M16.279,17.039c-1.396,1.209 -3.216,1.941 -5.206,1.941c-4.393,0 -7.96,-3.567 -7.96,-7.96c-0,-4.393 3.567,-7.96 7.96,-7.96c4.393,0 7.96,3.567 7.96,7.96c-0,2.044 -0.772,3.909 -2.04,5.319l0.165,0.165c1.194,1.194 2.388,2.388 3.583,3.582c0.455,0.456 -0.252,1.163 -0.707,0.708l-3.755,-3.755Zm1.754,-6.019c-0,-3.841 -3.119,-6.96 -6.96,-6.96c-3.842,0 -6.96,3.119 -6.96,6.96c-0,3.841 3.118,6.96 6.96,6.96c3.841,0 6.96,-3.119 6.96,-6.96Zm-4.96,-0.5c0.645,0 0.643,1 -0,1l-4,0c-0.645,0 -0.643,-1 -0,-1l4,0Z"}))}function g(t){const{scanning:n,capabilities:o,onZoom:r,value:a}=t;if(!n||!r)return null;const i=(o.max-o.min)/3;return e.createElement(e.Fragment,null,e.createElement("div",{style:{bottom:130,right:3,position:"absolute",zIndex:2,cursor:"pointer"}},e.createElement(f,{disabled:a<=o.min,onClick:function(){r(Math.max(a-i,o.min))}})),e.createElement("div",{style:{bottom:180,right:3,position:"absolute",zIndex:2,cursor:"pointer"}},e.createElement(m,{disabled:a>=o.max,onClick:function(){r(Math.min(a+i,o.max))}})))}function p(t){const{scanning:n,loading:o,capabilities:r,border:a=35,onOff:i,torch:s,zoom:l,startScanning:c,stopScanning:u}=t,h="rgba(255, 0, 0, 0.5)";return e.createElement("div",{style:{position:"relative"}},e.createElement("svg",{viewBox:"0 0 100 100",style:{top:0,left:0,zIndex:1,boxSizing:"border-box",border:`${a>=35?a:35}px solid rgba(0, 0, 0, 0.2)`}},o&&e.createElement("text",{x:"50",y:"50",textAnchor:"middle",fill:"black",fontSize:"8",fontFamily:"Arial",fontWeight:"bold"},"Loading ...",e.createElement("animate",{attributeName:"opacity",values:"0;1;0",dur:"2s",repeatCount:"indefinite"})),e.createElement("path",{fill:"none",d:"M23,0 L0,0 L0,23",stroke:h,strokeWidth:3}),e.createElement("path",{fill:"none",d:"M0,77 L0,100 L23,100",stroke:h,strokeWidth:3}),e.createElement("path",{fill:"none",d:"M77,100 L100,100 L100,77",stroke:h,strokeWidth:3}),e.createElement("path",{fill:"none",d:"M100,23 L100,0 77,0",stroke:h,strokeWidth:3})),i&&e.createElement(d,{scanning:n,startScanning:c,stopScanning:u}),s&&r.torch&&e.createElement(w,{scanning:n,status:s.status,torchToggle:s.toggle}),l&&r.zoom&&e.createElement(g,{scanning:n,capabilities:r.zoom,value:l.value,onZoom:l.onChange}))}const y={facingMode:"environment",width:{min:640,ideal:720,max:1920},height:{min:640,ideal:720,max:1080}},C={tracker:void 0,onOff:!1,finder:!0,torch:!0,zoom:!1},v={width:"100%",height:"100%",position:"relative"},x={top:0,left:0,width:"100%",height:"100%",display:"block",overflow:"hidden"};var b=function(e){let t,n=!1;return(...o)=>(n||(t=e(o),n=!0),t)}((()=>{const e=a.detectBrowser(window);switch(e.browser){case"chrome":n.shimGetUserMedia(window,e);break;case"firefox":o.shimGetUserMedia(window,e);break;case"safari":r.shimGetUserMedia(window,e);break;default:throw new Error("Unsupported browser")}}));function E(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function k(e){const{center:t,size:n,angle:o}=e,r=o*(Math.PI/180),a=n.width/2,i=n.height/2,l=[{x:-a,y:-i},{x:a,y:-i},{x:a,y:i},{x:-a,y:i}],c=l.map((e=>({x:Number(t.x+e.x),y:Number(t.y+e.y)})));let d=l.map((e=>new s.Point(t.x+e.x*Math.cos(r)-e.y*Math.sin(r),t.y+e.x*Math.sin(r)+e.y*Math.cos(r))));const u=d.map((e=>e.x)),h=d.map((e=>e.y)),w=Math.min(...u),m=Math.min(...h);let f=d.flatMap((e=>[e.x,e.y])),g=s.matFromArray(4,1,s.CV_32FC2,f);return console.log("getRotatedVertices"),{matCorners:g,corners:c,minX:w,minY:m}}function M(e){let t=new s.Mat;s.cvtColor(e,t,s.COLOR_GRAY2RGBA);const n=new ImageData(new Uint8ClampedArray(t.data),t.cols,t.rows);return t.delete(),n}function S(e){let t=new s.Mat,n=new s.Mat,o=new s.Size(5,5);s.GaussianBlur(e,t,o,9,9,s.BORDER_DEFAULT),s.subtract(e,t,n),s.add(e,n,n);let r=new s.Mat;s.cvtColor(e,r,s.COLOR_BGR2GRAY);let a=new s.Mat;s.equalizeHist(r,a);let i=new s.Mat;return s.threshold(a,i,130,255,s.THRESH_TRUNC),console.log("process_image"),t.delete(),n.delete(),r.delete(),a.delete(),i}async function R(e,t){const n=[];try{const{srcMat:o,dst:r}=function(e){const t=s.matFromImageData(e),n=new s.Mat;s.cvtColor(t,n,s.COLOR_RGBA2GRAY),s.blur(n,n,new s.Size(9,9)),s.adaptiveThreshold(n,n,255,s.ADAPTIVE_THRESH_GAUSSIAN_C,s.THRESH_BINARY_INV,11,2);const o=s.getStructuringElement(s.MORPH_RECT,new s.Size(13,13));return s.morphologyEx(n,n,s.MORPH_CLOSE,o),s.erode(n,n,new s.Mat,new s.Point(-1,-1),5),s.dilate(n,n,new s.Mat,new s.Point(-1,-1),5),s.Canny(n,n,50,150),console.log("preprocessImage"),{srcMat:t,dst:n}}(e),{approxList:a}=function(e,t,n){const o=new s.MatVector,r=new s.Mat;s.findContours(e,o,r,s.RETR_LIST,s.CHAIN_APPROX_SIMPLE);let a=[];for(let e=0;e<o.size();e++)a.push(o.get(e));a.sort(((e,t)=>{const n=s.contourArea(e);return s.contourArea(t)-n}));let i=[],l=[];for(let e=0;e<Math.min(a.length,10);e++){let o=a[e],r=s.minAreaRect(o),c=r.center.x,d=r.center.y,u=r.size.width,h=r.size.height,w=r.angle,m=u+u*t,f=h+h*t,g=new s.RotatedRect(new s.Point(c,d),new s.Size(m,f),w);l.some((e=>E(r.center,e)<n))||(i.push(g),l.push(r.center))}return o.delete(),r.delete(),console.log("findBarcodeContour"),{approxList:i}}(r,.05,10);for(let e of a){let r,a,i=e.size.height,l=e.size.width,c=i/l;[r,a]=c>=1?[200*c,200]:[200/c,200],e.angle>60&&([r,a]=[a,r],[i,l]=[l,i]);let{matCorners:d,corners:u,minX:h,minY:w}=k(e);console.log("rect of approxlist");let m=o.clone(),f=new s.Mat,g=s.matFromArray(4,1,s.CV_32FC2,[0,0,r,0,r,a,0,a]),p=s.getPerspectiveTransform(d,g);s.warpPerspective(m,f,p,new s.Size(r,a));let y=S(f);const C=M(y),v=await t.detect(C);if(console.log("detectedCodesImage: ",v),v.length>0)for(let e of v)n.push({rawValue:e.rawValue,format:e.format,boundingBox:new DOMRectReadOnly(h,w,l,i),cornerPoints:u});m.delete(),f.delete(),y.delete()}return console.log("barcodeDict: ",n),o.delete(),r.delete(),n}catch(e){return console.log(e),n}}function B(e,t){const n=window.innerWidth*window.innerHeight,o=[];return[...e,...t].forEach((e=>{const t=(e=>e.width*e.height)(e.boundingBox);t>=.02*n&&!o.some((t=>((e,t)=>E(new s.Point(e.boundingBox.x+e.boundingBox.width/2,e.boundingBox.y+e.boundingBox.height/2),new s.Point(t.boundingBox.x+t.boundingBox.width/2,t.boundingBox.y+t.boundingBox.height/2))<40)(t,e)))&&o.push(e)})),o}var L=e=>e instanceof Date,z=e=>null==e;const O=e=>"object"==typeof e;var T=e=>!z(e)&&!Array.isArray(e)&&O(e)&&!L(e),A=e=>z(e)||!O(e);function H(e,t){if(A(e)||A(t))return e===t;if(L(e)&&L(t))return e.getTime()===t.getTime();const n=Object.keys(e),o=Object.keys(t);if(n.length!==o.length)return!1;for(const r of n){const n=e[r];if(!o.includes(r))return!1;if("ref"!==r){const e=t[r];if(L(n)&&L(e)||T(n)&&T(e)||Array.isArray(n)&&Array.isArray(e)?!H(n,e):n!==e)return!1}}return!0}function D(e){if(null===e)throw new Error("Canvas should always be defined when component is mounted.");const t=e.getContext("2d");if(null===t)throw new Error("Canvas 2D context should be non-null");t.clearRect(0,0,e.width,e.height)}Object.defineProperty(exports,"setZXingModuleOverrides",{enumerable:!0,get:function(){return i.setZXingModuleOverrides}}),exports.Scanner=function(n){var o;const{onScan:r,constraints:a,formats:s=["qr_code"],paused:l=!1,components:c,children:d,styles:u,classNames:h,allowMultiple:w,scanDelay:m,onError:f,onBoundingBoxClick:g,onNewBarcodeDetected:E}=n,k=e.useRef(null),M=e.useRef(null),S=e.useRef(null),L=e.useMemo((()=>({...y,...a})),[a]),z=e.useMemo((()=>({...C,...c})),[c]),[O,T]=t(!1),[A,V]=t(!0),[N,P]=t(L),[I,_]=t([]),[W,F,U]=t([]),[j,q,Z]=t([]),[G,Y,X]=t([]),J=function(){const t=e.useRef(Promise.resolve({type:"stop",data:{}})),n=e.useRef(null),o=e.useRef(null),[r,a]=e.useState({}),[i,s]=e.useState({}),l=e.useCallback((async(e,t)=>{var r,i,l;if(!window.isSecureContext)throw new Error("camera access is only permitted in secure context. Use HTTPS or localhost rather than HTTP.");if(void 0===(null===(r=null===navigator||void 0===navigator?void 0:navigator.mediaDevices)||void 0===r?void 0:r.getUserMedia))throw new Error("this browser has no Stream API support");b();const c=await navigator.mediaDevices.getUserMedia({audio:!1,video:t});void 0!==e.srcObject?e.srcObject=c:void 0!==e.mozSrcObject?e.mozSrcObject=c:window.URL.createObjectURL?e.src=window.URL.createObjectURL(c):window.webkitURL?e.src=window.webkitURL.createObjectURL(c):e.src=c.id,await Promise.race([e.play(),new Promise((e=>setTimeout(e,3e3))).then((()=>{throw new Error("Loading camera stream timed out after 3 seconds.")}))]),await new Promise((e=>setTimeout(e,500)));const[d]=c.getVideoTracks();return s(d.getSettings()),a(null!==(l=null===(i=null==d?void 0:d.getCapabilities)||void 0===i?void 0:i.call(d))&&void 0!==l?l:{}),n.current=c,o.current=d,{type:"start",data:{videoEl:e,stream:c,constraints:t}}}),[]),c=e.useCallback((async(e,t)=>{e.src="",e.srcObject=null,e.load();for(const e of t.getTracks())t.removeTrack(e),e.stop();return n.current=null,o.current=null,s({}),{type:"stop",data:{}}}),[]),d=e.useCallback((async(e,{constraints:n,restart:o=!1})=>{if(t.current=t.current.then((t=>{if("start"===t.type){const{data:{videoEl:r,stream:a,constraints:i}}=t;return o||e!==r||n!==i?c(r,a).then((()=>l(e,n))):t}return l(e,n)})),"stop"===(await t.current).type)throw new Error("Something went wrong with the camera task queue (start task).")}),[l,c]),u=e.useCallback((async()=>{if(t.current=t.current.then((e=>{if("stop"===e.type)return e;const{data:{videoEl:t,stream:n}}=e;return c(t,n)})),"start"===(await t.current).type)throw new Error("Something went wrong with the camera task queue (stop task).")}),[c]),h=e.useCallback((async e=>{const t=o.current;if(!t)throw new Error("No active video track found.");{e.advanced&&e.advanced[0].zoom&&t.getCapabilities().torch&&await t.applyConstraints({advanced:[{torch:!1}]}),await t.applyConstraints(e);const n=t.getCapabilities(),o=t.getSettings();a(n),s(o)}}),[]);return e.useEffect((()=>()=>{(async()=>{await u()})()}),[u]),{capabilities:r,settings:i,startCamera:d,stopCamera:u,updateConstraints:h}}();function $(e,t,n,o){const r=n;if(null==r)throw new Error("onFound handler should only be called when component is mounted. Thus tracking canvas is always defined.");const a=t;if(null==a)throw new Error("onFound handler should only be called when component is mounted. Thus video element is always defined.");if(0===e.length||void 0===o)D(r),_([]),console.log("no detected codes onFound ",I);else{const t=a.offsetWidth,n=a.offsetHeight,i=a.videoWidth,s=a.videoHeight,l=Math.max(t/i,n/s),c=i*l,d=s*l,u=c/i,h=d/s,w=(t-c)/2,m=(n-d)/2,f=({x:e,y:t})=>({x:Math.floor(e*u),y:Math.floor(t*h)}),g=({x:e,y:t})=>({x:Math.floor(e+w),y:Math.floor(t+m)});!function(e){console.log("retrieveData detectedCodes: "+JSON.stringify(e)),console.log("retrieveData dataRef: "+U.current),console.log("retrieveData loadingRef: "+Z.current),e.map((e=>{U.current.includes(e.rawValue)?console.log("i am in data: "+e.rawValue):Z.current.includes(e.rawValue)?console.log("i am in loading: "+e.rawValue):X.current.includes(e.rawValue)?console.log("i am in errorCodes: "+e.rawValue):(q((t=>[...t,e.rawValue])),(async e=>{const t=e.rawValue;try{if(U.current.includes(t))return void console.log("fetchCodeData: i am in data: "+t);const e=await E(t);console.log(e),console.log("fetchCodeData detectedCode: "+t),1==e?(F((e=>[...e,t])),q((e=>e.filter((e=>e!==t))))):(Y((e=>[...e,t])),q((e=>e.filter((e=>e!==t)))))}catch(e){console.log(e),Y((e=>[...e,t])),q((e=>e.filter((e=>e!==t))))}})(e))}))}(e);const p=e.map((e=>{console.log("adjustedCodes detectedCode: "+JSON.stringify(e)),console.log("adjustedCodes dataRef: "+U.current),console.log("adjustedCodes loadingRef: "+Z.current),console.log("adjustedCodes errorCodesRef: "+X.current);let t="yellow";U.current.includes(e.rawValue)?t="green":Z.current.includes(e.rawValue)?t="yellow":X.current.includes(e.rawValue)&&(t="red");const{boundingBox:n,cornerPoints:o}=e,{x:r,y:a}=g(f({x:n.x,y:n.y})),{x:i,y:s}=f({x:n.width,y:n.height});return{...e,colour:t,cornerPoints:o.map((e=>g(f(e)))),boundingBox:DOMRectReadOnly.fromRect({x:r,y:a,width:i,height:s})}}));r.width=a.offsetWidth,r.height=a.offsetHeight;const y=r.getContext("2d");if(null===y)throw new Error("onFound handler should only be called when component is mounted. Thus tracking canvas 2D context is always defined.");const C=o(p,y);_(C)}}const{startScanning:K,stopScanning:Q}=function(t){var n,o;const{videoElementRef:r,onScan:a,onFound:s,retryDelay:l=(null!==(n=t.retryDelay)&&void 0!==n?n:500),scanDelay:c=(null!==(o=t.scanDelay)&&void 0!==o?o:0),formats:d=[],allowMultiple:u=!1}=t,h=e.useRef(new i.BarcodeDetector({formats:d})),w=e.useRef(null);e.useEffect((()=>{h.current=new i.BarcodeDetector({formats:d})}),[d]);const m=e.useCallback((e=>async t=>{if(null!==r.current&&r.current.readyState>1){const{lastScan:n,contentBefore:o,lastScanHadContent:i}=e;if(t-n<l)w.current=window.requestAnimationFrame(m(e));else{const n=r.current,l=document.createElement("canvas"),d=l.getContext("2d");if(!d)return;l.width=n.videoWidth,l.height=n.videoHeight,d.drawImage(n,0,0,l.width,l.height);const f=d.getImageData(0,0,l.width,l.height),g=h.current,p=await R(f,g),y=await g.detect(r.current),C=B(y,p);console.log("detectedCodesReal ",y),console.log("newDetectedCodes ",C);const v=C.some((e=>!o.includes(e.rawValue))),x=C.length>0;let b=e.lastOnScan;(v||u&&x&&t-b>=c)&&(b=t,a(C)),x&&s(C),!x&&i&&s(C);const E={lastScan:t,lastOnScan:b,lastScanHadContent:x,contentBefore:v?C.map((e=>e.rawValue)):o};w.current=window.requestAnimationFrame(m(E))}}}),[r.current,a,s,l]);return{startScanning:e.useCallback((()=>{const e=performance.now(),t={lastScan:e,lastOnScan:e,contentBefore:[],lastScanHadContent:!1};w.current=window.requestAnimationFrame(m(t))}),[m]),stopScanning:e.useCallback((()=>{null!==w.current&&(window.cancelAnimationFrame(w.current),w.current=null)}),[])}}({videoElementRef:k,onScan:r,onFound:e=>$(e,k.current,S.current,z.tracker),formats:s,allowMultiple:w,retryDelay:void 0===z.tracker?2e3:500,scanDelay:m});e.useEffect((()=>(T(!0),()=>{T(!1)})),[]),e.useEffect((()=>{O&&(Q(),K())}),[null==c?void 0:c.tracker]),e.useEffect((()=>{if(!H(L,N)){const e=L;(null==a?void 0:a.deviceId)&&delete e.facingMode,P(e)}}),[a]);const ee=e.useMemo((()=>({constraints:N,shouldStream:O&&!l})),[N,O,l]),te=async()=>{const e=k.current;if(null==e)throw new Error("Video should be defined when component is mounted.");const t=M.current;if(null==t)throw new Error("Canvas should be defined when component is mounted.");const n=t.getContext("2d");if(null==n)throw new Error("Canvas should be defined when component is mounted.");if(ee.shouldStream){await J.stopCamera(),V(!1);try{await J.startCamera(e,ee),e?V(!0):await J.stopCamera()}catch(e){null==f||f(e),console.error("error",e)}}else t.width=e.videoWidth,t.height=e.videoHeight,n.drawImage(e,0,0,e.videoWidth,e.videoHeight),await J.stopCamera(),V(!1)};e.useEffect((()=>{(async()=>{await te()})()}),[ee]);const ne=e.useMemo((()=>ee.shouldStream&&A),[ee.shouldStream,A]);return e.useEffect((()=>{if(ne){if(void 0===M.current)throw new Error("shouldScan effect should only be triggered when component is mounted. Thus pause frame canvas is defined");if(D(M.current),void 0===S.current)throw new Error("shouldScan effect should only be triggered when component is mounted. Thus tracking canvas is defined");D(S.current);const e=k.current;if(null==e)throw new Error("shouldScan effect should only be triggered when component is mounted. Thus video element is defined");K()}}),[ne]),e.useEffect((()=>{if(S.current){const e=S.current,t=t=>{const n=e.getBoundingClientRect(),o=t.clientX-n.left,r=t.clientY-n.top;console.log(`Canvas clicked at: (${o}, ${r})`),function(e,t,n){console.log("mouseBoundingBox BoundingBoxes:",e);for(const o of e){console.log(o);const{x:e,y:r,width:a,height:i}=o;if(t>=e&&t<=e+a&&n>=r&&n<=r+i)return console.log("In bounding box: "+o),void g(o.rawValue)}}(I,o,r)};return e.addEventListener("click",t,!1),()=>{e.removeEventListener("click",t)}}}),[I]),e.createElement("div",{style:{...v,...null==u?void 0:u.container},className:null==h?void 0:h.container},e.createElement("video",{ref:k,style:{...x,...null==u?void 0:u.video,visibility:l?"hidden":"visible"},className:null==h?void 0:h.video,autoPlay:!0,muted:!0,playsInline:!0}),e.createElement("canvas",{ref:M,style:{display:l?"block":"none",position:"absolute",top:0,left:0,width:"100%"}}),e.createElement("canvas",{ref:S,style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",zIndex:10}}),e.createElement("div",{style:{top:0,left:0,position:"absolute",width:"100%",height:"100%"}},z.finder&&e.createElement(p,{scanning:A,capabilities:J.capabilities,loading:!1,onOff:z.onOff,zoom:z.zoom&&J.settings.zoom?{value:J.settings.zoom,onChange:async e=>{const t={...N,advanced:[{zoom:e}]};await J.updateConstraints(t)}}:void 0,torch:z.torch?{status:null!==(o=J.settings.torch)&&void 0!==o&&o,toggle:async e=>{const t={...N,advanced:[{torch:e}]};await J.updateConstraints(t)}}:void 0,startScanning:async()=>await te(),stopScanning:async()=>{await J.stopCamera(),D(S.current),V(!1)},border:null==u?void 0:u.finderBorder}),d))},exports.boundingBox=function(e,t){const n=[];for(const o of e){const{boundingBox:{x:e,y:r,width:a,height:i}}=o,s=o.rawValue;t.lineWidth=2,t.strokeStyle=o.colour,t.strokeRect(e,r,a,i),n.push({x:e,y:r,width:a,height:i,rawValue:s});const l=20,c=r+i,d=e+a/2-t.measureText(s).width/2;t.fillStyle=o.colour,t.fillRect(e,c,a,l);const u=Math.max(10,Math.min(12,50*a/t.canvas.width));t.font=`${u}px sans-serif`,t.fillStyle="white",t.fillText(s,d,c+l/2+5)}return console.log("BoundingBoxes Overlay ",n),n};
//# sourceMappingURL=index.js.map